MediaWiki  1.29.1
GadgetHooks.php
Go to the documentation of this file.
1 <?php
2 
23 use WrappedString\WrappedString;
24 
25 class GadgetHooks {
34  public static function onPageContentSaveComplete( $article, $user, $content ) {
35  // update cache if MediaWiki:Gadgets-definition was edited
36  $title = $article->getTitle();
37  $repo = GadgetRepo::singleton();
38  if ( $title->getNamespace() == NS_MEDIAWIKI && $title->getText() == 'Gadgets-definition'
39  && $repo instanceof MediaWikiGadgetsDefinitionRepo
40  ) {
41  $repo->purgeDefinitionCache();
42  }
43  return true;
44  }
45 
51  public static function userGetDefaultOptions( &$defaultOptions ) {
52  $gadgets = GadgetRepo::singleton()->getStructuredList();
53  if ( !$gadgets ) {
54  return true;
55  }
56 
60  foreach ( $gadgets as $thisSection ) {
61  foreach ( $thisSection as $gadgetId => $gadget ) {
62  if ( $gadget->isOnByDefault() ) {
63  $defaultOptions['gadget-' . $gadgetId] = 1;
64  }
65  }
66  }
67 
68  return true;
69  }
70 
77  public static function getPreferences( $user, &$preferences ) {
78  $gadgets = GadgetRepo::singleton()->getStructuredList();
79  if ( !$gadgets ) {
80  return true;
81  }
82 
83  $options = [];
84  $default = [];
85  foreach ( $gadgets as $section => $thisSection ) {
86  $available = [];
87 
91  foreach ( $thisSection as $gadget ) {
92  if ( !$gadget->isHidden() && $gadget->isAllowed( $user ) ) {
93  $gname = $gadget->getName();
94  # bug 30182: dir="auto" because it's often not translated
95  $desc = '<span dir="auto">' . $gadget->getDescription() . '</span>';
96  $available[$desc] = $gname;
97  if ( $gadget->isEnabled( $user ) ) {
98  $default[] = $gname;
99  }
100  }
101  }
102 
103  if ( $section !== '' ) {
104  $section = wfMessage( "gadget-section-$section" )->parse();
105 
106  if ( count ( $available ) ) {
107  $options[$section] = $available;
108  }
109  } else {
110  $options = array_merge( $options, $available );
111  }
112  }
113 
114  $preferences['gadgets-intro'] =
115  [
116  'type' => 'info',
117  'label' => '&#160;',
118  'default' => Xml::tags( 'tr', [],
119  Xml::tags( 'td', [ 'colspan' => 2 ],
120  wfMessage( 'gadgets-prefstext' )->parseAsBlock() ) ),
121  'section' => 'gadgets',
122  'raw' => 1,
123  'rawrow' => 1,
124  ];
125 
126  $preferences['gadgets'] =
127  [
128  'type' => 'multiselect',
129  'options' => $options,
130  'section' => 'gadgets',
131  'label' => '&#160;',
132  'prefix' => 'gadget-',
133  'default' => $default,
134  ];
135 
136  return true;
137  }
138 
144  public static function registerModules( &$resourceLoader ) {
145  $repo = GadgetRepo::singleton();
146  $ids = $repo->getGadgetIds();
147 
148  foreach ( $ids as $id ) {
149  $resourceLoader->register( Gadget::getModuleName( $id ), [
150  'class' => 'GadgetResourceLoaderModule',
151  'id' => $id,
152  ] );
153  }
154 
155  return true;
156  }
157 
163  public static function beforePageDisplay( $out ) {
164  $repo = GadgetRepo::singleton();
165  $ids = $repo->getGadgetIds();
166  if ( !$ids ) {
167  return true;
168  }
169 
170  $lb = new LinkBatch();
171  $lb->setCaller( __METHOD__ );
172  $enabledLegacyGadgets = [];
173  $typelessMixedGadgets = [];
174 
178  $user = $out->getUser();
179  foreach ( $ids as $id ) {
180  try {
181  $gadget = $repo->getGadget( $id );
182  } catch ( InvalidArgumentException $e ) {
183  continue;
184  }
185  $peers = [];
186  foreach ( $gadget->getPeers() as $peerName ) {
187  try {
188  $peers[] = $repo->getGadget( $peerName );
189  } catch ( InvalidArgumentException $e ) {
190  // Ignore
191  // @todo: Emit warning for invalid peer?
192  }
193  }
194  if ( $gadget->isEnabled( $user ) && $gadget->isAllowed( $user ) ) {
195  if ( $gadget->hasModule() ) {
196  if ( $gadget->getType() === 'styles' ) {
197  $out->addModuleStyles( Gadget::getModuleName( $gadget->getName() ) );
198  } elseif ( $gadget->getType() === 'general' ) {
199  $out->addModules( Gadget::getModuleName( $gadget->getName() ) );
200  // Load peer modules
201  foreach ( $peers as $peer ) {
202  if ( $peer->getType() === 'styles' ) {
203  $out->addModuleStyles( Gadget::getModuleName( $peer->getName() ) );
204  }
205  // Else if not type=styles: Use dependencies instead.
206  // Note: No need for recursion as styles modules don't support
207  // either of 'dependencies' and 'peers'.
208  // @todo: Emit warning for non-styles peer?
209  }
210  } else {
211  $out->addModuleStyles( Gadget::getModuleName( $gadget->getName() ) );
212  $out->addModules( Gadget::getModuleName( $gadget->getName() ) );
213  $typelessMixedGadgets[] = $id;
214  }
215  }
216 
217  if ( $gadget->getLegacyScripts() ) {
218  $enabledLegacyGadgets[] = $id;
219  }
220  }
221  }
222 
223  $strings = [];
224  foreach ( $enabledLegacyGadgets as $id ) {
225  $strings[] = self::makeLegacyWarning( $id );
226  }
227  foreach ( $typelessMixedGadgets as $id ) {
228  $strings[] = self::makeTypelessWarning( $id );
229  }
230  $out->addHTML( WrappedString::join( "\n", $strings ) );
231 
232  return true;
233  }
234 
235  private static function makeLegacyWarning( $id ) {
236  $special = SpecialPage::getTitleFor( 'Gadgets' );
237 
238  return ResourceLoader::makeInlineScript(
239  Xml::encodeJsCall( 'mw.log.warn', [
240  "Gadget \"$id\" was not loaded. Please migrate it to use ResourceLoader. " .
241  'See <' . $special->getCanonicalURL() . '>.'
242  ] )
243  );
244  }
245 
246  private static function makeTypelessWarning( $id ) {
247  return ResourceLoader::makeInlineScript( Xml::encodeJsCall( 'mw.log.warn', [
248  "Gadget \"$id\" styles loaded twice. Migrate to type=general. " .
249  'See <https://www.mediawiki.org/wiki/RL/MGU#Gadget_type>.'
250  ] ) );
251  }
252 
263  public static function onEditFilterMergedContent( $context, $content, $status, $summary ) {
264  $title = $context->getTitle();
265 
266  if ( !$title->inNamespace( NS_GADGET_DEFINITION ) ) {
267  return true;
268  }
269 
270  if ( !$content instanceof GadgetDefinitionContent ) {
271  // This should not be possible?
272  throw new Exception( "Tried to save non-GadgetDefinitionContent to {$title->getPrefixedText()}" );
273  }
274 
275  $status = $content->validate();
276  if ( !$status->isGood() ) {
277  $status->merge( $status );
278  return false;
279  }
280 
281  return true;
282  }
283 
290  public static function onPageContentInsertComplete( WikiPage $page ) {
291  if ( $page->getTitle()->inNamespace( NS_GADGET_DEFINITION ) ) {
292  $repo = GadgetRepo::singleton();
293  if ( $repo instanceof GadgetDefinitionNamespaceRepo ) {
294  $repo->purgeGadgetIdsList();
295  }
296  }
297  }
298 
307  public static function onContentHandlerDefaultModelFor( Title $title, &$model ) {
308  if ( $title->inNamespace( NS_GADGET ) ) {
309  preg_match( '!\.(css|js)$!u', $title->getText(), $ext );
310  $ext = isset( $ext[1] ) ? $ext[1] : '';
311  switch ( $ext ) {
312  case 'js':
313  $model = 'javascript';
314  return false;
315  case 'css':
316  $model = 'css';
317  return false;
318  }
319  }
320 
321  return true;
322  }
323 
332  public static function onCodeEditorGetPageLanguage( Title $title, &$lang ) {
333  if ( $title->hasContentModel( 'GadgetDefinition' ) ) {
334  $lang = 'json';
335  return false;
336  }
337 
338  return true;
339  }
340 
346  public static function onwgQueryPages( &$queryPages ) {
347  $queryPages[] = [ 'SpecialGadgetUsage', 'GadgetUsage' ];
348  return true;
349  }
350 }
$context
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2612
GadgetHooks\makeTypelessWarning
static makeTypelessWarning( $id)
Definition: GadgetHooks.php:246
Gadget\getModuleName
static getModuleName( $id)
Definition: Gadgets_body.php:153
GadgetHooks\onContentHandlerDefaultModelFor
static onContentHandlerDefaultModelFor(Title $title, &$model)
Mark the Title as having a content model of javascript or css for pages in the Gadget namespace based...
Definition: GadgetHooks.php:307
LinkBatch
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
Xml\tags
static tags( $element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:131
GadgetHooks\onPageContentInsertComplete
static onPageContentInsertComplete(WikiPage $page)
After a new page is created in the Gadget definition namespace, invalidate the list of gadget ids.
Definition: GadgetHooks.php:290
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
captcha-old.count
count
Definition: captcha-old.py:225
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1049
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
WikiPage
Class representing a MediaWiki article and history.
Definition: WikiPage.php:36
GadgetHooks\userGetDefaultOptions
static userGetDefaultOptions(&$defaultOptions)
UserGetDefaultOptions hook handler.
Definition: GadgetHooks.php:51
ChangesListFilter\getName
getName()
Definition: ChangesListFilter.php:272
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:82
ContextSource\getTitle
getTitle()
Get the Title object.
Definition: ContextSource.php:88
MediaWikiGadgetsDefinitionRepo
Gadgets repo powered by MediaWiki:Gadgets-definition.
Definition: MediaWikiGadgetsDefinitionRepo.php:7
GadgetHooks\onPageContentSaveComplete
static onPageContentSaveComplete( $article, $user, $content)
PageContentSaveComplete hook handler.
Definition: GadgetHooks.php:34
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
GadgetHooks\registerModules
static registerModules(&$resourceLoader)
ResourceLoaderRegisterModules hook handler.
Definition: GadgetHooks.php:144
Xml\encodeJsCall
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:645
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
GadgetHooks
Definition: GadgetHooks.php:25
$content
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1049
$page
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2536
GadgetRepo\singleton
static singleton()
Get the configured default GadgetRepo.
Definition: GadgetRepo.php:53
GadgetHooks\makeLegacyWarning
static makeLegacyWarning( $id)
Definition: GadgetHooks.php:235
GadgetHooks\getPreferences
static getPreferences( $user, &$preferences)
GetPreferences hook handler.
Definition: GadgetHooks.php:77
GadgetHooks\onEditFilterMergedContent
static onEditFilterMergedContent( $context, $content, $status, $summary)
Valid gadget definition page after content is modified.
Definition: GadgetHooks.php:263
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
GadgetDefinitionContent
Definition: GadgetDefinitionContent.php:23
GadgetDefinitionNamespaceRepo
GadgetRepo implementation where each gadget has a page in the Gadget definition namespace,...
Definition: GadgetDefinitionNamespaceRepo.php:10
GadgetHooks\onCodeEditorGetPageLanguage
static onCodeEditorGetPageLanguage(Title $title, &$lang)
Set the CodeEditor language for Gadget definition pages.
Definition: GadgetHooks.php:332
$resourceLoader
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext such as when responding to a resource loader request or generating HTML output & $resourceLoader
Definition: hooks.txt:2612
Title
Represents a title within MediaWiki.
Definition: Title.php:39
GadgetHooks\onwgQueryPages
static onwgQueryPages(&$queryPages)
Add the GadgetUsage special page to the list of QueryPages.
Definition: GadgetHooks.php:346
$ext
$ext
Definition: NoLocalSettings.php:25
$section
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition: hooks.txt:2929
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$article
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function array $article
Definition: hooks.txt:78
$special
this hook is for auditing only RecentChangesLinked and Watchlist $special
Definition: hooks.txt:990
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:70
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
GadgetHooks\beforePageDisplay
static beforePageDisplay( $out)
BeforePageDisplay hook handler.
Definition: GadgetHooks.php:163
$out
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:783