MediaWiki  1.27.2
WikiPage.php
Go to the documentation of this file.
1 <?php
29 class WikiPage implements Page, IDBAccessObject {
30  // Constants for $mDataLoadedFrom and related
31 
35  public $mTitle = null;
36 
40  public $mDataLoaded = false; // !< Boolean
41  public $mIsRedirect = false; // !< Boolean
42  public $mLatest = false; // !< Integer (false means "not loaded")
46  public $mPreparedEdit = false;
47 
51  protected $mId = null;
52 
56  protected $mDataLoadedFrom = self::READ_NONE;
57 
61  protected $mRedirectTarget = null;
62 
66  protected $mLastRevision = null;
67 
71  protected $mTimestamp = '';
72 
76  protected $mTouched = '19700101000000';
77 
81  protected $mLinksUpdated = '19700101000000';
82 
87  public function __construct( Title $title ) {
88  $this->mTitle = $title;
89  }
90 
99  public static function factory( Title $title ) {
100  $ns = $title->getNamespace();
101 
102  if ( $ns == NS_MEDIA ) {
103  throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
104  } elseif ( $ns < 0 ) {
105  throw new MWException( "Invalid or virtual namespace $ns given." );
106  }
107 
108  switch ( $ns ) {
109  case NS_FILE:
110  $page = new WikiFilePage( $title );
111  break;
112  case NS_CATEGORY:
113  $page = new WikiCategoryPage( $title );
114  break;
115  default:
116  $page = new WikiPage( $title );
117  }
118 
119  return $page;
120  }
121 
132  public static function newFromID( $id, $from = 'fromdb' ) {
133  // page id's are never 0 or negative, see bug 61166
134  if ( $id < 1 ) {
135  return null;
136  }
137 
138  $from = self::convertSelectType( $from );
139  $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
140  $row = $db->selectRow(
141  'page', self::selectFields(), [ 'page_id' => $id ], __METHOD__ );
142  if ( !$row ) {
143  return null;
144  }
145  return self::newFromRow( $row, $from );
146  }
147 
159  public static function newFromRow( $row, $from = 'fromdb' ) {
160  $page = self::factory( Title::newFromRow( $row ) );
161  $page->loadFromRow( $row, $from );
162  return $page;
163  }
164 
171  private static function convertSelectType( $type ) {
172  switch ( $type ) {
173  case 'fromdb':
174  return self::READ_NORMAL;
175  case 'fromdbmaster':
176  return self::READ_LATEST;
177  case 'forupdate':
178  return self::READ_LOCKING;
179  default:
180  // It may already be an integer or whatever else
181  return $type;
182  }
183  }
184 
195  public function getActionOverrides() {
196  $content_handler = $this->getContentHandler();
197  return $content_handler->getActionOverrides();
198  }
199 
209  public function getContentHandler() {
211  }
212 
217  public function getTitle() {
218  return $this->mTitle;
219  }
220 
225  public function clear() {
226  $this->mDataLoaded = false;
227  $this->mDataLoadedFrom = self::READ_NONE;
228 
229  $this->clearCacheFields();
230  }
231 
236  protected function clearCacheFields() {
237  $this->mId = null;
238  $this->mRedirectTarget = null; // Title object if set
239  $this->mLastRevision = null; // Latest revision
240  $this->mTouched = '19700101000000';
241  $this->mLinksUpdated = '19700101000000';
242  $this->mTimestamp = '';
243  $this->mIsRedirect = false;
244  $this->mLatest = false;
245  // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
246  // the requested rev ID and content against the cached one for equality. For most
247  // content types, the output should not change during the lifetime of this cache.
248  // Clearing it can cause extra parses on edit for no reason.
249  }
250 
256  public function clearPreparedEdit() {
257  $this->mPreparedEdit = false;
258  }
259 
266  public static function selectFields() {
267  global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
268 
269  $fields = [
270  'page_id',
271  'page_namespace',
272  'page_title',
273  'page_restrictions',
274  'page_is_redirect',
275  'page_is_new',
276  'page_random',
277  'page_touched',
278  'page_links_updated',
279  'page_latest',
280  'page_len',
281  ];
282 
283  if ( $wgContentHandlerUseDB ) {
284  $fields[] = 'page_content_model';
285  }
286 
287  if ( $wgPageLanguageUseDB ) {
288  $fields[] = 'page_lang';
289  }
290 
291  return $fields;
292  }
293 
301  protected function pageData( $dbr, $conditions, $options = [] ) {
302  $fields = self::selectFields();
303 
304  Hooks::run( 'ArticlePageDataBefore', [ &$this, &$fields ] );
305 
306  $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
307 
308  Hooks::run( 'ArticlePageDataAfter', [ &$this, &$row ] );
309 
310  return $row;
311  }
312 
322  public function pageDataFromTitle( $dbr, $title, $options = [] ) {
323  return $this->pageData( $dbr, [
324  'page_namespace' => $title->getNamespace(),
325  'page_title' => $title->getDBkey() ], $options );
326  }
327 
336  public function pageDataFromId( $dbr, $id, $options = [] ) {
337  return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
338  }
339 
352  public function loadPageData( $from = 'fromdb' ) {
353  $from = self::convertSelectType( $from );
354  if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
355  // We already have the data from the correct location, no need to load it twice.
356  return;
357  }
358 
359  if ( is_int( $from ) ) {
360  list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
361  $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
362 
363  if ( !$data
364  && $index == DB_SLAVE
365  && wfGetLB()->getServerCount() > 1
366  && wfGetLB()->hasOrMadeRecentMasterChanges()
367  ) {
368  $from = self::READ_LATEST;
369  list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
370  $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
371  }
372  } else {
373  // No idea from where the caller got this data, assume slave database.
374  $data = $from;
375  $from = self::READ_NORMAL;
376  }
377 
378  $this->loadFromRow( $data, $from );
379  }
380 
392  public function loadFromRow( $data, $from ) {
393  $lc = LinkCache::singleton();
394  $lc->clearLink( $this->mTitle );
395 
396  if ( $data ) {
397  $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
398 
399  $this->mTitle->loadFromRow( $data );
400 
401  // Old-fashioned restrictions
402  $this->mTitle->loadRestrictions( $data->page_restrictions );
403 
404  $this->mId = intval( $data->page_id );
405  $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
406  $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
407  $this->mIsRedirect = intval( $data->page_is_redirect );
408  $this->mLatest = intval( $data->page_latest );
409  // Bug 37225: $latest may no longer match the cached latest Revision object.
410  // Double-check the ID of any cached latest Revision object for consistency.
411  if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
412  $this->mLastRevision = null;
413  $this->mTimestamp = '';
414  }
415  } else {
416  $lc->addBadLinkObj( $this->mTitle );
417 
418  $this->mTitle->loadFromRow( false );
419 
420  $this->clearCacheFields();
421 
422  $this->mId = 0;
423  }
424 
425  $this->mDataLoaded = true;
426  $this->mDataLoadedFrom = self::convertSelectType( $from );
427  }
428 
432  public function getId() {
433  if ( !$this->mDataLoaded ) {
434  $this->loadPageData();
435  }
436  return $this->mId;
437  }
438 
442  public function exists() {
443  if ( !$this->mDataLoaded ) {
444  $this->loadPageData();
445  }
446  return $this->mId > 0;
447  }
448 
457  public function hasViewableContent() {
458  return $this->exists() || $this->mTitle->isAlwaysKnown();
459  }
460 
466  public function isRedirect() {
467  if ( !$this->mDataLoaded ) {
468  $this->loadPageData();
469  }
470 
471  return (bool)$this->mIsRedirect;
472  }
473 
484  public function getContentModel() {
485  if ( $this->exists() ) {
486  // look at the revision's actual content model
487  $rev = $this->getRevision();
488 
489  if ( $rev !== null ) {
490  return $rev->getContentModel();
491  } else {
492  $title = $this->mTitle->getPrefixedDBkey();
493  wfWarn( "Page $title exists but has no (visible) revisions!" );
494  }
495  }
496 
497  // use the default model for this page
498  return $this->mTitle->getContentModel();
499  }
500 
505  public function checkTouched() {
506  if ( !$this->mDataLoaded ) {
507  $this->loadPageData();
508  }
509  return !$this->mIsRedirect;
510  }
511 
516  public function getTouched() {
517  if ( !$this->mDataLoaded ) {
518  $this->loadPageData();
519  }
520  return $this->mTouched;
521  }
522 
527  public function getLinksTimestamp() {
528  if ( !$this->mDataLoaded ) {
529  $this->loadPageData();
530  }
531  return $this->mLinksUpdated;
532  }
533 
538  public function getLatest() {
539  if ( !$this->mDataLoaded ) {
540  $this->loadPageData();
541  }
542  return (int)$this->mLatest;
543  }
544 
549  public function getOldestRevision() {
550 
551  // Try using the slave database first, then try the master
552  $continue = 2;
553  $db = wfGetDB( DB_SLAVE );
554  $revSelectFields = Revision::selectFields();
555 
556  $row = null;
557  while ( $continue ) {
558  $row = $db->selectRow(
559  [ 'page', 'revision' ],
560  $revSelectFields,
561  [
562  'page_namespace' => $this->mTitle->getNamespace(),
563  'page_title' => $this->mTitle->getDBkey(),
564  'rev_page = page_id'
565  ],
566  __METHOD__,
567  [
568  'ORDER BY' => 'rev_timestamp ASC'
569  ]
570  );
571 
572  if ( $row ) {
573  $continue = 0;
574  } else {
575  $db = wfGetDB( DB_MASTER );
576  $continue--;
577  }
578  }
579 
580  return $row ? Revision::newFromRow( $row ) : null;
581  }
582 
587  protected function loadLastEdit() {
588  if ( $this->mLastRevision !== null ) {
589  return; // already loaded
590  }
591 
592  $latest = $this->getLatest();
593  if ( !$latest ) {
594  return; // page doesn't exist or is missing page_latest info
595  }
596 
597  if ( $this->mDataLoadedFrom == self::READ_LOCKING ) {
598  // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
599  // includes the latest changes committed. This is true even within REPEATABLE-READ
600  // transactions, where S1 normally only sees changes committed before the first S1
601  // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
602  // may not find it since a page row UPDATE and revision row INSERT by S2 may have
603  // happened after the first S1 SELECT.
604  // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
606  } elseif ( $this->mDataLoadedFrom == self::READ_LATEST ) {
607  // Bug T93976: if page_latest was loaded from the master, fetch the
608  // revision from there as well, as it may not exist yet on a slave DB.
609  // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
611  } else {
612  $flags = 0;
613  }
614  $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
615  if ( $revision ) { // sanity
616  $this->setLastEdit( $revision );
617  }
618  }
619 
624  protected function setLastEdit( Revision $revision ) {
625  $this->mLastRevision = $revision;
626  $this->mTimestamp = $revision->getTimestamp();
627  }
628 
633  public function getRevision() {
634  $this->loadLastEdit();
635  if ( $this->mLastRevision ) {
636  return $this->mLastRevision;
637  }
638  return null;
639  }
640 
654  public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
655  $this->loadLastEdit();
656  if ( $this->mLastRevision ) {
657  return $this->mLastRevision->getContent( $audience, $user );
658  }
659  return null;
660  }
661 
674  public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
675  ContentHandler::deprecated( __METHOD__, '1.21' );
676 
677  $this->loadLastEdit();
678  if ( $this->mLastRevision ) {
679  return $this->mLastRevision->getText( $audience, $user );
680  }
681  return false;
682  }
683 
687  public function getTimestamp() {
688  // Check if the field has been filled by WikiPage::setTimestamp()
689  if ( !$this->mTimestamp ) {
690  $this->loadLastEdit();
691  }
692 
693  return wfTimestamp( TS_MW, $this->mTimestamp );
694  }
695 
701  public function setTimestamp( $ts ) {
702  $this->mTimestamp = wfTimestamp( TS_MW, $ts );
703  }
704 
714  public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
715  $this->loadLastEdit();
716  if ( $this->mLastRevision ) {
717  return $this->mLastRevision->getUser( $audience, $user );
718  } else {
719  return -1;
720  }
721  }
722 
733  public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
734  $revision = $this->getOldestRevision();
735  if ( $revision ) {
736  $userName = $revision->getUserText( $audience, $user );
737  return User::newFromName( $userName, false );
738  } else {
739  return null;
740  }
741  }
742 
752  public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
753  $this->loadLastEdit();
754  if ( $this->mLastRevision ) {
755  return $this->mLastRevision->getUserText( $audience, $user );
756  } else {
757  return '';
758  }
759  }
760 
770  public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
771  $this->loadLastEdit();
772  if ( $this->mLastRevision ) {
773  return $this->mLastRevision->getComment( $audience, $user );
774  } else {
775  return '';
776  }
777  }
778 
784  public function getMinorEdit() {
785  $this->loadLastEdit();
786  if ( $this->mLastRevision ) {
787  return $this->mLastRevision->isMinor();
788  } else {
789  return false;
790  }
791  }
792 
801  public function isCountable( $editInfo = false ) {
802  global $wgArticleCountMethod;
803 
804  if ( !$this->mTitle->isContentPage() ) {
805  return false;
806  }
807 
808  if ( $editInfo ) {
809  $content = $editInfo->pstContent;
810  } else {
811  $content = $this->getContent();
812  }
813 
814  if ( !$content || $content->isRedirect() ) {
815  return false;
816  }
817 
818  $hasLinks = null;
819 
820  if ( $wgArticleCountMethod === 'link' ) {
821  // nasty special case to avoid re-parsing to detect links
822 
823  if ( $editInfo ) {
824  // ParserOutput::getLinks() is a 2D array of page links, so
825  // to be really correct we would need to recurse in the array
826  // but the main array should only have items in it if there are
827  // links.
828  $hasLinks = (bool)count( $editInfo->output->getLinks() );
829  } else {
830  $hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
831  [ 'pl_from' => $this->getId() ], __METHOD__ );
832  }
833  }
834 
835  return $content->isCountable( $hasLinks );
836  }
837 
845  public function getRedirectTarget() {
846  if ( !$this->mTitle->isRedirect() ) {
847  return null;
848  }
849 
850  if ( $this->mRedirectTarget !== null ) {
851  return $this->mRedirectTarget;
852  }
853 
854  // Query the redirect table
855  $dbr = wfGetDB( DB_SLAVE );
856  $row = $dbr->selectRow( 'redirect',
857  [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
858  [ 'rd_from' => $this->getId() ],
859  __METHOD__
860  );
861 
862  // rd_fragment and rd_interwiki were added later, populate them if empty
863  if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
864  $this->mRedirectTarget = Title::makeTitle(
865  $row->rd_namespace, $row->rd_title,
866  $row->rd_fragment, $row->rd_interwiki
867  );
868  return $this->mRedirectTarget;
869  }
870 
871  // This page doesn't have an entry in the redirect table
872  $this->mRedirectTarget = $this->insertRedirect();
873  return $this->mRedirectTarget;
874  }
875 
884  public function insertRedirect() {
885  $content = $this->getContent();
886  $retval = $content ? $content->getUltimateRedirectTarget() : null;
887  if ( !$retval ) {
888  return null;
889  }
890 
891  // Update the DB post-send if the page has not cached since now
892  $that = $this;
893  $latest = $this->getLatest();
894  DeferredUpdates::addCallableUpdate( function() use ( $that, $retval, $latest ) {
895  $that->insertRedirectEntry( $retval, $latest );
896  } );
897 
898  return $retval;
899  }
900 
906  public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
907  $dbw = wfGetDB( DB_MASTER );
908  $dbw->startAtomic( __METHOD__ );
909 
910  if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
911  $dbw->replace( 'redirect',
912  [ 'rd_from' ],
913  [
914  'rd_from' => $this->getId(),
915  'rd_namespace' => $rt->getNamespace(),
916  'rd_title' => $rt->getDBkey(),
917  'rd_fragment' => $rt->getFragment(),
918  'rd_interwiki' => $rt->getInterwiki(),
919  ],
920  __METHOD__
921  );
922  }
923 
924  $dbw->endAtomic( __METHOD__ );
925  }
926 
932  public function followRedirect() {
933  return $this->getRedirectURL( $this->getRedirectTarget() );
934  }
935 
943  public function getRedirectURL( $rt ) {
944  if ( !$rt ) {
945  return false;
946  }
947 
948  if ( $rt->isExternal() ) {
949  if ( $rt->isLocal() ) {
950  // Offsite wikis need an HTTP redirect.
951  // This can be hard to reverse and may produce loops,
952  // so they may be disabled in the site configuration.
953  $source = $this->mTitle->getFullURL( 'redirect=no' );
954  return $rt->getFullURL( [ 'rdfrom' => $source ] );
955  } else {
956  // External pages without "local" bit set are not valid
957  // redirect targets
958  return false;
959  }
960  }
961 
962  if ( $rt->isSpecialPage() ) {
963  // Gotta handle redirects to special pages differently:
964  // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
965  // Some pages are not valid targets.
966  if ( $rt->isValidRedirectTarget() ) {
967  return $rt->getFullURL();
968  } else {
969  return false;
970  }
971  }
972 
973  return $rt;
974  }
975 
981  public function getContributors() {
982  // @todo FIXME: This is expensive; cache this info somewhere.
983 
984  $dbr = wfGetDB( DB_SLAVE );
985 
986  if ( $dbr->implicitGroupby() ) {
987  $realNameField = 'user_real_name';
988  } else {
989  $realNameField = 'MIN(user_real_name) AS user_real_name';
990  }
991 
992  $tables = [ 'revision', 'user' ];
993 
994  $fields = [
995  'user_id' => 'rev_user',
996  'user_name' => 'rev_user_text',
997  $realNameField,
998  'timestamp' => 'MAX(rev_timestamp)',
999  ];
1000 
1001  $conds = [ 'rev_page' => $this->getId() ];
1002 
1003  // The user who made the top revision gets credited as "this page was last edited by
1004  // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1005  $user = $this->getUser();
1006  if ( $user ) {
1007  $conds[] = "rev_user != $user";
1008  } else {
1009  $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1010  }
1011 
1012  // Username hidden?
1013  $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1014 
1015  $jconds = [
1016  'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1017  ];
1018 
1019  $options = [
1020  'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1021  'ORDER BY' => 'timestamp DESC',
1022  ];
1023 
1024  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1025  return new UserArrayFromResult( $res );
1026  }
1027 
1035  public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1036  return $parserOptions->getStubThreshold() == 0
1037  && $this->exists()
1038  && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1039  && $this->getContentHandler()->isParserCacheSupported();
1040  }
1041 
1055  public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1056 
1057  $useParserCache = $this->shouldCheckParserCache( $parserOptions, $oldid );
1058  wfDebug( __METHOD__ .
1059  ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1060  if ( $parserOptions->getStubThreshold() ) {
1061  wfIncrStats( 'pcache.miss.stub' );
1062  }
1063 
1064  if ( $useParserCache ) {
1065  $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1066  if ( $parserOutput !== false ) {
1067  return $parserOutput;
1068  }
1069  }
1070 
1071  if ( $oldid === null || $oldid === 0 ) {
1072  $oldid = $this->getLatest();
1073  }
1074 
1075  $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1076  $pool->execute();
1077 
1078  return $pool->getParserOutput();
1079  }
1080 
1086  public function doViewUpdates( User $user, $oldid = 0 ) {
1087  if ( wfReadOnly() ) {
1088  return;
1089  }
1090 
1091  Hooks::run( 'PageViewUpdates', [ $this, $user ] );
1092  // Update newtalk / watchlist notification status
1093  try {
1094  $user->clearNotification( $this->mTitle, $oldid );
1095  } catch ( DBError $e ) {
1096  // Avoid outage if the master is not reachable
1098  }
1099  }
1100 
1105  public function doPurge() {
1106  if ( !Hooks::run( 'ArticlePurge', [ &$this ] ) ) {
1107  return false;
1108  }
1109 
1111  wfGetDB( DB_MASTER )->onTransactionIdle( function() use ( $title ) {
1112  // Invalidate the cache in auto-commit mode
1113  $title->invalidateCache();
1114  } );
1115 
1116  // Send purge after above page_touched update was committed
1118  new CdnCacheUpdate( $title->getCdnUrls() ),
1120  );
1121 
1122  if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1123  // @todo move this logic to MessageCache
1124  if ( $this->exists() ) {
1125  // NOTE: use transclusion text for messages.
1126  // This is consistent with MessageCache::getMsgFromNamespace()
1127 
1128  $content = $this->getContent();
1129  $text = $content === null ? null : $content->getWikitextForTransclusion();
1130 
1131  if ( $text === null ) {
1132  $text = false;
1133  }
1134  } else {
1135  $text = false;
1136  }
1137 
1138  MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1139  }
1140 
1141  return true;
1142  }
1143 
1156  public function insertOn( $dbw, $pageId = null ) {
1157  $pageIdForInsert = $pageId ?: $dbw->nextSequenceValue( 'page_page_id_seq' );
1158  $dbw->insert(
1159  'page',
1160  [
1161  'page_id' => $pageIdForInsert,
1162  'page_namespace' => $this->mTitle->getNamespace(),
1163  'page_title' => $this->mTitle->getDBkey(),
1164  'page_restrictions' => '',
1165  'page_is_redirect' => 0, // Will set this shortly...
1166  'page_is_new' => 1,
1167  'page_random' => wfRandom(),
1168  'page_touched' => $dbw->timestamp(),
1169  'page_latest' => 0, // Fill this in shortly...
1170  'page_len' => 0, // Fill this in shortly...
1171  ],
1172  __METHOD__,
1173  'IGNORE'
1174  );
1175 
1176  if ( $dbw->affectedRows() > 0 ) {
1177  $newid = $pageId ?: $dbw->insertId();
1178  $this->mId = $newid;
1179  $this->mTitle->resetArticleID( $newid );
1180 
1181  return $newid;
1182  } else {
1183  return false; // nothing changed
1184  }
1185  }
1186 
1200  public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1201  $lastRevIsRedirect = null
1202  ) {
1203  global $wgContentHandlerUseDB;
1204 
1205  // Assertion to try to catch T92046
1206  if ( (int)$revision->getId() === 0 ) {
1207  throw new InvalidArgumentException(
1208  __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1209  );
1210  }
1211 
1212  $content = $revision->getContent();
1213  $len = $content ? $content->getSize() : 0;
1214  $rt = $content ? $content->getUltimateRedirectTarget() : null;
1215 
1216  $conditions = [ 'page_id' => $this->getId() ];
1217 
1218  if ( !is_null( $lastRevision ) ) {
1219  // An extra check against threads stepping on each other
1220  $conditions['page_latest'] = $lastRevision;
1221  }
1222 
1223  $row = [ /* SET */
1224  'page_latest' => $revision->getId(),
1225  'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1226  'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1227  'page_is_redirect' => $rt !== null ? 1 : 0,
1228  'page_len' => $len,
1229  ];
1230 
1231  if ( $wgContentHandlerUseDB ) {
1232  $row['page_content_model'] = $revision->getContentModel();
1233  }
1234 
1235  $dbw->update( 'page',
1236  $row,
1237  $conditions,
1238  __METHOD__ );
1239 
1240  $result = $dbw->affectedRows() > 0;
1241  if ( $result ) {
1242  $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1243  $this->setLastEdit( $revision );
1244  $this->mLatest = $revision->getId();
1245  $this->mIsRedirect = (bool)$rt;
1246  // Update the LinkCache.
1247  LinkCache::singleton()->addGoodLinkObj(
1248  $this->getId(),
1249  $this->mTitle,
1250  $len,
1251  $this->mIsRedirect,
1252  $this->mLatest,
1253  $revision->getContentModel()
1254  );
1255  }
1256 
1257  return $result;
1258  }
1259 
1271  public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1272  // Always update redirects (target link might have changed)
1273  // Update/Insert if we don't know if the last revision was a redirect or not
1274  // Delete if changing from redirect to non-redirect
1275  $isRedirect = !is_null( $redirectTitle );
1276 
1277  if ( !$isRedirect && $lastRevIsRedirect === false ) {
1278  return true;
1279  }
1280 
1281  if ( $isRedirect ) {
1282  $this->insertRedirectEntry( $redirectTitle );
1283  } else {
1284  // This is not a redirect, remove row from redirect table
1285  $where = [ 'rd_from' => $this->getId() ];
1286  $dbw->delete( 'redirect', $where, __METHOD__ );
1287  }
1288 
1289  if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1290  RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1291  }
1292 
1293  return ( $dbw->affectedRows() != 0 );
1294  }
1295 
1306  public function updateIfNewerOn( $dbw, $revision ) {
1307 
1308  $row = $dbw->selectRow(
1309  [ 'revision', 'page' ],
1310  [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1311  [
1312  'page_id' => $this->getId(),
1313  'page_latest=rev_id' ],
1314  __METHOD__ );
1315 
1316  if ( $row ) {
1317  if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1318  return false;
1319  }
1320  $prev = $row->rev_id;
1321  $lastRevIsRedirect = (bool)$row->page_is_redirect;
1322  } else {
1323  // No or missing previous revision; mark the page as new
1324  $prev = 0;
1325  $lastRevIsRedirect = null;
1326  }
1327 
1328  $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1329 
1330  return $ret;
1331  }
1332 
1343  public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1344  $handler = $undo->getContentHandler();
1345  return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1346  }
1347 
1358  public function supportsSections() {
1359  return $this->getContentHandler()->supportsSections();
1360  }
1361 
1376  public function replaceSectionContent(
1377  $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1378  ) {
1379 
1380  $baseRevId = null;
1381  if ( $edittime && $sectionId !== 'new' ) {
1382  $dbr = wfGetDB( DB_SLAVE );
1383  $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1384  // Try the master if this thread may have just added it.
1385  // This could be abstracted into a Revision method, but we don't want
1386  // to encourage loading of revisions by timestamp.
1387  if ( !$rev
1388  && wfGetLB()->getServerCount() > 1
1389  && wfGetLB()->hasOrMadeRecentMasterChanges()
1390  ) {
1391  $dbw = wfGetDB( DB_MASTER );
1392  $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1393  }
1394  if ( $rev ) {
1395  $baseRevId = $rev->getId();
1396  }
1397  }
1398 
1399  return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1400  }
1401 
1415  public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1416  $sectionTitle = '', $baseRevId = null
1417  ) {
1418 
1419  if ( strval( $sectionId ) === '' ) {
1420  // Whole-page edit; let the whole text through
1421  $newContent = $sectionContent;
1422  } else {
1423  if ( !$this->supportsSections() ) {
1424  throw new MWException( "sections not supported for content model " .
1425  $this->getContentHandler()->getModelID() );
1426  }
1427 
1428  // Bug 30711: always use current version when adding a new section
1429  if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1430  $oldContent = $this->getContent();
1431  } else {
1432  $rev = Revision::newFromId( $baseRevId );
1433  if ( !$rev ) {
1434  wfDebug( __METHOD__ . " asked for bogus section (page: " .
1435  $this->getId() . "; section: $sectionId)\n" );
1436  return null;
1437  }
1438 
1439  $oldContent = $rev->getContent();
1440  }
1441 
1442  if ( !$oldContent ) {
1443  wfDebug( __METHOD__ . ": no page text\n" );
1444  return null;
1445  }
1446 
1447  $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1448  }
1449 
1450  return $newContent;
1451  }
1452 
1458  public function checkFlags( $flags ) {
1459  if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1460  if ( $this->exists() ) {
1461  $flags |= EDIT_UPDATE;
1462  } else {
1463  $flags |= EDIT_NEW;
1464  }
1465  }
1466 
1467  return $flags;
1468  }
1469 
1522  public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1523  ContentHandler::deprecated( __METHOD__, '1.21' );
1524 
1525  $content = ContentHandler::makeContent( $text, $this->getTitle() );
1526 
1527  return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1528  }
1529 
1585  public function doEditContent(
1586  Content $content, $summary, $flags = 0, $baseRevId = false,
1587  User $user = null, $serialFormat = null, $tags = null
1588  ) {
1589  global $wgUser, $wgUseAutomaticEditSummaries;
1590 
1591  // Low-level sanity check
1592  if ( $this->mTitle->getText() === '' ) {
1593  throw new MWException( 'Something is trying to edit an article with an empty title' );
1594  }
1595  // Make sure the given content type is allowed for this page
1596  if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1597  return Status::newFatal( 'content-not-allowed-here',
1599  $this->mTitle->getPrefixedText()
1600  );
1601  }
1602 
1603  // Load the data from the master database if needed.
1604  // The caller may already loaded it from the master or even loaded it using
1605  // SELECT FOR UPDATE, so do not override that using clear().
1606  $this->loadPageData( 'fromdbmaster' );
1607 
1608  $user = $user ?: $wgUser;
1609  $flags = $this->checkFlags( $flags );
1610 
1611  // Trigger pre-save hook (using provided edit summary)
1612  $hookStatus = Status::newGood( [] );
1613  $hook_args = [ &$this, &$user, &$content, &$summary,
1614  $flags & EDIT_MINOR, null, null, &$flags, &$hookStatus ];
1615  // Check if the hook rejected the attempted save
1616  if ( !Hooks::run( 'PageContentSave', $hook_args )
1617  || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args )
1618  ) {
1619  if ( $hookStatus->isOK() ) {
1620  // Hook returned false but didn't call fatal(); use generic message
1621  $hookStatus->fatal( 'edit-hook-aborted' );
1622  }
1623 
1624  return $hookStatus;
1625  }
1626 
1627  $old_revision = $this->getRevision(); // current revision
1628  $old_content = $this->getContent( Revision::RAW ); // current revision's content
1629 
1630  // Provide autosummaries if one is not provided and autosummaries are enabled
1631  if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY ) && $summary == '' ) {
1632  $handler = $content->getContentHandler();
1633  $summary = $handler->getAutosummary( $old_content, $content, $flags );
1634  }
1635 
1636  // Get the pre-save transform content and final parser output
1637  $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1638  $pstContent = $editInfo->pstContent; // Content object
1639  $meta = [
1640  'bot' => ( $flags & EDIT_FORCE_BOT ),
1641  'minor' => ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' ),
1642  'serialized' => $editInfo->pst,
1643  'serialFormat' => $serialFormat,
1644  'baseRevId' => $baseRevId,
1645  'oldRevision' => $old_revision,
1646  'oldContent' => $old_content,
1647  'oldId' => $this->getLatest(),
1648  'oldIsRedirect' => $this->isRedirect(),
1649  'oldCountable' => $this->isCountable(),
1650  'tags' => ( $tags !== null ) ? (array)$tags : []
1651  ];
1652 
1653  // Actually create the revision and create/update the page
1654  if ( $flags & EDIT_UPDATE ) {
1655  $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1656  } else {
1657  $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1658  }
1659 
1660  // Promote user to any groups they meet the criteria for
1661  DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1662  $user->addAutopromoteOnceGroups( 'onEdit' );
1663  $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1664  } );
1665 
1666  return $status;
1667  }
1668 
1681  private function doModify(
1683  ) {
1684  global $wgUseRCPatrol;
1685 
1686  // Update article, but only if changed.
1687  $status = Status::newGood( [ 'new' => false, 'revision' => null ] );
1688 
1689  // Convenience variables
1690  $now = wfTimestampNow();
1691  $oldid = $meta['oldId'];
1693  $oldContent = $meta['oldContent'];
1694  $newsize = $content->getSize();
1695 
1696  if ( !$oldid ) {
1697  // Article gone missing
1698  $status->fatal( 'edit-gone-missing' );
1699 
1700  return $status;
1701  } elseif ( !$oldContent ) {
1702  // Sanity check for bug 37225
1703  throw new MWException( "Could not find text for current revision {$oldid}." );
1704  }
1705 
1706  // @TODO: pass content object?!
1707  $revision = new Revision( [
1708  'page' => $this->getId(),
1709  'title' => $this->mTitle, // for determining the default content model
1710  'comment' => $summary,
1711  'minor_edit' => $meta['minor'],
1712  'text' => $meta['serialized'],
1713  'len' => $newsize,
1714  'parent_id' => $oldid,
1715  'user' => $user->getId(),
1716  'user_text' => $user->getName(),
1717  'timestamp' => $now,
1718  'content_model' => $content->getModel(),
1719  'content_format' => $meta['serialFormat'],
1720  ] );
1721 
1722  $changed = !$content->equals( $oldContent );
1723 
1724  $dbw = wfGetDB( DB_MASTER );
1725 
1726  if ( $changed ) {
1727  $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1728  $status->merge( $prepStatus );
1729  if ( !$status->isOK() ) {
1730  return $status;
1731  }
1732 
1733  $dbw->startAtomic( __METHOD__ );
1734  // Get the latest page_latest value while locking it.
1735  // Do a CAS style check to see if it's the same as when this method
1736  // started. If it changed then bail out before touching the DB.
1737  $latestNow = $this->lockAndGetLatest();
1738  if ( $latestNow != $oldid ) {
1739  $dbw->endAtomic( __METHOD__ );
1740  // Page updated or deleted in the mean time
1741  $status->fatal( 'edit-conflict' );
1742 
1743  return $status;
1744  }
1745 
1746  // At this point we are now comitted to returning an OK
1747  // status unless some DB query error or other exception comes up.
1748  // This way callers don't have to call rollback() if $status is bad
1749  // unless they actually try to catch exceptions (which is rare).
1750 
1751  // Save the revision text
1752  $revisionId = $revision->insertOn( $dbw );
1753  // Update page_latest and friends to reflect the new revision
1754  if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1755  $dbw->rollback( __METHOD__ ); // sanity; this should never happen
1756  throw new MWException( "Failed to update page row to use new revision." );
1757  }
1758 
1759  Hooks::run( 'NewRevisionFromEditComplete',
1760  [ $this, $revision, $meta['baseRevId'], $user ] );
1761 
1762  // Update recentchanges
1763  if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1764  // Mark as patrolled if the user can do so
1765  $patrolled = $wgUseRCPatrol && !count(
1766  $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1767  // Add RC row to the DB
1769  $now,
1770  $this->mTitle,
1771  $revision->isMinor(),
1772  $user,
1773  $summary,
1774  $oldid,
1775  $this->getTimestamp(),
1776  $meta['bot'],
1777  '',
1778  $oldContent ? $oldContent->getSize() : 0,
1779  $newsize,
1780  $revisionId,
1781  $patrolled,
1782  $meta['tags']
1783  );
1784  }
1785 
1786  $user->incEditCount();
1787 
1788  $dbw->endAtomic( __METHOD__ );
1789  $this->mTimestamp = $now;
1790  } else {
1791  // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1792  // related variables correctly
1793  $revision->setId( $this->getLatest() );
1794  }
1795 
1796  if ( $changed ) {
1797  // Return the new revision to the caller
1798  $status->value['revision'] = $revision;
1799  } else {
1800  $status->warning( 'edit-no-change' );
1801  // Update page_touched as updateRevisionOn() was not called.
1802  // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1803  $this->mTitle->invalidateCache( $now );
1804  }
1805 
1806  // Do secondary updates once the main changes have been committed...
1807  $that = $this;
1808  $dbw->onTransactionIdle(
1809  function () use (
1810  $dbw, &$that, $revision, &$user, $content, $summary, &$flags,
1811  $changed, $meta, &$status
1812  ) {
1813  // Do per-page updates in a transaction
1814  $dbw->setFlag( DBO_TRX );
1815  // Update links tables, site stats, etc.
1816  $that->doEditUpdates(
1817  $revision,
1818  $user,
1819  [
1820  'changed' => $changed,
1821  'oldcountable' => $meta['oldCountable'],
1822  'oldrevision' => $meta['oldRevision']
1823  ]
1824  );
1825  // Trigger post-save hook
1826  $params = [ &$that, &$user, $content, $summary, $flags & EDIT_MINOR,
1827  null, null, &$flags, $revision, &$status, $meta['baseRevId'] ];
1828  ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $params );
1829  Hooks::run( 'PageContentSaveComplete', $params );
1830  }
1831  );
1832 
1833  return $status;
1834  }
1835 
1848  private function doCreate(
1850  ) {
1851  global $wgUseRCPatrol, $wgUseNPPatrol;
1852 
1853  $status = Status::newGood( [ 'new' => true, 'revision' => null ] );
1854 
1855  $now = wfTimestampNow();
1856  $newsize = $content->getSize();
1857  $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1858  $status->merge( $prepStatus );
1859  if ( !$status->isOK() ) {
1860  return $status;
1861  }
1862 
1863  $dbw = wfGetDB( DB_MASTER );
1864  $dbw->startAtomic( __METHOD__ );
1865 
1866  // Add the page record unless one already exists for the title
1867  $newid = $this->insertOn( $dbw );
1868  if ( $newid === false ) {
1869  $dbw->endAtomic( __METHOD__ ); // nothing inserted
1870  $status->fatal( 'edit-already-exists' );
1871 
1872  return $status; // nothing done
1873  }
1874 
1875  // At this point we are now comitted to returning an OK
1876  // status unless some DB query error or other exception comes up.
1877  // This way callers don't have to call rollback() if $status is bad
1878  // unless they actually try to catch exceptions (which is rare).
1879 
1880  // @TODO: pass content object?!
1881  $revision = new Revision( [
1882  'page' => $newid,
1883  'title' => $this->mTitle, // for determining the default content model
1884  'comment' => $summary,
1885  'minor_edit' => $meta['minor'],
1886  'text' => $meta['serialized'],
1887  'len' => $newsize,
1888  'user' => $user->getId(),
1889  'user_text' => $user->getName(),
1890  'timestamp' => $now,
1891  'content_model' => $content->getModel(),
1892  'content_format' => $meta['serialFormat'],
1893  ] );
1894 
1895  // Save the revision text...
1896  $revisionId = $revision->insertOn( $dbw );
1897  // Update the page record with revision data
1898  if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1899  $dbw->rollback( __METHOD__ ); // sanity; this should never happen
1900  throw new MWException( "Failed to update page row to use new revision." );
1901  }
1902 
1903  Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1904 
1905  // Update recentchanges
1906  if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1907  // Mark as patrolled if the user can do so
1908  $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) &&
1909  !count( $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1910  // Add RC row to the DB
1912  $now,
1913  $this->mTitle,
1914  $revision->isMinor(),
1915  $user,
1916  $summary,
1917  $meta['bot'],
1918  '',
1919  $newsize,
1920  $revisionId,
1921  $patrolled,
1922  $meta['tags']
1923  );
1924  }
1925 
1926  $user->incEditCount();
1927 
1928  $dbw->endAtomic( __METHOD__ );
1929  $this->mTimestamp = $now;
1930 
1931  // Return the new revision to the caller
1932  $status->value['revision'] = $revision;
1933 
1934  // Do secondary updates once the main changes have been committed...
1935  $that = $this;
1936  $dbw->onTransactionIdle(
1937  function () use (
1938  &$that, $dbw, $revision, &$user, $content, $summary, &$flags, $meta, &$status
1939  ) {
1940  // Do per-page updates in a transaction
1941  $dbw->setFlag( DBO_TRX );
1942  // Update links, etc.
1943  $that->doEditUpdates( $revision, $user, [ 'created' => true ] );
1944  // Trigger post-create hook
1945  $params = [ &$that, &$user, $content, $summary,
1946  $flags & EDIT_MINOR, null, null, &$flags, $revision ];
1947  ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $params );
1948  Hooks::run( 'PageContentInsertComplete', $params );
1949  // Trigger post-save hook
1950  $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1951  ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $params );
1952  Hooks::run( 'PageContentSaveComplete', $params );
1953 
1954  }
1955  );
1956 
1957  return $status;
1958  }
1959 
1974  public function makeParserOptions( $context ) {
1975  $options = $this->getContentHandler()->makeParserOptions( $context );
1976 
1977  if ( $this->getTitle()->isConversionTable() ) {
1978  // @todo ConversionTable should become a separate content model, so
1979  // we don't need special cases like this one.
1980  $options->disableContentConversion();
1981  }
1982 
1983  return $options;
1984  }
1985 
1996  public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1997  ContentHandler::deprecated( __METHOD__, '1.21' );
1998  $content = ContentHandler::makeContent( $text, $this->getTitle() );
1999  return $this->prepareContentForEdit( $content, $revid, $user );
2000  }
2001 
2017  public function prepareContentForEdit(
2018  Content $content, $revision = null, User $user = null,
2019  $serialFormat = null, $useCache = true
2020  ) {
2021  global $wgContLang, $wgUser, $wgAjaxEditStash;
2022 
2023  if ( is_object( $revision ) ) {
2024  $revid = $revision->getId();
2025  } else {
2026  $revid = $revision;
2027  // This code path is deprecated, and nothing is known to
2028  // use it, so performance here shouldn't be a worry.
2029  if ( $revid !== null ) {
2030  $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2031  } else {
2032  $revision = null;
2033  }
2034  }
2035 
2036  $user = is_null( $user ) ? $wgUser : $user;
2037  // XXX: check $user->getId() here???
2038 
2039  // Use a sane default for $serialFormat, see bug 57026
2040  if ( $serialFormat === null ) {
2041  $serialFormat = $content->getContentHandler()->getDefaultFormat();
2042  }
2043 
2044  if ( $this->mPreparedEdit
2045  && $this->mPreparedEdit->newContent
2046  && $this->mPreparedEdit->newContent->equals( $content )
2047  && $this->mPreparedEdit->revid == $revid
2048  && $this->mPreparedEdit->format == $serialFormat
2049  // XXX: also check $user here?
2050  ) {
2051  // Already prepared
2052  return $this->mPreparedEdit;
2053  }
2054 
2055  // The edit may have already been prepared via api.php?action=stashedit
2056  $cachedEdit = $useCache && $wgAjaxEditStash
2057  ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2058  : false;
2059 
2060  $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2061  Hooks::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2062 
2063  $edit = (object)[];
2064  if ( $cachedEdit ) {
2065  $edit->timestamp = $cachedEdit->timestamp;
2066  } else {
2067  $edit->timestamp = wfTimestampNow();
2068  }
2069  // @note: $cachedEdit is not used if the rev ID was referenced in the text
2070  $edit->revid = $revid;
2071 
2072  if ( $cachedEdit ) {
2073  $edit->pstContent = $cachedEdit->pstContent;
2074  } else {
2075  $edit->pstContent = $content
2076  ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2077  : null;
2078  }
2079 
2080  $edit->format = $serialFormat;
2081  $edit->popts = $this->makeParserOptions( 'canonical' );
2082  if ( $cachedEdit ) {
2083  $edit->output = $cachedEdit->output;
2084  } else {
2085  if ( $revision ) {
2086  // We get here if vary-revision is set. This means that this page references
2087  // itself (such as via self-transclusion). In this case, we need to make sure
2088  // that any such self-references refer to the newly-saved revision, and not
2089  // to the previous one, which could otherwise happen due to slave lag.
2090  $oldCallback = $edit->popts->getCurrentRevisionCallback();
2091  $edit->popts->setCurrentRevisionCallback(
2092  function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2093  if ( $title->equals( $revision->getTitle() ) ) {
2094  return $revision;
2095  } else {
2096  return call_user_func( $oldCallback, $title, $parser );
2097  }
2098  }
2099  );
2100  }
2101  $edit->output = $edit->pstContent
2102  ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2103  : null;
2104  }
2105 
2106  $edit->newContent = $content;
2107  $edit->oldContent = $this->getContent( Revision::RAW );
2108 
2109  // NOTE: B/C for hooks! don't use these fields!
2110  $edit->newText = $edit->newContent
2111  ? ContentHandler::getContentText( $edit->newContent )
2112  : '';
2113  $edit->oldText = $edit->oldContent
2114  ? ContentHandler::getContentText( $edit->oldContent )
2115  : '';
2116  $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2117 
2118  if ( $edit->output ) {
2119  $edit->output->setCacheTime( wfTimestampNow() );
2120  }
2121 
2122  // Process cache the result
2123  $this->mPreparedEdit = $edit;
2124 
2125  return $edit;
2126  }
2127 
2149  public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2150  global $wgRCWatchCategoryMembership, $wgContLang;
2151 
2152  $options += [
2153  'changed' => true,
2154  'created' => false,
2155  'moved' => false,
2156  'restored' => false,
2157  'oldrevision' => null,
2158  'oldcountable' => null
2159  ];
2160  $content = $revision->getContent();
2161 
2162  // Parse the text
2163  // Be careful not to do pre-save transform twice: $text is usually
2164  // already pre-save transformed once.
2165  if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2166  wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2167  $editInfo = $this->prepareContentForEdit( $content, $revision, $user );
2168  } else {
2169  wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2170  $editInfo = $this->mPreparedEdit;
2171  }
2172 
2173  // Save it to the parser cache.
2174  // Make sure the cache time matches page_touched to avoid double parsing.
2175  ParserCache::singleton()->save(
2176  $editInfo->output, $this, $editInfo->popts,
2177  $revision->getTimestamp(), $editInfo->revid
2178  );
2179 
2180  // Update the links tables and other secondary data
2181  if ( $content ) {
2182  $recursive = $options['changed']; // bug 50785
2183  $updates = $content->getSecondaryDataUpdates(
2184  $this->getTitle(), null, $recursive, $editInfo->output
2185  );
2186  foreach ( $updates as $update ) {
2187  if ( $update instanceof LinksUpdate ) {
2188  $update->setRevision( $revision );
2189  $update->setTriggeringUser( $user );
2190  }
2191  DeferredUpdates::addUpdate( $update );
2192  }
2193  if ( $wgRCWatchCategoryMembership
2194  && $this->getContentHandler()->supportsCategories() === true
2195  && ( $options['changed'] || $options['created'] )
2196  && !$options['restored']
2197  ) {
2198  // Note: jobs are pushed after deferred updates, so the job should be able to see
2199  // the recent change entry (also done via deferred updates) and carry over any
2200  // bot/deletion/IP flags, ect.
2202  $this->getTitle(),
2203  [
2204  'pageId' => $this->getId(),
2205  'revTimestamp' => $revision->getTimestamp()
2206  ]
2207  ) );
2208  }
2209  }
2210 
2211  Hooks::run( 'ArticleEditUpdates', [ &$this, &$editInfo, $options['changed'] ] );
2212 
2213  if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$this ] ) ) {
2214  // Flush old entries from the `recentchanges` table
2215  if ( mt_rand( 0, 9 ) == 0 ) {
2217  }
2218  }
2219 
2220  if ( !$this->exists() ) {
2221  return;
2222  }
2223 
2224  $id = $this->getId();
2225  $title = $this->mTitle->getPrefixedDBkey();
2226  $shortTitle = $this->mTitle->getDBkey();
2227 
2228  if ( $options['oldcountable'] === 'no-change' ||
2229  ( !$options['changed'] && !$options['moved'] )
2230  ) {
2231  $good = 0;
2232  } elseif ( $options['created'] ) {
2233  $good = (int)$this->isCountable( $editInfo );
2234  } elseif ( $options['oldcountable'] !== null ) {
2235  $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2236  } else {
2237  $good = 0;
2238  }
2239  $edits = $options['changed'] ? 1 : 0;
2240  $total = $options['created'] ? 1 : 0;
2241 
2242  DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2244 
2245  // If this is another user's talk page, update newtalk.
2246  // Don't do this if $options['changed'] = false (null-edits) nor if
2247  // it's a minor edit and the user doesn't want notifications for those.
2248  if ( $options['changed']
2249  && $this->mTitle->getNamespace() == NS_USER_TALK
2250  && $shortTitle != $user->getTitleKey()
2251  && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2252  ) {
2253  $recipient = User::newFromName( $shortTitle, false );
2254  if ( !$recipient ) {
2255  wfDebug( __METHOD__ . ": invalid username\n" );
2256  } else {
2257  // Allow extensions to prevent user notification
2258  // when a new message is added to their talk page
2259  if ( Hooks::run( 'ArticleEditUpdateNewTalk', [ &$this, $recipient ] ) ) {
2260  if ( User::isIP( $shortTitle ) ) {
2261  // An anonymous user
2262  $recipient->setNewtalk( true, $revision );
2263  } elseif ( $recipient->isLoggedIn() ) {
2264  $recipient->setNewtalk( true, $revision );
2265  } else {
2266  wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2267  }
2268  }
2269  }
2270  }
2271 
2272  if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2273  // XXX: could skip pseudo-messages like js/css here, based on content model.
2274  $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2275  if ( $msgtext === false || $msgtext === null ) {
2276  $msgtext = '';
2277  }
2278 
2279  MessageCache::singleton()->replace( $shortTitle, $msgtext );
2280 
2281  if ( $wgContLang->hasVariants() ) {
2282  $wgContLang->updateConversionTable( $this->mTitle );
2283  }
2284  }
2285 
2286  if ( $options['created'] ) {
2287  self::onArticleCreate( $this->mTitle );
2288  } elseif ( $options['changed'] ) { // bug 50785
2289  self::onArticleEdit( $this->mTitle, $revision );
2290  }
2291  }
2292 
2304  public function doQuickEditContent(
2305  Content $content, User $user, $comment = '', $minor = false, $serialFormat = null
2306  ) {
2307 
2308  $serialized = $content->serialize( $serialFormat );
2309 
2310  $dbw = wfGetDB( DB_MASTER );
2311  $revision = new Revision( [
2312  'title' => $this->getTitle(), // for determining the default content model
2313  'page' => $this->getId(),
2314  'user_text' => $user->getName(),
2315  'user' => $user->getId(),
2316  'text' => $serialized,
2317  'length' => $content->getSize(),
2318  'comment' => $comment,
2319  'minor_edit' => $minor ? 1 : 0,
2320  ] ); // XXX: set the content object?
2321  $revision->insertOn( $dbw );
2322  $this->updateRevisionOn( $dbw, $revision );
2323 
2324  Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
2325 
2326  }
2327 
2342  public function doUpdateRestrictions( array $limit, array $expiry,
2343  &$cascade, $reason, User $user, $tags = null
2344  ) {
2345  global $wgCascadingRestrictionLevels, $wgContLang;
2346 
2347  if ( wfReadOnly() ) {
2348  return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2349  }
2350 
2351  $this->loadPageData( 'fromdbmaster' );
2352  $restrictionTypes = $this->mTitle->getRestrictionTypes();
2353  $id = $this->getId();
2354 
2355  if ( !$cascade ) {
2356  $cascade = false;
2357  }
2358 
2359  // Take this opportunity to purge out expired restrictions
2361 
2362  // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2363  // we expect a single selection, but the schema allows otherwise.
2364  $isProtected = false;
2365  $protect = false;
2366  $changed = false;
2367 
2368  $dbw = wfGetDB( DB_MASTER );
2369 
2370  foreach ( $restrictionTypes as $action ) {
2371  if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2372  $expiry[$action] = 'infinity';
2373  }
2374  if ( !isset( $limit[$action] ) ) {
2375  $limit[$action] = '';
2376  } elseif ( $limit[$action] != '' ) {
2377  $protect = true;
2378  }
2379 
2380  // Get current restrictions on $action
2381  $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2382  if ( $current != '' ) {
2383  $isProtected = true;
2384  }
2385 
2386  if ( $limit[$action] != $current ) {
2387  $changed = true;
2388  } elseif ( $limit[$action] != '' ) {
2389  // Only check expiry change if the action is actually being
2390  // protected, since expiry does nothing on an not-protected
2391  // action.
2392  if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2393  $changed = true;
2394  }
2395  }
2396  }
2397 
2398  if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2399  $changed = true;
2400  }
2401 
2402  // If nothing has changed, do nothing
2403  if ( !$changed ) {
2404  return Status::newGood();
2405  }
2406 
2407  if ( !$protect ) { // No protection at all means unprotection
2408  $revCommentMsg = 'unprotectedarticle';
2409  $logAction = 'unprotect';
2410  } elseif ( $isProtected ) {
2411  $revCommentMsg = 'modifiedarticleprotection';
2412  $logAction = 'modify';
2413  } else {
2414  $revCommentMsg = 'protectedarticle';
2415  $logAction = 'protect';
2416  }
2417 
2418  // Truncate for whole multibyte characters
2419  $reason = $wgContLang->truncate( $reason, 255 );
2420 
2421  $logRelationsValues = [];
2422  $logRelationsField = null;
2423  $logParamsDetails = [];
2424 
2425  // Null revision (used for change tag insertion)
2426  $nullRevision = null;
2427 
2428  if ( $id ) { // Protection of existing page
2429  if ( !Hooks::run( 'ArticleProtect', [ &$this, &$user, $limit, $reason ] ) ) {
2430  return Status::newGood();
2431  }
2432 
2433  // Only certain restrictions can cascade...
2434  $editrestriction = isset( $limit['edit'] )
2435  ? [ $limit['edit'] ]
2436  : $this->mTitle->getRestrictions( 'edit' );
2437  foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2438  $editrestriction[$key] = 'editprotected'; // backwards compatibility
2439  }
2440  foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2441  $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2442  }
2443 
2444  $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2445  foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2446  $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2447  }
2448  foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2449  $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2450  }
2451 
2452  // The schema allows multiple restrictions
2453  if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2454  $cascade = false;
2455  }
2456 
2457  // insert null revision to identify the page protection change as edit summary
2458  $latest = $this->getLatest();
2459  $nullRevision = $this->insertProtectNullRevision(
2460  $revCommentMsg,
2461  $limit,
2462  $expiry,
2463  $cascade,
2464  $reason,
2465  $user
2466  );
2467 
2468  if ( $nullRevision === null ) {
2469  return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2470  }
2471 
2472  $logRelationsField = 'pr_id';
2473 
2474  // Update restrictions table
2475  foreach ( $limit as $action => $restrictions ) {
2476  $dbw->delete(
2477  'page_restrictions',
2478  [
2479  'pr_page' => $id,
2480  'pr_type' => $action
2481  ],
2482  __METHOD__
2483  );
2484  if ( $restrictions != '' ) {
2485  $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2486  $dbw->insert(
2487  'page_restrictions',
2488  [
2489  'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2490  'pr_page' => $id,
2491  'pr_type' => $action,
2492  'pr_level' => $restrictions,
2493  'pr_cascade' => $cascadeValue,
2494  'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2495  ],
2496  __METHOD__
2497  );
2498  $logRelationsValues[] = $dbw->insertId();
2499  $logParamsDetails[] = [
2500  'type' => $action,
2501  'level' => $restrictions,
2502  'expiry' => $expiry[$action],
2503  'cascade' => (bool)$cascadeValue,
2504  ];
2505  }
2506  }
2507 
2508  // Clear out legacy restriction fields
2509  $dbw->update(
2510  'page',
2511  [ 'page_restrictions' => '' ],
2512  [ 'page_id' => $id ],
2513  __METHOD__
2514  );
2515 
2516  Hooks::run( 'NewRevisionFromEditComplete',
2517  [ $this, $nullRevision, $latest, $user ] );
2518  Hooks::run( 'ArticleProtectComplete', [ &$this, &$user, $limit, $reason ] );
2519  } else { // Protection of non-existing page (also known as "title protection")
2520  // Cascade protection is meaningless in this case
2521  $cascade = false;
2522 
2523  if ( $limit['create'] != '' ) {
2524  $dbw->replace( 'protected_titles',
2525  [ [ 'pt_namespace', 'pt_title' ] ],
2526  [
2527  'pt_namespace' => $this->mTitle->getNamespace(),
2528  'pt_title' => $this->mTitle->getDBkey(),
2529  'pt_create_perm' => $limit['create'],
2530  'pt_timestamp' => $dbw->timestamp(),
2531  'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2532  'pt_user' => $user->getId(),
2533  'pt_reason' => $reason,
2534  ], __METHOD__
2535  );
2536  $logParamsDetails[] = [
2537  'type' => 'create',
2538  'level' => $limit['create'],
2539  'expiry' => $expiry['create'],
2540  ];
2541  } else {
2542  $dbw->delete( 'protected_titles',
2543  [
2544  'pt_namespace' => $this->mTitle->getNamespace(),
2545  'pt_title' => $this->mTitle->getDBkey()
2546  ], __METHOD__
2547  );
2548  }
2549  }
2550 
2551  $this->mTitle->flushRestrictions();
2552  InfoAction::invalidateCache( $this->mTitle );
2553 
2554  if ( $logAction == 'unprotect' ) {
2555  $params = [];
2556  } else {
2557  $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2558  $params = [
2559  '4::description' => $protectDescriptionLog, // parameter for IRC
2560  '5:bool:cascade' => $cascade,
2561  'details' => $logParamsDetails, // parameter for localize and api
2562  ];
2563  }
2564 
2565  // Update the protection log
2566  $logEntry = new ManualLogEntry( 'protect', $logAction );
2567  $logEntry->setTarget( $this->mTitle );
2568  $logEntry->setComment( $reason );
2569  $logEntry->setPerformer( $user );
2570  $logEntry->setParameters( $params );
2571  if ( !is_null( $nullRevision ) ) {
2572  $logEntry->setAssociatedRevId( $nullRevision->getId() );
2573  }
2574  $logEntry->setTags( $tags );
2575  if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2576  $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2577  }
2578  $logId = $logEntry->insert();
2579  $logEntry->publish( $logId );
2580 
2581  return Status::newGood( $logId );
2582  }
2583 
2595  public function insertProtectNullRevision( $revCommentMsg, array $limit,
2596  array $expiry, $cascade, $reason, $user = null
2597  ) {
2599  $dbw = wfGetDB( DB_MASTER );
2600 
2601  // Prepare a null revision to be added to the history
2602  $editComment = $wgContLang->ucfirst(
2603  wfMessage(
2604  $revCommentMsg,
2605  $this->mTitle->getPrefixedText()
2606  )->inContentLanguage()->text()
2607  );
2608  if ( $reason ) {
2609  $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2610  }
2611  $protectDescription = $this->protectDescription( $limit, $expiry );
2612  if ( $protectDescription ) {
2613  $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2614  $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2615  ->inContentLanguage()->text();
2616  }
2617  if ( $cascade ) {
2618  $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2619  $editComment .= wfMessage( 'brackets' )->params(
2620  wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2621  )->inContentLanguage()->text();
2622  }
2623 
2624  $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2625  if ( $nullRev ) {
2626  $nullRev->insertOn( $dbw );
2627 
2628  // Update page record and touch page
2629  $oldLatest = $nullRev->getParentId();
2630  $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2631  }
2632 
2633  return $nullRev;
2634  }
2635 
2640  protected function formatExpiry( $expiry ) {
2642 
2643  if ( $expiry != 'infinity' ) {
2644  return wfMessage(
2645  'protect-expiring',
2646  $wgContLang->timeanddate( $expiry, false, false ),
2647  $wgContLang->date( $expiry, false, false ),
2648  $wgContLang->time( $expiry, false, false )
2649  )->inContentLanguage()->text();
2650  } else {
2651  return wfMessage( 'protect-expiry-indefinite' )
2652  ->inContentLanguage()->text();
2653  }
2654  }
2655 
2663  public function protectDescription( array $limit, array $expiry ) {
2664  $protectDescription = '';
2665 
2666  foreach ( array_filter( $limit ) as $action => $restrictions ) {
2667  # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2668  # All possible message keys are listed here for easier grepping:
2669  # * restriction-create
2670  # * restriction-edit
2671  # * restriction-move
2672  # * restriction-upload
2673  $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2674  # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2675  # with '' filtered out. All possible message keys are listed below:
2676  # * protect-level-autoconfirmed
2677  # * protect-level-sysop
2678  $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2679  ->inContentLanguage()->text();
2680 
2681  $expiryText = $this->formatExpiry( $expiry[$action] );
2682 
2683  if ( $protectDescription !== '' ) {
2684  $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2685  }
2686  $protectDescription .= wfMessage( 'protect-summary-desc' )
2687  ->params( $actionText, $restrictionsText, $expiryText )
2688  ->inContentLanguage()->text();
2689  }
2690 
2691  return $protectDescription;
2692  }
2693 
2705  public function protectDescriptionLog( array $limit, array $expiry ) {
2707 
2708  $protectDescriptionLog = '';
2709 
2710  foreach ( array_filter( $limit ) as $action => $restrictions ) {
2711  $expiryText = $this->formatExpiry( $expiry[$action] );
2712  $protectDescriptionLog .= $wgContLang->getDirMark() .
2713  "[$action=$restrictions] ($expiryText)";
2714  }
2715 
2716  return trim( $protectDescriptionLog );
2717  }
2718 
2728  protected static function flattenRestrictions( $limit ) {
2729  if ( !is_array( $limit ) ) {
2730  throw new MWException( __METHOD__ . ' given non-array restriction set' );
2731  }
2732 
2733  $bits = [];
2734  ksort( $limit );
2735 
2736  foreach ( array_filter( $limit ) as $action => $restrictions ) {
2737  $bits[] = "$action=$restrictions";
2738  }
2739 
2740  return implode( ':', $bits );
2741  }
2742 
2759  public function doDeleteArticle(
2760  $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2761  ) {
2762  $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2763  return $status->isGood();
2764  }
2765 
2783  public function doDeleteArticleReal(
2784  $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2785  ) {
2786  global $wgUser, $wgContentHandlerUseDB;
2787 
2788  wfDebug( __METHOD__ . "\n" );
2789 
2791 
2792  if ( $this->mTitle->getDBkey() === '' ) {
2793  $status->error( 'cannotdelete',
2794  wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2795  return $status;
2796  }
2797 
2798  $user = is_null( $user ) ? $wgUser : $user;
2799  if ( !Hooks::run( 'ArticleDelete',
2800  [ &$this, &$user, &$reason, &$error, &$status, $suppress ]
2801  ) ) {
2802  if ( $status->isOK() ) {
2803  // Hook aborted but didn't set a fatal status
2804  $status->fatal( 'delete-hook-aborted' );
2805  }
2806  return $status;
2807  }
2808 
2809  $dbw = wfGetDB( DB_MASTER );
2810  $dbw->startAtomic( __METHOD__ );
2811 
2812  $this->loadPageData( self::READ_LATEST );
2813  $id = $this->getId();
2814  // T98706: lock the page from various other updates but avoid using
2815  // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2816  // the revisions queries (which also JOIN on user). Only lock the page
2817  // row and CAS check on page_latest to see if the trx snapshot matches.
2818  $lockedLatest = $this->lockAndGetLatest();
2819  if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2820  $dbw->endAtomic( __METHOD__ );
2821  // Page not there or trx snapshot is stale
2822  $status->error( 'cannotdelete',
2823  wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2824  return $status;
2825  }
2826 
2827  // At this point we are now comitted to returning an OK
2828  // status unless some DB query error or other exception comes up.
2829  // This way callers don't have to call rollback() if $status is bad
2830  // unless they actually try to catch exceptions (which is rare).
2831 
2832  // we need to remember the old content so we can use it to generate all deletion updates.
2833  $content = $this->getContent( Revision::RAW );
2834 
2835  // Bitfields to further suppress the content
2836  if ( $suppress ) {
2837  $bitfield = 0;
2838  // This should be 15...
2839  $bitfield |= Revision::DELETED_TEXT;
2840  $bitfield |= Revision::DELETED_COMMENT;
2841  $bitfield |= Revision::DELETED_USER;
2842  $bitfield |= Revision::DELETED_RESTRICTED;
2843  } else {
2844  $bitfield = 'rev_deleted';
2845  }
2846 
2860  $row = [
2861  'ar_namespace' => 'page_namespace',
2862  'ar_title' => 'page_title',
2863  'ar_comment' => 'rev_comment',
2864  'ar_user' => 'rev_user',
2865  'ar_user_text' => 'rev_user_text',
2866  'ar_timestamp' => 'rev_timestamp',
2867  'ar_minor_edit' => 'rev_minor_edit',
2868  'ar_rev_id' => 'rev_id',
2869  'ar_parent_id' => 'rev_parent_id',
2870  'ar_text_id' => 'rev_text_id',
2871  'ar_text' => '\'\'', // Be explicit to appease
2872  'ar_flags' => '\'\'', // MySQL's "strict mode"...
2873  'ar_len' => 'rev_len',
2874  'ar_page_id' => 'page_id',
2875  'ar_deleted' => $bitfield,
2876  'ar_sha1' => 'rev_sha1',
2877  ];
2878 
2879  if ( $wgContentHandlerUseDB ) {
2880  $row['ar_content_model'] = 'rev_content_model';
2881  $row['ar_content_format'] = 'rev_content_format';
2882  }
2883 
2884  // Copy all the page revisions into the archive table
2885  $dbw->insertSelect(
2886  'archive',
2887  [ 'page', 'revision' ],
2888  $row,
2889  [
2890  'page_id' => $id,
2891  'page_id = rev_page'
2892  ],
2893  __METHOD__
2894  );
2895 
2896  // Now that it's safely backed up, delete it
2897  $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
2898 
2899  if ( !$dbw->cascadingDeletes() ) {
2900  $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__ );
2901  }
2902 
2903  // Clone the title, so we have the information we need when we log
2904  $logTitle = clone $this->mTitle;
2905 
2906  // Log the deletion, if the page was suppressed, put it in the suppression log instead
2907  $logtype = $suppress ? 'suppress' : 'delete';
2908 
2909  $logEntry = new ManualLogEntry( $logtype, 'delete' );
2910  $logEntry->setPerformer( $user );
2911  $logEntry->setTarget( $logTitle );
2912  $logEntry->setComment( $reason );
2913  $logid = $logEntry->insert();
2914 
2915  $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2916  // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2917  $logEntry->publish( $logid );
2918  } );
2919 
2920  $dbw->endAtomic( __METHOD__ );
2921 
2922  $this->doDeleteUpdates( $id, $content );
2923 
2924  Hooks::run( 'ArticleDeleteComplete',
2925  [ &$this, &$user, $reason, $id, $content, $logEntry ] );
2926  $status->value = $logid;
2927 
2928  // Show log excerpt on 404 pages rather than just a link
2930  $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2931  $cache->set( $key, 1, $cache::TTL_DAY );
2932 
2933  return $status;
2934  }
2935 
2942  public function lockAndGetLatest() {
2943  return (int)wfGetDB( DB_MASTER )->selectField(
2944  'page',
2945  'page_latest',
2946  [
2947  'page_id' => $this->getId(),
2948  // Typically page_id is enough, but some code might try to do
2949  // updates assuming the title is the same, so verify that
2950  'page_namespace' => $this->getTitle()->getNamespace(),
2951  'page_title' => $this->getTitle()->getDBkey()
2952  ],
2953  __METHOD__,
2954  [ 'FOR UPDATE' ]
2955  );
2956  }
2957 
2966  public function doDeleteUpdates( $id, Content $content = null ) {
2967  // Update site status
2968  DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2969 
2970  // Delete pagelinks, update secondary indexes, etc
2971  $updates = $this->getDeletionUpdates( $content );
2972  foreach ( $updates as $update ) {
2973  DeferredUpdates::addUpdate( $update );
2974  }
2975 
2976  // Reparse any pages transcluding this page
2977  LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2978 
2979  // Reparse any pages including this image
2980  if ( $this->mTitle->getNamespace() == NS_FILE ) {
2981  LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
2982  }
2983 
2984  // Clear caches
2985  WikiPage::onArticleDelete( $this->mTitle );
2986 
2987  // Reset this object and the Title object
2988  $this->loadFromRow( false, self::READ_LATEST );
2989 
2990  // Search engine
2991  DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2992  }
2993 
3022  public function doRollback(
3023  $fromP, $summary, $token, $bot, &$resultDetails, User $user, $tags = null
3024  ) {
3025  $resultDetails = null;
3026 
3027  // Check permissions
3028  $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
3029  $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
3030  $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3031 
3032  if ( !$user->matchEditToken( $token, [ $this->mTitle->getPrefixedText(), $fromP ] ) ) {
3033  $errors[] = [ 'sessionfailure' ];
3034  }
3035 
3036  if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
3037  $errors[] = [ 'actionthrottledtext' ];
3038  }
3039 
3040  // If there were errors, bail out now
3041  if ( !empty( $errors ) ) {
3042  return $errors;
3043  }
3044 
3045  return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3046  }
3047 
3068  public function commitRollback( $fromP, $summary, $bot,
3069  &$resultDetails, User $guser, $tags = null
3070  ) {
3071  global $wgUseRCPatrol, $wgContLang;
3072 
3073  $dbw = wfGetDB( DB_MASTER );
3074 
3075  if ( wfReadOnly() ) {
3076  return [ [ 'readonlytext' ] ];
3077  }
3078 
3079  // Get the last editor
3080  $current = $this->getRevision();
3081  if ( is_null( $current ) ) {
3082  // Something wrong... no page?
3083  return [ [ 'notanarticle' ] ];
3084  }
3085 
3086  $from = str_replace( '_', ' ', $fromP );
3087  // User name given should match up with the top revision.
3088  // If the user was deleted then $from should be empty.
3089  if ( $from != $current->getUserText() ) {
3090  $resultDetails = [ 'current' => $current ];
3091  return [ [ 'alreadyrolled',
3092  htmlspecialchars( $this->mTitle->getPrefixedText() ),
3093  htmlspecialchars( $fromP ),
3094  htmlspecialchars( $current->getUserText() )
3095  ] ];
3096  }
3097 
3098  // Get the last edit not by this person...
3099  // Note: these may not be public values
3100  $user = intval( $current->getUser( Revision::RAW ) );
3101  $user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
3102  $s = $dbw->selectRow( 'revision',
3103  [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3104  [ 'rev_page' => $current->getPage(),
3105  "rev_user != {$user} OR rev_user_text != {$user_text}"
3106  ], __METHOD__,
3107  [ 'USE INDEX' => 'page_timestamp',
3108  'ORDER BY' => 'rev_timestamp DESC' ]
3109  );
3110  if ( $s === false ) {
3111  // No one else ever edited this page
3112  return [ [ 'cantrollback' ] ];
3113  } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3114  || $s->rev_deleted & Revision::DELETED_USER
3115  ) {
3116  // Only admins can see this text
3117  return [ [ 'notvisiblerev' ] ];
3118  }
3119 
3120  // Generate the edit summary if necessary
3121  $target = Revision::newFromId( $s->rev_id, Revision::READ_LATEST );
3122  if ( empty( $summary ) ) {
3123  if ( $from == '' ) { // no public user name
3124  $summary = wfMessage( 'revertpage-nouser' );
3125  } else {
3126  $summary = wfMessage( 'revertpage' );
3127  }
3128  }
3129 
3130  // Allow the custom summary to use the same args as the default message
3131  $args = [
3132  $target->getUserText(), $from, $s->rev_id,
3133  $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3134  $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3135  ];
3136  if ( $summary instanceof Message ) {
3137  $summary = $summary->params( $args )->inContentLanguage()->text();
3138  } else {
3140  }
3141 
3142  // Trim spaces on user supplied text
3143  $summary = trim( $summary );
3144 
3145  // Truncate for whole multibyte characters.
3146  $summary = $wgContLang->truncate( $summary, 255 );
3147 
3148  // Save
3149  $flags = EDIT_UPDATE;
3150 
3151  if ( $guser->isAllowed( 'minoredit' ) ) {
3152  $flags |= EDIT_MINOR;
3153  }
3154 
3155  if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3157  }
3158 
3159  // Actually store the edit
3160  $status = $this->doEditContent(
3161  $target->getContent(),
3162  $summary,
3163  $flags,
3164  $target->getId(),
3165  $guser,
3166  null,
3167  $tags
3168  );
3169 
3170  // Set patrolling and bot flag on the edits, which gets rollbacked.
3171  // This is done even on edit failure to have patrolling in that case (bug 62157).
3172  $set = [];
3173  if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3174  // Mark all reverted edits as bot
3175  $set['rc_bot'] = 1;
3176  }
3177 
3178  if ( $wgUseRCPatrol ) {
3179  // Mark all reverted edits as patrolled
3180  $set['rc_patrolled'] = 1;
3181  }
3182 
3183  if ( count( $set ) ) {
3184  $dbw->update( 'recentchanges', $set,
3185  [ /* WHERE */
3186  'rc_cur_id' => $current->getPage(),
3187  'rc_user_text' => $current->getUserText(),
3188  'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3189  ],
3190  __METHOD__
3191  );
3192  }
3193 
3194  if ( !$status->isOK() ) {
3195  return $status->getErrorsArray();
3196  }
3197 
3198  // raise error, when the edit is an edit without a new version
3199  $statusRev = isset( $status->value['revision'] )
3200  ? $status->value['revision']
3201  : null;
3202  if ( !( $statusRev instanceof Revision ) ) {
3203  $resultDetails = [ 'current' => $current ];
3204  return [ [ 'alreadyrolled',
3205  htmlspecialchars( $this->mTitle->getPrefixedText() ),
3206  htmlspecialchars( $fromP ),
3207  htmlspecialchars( $current->getUserText() )
3208  ] ];
3209  }
3210 
3211  $revId = $statusRev->getId();
3212 
3213  Hooks::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3214 
3215  $resultDetails = [
3216  'summary' => $summary,
3217  'current' => $current,
3218  'target' => $target,
3219  'newid' => $revId
3220  ];
3221 
3222  return [];
3223  }
3224 
3236  public static function onArticleCreate( Title $title ) {
3237  // Update existence markers on article/talk tabs...
3238  $other = $title->getOtherPage();
3239 
3240  $other->purgeSquid();
3241 
3242  $title->touchLinks();
3243  $title->purgeSquid();
3244  $title->deleteTitleProtection();
3245  }
3246 
3252  public static function onArticleDelete( Title $title ) {
3254 
3255  // Update existence markers on article/talk tabs...
3256  $other = $title->getOtherPage();
3257 
3258  $other->purgeSquid();
3259 
3260  $title->touchLinks();
3261  $title->purgeSquid();
3262 
3263  // File cache
3265  InfoAction::invalidateCache( $title );
3266 
3267  // Messages
3268  if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3269  MessageCache::singleton()->replace( $title->getDBkey(), false );
3270 
3271  if ( $wgContLang->hasVariants() ) {
3272  $wgContLang->updateConversionTable( $title );
3273  }
3274  }
3275 
3276  // Images
3277  if ( $title->getNamespace() == NS_FILE ) {
3278  DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3279  }
3280 
3281  // User talk pages
3282  if ( $title->getNamespace() == NS_USER_TALK ) {
3283  $user = User::newFromName( $title->getText(), false );
3284  if ( $user ) {
3285  $user->setNewtalk( false );
3286  }
3287  }
3288 
3289  // Image redirects
3290  RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3291  }
3292 
3299  public static function onArticleEdit( Title $title, Revision $revision = null ) {
3300  // Invalidate caches of articles which include this page
3301  DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3302 
3303  // Invalidate the caches of all pages which redirect here
3304  DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3305 
3306  // Purge CDN for this page only
3307  $title->purgeSquid();
3308  // Clear file cache for this page only
3310 
3311  $revid = $revision ? $revision->getId() : null;
3312  DeferredUpdates::addCallableUpdate( function() use ( $title, $revid ) {
3313  InfoAction::invalidateCache( $title, $revid );
3314  } );
3315  }
3316 
3325  public function getCategories() {
3326  $id = $this->getId();
3327  if ( $id == 0 ) {
3328  return TitleArray::newFromResult( new FakeResultWrapper( [] ) );
3329  }
3330 
3331  $dbr = wfGetDB( DB_SLAVE );
3332  $res = $dbr->select( 'categorylinks',
3333  [ 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ],
3334  // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3335  // as not being aliases, and NS_CATEGORY is numeric
3336  [ 'cl_from' => $id ],
3337  __METHOD__ );
3338 
3339  return TitleArray::newFromResult( $res );
3340  }
3341 
3348  public function getHiddenCategories() {
3349  $result = [];
3350  $id = $this->getId();
3351 
3352  if ( $id == 0 ) {
3353  return [];
3354  }
3355 
3356  $dbr = wfGetDB( DB_SLAVE );
3357  $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3358  [ 'cl_to' ],
3359  [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3360  'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ],
3361  __METHOD__ );
3362 
3363  if ( $res !== false ) {
3364  foreach ( $res as $row ) {
3365  $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3366  }
3367  }
3368 
3369  return $result;
3370  }
3371 
3381  public static function getAutosummary( $oldtext, $newtext, $flags ) {
3382  // NOTE: stub for backwards-compatibility. assumes the given text is
3383  // wikitext. will break horribly if it isn't.
3384 
3385  ContentHandler::deprecated( __METHOD__, '1.21' );
3386 
3388  $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3389  $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3390 
3391  return $handler->getAutosummary( $oldContent, $newContent, $flags );
3392  }
3393 
3401  public function getAutoDeleteReason( &$hasHistory ) {
3402  return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3403  }
3404 
3412  public function updateCategoryCounts( array $added, array $deleted ) {
3413  $that = $this;
3414  $method = __METHOD__;
3415  $dbw = wfGetDB( DB_MASTER );
3416 
3417  // Do this at the end of the commit to reduce lock wait timeouts
3418  $dbw->onTransactionPreCommitOrIdle(
3419  function () use ( $dbw, $that, $method, $added, $deleted ) {
3420  $ns = $that->getTitle()->getNamespace();
3421 
3422  $addFields = [ 'cat_pages = cat_pages + 1' ];
3423  $removeFields = [ 'cat_pages = cat_pages - 1' ];
3424  if ( $ns == NS_CATEGORY ) {
3425  $addFields[] = 'cat_subcats = cat_subcats + 1';
3426  $removeFields[] = 'cat_subcats = cat_subcats - 1';
3427  } elseif ( $ns == NS_FILE ) {
3428  $addFields[] = 'cat_files = cat_files + 1';
3429  $removeFields[] = 'cat_files = cat_files - 1';
3430  }
3431 
3432  if ( count( $added ) ) {
3433  $existingAdded = $dbw->selectFieldValues(
3434  'category',
3435  'cat_title',
3436  [ 'cat_title' => $added ],
3437  __METHOD__
3438  );
3439 
3440  // For category rows that already exist, do a plain
3441  // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3442  // to avoid creating gaps in the cat_id sequence.
3443  if ( count( $existingAdded ) ) {
3444  $dbw->update(
3445  'category',
3446  $addFields,
3447  [ 'cat_title' => $existingAdded ],
3448  __METHOD__
3449  );
3450  }
3451 
3452  $missingAdded = array_diff( $added, $existingAdded );
3453  if ( count( $missingAdded ) ) {
3454  $insertRows = [];
3455  foreach ( $missingAdded as $cat ) {
3456  $insertRows[] = [
3457  'cat_title' => $cat,
3458  'cat_pages' => 1,
3459  'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3460  'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3461  ];
3462  }
3463  $dbw->upsert(
3464  'category',
3465  $insertRows,
3466  [ 'cat_title' ],
3467  $addFields,
3468  $method
3469  );
3470  }
3471  }
3472 
3473  if ( count( $deleted ) ) {
3474  $dbw->update(
3475  'category',
3476  $removeFields,
3477  [ 'cat_title' => $deleted ],
3478  $method
3479  );
3480  }
3481 
3482  foreach ( $added as $catName ) {
3483  $cat = Category::newFromName( $catName );
3484  Hooks::run( 'CategoryAfterPageAdded', [ $cat, $that ] );
3485  }
3486 
3487  foreach ( $deleted as $catName ) {
3488  $cat = Category::newFromName( $catName );
3489  Hooks::run( 'CategoryAfterPageRemoved', [ $cat, $that ] );
3490  }
3491  }
3492  );
3493  }
3494 
3502  if ( wfReadOnly() ) {
3503  return;
3504  }
3505 
3506  if ( !Hooks::run( 'OpportunisticLinksUpdate',
3507  [ $this, $this->mTitle, $parserOutput ]
3508  ) ) {
3509  return;
3510  }
3511 
3512  $config = RequestContext::getMain()->getConfig();
3513 
3514  $params = [
3515  'isOpportunistic' => true,
3516  'rootJobTimestamp' => $parserOutput->getCacheTime()
3517  ];
3518 
3519  if ( $this->mTitle->areRestrictionsCascading() ) {
3520  // If the page is cascade protecting, the links should really be up-to-date
3521  JobQueueGroup::singleton()->lazyPush(
3522  RefreshLinksJob::newPrioritized( $this->mTitle, $params )
3523  );
3524  } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3525  // Assume the output contains "dynamic" time/random based magic words.
3526  // Only update pages that expired due to dynamic content and NOT due to edits
3527  // to referenced templates/files. When the cache expires due to dynamic content,
3528  // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3529  // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3530  // template/file edit already triggered recursive RefreshLinksJob jobs.
3531  if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3532  // If a page is uncacheable, do not keep spamming a job for it.
3533  // Although it would be de-duplicated, it would still waste I/O.
3535  $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3536  $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3537  if ( $cache->add( $key, time(), $ttl ) ) {
3538  JobQueueGroup::singleton()->lazyPush(
3539  RefreshLinksJob::newDynamic( $this->mTitle, $params )
3540  );
3541  }
3542  }
3543  }
3544  }
3545 
3555  public function getDeletionUpdates( Content $content = null ) {
3556  if ( !$content ) {
3557  // load content object, which may be used to determine the necessary updates.
3558  // XXX: the content may not be needed to determine the updates.
3559  $content = $this->getContent( Revision::RAW );
3560  }
3561 
3562  if ( !$content ) {
3563  $updates = [];
3564  } else {
3565  $updates = $content->getDeletionUpdates( $this );
3566  }
3567 
3568  Hooks::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3569  return $updates;
3570  }
3571 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:568
getLinksTimestamp()
Get the page_links_updated field.
Definition: WikiPage.php:527
isCountable($editInfo=false)
Determine whether a page would be suitable for being counted as an article in the site_stats table ba...
Definition: WikiPage.php:801
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:99
static newFromRow($row)
Make a Title object from a DB row.
Definition: Title.php:465
static purgeExpiredRestrictions()
Purge expired restrictions from the page_restrictions table.
Definition: Title.php:3052
setLastEdit(Revision $revision)
Set the latest revision.
Definition: WikiPage.php:624
makeParserOptions($context)
Get parser options suitable for rendering the primary article wikitext.
Definition: WikiPage.php:1974
static onArticleCreate(Title $title)
The onArticle*() functions are supposed to be a kind of hooks which should be called whenever any of ...
Definition: WikiPage.php:3236
getUndoContent(Revision $undo, Revision $undoafter=null)
Get the content that needs to be saved in order to undo all revisions between $undo and $undoafter...
Definition: WikiPage.php:1343
touchLinks()
Update page_touched timestamps and send CDN purge messages for pages linking to this title...
Definition: Title.php:4436
getFragment()
Get the Title fragment (i.e.
Definition: Title.php:1353
string $mLinksUpdated
Definition: WikiPage.php:81
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
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
Database error base class.
static newFromName($name)
Factory function.
Definition: Category.php:111
the array() calling protocol came about after MediaWiki 1.4rc1.
replaceSectionContent($sectionId, Content $sectionContent, $sectionTitle= '', $edittime=null)
Definition: WikiPage.php:1376
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:277
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
getLatest()
Get the page_latest field.
Definition: WikiPage.php:538
stdClass $mPreparedEdit
Map of cache fields (text, parser output, ect) for a proposed/new edit.
Definition: WikiPage.php:46
$context
Definition: load.php:44
getContentHandler()
Convenience method that returns the ContentHandler singleton for handling the content model that this...
serialize($format=null)
Convenience method for serializing this Content object.
string $mTouched
Definition: WikiPage.php:76
getUser($audience=Revision::FOR_PUBLIC, User $user=null)
Definition: WikiPage.php:714
getParserOutput(ParserOptions $parserOptions, $oldid=null)
Get a ParserOutput for the given ParserOptions and revision ID.
Definition: WikiPage.php:1055
getText()
Get the text form (spaces not underscores) of the main part.
Definition: Title.php:893
clearNotification(&$title, $oldid=0)
Clear the user's notification timestamp for the given title.
Definition: User.php:3519
doEditContent(Content $content, $summary, $flags=0, $baseRevId=false, User $user=null, $serialFormat=null, $tags=null)
Change an existing article or create a new article.
Definition: WikiPage.php:1585
int $mId
Definition: WikiPage.php:51
static checkCache(Title $title, Content $content, User $user)
Check that a prepared edit is in cache and still up-to-date.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
int $mDataLoadedFrom
One of the READ_* constants.
Definition: WikiPage.php:56
getTimestamp()
Definition: Revision.php:1152
See docs/deferred.txt.
Definition: LinksUpdate.php:28
isAllowedAny()
Check if user is allowed to access a feature / make an action.
Definition: User.php:3378
static getForModelID($modelId)
Returns the ContentHandler singleton for the given model ID.
protectDescription(array $limit, array $expiry)
Builds the description to serve as comment for the edit.
Definition: WikiPage.php:2663
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
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 noclasses & $ret
Definition: hooks.txt:1798
Set options of the Parser.
insertRedirect()
Insert an entry for this page into the redirect table if the content is a redirect.
Definition: WikiPage.php:884
pingLimiter($action= 'edit', $incrBy=1)
Primitive rate limits: enforce maximum actions per time period to put a brake on flooding.
Definition: User.php:1776
Title $mTitle
Definition: WikiPage.php:35
updateCategoryCounts(array $added, array $deleted)
Update all the appropriate counts in the category table, given that we've added the categories $added...
Definition: WikiPage.php:3412
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
updateRevisionOn($dbw, $revision, $lastRevision=null, $lastRevIsRedirect=null)
Update the page record to point to a newly saved revision.
Definition: WikiPage.php:1200
clear()
Clear the object.
Definition: WikiPage.php:225
Handles purging appropriate CDN URLs given a title (or titles)
triggerOpportunisticLinksUpdate(ParserOutput $parserOutput)
Opportunistically enqueue link update jobs given fresh parser output if useful.
Definition: WikiPage.php:3501
$comment
static newFromUserAndLang(User $user, Language $lang)
Get a ParserOptions object from a given user and language.
$source
const DBO_TRX
Definition: Defines.php:33
getMinorEdit()
Returns true if last revision was marked as "minor edit".
Definition: WikiPage.php:784
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 $revId
Definition: hooks.txt:1004
getOtherPage()
Get the other title for this page, if this is a subject page get the talk page, if it is a subject pa...
Definition: Title.php:1326
static getLocalClusterInstance()
Get the main cluster-local cache object.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
getContributors()
Get a list of users who have edited this article, not including the user who made the most recent rev...
Definition: WikiPage.php:981
checkFlags($flags)
Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
Definition: WikiPage.php:1458
const EDIT_MINOR
Definition: Defines.php:181
static getMainStashInstance()
Get the cache object for the main stash.
const EDIT_UPDATE
Definition: Defines.php:180
doQuickEditContent(Content $content, User $user, $comment= '', $minor=false, $serialFormat=null)
Edit an article without doing all that other stuff The article must already exist; link tables etc ar...
Definition: WikiPage.php:2304
insertProtectNullRevision($revCommentMsg, array $limit, array $expiry, $cascade, $reason, $user=null)
Insert a new null revision for this page.
Definition: WikiPage.php:2595
Represents a title within MediaWiki.
Definition: Title.php:34
static newFromPageId($pageId, $revId=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given page ID...
Definition: Revision.php:148
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
getTouched()
Get the page_touched field.
Definition: WikiPage.php:516
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
matchEditToken($val, $salt= '', $request=null, $maxage=null)
Check given value against the token value stored in the session.
Definition: User.php:4207
getDeletionUpdates(Content $content=null)
Returns a list of updates to be performed when this page is deleted.
Definition: WikiPage.php:3555
string $mTimestamp
Timestamp of the current revision or empty string if not loaded.
Definition: WikiPage.php:71
magic word & $parser
Definition: hooks.txt:2321
clearCacheFields()
Clear the object cache fields.
Definition: WikiPage.php:236
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition: globals.txt:25
loadLastEdit()
Loads everything except the text This isn't necessary for all uses, so it's only done if needed...
Definition: WikiPage.php:587
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2086
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
Definition: hooks.txt:965
pageDataFromTitle($dbr, $title, $options=[])
Fetch a page record matching the Title object's namespace and title using a sanitized title string...
Definition: WikiPage.php:322
getActionOverrides()
Returns overrides for action handlers.
Definition: WikiPage.php:195
isRedirect()
Tests if the article content represents a redirect.
Definition: WikiPage.php:466
static queueRecursiveJobsForTable(Title $title, $table)
Queue a RefreshLinks job for any table.
wfArrayDiff2($a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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:1796
getTitleKey()
Get the user's name escaped by underscores.
Definition: User.php:2122
static notifyEdit($timestamp, &$title, $minor, &$user, $comment, $oldId, $lastTimestamp, $bot, $ip= '', $oldSize=0, $newSize=0, $newId=0, $patrol=0, $tags=[])
Makes an entry in the database corresponding to an edit.
if($line===false) $args
Definition: cdb.php:64
doEdit($text, $summary, $flags=0, $baseRevId=false, $user=null)
Change an existing article or create a new article.
Definition: WikiPage.php:1522
getContentModel()
Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
Definition: WikiPage.php:484
static addCallableUpdate($callable, $type=self::POSTSEND)
Add a callable update.
checkTouched()
Loads page_touched and returns a value indicating if it should be used.
Definition: WikiPage.php:505
Database independant search index updater.
getSize()
Returns the content's nominal size in "bogo-bytes".
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$mIsRedirect
Definition: WikiPage.php:41
wfMsgReplaceArgs($message, $args)
Replace message parameter keys on the given formatted output.
loadFromRow($data, $from)
Load the object from a database row.
Definition: WikiPage.php:392
static getLocalizedName($name, Language $lang=null)
Returns the localized name for a given content model.
getRevision()
Get the latest revision.
Definition: WikiPage.php:633
getContent($audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition: WikiPage.php:654
Interface for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
Definition: Page.php:24
static invalidateCache(Title $title, $revid=null)
Clear the info cache for a given Title.
Definition: InfoAction.php:67
getCacheExpiry()
Returns the number of seconds after which this object should expire.
Definition: CacheTime.php:107
wfGetLB($wiki=false)
Get a load balancer object.
wfEscapeWikiText($text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
wfReadOnly()
Check whether the wiki is in read-only mode.
deleteTitleProtection()
Remove any title protection due to page existing.
Definition: Title.php:2631
static getMain()
Static methods.
static singleton()
Get an instance of this class.
Definition: LinkCache.php:61
const FOR_PUBLIC
Definition: Revision.php:83
const EDIT_FORCE_BOT
Definition: Defines.php:183
static clearFileCache(Title $title)
Clear the file caches for a page for all actions.
commitRollback($fromP, $summary, $bot, &$resultDetails, User $guser, $tags=null)
Backend implementation of doRollback(), please refer there for parameter and return value documentati...
Definition: WikiPage.php:3068
Revision $mLastRevision
Definition: WikiPage.php:66
static deprecated($func, $version, $component=false)
Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if self::$enableDeprecationWa...
isAllowed($action= '')
Internal mechanics of testing a permission.
Definition: User.php:3408
Class to invalidate the HTML cache of all the pages linking to a given title.
getDBkey()
Get the main part with underscores.
Definition: Title.php:911
wfWarn($msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
getComment($audience=Revision::FOR_PUBLIC, User $user=null)
Definition: WikiPage.php:770
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 $parserOutput
Definition: hooks.txt:1004
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:1004
static runLegacyHooks($event, $args=[], $warn=null)
Call a legacy hook that uses text instead of Content objects.
followRedirect()
Get the Title object or URL this page redirects to.
Definition: WikiPage.php:932
const NS_MEDIA
Definition: Defines.php:57
$res
Definition: database.txt:21
static loadFromTimestamp($db, $title, $timestamp)
Load the revision for the given title with the given timestamp.
Definition: Revision.php:290
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
static getContentText(Content $content=null)
Convenience function for getting flat text from a Content object.
getContentHandler()
Returns the content handler appropriate for this revision's content model.
Definition: Revision.php:1133
$summary
doDeleteArticle($reason, $suppress=false, $u1=null, $u2=null, &$error= '', User $user=null)
Same as doDeleteArticleReal(), but returns a simple boolean.
Definition: WikiPage.php:2759
static newNullRevision($dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page's history.
Definition: Revision.php:1624
static newFromRow($row, $from= 'fromdb')
Constructor from a database row.
Definition: WikiPage.php:159
doRollback($fromP, $summary, $token, $bot, &$resultDetails, User $user, $tags=null)
Roll back the most recent consecutive set of edits to a page from the same user; fails if there are n...
Definition: WikiPage.php:3022
Class for handling updates to the site_stats table.
incEditCount()
Deferred version of incEditCountImmediate()
Definition: User.php:4862
doCreate(Content $content, $flags, User $user, $summary, array $meta)
Definition: WikiPage.php:1848
const EDIT_AUTOSUMMARY
Definition: Defines.php:185
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
doModify(Content $content, $flags, User $user, $summary, array $meta)
Definition: WikiPage.php:1681
Base interface for content objects.
Definition: Content.php:34
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 noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
getCacheTime()
Definition: CacheTime.php:50
getOldestRevision()
Get the Revision object of the oldest revision.
Definition: WikiPage.php:549
$cache
Definition: mcc.php:33
$params
getHiddenCategories()
Returns a list of hidden categories this page is a member of.
Definition: WikiPage.php:3348
doViewUpdates(User $user, $oldid=0)
Do standard deferred updates after page view (existing or missing page)
Definition: WikiPage.php:1086
getTitle()
Get the title object of the article.
Definition: WikiPage.php:217
const NS_CATEGORY
Definition: Defines.php:83
const EDIT_SUPPRESS_RC
Definition: Defines.php:182
static selectFields()
Return the list of revision fields that should be selected to create a new revision.
Definition: Revision.php:429
static isIP($name)
Does the string match an anonymous IPv4 address?
Definition: User.php:830
wfIncrStats($key, $count=1)
Increment a statistics counter.
const DELETED_RESTRICTED
Definition: Revision.php:79
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty & $sectionContent
Definition: hooks.txt:2338
const DB_SLAVE
Definition: Defines.php:46
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
hasViewableContent()
Check if this page is something we're going to be showing some sort of sensible content for...
Definition: WikiPage.php:457
static addUpdate(DeferrableUpdate $update, $type=self::POSTSEND)
Add an update to the deferred list.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:934
static getDBOptions($bitfield)
Get an appropriate DB index and options for a query.
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
equals(Title $title)
Compare with another title.
Definition: Title.php:4240
const NS_FILE
Definition: Defines.php:75
static newFromResult($res)
Definition: TitleArray.php:38
static makeContent($text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
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:1584
getInterwiki()
Get the interwiki prefix.
Definition: Title.php:821
const RAW
Definition: Revision.php:85
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Special handling for file pages.
getRedirectURL($rt)
Get the Title object or URL to use for a redirect.
Definition: WikiPage.php:943
const NS_MEDIAWIKI
Definition: Defines.php:77
getContentHandler()
Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
Definition: WikiPage.php:209
doPurge()
Perform the actions of a page purging.
Definition: WikiPage.php:1105
equals(Content $that=null)
Returns true if this Content objects is conceptually equivalent to the given Content object...
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:242
getAutoDeleteReason(&$hasHistory)
Auto-generates a deletion reason.
Definition: WikiPage.php:3401
static onArticleEdit(Title $title, Revision $revision=null)
Purge caches on page update etc.
Definition: WikiPage.php:3299
doDeleteUpdates($id, Content $content=null)
Do some database updates after deletion.
Definition: WikiPage.php:2966
const DELETED_TEXT
Definition: Revision.php:76
static singleton($wiki=false)
static singleton()
Get an instance of this object.
Definition: ParserCache.php:36
prepareSave(WikiPage $page, $flags, $parentRevId, User $user)
Prepare Content for saving.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
getUserText($audience=Revision::FOR_PUBLIC, User $user=null)
Definition: WikiPage.php:752
Class representing a MediaWiki article and history.
Definition: WikiPage.php:29
static newFromId($id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:99
replaceSectionAtRev($sectionId, Content $sectionContent, $sectionTitle= '', $baseRevId=null)
Definition: WikiPage.php:1415
prepareContentForEdit(Content $content, $revision=null, User $user=null, $serialFormat=null, $useCache=true)
Prepare content which is about to be saved.
Definition: WikiPage.php:2017
$from
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static newDynamic(Title $title, array $params)
wfRandom()
Get a random decimal value between 0 and 1, in a way not likely to give duplicate values for any real...
Job to add recent change entries mentioning category membership changes.
const DELETED_USER
Definition: Revision.php:78
Class for creating log entries manually, to inject them into the database.
Definition: LogEntry.php:394
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
getCategories()
#@-
Definition: WikiPage.php:3325
hasDynamicContent()
Check whether the cache TTL was lowered due to dynamic content.
doEditUpdates(Revision $revision, User $user, array $options=[])
Do standard deferred updates after page edit.
Definition: WikiPage.php:2149
getId()
Get the user's ID.
Definition: User.php:2061
insertOn($dbw)
Insert a new revision into the database, returning the new revision ID number on success and dies hor...
Definition: Revision.php:1354
Overloads the relevant methods of the real ResultsWrapper so it doesn't go anywhere near an actual da...
const EDIT_NEW
Definition: Defines.php:179
getTimestamp()
Definition: WikiPage.php:687
insertOn($dbw, $pageId=null)
Insert a new empty page record for this article.
Definition: WikiPage.php:1156
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 $content
Definition: hooks.txt:1004
static onArticleDelete(Title $title)
Clears caches when article is deleted.
Definition: WikiPage.php:3252
static convertSelectType($type)
Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
Definition: WikiPage.php:171
supportsSections()
Returns true if this page's content model supports sections.
Definition: WikiPage.php:1358
static newPrioritized(Title $title, array $params)
preSaveTransform(Title $title, User $user, ParserOptions $parserOptions)
Returns a Content object with pre-save transformations applied (or this object if no transformations ...
getContent($audience=self::FOR_PUBLIC, User $user=null)
Fetch revision content if it's available to the specified audience.
Definition: Revision.php:1029
updateRedirectOn($dbw, $redirectTitle, $lastRevIsRedirect=null)
Add row to the redirect table if this is a redirect, remove otherwise.
Definition: WikiPage.php:1271
$mDataLoaded
Definition: WikiPage.php:40
static newFromRow($row)
Definition: Revision.php:219
shouldCheckParserCache(ParserOptions $parserOptions, $oldId)
Should the parser cache be used?
Definition: WikiPage.php:1035
getRedirectTarget()
If this page is a redirect, get its target.
Definition: WikiPage.php:845
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 $limit
Definition: hooks.txt:1004
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
Interface for database access objects.
updateIfNewerOn($dbw, $revision)
If the given revision is newer than the currently set page_latest, update the page record...
Definition: WikiPage.php:1306
static newFromID($id, $from= 'fromdb')
Constructor from a page id.
Definition: WikiPage.php:132
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 $status
Definition: hooks.txt:1004
loadPageData($from= 'fromdb')
Load the object from a given source by title.
Definition: WikiPage.php:352
insertRedirectEntry(Title $rt, $oldLatest=null)
Insert or update the redirect table entry for this page to indicate it redirects to $rt...
Definition: WikiPage.php:906
wfMemcKey()
Make a cache key for the local wiki.
const DB_MASTER
Definition: Defines.php:47
setTimestamp($ts)
Set the page timestamp (use only to avoid DB queries)
Definition: WikiPage.php:701
doDeleteArticleReal($reason, $suppress=false, $u1=null, $u2=null, &$error= '', User $user=null)
Back-end article deletion Deletes the article with database consistency, writes logs, purges caches.
Definition: WikiPage.php:2783
lockAndGetLatest()
Lock the page row for this title+id and return page_latest (or 0)
Definition: WikiPage.php:2942
const DELETED_COMMENT
Definition: Revision.php:77
foreach($res as $row) $serialized
static notifyNew($timestamp, &$title, $minor, &$user, $comment, $bot, $ip= '', $size=0, $newId=0, $patrol=0, $tags=[])
Makes an entry in the database corresponding to page creation Note: the title object must be loaded w...
pageData($dbr, $conditions, $options=[])
Fetch a page record with the given conditions.
Definition: WikiPage.php:301
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 modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:762
getModel()
Returns the ID of the content model used by this Content object.
static logException($e)
Log an exception to the exception log (if enabled).
prepareTextForEdit($text, $revid=null, User $user=null)
Prepare text which is about to be saved.
Definition: WikiPage.php:1996
wfTimestampOrNull($outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
static selectFields()
Return the list of revision fields that should be selected to create a new page.
Definition: WikiPage.php:266
static getAutosummary($oldtext, $newtext, $flags)
Return an applicable autosummary if one exists for the given edit.
Definition: WikiPage.php:3381
clearPreparedEdit()
Clear the mPreparedEdit cache field, as may be needed by mutable content types.
Definition: WikiPage.php:256
const NS_USER_TALK
Definition: Defines.php:72
formatExpiry($expiry)
Definition: WikiPage.php:2640
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 incomplete not yet checked for validity & $retval
Definition: hooks.txt:242
Title $mRedirectTarget
Definition: WikiPage.php:61
__construct(Title $title)
Constructor and clear the article.
Definition: WikiPage.php:87
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2338
getText($audience=Revision::FOR_PUBLIC, User $user=null)
Get the text of the current revision.
Definition: WikiPage.php:674
pageDataFromId($dbr, $id, $options=[])
Fetch a page record matching the requested ID.
Definition: WikiPage.php:336
Special handling for category pages.
static & makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:524
static singleton()
Get the signleton instance of this class.
purgeSquid()
Purge all applicable CDN URLs.
Definition: Title.php:3607
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101
doUpdateRestrictions(array $limit, array $expiry, &$cascade, $reason, User $user, $tags=null)
Update the article's restriction field, and leave a log entry.
Definition: WikiPage.php:2342
static flattenRestrictions($limit)
Take an array of page restrictions and flatten it to a string suitable for insertion into the page_re...
Definition: WikiPage.php:2728
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2338
$wgUser
Definition: Setup.php:794
getCreator($audience=Revision::FOR_PUBLIC, User $user=null)
Get the User object of the user who created the page.
Definition: WikiPage.php:733
protectDescriptionLog(array $limit, array $expiry)
Builds the description to serve as comment for the log entry.
Definition: WikiPage.php:2705