MediaWiki  1.32.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, IContextSource $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, IContextSource $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  $originalDesc = self::tagLongDescriptionMessage( $tag, $context );
200  // If there is no tag description, return empty string
201  if ( !$originalDesc ) {
202  return '';
203  }
204 
205  $taglessDesc = Sanitizer::stripAllTags( $originalDesc->parse() );
206 
207  return $context->getLanguage()->truncateForVisual( $taglessDesc, $length );
208  }
209 
224  public static function addTags( $tags, $rc_id = null, $rev_id = null,
225  $log_id = null, $params = null, RecentChange $rc = null
226  ) {
227  $result = self::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
228  return (bool)$result[0];
229  }
230 
261  public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
262  &$rev_id = null, &$log_id = null, $params = null, RecentChange $rc = null,
263  User $user = null
264  ) {
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  // update the tag_summary row
338  $prevTags = [];
339  if ( !self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
340  $log_id, $prevTags )
341  ) {
342  // nothing to do
343  return [ [], [], $prevTags ];
344  }
345 
346  // insert a row into change_tag for each new tag
347  $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
348  if ( count( $tagsToAdd ) ) {
349  $changeTagMapping = [];
351  foreach ( $tagsToAdd as $tag ) {
352  $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
353  }
354 
355  $dbw->update(
356  'change_tag_def',
357  [ 'ctd_count = ctd_count + 1' ],
358  [ 'ctd_name' => $tagsToAdd ],
359  __METHOD__
360  );
361  }
362 
363  $tagsRows = [];
364  foreach ( $tagsToAdd as $tag ) {
366  $tagName = null;
367  } else {
368  $tagName = $tag;
369  }
370  // Filter so we don't insert NULLs as zero accidentally.
371  // Keep in mind that $rc_id === null means "I don't care/know about the
372  // rc_id, just delete $tag on this revision/log entry". It doesn't
373  // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
374  $tagsRows[] = array_filter(
375  [
376  'ct_tag' => $tagName,
377  'ct_rc_id' => $rc_id,
378  'ct_log_id' => $log_id,
379  'ct_rev_id' => $rev_id,
380  'ct_params' => $params,
381  'ct_tag_id' => $changeTagMapping[$tag] ?? null,
382  ]
383  );
384 
385  }
386 
387  $dbw->insert( 'change_tag', $tagsRows, __METHOD__, [ 'IGNORE' ] );
388  }
389 
390  // delete from change_tag
391  if ( count( $tagsToRemove ) ) {
392  foreach ( $tagsToRemove as $tag ) {
394  $tagName = null;
395  $tagId = $changeTagDefStore->getId( $tag );
396  } else {
397  $tagName = $tag;
398  $tagId = null;
399  }
400  $conds = array_filter(
401  [
402  'ct_tag' => $tagName,
403  'ct_rc_id' => $rc_id,
404  'ct_log_id' => $log_id,
405  'ct_rev_id' => $rev_id,
406  'ct_tag_id' => $tagId,
407  ]
408  );
409  $dbw->delete( 'change_tag', $conds, __METHOD__ );
410  if ( $dbw->affectedRows() && $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD ) {
411  $dbw->update(
412  'change_tag_def',
413  [ 'ctd_count = ctd_count - 1' ],
414  [ 'ctd_name' => $tag ],
415  __METHOD__
416  );
417 
418  $dbw->delete(
419  'change_tag_def',
420  [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
421  __METHOD__
422  );
423  }
424  }
425  }
426 
428 
429  Hooks::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
430  $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
431 
432  return [ $tagsToAdd, $tagsToRemove, $prevTags ];
433  }
434 
451  protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
452  $rc_id, $rev_id, $log_id, &$prevTags = []
453  ) {
454  $dbw = wfGetDB( DB_MASTER );
455 
456  $tsConds = array_filter( [
457  'ts_rc_id' => $rc_id,
458  'ts_rev_id' => $rev_id,
459  'ts_log_id' => $log_id
460  ] );
461 
462  // Can't both add and remove a tag at the same time...
463  $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
464 
465  // Update the summary row.
466  // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
467  // causing loss of tags added recently in tag_summary table.
468  $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__ );
469  $prevTags = $prevTags ?: '';
470  $prevTags = array_filter( explode( ',', $prevTags ) );
471 
472  // add tags
473  $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
474  $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
475 
476  // remove tags
477  $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
478  $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
479 
480  sort( $prevTags );
481  sort( $newTags );
482  if ( $prevTags == $newTags ) {
483  return false;
484  }
485 
486  if ( !$newTags ) {
487  // No tags left, so delete the row altogether
488  $dbw->delete( 'tag_summary', $tsConds, __METHOD__ );
489  } else {
490  // Specify the non-DEFAULT value columns in the INSERT/REPLACE clause
491  $row = array_filter( [ 'ts_tags' => implode( ',', $newTags ) ] + $tsConds );
492  // Check the unique keys for conflicts, ignoring any NULL *_id values
493  $uniqueKeys = [];
494  foreach ( [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ] as $uniqueColumn ) {
495  if ( isset( $row[$uniqueColumn] ) ) {
496  $uniqueKeys[] = [ $uniqueColumn ];
497  }
498  }
499 
500  $dbw->replace( 'tag_summary', $uniqueKeys, $row, __METHOD__ );
501  }
502 
503  return true;
504  }
505 
516  protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
517  $lang = RequestContext::getMain()->getLanguage();
518  $count = count( $tags );
519  return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
520  $lang->commaList( $tags ), $count );
521  }
522 
536  public static function canAddTagsAccompanyingChange( array $tags, User $user = null ) {
537  if ( !is_null( $user ) ) {
538  if ( !$user->isAllowed( 'applychangetags' ) ) {
539  return Status::newFatal( 'tags-apply-no-permission' );
540  } elseif ( $user->isBlocked() ) {
541  return Status::newFatal( 'tags-apply-blocked', $user->getName() );
542  }
543  }
544 
545  // to be applied, a tag has to be explicitly defined
546  $allowedTags = self::listExplicitlyDefinedTags();
547  Hooks::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
548  $disallowedTags = array_diff( $tags, $allowedTags );
549  if ( $disallowedTags ) {
550  return self::restrictedTagError( 'tags-apply-not-allowed-one',
551  'tags-apply-not-allowed-multi', $disallowedTags );
552  }
553 
554  return Status::newGood();
555  }
556 
577  public static function addTagsAccompanyingChangeWithChecks(
578  array $tags, $rc_id, $rev_id, $log_id, $params, User $user
579  ) {
580  // are we allowed to do this?
582  if ( !$result->isOK() ) {
583  $result->value = null;
584  return $result;
585  }
586 
587  // do it!
588  self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
589 
590  return Status::newGood( true );
591  }
592 
607  public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
608  User $user = null
609  ) {
610  if ( !is_null( $user ) ) {
611  if ( !$user->isAllowed( 'changetags' ) ) {
612  return Status::newFatal( 'tags-update-no-permission' );
613  } elseif ( $user->isBlocked() ) {
614  return Status::newFatal( 'tags-update-blocked', $user->getName() );
615  }
616  }
617 
618  if ( $tagsToAdd ) {
619  // to be added, a tag has to be explicitly defined
620  // @todo Allow extensions to define tags that can be applied by users...
621  $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
622  $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
623  if ( $diff ) {
624  return self::restrictedTagError( 'tags-update-add-not-allowed-one',
625  'tags-update-add-not-allowed-multi', $diff );
626  }
627  }
628 
629  if ( $tagsToRemove ) {
630  // to be removed, a tag must not be defined by an extension, or equivalently it
631  // has to be either explicitly defined or not defined at all
632  // (assuming no edge case of a tag both explicitly-defined and extension-defined)
633  $softwareDefinedTags = self::listSoftwareDefinedTags();
634  $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
635  if ( $intersect ) {
636  return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
637  'tags-update-remove-not-allowed-multi', $intersect );
638  }
639  }
640 
641  return Status::newGood();
642  }
643 
674  public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
675  $rc_id, $rev_id, $log_id, $params, $reason, User $user
676  ) {
677  if ( is_null( $tagsToAdd ) ) {
678  $tagsToAdd = [];
679  }
680  if ( is_null( $tagsToRemove ) ) {
681  $tagsToRemove = [];
682  }
683  if ( !$tagsToAdd && !$tagsToRemove ) {
684  // no-op, don't bother
685  return Status::newGood( (object)[
686  'logId' => null,
687  'addedTags' => [],
688  'removedTags' => [],
689  ] );
690  }
691 
692  // are we allowed to do this?
693  $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
694  if ( !$result->isOK() ) {
695  $result->value = null;
696  return $result;
697  }
698 
699  // basic rate limiting
700  if ( $user->pingLimiter( 'changetag' ) ) {
701  return Status::newFatal( 'actionthrottledtext' );
702  }
703 
704  // do it!
705  list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
706  $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
707  if ( !$tagsAdded && !$tagsRemoved ) {
708  // no-op, don't log it
709  return Status::newGood( (object)[
710  'logId' => null,
711  'addedTags' => [],
712  'removedTags' => [],
713  ] );
714  }
715 
716  // log it
717  $logEntry = new ManualLogEntry( 'tag', 'update' );
718  $logEntry->setPerformer( $user );
719  $logEntry->setComment( $reason );
720 
721  // find the appropriate target page
722  if ( $rev_id ) {
723  $rev = Revision::newFromId( $rev_id );
724  if ( $rev ) {
725  $logEntry->setTarget( $rev->getTitle() );
726  }
727  } elseif ( $log_id ) {
728  // This function is from revision deletion logic and has nothing to do with
729  // change tags, but it appears to be the only other place in core where we
730  // perform logged actions on log items.
731  $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
732  }
733 
734  if ( !$logEntry->getTarget() ) {
735  // target is required, so we have to set something
736  $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
737  }
738 
739  $logParams = [
740  '4::revid' => $rev_id,
741  '5::logid' => $log_id,
742  '6:list:tagsAdded' => $tagsAdded,
743  '7:number:tagsAddedCount' => count( $tagsAdded ),
744  '8:list:tagsRemoved' => $tagsRemoved,
745  '9:number:tagsRemovedCount' => count( $tagsRemoved ),
746  'initialTags' => $initialTags,
747  ];
748  $logEntry->setParameters( $logParams );
749  $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
750 
751  $dbw = wfGetDB( DB_MASTER );
752  $logId = $logEntry->insert( $dbw );
753  // Only send this to UDP, not RC, similar to patrol events
754  $logEntry->publish( $logId, 'udp' );
755 
756  return Status::newGood( (object)[
757  'logId' => $logId,
758  'addedTags' => $tagsAdded,
759  'removedTags' => $tagsRemoved,
760  ] );
761  }
762 
783  public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
784  &$join_conds, &$options, $filter_tag = ''
785  ) {
787 
788  // Normalize to arrays
789  $tables = (array)$tables;
790  $fields = (array)$fields;
791  $conds = (array)$conds;
793 
794  // Figure out which ID field to use
795  if ( in_array( 'recentchanges', $tables ) ) {
796  $join_cond = 'ct_rc_id=rc_id';
797  } elseif ( in_array( 'logging', $tables ) ) {
798  $join_cond = 'ct_log_id=log_id';
799  } elseif ( in_array( 'revision', $tables ) ) {
800  $join_cond = 'ct_rev_id=rev_id';
801  } elseif ( in_array( 'archive', $tables ) ) {
802  $join_cond = 'ct_rev_id=ar_rev_id';
803  } else {
804  throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
805  }
806 
807  $tagTables[] = 'change_tag';
809  $tagTables[] = 'change_tag_def';
810  $join_cond_ts_tags = [ $join_cond, 'ct_tag_id=ctd_id' ];
811  $field = 'ctd_name';
812  } else {
813  $field = 'ct_tag';
814  $join_cond_ts_tags = $join_cond;
815  }
816 
817  $fields['ts_tags'] = wfGetDB( DB_REPLICA )->buildGroupConcatField(
818  ',', $tagTables, $field, $join_cond_ts_tags
819  );
820 
821  if ( $wgUseTagFilter && $filter_tag ) {
822  // Somebody wants to filter on a tag.
823  // Add an INNER JOIN on change_tag
824 
825  $tables[] = 'change_tag';
826  $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
828  $filterTagIds = [];
829  $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
830  foreach ( (array)$filter_tag as $filterTagName ) {
831  try {
832  $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
833  } catch ( NameTableAccessException $exception ) {
834  // Return nothing.
835  $conds[] = '0';
836  break;
837  };
838  }
839 
840  if ( $filterTagIds !== [] ) {
841  $conds['ct_tag_id'] = $filterTagIds;
842  }
843  } else {
844  $conds['ct_tag'] = $filter_tag;
845  }
846 
847  if (
848  is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
849  !in_array( 'DISTINCT', $options )
850  ) {
851  $options[] = 'DISTINCT';
852  }
853  }
854  }
855 
867  public static function buildTagFilterSelector(
868  $selected = '', $ooui = false, IContextSource $context = null
869  ) {
870  if ( !$context ) {
872  }
873 
874  $config = $context->getConfig();
875  if ( !$config->get( 'UseTagFilter' ) || !count( self::listDefinedTags() ) ) {
876  return [];
877  }
878 
879  $data = [
881  'label',
882  [ 'for' => 'tagfilter' ],
883  $context->msg( 'tag-filter' )->parse()
884  )
885  ];
886 
887  if ( $ooui ) {
888  $data[] = new OOUI\TextInputWidget( [
889  'id' => 'tagfilter',
890  'name' => 'tagfilter',
891  'value' => $selected,
892  'classes' => 'mw-tagfilter-input',
893  ] );
894  } else {
895  $data[] = Xml::input(
896  'tagfilter',
897  20,
898  $selected,
899  [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
900  );
901  }
902 
903  return $data;
904  }
905 
915  public static function defineTag( $tag ) {
917 
918  $dbw = wfGetDB( DB_MASTER );
920  $tagDef = [
921  'ctd_name' => $tag,
922  'ctd_user_defined' => 1,
923  'ctd_count' => 0
924  ];
925  $dbw->upsert(
926  'change_tag_def',
927  $tagDef,
928  [ 'ctd_name' ],
929  [ 'ctd_user_defined' => 1 ],
930  __METHOD__
931  );
932  }
933 
935  $dbw->replace(
936  'valid_tag',
937  [ 'vt_tag' ],
938  [ 'vt_tag' => $tag ],
939  __METHOD__
940  );
941  }
942  // clear the memcache of defined tags
944  }
945 
954  public static function undefineTag( $tag ) {
956 
957  $dbw = wfGetDB( DB_MASTER );
958 
960  $dbw->update(
961  'change_tag_def',
962  [ 'ctd_user_defined' => 0 ],
963  [ 'ctd_name' => $tag ],
964  __METHOD__
965  );
966 
967  $dbw->delete(
968  'change_tag_def',
969  [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
970  __METHOD__
971  );
972  }
973 
975  $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__ );
976  }
977 
978  // clear the memcache of defined tags
980  }
981 
996  protected static function logTagManagementAction( $action, $tag, $reason,
997  User $user, $tagCount = null, array $logEntryTags = []
998  ) {
999  $dbw = wfGetDB( DB_MASTER );
1000 
1001  $logEntry = new ManualLogEntry( 'managetags', $action );
1002  $logEntry->setPerformer( $user );
1003  // target page is not relevant, but it has to be set, so we just put in
1004  // the title of Special:Tags
1005  $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
1006  $logEntry->setComment( $reason );
1007 
1008  $params = [ '4::tag' => $tag ];
1009  if ( !is_null( $tagCount ) ) {
1010  $params['5:number:count'] = $tagCount;
1011  }
1012  $logEntry->setParameters( $params );
1013  $logEntry->setRelations( [ 'Tag' => $tag ] );
1014  $logEntry->setTags( $logEntryTags );
1015 
1016  $logId = $logEntry->insert( $dbw );
1017  $logEntry->publish( $logId );
1018  return $logId;
1019  }
1020 
1030  public static function canActivateTag( $tag, User $user = null ) {
1031  if ( !is_null( $user ) ) {
1032  if ( !$user->isAllowed( 'managechangetags' ) ) {
1033  return Status::newFatal( 'tags-manage-no-permission' );
1034  } elseif ( $user->isBlocked() ) {
1035  return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1036  }
1037  }
1038 
1039  // defined tags cannot be activated (a defined tag is either extension-
1040  // defined, in which case the extension chooses whether or not to active it;
1041  // or user-defined, in which case it is considered active)
1042  $definedTags = self::listDefinedTags();
1043  if ( in_array( $tag, $definedTags ) ) {
1044  return Status::newFatal( 'tags-activate-not-allowed', $tag );
1045  }
1046 
1047  // non-existing tags cannot be activated
1048  $tagUsage = self::tagUsageStatistics();
1049  if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
1050  return Status::newFatal( 'tags-activate-not-found', $tag );
1051  }
1052 
1053  return Status::newGood();
1054  }
1055 
1073  public static function activateTagWithChecks( $tag, $reason, User $user,
1074  $ignoreWarnings = false, array $logEntryTags = []
1075  ) {
1076  // are we allowed to do this?
1077  $result = self::canActivateTag( $tag, $user );
1078  if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1079  $result->value = null;
1080  return $result;
1081  }
1082 
1083  // do it!
1084  self::defineTag( $tag );
1085 
1086  // log it
1087  $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user,
1088  null, $logEntryTags );
1089 
1090  return Status::newGood( $logId );
1091  }
1092 
1102  public static function canDeactivateTag( $tag, User $user = null ) {
1103  if ( !is_null( $user ) ) {
1104  if ( !$user->isAllowed( 'managechangetags' ) ) {
1105  return Status::newFatal( 'tags-manage-no-permission' );
1106  } elseif ( $user->isBlocked() ) {
1107  return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1108  }
1109  }
1110 
1111  // only explicitly-defined tags can be deactivated
1112  $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
1113  if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1114  return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
1115  }
1116  return Status::newGood();
1117  }
1118 
1136  public static function deactivateTagWithChecks( $tag, $reason, User $user,
1137  $ignoreWarnings = false, array $logEntryTags = []
1138  ) {
1139  // are we allowed to do this?
1141  if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1142  $result->value = null;
1143  return $result;
1144  }
1145 
1146  // do it!
1147  self::undefineTag( $tag );
1148 
1149  // log it
1150  $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1151  null, $logEntryTags );
1152 
1153  return Status::newGood( $logId );
1154  }
1155 
1163  public static function isTagNameValid( $tag ) {
1164  // no empty tags
1165  if ( $tag === '' ) {
1166  return Status::newFatal( 'tags-create-no-name' );
1167  }
1168 
1169  // tags cannot contain commas (used as a delimiter in tag_summary table),
1170  // pipe (used as a delimiter between multiple tags in
1171  // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1172  // MediaWiki namespace)
1173  if ( strpos( $tag, ',' ) !== false || strpos( $tag, '|' ) !== false
1174  || strpos( $tag, '/' ) !== false ) {
1175  return Status::newFatal( 'tags-create-invalid-chars' );
1176  }
1177 
1178  // could the MediaWiki namespace description messages be created?
1179  $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
1180  if ( is_null( $title ) ) {
1181  return Status::newFatal( 'tags-create-invalid-title-chars' );
1182  }
1183 
1184  return Status::newGood();
1185  }
1186 
1199  public static function canCreateTag( $tag, User $user = null ) {
1200  if ( !is_null( $user ) ) {
1201  if ( !$user->isAllowed( 'managechangetags' ) ) {
1202  return Status::newFatal( 'tags-manage-no-permission' );
1203  } elseif ( $user->isBlocked() ) {
1204  return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1205  }
1206  }
1207 
1208  $status = self::isTagNameValid( $tag );
1209  if ( !$status->isGood() ) {
1210  return $status;
1211  }
1212 
1213  // does the tag already exist?
1214  $tagUsage = self::tagUsageStatistics();
1215  if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
1216  return Status::newFatal( 'tags-create-already-exists', $tag );
1217  }
1218 
1219  // check with hooks
1220  $canCreateResult = Status::newGood();
1221  Hooks::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1222  return $canCreateResult;
1223  }
1224 
1245  public static function createTagWithChecks( $tag, $reason, User $user,
1246  $ignoreWarnings = false, array $logEntryTags = []
1247  ) {
1248  // are we allowed to do this?
1249  $result = self::canCreateTag( $tag, $user );
1250  if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1251  $result->value = null;
1252  return $result;
1253  }
1254 
1255  // do it!
1256  self::defineTag( $tag );
1257 
1258  // log it
1259  $logId = self::logTagManagementAction( 'create', $tag, $reason, $user,
1260  null, $logEntryTags );
1261 
1262  return Status::newGood( $logId );
1263  }
1264 
1277  public static function deleteTagEverywhere( $tag ) {
1279  $dbw = wfGetDB( DB_MASTER );
1280  $dbw->startAtomic( __METHOD__ );
1281 
1282  // delete from valid_tag and/or set ctd_user_defined = 0
1283  self::undefineTag( $tag );
1284 
1286  $tagId = MediaWikiServices::getInstance()->getChangeTagDefStore()->getId( $tag );
1287  $conditions = [ 'ct_tag_id' => $tagId ];
1288  } else {
1289  $conditions = [ 'ct_tag' => $tag ];
1290  }
1291 
1292  // find out which revisions use this tag, so we can delete from tag_summary
1293  $result = $dbw->select( 'change_tag',
1294  [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id' ],
1295  $conditions,
1296  __METHOD__ );
1297  foreach ( $result as $row ) {
1298  // remove the tag from the relevant row of tag_summary
1299  $tagsToAdd = [];
1300  $tagsToRemove = [ $tag ];
1301  self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id,
1302  $row->ct_rev_id, $row->ct_log_id );
1303  }
1304 
1305  // delete from change_tag
1307  $tagId = MediaWikiServices::getInstance()->getChangeTagDefStore()->getId( $tag );
1308  $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__ );
1309  } else {
1310  $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__ );
1311  }
1312 
1314  $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__ );
1315  }
1316 
1317  $dbw->endAtomic( __METHOD__ );
1318 
1319  // give extensions a chance
1321  Hooks::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1322  // let's not allow error results, as the actual tag deletion succeeded
1323  if ( !$status->isOK() ) {
1324  wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1325  $status->setOK( true );
1326  }
1327 
1328  // clear the memcache of defined tags
1330 
1331  return $status;
1332  }
1333 
1343  public static function canDeleteTag( $tag, User $user = null ) {
1344  $tagUsage = self::tagUsageStatistics();
1345 
1346  if ( !is_null( $user ) ) {
1347  if ( !$user->isAllowed( 'deletechangetags' ) ) {
1348  return Status::newFatal( 'tags-delete-no-permission' );
1349  } elseif ( $user->isBlocked() ) {
1350  return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1351  }
1352  }
1353 
1354  if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1355  return Status::newFatal( 'tags-delete-not-found', $tag );
1356  }
1357 
1358  if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1359  return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1360  }
1361 
1362  $softwareDefined = self::listSoftwareDefinedTags();
1363  if ( in_array( $tag, $softwareDefined ) ) {
1364  // extension-defined tags can't be deleted unless the extension
1365  // specifically allows it
1366  $status = Status::newFatal( 'tags-delete-not-allowed' );
1367  } else {
1368  // user-defined tags are deletable unless otherwise specified
1370  }
1371 
1372  Hooks::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1373  return $status;
1374  }
1375 
1393  public static function deleteTagWithChecks( $tag, $reason, User $user,
1394  $ignoreWarnings = false, array $logEntryTags = []
1395  ) {
1396  // are we allowed to do this?
1397  $result = self::canDeleteTag( $tag, $user );
1398  if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1399  $result->value = null;
1400  return $result;
1401  }
1402 
1403  // store the tag usage statistics
1404  $tagUsage = self::tagUsageStatistics();
1405  $hitcount = $tagUsage[$tag] ?? 0;
1406 
1407  // do it!
1408  $deleteResult = self::deleteTagEverywhere( $tag );
1409  if ( !$deleteResult->isOK() ) {
1410  return $deleteResult;
1411  }
1412 
1413  // log it
1414  $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user,
1415  $hitcount, $logEntryTags );
1416 
1417  $deleteResult->value = $logId;
1418  return $deleteResult;
1419  }
1420 
1427  public static function listSoftwareActivatedTags() {
1428  // core active tags
1429  $tags = self::getSoftwareTags();
1430  if ( !Hooks::isRegistered( 'ChangeTagsListActive' ) ) {
1431  return $tags;
1432  }
1433  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1434  return $cache->getWithSetCallback(
1435  $cache->makeKey( 'active-tags' ),
1437  function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1438  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1439 
1440  // Ask extensions which tags they consider active
1441  Hooks::run( 'ChangeTagsListActive', [ &$tags ] );
1442  return $tags;
1443  },
1444  [
1445  'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1446  'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1448  ]
1449  );
1450  }
1451 
1458  public static function listDefinedTags() {
1460  $tags2 = self::listSoftwareDefinedTags();
1461  return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1462  }
1463 
1474  public static function listExplicitlyDefinedTags() {
1475  $fname = __METHOD__;
1476 
1477  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1478  return $cache->getWithSetCallback(
1479  $cache->makeKey( 'valid-tags-db' ),
1481  function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1483  $dbr = wfGetDB( DB_REPLICA );
1484 
1485  $setOpts += Database::getCacheSetOptions( $dbr );
1486 
1489  } else {
1490  $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1491  }
1492 
1493  return array_filter( array_unique( $tags ) );
1494  },
1495  [
1496  'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1497  'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1499  ]
1500  );
1501  }
1502 
1509  private static function listExplicitlyDefinedTagsNewBackend() {
1510  $dbr = wfGetDB( DB_REPLICA );
1511  return $dbr->selectFieldValues(
1512  'change_tag_def',
1513  'ctd_name',
1514  [ 'ctd_user_defined' => 1 ],
1515  __METHOD__
1516  );
1517  }
1518 
1528  public static function listSoftwareDefinedTags() {
1529  // core defined tags
1530  $tags = self::getSoftwareTags( true );
1531  if ( !Hooks::isRegistered( 'ListDefinedTags' ) ) {
1532  return $tags;
1533  }
1534  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1535  return $cache->getWithSetCallback(
1536  $cache->makeKey( 'valid-tags-hook' ),
1538  function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1539  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1540 
1541  Hooks::run( 'ListDefinedTags', [ &$tags ] );
1542  return array_filter( array_unique( $tags ) );
1543  },
1544  [
1545  'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1546  'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1548  ]
1549  );
1550  }
1551 
1557  public static function purgeTagCacheAll() {
1558  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1559 
1560  $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1561  $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1562  $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1563 
1565  }
1566 
1571  public static function purgeTagUsageCache() {
1572  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1573 
1574  $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1575  }
1576 
1587  public static function tagUsageStatistics() {
1591  ) {
1592  return self::newTagUsageStatistics();
1593  }
1594 
1595  $fname = __METHOD__;
1596  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1597  return $cache->getWithSetCallback(
1598  $cache->makeKey( 'change-tag-statistics' ),
1600  function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1601  $dbr = wfGetDB( DB_REPLICA, 'vslow' );
1602 
1603  $setOpts += Database::getCacheSetOptions( $dbr );
1604 
1605  $res = $dbr->select(
1606  'change_tag',
1607  [ 'ct_tag', 'hitcount' => 'count(*)' ],
1608  [],
1609  $fname,
1610  [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1611  );
1612 
1613  $out = [];
1614  foreach ( $res as $row ) {
1615  $out[$row->ct_tag] = $row->hitcount;
1616  }
1617 
1618  return $out;
1619  },
1620  [
1621  'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1622  'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1624  ]
1625  );
1626  }
1627 
1633  private static function newTagUsageStatistics() {
1634  $dbr = wfGetDB( DB_REPLICA );
1635  $res = $dbr->select(
1636  'change_tag_def',
1637  [ 'ctd_name', 'ctd_count' ],
1638  [],
1639  __METHOD__,
1640  [ 'ORDER BY' => 'ctd_count DESC' ]
1641  );
1642 
1643  $out = [];
1644  foreach ( $res as $row ) {
1645  $out[$row->ctd_name] = $row->ctd_count;
1646  }
1647 
1648  return $out;
1649  }
1650 
1665  public static function showTagEditingUI( User $user ) {
1666  return $user->isAllowed( 'changetags' ) && (bool)self::listExplicitlyDefinedTags();
1667  }
1668 }
$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:1305
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
$wgUseTagFilter
$wgUseTagFilter
Allow filtering by change tag in recentchanges, history, etc Has no effect if no tags are defined in ...
Definition: DefaultSettings.php:7052
$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:244
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:280
ChangeTags\tagLongDescriptionMessage
static tagLongDescriptionMessage( $tag, IContextSource $context)
Get the message object for the tag's long description.
Definition: ChangeTags.php:175
ChangeTags\purgeTagCacheAll
static purgeTagCacheAll()
Invalidates the short-term cache of defined tags used by the list*DefinedTags functions,...
Definition: ChangeTags.php:1557
Revision\newFromId
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:114
$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:2675
$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:68
$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. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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:2034
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:996
MIGRATION_NEW
const MIGRATION_NEW
Definition: Defines.php:318
ChangeTags\listExplicitlyDefinedTagsNewBackend
static listExplicitlyDefinedTagsNewBackend()
Lists tags explicitly user defined tags.
Definition: ChangeTags.php:1509
$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:1018
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
$params
$params
Definition: styleTest.css.php:44
MIGRATION_WRITE_BOTH
const MIGRATION_WRITE_BOTH
Definition: Defines.php:316
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:1665
ChangeTags\buildTagFilterSelector
static buildTagFilterSelector( $selected='', $ooui=false, IContextSource $context=null)
Build a text box to select a change tag.
Definition: ChangeTags.php:867
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:516
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:1163
$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:1528
ChangeTags\deleteTagEverywhere
static deleteTagEverywhere( $tag)
Permanently removes all traces of a tag from the DB.
Definition: ChangeTags.php:1277
ChangeTags\modifyDisplayQuery
static modifyDisplayQuery(&$tables, &$fields, &$conds, &$join_conds, &$options, $filter_tag='')
Applies all tags-related changes to a query.
Definition: ChangeTags.php:783
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:964
ChangeTags\undefineTag
static undefineTag( $tag)
Removes a tag from the valid_tag table and/or update ctd_user_defined field in change_tag_def.
Definition: ChangeTags.php:954
ChangeTags
Definition: ChangeTags.php:28
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2693
ChangeTags\purgeTagUsageCache
static purgeTagUsageCache()
Invalidates the tag statistics cache only.
Definition: ChangeTags.php:1571
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:1458
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)
Defines a tag in the valid_tag table and/or update ctd_user_defined field in change_tag_def,...
Definition: ChangeTags.php:915
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
$wgSoftwareTags
array $wgSoftwareTags
List of core tags to enable.
Definition: DefaultSettings.php:7068
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:1030
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:988
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
MIGRATION_OLD
const MIGRATION_OLD
Definition: Defines.php:315
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:121
$wgChangeTagsSchemaMigrationStage
int $wgChangeTagsSchemaMigrationStage
change_tag table schema migration stage.
Definition: DefaultSettings.php:9020
ChangeTags\listExplicitlyDefinedTags
static listExplicitlyDefinedTags()
Lists tags explicitly defined in the valid_tag table of the database.
Definition: ChangeTags.php:1474
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:573
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:132
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:1136
RevDelLogList\suggestTarget
static suggestTarget( $target, array $ids)
Suggest a target for the revision deletion Optionally override this function.
Definition: RevDelLogList.php:44
ChangeTags\tagDescription
static tagDescription( $tag, IContextSource $context)
Get a short description for a tag.
Definition: ChangeTags.php:148
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:432
ChangeTags\listSoftwareActivatedTags
static listSoftwareActivatedTags()
Lists those tags which core or extensions report as being "active".
Definition: ChangeTags.php:1427
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:536
$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:1199
$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:2036
$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:1808
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
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
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:261
MediaWiki\Storage\NameTableAccessException
Exception representing a failure to look up a row from a name table.
Definition: NameTableAccessException.php:32
$wgTagStatisticsNewTable
bool $wgTagStatisticsNewTable
Temporarily flag to use change_tag_def table as backend of change tag statistics.
Definition: DefaultSettings.php:9032
ChangeTags\updateTagSummaryRow
static updateTagSummaryRow(&$tagsToAdd, &$tagsToRemove, $rc_id, $rev_id, $log_id, &$prevTags=[])
Adds or removes a given set of tags to/from the relevant row of the tag_summary table.
Definition: ChangeTags.php:451
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: LogEntry.php:437
ChangeTags\newTagUsageStatistics
static newTagUsageStatistics()
Same self::tagUsageStatistics() but uses change_tag_def.
Definition: ChangeTags.php:1633
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:1587
Xml\input
static input( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition: Xml.php:276
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:1132
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:577
ChangeTags\createTagWithChecks
static createTagWithChecks( $tag, $reason, User $user, $ignoreWarnings=false, array $logEntryTags=[])
Creates a tag by adding a row to the valid_tag table.
Definition: ChangeTags.php:1245
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:607
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:47
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
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:1393
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:674
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:224
ChangeTags\canDeleteTag
static canDeleteTag( $tag, User $user=null)
Is it OK to allow the user to delete this tag?
Definition: ChangeTags.php:1343
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:1073
ChangeTags\canDeactivateTag
static canDeactivateTag( $tag, User $user=null)
Is it OK to allow the user to deactivate this tag?
Definition: ChangeTags.php:1102
$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:813