MediaWiki REL1_27
WatchedItemStore.php
Go to the documentation of this file.
1<?php
2
3use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
5use Wikimedia\Assert\Assert;
6
16
17 const SORT_DESC = 'DESC';
18 const SORT_ASC = 'ASC';
19
24
28 private $cache;
29
36 private $cacheIndex = [];
37
42
47
51 private $stats;
52
56 private static $instance;
57
62 public function __construct(
65 ) {
66 $this->loadBalancer = $loadBalancer;
67 $this->cache = $cache;
68 $this->stats = new NullStatsdDataFactory();
69 $this->deferredUpdatesAddCallableUpdateCallback = [ 'DeferredUpdates', 'addCallableUpdate' ];
70 $this->revisionGetTimestampFromIdCallback = [ 'Revision', 'getTimestampFromId' ];
71 }
72
73 public function setStatsdDataFactory( StatsdDataFactoryInterface $stats ) {
74 $this->stats = $stats;
75 }
76
89 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
90 throw new MWException(
91 'Cannot override DeferredUpdates::addCallableUpdate callback in operation.'
92 );
93 }
94 Assert::parameterType( 'callable', $callback, '$callback' );
95
97 $this->deferredUpdatesAddCallableUpdateCallback = $callback;
98 return new ScopedCallback( function() use ( $previousValue ) {
99 $this->deferredUpdatesAddCallableUpdateCallback = $previousValue;
100 } );
101 }
102
113 public function overrideRevisionGetTimestampFromIdCallback( $callback ) {
114 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
115 throw new MWException(
116 'Cannot override Revision::getTimestampFromId callback in operation.'
117 );
118 }
119 Assert::parameterType( 'callable', $callback, '$callback' );
120
122 $this->revisionGetTimestampFromIdCallback = $callback;
123 return new ScopedCallback( function() use ( $previousValue ) {
124 $this->revisionGetTimestampFromIdCallback = $previousValue;
125 } );
126 }
127
140 public static function overrideDefaultInstance( WatchedItemStore $store = null ) {
141 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
142 throw new MWException(
143 'Cannot override ' . __CLASS__ . 'default instance in operation.'
144 );
145 }
146
147 $previousValue = self::$instance;
148 self::$instance = $store;
149 return new ScopedCallback( function() use ( $previousValue ) {
150 self::$instance = $previousValue;
151 } );
152 }
153
157 public static function getDefaultInstance() {
158 if ( !self::$instance ) {
159 self::$instance = new self(
160 wfGetLB(),
161 new HashBagOStuff( [ 'maxKeys' => 100 ] )
162 );
163 self::$instance->setStatsdDataFactory( RequestContext::getMain()->getStats() );
164 }
165 return self::$instance;
166 }
167
168 private function getCacheKey( User $user, LinkTarget $target ) {
169 return $this->cache->makeKey(
170 (string)$target->getNamespace(),
171 $target->getDBkey(),
172 (string)$user->getId()
173 );
174 }
175
176 private function cache( WatchedItem $item ) {
177 $user = $item->getUser();
178 $target = $item->getLinkTarget();
179 $key = $this->getCacheKey( $user, $target );
180 $this->cache->set( $key, $item );
181 $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] = $key;
182 $this->stats->increment( 'WatchedItemStore.cache' );
183 }
184
185 private function uncache( User $user, LinkTarget $target ) {
186 $this->cache->delete( $this->getCacheKey( $user, $target ) );
187 unset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()][$user->getId()] );
188 $this->stats->increment( 'WatchedItemStore.uncache' );
189 }
190
191 private function uncacheLinkTarget( LinkTarget $target ) {
192 if ( !isset( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] ) ) {
193 return;
194 }
195 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget' );
196 foreach ( $this->cacheIndex[$target->getNamespace()][$target->getDBkey()] as $key ) {
197 $this->stats->increment( 'WatchedItemStore.uncacheLinkTarget.items' );
198 $this->cache->delete( $key );
199 }
200 }
201
208 private function getCached( User $user, LinkTarget $target ) {
209 return $this->cache->get( $this->getCacheKey( $user, $target ) );
210 }
211
221 private function dbCond( User $user, LinkTarget $target ) {
222 return [
223 'wl_user' => $user->getId(),
224 'wl_namespace' => $target->getNamespace(),
225 'wl_title' => $target->getDBkey(),
226 ];
227 }
228
235 private function getConnection( $slaveOrMaster ) {
236 return $this->loadBalancer->getConnection( $slaveOrMaster, [ 'watchlist' ] );
237 }
238
244 private function reuseConnection( $connection ) {
245 $this->loadBalancer->reuseConnection( $connection );
246 }
247
256 public function countWatchedItems( User $user ) {
257 $dbr = $this->getConnection( DB_SLAVE );
258 $return = (int)$dbr->selectField(
259 'watchlist',
260 'COUNT(*)',
261 [
262 'wl_user' => $user->getId()
263 ],
264 __METHOD__
265 );
266 $this->reuseConnection( $dbr );
267
268 return $return;
269 }
270
276 public function countWatchers( LinkTarget $target ) {
277 $dbr = $this->getConnection( DB_SLAVE );
278 $return = (int)$dbr->selectField(
279 'watchlist',
280 'COUNT(*)',
281 [
282 'wl_namespace' => $target->getNamespace(),
283 'wl_title' => $target->getDBkey(),
284 ],
285 __METHOD__
286 );
287 $this->reuseConnection( $dbr );
288
289 return $return;
290 }
291
302 public function countVisitingWatchers( LinkTarget $target, $threshold ) {
303 $dbr = $this->getConnection( DB_SLAVE );
304 $visitingWatchers = (int)$dbr->selectField(
305 'watchlist',
306 'COUNT(*)',
307 [
308 'wl_namespace' => $target->getNamespace(),
309 'wl_title' => $target->getDBkey(),
310 'wl_notificationtimestamp >= ' .
311 $dbr->addQuotes( $dbr->timestamp( $threshold ) ) .
312 ' OR wl_notificationtimestamp IS NULL'
313 ],
314 __METHOD__
315 );
316 $this->reuseConnection( $dbr );
317
318 return $visitingWatchers;
319 }
320
330 public function countWatchersMultiple( array $targets, array $options = [] ) {
331 if ( $targets === [] ) {
332 // No titles requested => no results returned
333 return [];
334 }
335
336 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
337
338 $dbr = $this->getConnection( DB_SLAVE );
339
340 if ( array_key_exists( 'minimumWatchers', $options ) ) {
341 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$options['minimumWatchers'];
342 }
343
344 $lb = new LinkBatch( $targets );
345 $res = $dbr->select(
346 'watchlist',
347 [ 'wl_title', 'wl_namespace', 'watchers' => 'COUNT(*)' ],
348 [ $lb->constructSet( 'wl', $dbr ) ],
349 __METHOD__,
350 $dbOptions
351 );
352
353 $this->reuseConnection( $dbr );
354
355 $watchCounts = [];
356 foreach ( $targets as $linkTarget ) {
357 $watchCounts[$linkTarget->getNamespace()][$linkTarget->getDBkey()] = 0;
358 }
359
360 foreach ( $res as $row ) {
361 $watchCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
362 }
363
364 return $watchCounts;
365 }
366
383 array $targetsWithVisitThresholds,
384 $minimumWatchers = null
385 ) {
386 $dbr = $this->getConnection( DB_SLAVE );
387
388 $conds = $this->getVisitingWatchersCondition( $dbr, $targetsWithVisitThresholds );
389
390 $dbOptions = [ 'GROUP BY' => [ 'wl_namespace', 'wl_title' ] ];
391 if ( $minimumWatchers !== null ) {
392 $dbOptions['HAVING'] = 'COUNT(*) >= ' . (int)$minimumWatchers;
393 }
394 $res = $dbr->select(
395 'watchlist',
396 [ 'wl_namespace', 'wl_title', 'watchers' => 'COUNT(*)' ],
397 $conds,
398 __METHOD__,
399 $dbOptions
400 );
401
402 $this->reuseConnection( $dbr );
403
404 $watcherCounts = [];
405 foreach ( $targetsWithVisitThresholds as list( $target ) ) {
406 /* @var LinkTarget $target */
407 $watcherCounts[$target->getNamespace()][$target->getDBkey()] = 0;
408 }
409
410 foreach ( $res as $row ) {
411 $watcherCounts[$row->wl_namespace][$row->wl_title] = (int)$row->watchers;
412 }
413
414 return $watcherCounts;
415 }
416
425 IDatabase $db,
426 array $targetsWithVisitThresholds
427 ) {
428 $missingTargets = [];
429 $namespaceConds = [];
430 foreach ( $targetsWithVisitThresholds as list( $target, $threshold ) ) {
431 if ( $threshold === null ) {
432 $missingTargets[] = $target;
433 continue;
434 }
435 /* @var LinkTarget $target */
436 $namespaceConds[$target->getNamespace()][] = $db->makeList( [
437 'wl_title = ' . $db->addQuotes( $target->getDBkey() ),
438 $db->makeList( [
439 'wl_notificationtimestamp >= ' . $db->addQuotes( $db->timestamp( $threshold ) ),
440 'wl_notificationtimestamp IS NULL'
441 ], LIST_OR )
442 ], LIST_AND );
443 }
444
445 $conds = [];
446 foreach ( $namespaceConds as $namespace => $pageConds ) {
447 $conds[] = $db->makeList( [
448 'wl_namespace = ' . $namespace,
449 '(' . $db->makeList( $pageConds, LIST_OR ) . ')'
450 ], LIST_AND );
451 }
452
453 if ( $missingTargets ) {
454 $lb = new LinkBatch( $missingTargets );
455 $conds[] = $lb->constructSet( 'wl', $db );
456 }
457
458 return $db->makeList( $conds, LIST_OR );
459 }
460
469 public function getWatchedItem( User $user, LinkTarget $target ) {
470 if ( $user->isAnon() ) {
471 return false;
472 }
473
474 $cached = $this->getCached( $user, $target );
475 if ( $cached ) {
476 $this->stats->increment( 'WatchedItemStore.getWatchedItem.cached' );
477 return $cached;
478 }
479 $this->stats->increment( 'WatchedItemStore.getWatchedItem.load' );
480 return $this->loadWatchedItem( $user, $target );
481 }
482
491 public function loadWatchedItem( User $user, LinkTarget $target ) {
492 // Only loggedin user can have a watchlist
493 if ( $user->isAnon() ) {
494 return false;
495 }
496
497 $dbr = $this->getConnection( DB_SLAVE );
498 $row = $dbr->selectRow(
499 'watchlist',
500 'wl_notificationtimestamp',
501 $this->dbCond( $user, $target ),
502 __METHOD__
503 );
504 $this->reuseConnection( $dbr );
505
506 if ( !$row ) {
507 return false;
508 }
509
510 $item = new WatchedItem(
511 $user,
512 $target,
513 $row->wl_notificationtimestamp
514 );
515 $this->cache( $item );
516
517 return $item;
518 }
519
529 public function getWatchedItemsForUser( User $user, array $options = [] ) {
530 $options += [ 'forWrite' => false ];
531
532 $dbOptions = [];
533 if ( array_key_exists( 'sort', $options ) ) {
534 Assert::parameter(
535 ( in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ) ),
536 '$options[\'sort\']',
537 'must be SORT_ASC or SORT_DESC'
538 );
539 $dbOptions['ORDER BY'] = [
540 "wl_namespace {$options['sort']}",
541 "wl_title {$options['sort']}"
542 ];
543 }
544 $db = $this->getConnection( $options['forWrite'] ? DB_MASTER : DB_SLAVE );
545
546 $res = $db->select(
547 'watchlist',
548 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
549 [ 'wl_user' => $user->getId() ],
550 __METHOD__,
551 $dbOptions
552 );
553 $this->reuseConnection( $db );
554
555 $watchedItems = [];
556 foreach ( $res as $row ) {
557 // todo these could all be cached at some point?
558 $watchedItems[] = new WatchedItem(
559 $user,
560 new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
561 $row->wl_notificationtimestamp
562 );
563 }
564
565 return $watchedItems;
566 }
567
576 public function isWatched( User $user, LinkTarget $target ) {
577 return (bool)$this->getWatchedItem( $user, $target );
578 }
579
589 public function getNotificationTimestampsBatch( User $user, array $targets ) {
590 $timestamps = [];
591 foreach ( $targets as $target ) {
592 $timestamps[$target->getNamespace()][$target->getDBkey()] = false;
593 }
594
595 if ( $user->isAnon() ) {
596 return $timestamps;
597 }
598
599 $targetsToLoad = [];
600 foreach ( $targets as $target ) {
601 $cachedItem = $this->getCached( $user, $target );
602 if ( $cachedItem ) {
603 $timestamps[$target->getNamespace()][$target->getDBkey()] =
604 $cachedItem->getNotificationTimestamp();
605 } else {
606 $targetsToLoad[] = $target;
607 }
608 }
609
610 if ( !$targetsToLoad ) {
611 return $timestamps;
612 }
613
614 $dbr = $this->getConnection( DB_SLAVE );
615
616 $lb = new LinkBatch( $targetsToLoad );
617 $res = $dbr->select(
618 'watchlist',
619 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
620 [
621 $lb->constructSet( 'wl', $dbr ),
622 'wl_user' => $user->getId(),
623 ],
624 __METHOD__
625 );
626 $this->reuseConnection( $dbr );
627
628 foreach ( $res as $row ) {
629 $timestamps[$row->wl_namespace][$row->wl_title] = $row->wl_notificationtimestamp;
630 }
631
632 return $timestamps;
633 }
634
641 public function addWatch( User $user, LinkTarget $target ) {
642 $this->addWatchBatchForUser( $user, [ $target ] );
643 }
644
651 public function addWatchBatchForUser( User $user, array $targets ) {
652 if ( $this->loadBalancer->getReadOnlyReason() !== false ) {
653 return false;
654 }
655 // Only loggedin user can have a watchlist
656 if ( $user->isAnon() ) {
657 return false;
658 }
659
660 if ( !$targets ) {
661 return true;
662 }
663
664 $rows = [];
665 foreach ( $targets as $target ) {
666 $rows[] = [
667 'wl_user' => $user->getId(),
668 'wl_namespace' => $target->getNamespace(),
669 'wl_title' => $target->getDBkey(),
670 'wl_notificationtimestamp' => null,
671 ];
672 $this->uncache( $user, $target );
673 }
674
675 $dbw = $this->getConnection( DB_MASTER );
676 foreach ( array_chunk( $rows, 100 ) as $toInsert ) {
677 // Use INSERT IGNORE to avoid overwriting the notification timestamp
678 // if there's already an entry for this page
679 $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
680 }
681 $this->reuseConnection( $dbw );
682
683 return true;
684 }
685
697 public function removeWatch( User $user, LinkTarget $target ) {
698 // Only logged in user can have a watchlist
699 if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
700 return false;
701 }
702
703 $this->uncache( $user, $target );
704
705 $dbw = $this->getConnection( DB_MASTER );
706 $dbw->delete( 'watchlist',
707 [
708 'wl_user' => $user->getId(),
709 'wl_namespace' => $target->getNamespace(),
710 'wl_title' => $target->getDBkey(),
711 ], __METHOD__
712 );
713 $success = (bool)$dbw->affectedRows();
714 $this->reuseConnection( $dbw );
715
716 return $success;
717 }
718
728 $dbw = $this->getConnection( DB_MASTER );
729 $res = $dbw->select( [ 'watchlist' ],
730 [ 'wl_user' ],
731 [
732 'wl_user != ' . intval( $editor->getId() ),
733 'wl_namespace' => $target->getNamespace(),
734 'wl_title' => $target->getDBkey(),
735 'wl_notificationtimestamp IS NULL',
736 ], __METHOD__
737 );
738
739 $watchers = [];
740 foreach ( $res as $row ) {
741 $watchers[] = intval( $row->wl_user );
742 }
743
744 if ( $watchers ) {
745 // Update wl_notificationtimestamp for all watching users except the editor
746 $fname = __METHOD__;
747 $dbw->onTransactionIdle(
748 function () use ( $dbw, $timestamp, $watchers, $target, $fname ) {
749 $dbw->update( 'watchlist',
750 [ /* SET */
751 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
752 ], [ /* WHERE */
753 'wl_user' => $watchers,
754 'wl_namespace' => $target->getNamespace(),
755 'wl_title' => $target->getDBkey(),
756 ], $fname
757 );
758 $this->uncacheLinkTarget( $target );
759 }
760 );
761 }
762
763 $this->reuseConnection( $dbw );
764
765 return $watchers;
766 }
767
780 public function resetNotificationTimestamp( User $user, Title $title, $force = '', $oldid = 0 ) {
781 // Only loggedin user can have a watchlist
782 if ( $this->loadBalancer->getReadOnlyReason() !== false || $user->isAnon() ) {
783 return false;
784 }
785
786 $item = null;
787 if ( $force != 'force' ) {
788 $item = $this->loadWatchedItem( $user, $title );
789 if ( !$item || $item->getNotificationTimestamp() === null ) {
790 return false;
791 }
792 }
793
794 // If the page is watched by the user (or may be watched), update the timestamp
796 $title,
797 [
798 'type' => 'updateWatchlistNotification',
799 'userid' => $user->getId(),
800 'notifTime' => $this->getNotificationTimestamp( $user, $title, $item, $force, $oldid ),
801 'curTime' => time()
802 ]
803 );
804
805 // Try to run this post-send
806 // Calls DeferredUpdates::addCallableUpdate in normal operation
807 call_user_func(
808 $this->deferredUpdatesAddCallableUpdateCallback,
809 function() use ( $job ) {
810 $job->run();
811 }
812 );
813
814 $this->uncache( $user, $title );
815
816 return true;
817 }
818
819 private function getNotificationTimestamp( User $user, Title $title, $item, $force, $oldid ) {
820 if ( !$oldid ) {
821 // No oldid given, assuming latest revision; clear the timestamp.
822 return null;
823 }
824
825 if ( !$title->getNextRevisionID( $oldid ) ) {
826 // Oldid given and is the latest revision for this title; clear the timestamp.
827 return null;
828 }
829
830 if ( $item === null ) {
831 $item = $this->loadWatchedItem( $user, $title );
832 }
833
834 if ( !$item ) {
835 // This can only happen if $force is enabled.
836 return null;
837 }
838
839 // Oldid given and isn't the latest; update the timestamp.
840 // This will result in no further notification emails being sent!
841 // Calls Revision::getTimestampFromId in normal operation
842 $notificationTimestamp = call_user_func(
843 $this->revisionGetTimestampFromIdCallback,
844 $title,
845 $oldid
846 );
847
848 // We need to go one second to the future because of various strict comparisons
849 // throughout the codebase
850 $ts = new MWTimestamp( $notificationTimestamp );
851 $ts->timestamp->add( new DateInterval( 'PT1S' ) );
852 $notificationTimestamp = $ts->getTimestamp( TS_MW );
853
854 if ( $notificationTimestamp < $item->getNotificationTimestamp() ) {
855 if ( $force != 'force' ) {
856 return false;
857 } else {
858 // This is a little silly…
859 return $item->getNotificationTimestamp();
860 }
861 }
862
863 return $notificationTimestamp;
864 }
865
873 public function countUnreadNotifications( User $user, $unreadLimit = null ) {
874 $queryOptions = [];
875 if ( $unreadLimit !== null ) {
876 $unreadLimit = (int)$unreadLimit;
877 $queryOptions['LIMIT'] = $unreadLimit;
878 }
879
880 $dbr = $this->getConnection( DB_SLAVE );
881 $rowCount = $dbr->selectRowCount(
882 'watchlist',
883 '1',
884 [
885 'wl_user' => $user->getId(),
886 'wl_notificationtimestamp IS NOT NULL',
887 ],
888 __METHOD__,
889 $queryOptions
890 );
891 $this->reuseConnection( $dbr );
892
893 if ( !isset( $unreadLimit ) ) {
894 return $rowCount;
895 }
896
897 if ( $rowCount >= $unreadLimit ) {
898 return true;
899 }
900
901 return $rowCount;
902 }
903
913 public function duplicateAllAssociatedEntries( LinkTarget $oldTarget, LinkTarget $newTarget ) {
914 $oldTarget = Title::newFromLinkTarget( $oldTarget );
915 $newTarget = Title::newFromLinkTarget( $newTarget );
916
917 $this->duplicateEntry( $oldTarget->getSubjectPage(), $newTarget->getSubjectPage() );
918 $this->duplicateEntry( $oldTarget->getTalkPage(), $newTarget->getTalkPage() );
919 }
920
931 public function duplicateEntry( LinkTarget $oldTarget, LinkTarget $newTarget ) {
932 $dbw = $this->getConnection( DB_MASTER );
933
934 $result = $dbw->select(
935 'watchlist',
936 [ 'wl_user', 'wl_notificationtimestamp' ],
937 [
938 'wl_namespace' => $oldTarget->getNamespace(),
939 'wl_title' => $oldTarget->getDBkey(),
940 ],
941 __METHOD__,
942 [ 'FOR UPDATE' ]
943 );
944
945 $newNamespace = $newTarget->getNamespace();
946 $newDBkey = $newTarget->getDBkey();
947
948 # Construct array to replace into the watchlist
949 $values = [];
950 foreach ( $result as $row ) {
951 $values[] = [
952 'wl_user' => $row->wl_user,
953 'wl_namespace' => $newNamespace,
954 'wl_title' => $newDBkey,
955 'wl_notificationtimestamp' => $row->wl_notificationtimestamp,
956 ];
957 }
958
959 if ( !empty( $values ) ) {
960 # Perform replace
961 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
962 # some other DBMSes, mostly due to poor simulation by us
963 $dbw->replace(
964 'watchlist',
965 [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ],
966 $values,
967 __METHOD__
968 );
969 }
970
971 $this->reuseConnection( $dbw );
972 }
973
974}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfGetLB( $wiki=false)
Get a load balancer object.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition Setup.php:35
Job for updating user activity like "last viewed" timestamps.
Simple store for keeping values in an associative array for the current process.
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition LinkBatch.php:31
Database load balancing object.
MediaWiki exception.
Library for creating and parsing MW-style timestamps.
static getMain()
Static methods.
Class for asserting that a callback happens when an dummy object leaves scope.
Represents a page (or page fragment) title within MediaWiki.
Represents a title within MediaWiki.
Definition Title.php:34
static newFromLinkTarget(LinkTarget $linkTarget)
Create a new Title from a LinkTarget.
Definition Title.php:251
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:47
Storage layer class for WatchedItems.
getCacheKey(User $user, LinkTarget $target)
countWatchedItems(User $user)
Count the number of individual items that are watched by the user.
uncacheLinkTarget(LinkTarget $target)
callable null $deferredUpdatesAddCallableUpdateCallback
loadWatchedItem(User $user, LinkTarget $target)
Loads an item from the db.
duplicateEntry(LinkTarget $oldTarget, LinkTarget $newTarget)
Check if the given title already is watched by the user, and if so add a watch for the new title.
duplicateAllAssociatedEntries(LinkTarget $oldTarget, LinkTarget $newTarget)
Check if the given title already is watched by the user, and if so add a watch for the new title.
overrideRevisionGetTimestampFromIdCallback( $callback)
Overrides the Revision::getTimestampFromId callback This is intended for use while testing and will f...
overrideDeferredUpdatesAddCallableUpdateCallback( $callback)
Overrides the DeferredUpdates::addCallableUpdate callback This is intended for use while testing and ...
static overrideDefaultInstance(WatchedItemStore $store=null)
Overrides the default instance of this class This is intended for use while testing and will fail if ...
countVisitingWatchersMultiple(array $targetsWithVisitThresholds, $minimumWatchers=null)
Number of watchers of each page who have visited recent edits to that page.
countUnreadNotifications(User $user, $unreadLimit=null)
updateNotificationTimestamp(User $editor, LinkTarget $target, $timestamp)
getNotificationTimestamp(User $user, Title $title, $item, $force, $oldid)
uncache(User $user, LinkTarget $target)
countVisitingWatchers(LinkTarget $target, $threshold)
Number of page watchers who also visited a "recent" edit.
HashBagOStuff $cache
setStatsdDataFactory(StatsdDataFactoryInterface $stats)
Sets a StatsdDataFactory instance on the object.
addWatchBatchForUser(User $user, array $targets)
getWatchedItemsForUser(User $user, array $options=[])
dbCond(User $user, LinkTarget $target)
Return an array of conditions to select or update the appropriate database row.
cache(WatchedItem $item)
callable null $revisionGetTimestampFromIdCallback
countWatchers(LinkTarget $target)
resetNotificationTimestamp(User $user, Title $title, $force='', $oldid=0)
Reset the notification timestamp of this entry.
getConnection( $slaveOrMaster)
addWatch(User $user, LinkTarget $target)
Must be called separately for Subject & Talk namespaces.
countWatchersMultiple(array $targets, array $options=[])
isWatched(User $user, LinkTarget $target)
Must be called separately for Subject & Talk namespaces.
StatsdDataFactoryInterface $stats
static self null $instance
getNotificationTimestampsBatch(User $user, array $targets)
getWatchedItem(User $user, LinkTarget $target)
Get an item (may be cached)
getVisitingWatchersCondition(IDatabase $db, array $targetsWithVisitThresholds)
Generates condition for the query used in a batch count visiting watchers.
removeWatch(User $user, LinkTarget $target)
Removes the an entry for the User watching the LinkTarget Must be called separately for Subject & Tal...
reuseConnection( $connection)
getCached(User $user, LinkTarget $target)
LoadBalancer $loadBalancer
array[] $cacheIndex
Looks like $cacheIndex[Namespace ID][Target DB Key][User Id] => 'key' The index is needed so that on ...
__construct(LoadBalancer $loadBalancer, HashBagOStuff $cache)
Representation of a pair of user and title for watchlist entries.
$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
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 DB_MASTER
Definition Defines.php:48
const LIST_OR
Definition Defines.php:197
const LIST_AND
Definition Defines.php:194
const DB_SLAVE
Definition Defines.php:47
the array() calling protocol came about after MediaWiki 1.4rc1.
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:249
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 '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:Associative array mapping language codes to prefixed links of the form "language:title". & $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':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:1799
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition hooks.txt:1042
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired 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 inclusive false for true for descending in case the handler function wants to provide a converted Content object Note that $result getContentModel() must return $toModel. 'CustomEditor' you ll need to handle error etc yourself modifying $error and returning true will cause the contents of $error to be echoed at the top of the edit form as wikitext Return true without altering $error to allow the edit to proceed & $editor
Definition hooks.txt:1241
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:944
processing should stop and the error should be shown to the user * false
Definition hooks.txt:189
if( $limit) $timestamp
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
Basic database interface for live and lazy-loaded DB handles.
Definition IDatabase.php:35
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
makeList( $a, $mode=LIST_COMMA)
Makes an encoded list of strings from an array.
addQuotes( $s)
Adds quotes and backslashes.
getNamespace()
Get the namespace index.
getDBkey()
Get the main part with underscores.
Describes a Statsd aware interface.
you have access to all of the normal MediaWiki so you can get a DB use the cache
if(count( $args)< 1) $job