MediaWiki  1.33.0
ChangeTags.php
Go to the documentation of this file.
1 <?php
27 
28 class ChangeTags {
34  const MAX_DELETE_USES = 5000;
35 
39  private static $definedSoftwareTags = [
40  'mw-contentmodelchange',
41  'mw-new-redirect',
42  'mw-removed-redirect',
43  'mw-changed-redirect-target',
44  'mw-blank',
45  'mw-replace',
46  'mw-rollback',
47  'mw-undo',
48  ];
49 
57  public static function getSoftwareTags( $all = false ) {
58  global $wgSoftwareTags;
59  $softwareTags = [];
60 
61  if ( !is_array( $wgSoftwareTags ) ) {
62  wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
63  Please refer to documentation for the list of tags you can enable' );
64  return $softwareTags;
65  }
66 
67  $availableSoftwareTags = !$all ?
68  array_keys( array_filter( $wgSoftwareTags ) ) :
69  array_keys( $wgSoftwareTags );
70 
71  $softwareTags = array_intersect(
72  $availableSoftwareTags,
73  self::$definedSoftwareTags
74  );
75 
76  return $softwareTags;
77  }
78 
93  public static function formatSummaryRow( $tags, $page, IContextSource $context = null ) {
94  if ( !$tags ) {
95  return [ '', [] ];
96  }
97  if ( !$context ) {
99  }
100 
101  $classes = [];
102 
103  $tags = explode( ',', $tags );
104  $displayTags = [];
105  foreach ( $tags as $tag ) {
106  if ( !$tag ) {
107  continue;
108  }
109  $description = self::tagDescription( $tag, $context );
110  if ( $description === false ) {
111  continue;
112  }
113  $displayTags[] = Xml::tags(
114  'span',
115  [ 'class' => 'mw-tag-marker ' .
116  Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
117  $description
118  );
119  $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
120  }
121 
122  if ( !$displayTags ) {
123  return [ '', [] ];
124  }
125 
126  $markers = $context->msg( 'tag-list-wrapper' )
127  ->numParams( count( $displayTags ) )
128  ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
129  ->parse();
130  $markers = Xml::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
131 
132  return [ $markers, $classes ];
133  }
134 
148  public static function tagDescription( $tag, MessageLocalizer $context ) {
149  $msg = $context->msg( "tag-$tag" );
150  if ( !$msg->exists() ) {
151  // No such message, so return the HTML-escaped tag name.
152  return htmlspecialchars( $tag );
153  }
154  if ( $msg->isDisabled() ) {
155  // The message exists but is disabled, hide the tag.
156  return false;
157  }
158 
159  // Message exists and isn't disabled, use it.
160  return $msg->parse();
161  }
162 
175  public static function tagLongDescriptionMessage( $tag, MessageLocalizer $context ) {
176  $msg = $context->msg( "tag-$tag-description" );
177  if ( !$msg->exists() ) {
178  return false;
179  }
180  if ( $msg->isDisabled() ) {
181  // The message exists but is disabled, hide the description.
182  return false;
183  }
184 
185  // Message exists and isn't disabled, use it.
186  return $msg;
187  }
188 
198  public static function truncateTagDescription( $tag, $length, IContextSource $context ) {
199  // FIXME: Make this accept MessageLocalizer and Language instead of IContextSource
200 
201  $originalDesc = self::tagLongDescriptionMessage( $tag, $context );
202  // If there is no tag description, return empty string
203  if ( !$originalDesc ) {
204  return '';
205  }
206 
207  $taglessDesc = Sanitizer::stripAllTags( $originalDesc->parse() );
208 
209  return $context->getLanguage()->truncateForVisual( $taglessDesc, $length );
210  }
211 
226  public static function addTags( $tags, $rc_id = null, $rev_id = null,
227  $log_id = null, $params = null, RecentChange $rc = null
228  ) {
229  $result = self::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
230  return (bool)$result[0];
231  }
232 
263  public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
264  &$rev_id = null, &$log_id = null, $params = null, RecentChange $rc = null,
265  User $user = null
266  ) {
267  $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
268  $tagsToRemove = array_filter( (array)$tagsToRemove );
269 
270  if ( !$rc_id && !$rev_id && !$log_id ) {
271  throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
272  'specified when adding or removing a tag from a change!' );
273  }
274 
275  $dbw = wfGetDB( DB_MASTER );
276 
277  // Might as well look for rcids and so on.
278  if ( !$rc_id ) {
279  // Info might be out of date, somewhat fractionally, on replica DB.
280  // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
281  // so use that relation to avoid full table scans.
282  if ( $log_id ) {
283  $rc_id = $dbw->selectField(
284  [ 'logging', 'recentchanges' ],
285  'rc_id',
286  [
287  'log_id' => $log_id,
288  'rc_timestamp = log_timestamp',
289  'rc_logid = log_id'
290  ],
291  __METHOD__
292  );
293  } elseif ( $rev_id ) {
294  $rc_id = $dbw->selectField(
295  [ 'revision', 'recentchanges' ],
296  'rc_id',
297  [
298  'rev_id' => $rev_id,
299  'rc_timestamp = rev_timestamp',
300  'rc_this_oldid = rev_id'
301  ],
302  __METHOD__
303  );
304  }
305  } elseif ( !$log_id && !$rev_id ) {
306  // Info might be out of date, somewhat fractionally, on replica DB.
307  $log_id = $dbw->selectField(
308  'recentchanges',
309  'rc_logid',
310  [ 'rc_id' => $rc_id ],
311  __METHOD__
312  );
313  $rev_id = $dbw->selectField(
314  'recentchanges',
315  'rc_this_oldid',
316  [ 'rc_id' => $rc_id ],
317  __METHOD__
318  );
319  }
320 
321  if ( $log_id && !$rev_id ) {
322  $rev_id = $dbw->selectField(
323  'log_search',
324  'ls_value',
325  [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
326  __METHOD__
327  );
328  } elseif ( !$log_id && $rev_id ) {
329  $log_id = $dbw->selectField(
330  'log_search',
331  'ls_log_id',
332  [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
333  __METHOD__
334  );
335  }
336 
337  $prevTags = self::getPrevTags( $rc_id, $log_id, $rev_id );
338 
339  // add tags
340  $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
341  $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
342 
343  // remove tags
344  $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
345  $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
346 
347  sort( $prevTags );
348  sort( $newTags );
349  if ( $prevTags == $newTags ) {
350  return [ [], [], $prevTags ];
351  }
352 
353  // insert a row into change_tag for each new tag
354  $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
355  if ( count( $tagsToAdd ) ) {
356  $changeTagMapping = [];
357  foreach ( $tagsToAdd as $tag ) {
358  $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
359  }
360  $fname = __METHOD__;
361  // T207881: update the counts at the end of the transaction
362  $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tagsToAdd, $fname ) {
363  $dbw->update(
364  'change_tag_def',
365  [ 'ctd_count = ctd_count + 1' ],
366  [ 'ctd_name' => $tagsToAdd ],
367  $fname
368  );
369  } );
370 
371  $tagsRows = [];
372  foreach ( $tagsToAdd as $tag ) {
373  // Filter so we don't insert NULLs as zero accidentally.
374  // Keep in mind that $rc_id === null means "I don't care/know about the
375  // rc_id, just delete $tag on this revision/log entry". It doesn't
376  // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
377  $tagsRows[] = array_filter(
378  [
379  'ct_rc_id' => $rc_id,
380  'ct_log_id' => $log_id,
381  'ct_rev_id' => $rev_id,
382  'ct_params' => $params,
383  'ct_tag_id' => $changeTagMapping[$tag] ?? null,
384  ]
385  );
386 
387  }
388 
389  $dbw->insert( 'change_tag', $tagsRows, __METHOD__, [ 'IGNORE' ] );
390  }
391 
392  // delete from change_tag
393  if ( count( $tagsToRemove ) ) {
394  $fname = __METHOD__;
395  foreach ( $tagsToRemove as $tag ) {
396  $conds = array_filter(
397  [
398  'ct_rc_id' => $rc_id,
399  'ct_log_id' => $log_id,
400  'ct_rev_id' => $rev_id,
401  'ct_tag_id' => $changeTagDefStore->getId( $tag ),
402  ]
403  );
404  $dbw->delete( 'change_tag', $conds, __METHOD__ );
405  if ( $dbw->affectedRows() ) {
406  // T207881: update the counts at the end of the transaction
407  $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tag, $fname ) {
408  $dbw->update(
409  'change_tag_def',
410  [ 'ctd_count = ctd_count - 1' ],
411  [ 'ctd_name' => $tag ],
412  $fname
413  );
414 
415  $dbw->delete(
416  'change_tag_def',
417  [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
418  $fname
419  );
420  } );
421  }
422  }
423  }
424 
425  Hooks::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
426  $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
427 
428  return [ $tagsToAdd, $tagsToRemove, $prevTags ];
429  }
430 
431  private static function getPrevTags( $rc_id = null, $log_id = null, $rev_id = null ) {
432  $conds = array_filter(
433  [
434  'ct_rc_id' => $rc_id,
435  'ct_log_id' => $log_id,
436  'ct_rev_id' => $rev_id,
437  ]
438  );
439 
440  $dbw = wfGetDB( DB_MASTER );
441  $tagIds = $dbw->selectFieldValues( 'change_tag', 'ct_tag_id', $conds, __METHOD__ );
442 
443  $tags = [];
444  foreach ( $tagIds as $tagId ) {
445  $tags[] = MediaWikiServices::getInstance()->getChangeTagDefStore()->getName( (int)$tagId );
446  }
447 
448  return $tags;
449  }
450 
461  protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
462  $lang = RequestContext::getMain()->getLanguage();
463  $count = count( $tags );
464  return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
465  $lang->commaList( $tags ), $count );
466  }
467 
481  public static function canAddTagsAccompanyingChange( array $tags, User $user = null ) {
482  if ( !is_null( $user ) ) {
483  if ( !$user->isAllowed( 'applychangetags' ) ) {
484  return Status::newFatal( 'tags-apply-no-permission' );
485  } elseif ( $user->isBlocked() ) {
486  return Status::newFatal( 'tags-apply-blocked', $user->getName() );
487  }
488  }
489 
490  // to be applied, a tag has to be explicitly defined
491  $allowedTags = self::listExplicitlyDefinedTags();
492  Hooks::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
493  $disallowedTags = array_diff( $tags, $allowedTags );
494  if ( $disallowedTags ) {
495  return self::restrictedTagError( 'tags-apply-not-allowed-one',
496  'tags-apply-not-allowed-multi', $disallowedTags );
497  }
498 
499  return Status::newGood();
500  }
501 
522  public static function addTagsAccompanyingChangeWithChecks(
523  array $tags, $rc_id, $rev_id, $log_id, $params, User $user
524  ) {
525  // are we allowed to do this?
527  if ( !$result->isOK() ) {
528  $result->value = null;
529  return $result;
530  }
531 
532  // do it!
533  self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
534 
535  return Status::newGood( true );
536  }
537 
552  public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
553  User $user = null
554  ) {
555  if ( !is_null( $user ) ) {
556  if ( !$user->isAllowed( 'changetags' ) ) {
557  return Status::newFatal( 'tags-update-no-permission' );
558  } elseif ( $user->isBlocked() ) {
559  return Status::newFatal( 'tags-update-blocked', $user->getName() );
560  }
561  }
562 
563  if ( $tagsToAdd ) {
564  // to be added, a tag has to be explicitly defined
565  // @todo Allow extensions to define tags that can be applied by users...
566  $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
567  $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
568  if ( $diff ) {
569  return self::restrictedTagError( 'tags-update-add-not-allowed-one',
570  'tags-update-add-not-allowed-multi', $diff );
571  }
572  }
573 
574  if ( $tagsToRemove ) {
575  // to be removed, a tag must not be defined by an extension, or equivalently it
576  // has to be either explicitly defined or not defined at all
577  // (assuming no edge case of a tag both explicitly-defined and extension-defined)
578  $softwareDefinedTags = self::listSoftwareDefinedTags();
579  $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
580  if ( $intersect ) {
581  return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
582  'tags-update-remove-not-allowed-multi', $intersect );
583  }
584  }
585 
586  return Status::newGood();
587  }
588 
619  public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
620  $rc_id, $rev_id, $log_id, $params, $reason, User $user
621  ) {
622  if ( is_null( $tagsToAdd ) ) {
623  $tagsToAdd = [];
624  }
625  if ( is_null( $tagsToRemove ) ) {
626  $tagsToRemove = [];
627  }
628  if ( !$tagsToAdd && !$tagsToRemove ) {
629  // no-op, don't bother
630  return Status::newGood( (object)[
631  'logId' => null,
632  'addedTags' => [],
633  'removedTags' => [],
634  ] );
635  }
636 
637  // are we allowed to do this?
638  $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
639  if ( !$result->isOK() ) {
640  $result->value = null;
641  return $result;
642  }
643 
644  // basic rate limiting
645  if ( $user->pingLimiter( 'changetag' ) ) {
646  return Status::newFatal( 'actionthrottledtext' );
647  }
648 
649  // do it!
650  list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
651  $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
652  if ( !$tagsAdded && !$tagsRemoved ) {
653  // no-op, don't log it
654  return Status::newGood( (object)[
655  'logId' => null,
656  'addedTags' => [],
657  'removedTags' => [],
658  ] );
659  }
660 
661  // log it
662  $logEntry = new ManualLogEntry( 'tag', 'update' );
663  $logEntry->setPerformer( $user );
664  $logEntry->setComment( $reason );
665 
666  // find the appropriate target page
667  if ( $rev_id ) {
668  $rev = Revision::newFromId( $rev_id );
669  if ( $rev ) {
670  $logEntry->setTarget( $rev->getTitle() );
671  }
672  } elseif ( $log_id ) {
673  // This function is from revision deletion logic and has nothing to do with
674  // change tags, but it appears to be the only other place in core where we
675  // perform logged actions on log items.
676  $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
677  }
678 
679  if ( !$logEntry->getTarget() ) {
680  // target is required, so we have to set something
681  $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
682  }
683 
684  $logParams = [
685  '4::revid' => $rev_id,
686  '5::logid' => $log_id,
687  '6:list:tagsAdded' => $tagsAdded,
688  '7:number:tagsAddedCount' => count( $tagsAdded ),
689  '8:list:tagsRemoved' => $tagsRemoved,
690  '9:number:tagsRemovedCount' => count( $tagsRemoved ),
691  'initialTags' => $initialTags,
692  ];
693  $logEntry->setParameters( $logParams );
694  $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
695 
696  $dbw = wfGetDB( DB_MASTER );
697  $logId = $logEntry->insert( $dbw );
698  // Only send this to UDP, not RC, similar to patrol events
699  $logEntry->publish( $logId, 'udp' );
700 
701  return Status::newGood( (object)[
702  'logId' => $logId,
703  'addedTags' => $tagsAdded,
704  'removedTags' => $tagsRemoved,
705  ] );
706  }
707 
728  public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
729  &$join_conds, &$options, $filter_tag = ''
730  ) {
731  global $wgUseTagFilter;
732 
733  // Normalize to arrays
734  $tables = (array)$tables;
735  $fields = (array)$fields;
736  $conds = (array)$conds;
738 
739  $fields['ts_tags'] = self::makeTagSummarySubquery( $tables );
740 
741  // Figure out which ID field to use
742  if ( in_array( 'recentchanges', $tables ) ) {
743  $join_cond = 'ct_rc_id=rc_id';
744  } elseif ( in_array( 'logging', $tables ) ) {
745  $join_cond = 'ct_log_id=log_id';
746  } elseif ( in_array( 'revision', $tables ) ) {
747  $join_cond = 'ct_rev_id=rev_id';
748  } elseif ( in_array( 'archive', $tables ) ) {
749  $join_cond = 'ct_rev_id=ar_rev_id';
750  } else {
751  throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
752  }
753 
754  if ( $wgUseTagFilter && $filter_tag ) {
755  // Somebody wants to filter on a tag.
756  // Add an INNER JOIN on change_tag
757 
758  $tables[] = 'change_tag';
759  $join_conds['change_tag'] = [ 'JOIN', $join_cond ];
760  $filterTagIds = [];
761  $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
762  foreach ( (array)$filter_tag as $filterTagName ) {
763  try {
764  $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
765  } catch ( NameTableAccessException $exception ) {
766  // Return nothing.
767  $conds[] = '0';
768  break;
769  }
770  }
771 
772  if ( $filterTagIds !== [] ) {
773  $conds['ct_tag_id'] = $filterTagIds;
774  }
775 
776  if (
777  is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
778  !in_array( 'DISTINCT', $options )
779  ) {
780  $options[] = 'DISTINCT';
781  }
782  }
783  }
784 
793  public static function makeTagSummarySubquery( $tables ) {
794  // Normalize to arrays
795  $tables = (array)$tables;
796 
797  // Figure out which ID field to use
798  if ( in_array( 'recentchanges', $tables ) ) {
799  $join_cond = 'ct_rc_id=rc_id';
800  } elseif ( in_array( 'logging', $tables ) ) {
801  $join_cond = 'ct_log_id=log_id';
802  } elseif ( in_array( 'revision', $tables ) ) {
803  $join_cond = 'ct_rev_id=rev_id';
804  } elseif ( in_array( 'archive', $tables ) ) {
805  $join_cond = 'ct_rev_id=ar_rev_id';
806  } else {
807  throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
808  }
809 
810  $tagTables = [ 'change_tag', 'change_tag_def' ];
811  $join_cond_ts_tags = [ 'change_tag_def' => [ 'JOIN', 'ct_tag_id=ctd_id' ] ];
812  $field = 'ctd_name';
813 
814  return wfGetDB( DB_REPLICA )->buildGroupConcatField(
815  ',', $tagTables, $field, $join_cond, $join_cond_ts_tags
816  );
817  }
818 
830  public static function buildTagFilterSelector(
831  $selected = '', $ooui = false, IContextSource $context = null
832  ) {
833  if ( !$context ) {
835  }
836 
837  $config = $context->getConfig();
838  if ( !$config->get( 'UseTagFilter' ) || !count( self::listDefinedTags() ) ) {
839  return [];
840  }
841 
842  $data = [
843  Html::rawElement(
844  'label',
845  [ 'for' => 'tagfilter' ],
846  $context->msg( 'tag-filter' )->parse()
847  )
848  ];
849 
850  if ( $ooui ) {
851  $data[] = new OOUI\TextInputWidget( [
852  'id' => 'tagfilter',
853  'name' => 'tagfilter',
854  'value' => $selected,
855  'classes' => 'mw-tagfilter-input',
856  ] );
857  } else {
858  $data[] = Xml::input(
859  'tagfilter',
860  20,
861  $selected,
862  [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
863  );
864  }
865 
866  return $data;
867  }
868 
877  public static function defineTag( $tag ) {
878  $dbw = wfGetDB( DB_MASTER );
879  $tagDef = [
880  'ctd_name' => $tag,
881  'ctd_user_defined' => 1,
882  'ctd_count' => 0
883  ];
884  $dbw->upsert(
885  'change_tag_def',
886  $tagDef,
887  [ 'ctd_name' ],
888  [ 'ctd_user_defined' => 1 ],
889  __METHOD__
890  );
891 
892  // clear the memcache of defined tags
894  }
895 
904  public static function undefineTag( $tag ) {
905  $dbw = wfGetDB( DB_MASTER );
906 
907  $dbw->update(
908  'change_tag_def',
909  [ 'ctd_user_defined' => 0 ],
910  [ 'ctd_name' => $tag ],
911  __METHOD__
912  );
913 
914  $dbw->delete(
915  'change_tag_def',
916  [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
917  __METHOD__
918  );
919 
920  // clear the memcache of defined tags
922  }
923 
938  protected static function logTagManagementAction( $action, $tag, $reason,
939  User $user, $tagCount = null, array $logEntryTags = []
940  ) {
941  $dbw = wfGetDB( DB_MASTER );
942 
943  $logEntry = new ManualLogEntry( 'managetags', $action );
944  $logEntry->setPerformer( $user );
945  // target page is not relevant, but it has to be set, so we just put in
946  // the title of Special:Tags
947  $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
948  $logEntry->setComment( $reason );
949 
950  $params = [ '4::tag' => $tag ];
951  if ( !is_null( $tagCount ) ) {
952  $params['5:number:count'] = $tagCount;
953  }
954  $logEntry->setParameters( $params );
955  $logEntry->setRelations( [ 'Tag' => $tag ] );
956  $logEntry->setTags( $logEntryTags );
957 
958  $logId = $logEntry->insert( $dbw );
959  $logEntry->publish( $logId );
960  return $logId;
961  }
962 
972  public static function canActivateTag( $tag, User $user = null ) {
973  if ( !is_null( $user ) ) {
974  if ( !$user->isAllowed( 'managechangetags' ) ) {
975  return Status::newFatal( 'tags-manage-no-permission' );
976  } elseif ( $user->isBlocked() ) {
977  return Status::newFatal( 'tags-manage-blocked', $user->getName() );
978  }
979  }
980 
981  // defined tags cannot be activated (a defined tag is either extension-
982  // defined, in which case the extension chooses whether or not to active it;
983  // or user-defined, in which case it is considered active)
984  $definedTags = self::listDefinedTags();
985  if ( in_array( $tag, $definedTags ) ) {
986  return Status::newFatal( 'tags-activate-not-allowed', $tag );
987  }
988 
989  // non-existing tags cannot be activated
990  $tagUsage = self::tagUsageStatistics();
991  if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
992  return Status::newFatal( 'tags-activate-not-found', $tag );
993  }
994 
995  return Status::newGood();
996  }
997 
1015  public static function activateTagWithChecks( $tag, $reason, User $user,
1016  $ignoreWarnings = false, array $logEntryTags = []
1017  ) {
1018  // are we allowed to do this?
1019  $result = self::canActivateTag( $tag, $user );
1020  if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1021  $result->value = null;
1022  return $result;
1023  }
1024 
1025  // do it!
1026  self::defineTag( $tag );
1027 
1028  // log it
1029  $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user,
1030  null, $logEntryTags );
1031 
1032  return Status::newGood( $logId );
1033  }
1034 
1044  public static function canDeactivateTag( $tag, User $user = null ) {
1045  if ( !is_null( $user ) ) {
1046  if ( !$user->isAllowed( 'managechangetags' ) ) {
1047  return Status::newFatal( 'tags-manage-no-permission' );
1048  } elseif ( $user->isBlocked() ) {
1049  return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1050  }
1051  }
1052 
1053  // only explicitly-defined tags can be deactivated
1054  $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
1055  if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1056  return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
1057  }
1058  return Status::newGood();
1059  }
1060 
1078  public static function deactivateTagWithChecks( $tag, $reason, User $user,
1079  $ignoreWarnings = false, array $logEntryTags = []
1080  ) {
1081  // are we allowed to do this?
1083  if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1084  $result->value = null;
1085  return $result;
1086  }
1087 
1088  // do it!
1089  self::undefineTag( $tag );
1090 
1091  // log it
1092  $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1093  null, $logEntryTags );
1094 
1095  return Status::newGood( $logId );
1096  }
1097 
1105  public static function isTagNameValid( $tag ) {
1106  // no empty tags
1107  if ( $tag === '' ) {
1108  return Status::newFatal( 'tags-create-no-name' );
1109  }
1110 
1111  // tags cannot contain commas (used to be used as a delimiter in tag_summary table),
1112  // pipe (used as a delimiter between multiple tags in
1113  // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1114  // MediaWiki namespace)
1115  if ( strpos( $tag, ',' ) !== false || strpos( $tag, '|' ) !== false
1116  || strpos( $tag, '/' ) !== false ) {
1117  return Status::newFatal( 'tags-create-invalid-chars' );
1118  }
1119 
1120  // could the MediaWiki namespace description messages be created?
1121  $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
1122  if ( is_null( $title ) ) {
1123  return Status::newFatal( 'tags-create-invalid-title-chars' );
1124  }
1125 
1126  return Status::newGood();
1127  }
1128 
1141  public static function canCreateTag( $tag, User $user = null ) {
1142  if ( !is_null( $user ) ) {
1143  if ( !$user->isAllowed( 'managechangetags' ) ) {
1144  return Status::newFatal( 'tags-manage-no-permission' );
1145  } elseif ( $user->isBlocked() ) {
1146  return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1147  }
1148  }
1149 
1150  $status = self::isTagNameValid( $tag );
1151  if ( !$status->isGood() ) {
1152  return $status;
1153  }
1154 
1155  // does the tag already exist?
1156  $tagUsage = self::tagUsageStatistics();
1157  if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
1158  return Status::newFatal( 'tags-create-already-exists', $tag );
1159  }
1160 
1161  // check with hooks
1162  $canCreateResult = Status::newGood();
1163  Hooks::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1164  return $canCreateResult;
1165  }
1166 
1186  public static function createTagWithChecks( $tag, $reason, User $user,
1187  $ignoreWarnings = false, array $logEntryTags = []
1188  ) {
1189  // are we allowed to do this?
1190  $result = self::canCreateTag( $tag, $user );
1191  if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1192  $result->value = null;
1193  return $result;
1194  }
1195 
1196  // do it!
1197  self::defineTag( $tag );
1198 
1199  // log it
1200  $logId = self::logTagManagementAction( 'create', $tag, $reason, $user,
1201  null, $logEntryTags );
1202 
1203  return Status::newGood( $logId );
1204  }
1205 
1218  public static function deleteTagEverywhere( $tag ) {
1219  $dbw = wfGetDB( DB_MASTER );
1220  $dbw->startAtomic( __METHOD__ );
1221 
1222  // fetch tag id, this must be done before calling undefineTag(), see T225564
1223  $tagId = MediaWikiServices::getInstance()->getChangeTagDefStore()->getId( $tag );
1224 
1225  // set ctd_user_defined = 0
1226  self::undefineTag( $tag );
1227 
1228  // delete from change_tag
1229  $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__ );
1230  $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__ );
1231  $dbw->endAtomic( __METHOD__ );
1232 
1233  // give extensions a chance
1235  Hooks::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1236  // let's not allow error results, as the actual tag deletion succeeded
1237  if ( !$status->isOK() ) {
1238  wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1239  $status->setOK( true );
1240  }
1241 
1242  // clear the memcache of defined tags
1244 
1245  return $status;
1246  }
1247 
1257  public static function canDeleteTag( $tag, User $user = null ) {
1258  $tagUsage = self::tagUsageStatistics();
1259 
1260  if ( !is_null( $user ) ) {
1261  if ( !$user->isAllowed( 'deletechangetags' ) ) {
1262  return Status::newFatal( 'tags-delete-no-permission' );
1263  } elseif ( $user->isBlocked() ) {
1264  return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1265  }
1266  }
1267 
1268  if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1269  return Status::newFatal( 'tags-delete-not-found', $tag );
1270  }
1271 
1272  if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1273  return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1274  }
1275 
1276  $softwareDefined = self::listSoftwareDefinedTags();
1277  if ( in_array( $tag, $softwareDefined ) ) {
1278  // extension-defined tags can't be deleted unless the extension
1279  // specifically allows it
1280  $status = Status::newFatal( 'tags-delete-not-allowed' );
1281  } else {
1282  // user-defined tags are deletable unless otherwise specified
1284  }
1285 
1286  Hooks::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1287  return $status;
1288  }
1289 
1307  public static function deleteTagWithChecks( $tag, $reason, User $user,
1308  $ignoreWarnings = false, array $logEntryTags = []
1309  ) {
1310  // are we allowed to do this?
1311  $result = self::canDeleteTag( $tag, $user );
1312  if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1313  $result->value = null;
1314  return $result;
1315  }
1316 
1317  // store the tag usage statistics
1318  $tagUsage = self::tagUsageStatistics();
1319  $hitcount = $tagUsage[$tag] ?? 0;
1320 
1321  // do it!
1322  $deleteResult = self::deleteTagEverywhere( $tag );
1323  if ( !$deleteResult->isOK() ) {
1324  return $deleteResult;
1325  }
1326 
1327  // log it
1328  $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user,
1329  $hitcount, $logEntryTags );
1330 
1331  $deleteResult->value = $logId;
1332  return $deleteResult;
1333  }
1334 
1341  public static function listSoftwareActivatedTags() {
1342  // core active tags
1343  $tags = self::getSoftwareTags();
1344  if ( !Hooks::isRegistered( 'ChangeTagsListActive' ) ) {
1345  return $tags;
1346  }
1347  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1348  return $cache->getWithSetCallback(
1349  $cache->makeKey( 'active-tags' ),
1351  function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1352  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1353 
1354  // Ask extensions which tags they consider active
1355  Hooks::run( 'ChangeTagsListActive', [ &$tags ] );
1356  return $tags;
1357  },
1358  [
1359  'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1360  'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1362  ]
1363  );
1364  }
1365 
1372  public static function listDefinedTags() {
1374  $tags2 = self::listSoftwareDefinedTags();
1375  return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1376  }
1377 
1386  public static function listExplicitlyDefinedTags() {
1387  $fname = __METHOD__;
1388 
1389  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1390  return $cache->getWithSetCallback(
1391  $cache->makeKey( 'valid-tags-db' ),
1393  function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1394  $dbr = wfGetDB( DB_REPLICA );
1395 
1396  $setOpts += Database::getCacheSetOptions( $dbr );
1397 
1398  $tags = $dbr->selectFieldValues(
1399  'change_tag_def',
1400  'ctd_name',
1401  [ 'ctd_user_defined' => 1 ],
1402  $fname
1403  );
1404 
1405  return array_filter( array_unique( $tags ) );
1406  },
1407  [
1408  'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1409  'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1411  ]
1412  );
1413  }
1414 
1424  public static function listSoftwareDefinedTags() {
1425  // core defined tags
1426  $tags = self::getSoftwareTags( true );
1427  if ( !Hooks::isRegistered( 'ListDefinedTags' ) ) {
1428  return $tags;
1429  }
1430  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1431  return $cache->getWithSetCallback(
1432  $cache->makeKey( 'valid-tags-hook' ),
1434  function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1435  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1436 
1437  Hooks::run( 'ListDefinedTags', [ &$tags ] );
1438  return array_filter( array_unique( $tags ) );
1439  },
1440  [
1441  'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1442  'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1444  ]
1445  );
1446  }
1447 
1453  public static function purgeTagCacheAll() {
1454  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1455 
1456  $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1457  $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1458  $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1459 
1460  MediaWikiServices::getInstance()->getChangeTagDefStore()->reloadMap();
1461  }
1462 
1468  public static function purgeTagUsageCache() {
1469  wfDeprecated( __METHOD__, '1.33' );
1470  }
1471 
1478  public static function tagUsageStatistics() {
1479  $dbr = wfGetDB( DB_REPLICA );
1480  $res = $dbr->select(
1481  'change_tag_def',
1482  [ 'ctd_name', 'ctd_count' ],
1483  [],
1484  __METHOD__,
1485  [ 'ORDER BY' => 'ctd_count DESC' ]
1486  );
1487 
1488  $out = [];
1489  foreach ( $res as $row ) {
1490  $out[$row->ctd_name] = $row->ctd_count;
1491  }
1492 
1493  return $out;
1494  }
1495 
1510  public static function showTagEditingUI( User $user ) {
1511  return $user->isAllowed( 'changetags' ) && (bool)self::listExplicitlyDefinedTags();
1512  }
1513 }
$status
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1266
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
ChangeTags\makeTagSummarySubquery
static makeTagSummarySubquery( $tables)
Make the tag summary subquery based on the given tables and return it.
Definition: ChangeTags.php:793
$wgUseTagFilter
$wgUseTagFilter
Allow filtering by change tag in recentchanges, history, etc Has no effect if no tags are defined in ...
Definition: DefaultSettings.php:7030
$user
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:306
ChangeTags\purgeTagCacheAll
static purgeTagCacheAll()
Invalidates the short-term cache of defined tags used by the list*DefinedTags functions,...
Definition: ChangeTags.php:1453
Revision\newFromId
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:118
$context
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2636
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
captcha-old.count
count
Definition: captcha-old.py:249
RecentChange
Utility class for creating new RC entries.
Definition: RecentChange.php:69
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1983
$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 When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:780
ChangeTags\logTagManagementAction
static logTagManagementAction( $action, $tag, $reason, User $user, $tagCount=null, array $logEntryTags=[])
Writes a tag action into the tag management log.
Definition: ChangeTags.php:938
$tables
this hook is for auditing only 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 & $tables
Definition: hooks.txt:979
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
$params
$params
Definition: styleTest.css.php:44
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
$res
$res
Definition: database.txt:21
ChangeTags\showTagEditingUI
static showTagEditingUI(User $user)
Indicate whether change tag editing UI is relevant.
Definition: ChangeTags.php:1510
ChangeTags\buildTagFilterSelector
static buildTagFilterSelector( $selected='', $ooui=false, IContextSource $context=null)
Build a text box to select a change tag.
Definition: ChangeTags.php:830
IExpiringStore\TTL_MINUTE
const TTL_MINUTE
Definition: IExpiringStore.php:34
ChangeTags\restrictedTagError
static restrictedTagError( $msgOne, $msgMulti, $tags)
Helper function to generate a fatal status with a 'not-allowed' type error.
Definition: ChangeTags.php:461
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
ChangeTags\isTagNameValid
static isTagNameValid( $tag)
Is the tag name valid?
Definition: ChangeTags.php:1105
MessageLocalizer
Interface for localizing messages in MediaWiki.
Definition: MessageLocalizer.php:28
$dbr
$dbr
Definition: testCompression.php:50
ChangeTags\truncateTagDescription
static truncateTagDescription( $tag, $length, IContextSource $context)
Get truncated message for the tag's long description.
Definition: ChangeTags.php:198
ChangeTags\listSoftwareDefinedTags
static listSoftwareDefinedTags()
Lists tags defined by core or extensions using the ListDefinedTags hook.
Definition: ChangeTags.php:1424
ChangeTags\deleteTagEverywhere
static deleteTagEverywhere( $tag)
Permanently removes all traces of a tag from the DB.
Definition: ChangeTags.php:1218
ChangeTags\modifyDisplayQuery
static modifyDisplayQuery(&$tables, &$fields, &$conds, &$join_conds, &$options, $filter_tag='')
Applies all tags-related changes to a query.
Definition: ChangeTags.php:728
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
MWException
MediaWiki exception.
Definition: MWException.php:26
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
ChangeTags\undefineTag
static undefineTag( $tag)
Update ctd_user_defined = 0 field in change_tag_def.
Definition: ChangeTags.php:904
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1078
ChangeTags
Definition: ChangeTags.php:28
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2636
ChangeTags\purgeTagUsageCache
static purgeTagUsageCache()
Invalidates the tag statistics cache only.
Definition: ChangeTags.php:1468
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
ChangeTags\listDefinedTags
static listDefinedTags()
Basically lists defined tags which count even if they aren't applied to anything.
Definition: ChangeTags.php:1372
ChangeTags\getPrevTags
static getPrevTags( $rc_id=null, $log_id=null, $rev_id=null)
Definition: ChangeTags.php:431
ChangeTags\getSoftwareTags
static getSoftwareTags( $all=false)
Loads defined core tags, checks for invalid types (if not array), and filters for supported and enabl...
Definition: ChangeTags.php:57
ChangeTags\MAX_DELETE_USES
const MAX_DELETE_USES
Can't delete tags with more than this many uses.
Definition: ChangeTags.php:34
ChangeTags\defineTag
static defineTag( $tag)
Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
Definition: ChangeTags.php:877
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
$wgSoftwareTags
array $wgSoftwareTags
List of core tags to enable.
Definition: DefaultSettings.php:7046
DB_MASTER
const DB_MASTER
Definition: defines.php:26
ChangeTags\$definedSoftwareTags
static $definedSoftwareTags
A list of tags defined and used by MediaWiki itself.
Definition: ChangeTags.php:39
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
ChangeTags\canActivateTag
static canActivateTag( $tag, User $user=null)
Is it OK to allow the user to activate this tag?
Definition: ChangeTags.php:972
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:949
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:123
ChangeTags\listExplicitlyDefinedTags
static listExplicitlyDefinedTags()
Lists tags explicitly defined in the change_tag_def table of the database.
Definition: ChangeTags.php:1386
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:604
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
Xml\tags
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:130
ChangeTags\deactivateTagWithChecks
static deactivateTagWithChecks( $tag, $reason, User $user, $ignoreWarnings=false, array $logEntryTags=[])
Deactivates a tag, checking whether it is allowed first, and adding a log entry afterwards.
Definition: ChangeTags.php:1078
RevDelLogList\suggestTarget
static suggestTarget( $target, array $ids)
Suggest a target for the revision deletion Optionally override this function.
Definition: RevDelLogList.php:44
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:430
ChangeTags\listSoftwareActivatedTags
static listSoftwareActivatedTags()
Lists those tags which core or extensions report as being "active".
Definition: ChangeTags.php:1341
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:53
Hooks\isRegistered
static isRegistered( $name)
Returns true if a hook has a function registered to it.
Definition: Hooks.php:80
ChangeTags\canAddTagsAccompanyingChange
static canAddTagsAccompanyingChange(array $tags, User $user=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
Definition: ChangeTags.php:481
$cache
$cache
Definition: mcc.php:33
ChangeTags\canCreateTag
static canCreateTag( $tag, User $user=null)
Is it OK to allow the user to create this tag?
Definition: ChangeTags.php:1141
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1985
$rev
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1769
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
ChangeTags\updateTags
static updateTags( $tagsToAdd, $tagsToRemove, &$rc_id=null, &$rev_id=null, &$log_id=null, $params=null, RecentChange $rc=null, User $user=null)
Add and remove tags to/from a change given its rc_id, rev_id and/or log_id, without verifying that th...
Definition: ChangeTags.php:263
MediaWiki\Storage\NameTableAccessException
Exception representing a failure to look up a row from a name table.
Definition: NameTableAccessException.php:32
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: LogEntry.php:441
ChangeTags\tagUsageStatistics
static tagUsageStatistics()
Returns a map of any tags used on the wiki to number of edits tagged with them, ordered descending by...
Definition: ChangeTags.php:1478
Xml\input
static input( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition: Xml.php:274
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1092
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:72
MediaWikiServices
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 MediaWikiServices
Definition: injection.txt:23
ChangeTags\addTagsAccompanyingChangeWithChecks
static addTagsAccompanyingChangeWithChecks(array $tags, $rc_id, $rev_id, $log_id, $params, User $user)
Adds tags to a given change, checking whether it is allowed first, but without adding a log entry.
Definition: ChangeTags.php:522
ChangeTags\createTagWithChecks
static createTagWithChecks( $tag, $reason, User $user, $ignoreWarnings=false, array $logEntryTags=[])
Creates a tag by adding it to change_tag_def table.
Definition: ChangeTags.php:1186
ChangeTags\canUpdateTags
static canUpdateTags(array $tagsToAdd, array $tagsToRemove, User $user=null)
Is it OK to allow the user to adds and remove the given tags tags to/from a change?
Definition: ChangeTags.php:552
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:48
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
ChangeTags\tagLongDescriptionMessage
static tagLongDescriptionMessage( $tag, MessageLocalizer $context)
Get the message object for the tag's long description.
Definition: ChangeTags.php:175
ChangeTags\deleteTagWithChecks
static deleteTagWithChecks( $tag, $reason, User $user, $ignoreWarnings=false, array $logEntryTags=[])
Deletes a tag, checking whether it is allowed first, and adding a log entry afterwards.
Definition: ChangeTags.php:1307
ChangeTags\formatSummaryRow
static formatSummaryRow( $tags, $page, IContextSource $context=null)
Creates HTML for the given tags.
Definition: ChangeTags.php:93
ChangeTags\updateTagsWithChecks
static updateTagsWithChecks( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id, $log_id, $params, $reason, User $user)
Adds and/or removes tags to/from a given change, checking whether it is allowed first,...
Definition: ChangeTags.php:619
IExpiringStore\TTL_PROC_LONG
const TTL_PROC_LONG
Definition: IExpiringStore.php:43
ChangeTags\addTags
static addTags( $tags, $rc_id=null, $rev_id=null, $log_id=null, $params=null, RecentChange $rc=null)
Add tags to a change given its rc_id, rev_id and/or log_id.
Definition: ChangeTags.php:226
ChangeTags\canDeleteTag
static canDeleteTag( $tag, User $user=null)
Is it OK to allow the user to delete this tag?
Definition: ChangeTags.php:1257
ChangeTags\tagDescription
static tagDescription( $tag, MessageLocalizer $context)
Get a short description for a tag.
Definition: ChangeTags.php:148
ChangeTags\activateTagWithChecks
static activateTagWithChecks( $tag, $reason, User $user, $ignoreWarnings=false, array $logEntryTags=[])
Activates a tag, checking whether it is allowed first, and adding a log entry afterwards.
Definition: ChangeTags.php:1015
ChangeTags\canDeactivateTag
static canDeactivateTag( $tag, User $user=null)
Is it OK to allow the user to deactivate this tag?
Definition: ChangeTags.php:1044