MediaWiki REL1_31
ChangeTags.php
Go to the documentation of this file.
1<?php
26
33 const MAX_DELETE_USES = 5000;
34
35 private static $definedSoftwareTags = [
36 'mw-contentmodelchange',
37 'mw-new-redirect',
38 'mw-removed-redirect',
39 'mw-changed-redirect-target',
40 'mw-blank',
41 'mw-replace',
42 'mw-rollback',
43 'mw-undo',
44 ];
45
53 public static function getSoftwareTags( $all = false ) {
55 $softwareTags = [];
56
57 if ( !is_array( $wgSoftwareTags ) ) {
58 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
59 Please refer to documentation for the list of tags you can enable' );
60 return $softwareTags;
61 }
62
63 $availableSoftwareTags = !$all ?
64 array_keys( array_filter( $wgSoftwareTags ) ) :
65 array_keys( $wgSoftwareTags );
66
67 $softwareTags = array_intersect(
68 $availableSoftwareTags,
69 self::$definedSoftwareTags
70 );
71
72 return $softwareTags;
73 }
74
88 public static function formatSummaryRow( $tags, $page, IContextSource $context = null ) {
89 if ( !$tags ) {
90 return [ '', [] ];
91 }
92 if ( !$context ) {
94 }
95
96 $classes = [];
97
98 $tags = explode( ',', $tags );
99 $displayTags = [];
100 foreach ( $tags as $tag ) {
101 if ( !$tag ) {
102 continue;
103 }
104 $description = self::tagDescription( $tag, $context );
105 if ( $description === false ) {
106 continue;
107 }
108 $displayTags[] = Xml::tags(
109 'span',
110 [ 'class' => 'mw-tag-marker ' .
111 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
112 $description
113 );
114 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
115 }
116
117 if ( !$displayTags ) {
118 return [ '', [] ];
119 }
120
121 $markers = $context->msg( 'tag-list-wrapper' )
122 ->numParams( count( $displayTags ) )
123 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
124 ->parse();
125 $markers = Xml::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
126
127 return [ $markers, $classes ];
128 }
129
143 public static function tagDescription( $tag, IContextSource $context ) {
144 $msg = $context->msg( "tag-$tag" );
145 if ( !$msg->exists() ) {
146 // No such message, so return the HTML-escaped tag name.
147 return htmlspecialchars( $tag );
148 }
149 if ( $msg->isDisabled() ) {
150 // The message exists but is disabled, hide the tag.
151 return false;
152 }
153
154 // Message exists and isn't disabled, use it.
155 return $msg->parse();
156 }
157
170 public static function tagLongDescriptionMessage( $tag, IContextSource $context ) {
171 $msg = $context->msg( "tag-$tag-description" );
172 if ( !$msg->exists() ) {
173 return false;
174 }
175 if ( $msg->isDisabled() ) {
176 // The message exists but is disabled, hide the description.
177 return false;
178 }
179
180 // Message exists and isn't disabled, use it.
181 return $msg;
182 }
183
193 public static function truncateTagDescription( $tag, $length, IContextSource $context ) {
194 $originalDesc = self::tagLongDescriptionMessage( $tag, $context );
195 // If there is no tag description, return empty string
196 if ( !$originalDesc ) {
197 return '';
198 }
199
200 $taglessDesc = Sanitizer::stripAllTags( $originalDesc->parse() );
201 $escapedDesc = Sanitizer::escapeHtmlAllowEntities( $taglessDesc );
202
203 return $context->getLanguage()->truncateForVisual( $escapedDesc, $length );
204 }
205
220 public static function addTags( $tags, $rc_id = null, $rev_id = null,
221 $log_id = null, $params = null, RecentChange $rc = null
222 ) {
223 $result = self::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
224 return (bool)$result[0];
225 }
226
257 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
258 &$rev_id = null, &$log_id = null, $params = null, RecentChange $rc = null,
259 User $user = null
260 ) {
261 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
262 $tagsToRemove = array_filter( (array)$tagsToRemove );
263
264 if ( !$rc_id && !$rev_id && !$log_id ) {
265 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
266 'specified when adding or removing a tag from a change!' );
267 }
268
269 $dbw = wfGetDB( DB_MASTER );
270
271 // Might as well look for rcids and so on.
272 if ( !$rc_id ) {
273 // Info might be out of date, somewhat fractionally, on replica DB.
274 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
275 // so use that relation to avoid full table scans.
276 if ( $log_id ) {
277 $rc_id = $dbw->selectField(
278 [ 'logging', 'recentchanges' ],
279 'rc_id',
280 [
281 'log_id' => $log_id,
282 'rc_timestamp = log_timestamp',
283 'rc_logid = log_id'
284 ],
285 __METHOD__
286 );
287 } elseif ( $rev_id ) {
288 $rc_id = $dbw->selectField(
289 [ 'revision', 'recentchanges' ],
290 'rc_id',
291 [
292 'rev_id' => $rev_id,
293 'rc_timestamp = rev_timestamp',
294 'rc_this_oldid = rev_id'
295 ],
296 __METHOD__
297 );
298 }
299 } elseif ( !$log_id && !$rev_id ) {
300 // Info might be out of date, somewhat fractionally, on replica DB.
301 $log_id = $dbw->selectField(
302 'recentchanges',
303 'rc_logid',
304 [ 'rc_id' => $rc_id ],
305 __METHOD__
306 );
307 $rev_id = $dbw->selectField(
308 'recentchanges',
309 'rc_this_oldid',
310 [ 'rc_id' => $rc_id ],
311 __METHOD__
312 );
313 }
314
315 if ( $log_id && !$rev_id ) {
316 $rev_id = $dbw->selectField(
317 'log_search',
318 'ls_value',
319 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
320 __METHOD__
321 );
322 } elseif ( !$log_id && $rev_id ) {
323 $log_id = $dbw->selectField(
324 'log_search',
325 'ls_log_id',
326 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
327 __METHOD__
328 );
329 }
330
331 // update the tag_summary row
332 $prevTags = [];
333 if ( !self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
334 $log_id, $prevTags )
335 ) {
336 // nothing to do
337 return [ [], [], $prevTags ];
338 }
339
340 // insert a row into change_tag for each new tag
341 if ( count( $tagsToAdd ) ) {
342 $tagsRows = [];
343 foreach ( $tagsToAdd as $tag ) {
344 // Filter so we don't insert NULLs as zero accidentally.
345 // Keep in mind that $rc_id === null means "I don't care/know about the
346 // rc_id, just delete $tag on this revision/log entry". It doesn't
347 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
348 $tagsRows[] = array_filter(
349 [
350 'ct_tag' => $tag,
351 'ct_rc_id' => $rc_id,
352 'ct_log_id' => $log_id,
353 'ct_rev_id' => $rev_id,
354 'ct_params' => $params
355 ]
356 );
357 }
358
359 $dbw->insert( 'change_tag', $tagsRows, __METHOD__, [ 'IGNORE' ] );
360 }
361
362 // delete from change_tag
363 if ( count( $tagsToRemove ) ) {
364 foreach ( $tagsToRemove as $tag ) {
365 $conds = array_filter(
366 [
367 'ct_tag' => $tag,
368 'ct_rc_id' => $rc_id,
369 'ct_log_id' => $log_id,
370 'ct_rev_id' => $rev_id
371 ]
372 );
373 $dbw->delete( 'change_tag', $conds, __METHOD__ );
374 }
375 }
376
378
379 Hooks::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
380 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
381
382 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
383 }
384
401 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
402 $rc_id, $rev_id, $log_id, &$prevTags = []
403 ) {
404 $dbw = wfGetDB( DB_MASTER );
405
406 $tsConds = array_filter( [
407 'ts_rc_id' => $rc_id,
408 'ts_rev_id' => $rev_id,
409 'ts_log_id' => $log_id
410 ] );
411
412 // Can't both add and remove a tag at the same time...
413 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
414
415 // Update the summary row.
416 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
417 // causing loss of tags added recently in tag_summary table.
418 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__ );
419 $prevTags = $prevTags ? $prevTags : '';
420 $prevTags = array_filter( explode( ',', $prevTags ) );
421
422 // add tags
423 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
424 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
425
426 // remove tags
427 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
428 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
429
430 sort( $prevTags );
431 sort( $newTags );
432 if ( $prevTags == $newTags ) {
433 return false;
434 }
435
436 if ( !$newTags ) {
437 // No tags left, so delete the row altogether
438 $dbw->delete( 'tag_summary', $tsConds, __METHOD__ );
439 } else {
440 // Specify the non-DEFAULT value columns in the INSERT/REPLACE clause
441 $row = array_filter( [ 'ts_tags' => implode( ',', $newTags ) ] + $tsConds );
442 // Check the unique keys for conflicts, ignoring any NULL *_id values
443 $uniqueKeys = [];
444 foreach ( [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ] as $uniqueColumn ) {
445 if ( isset( $row[$uniqueColumn] ) ) {
446 $uniqueKeys[] = [ $uniqueColumn ];
447 }
448 }
449
450 $dbw->replace( 'tag_summary', $uniqueKeys, $row, __METHOD__ );
451 }
452
453 return true;
454 }
455
466 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
467 $lang = RequestContext::getMain()->getLanguage();
468 $count = count( $tags );
469 return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
470 $lang->commaList( $tags ), $count );
471 }
472
483 public static function canAddTagsAccompanyingChange( array $tags, User $user = null ) {
484 if ( !is_null( $user ) ) {
485 if ( !$user->isAllowed( 'applychangetags' ) ) {
486 return Status::newFatal( 'tags-apply-no-permission' );
487 } elseif ( $user->isBlocked() ) {
488 return Status::newFatal( 'tags-apply-blocked', $user->getName() );
489 }
490 }
491
492 // to be applied, a tag has to be explicitly defined
493 $allowedTags = self::listExplicitlyDefinedTags();
494 Hooks::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
495 $disallowedTags = array_diff( $tags, $allowedTags );
496 if ( $disallowedTags ) {
497 return self::restrictedTagError( 'tags-apply-not-allowed-one',
498 'tags-apply-not-allowed-multi', $disallowedTags );
499 }
500
501 return Status::newGood();
502 }
503
525 array $tags, $rc_id, $rev_id, $log_id, $params, User $user
526 ) {
527 // are we allowed to do this?
529 if ( !$result->isOK() ) {
530 $result->value = null;
531 return $result;
532 }
533
534 // do it!
535 self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
536
537 return Status::newGood( true );
538 }
539
551 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
552 User $user = null
553 ) {
554 if ( !is_null( $user ) ) {
555 if ( !$user->isAllowed( 'changetags' ) ) {
556 return Status::newFatal( 'tags-update-no-permission' );
557 } elseif ( $user->isBlocked() ) {
558 return Status::newFatal( 'tags-update-blocked', $user->getName() );
559 }
560 }
561
562 if ( $tagsToAdd ) {
563 // to be added, a tag has to be explicitly defined
564 // @todo Allow extensions to define tags that can be applied by users...
565 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
566 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
567 if ( $diff ) {
568 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
569 'tags-update-add-not-allowed-multi', $diff );
570 }
571 }
572
573 if ( $tagsToRemove ) {
574 // to be removed, a tag must not be defined by an extension, or equivalently it
575 // has to be either explicitly defined or not defined at all
576 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
577 $softwareDefinedTags = self::listSoftwareDefinedTags();
578 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
579 if ( $intersect ) {
580 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
581 'tags-update-remove-not-allowed-multi', $intersect );
582 }
583 }
584
585 return Status::newGood();
586 }
587
614 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
615 $rc_id, $rev_id, $log_id, $params, $reason, User $user
616 ) {
617 if ( is_null( $tagsToAdd ) ) {
618 $tagsToAdd = [];
619 }
620 if ( is_null( $tagsToRemove ) ) {
621 $tagsToRemove = [];
622 }
623 if ( !$tagsToAdd && !$tagsToRemove ) {
624 // no-op, don't bother
625 return Status::newGood( (object)[
626 'logId' => null,
627 'addedTags' => [],
628 'removedTags' => [],
629 ] );
630 }
631
632 // are we allowed to do this?
633 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
634 if ( !$result->isOK() ) {
635 $result->value = null;
636 return $result;
637 }
638
639 // basic rate limiting
640 if ( $user->pingLimiter( 'changetag' ) ) {
641 return Status::newFatal( 'actionthrottledtext' );
642 }
643
644 // do it!
645 list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
646 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
647 if ( !$tagsAdded && !$tagsRemoved ) {
648 // no-op, don't log it
649 return Status::newGood( (object)[
650 'logId' => null,
651 'addedTags' => [],
652 'removedTags' => [],
653 ] );
654 }
655
656 // log it
657 $logEntry = new ManualLogEntry( 'tag', 'update' );
658 $logEntry->setPerformer( $user );
659 $logEntry->setComment( $reason );
660
661 // find the appropriate target page
662 if ( $rev_id ) {
663 $rev = Revision::newFromId( $rev_id );
664 if ( $rev ) {
665 $logEntry->setTarget( $rev->getTitle() );
666 }
667 } elseif ( $log_id ) {
668 // This function is from revision deletion logic and has nothing to do with
669 // change tags, but it appears to be the only other place in core where we
670 // perform logged actions on log items.
671 $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
672 }
673
674 if ( !$logEntry->getTarget() ) {
675 // target is required, so we have to set something
676 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
677 }
678
679 $logParams = [
680 '4::revid' => $rev_id,
681 '5::logid' => $log_id,
682 '6:list:tagsAdded' => $tagsAdded,
683 '7:number:tagsAddedCount' => count( $tagsAdded ),
684 '8:list:tagsRemoved' => $tagsRemoved,
685 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
686 'initialTags' => $initialTags,
687 ];
688 $logEntry->setParameters( $logParams );
689 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
690
691 $dbw = wfGetDB( DB_MASTER );
692 $logId = $logEntry->insert( $dbw );
693 // Only send this to UDP, not RC, similar to patrol events
694 $logEntry->publish( $logId, 'udp' );
695
696 return Status::newGood( (object)[
697 'logId' => $logId,
698 'addedTags' => $tagsAdded,
699 'removedTags' => $tagsRemoved,
700 ] );
701 }
702
723 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
724 &$join_conds, &$options, $filter_tag = '' ) {
726
727 // Normalize to arrays
729 $fields = (array)$fields;
730 $conds = (array)$conds;
732
733 // Figure out which ID field to use
734 if ( in_array( 'recentchanges', $tables ) ) {
735 $join_cond = 'ct_rc_id=rc_id';
736 } elseif ( in_array( 'logging', $tables ) ) {
737 $join_cond = 'ct_log_id=log_id';
738 } elseif ( in_array( 'revision', $tables ) ) {
739 $join_cond = 'ct_rev_id=rev_id';
740 } elseif ( in_array( 'archive', $tables ) ) {
741 $join_cond = 'ct_rev_id=ar_rev_id';
742 } else {
743 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
744 }
745
746 $fields['ts_tags'] = wfGetDB( DB_REPLICA )->buildGroupConcatField(
747 ',', 'change_tag', 'ct_tag', $join_cond
748 );
749
750 if ( $wgUseTagFilter && $filter_tag ) {
751 // Somebody wants to filter on a tag.
752 // Add an INNER JOIN on change_tag
753
754 $tables[] = 'change_tag';
755 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
756 $conds['ct_tag'] = $filter_tag;
757 if (
758 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
759 !in_array( 'DISTINCT', $options )
760 ) {
761 $options[] = 'DISTINCT';
762 }
763 }
764 }
765
777 public static function buildTagFilterSelector(
778 $selected = '', $ooui = false, IContextSource $context = null
779 ) {
780 if ( !$context ) {
782 }
783
784 $config = $context->getConfig();
785 if ( !$config->get( 'UseTagFilter' ) || !count( self::listDefinedTags() ) ) {
786 return [];
787 }
788
789 $data = [
790 Html::rawElement(
791 'label',
792 [ 'for' => 'tagfilter' ],
793 $context->msg( 'tag-filter' )->parse()
794 )
795 ];
796
797 if ( $ooui ) {
798 $data[] = new OOUI\TextInputWidget( [
799 'id' => 'tagfilter',
800 'name' => 'tagfilter',
801 'value' => $selected,
802 'classes' => 'mw-tagfilter-input',
803 ] );
804 } else {
805 $data[] = Xml::input(
806 'tagfilter',
807 20,
808 $selected,
809 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
810 );
811 }
812
813 return $data;
814 }
815
825 public static function defineTag( $tag ) {
826 $dbw = wfGetDB( DB_MASTER );
827 $dbw->replace( 'valid_tag',
828 [ 'vt_tag' ],
829 [ 'vt_tag' => $tag ],
830 __METHOD__ );
831
832 // clear the memcache of defined tags
834 }
835
844 public static function undefineTag( $tag ) {
845 $dbw = wfGetDB( DB_MASTER );
846 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__ );
847
848 // clear the memcache of defined tags
850 }
851
866 protected static function logTagManagementAction( $action, $tag, $reason,
867 User $user, $tagCount = null, array $logEntryTags = []
868 ) {
869 $dbw = wfGetDB( DB_MASTER );
870
871 $logEntry = new ManualLogEntry( 'managetags', $action );
872 $logEntry->setPerformer( $user );
873 // target page is not relevant, but it has to be set, so we just put in
874 // the title of Special:Tags
875 $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
876 $logEntry->setComment( $reason );
877
878 $params = [ '4::tag' => $tag ];
879 if ( !is_null( $tagCount ) ) {
880 $params['5:number:count'] = $tagCount;
881 }
882 $logEntry->setParameters( $params );
883 $logEntry->setRelations( [ 'Tag' => $tag ] );
884 $logEntry->setTags( $logEntryTags );
885
886 $logId = $logEntry->insert( $dbw );
887 $logEntry->publish( $logId );
888 return $logId;
889 }
890
900 public static function canActivateTag( $tag, User $user = null ) {
901 if ( !is_null( $user ) ) {
902 if ( !$user->isAllowed( 'managechangetags' ) ) {
903 return Status::newFatal( 'tags-manage-no-permission' );
904 } elseif ( $user->isBlocked() ) {
905 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
906 }
907 }
908
909 // defined tags cannot be activated (a defined tag is either extension-
910 // defined, in which case the extension chooses whether or not to active it;
911 // or user-defined, in which case it is considered active)
912 $definedTags = self::listDefinedTags();
913 if ( in_array( $tag, $definedTags ) ) {
914 return Status::newFatal( 'tags-activate-not-allowed', $tag );
915 }
916
917 // non-existing tags cannot be activated
918 $tagUsage = self::tagUsageStatistics();
919 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
920 return Status::newFatal( 'tags-activate-not-found', $tag );
921 }
922
923 return Status::newGood();
924 }
925
943 public static function activateTagWithChecks( $tag, $reason, User $user,
944 $ignoreWarnings = false, array $logEntryTags = []
945 ) {
946 // are we allowed to do this?
948 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
949 $result->value = null;
950 return $result;
951 }
952
953 // do it!
954 self::defineTag( $tag );
955
956 // log it
957 $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user,
958 null, $logEntryTags );
959
960 return Status::newGood( $logId );
961 }
962
972 public static function canDeactivateTag( $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 // only explicitly-defined tags can be deactivated
982 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
983 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
984 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
985 }
986 return Status::newGood();
987 }
988
1006 public static function deactivateTagWithChecks( $tag, $reason, User $user,
1007 $ignoreWarnings = false, array $logEntryTags = []
1008 ) {
1009 // are we allowed to do this?
1011 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1012 $result->value = null;
1013 return $result;
1014 }
1015
1016 // do it!
1017 self::undefineTag( $tag );
1018
1019 // log it
1020 $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1021 null, $logEntryTags );
1022
1023 return Status::newGood( $logId );
1024 }
1025
1033 public static function isTagNameValid( $tag ) {
1034 // no empty tags
1035 if ( $tag === '' ) {
1036 return Status::newFatal( 'tags-create-no-name' );
1037 }
1038
1039 // tags cannot contain commas (used as a delimiter in tag_summary table),
1040 // pipe (used as a delimiter between multiple tags in
1041 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1042 // MediaWiki namespace)
1043 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '|' ) !== false
1044 || strpos( $tag, '/' ) !== false ) {
1045 return Status::newFatal( 'tags-create-invalid-chars' );
1046 }
1047
1048 // could the MediaWiki namespace description messages be created?
1049 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
1050 if ( is_null( $title ) ) {
1051 return Status::newFatal( 'tags-create-invalid-title-chars' );
1052 }
1053
1054 return Status::newGood();
1055 }
1056
1066 public static function canCreateTag( $tag, User $user = null ) {
1067 if ( !is_null( $user ) ) {
1068 if ( !$user->isAllowed( 'managechangetags' ) ) {
1069 return Status::newFatal( 'tags-manage-no-permission' );
1070 } elseif ( $user->isBlocked() ) {
1071 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1072 }
1073 }
1074
1075 $status = self::isTagNameValid( $tag );
1076 if ( !$status->isGood() ) {
1077 return $status;
1078 }
1079
1080 // does the tag already exist?
1081 $tagUsage = self::tagUsageStatistics();
1082 if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
1083 return Status::newFatal( 'tags-create-already-exists', $tag );
1084 }
1085
1086 // check with hooks
1087 $canCreateResult = Status::newGood();
1088 Hooks::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1089 return $canCreateResult;
1090 }
1091
1108 public static function createTagWithChecks( $tag, $reason, User $user,
1109 $ignoreWarnings = false, array $logEntryTags = []
1110 ) {
1111 // are we allowed to do this?
1112 $result = self::canCreateTag( $tag, $user );
1113 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1114 $result->value = null;
1115 return $result;
1116 }
1117
1118 // do it!
1119 self::defineTag( $tag );
1120
1121 // log it
1122 $logId = self::logTagManagementAction( 'create', $tag, $reason, $user,
1123 null, $logEntryTags );
1124
1125 return Status::newGood( $logId );
1126 }
1127
1140 public static function deleteTagEverywhere( $tag ) {
1141 $dbw = wfGetDB( DB_MASTER );
1142 $dbw->startAtomic( __METHOD__ );
1143
1144 // delete from valid_tag
1145 self::undefineTag( $tag );
1146
1147 // find out which revisions use this tag, so we can delete from tag_summary
1148 $result = $dbw->select( 'change_tag',
1149 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1150 [ 'ct_tag' => $tag ],
1151 __METHOD__ );
1152 foreach ( $result as $row ) {
1153 // remove the tag from the relevant row of tag_summary
1154 $tagsToAdd = [];
1155 $tagsToRemove = [ $tag ];
1156 self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id,
1157 $row->ct_rev_id, $row->ct_log_id );
1158 }
1159
1160 // delete from change_tag
1161 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__ );
1162
1163 $dbw->endAtomic( __METHOD__ );
1164
1165 // give extensions a chance
1166 $status = Status::newGood();
1167 Hooks::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1168 // let's not allow error results, as the actual tag deletion succeeded
1169 if ( !$status->isOK() ) {
1170 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1171 $status->setOK( true );
1172 }
1173
1174 // clear the memcache of defined tags
1176
1177 return $status;
1178 }
1179
1189 public static function canDeleteTag( $tag, User $user = null ) {
1190 $tagUsage = self::tagUsageStatistics();
1191
1192 if ( !is_null( $user ) ) {
1193 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1194 return Status::newFatal( 'tags-delete-no-permission' );
1195 } elseif ( $user->isBlocked() ) {
1196 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1197 }
1198 }
1199
1200 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1201 return Status::newFatal( 'tags-delete-not-found', $tag );
1202 }
1203
1204 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1205 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1206 }
1207
1208 $softwareDefined = self::listSoftwareDefinedTags();
1209 if ( in_array( $tag, $softwareDefined ) ) {
1210 // extension-defined tags can't be deleted unless the extension
1211 // specifically allows it
1212 $status = Status::newFatal( 'tags-delete-not-allowed' );
1213 } else {
1214 // user-defined tags are deletable unless otherwise specified
1215 $status = Status::newGood();
1216 }
1217
1218 Hooks::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1219 return $status;
1220 }
1221
1239 public static function deleteTagWithChecks( $tag, $reason, User $user,
1240 $ignoreWarnings = false, array $logEntryTags = []
1241 ) {
1242 // are we allowed to do this?
1243 $result = self::canDeleteTag( $tag, $user );
1244 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1245 $result->value = null;
1246 return $result;
1247 }
1248
1249 // store the tag usage statistics
1250 $tagUsage = self::tagUsageStatistics();
1251 $hitcount = isset( $tagUsage[$tag] ) ? $tagUsage[$tag] : 0;
1252
1253 // do it!
1254 $deleteResult = self::deleteTagEverywhere( $tag );
1255 if ( !$deleteResult->isOK() ) {
1256 return $deleteResult;
1257 }
1258
1259 // log it
1260 $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user,
1261 $hitcount, $logEntryTags );
1262
1263 $deleteResult->value = $logId;
1264 return $deleteResult;
1265 }
1266
1273 public static function listSoftwareActivatedTags() {
1274 // core active tags
1275 $tags = self::getSoftwareTags();
1276 if ( !Hooks::isRegistered( 'ChangeTagsListActive' ) ) {
1277 return $tags;
1278 }
1279 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1280 return $cache->getWithSetCallback(
1281 $cache->makeKey( 'active-tags' ),
1282 WANObjectCache::TTL_MINUTE * 5,
1283 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1284 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1285
1286 // Ask extensions which tags they consider active
1287 Hooks::run( 'ChangeTagsListActive', [ &$tags ] );
1288 return $tags;
1289 },
1290 [
1291 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1292 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1293 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1294 ]
1295 );
1296 }
1297
1304 public static function listDefinedTags() {
1307 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1308 }
1309
1320 public static function listExplicitlyDefinedTags() {
1321 $fname = __METHOD__;
1322
1323 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1324 return $cache->getWithSetCallback(
1325 $cache->makeKey( 'valid-tags-db' ),
1326 WANObjectCache::TTL_MINUTE * 5,
1327 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1328 $dbr = wfGetDB( DB_REPLICA );
1329
1330 $setOpts += Database::getCacheSetOptions( $dbr );
1331
1332 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1333
1334 return array_filter( array_unique( $tags ) );
1335 },
1336 [
1337 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1338 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1339 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1340 ]
1341 );
1342 }
1343
1353 public static function listSoftwareDefinedTags() {
1354 // core defined tags
1355 $tags = self::getSoftwareTags( true );
1356 if ( !Hooks::isRegistered( 'ListDefinedTags' ) ) {
1357 return $tags;
1358 }
1359 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1360 return $cache->getWithSetCallback(
1361 $cache->makeKey( 'valid-tags-hook' ),
1362 WANObjectCache::TTL_MINUTE * 5,
1363 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1364 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1365
1366 Hooks::run( 'ListDefinedTags', [ &$tags ] );
1367 return array_filter( array_unique( $tags ) );
1368 },
1369 [
1370 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1371 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1372 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1373 ]
1374 );
1375 }
1376
1382 public static function purgeTagCacheAll() {
1383 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1384
1385 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1386 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1387 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1388
1390 }
1391
1396 public static function purgeTagUsageCache() {
1397 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1398
1399 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1400 }
1401
1412 public static function tagUsageStatistics() {
1413 $fname = __METHOD__;
1414 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1415 return $cache->getWithSetCallback(
1416 $cache->makeKey( 'change-tag-statistics' ),
1417 WANObjectCache::TTL_MINUTE * 5,
1418 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1419 $dbr = wfGetDB( DB_REPLICA, 'vslow' );
1420
1421 $setOpts += Database::getCacheSetOptions( $dbr );
1422
1423 $res = $dbr->select(
1424 'change_tag',
1425 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1426 [],
1427 $fname,
1428 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1429 );
1430
1431 $out = [];
1432 foreach ( $res as $row ) {
1433 $out[$row->ct_tag] = $row->hitcount;
1434 }
1435
1436 return $out;
1437 },
1438 [
1439 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1440 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1441 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1442 ]
1443 );
1444 }
1445
1460 public static function showTagEditingUI( User $user ) {
1461 return $user->isAllowed( 'changetags' ) && (bool)self::listExplicitlyDefinedTags();
1462 }
1463}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgUseTagFilter
Allow filtering by change tag in recentchanges, history, etc Has no effect if no tags are defined in ...
array $wgSoftwareTags
List of core tags to enable.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:112
static truncateTagDescription( $tag, $length, IContextSource $context)
Get truncated message for the tag's long description.
static createTagWithChecks( $tag, $reason, User $user, $ignoreWarnings=false, array $logEntryTags=[])
Creates a tag by adding a row to the valid_tag table.
static listSoftwareDefinedTags()
Lists tags defined by core or extensions using the ListDefinedTags hook.
static buildTagFilterSelector( $selected='', $ooui=false, IContextSource $context=null)
Build a text box to select a change tag.
static purgeTagUsageCache()
Invalidates the tag statistics cache only.
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.
static logTagManagementAction( $action, $tag, $reason, User $user, $tagCount=null, array $logEntryTags=[])
Writes a tag action into the tag management log.
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...
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.
static getSoftwareTags( $all=false)
Loads defined core tags, checks for invalid types (if not array), and filters for supported and enabl...
static tagLongDescriptionMessage( $tag, IContextSource $context)
Get the message object for the tag's long description.
static restrictedTagError( $msgOne, $msgMulti, $tags)
Helper function to generate a fatal status with a 'not-allowed' type error.
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.
static tagDescription( $tag, IContextSource $context)
Get a short description for a tag.
static listSoftwareActivatedTags()
Lists those tags which core or extensions report as being "active".
static undefineTag( $tag)
Removes a tag from the valid_tag table.
static canCreateTag( $tag, User $user=null)
Is it OK to allow the user to create this tag?
static purgeTagCacheAll()
Invalidates the short-term cache of defined tags used by the list*DefinedTags functions,...
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.
static tagUsageStatistics()
Returns a map of any tags used on the wiki to number of edits tagged with them, ordered descending by...
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.
static modifyDisplayQuery(&$tables, &$fields, &$conds, &$join_conds, &$options, $filter_tag='')
Applies all tags-related changes to a query.
static formatSummaryRow( $tags, $page, IContextSource $context=null)
Creates HTML for the given tags.
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,...
static canActivateTag( $tag, User $user=null)
Is it OK to allow the user to activate this tag?
static listDefinedTags()
Basically lists defined tags which count even if they aren't applied to anything.
static defineTag( $tag)
Defines a tag in the valid_tag table, without checking that the tag name is valid.
static canDeactivateTag( $tag, User $user=null)
Is it OK to allow the user to deactivate this tag?
static showTagEditingUI(User $user)
Indicate whether change tag editing UI is relevant.
static canDeleteTag( $tag, User $user=null)
Is it OK to allow the user to delete this tag?
static $definedSoftwareTags
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.
static isTagNameValid( $tag)
Is the tag name valid?
static deleteTagEverywhere( $tag)
Permanently removes all traces of a tag from the DB.
const MAX_DELETE_USES
Can't delete tags with more than this many uses.
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?
static listExplicitlyDefinedTags()
Lists tags explicitly defined in the valid_tag table of the database.
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...
MediaWiki exception.
Class for creating log entries manually, to inject them into the database.
Definition LogEntry.php:432
MediaWikiServices is the service locator for the application scope of MediaWiki.
Utility class for creating new RC entries.
static getMain()
Get the RequestContext object associated with the main request.
static suggestTarget( $target, array $ids)
Suggest a target for the revision deletion Optionally override this function.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:53
Relational database abstraction object.
Definition Database.php:48
$res
Definition database.txt:21
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
when a variable name is used in a function
Definition design.txt:94
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
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
const NS_MEDIAWIKI
Definition Defines.php:82
the array() calling protocol came about after MediaWiki 1.4rc1.
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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! 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! 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:1993
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition hooks.txt:1015
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:2001
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:2811
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:964
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:864
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. '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:1255
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:1777
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 local account $user
Definition hooks.txt:247
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:37
Interface for objects which can provide a MediaWiki context on request.
$cache
Definition mcc.php:33
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:29
$params
if(!isset( $args[0])) $lang