MediaWiki  master
WikiPage.php
Go to the documentation of this file.
1 <?php
24 
31 class WikiPage implements Page, IDBAccessObject {
32  // Constants for $mDataLoadedFrom and related
33 
37  public $mTitle = null;
38 
42  public $mDataLoaded = false; // !< Boolean
43  public $mIsRedirect = false; // !< Boolean
44  public $mLatest = false; // !< Integer (false means "not loaded")
48  public $mPreparedEdit = false;
49 
53  protected $mId = null;
54 
58  protected $mDataLoadedFrom = self::READ_NONE;
59 
63  protected $mRedirectTarget = null;
64 
68  protected $mLastRevision = null;
69 
73  protected $mTimestamp = '';
74 
78  protected $mTouched = '19700101000000';
79 
83  protected $mLinksUpdated = '19700101000000';
84 
89  public function __construct( Title $title ) {
90  $this->mTitle = $title;
91  }
92 
101  public static function factory( Title $title ) {
102  $ns = $title->getNamespace();
103 
104  if ( $ns == NS_MEDIA ) {
105  throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
106  } elseif ( $ns < 0 ) {
107  throw new MWException( "Invalid or virtual namespace $ns given." );
108  }
109 
110  switch ( $ns ) {
111  case NS_FILE:
112  $page = new WikiFilePage( $title );
113  break;
114  case NS_CATEGORY:
115  $page = new WikiCategoryPage( $title );
116  break;
117  default:
118  $page = new WikiPage( $title );
119  }
120 
121  return $page;
122  }
123 
134  public static function newFromID( $id, $from = 'fromdb' ) {
135  // page id's are never 0 or negative, see bug 61166
136  if ( $id < 1 ) {
137  return null;
138  }
139 
140  $from = self::convertSelectType( $from );
141  $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
142  $row = $db->selectRow(
143  'page', self::selectFields(), [ 'page_id' => $id ], __METHOD__ );
144  if ( !$row ) {
145  return null;
146  }
147  return self::newFromRow( $row, $from );
148  }
149 
161  public static function newFromRow( $row, $from = 'fromdb' ) {
162  $page = self::factory( Title::newFromRow( $row ) );
163  $page->loadFromRow( $row, $from );
164  return $page;
165  }
166 
173  private static function convertSelectType( $type ) {
174  switch ( $type ) {
175  case 'fromdb':
176  return self::READ_NORMAL;
177  case 'fromdbmaster':
178  return self::READ_LATEST;
179  case 'forupdate':
180  return self::READ_LOCKING;
181  default:
182  // It may already be an integer or whatever else
183  return $type;
184  }
185  }
186 
192  public function getActionOverrides() {
193  return $this->getContentHandler()->getActionOverrides();
194  }
195 
205  public function getContentHandler() {
206  return ContentHandler::getForModelID( $this->getContentModel() );
207  }
208 
213  public function getTitle() {
214  return $this->mTitle;
215  }
216 
221  public function clear() {
222  $this->mDataLoaded = false;
223  $this->mDataLoadedFrom = self::READ_NONE;
224 
225  $this->clearCacheFields();
226  }
227 
232  protected function clearCacheFields() {
233  $this->mId = null;
234  $this->mRedirectTarget = null; // Title object if set
235  $this->mLastRevision = null; // Latest revision
236  $this->mTouched = '19700101000000';
237  $this->mLinksUpdated = '19700101000000';
238  $this->mTimestamp = '';
239  $this->mIsRedirect = false;
240  $this->mLatest = false;
241  // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
242  // the requested rev ID and content against the cached one for equality. For most
243  // content types, the output should not change during the lifetime of this cache.
244  // Clearing it can cause extra parses on edit for no reason.
245  }
246 
252  public function clearPreparedEdit() {
253  $this->mPreparedEdit = false;
254  }
255 
262  public static function selectFields() {
264 
265  $fields = [
266  'page_id',
267  'page_namespace',
268  'page_title',
269  'page_restrictions',
270  'page_is_redirect',
271  'page_is_new',
272  'page_random',
273  'page_touched',
274  'page_links_updated',
275  'page_latest',
276  'page_len',
277  ];
278 
279  if ( $wgContentHandlerUseDB ) {
280  $fields[] = 'page_content_model';
281  }
282 
283  if ( $wgPageLanguageUseDB ) {
284  $fields[] = 'page_lang';
285  }
286 
287  return $fields;
288  }
289 
297  protected function pageData( $dbr, $conditions, $options = [] ) {
298  $fields = self::selectFields();
299 
300  Hooks::run( 'ArticlePageDataBefore', [ &$this, &$fields ] );
301 
302  $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
303 
304  Hooks::run( 'ArticlePageDataAfter', [ &$this, &$row ] );
305 
306  return $row;
307  }
308 
318  public function pageDataFromTitle( $dbr, $title, $options = [] ) {
319  return $this->pageData( $dbr, [
320  'page_namespace' => $title->getNamespace(),
321  'page_title' => $title->getDBkey() ], $options );
322  }
323 
332  public function pageDataFromId( $dbr, $id, $options = [] ) {
333  return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
334  }
335 
348  public function loadPageData( $from = 'fromdb' ) {
349  $from = self::convertSelectType( $from );
350  if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
351  // We already have the data from the correct location, no need to load it twice.
352  return;
353  }
354 
355  if ( is_int( $from ) ) {
356  list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
357  $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
358 
359  if ( !$data
360  && $index == DB_SLAVE
361  && wfGetLB()->getServerCount() > 1
362  && wfGetLB()->hasOrMadeRecentMasterChanges()
363  ) {
364  $from = self::READ_LATEST;
365  list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
366  $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
367  }
368  } else {
369  // No idea from where the caller got this data, assume slave database.
370  $data = $from;
371  $from = self::READ_NORMAL;
372  }
373 
374  $this->loadFromRow( $data, $from );
375  }
376 
388  public function loadFromRow( $data, $from ) {
389  $lc = LinkCache::singleton();
390  $lc->clearLink( $this->mTitle );
391 
392  if ( $data ) {
393  $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
394 
395  $this->mTitle->loadFromRow( $data );
396 
397  // Old-fashioned restrictions
398  $this->mTitle->loadRestrictions( $data->page_restrictions );
399 
400  $this->mId = intval( $data->page_id );
401  $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
402  $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
403  $this->mIsRedirect = intval( $data->page_is_redirect );
404  $this->mLatest = intval( $data->page_latest );
405  // Bug 37225: $latest may no longer match the cached latest Revision object.
406  // Double-check the ID of any cached latest Revision object for consistency.
407  if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
408  $this->mLastRevision = null;
409  $this->mTimestamp = '';
410  }
411  } else {
412  $lc->addBadLinkObj( $this->mTitle );
413 
414  $this->mTitle->loadFromRow( false );
415 
416  $this->clearCacheFields();
417 
418  $this->mId = 0;
419  }
420 
421  $this->mDataLoaded = true;
422  $this->mDataLoadedFrom = self::convertSelectType( $from );
423  }
424 
428  public function getId() {
429  if ( !$this->mDataLoaded ) {
430  $this->loadPageData();
431  }
432  return $this->mId;
433  }
434 
438  public function exists() {
439  if ( !$this->mDataLoaded ) {
440  $this->loadPageData();
441  }
442  return $this->mId > 0;
443  }
444 
453  public function hasViewableContent() {
454  return $this->exists() || $this->mTitle->isAlwaysKnown();
455  }
456 
462  public function isRedirect() {
463  if ( !$this->mDataLoaded ) {
464  $this->loadPageData();
465  }
466 
467  return (bool)$this->mIsRedirect;
468  }
469 
480  public function getContentModel() {
481  if ( $this->exists() ) {
482  // look at the revision's actual content model
483  $rev = $this->getRevision();
484 
485  if ( $rev !== null ) {
486  return $rev->getContentModel();
487  } else {
488  $title = $this->mTitle->getPrefixedDBkey();
489  wfWarn( "Page $title exists but has no (visible) revisions!" );
490  }
491  }
492 
493  // use the default model for this page
494  return $this->mTitle->getContentModel();
495  }
496 
501  public function checkTouched() {
502  if ( !$this->mDataLoaded ) {
503  $this->loadPageData();
504  }
505  return !$this->mIsRedirect;
506  }
507 
512  public function getTouched() {
513  if ( !$this->mDataLoaded ) {
514  $this->loadPageData();
515  }
516  return $this->mTouched;
517  }
518 
523  public function getLinksTimestamp() {
524  if ( !$this->mDataLoaded ) {
525  $this->loadPageData();
526  }
527  return $this->mLinksUpdated;
528  }
529 
534  public function getLatest() {
535  if ( !$this->mDataLoaded ) {
536  $this->loadPageData();
537  }
538  return (int)$this->mLatest;
539  }
540 
545  public function getOldestRevision() {
546 
547  // Try using the slave database first, then try the master
548  $continue = 2;
549  $db = wfGetDB( DB_SLAVE );
550  $revSelectFields = Revision::selectFields();
551 
552  $row = null;
553  while ( $continue ) {
554  $row = $db->selectRow(
555  [ 'page', 'revision' ],
556  $revSelectFields,
557  [
558  'page_namespace' => $this->mTitle->getNamespace(),
559  'page_title' => $this->mTitle->getDBkey(),
560  'rev_page = page_id'
561  ],
562  __METHOD__,
563  [
564  'ORDER BY' => 'rev_timestamp ASC'
565  ]
566  );
567 
568  if ( $row ) {
569  $continue = 0;
570  } else {
571  $db = wfGetDB( DB_MASTER );
572  $continue--;
573  }
574  }
575 
576  return $row ? Revision::newFromRow( $row ) : null;
577  }
578 
583  protected function loadLastEdit() {
584  if ( $this->mLastRevision !== null ) {
585  return; // already loaded
586  }
587 
588  $latest = $this->getLatest();
589  if ( !$latest ) {
590  return; // page doesn't exist or is missing page_latest info
591  }
592 
593  if ( $this->mDataLoadedFrom == self::READ_LOCKING ) {
594  // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
595  // includes the latest changes committed. This is true even within REPEATABLE-READ
596  // transactions, where S1 normally only sees changes committed before the first S1
597  // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
598  // may not find it since a page row UPDATE and revision row INSERT by S2 may have
599  // happened after the first S1 SELECT.
600  // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
602  } elseif ( $this->mDataLoadedFrom == self::READ_LATEST ) {
603  // Bug T93976: if page_latest was loaded from the master, fetch the
604  // revision from there as well, as it may not exist yet on a slave DB.
605  // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
607  } else {
608  $flags = 0;
609  }
610  $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
611  if ( $revision ) { // sanity
612  $this->setLastEdit( $revision );
613  }
614  }
615 
620  protected function setLastEdit( Revision $revision ) {
621  $this->mLastRevision = $revision;
622  $this->mTimestamp = $revision->getTimestamp();
623  }
624 
629  public function getRevision() {
630  $this->loadLastEdit();
631  if ( $this->mLastRevision ) {
632  return $this->mLastRevision;
633  }
634  return null;
635  }
636 
650  public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
651  $this->loadLastEdit();
652  if ( $this->mLastRevision ) {
653  return $this->mLastRevision->getContent( $audience, $user );
654  }
655  return null;
656  }
657 
670  public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
671  ContentHandler::deprecated( __METHOD__, '1.21' );
672 
673  $this->loadLastEdit();
674  if ( $this->mLastRevision ) {
675  return $this->mLastRevision->getText( $audience, $user );
676  }
677  return false;
678  }
679 
683  public function getTimestamp() {
684  // Check if the field has been filled by WikiPage::setTimestamp()
685  if ( !$this->mTimestamp ) {
686  $this->loadLastEdit();
687  }
688 
689  return wfTimestamp( TS_MW, $this->mTimestamp );
690  }
691 
697  public function setTimestamp( $ts ) {
698  $this->mTimestamp = wfTimestamp( TS_MW, $ts );
699  }
700 
710  public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
711  $this->loadLastEdit();
712  if ( $this->mLastRevision ) {
713  return $this->mLastRevision->getUser( $audience, $user );
714  } else {
715  return -1;
716  }
717  }
718 
729  public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
730  $revision = $this->getOldestRevision();
731  if ( $revision ) {
732  $userName = $revision->getUserText( $audience, $user );
733  return User::newFromName( $userName, false );
734  } else {
735  return null;
736  }
737  }
738 
748  public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
749  $this->loadLastEdit();
750  if ( $this->mLastRevision ) {
751  return $this->mLastRevision->getUserText( $audience, $user );
752  } else {
753  return '';
754  }
755  }
756 
766  public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
767  $this->loadLastEdit();
768  if ( $this->mLastRevision ) {
769  return $this->mLastRevision->getComment( $audience, $user );
770  } else {
771  return '';
772  }
773  }
774 
780  public function getMinorEdit() {
781  $this->loadLastEdit();
782  if ( $this->mLastRevision ) {
783  return $this->mLastRevision->isMinor();
784  } else {
785  return false;
786  }
787  }
788 
797  public function isCountable( $editInfo = false ) {
799 
800  if ( !$this->mTitle->isContentPage() ) {
801  return false;
802  }
803 
804  if ( $editInfo ) {
805  $content = $editInfo->pstContent;
806  } else {
807  $content = $this->getContent();
808  }
809 
810  if ( !$content || $content->isRedirect() ) {
811  return false;
812  }
813 
814  $hasLinks = null;
815 
816  if ( $wgArticleCountMethod === 'link' ) {
817  // nasty special case to avoid re-parsing to detect links
818 
819  if ( $editInfo ) {
820  // ParserOutput::getLinks() is a 2D array of page links, so
821  // to be really correct we would need to recurse in the array
822  // but the main array should only have items in it if there are
823  // links.
824  $hasLinks = (bool)count( $editInfo->output->getLinks() );
825  } else {
826  $hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
827  [ 'pl_from' => $this->getId() ], __METHOD__ );
828  }
829  }
830 
831  return $content->isCountable( $hasLinks );
832  }
833 
841  public function getRedirectTarget() {
842  if ( !$this->mTitle->isRedirect() ) {
843  return null;
844  }
845 
846  if ( $this->mRedirectTarget !== null ) {
847  return $this->mRedirectTarget;
848  }
849 
850  // Query the redirect table
851  $dbr = wfGetDB( DB_SLAVE );
852  $row = $dbr->selectRow( 'redirect',
853  [ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
854  [ 'rd_from' => $this->getId() ],
855  __METHOD__
856  );
857 
858  // rd_fragment and rd_interwiki were added later, populate them if empty
859  if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
860  $this->mRedirectTarget = Title::makeTitle(
861  $row->rd_namespace, $row->rd_title,
862  $row->rd_fragment, $row->rd_interwiki
863  );
864  return $this->mRedirectTarget;
865  }
866 
867  // This page doesn't have an entry in the redirect table
868  $this->mRedirectTarget = $this->insertRedirect();
869  return $this->mRedirectTarget;
870  }
871 
880  public function insertRedirect() {
881  $content = $this->getContent();
882  $retval = $content ? $content->getUltimateRedirectTarget() : null;
883  if ( !$retval ) {
884  return null;
885  }
886 
887  // Update the DB post-send if the page has not cached since now
888  $that = $this;
889  $latest = $this->getLatest();
890  DeferredUpdates::addCallableUpdate( function() use ( $that, $retval, $latest ) {
891  $that->insertRedirectEntry( $retval, $latest );
892  } );
893 
894  return $retval;
895  }
896 
902  public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
903  $dbw = wfGetDB( DB_MASTER );
904  $dbw->startAtomic( __METHOD__ );
905 
906  if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
907  $dbw->replace( 'redirect',
908  [ 'rd_from' ],
909  [
910  'rd_from' => $this->getId(),
911  'rd_namespace' => $rt->getNamespace(),
912  'rd_title' => $rt->getDBkey(),
913  'rd_fragment' => $rt->getFragment(),
914  'rd_interwiki' => $rt->getInterwiki(),
915  ],
916  __METHOD__
917  );
918  }
919 
920  $dbw->endAtomic( __METHOD__ );
921  }
922 
928  public function followRedirect() {
929  return $this->getRedirectURL( $this->getRedirectTarget() );
930  }
931 
939  public function getRedirectURL( $rt ) {
940  if ( !$rt ) {
941  return false;
942  }
943 
944  if ( $rt->isExternal() ) {
945  if ( $rt->isLocal() ) {
946  // Offsite wikis need an HTTP redirect.
947  // This can be hard to reverse and may produce loops,
948  // so they may be disabled in the site configuration.
949  $source = $this->mTitle->getFullURL( 'redirect=no' );
950  return $rt->getFullURL( [ 'rdfrom' => $source ] );
951  } else {
952  // External pages without "local" bit set are not valid
953  // redirect targets
954  return false;
955  }
956  }
957 
958  if ( $rt->isSpecialPage() ) {
959  // Gotta handle redirects to special pages differently:
960  // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
961  // Some pages are not valid targets.
962  if ( $rt->isValidRedirectTarget() ) {
963  return $rt->getFullURL();
964  } else {
965  return false;
966  }
967  }
968 
969  return $rt;
970  }
971 
977  public function getContributors() {
978  // @todo FIXME: This is expensive; cache this info somewhere.
979 
980  $dbr = wfGetDB( DB_SLAVE );
981 
982  if ( $dbr->implicitGroupby() ) {
983  $realNameField = 'user_real_name';
984  } else {
985  $realNameField = 'MIN(user_real_name) AS user_real_name';
986  }
987 
988  $tables = [ 'revision', 'user' ];
989 
990  $fields = [
991  'user_id' => 'rev_user',
992  'user_name' => 'rev_user_text',
993  $realNameField,
994  'timestamp' => 'MAX(rev_timestamp)',
995  ];
996 
997  $conds = [ 'rev_page' => $this->getId() ];
998 
999  // The user who made the top revision gets credited as "this page was last edited by
1000  // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1001  $user = $this->getUser();
1002  if ( $user ) {
1003  $conds[] = "rev_user != $user";
1004  } else {
1005  $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1006  }
1007 
1008  // Username hidden?
1009  $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1010 
1011  $jconds = [
1012  'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1013  ];
1014 
1015  $options = [
1016  'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1017  'ORDER BY' => 'timestamp DESC',
1018  ];
1019 
1020  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1021  return new UserArrayFromResult( $res );
1022  }
1023 
1031  public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1032  return $parserOptions->getStubThreshold() == 0
1033  && $this->exists()
1034  && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1035  && $this->getContentHandler()->isParserCacheSupported();
1036  }
1037 
1051  public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1052 
1053  $useParserCache = $this->shouldCheckParserCache( $parserOptions, $oldid );
1054  wfDebug( __METHOD__ .
1055  ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1056  if ( $parserOptions->getStubThreshold() ) {
1057  wfIncrStats( 'pcache.miss.stub' );
1058  }
1059 
1060  if ( $useParserCache ) {
1061  $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1062  if ( $parserOutput !== false ) {
1063  return $parserOutput;
1064  }
1065  }
1066 
1067  if ( $oldid === null || $oldid === 0 ) {
1068  $oldid = $this->getLatest();
1069  }
1070 
1071  $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1072  $pool->execute();
1073 
1074  return $pool->getParserOutput();
1075  }
1076 
1082  public function doViewUpdates( User $user, $oldid = 0 ) {
1083  if ( wfReadOnly() ) {
1084  return;
1085  }
1086 
1087  Hooks::run( 'PageViewUpdates', [ $this, $user ] );
1088  // Update newtalk / watchlist notification status
1089  try {
1090  $user->clearNotification( $this->mTitle, $oldid );
1091  } catch ( DBError $e ) {
1092  // Avoid outage if the master is not reachable
1094  }
1095  }
1096 
1101  public function doPurge() {
1102  if ( !Hooks::run( 'ArticlePurge', [ &$this ] ) ) {
1103  return false;
1104  }
1105 
1106  $this->mTitle->invalidateCache();
1107  // Send purge after above page_touched update was committed
1109  new CdnCacheUpdate( $this->mTitle->getCdnUrls() ),
1111  );
1112 
1113  if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1114  // @todo move this logic to MessageCache
1115  if ( $this->exists() ) {
1116  // NOTE: use transclusion text for messages.
1117  // This is consistent with MessageCache::getMsgFromNamespace()
1118 
1119  $content = $this->getContent();
1120  $text = $content === null ? null : $content->getWikitextForTransclusion();
1121 
1122  if ( $text === null ) {
1123  $text = false;
1124  }
1125  } else {
1126  $text = false;
1127  }
1128 
1129  MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1130  }
1131 
1132  return true;
1133  }
1134 
1147  public function insertOn( $dbw, $pageId = null ) {
1148  $pageIdForInsert = $pageId ?: $dbw->nextSequenceValue( 'page_page_id_seq' );
1149  $dbw->insert(
1150  'page',
1151  [
1152  'page_id' => $pageIdForInsert,
1153  'page_namespace' => $this->mTitle->getNamespace(),
1154  'page_title' => $this->mTitle->getDBkey(),
1155  'page_restrictions' => '',
1156  'page_is_redirect' => 0, // Will set this shortly...
1157  'page_is_new' => 1,
1158  'page_random' => wfRandom(),
1159  'page_touched' => $dbw->timestamp(),
1160  'page_latest' => 0, // Fill this in shortly...
1161  'page_len' => 0, // Fill this in shortly...
1162  ],
1163  __METHOD__,
1164  'IGNORE'
1165  );
1166 
1167  if ( $dbw->affectedRows() > 0 ) {
1168  $newid = $pageId ?: $dbw->insertId();
1169  $this->mId = $newid;
1170  $this->mTitle->resetArticleID( $newid );
1171 
1172  return $newid;
1173  } else {
1174  return false; // nothing changed
1175  }
1176  }
1177 
1191  public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1192  $lastRevIsRedirect = null
1193  ) {
1195 
1196  // Assertion to try to catch T92046
1197  if ( (int)$revision->getId() === 0 ) {
1198  throw new InvalidArgumentException(
1199  __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1200  );
1201  }
1202 
1203  $content = $revision->getContent();
1204  $len = $content ? $content->getSize() : 0;
1205  $rt = $content ? $content->getUltimateRedirectTarget() : null;
1206 
1207  $conditions = [ 'page_id' => $this->getId() ];
1208 
1209  if ( !is_null( $lastRevision ) ) {
1210  // An extra check against threads stepping on each other
1211  $conditions['page_latest'] = $lastRevision;
1212  }
1213 
1214  $row = [ /* SET */
1215  'page_latest' => $revision->getId(),
1216  'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1217  'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1218  'page_is_redirect' => $rt !== null ? 1 : 0,
1219  'page_len' => $len,
1220  ];
1221 
1222  if ( $wgContentHandlerUseDB ) {
1223  $row['page_content_model'] = $revision->getContentModel();
1224  }
1225 
1226  $dbw->update( 'page',
1227  $row,
1228  $conditions,
1229  __METHOD__ );
1230 
1231  $result = $dbw->affectedRows() > 0;
1232  if ( $result ) {
1233  $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1234  $this->setLastEdit( $revision );
1235  $this->mLatest = $revision->getId();
1236  $this->mIsRedirect = (bool)$rt;
1237  // Update the LinkCache.
1238  LinkCache::singleton()->addGoodLinkObj(
1239  $this->getId(),
1240  $this->mTitle,
1241  $len,
1242  $this->mIsRedirect,
1243  $this->mLatest,
1244  $revision->getContentModel()
1245  );
1246  }
1247 
1248  return $result;
1249  }
1250 
1262  public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1263  // Always update redirects (target link might have changed)
1264  // Update/Insert if we don't know if the last revision was a redirect or not
1265  // Delete if changing from redirect to non-redirect
1266  $isRedirect = !is_null( $redirectTitle );
1267 
1268  if ( !$isRedirect && $lastRevIsRedirect === false ) {
1269  return true;
1270  }
1271 
1272  if ( $isRedirect ) {
1273  $this->insertRedirectEntry( $redirectTitle );
1274  } else {
1275  // This is not a redirect, remove row from redirect table
1276  $where = [ 'rd_from' => $this->getId() ];
1277  $dbw->delete( 'redirect', $where, __METHOD__ );
1278  }
1279 
1280  if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1281  RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1282  }
1283 
1284  return ( $dbw->affectedRows() != 0 );
1285  }
1286 
1297  public function updateIfNewerOn( $dbw, $revision ) {
1298 
1299  $row = $dbw->selectRow(
1300  [ 'revision', 'page' ],
1301  [ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1302  [
1303  'page_id' => $this->getId(),
1304  'page_latest=rev_id' ],
1305  __METHOD__ );
1306 
1307  if ( $row ) {
1308  if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1309  return false;
1310  }
1311  $prev = $row->rev_id;
1312  $lastRevIsRedirect = (bool)$row->page_is_redirect;
1313  } else {
1314  // No or missing previous revision; mark the page as new
1315  $prev = 0;
1316  $lastRevIsRedirect = null;
1317  }
1318 
1319  $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1320 
1321  return $ret;
1322  }
1323 
1334  public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1335  $handler = $undo->getContentHandler();
1336  return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1337  }
1338 
1349  public function supportsSections() {
1350  return $this->getContentHandler()->supportsSections();
1351  }
1352 
1367  public function replaceSectionContent(
1368  $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1369  ) {
1370 
1371  $baseRevId = null;
1372  if ( $edittime && $sectionId !== 'new' ) {
1373  $dbr = wfGetDB( DB_SLAVE );
1374  $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1375  // Try the master if this thread may have just added it.
1376  // This could be abstracted into a Revision method, but we don't want
1377  // to encourage loading of revisions by timestamp.
1378  if ( !$rev
1379  && wfGetLB()->getServerCount() > 1
1380  && wfGetLB()->hasOrMadeRecentMasterChanges()
1381  ) {
1382  $dbw = wfGetDB( DB_MASTER );
1383  $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1384  }
1385  if ( $rev ) {
1386  $baseRevId = $rev->getId();
1387  }
1388  }
1389 
1390  return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1391  }
1392 
1406  public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1407  $sectionTitle = '', $baseRevId = null
1408  ) {
1409 
1410  if ( strval( $sectionId ) === '' ) {
1411  // Whole-page edit; let the whole text through
1412  $newContent = $sectionContent;
1413  } else {
1414  if ( !$this->supportsSections() ) {
1415  throw new MWException( "sections not supported for content model " .
1416  $this->getContentHandler()->getModelID() );
1417  }
1418 
1419  // Bug 30711: always use current version when adding a new section
1420  if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1421  $oldContent = $this->getContent();
1422  } else {
1423  $rev = Revision::newFromId( $baseRevId );
1424  if ( !$rev ) {
1425  wfDebug( __METHOD__ . " asked for bogus section (page: " .
1426  $this->getId() . "; section: $sectionId)\n" );
1427  return null;
1428  }
1429 
1430  $oldContent = $rev->getContent();
1431  }
1432 
1433  if ( !$oldContent ) {
1434  wfDebug( __METHOD__ . ": no page text\n" );
1435  return null;
1436  }
1437 
1438  $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1439  }
1440 
1441  return $newContent;
1442  }
1443 
1449  public function checkFlags( $flags ) {
1450  if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1451  if ( $this->exists() ) {
1452  $flags |= EDIT_UPDATE;
1453  } else {
1454  $flags |= EDIT_NEW;
1455  }
1456  }
1457 
1458  return $flags;
1459  }
1460 
1515  public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1516  ContentHandler::deprecated( __METHOD__, '1.21' );
1517 
1518  $content = ContentHandler::makeContent( $text, $this->getTitle() );
1519 
1520  return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1521  }
1522 
1580  public function doEditContent(
1581  Content $content, $summary, $flags = 0, $baseRevId = false,
1582  User $user = null, $serialFormat = null, $tags = null
1583  ) {
1585 
1586  // Low-level sanity check
1587  if ( $this->mTitle->getText() === '' ) {
1588  throw new MWException( 'Something is trying to edit an article with an empty title' );
1589  }
1590  // Make sure the given content type is allowed for this page
1591  if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1592  return Status::newFatal( 'content-not-allowed-here',
1593  ContentHandler::getLocalizedName( $content->getModel() ),
1594  $this->mTitle->getPrefixedText()
1595  );
1596  }
1597 
1598  // Load the data from the master database if needed.
1599  // The caller may already loaded it from the master or even loaded it using
1600  // SELECT FOR UPDATE, so do not override that using clear().
1601  $this->loadPageData( 'fromdbmaster' );
1602 
1603  $user = $user ?: $wgUser;
1604  $flags = $this->checkFlags( $flags );
1605 
1606  // Trigger pre-save hook (using provided edit summary)
1607  $hookStatus = Status::newGood( [] );
1608  $hook_args = [ &$this, &$user, &$content, &$summary,
1609  $flags & EDIT_MINOR, null, null, &$flags, &$hookStatus ];
1610  // Check if the hook rejected the attempted save
1611  if ( !Hooks::run( 'PageContentSave', $hook_args )
1612  || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args )
1613  ) {
1614  if ( $hookStatus->isOK() ) {
1615  // Hook returned false but didn't call fatal(); use generic message
1616  $hookStatus->fatal( 'edit-hook-aborted' );
1617  }
1618 
1619  return $hookStatus;
1620  }
1621 
1622  $old_revision = $this->getRevision(); // current revision
1623  $old_content = $this->getContent( Revision::RAW ); // current revision's content
1624 
1625  // Provide autosummaries if one is not provided and autosummaries are enabled
1626  if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY ) && $summary == '' ) {
1627  $handler = $content->getContentHandler();
1628  $summary = $handler->getAutosummary( $old_content, $content, $flags );
1629  }
1630 
1631  // Avoid statsd noise and wasted cycles check the edit stash (T136678)
1632  if ( ( $flags & EDIT_INTERNAL ) || ( $flags & EDIT_FORCE_BOT ) ) {
1633  $useCache = false;
1634  } else {
1635  $useCache = true;
1636  }
1637 
1638  // Get the pre-save transform content and final parser output
1639  $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1640  $pstContent = $editInfo->pstContent; // Content object
1641  $meta = [
1642  'bot' => ( $flags & EDIT_FORCE_BOT ),
1643  'minor' => ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' ),
1644  'serialized' => $editInfo->pst,
1645  'serialFormat' => $serialFormat,
1646  'baseRevId' => $baseRevId,
1647  'oldRevision' => $old_revision,
1648  'oldContent' => $old_content,
1649  'oldId' => $this->getLatest(),
1650  'oldIsRedirect' => $this->isRedirect(),
1651  'oldCountable' => $this->isCountable(),
1652  'tags' => ( $tags !== null ) ? (array)$tags : []
1653  ];
1654 
1655  // Actually create the revision and create/update the page
1656  if ( $flags & EDIT_UPDATE ) {
1657  $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1658  } else {
1659  $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1660  }
1661 
1662  // Promote user to any groups they meet the criteria for
1663  DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1664  $user->addAutopromoteOnceGroups( 'onEdit' );
1665  $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1666  } );
1667 
1668  return $status;
1669  }
1670 
1683  private function doModify(
1685  ) {
1687 
1688  // Update article, but only if changed.
1689  $status = Status::newGood( [ 'new' => false, 'revision' => null ] );
1690 
1691  // Convenience variables
1692  $now = wfTimestampNow();
1693  $oldid = $meta['oldId'];
1695  $oldContent = $meta['oldContent'];
1696  $newsize = $content->getSize();
1697 
1698  if ( !$oldid ) {
1699  // Article gone missing
1700  $status->fatal( 'edit-gone-missing' );
1701 
1702  return $status;
1703  } elseif ( !$oldContent ) {
1704  // Sanity check for bug 37225
1705  throw new MWException( "Could not find text for current revision {$oldid}." );
1706  }
1707 
1708  // @TODO: pass content object?!
1709  $revision = new Revision( [
1710  'page' => $this->getId(),
1711  'title' => $this->mTitle, // for determining the default content model
1712  'comment' => $summary,
1713  'minor_edit' => $meta['minor'],
1714  'text' => $meta['serialized'],
1715  'len' => $newsize,
1716  'parent_id' => $oldid,
1717  'user' => $user->getId(),
1718  'user_text' => $user->getName(),
1719  'timestamp' => $now,
1720  'content_model' => $content->getModel(),
1721  'content_format' => $meta['serialFormat'],
1722  ] );
1723 
1724  $changed = !$content->equals( $oldContent );
1725 
1726  $dbw = wfGetDB( DB_MASTER );
1727 
1728  if ( $changed ) {
1729  $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1730  $status->merge( $prepStatus );
1731  if ( !$status->isOK() ) {
1732  return $status;
1733  }
1734 
1735  $dbw->startAtomic( __METHOD__ );
1736  // Get the latest page_latest value while locking it.
1737  // Do a CAS style check to see if it's the same as when this method
1738  // started. If it changed then bail out before touching the DB.
1739  $latestNow = $this->lockAndGetLatest();
1740  if ( $latestNow != $oldid ) {
1741  $dbw->endAtomic( __METHOD__ );
1742  // Page updated or deleted in the mean time
1743  $status->fatal( 'edit-conflict' );
1744 
1745  return $status;
1746  }
1747 
1748  // At this point we are now comitted to returning an OK
1749  // status unless some DB query error or other exception comes up.
1750  // This way callers don't have to call rollback() if $status is bad
1751  // unless they actually try to catch exceptions (which is rare).
1752 
1753  // Save the revision text
1754  $revisionId = $revision->insertOn( $dbw );
1755  // Update page_latest and friends to reflect the new revision
1756  if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1757  $dbw->rollback( __METHOD__ ); // sanity; this should never happen
1758  throw new MWException( "Failed to update page row to use new revision." );
1759  }
1760 
1761  Hooks::run( 'NewRevisionFromEditComplete',
1762  [ $this, $revision, $meta['baseRevId'], $user ] );
1763 
1764  // Update recentchanges
1765  if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1766  // Mark as patrolled if the user can do so
1767  $patrolled = $wgUseRCPatrol && !count(
1768  $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1769  // Add RC row to the DB
1771  $now,
1772  $this->mTitle,
1773  $revision->isMinor(),
1774  $user,
1775  $summary,
1776  $oldid,
1777  $this->getTimestamp(),
1778  $meta['bot'],
1779  '',
1780  $oldContent ? $oldContent->getSize() : 0,
1781  $newsize,
1782  $revisionId,
1783  $patrolled,
1784  $meta['tags']
1785  );
1786  }
1787 
1788  $user->incEditCount();
1789 
1790  $dbw->endAtomic( __METHOD__ );
1791  $this->mTimestamp = $now;
1792  } else {
1793  // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1794  // related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1795  $revision->setId( $this->getLatest() );
1796  $revision->setUserIdAndName(
1797  $this->getUser( Revision::RAW ),
1798  $this->getUserText( Revision::RAW )
1799  );
1800  }
1801 
1802  if ( $changed ) {
1803  // Return the new revision to the caller
1804  $status->value['revision'] = $revision;
1805  } else {
1806  $status->warning( 'edit-no-change' );
1807  // Update page_touched as updateRevisionOn() was not called.
1808  // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1809  $this->mTitle->invalidateCache( $now );
1810  }
1811 
1812  // Do secondary updates once the main changes have been committed...
1814  new AtomicSectionUpdate(
1815  $dbw,
1816  __METHOD__,
1817  function () use (
1818  $revision, &$user, $content, $summary, &$flags,
1819  $changed, $meta, &$status
1820  ) {
1821  // Update links tables, site stats, etc.
1822  $this->doEditUpdates(
1823  $revision,
1824  $user,
1825  [
1826  'changed' => $changed,
1827  'oldcountable' => $meta['oldCountable'],
1828  'oldrevision' => $meta['oldRevision']
1829  ]
1830  );
1831  // Trigger post-save hook
1832  $params = [ &$this, &$user, $content, $summary, $flags & EDIT_MINOR,
1833  null, null, &$flags, $revision, &$status, $meta['baseRevId'] ];
1834  ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $params );
1835  Hooks::run( 'PageContentSaveComplete', $params );
1836  }
1837  )
1838  );
1839 
1840  return $status;
1841  }
1842 
1855  private function doCreate(
1857  ) {
1859 
1860  $status = Status::newGood( [ 'new' => true, 'revision' => null ] );
1861 
1862  $now = wfTimestampNow();
1863  $newsize = $content->getSize();
1864  $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1865  $status->merge( $prepStatus );
1866  if ( !$status->isOK() ) {
1867  return $status;
1868  }
1869 
1870  $dbw = wfGetDB( DB_MASTER );
1871  $dbw->startAtomic( __METHOD__ );
1872 
1873  // Add the page record unless one already exists for the title
1874  $newid = $this->insertOn( $dbw );
1875  if ( $newid === false ) {
1876  $dbw->endAtomic( __METHOD__ ); // nothing inserted
1877  $status->fatal( 'edit-already-exists' );
1878 
1879  return $status; // nothing done
1880  }
1881 
1882  // At this point we are now comitted to returning an OK
1883  // status unless some DB query error or other exception comes up.
1884  // This way callers don't have to call rollback() if $status is bad
1885  // unless they actually try to catch exceptions (which is rare).
1886 
1887  // @TODO: pass content object?!
1888  $revision = new Revision( [
1889  'page' => $newid,
1890  'title' => $this->mTitle, // for determining the default content model
1891  'comment' => $summary,
1892  'minor_edit' => $meta['minor'],
1893  'text' => $meta['serialized'],
1894  'len' => $newsize,
1895  'user' => $user->getId(),
1896  'user_text' => $user->getName(),
1897  'timestamp' => $now,
1898  'content_model' => $content->getModel(),
1899  'content_format' => $meta['serialFormat'],
1900  ] );
1901 
1902  // Save the revision text...
1903  $revisionId = $revision->insertOn( $dbw );
1904  // Update the page record with revision data
1905  if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1906  $dbw->rollback( __METHOD__ ); // sanity; this should never happen
1907  throw new MWException( "Failed to update page row to use new revision." );
1908  }
1909 
1910  Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1911 
1912  // Update recentchanges
1913  if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1914  // Mark as patrolled if the user can do so
1915  $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) &&
1916  !count( $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1917  // Add RC row to the DB
1919  $now,
1920  $this->mTitle,
1921  $revision->isMinor(),
1922  $user,
1923  $summary,
1924  $meta['bot'],
1925  '',
1926  $newsize,
1927  $revisionId,
1928  $patrolled,
1929  $meta['tags']
1930  );
1931  }
1932 
1933  $user->incEditCount();
1934 
1935  $dbw->endAtomic( __METHOD__ );
1936  $this->mTimestamp = $now;
1937 
1938  // Return the new revision to the caller
1939  $status->value['revision'] = $revision;
1940 
1941  // Do secondary updates once the main changes have been committed...
1943  new AtomicSectionUpdate(
1944  $dbw,
1945  __METHOD__,
1946  function () use (
1947  $revision, &$user, $content, $summary, &$flags, $meta, &$status
1948  ) {
1949  // Update links, etc.
1950  $this->doEditUpdates( $revision, $user, [ 'created' => true ] );
1951  // Trigger post-create hook
1952  $params = [ &$this, &$user, $content, $summary,
1953  $flags & EDIT_MINOR, null, null, &$flags, $revision ];
1954  ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $params );
1955  Hooks::run( 'PageContentInsertComplete', $params );
1956  // Trigger post-save hook
1957  $params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1958  ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $params );
1959  Hooks::run( 'PageContentSaveComplete', $params );
1960 
1961  }
1962  )
1963  );
1964 
1965  return $status;
1966  }
1967 
1982  public function makeParserOptions( $context ) {
1983  $options = $this->getContentHandler()->makeParserOptions( $context );
1984 
1985  if ( $this->getTitle()->isConversionTable() ) {
1986  // @todo ConversionTable should become a separate content model, so
1987  // we don't need special cases like this one.
1988  $options->disableContentConversion();
1989  }
1990 
1991  return $options;
1992  }
1993 
2004  public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2005  ContentHandler::deprecated( __METHOD__, '1.21' );
2006  $content = ContentHandler::makeContent( $text, $this->getTitle() );
2007  return $this->prepareContentForEdit( $content, $revid, $user );
2008  }
2009 
2025  public function prepareContentForEdit(
2026  Content $content, $revision = null, User $user = null,
2027  $serialFormat = null, $useCache = true
2028  ) {
2030 
2031  if ( is_object( $revision ) ) {
2032  $revid = $revision->getId();
2033  } else {
2034  $revid = $revision;
2035  // This code path is deprecated, and nothing is known to
2036  // use it, so performance here shouldn't be a worry.
2037  if ( $revid !== null ) {
2038  $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2039  } else {
2040  $revision = null;
2041  }
2042  }
2043 
2044  $user = is_null( $user ) ? $wgUser : $user;
2045  // XXX: check $user->getId() here???
2046 
2047  // Use a sane default for $serialFormat, see bug 57026
2048  if ( $serialFormat === null ) {
2049  $serialFormat = $content->getContentHandler()->getDefaultFormat();
2050  }
2051 
2052  if ( $this->mPreparedEdit
2053  && isset( $this->mPreparedEdit->newContent )
2054  && $this->mPreparedEdit->newContent->equals( $content )
2055  && $this->mPreparedEdit->revid == $revid
2056  && $this->mPreparedEdit->format == $serialFormat
2057  // XXX: also check $user here?
2058  ) {
2059  // Already prepared
2060  return $this->mPreparedEdit;
2061  }
2062 
2063  // The edit may have already been prepared via api.php?action=stashedit
2064  $cachedEdit = $useCache && $wgAjaxEditStash
2065  ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2066  : false;
2067 
2068  $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2069  Hooks::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2070 
2071  $edit = (object)[];
2072  if ( $cachedEdit ) {
2073  $edit->timestamp = $cachedEdit->timestamp;
2074  } else {
2075  $edit->timestamp = wfTimestampNow();
2076  }
2077  // @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2078  $edit->revid = $revid;
2079 
2080  if ( $cachedEdit ) {
2081  $edit->pstContent = $cachedEdit->pstContent;
2082  } else {
2083  $edit->pstContent = $content
2084  ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2085  : null;
2086  }
2087 
2088  $edit->format = $serialFormat;
2089  $edit->popts = $this->makeParserOptions( 'canonical' );
2090  if ( $cachedEdit ) {
2091  $edit->output = $cachedEdit->output;
2092  } else {
2093  if ( $revision ) {
2094  // We get here if vary-revision is set. This means that this page references
2095  // itself (such as via self-transclusion). In this case, we need to make sure
2096  // that any such self-references refer to the newly-saved revision, and not
2097  // to the previous one, which could otherwise happen due to slave lag.
2098  $oldCallback = $edit->popts->getCurrentRevisionCallback();
2099  $edit->popts->setCurrentRevisionCallback(
2100  function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2101  if ( $title->equals( $revision->getTitle() ) ) {
2102  return $revision;
2103  } else {
2104  return call_user_func( $oldCallback, $title, $parser );
2105  }
2106  }
2107  );
2108  } else {
2109  // Try to avoid a second parse if {{REVISIONID}} is used
2110  $edit->popts->setSpeculativeRevIdCallback( function () {
2111  return 1 + (int)wfGetDB( DB_MASTER )->selectField(
2112  'revision',
2113  'MAX(rev_id)',
2114  [],
2115  __METHOD__
2116  );
2117  } );
2118  }
2119  $edit->output = $edit->pstContent
2120  ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2121  : null;
2122  }
2123 
2124  $edit->newContent = $content;
2125  $edit->oldContent = $this->getContent( Revision::RAW );
2126 
2127  // NOTE: B/C for hooks! don't use these fields!
2128  $edit->newText = $edit->newContent
2129  ? ContentHandler::getContentText( $edit->newContent )
2130  : '';
2131  $edit->oldText = $edit->oldContent
2132  ? ContentHandler::getContentText( $edit->oldContent )
2133  : '';
2134  $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2135 
2136  if ( $edit->output ) {
2137  $edit->output->setCacheTime( wfTimestampNow() );
2138  }
2139 
2140  // Process cache the result
2141  $this->mPreparedEdit = $edit;
2142 
2143  return $edit;
2144  }
2145 
2167  public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2169 
2170  $options += [
2171  'changed' => true,
2172  'created' => false,
2173  'moved' => false,
2174  'restored' => false,
2175  'oldrevision' => null,
2176  'oldcountable' => null
2177  ];
2178  $content = $revision->getContent();
2179 
2180  $logger = LoggerFactory::getInstance( 'SaveParse' );
2181 
2182  // See if the parser output before $revision was inserted is still valid
2183  $editInfo = false;
2184  if ( !$this->mPreparedEdit ) {
2185  $logger->debug( __METHOD__ . ": No prepared edit...\n" );
2186  } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2187  $logger->info( __METHOD__ . ": Prepared edit has vary-revision...\n" );
2188  } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision-id' )
2189  && $this->mPreparedEdit->output->getSpeculativeRevIdUsed() !== $revision->getId()
2190  ) {
2191  $logger->info( __METHOD__ . ": Prepared edit has vary-revision-id with wrong ID...\n" );
2192  } elseif ( $this->mPreparedEdit->output->getFlag( 'vary-user' ) && !$options['changed'] ) {
2193  $logger->info( __METHOD__ . ": Prepared edit has vary-user and is null...\n" );
2194  } else {
2195  wfDebug( __METHOD__ . ": Using prepared edit...\n" );
2196  $editInfo = $this->mPreparedEdit;
2197  }
2198 
2199  if ( !$editInfo ) {
2200  // Parse the text again if needed. Be careful not to do pre-save transform twice:
2201  // $text is usually already pre-save transformed once. Avoid using the edit stash
2202  // as any prepared content from there or in doEditContent() was already rejected.
2203  $editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
2204  }
2205 
2206  // Save it to the parser cache.
2207  // Make sure the cache time matches page_touched to avoid double parsing.
2208  ParserCache::singleton()->save(
2209  $editInfo->output, $this, $editInfo->popts,
2210  $revision->getTimestamp(), $editInfo->revid
2211  );
2212 
2213  // Update the links tables and other secondary data
2214  if ( $content ) {
2215  $recursive = $options['changed']; // bug 50785
2216  $updates = $content->getSecondaryDataUpdates(
2217  $this->getTitle(), null, $recursive, $editInfo->output
2218  );
2219  foreach ( $updates as $update ) {
2220  if ( $update instanceof LinksUpdate ) {
2221  $update->setRevision( $revision );
2222  $update->setTriggeringUser( $user );
2223  }
2224  DeferredUpdates::addUpdate( $update );
2225  }
2226  if ( $wgRCWatchCategoryMembership
2227  && $this->getContentHandler()->supportsCategories() === true
2228  && ( $options['changed'] || $options['created'] )
2229  && !$options['restored']
2230  ) {
2231  // Note: jobs are pushed after deferred updates, so the job should be able to see
2232  // the recent change entry (also done via deferred updates) and carry over any
2233  // bot/deletion/IP flags, ect.
2235  $this->getTitle(),
2236  [
2237  'pageId' => $this->getId(),
2238  'revTimestamp' => $revision->getTimestamp()
2239  ]
2240  ) );
2241  }
2242  }
2243 
2244  Hooks::run( 'ArticleEditUpdates', [ &$this, &$editInfo, $options['changed'] ] );
2245 
2246  if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$this ] ) ) {
2247  // Flush old entries from the `recentchanges` table
2248  if ( mt_rand( 0, 9 ) == 0 ) {
2250  }
2251  }
2252 
2253  if ( !$this->exists() ) {
2254  return;
2255  }
2256 
2257  $id = $this->getId();
2258  $title = $this->mTitle->getPrefixedDBkey();
2259  $shortTitle = $this->mTitle->getDBkey();
2260 
2261  if ( $options['oldcountable'] === 'no-change' ||
2262  ( !$options['changed'] && !$options['moved'] )
2263  ) {
2264  $good = 0;
2265  } elseif ( $options['created'] ) {
2266  $good = (int)$this->isCountable( $editInfo );
2267  } elseif ( $options['oldcountable'] !== null ) {
2268  $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2269  } else {
2270  $good = 0;
2271  }
2272  $edits = $options['changed'] ? 1 : 0;
2273  $total = $options['created'] ? 1 : 0;
2274 
2275  DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2277 
2278  // If this is another user's talk page, update newtalk.
2279  // Don't do this if $options['changed'] = false (null-edits) nor if
2280  // it's a minor edit and the user doesn't want notifications for those.
2281  if ( $options['changed']
2282  && $this->mTitle->getNamespace() == NS_USER_TALK
2283  && $shortTitle != $user->getTitleKey()
2284  && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2285  ) {
2286  $recipient = User::newFromName( $shortTitle, false );
2287  if ( !$recipient ) {
2288  wfDebug( __METHOD__ . ": invalid username\n" );
2289  } else {
2290  // Allow extensions to prevent user notification
2291  // when a new message is added to their talk page
2292  if ( Hooks::run( 'ArticleEditUpdateNewTalk', [ &$this, $recipient ] ) ) {
2293  if ( User::isIP( $shortTitle ) ) {
2294  // An anonymous user
2295  $recipient->setNewtalk( true, $revision );
2296  } elseif ( $recipient->isLoggedIn() ) {
2297  $recipient->setNewtalk( true, $revision );
2298  } else {
2299  wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2300  }
2301  }
2302  }
2303  }
2304 
2305  if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2306  // XXX: could skip pseudo-messages like js/css here, based on content model.
2307  $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2308  if ( $msgtext === false || $msgtext === null ) {
2309  $msgtext = '';
2310  }
2311 
2312  MessageCache::singleton()->replace( $shortTitle, $msgtext );
2313 
2314  if ( $wgContLang->hasVariants() ) {
2315  $wgContLang->updateConversionTable( $this->mTitle );
2316  }
2317  }
2318 
2319  if ( $options['created'] ) {
2320  self::onArticleCreate( $this->mTitle );
2321  } elseif ( $options['changed'] ) { // bug 50785
2322  self::onArticleEdit( $this->mTitle, $revision );
2323  }
2324  }
2325 
2337  public function doQuickEditContent(
2338  Content $content, User $user, $comment = '', $minor = false, $serialFormat = null
2339  ) {
2340 
2341  $serialized = $content->serialize( $serialFormat );
2342 
2343  $dbw = wfGetDB( DB_MASTER );
2344  $revision = new Revision( [
2345  'title' => $this->getTitle(), // for determining the default content model
2346  'page' => $this->getId(),
2347  'user_text' => $user->getName(),
2348  'user' => $user->getId(),
2349  'text' => $serialized,
2350  'length' => $content->getSize(),
2351  'comment' => $comment,
2352  'minor_edit' => $minor ? 1 : 0,
2353  ] ); // XXX: set the content object?
2354  $revision->insertOn( $dbw );
2355  $this->updateRevisionOn( $dbw, $revision );
2356 
2357  Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
2358 
2359  }
2360 
2375  public function doUpdateRestrictions( array $limit, array $expiry,
2376  &$cascade, $reason, User $user, $tags = null
2377  ) {
2379 
2380  if ( wfReadOnly() ) {
2381  return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2382  }
2383 
2384  $this->loadPageData( 'fromdbmaster' );
2385  $restrictionTypes = $this->mTitle->getRestrictionTypes();
2386  $id = $this->getId();
2387 
2388  if ( !$cascade ) {
2389  $cascade = false;
2390  }
2391 
2392  // Take this opportunity to purge out expired restrictions
2394 
2395  // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2396  // we expect a single selection, but the schema allows otherwise.
2397  $isProtected = false;
2398  $protect = false;
2399  $changed = false;
2400 
2401  $dbw = wfGetDB( DB_MASTER );
2402 
2403  foreach ( $restrictionTypes as $action ) {
2404  if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2405  $expiry[$action] = 'infinity';
2406  }
2407  if ( !isset( $limit[$action] ) ) {
2408  $limit[$action] = '';
2409  } elseif ( $limit[$action] != '' ) {
2410  $protect = true;
2411  }
2412 
2413  // Get current restrictions on $action
2414  $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2415  if ( $current != '' ) {
2416  $isProtected = true;
2417  }
2418 
2419  if ( $limit[$action] != $current ) {
2420  $changed = true;
2421  } elseif ( $limit[$action] != '' ) {
2422  // Only check expiry change if the action is actually being
2423  // protected, since expiry does nothing on an not-protected
2424  // action.
2425  if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2426  $changed = true;
2427  }
2428  }
2429  }
2430 
2431  if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2432  $changed = true;
2433  }
2434 
2435  // If nothing has changed, do nothing
2436  if ( !$changed ) {
2437  return Status::newGood();
2438  }
2439 
2440  if ( !$protect ) { // No protection at all means unprotection
2441  $revCommentMsg = 'unprotectedarticle';
2442  $logAction = 'unprotect';
2443  } elseif ( $isProtected ) {
2444  $revCommentMsg = 'modifiedarticleprotection';
2445  $logAction = 'modify';
2446  } else {
2447  $revCommentMsg = 'protectedarticle';
2448  $logAction = 'protect';
2449  }
2450 
2451  // Truncate for whole multibyte characters
2452  $reason = $wgContLang->truncate( $reason, 255 );
2453 
2454  $logRelationsValues = [];
2455  $logRelationsField = null;
2456  $logParamsDetails = [];
2457 
2458  // Null revision (used for change tag insertion)
2459  $nullRevision = null;
2460 
2461  if ( $id ) { // Protection of existing page
2462  if ( !Hooks::run( 'ArticleProtect', [ &$this, &$user, $limit, $reason ] ) ) {
2463  return Status::newGood();
2464  }
2465 
2466  // Only certain restrictions can cascade...
2467  $editrestriction = isset( $limit['edit'] )
2468  ? [ $limit['edit'] ]
2469  : $this->mTitle->getRestrictions( 'edit' );
2470  foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2471  $editrestriction[$key] = 'editprotected'; // backwards compatibility
2472  }
2473  foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2474  $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2475  }
2476 
2477  $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2478  foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2479  $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2480  }
2481  foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2482  $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2483  }
2484 
2485  // The schema allows multiple restrictions
2486  if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2487  $cascade = false;
2488  }
2489 
2490  // insert null revision to identify the page protection change as edit summary
2491  $latest = $this->getLatest();
2492  $nullRevision = $this->insertProtectNullRevision(
2493  $revCommentMsg,
2494  $limit,
2495  $expiry,
2496  $cascade,
2497  $reason,
2498  $user
2499  );
2500 
2501  if ( $nullRevision === null ) {
2502  return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2503  }
2504 
2505  $logRelationsField = 'pr_id';
2506 
2507  // Update restrictions table
2508  foreach ( $limit as $action => $restrictions ) {
2509  $dbw->delete(
2510  'page_restrictions',
2511  [
2512  'pr_page' => $id,
2513  'pr_type' => $action
2514  ],
2515  __METHOD__
2516  );
2517  if ( $restrictions != '' ) {
2518  $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2519  $dbw->insert(
2520  'page_restrictions',
2521  [
2522  'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2523  'pr_page' => $id,
2524  'pr_type' => $action,
2525  'pr_level' => $restrictions,
2526  'pr_cascade' => $cascadeValue,
2527  'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2528  ],
2529  __METHOD__
2530  );
2531  $logRelationsValues[] = $dbw->insertId();
2532  $logParamsDetails[] = [
2533  'type' => $action,
2534  'level' => $restrictions,
2535  'expiry' => $expiry[$action],
2536  'cascade' => (bool)$cascadeValue,
2537  ];
2538  }
2539  }
2540 
2541  // Clear out legacy restriction fields
2542  $dbw->update(
2543  'page',
2544  [ 'page_restrictions' => '' ],
2545  [ 'page_id' => $id ],
2546  __METHOD__
2547  );
2548 
2549  Hooks::run( 'NewRevisionFromEditComplete',
2550  [ $this, $nullRevision, $latest, $user ] );
2551  Hooks::run( 'ArticleProtectComplete', [ &$this, &$user, $limit, $reason ] );
2552  } else { // Protection of non-existing page (also known as "title protection")
2553  // Cascade protection is meaningless in this case
2554  $cascade = false;
2555 
2556  if ( $limit['create'] != '' ) {
2557  $dbw->replace( 'protected_titles',
2558  [ [ 'pt_namespace', 'pt_title' ] ],
2559  [
2560  'pt_namespace' => $this->mTitle->getNamespace(),
2561  'pt_title' => $this->mTitle->getDBkey(),
2562  'pt_create_perm' => $limit['create'],
2563  'pt_timestamp' => $dbw->timestamp(),
2564  'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2565  'pt_user' => $user->getId(),
2566  'pt_reason' => $reason,
2567  ], __METHOD__
2568  );
2569  $logParamsDetails[] = [
2570  'type' => 'create',
2571  'level' => $limit['create'],
2572  'expiry' => $expiry['create'],
2573  ];
2574  } else {
2575  $dbw->delete( 'protected_titles',
2576  [
2577  'pt_namespace' => $this->mTitle->getNamespace(),
2578  'pt_title' => $this->mTitle->getDBkey()
2579  ], __METHOD__
2580  );
2581  }
2582  }
2583 
2584  $this->mTitle->flushRestrictions();
2585  InfoAction::invalidateCache( $this->mTitle );
2586 
2587  if ( $logAction == 'unprotect' ) {
2588  $params = [];
2589  } else {
2590  $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2591  $params = [
2592  '4::description' => $protectDescriptionLog, // parameter for IRC
2593  '5:bool:cascade' => $cascade,
2594  'details' => $logParamsDetails, // parameter for localize and api
2595  ];
2596  }
2597 
2598  // Update the protection log
2599  $logEntry = new ManualLogEntry( 'protect', $logAction );
2600  $logEntry->setTarget( $this->mTitle );
2601  $logEntry->setComment( $reason );
2602  $logEntry->setPerformer( $user );
2603  $logEntry->setParameters( $params );
2604  if ( !is_null( $nullRevision ) ) {
2605  $logEntry->setAssociatedRevId( $nullRevision->getId() );
2606  }
2607  $logEntry->setTags( $tags );
2608  if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2609  $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2610  }
2611  $logId = $logEntry->insert();
2612  $logEntry->publish( $logId );
2613 
2614  return Status::newGood( $logId );
2615  }
2616 
2628  public function insertProtectNullRevision( $revCommentMsg, array $limit,
2629  array $expiry, $cascade, $reason, $user = null
2630  ) {
2632  $dbw = wfGetDB( DB_MASTER );
2633 
2634  // Prepare a null revision to be added to the history
2635  $editComment = $wgContLang->ucfirst(
2636  wfMessage(
2637  $revCommentMsg,
2638  $this->mTitle->getPrefixedText()
2639  )->inContentLanguage()->text()
2640  );
2641  if ( $reason ) {
2642  $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2643  }
2644  $protectDescription = $this->protectDescription( $limit, $expiry );
2645  if ( $protectDescription ) {
2646  $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2647  $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2648  ->inContentLanguage()->text();
2649  }
2650  if ( $cascade ) {
2651  $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2652  $editComment .= wfMessage( 'brackets' )->params(
2653  wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2654  )->inContentLanguage()->text();
2655  }
2656 
2657  $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2658  if ( $nullRev ) {
2659  $nullRev->insertOn( $dbw );
2660 
2661  // Update page record and touch page
2662  $oldLatest = $nullRev->getParentId();
2663  $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2664  }
2665 
2666  return $nullRev;
2667  }
2668 
2673  protected function formatExpiry( $expiry ) {
2675 
2676  if ( $expiry != 'infinity' ) {
2677  return wfMessage(
2678  'protect-expiring',
2679  $wgContLang->timeanddate( $expiry, false, false ),
2680  $wgContLang->date( $expiry, false, false ),
2681  $wgContLang->time( $expiry, false, false )
2682  )->inContentLanguage()->text();
2683  } else {
2684  return wfMessage( 'protect-expiry-indefinite' )
2685  ->inContentLanguage()->text();
2686  }
2687  }
2688 
2696  public function protectDescription( array $limit, array $expiry ) {
2697  $protectDescription = '';
2698 
2699  foreach ( array_filter( $limit ) as $action => $restrictions ) {
2700  # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2701  # All possible message keys are listed here for easier grepping:
2702  # * restriction-create
2703  # * restriction-edit
2704  # * restriction-move
2705  # * restriction-upload
2706  $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2707  # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2708  # with '' filtered out. All possible message keys are listed below:
2709  # * protect-level-autoconfirmed
2710  # * protect-level-sysop
2711  $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2712  ->inContentLanguage()->text();
2713 
2714  $expiryText = $this->formatExpiry( $expiry[$action] );
2715 
2716  if ( $protectDescription !== '' ) {
2717  $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2718  }
2719  $protectDescription .= wfMessage( 'protect-summary-desc' )
2720  ->params( $actionText, $restrictionsText, $expiryText )
2721  ->inContentLanguage()->text();
2722  }
2723 
2724  return $protectDescription;
2725  }
2726 
2738  public function protectDescriptionLog( array $limit, array $expiry ) {
2740 
2741  $protectDescriptionLog = '';
2742 
2743  foreach ( array_filter( $limit ) as $action => $restrictions ) {
2744  $expiryText = $this->formatExpiry( $expiry[$action] );
2745  $protectDescriptionLog .= $wgContLang->getDirMark() .
2746  "[$action=$restrictions] ($expiryText)";
2747  }
2748 
2749  return trim( $protectDescriptionLog );
2750  }
2751 
2761  protected static function flattenRestrictions( $limit ) {
2762  if ( !is_array( $limit ) ) {
2763  throw new MWException( __METHOD__ . ' given non-array restriction set' );
2764  }
2765 
2766  $bits = [];
2767  ksort( $limit );
2768 
2769  foreach ( array_filter( $limit ) as $action => $restrictions ) {
2770  $bits[] = "$action=$restrictions";
2771  }
2772 
2773  return implode( ':', $bits );
2774  }
2775 
2792  public function doDeleteArticle(
2793  $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2794  ) {
2795  $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2796  return $status->isGood();
2797  }
2798 
2816  public function doDeleteArticleReal(
2817  $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2818  ) {
2820 
2821  wfDebug( __METHOD__ . "\n" );
2822 
2824 
2825  if ( $this->mTitle->getDBkey() === '' ) {
2826  $status->error( 'cannotdelete',
2827  wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2828  return $status;
2829  }
2830 
2831  $user = is_null( $user ) ? $wgUser : $user;
2832  if ( !Hooks::run( 'ArticleDelete',
2833  [ &$this, &$user, &$reason, &$error, &$status, $suppress ]
2834  ) ) {
2835  if ( $status->isOK() ) {
2836  // Hook aborted but didn't set a fatal status
2837  $status->fatal( 'delete-hook-aborted' );
2838  }
2839  return $status;
2840  }
2841 
2842  $dbw = wfGetDB( DB_MASTER );
2843  $dbw->startAtomic( __METHOD__ );
2844 
2845  $this->loadPageData( self::READ_LATEST );
2846  $id = $this->getId();
2847  // T98706: lock the page from various other updates but avoid using
2848  // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2849  // the revisions queries (which also JOIN on user). Only lock the page
2850  // row and CAS check on page_latest to see if the trx snapshot matches.
2851  $lockedLatest = $this->lockAndGetLatest();
2852  if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2853  $dbw->endAtomic( __METHOD__ );
2854  // Page not there or trx snapshot is stale
2855  $status->error( 'cannotdelete',
2856  wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2857  return $status;
2858  }
2859 
2860  // At this point we are now comitted to returning an OK
2861  // status unless some DB query error or other exception comes up.
2862  // This way callers don't have to call rollback() if $status is bad
2863  // unless they actually try to catch exceptions (which is rare).
2864 
2865  // we need to remember the old content so we can use it to generate all deletion updates.
2866  $content = $this->getContent( Revision::RAW );
2867 
2868  // Bitfields to further suppress the content
2869  if ( $suppress ) {
2870  $bitfield = 0;
2871  // This should be 15...
2872  $bitfield |= Revision::DELETED_TEXT;
2873  $bitfield |= Revision::DELETED_COMMENT;
2874  $bitfield |= Revision::DELETED_USER;
2875  $bitfield |= Revision::DELETED_RESTRICTED;
2876  } else {
2877  $bitfield = 'rev_deleted';
2878  }
2879 
2893  $row = [
2894  'ar_namespace' => 'page_namespace',
2895  'ar_title' => 'page_title',
2896  'ar_comment' => 'rev_comment',
2897  'ar_user' => 'rev_user',
2898  'ar_user_text' => 'rev_user_text',
2899  'ar_timestamp' => 'rev_timestamp',
2900  'ar_minor_edit' => 'rev_minor_edit',
2901  'ar_rev_id' => 'rev_id',
2902  'ar_parent_id' => 'rev_parent_id',
2903  'ar_text_id' => 'rev_text_id',
2904  'ar_text' => '\'\'', // Be explicit to appease
2905  'ar_flags' => '\'\'', // MySQL's "strict mode"...
2906  'ar_len' => 'rev_len',
2907  'ar_page_id' => 'page_id',
2908  'ar_deleted' => $bitfield,
2909  'ar_sha1' => 'rev_sha1',
2910  ];
2911 
2912  if ( $wgContentHandlerUseDB ) {
2913  $row['ar_content_model'] = 'rev_content_model';
2914  $row['ar_content_format'] = 'rev_content_format';
2915  }
2916 
2917  // Copy all the page revisions into the archive table
2918  $dbw->insertSelect(
2919  'archive',
2920  [ 'page', 'revision' ],
2921  $row,
2922  [
2923  'page_id' => $id,
2924  'page_id = rev_page'
2925  ],
2926  __METHOD__
2927  );
2928 
2929  // Now that it's safely backed up, delete it
2930  $dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
2931 
2932  if ( !$dbw->cascadingDeletes() ) {
2933  $dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__ );
2934  }
2935 
2936  // Clone the title, so we have the information we need when we log
2937  $logTitle = clone $this->mTitle;
2938 
2939  // Log the deletion, if the page was suppressed, put it in the suppression log instead
2940  $logtype = $suppress ? 'suppress' : 'delete';
2941 
2942  $logEntry = new ManualLogEntry( $logtype, 'delete' );
2943  $logEntry->setPerformer( $user );
2944  $logEntry->setTarget( $logTitle );
2945  $logEntry->setComment( $reason );
2946  $logid = $logEntry->insert();
2947 
2948  $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2949  // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2950  $logEntry->publish( $logid );
2951  } );
2952 
2953  $dbw->endAtomic( __METHOD__ );
2954 
2955  $this->doDeleteUpdates( $id, $content );
2956 
2957  Hooks::run( 'ArticleDeleteComplete',
2958  [ &$this, &$user, $reason, $id, $content, $logEntry ] );
2959  $status->value = $logid;
2960 
2961  // Show log excerpt on 404 pages rather than just a link
2963  $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2964  $cache->set( $key, 1, $cache::TTL_DAY );
2965 
2966  return $status;
2967  }
2968 
2975  public function lockAndGetLatest() {
2976  return (int)wfGetDB( DB_MASTER )->selectField(
2977  'page',
2978  'page_latest',
2979  [
2980  'page_id' => $this->getId(),
2981  // Typically page_id is enough, but some code might try to do
2982  // updates assuming the title is the same, so verify that
2983  'page_namespace' => $this->getTitle()->getNamespace(),
2984  'page_title' => $this->getTitle()->getDBkey()
2985  ],
2986  __METHOD__,
2987  [ 'FOR UPDATE' ]
2988  );
2989  }
2990 
2999  public function doDeleteUpdates( $id, Content $content = null ) {
3000  // Update site status
3001  DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
3002 
3003  // Delete pagelinks, update secondary indexes, etc
3004  $updates = $this->getDeletionUpdates( $content );
3005  foreach ( $updates as $update ) {
3006  DeferredUpdates::addUpdate( $update );
3007  }
3008 
3009  // Reparse any pages transcluding this page
3010  LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
3011 
3012  // Reparse any pages including this image
3013  if ( $this->mTitle->getNamespace() == NS_FILE ) {
3014  LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
3015  }
3016 
3017  // Clear caches
3018  WikiPage::onArticleDelete( $this->mTitle );
3019 
3020  // Reset this object and the Title object
3021  $this->loadFromRow( false, self::READ_LATEST );
3022 
3023  // Search engine
3024  DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
3025  }
3026 
3056  public function doRollback(
3057  $fromP, $summary, $token, $bot, &$resultDetails, User $user, $tags = null
3058  ) {
3059  $resultDetails = null;
3060 
3061  // Check permissions
3062  $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
3063  $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
3064  $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3065 
3066  if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3067  $errors[] = [ 'sessionfailure' ];
3068  }
3069 
3070  if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
3071  $errors[] = [ 'actionthrottledtext' ];
3072  }
3073 
3074  // If there were errors, bail out now
3075  if ( !empty( $errors ) ) {
3076  return $errors;
3077  }
3078 
3079  return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3080  }
3081 
3102  public function commitRollback( $fromP, $summary, $bot,
3103  &$resultDetails, User $guser, $tags = null
3104  ) {
3106 
3107  $dbw = wfGetDB( DB_MASTER );
3108 
3109  if ( wfReadOnly() ) {
3110  return [ [ 'readonlytext' ] ];
3111  }
3112 
3113  // Get the last editor
3114  $current = $this->getRevision();
3115  if ( is_null( $current ) ) {
3116  // Something wrong... no page?
3117  return [ [ 'notanarticle' ] ];
3118  }
3119 
3120  $from = str_replace( '_', ' ', $fromP );
3121  // User name given should match up with the top revision.
3122  // If the user was deleted then $from should be empty.
3123  if ( $from != $current->getUserText() ) {
3124  $resultDetails = [ 'current' => $current ];
3125  return [ [ 'alreadyrolled',
3126  htmlspecialchars( $this->mTitle->getPrefixedText() ),
3127  htmlspecialchars( $fromP ),
3128  htmlspecialchars( $current->getUserText() )
3129  ] ];
3130  }
3131 
3132  // Get the last edit not by this person...
3133  // Note: these may not be public values
3134  $user = intval( $current->getUser( Revision::RAW ) );
3135  $user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
3136  $s = $dbw->selectRow( 'revision',
3137  [ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3138  [ 'rev_page' => $current->getPage(),
3139  "rev_user != {$user} OR rev_user_text != {$user_text}"
3140  ], __METHOD__,
3141  [ 'USE INDEX' => 'page_timestamp',
3142  'ORDER BY' => 'rev_timestamp DESC' ]
3143  );
3144  if ( $s === false ) {
3145  // No one else ever edited this page
3146  return [ [ 'cantrollback' ] ];
3147  } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3148  || $s->rev_deleted & Revision::DELETED_USER
3149  ) {
3150  // Only admins can see this text
3151  return [ [ 'notvisiblerev' ] ];
3152  }
3153 
3154  // Generate the edit summary if necessary
3155  $target = Revision::newFromId( $s->rev_id, Revision::READ_LATEST );
3156  if ( empty( $summary ) ) {
3157  if ( $from == '' ) { // no public user name
3158  $summary = wfMessage( 'revertpage-nouser' );
3159  } else {
3160  $summary = wfMessage( 'revertpage' );
3161  }
3162  }
3163 
3164  // Allow the custom summary to use the same args as the default message
3165  $args = [
3166  $target->getUserText(), $from, $s->rev_id,
3167  $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3168  $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3169  ];
3170  if ( $summary instanceof Message ) {
3171  $summary = $summary->params( $args )->inContentLanguage()->text();
3172  } else {
3174  }
3175 
3176  // Trim spaces on user supplied text
3177  $summary = trim( $summary );
3178 
3179  // Truncate for whole multibyte characters.
3180  $summary = $wgContLang->truncate( $summary, 255 );
3181 
3182  // Save
3184 
3185  if ( $guser->isAllowed( 'minoredit' ) ) {
3186  $flags |= EDIT_MINOR;
3187  }
3188 
3189  if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3191  }
3192 
3193  // Actually store the edit
3194  $status = $this->doEditContent(
3195  $target->getContent(),
3196  $summary,
3197  $flags,
3198  $target->getId(),
3199  $guser,
3200  null,
3201  $tags
3202  );
3203 
3204  // Set patrolling and bot flag on the edits, which gets rollbacked.
3205  // This is done even on edit failure to have patrolling in that case (bug 62157).
3206  $set = [];
3207  if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3208  // Mark all reverted edits as bot
3209  $set['rc_bot'] = 1;
3210  }
3211 
3212  if ( $wgUseRCPatrol ) {
3213  // Mark all reverted edits as patrolled
3214  $set['rc_patrolled'] = 1;
3215  }
3216 
3217  if ( count( $set ) ) {
3218  $dbw->update( 'recentchanges', $set,
3219  [ /* WHERE */
3220  'rc_cur_id' => $current->getPage(),
3221  'rc_user_text' => $current->getUserText(),
3222  'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3223  ],
3224  __METHOD__
3225  );
3226  }
3227 
3228  if ( !$status->isOK() ) {
3229  return $status->getErrorsArray();
3230  }
3231 
3232  // raise error, when the edit is an edit without a new version
3233  $statusRev = isset( $status->value['revision'] )
3234  ? $status->value['revision']
3235  : null;
3236  if ( !( $statusRev instanceof Revision ) ) {
3237  $resultDetails = [ 'current' => $current ];
3238  return [ [ 'alreadyrolled',
3239  htmlspecialchars( $this->mTitle->getPrefixedText() ),
3240  htmlspecialchars( $fromP ),
3241  htmlspecialchars( $current->getUserText() )
3242  ] ];
3243  }
3244 
3245  $revId = $statusRev->getId();
3246 
3247  Hooks::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3248 
3249  $resultDetails = [
3250  'summary' => $summary,
3251  'current' => $current,
3252  'target' => $target,
3253  'newid' => $revId
3254  ];
3255 
3256  return [];
3257  }
3258 
3270  public static function onArticleCreate( Title $title ) {
3271  // Update existence markers on article/talk tabs...
3272  $other = $title->getOtherPage();
3273 
3274  $other->purgeSquid();
3275 
3276  $title->touchLinks();
3277  $title->purgeSquid();
3278  $title->deleteTitleProtection();
3279 
3280  if ( $title->getNamespace() == NS_CATEGORY ) {
3281  // Load the Category object, which will schedule a job to create
3282  // the category table row if necessary. Checking a slave is ok
3283  // here, in the worst case it'll run an unnecessary recount job on
3284  // a category that probably doesn't have many members.
3285  Category::newFromTitle( $title )->getID();
3286  }
3287  }
3288 
3294  public static function onArticleDelete( Title $title ) {
3296 
3297  // Update existence markers on article/talk tabs...
3298  $other = $title->getOtherPage();
3299 
3300  $other->purgeSquid();
3301 
3302  $title->touchLinks();
3303  $title->purgeSquid();
3304 
3305  // File cache
3307  InfoAction::invalidateCache( $title );
3308 
3309  // Messages
3310  if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3311  MessageCache::singleton()->replace( $title->getDBkey(), false );
3312 
3313  if ( $wgContLang->hasVariants() ) {
3314  $wgContLang->updateConversionTable( $title );
3315  }
3316  }
3317 
3318  // Images
3319  if ( $title->getNamespace() == NS_FILE ) {
3320  DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3321  }
3322 
3323  // User talk pages
3324  if ( $title->getNamespace() == NS_USER_TALK ) {
3325  $user = User::newFromName( $title->getText(), false );
3326  if ( $user ) {
3327  $user->setNewtalk( false );
3328  }
3329  }
3330 
3331  // Image redirects
3332  RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3333  }
3334 
3341  public static function onArticleEdit( Title $title, Revision $revision = null ) {
3342  // Invalidate caches of articles which include this page
3343  DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3344 
3345  // Invalidate the caches of all pages which redirect here
3346  DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3347 
3348  // Purge CDN for this page only
3349  $title->purgeSquid();
3350  // Clear file cache for this page only
3352 
3353  $revid = $revision ? $revision->getId() : null;
3354  DeferredUpdates::addCallableUpdate( function() use ( $title, $revid ) {
3355  InfoAction::invalidateCache( $title, $revid );
3356  } );
3357  }
3358 
3367  public function getCategories() {
3368  $id = $this->getId();
3369  if ( $id == 0 ) {
3370  return TitleArray::newFromResult( new FakeResultWrapper( [] ) );
3371  }
3372 
3373  $dbr = wfGetDB( DB_SLAVE );
3374  $res = $dbr->select( 'categorylinks',
3375  [ 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ],
3376  // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3377  // as not being aliases, and NS_CATEGORY is numeric
3378  [ 'cl_from' => $id ],
3379  __METHOD__ );
3380 
3381  return TitleArray::newFromResult( $res );
3382  }
3383 
3390  public function getHiddenCategories() {
3391  $result = [];
3392  $id = $this->getId();
3393 
3394  if ( $id == 0 ) {
3395  return [];
3396  }
3397 
3398  $dbr = wfGetDB( DB_SLAVE );
3399  $res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3400  [ 'cl_to' ],
3401  [ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3402  'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ],
3403  __METHOD__ );
3404 
3405  if ( $res !== false ) {
3406  foreach ( $res as $row ) {
3407  $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3408  }
3409  }
3410 
3411  return $result;
3412  }
3413 
3423  public static function getAutosummary( $oldtext, $newtext, $flags ) {
3424  // NOTE: stub for backwards-compatibility. assumes the given text is
3425  // wikitext. will break horribly if it isn't.
3426 
3427  ContentHandler::deprecated( __METHOD__, '1.21' );
3428 
3429  $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3430  $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3431  $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3432 
3433  return $handler->getAutosummary( $oldContent, $newContent, $flags );
3434  }
3435 
3443  public function getAutoDeleteReason( &$hasHistory ) {
3444  return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3445  }
3446 
3455  public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3456  $id = $id ?: $this->getId();
3457  $dbw = wfGetDB( DB_MASTER );
3458  $method = __METHOD__;
3459  // Do this at the end of the commit to reduce lock wait timeouts
3460  $dbw->onTransactionPreCommitOrIdle(
3461  function () use ( $dbw, $added, $deleted, $id, $method ) {
3462  $ns = $this->getTitle()->getNamespace();
3463 
3464  $addFields = [ 'cat_pages = cat_pages + 1' ];
3465  $removeFields = [ 'cat_pages = cat_pages - 1' ];
3466  if ( $ns == NS_CATEGORY ) {
3467  $addFields[] = 'cat_subcats = cat_subcats + 1';
3468  $removeFields[] = 'cat_subcats = cat_subcats - 1';
3469  } elseif ( $ns == NS_FILE ) {
3470  $addFields[] = 'cat_files = cat_files + 1';
3471  $removeFields[] = 'cat_files = cat_files - 1';
3472  }
3473 
3474  if ( count( $added ) ) {
3475  $existingAdded = $dbw->selectFieldValues(
3476  'category',
3477  'cat_title',
3478  [ 'cat_title' => $added ],
3479  $method
3480  );
3481 
3482  // For category rows that already exist, do a plain
3483  // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3484  // to avoid creating gaps in the cat_id sequence.
3485  if ( count( $existingAdded ) ) {
3486  $dbw->update(
3487  'category',
3488  $addFields,
3489  [ 'cat_title' => $existingAdded ],
3490  $method
3491  );
3492  }
3493 
3494  $missingAdded = array_diff( $added, $existingAdded );
3495  if ( count( $missingAdded ) ) {
3496  $insertRows = [];
3497  foreach ( $missingAdded as $cat ) {
3498  $insertRows[] = [
3499  'cat_title' => $cat,
3500  'cat_pages' => 1,
3501  'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3502  'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3503  ];
3504  }
3505  $dbw->upsert(
3506  'category',
3507  $insertRows,
3508  [ 'cat_title' ],
3509  $addFields,
3510  $method
3511  );
3512  }
3513  }
3514 
3515  if ( count( $deleted ) ) {
3516  $dbw->update(
3517  'category',
3518  $removeFields,
3519  [ 'cat_title' => $deleted ],
3520  $method
3521  );
3522  }
3523 
3524  foreach ( $added as $catName ) {
3525  $cat = Category::newFromName( $catName );
3526  Hooks::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3527  }
3528 
3529  foreach ( $deleted as $catName ) {
3530  $cat = Category::newFromName( $catName );
3531  Hooks::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3532  }
3533 
3534  // Refresh counts on categories that should be empty now, to
3535  // trigger possible deletion. Check master for the most
3536  // up-to-date cat_pages.
3537  if ( count( $deleted ) ) {
3538  $rows = $dbw->select(
3539  'category',
3540  [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
3541  [ 'cat_title' => $deleted, 'cat_pages <= 0' ],
3542  $method
3543  );
3544  foreach ( $rows as $row ) {
3545  $cat = Category::newFromRow( $row );
3546  $cat->refreshCounts();
3547  }
3548  }
3549  }
3550  );
3551  }
3552 
3560  if ( wfReadOnly() ) {
3561  return;
3562  }
3563 
3564  if ( !Hooks::run( 'OpportunisticLinksUpdate',
3565  [ $this, $this->mTitle, $parserOutput ]
3566  ) ) {
3567  return;
3568  }
3569 
3570  $config = RequestContext::getMain()->getConfig();
3571 
3572  $params = [
3573  'isOpportunistic' => true,
3574  'rootJobTimestamp' => $parserOutput->getCacheTime()
3575  ];
3576 
3577  if ( $this->mTitle->areRestrictionsCascading() ) {
3578  // If the page is cascade protecting, the links should really be up-to-date
3579  JobQueueGroup::singleton()->lazyPush(
3580  RefreshLinksJob::newPrioritized( $this->mTitle, $params )
3581  );
3582  } elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3583  // Assume the output contains "dynamic" time/random based magic words.
3584  // Only update pages that expired due to dynamic content and NOT due to edits
3585  // to referenced templates/files. When the cache expires due to dynamic content,
3586  // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3587  // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3588  // template/file edit already triggered recursive RefreshLinksJob jobs.
3589  if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3590  // If a page is uncacheable, do not keep spamming a job for it.
3591  // Although it would be de-duplicated, it would still waste I/O.
3593  $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3594  $ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3595  if ( $cache->add( $key, time(), $ttl ) ) {
3596  JobQueueGroup::singleton()->lazyPush(
3597  RefreshLinksJob::newDynamic( $this->mTitle, $params )
3598  );
3599  }
3600  }
3601  }
3602  }
3603 
3613  public function getDeletionUpdates( Content $content = null ) {
3614  if ( !$content ) {
3615  // load content object, which may be used to determine the necessary updates.
3616  // XXX: the content may not be needed to determine the updates.
3617  $content = $this->getContent( Revision::RAW );
3618  }
3619 
3620  if ( !$content ) {
3621  $updates = [];
3622  } else {
3623  $updates = $content->getDeletionUpdates( $this );
3624  }
3625 
3626  Hooks::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3627  return $updates;
3628  }
3629 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:522
getLinksTimestamp()
Get the page_links_updated field.
Definition: WikiPage.php:523
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:797
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:101
static newFromRow($row)
Make a Title object from a DB row.
Definition: Title.php:444
static purgeExpiredRestrictions()
Purge expired restrictions from the page_restrictions table.
Definition: Title.php:2993
setLastEdit(Revision $revision)
Set the latest revision.
Definition: WikiPage.php:620
makeParserOptions($context)
Get parser options suitable for rendering the primary article wikitext.
Definition: WikiPage.php:1982
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:3270
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:1334
touchLinks()
Update page_touched timestamps and send CDN purge messages for pages linking to this title...
Definition: Title.php:4396
$wgArticleCountMethod
Method used to determine if a page in a content namespace should be counted as a valid article...
getFragment()
Get the Title fragment (i.e.
Definition: Title.php:1334
string $mLinksUpdated
Definition: WikiPage.php:83
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:120
the array() calling protocol came about after MediaWiki 1.4rc1.
replaceSectionContent($sectionId, Content $sectionContent, $sectionTitle= '', $edittime=null)
Definition: WikiPage.php:1367
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:278
getLatest()
Get the page_latest field.
Definition: WikiPage.php:534
stdClass $mPreparedEdit
Map of cache fields (text, parser output, ect) for a proposed/new edit.
Definition: WikiPage.php:48
$context
Definition: load.php:43
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:78
getUser($audience=Revision::FOR_PUBLIC, User $user=null)
Definition: WikiPage.php:710
getParserOutput(ParserOptions $parserOptions, $oldid=null)
Get a ParserOutput for the given ParserOptions and revision ID.
Definition: WikiPage.php:1051
$wgUseAutomaticEditSummaries
If user doesn't specify any edit summary when making a an edit, MediaWiki will try to automatically c...
getText()
Get the text form (spaces not underscores) of the main part.
Definition: Title.php:872
clearNotification(&$title, $oldid=0)
Clear the user's notification timestamp for the given title.
Definition: User.php:3688
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:1580
int $mId
Definition: WikiPage.php:53
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
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:58
updateCategoryCounts(array $added, array $deleted, $id=0)
Update all the appropriate counts in the category table, given that we've added the categories $added...
Definition: WikiPage.php:3455
getTimestamp()
Definition: Revision.php:1169
Class the manages updates of *_link tables as well as similar extension-managed tables.
Definition: LinksUpdate.php:30
isAllowedAny()
Check if user is allowed to access a feature / make an action.
Definition: User.php:3546
protectDescription(array $limit, array $expiry)
Builds the description to serve as comment for the edit.
Definition: WikiPage.php:2696
The Message class provides methods which fulfil two basic services:
Definition: Message.php:159
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
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:880
pingLimiter($action= 'edit', $incrBy=1)
Primitive rate limits: enforce maximum actions per time period to put a brake on flooding.
Definition: User.php:1829
Title $mTitle
Definition: WikiPage.php:37
updateRevisionOn($dbw, $revision, $lastRevision=null, $lastRevIsRedirect=null)
Update the page record to point to a newly saved revision.
Definition: WikiPage.php:1191
const EDIT_INTERNAL
Definition: Defines.php:186
clear()
Clear the object.
Definition: WikiPage.php:221
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:3559
$comment
static newFromUserAndLang(User $user, Language $lang)
Get a ParserOptions object from a given user and language.
$source
getMinorEdit()
Returns true if last revision was marked as "minor edit".
Definition: WikiPage.php:780
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:1020
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:1307
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:2588
getContributors()
Get a list of users who have edited this article, not including the user who made the most recent rev...
Definition: WikiPage.php:977
checkFlags($flags)
Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
Definition: WikiPage.php:1449
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:2337
insertProtectNullRevision($revCommentMsg, array $limit, array $expiry, $cascade, $reason, $user=null)
Insert a new null revision for this page.
Definition: WikiPage.php:2628
Represents a title within MediaWiki.
Definition: Title.php:36
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:512
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:4477
getDeletionUpdates(Content $content=null)
Returns a list of updates to be performed when this page is deleted.
Definition: WikiPage.php:3613
string $mTimestamp
Timestamp of the current revision or empty string if not loaded.
Definition: WikiPage.php:73
magic word & $parser
Definition: hooks.txt:2372
$wgUseNPPatrol
Use new page patrolling to check new pages on Special:Newpages.
clearCacheFields()
Clear the object cache fields.
Definition: WikiPage.php:232
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:583
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2139
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
Definition: hooks.txt:981
pageDataFromTitle($dbr, $title, $options=[])
Fetch a page record matching the Title object's namespace and title using a sanitized title string...
Definition: WikiPage.php:318
getActionOverrides()
Definition: WikiPage.php:192
isRedirect()
Tests if the article content represents a redirect.
Definition: WikiPage.php:462
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':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1814
getTitleKey()
Get the user's name escaped by underscores.
Definition: User.php:2175
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:1515
getContentModel()
Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
Definition: WikiPage.php:480
static addCallableUpdate($callable, $type=self::POSTSEND)
Add a callable update.
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:47
checkTouched()
Loads page_touched and returns a value indicating if it should be used.
Definition: WikiPage.php:501
$wgContentHandlerUseDB
Set to false to disable use of the database fields introduced by the ContentHandler facility...
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:43
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:388
getRevision()
Get the latest revision.
Definition: WikiPage.php:629
getContent($audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition: WikiPage.php:650
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:69
getCacheExpiry()
Returns the number of seconds after which this object should expire.
Definition: CacheTime.php:110
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:2570
static getMain()
Static methods.
static singleton()
Get an instance of this class.
Definition: LinkCache.php:65
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:3102
Revision $mLastRevision
Definition: WikiPage.php:68
isAllowed($action= '')
Internal mechanics of testing a permission.
Definition: User.php:3576
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:890
wfWarn($msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
$wgAjaxEditStash
Have clients send edits to be prepared when filling in edit summaries.
getComment($audience=Revision::FOR_PUBLIC, User $user=null)
Definition: WikiPage.php:766
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:1020
getId()
Get revision ID.
Definition: Revision.php:716
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:1020
followRedirect()
Get the Title object or URL this page redirects to.
Definition: WikiPage.php:928
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
getContentHandler()
Returns the content handler appropriate for this revision's content model.
Definition: Revision.php:1150
$summary
doDeleteArticle($reason, $suppress=false, $u1=null, $u2=null, &$error= '', User $user=null)
Same as doDeleteArticleReal(), but returns a simple boolean.
Definition: WikiPage.php:2792
static newNullRevision($dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page's history.
Definition: Revision.php:1640
static newFromRow($row, $from= 'fromdb')
Constructor from a database row.
Definition: WikiPage.php:161
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:3056
Class for handling updates to the site_stats table.
MediaWiki exception.
Definition: MWException.php:26
incEditCount()
Deferred version of incEditCountImmediate()
Definition: User.php:5132
$wgRCWatchCategoryMembership
Treat category membership changes as a RecentChange.
doCreate(Content $content, $flags, User $user, $summary, array $meta)
Definition: WikiPage.php:1855
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:1683
Base interface for content objects.
Definition: Content.php:34
getCacheTime()
Definition: CacheTime.php:50
static newFromTitle($title)
Factory function.
Definition: Category.php:140
getOldestRevision()
Get the Revision object of the oldest revision.
Definition: WikiPage.php:545
Deferrable Update for closure/callback updates via IDatabase::doAtomicSection()
$cache
Definition: mcc.php:33
$params
getHiddenCategories()
Returns a list of hidden categories this page is a member of.
Definition: WikiPage.php:3390
doViewUpdates(User $user, $oldid=0)
Do standard deferred updates after page view (existing or missing page)
Definition: WikiPage.php:1082
getTitle()
Get the title object of the article.
Definition: WikiPage.php:213
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 IP address?
Definition: User.php:824
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:2376
const DB_SLAVE
Definition: Defines.php:46
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 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 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
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead.&$feedLinks conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:312
hasViewableContent()
Check if this page is something we're going to be showing some sort of sensible content for...
Definition: WikiPage.php:453
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
$wgUseRCPatrol
Use RC Patrolling to check for vandalism (from recent changes and watchlists) New pages and new files...
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:913
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:4196
const NS_FILE
Definition: Defines.php:75
static newFromResult($res)
Definition: TitleArray.php:38
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:1601
getInterwiki()
Get the interwiki prefix.
Definition: Title.php:800
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:1816
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:939
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:205
doPurge()
Perform the actions of a page purging.
Definition: WikiPage.php:1101
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:3443
static onArticleEdit(Title $title, Revision $revision=null)
Purge caches on page update etc.
Definition: WikiPage.php:3341
bool $wgPageLanguageUseDB
Enable page language feature Allows setting page language in database.
doDeleteUpdates($id, Content $content=null)
Do some database updates after deletion.
Definition: WikiPage.php:2999
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:748
Class representing a MediaWiki article and history.
Definition: WikiPage.php:31
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:1406
prepareContentForEdit(Content $content, $revision=null, User $user=null, $serialFormat=null, $useCache=true)
Prepare content which is about to be saved.
Definition: WikiPage.php:2025
$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:3367
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:2167
getId()
Get the user's ID.
Definition: User.php:2114
insertOn($dbw)
Insert a new revision into the database, returning the new revision ID number on success and dies hor...
Definition: Revision.php:1371
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:683
insertOn($dbw, $pageId=null)
Insert a new empty page record for this article.
Definition: WikiPage.php:1147
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:1020
static onArticleDelete(Title $title)
Clears caches when article is deleted.
Definition: WikiPage.php:3294
static convertSelectType($type)
Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
Definition: WikiPage.php:173
supportsSections()
Returns true if this page's content model supports sections.
Definition: WikiPage.php:1349
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:1046
updateRedirectOn($dbw, $redirectTitle, $lastRevIsRedirect=null)
Add row to the redirect table if this is a redirect, remove otherwise.
Definition: WikiPage.php:1262
$mDataLoaded
Definition: WikiPage.php:42
static newFromRow($row)
Definition: Revision.php:219
shouldCheckParserCache(ParserOptions $parserOptions, $oldId)
Should the parser cache be used?
Definition: WikiPage.php:1031
getRedirectTarget()
If this page is a redirect, get its target.
Definition: WikiPage.php:841
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:1020
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:1297
static newFromID($id, $from= 'fromdb')
Constructor from a page id.
Definition: WikiPage.php:134
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:1020
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
loadPageData($from= 'fromdb')
Load the object from a given source by title.
Definition: WikiPage.php:348
insertRedirectEntry(Title $rt, $oldLatest=null)
Insert or update the redirect table entry for this page to indicate it redirects to $rt...
Definition: WikiPage.php:902
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:697
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:2816
lockAndGetLatest()
Lock the page row for this title+id and return page_latest (or 0)
Definition: WikiPage.php:2975
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:297
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:776
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).
static newFromRow($row, $title=null)
Factory function, for constructing a Category object from a result set.
Definition: Category.php:173
prepareTextForEdit($text, $revid=null, User $user=null)
Prepare text which is about to be saved.
Definition: WikiPage.php:2004
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:262
static getAutosummary($oldtext, $newtext, $flags)
Return an applicable autosummary if one exists for the given edit.
Definition: WikiPage.php:3423
clearPreparedEdit()
Clear the mPreparedEdit cache field, as may be needed by mutable content types.
Definition: WikiPage.php:252
const NS_USER_TALK
Definition: Defines.php:72
formatExpiry($expiry)
Definition: WikiPage.php:2673
$wgCascadingRestrictionLevels
Restriction levels that can be used with cascading protection.
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:63
__construct(Title $title)
Constructor and clear the article.
Definition: WikiPage.php:89
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:2376
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:503
getText($audience=Revision::FOR_PUBLIC, User $user=null)
Get the text of the current revision.
Definition: WikiPage.php:670
pageDataFromId($dbr, $id, $options=[])
Fetch a page record matching the requested ID.
Definition: WikiPage.php:332
Special handling for category pages.
static singleton()
Get the signleton instance of this class.
purgeSquid()
Purge all applicable CDN URLs.
Definition: Title.php:3563
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:2375
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:2761
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:2376
$wgUser
Definition: Setup.php:801
getCreator($audience=Revision::FOR_PUBLIC, User $user=null)
Get the User object of the user who created the page.
Definition: WikiPage.php:729
protectDescriptionLog(array $limit, array $expiry)
Builds the description to serve as comment for the log entry.
Definition: WikiPage.php:2738