100 $ns =
$title->getNamespace();
103 throw new MWException(
"NS_MEDIA is a virtual namespace; use NS_FILE." );
104 } elseif ( $ns < 0 ) {
105 throw new MWException(
"Invalid or virtual namespace $ns given." );
140 $row = $db->selectRow(
141 'page', self::selectFields(), [
'page_id' => $id ], __METHOD__ );
197 return $content_handler->getActionOverrides();
226 $this->mDataLoaded =
false;
238 $this->mRedirectTarget =
null;
239 $this->mLastRevision =
null;
240 $this->mTouched =
'19700101000000';
241 $this->mLinksUpdated =
'19700101000000';
242 $this->mTimestamp =
'';
243 $this->mIsRedirect =
false;
244 $this->mLatest =
false;
257 $this->mPreparedEdit =
false;
278 'page_links_updated',
284 $fields[] =
'page_content_model';
288 $fields[] =
'page_lang';
307 Hooks::run(
'ArticlePageDataBefore', [ &$wikiPage, &$fields ] );
309 $row =
$dbr->selectRow(
'page', $fields, $conditions, __METHOD__,
$options );
311 Hooks::run(
'ArticlePageDataAfter', [ &$wikiPage, &$row ] );
327 'page_namespace' =>
$title->getNamespace(),
357 if ( is_int(
$from ) && $from <= $this->mDataLoadedFrom ) {
362 if ( is_int(
$from ) ) {
368 &&
wfGetLB()->getServerCount() > 1
369 &&
wfGetLB()->hasOrMadeRecentMasterChanges()
397 $lc->clearLink( $this->mTitle );
400 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
402 $this->mTitle->loadFromRow( $data );
405 $this->mTitle->loadRestrictions( $data->page_restrictions );
407 $this->mId = intval( $data->page_id );
410 $this->mIsRedirect = intval( $data->page_is_redirect );
411 $this->mLatest = intval( $data->page_latest );
414 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
415 $this->mLastRevision =
null;
416 $this->mTimestamp =
'';
419 $lc->addBadLinkObj( $this->mTitle );
421 $this->mTitle->loadFromRow(
false );
428 $this->mDataLoaded =
true;
436 if ( !$this->mDataLoaded ) {
446 if ( !$this->mDataLoaded ) {
449 return $this->mId > 0;
461 return $this->
exists() || $this->mTitle->isAlwaysKnown();
470 if ( !$this->mDataLoaded ) {
492 if (
$rev !==
null ) {
493 return $rev->getContentModel();
495 $title = $this->mTitle->getPrefixedDBkey();
496 wfWarn(
"Page $title exists but has no (visible) revisions!" );
501 return $this->mTitle->getContentModel();
509 if ( !$this->mDataLoaded ) {
520 if ( !$this->mDataLoaded ) {
531 if ( !$this->mDataLoaded ) {
542 if ( !$this->mDataLoaded ) {
560 while ( $continue ) {
561 $row = $db->selectRow(
562 [
'page',
'revision' ],
565 'page_namespace' => $this->mTitle->getNamespace(),
566 'page_title' => $this->mTitle->getDBkey(),
571 'ORDER BY' =>
'rev_timestamp ASC'
591 if ( $this->mLastRevision !==
null ) {
600 if ( $this->mDataLoadedFrom == self::READ_LOCKING ) {
609 } elseif ( $this->mDataLoadedFrom == self::READ_LATEST ) {
628 $this->mLastRevision = $revision;
638 if ( $this->mLastRevision ) {
659 if ( $this->mLastRevision ) {
660 return $this->mLastRevision->getContent( $audience,
$user );
681 if ( $this->mLastRevision ) {
682 return $this->mLastRevision->getText( $audience,
$user );
692 if ( !$this->mTimestamp ) {
719 if ( $this->mLastRevision ) {
720 return $this->mLastRevision->getUser( $audience,
$user );
739 $userName = $revision->getUserText( $audience,
$user );
740 return User::newFromName( $userName,
false );
757 if ( $this->mLastRevision ) {
758 return $this->mLastRevision->getUserText( $audience,
$user );
775 if ( $this->mLastRevision ) {
776 return $this->mLastRevision->getComment( $audience,
$user );
789 if ( $this->mLastRevision ) {
790 return $this->mLastRevision->isMinor();
807 if ( !$this->mTitle->isContentPage() ) {
831 $hasLinks = (bool)count( $editInfo->output->getLinks() );
834 [
'pl_from' => $this->
getId() ], __METHOD__ );
838 return $content->isCountable( $hasLinks );
849 if ( !$this->mTitle->isRedirect() ) {
853 if ( $this->mRedirectTarget !==
null ) {
859 $row =
$dbr->selectRow(
'redirect',
860 [
'rd_namespace',
'rd_title',
'rd_fragment',
'rd_interwiki' ],
861 [
'rd_from' => $this->
getId() ],
866 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
868 $row->rd_namespace, $row->rd_title,
869 $row->rd_fragment, $row->rd_interwiki
897 DeferredUpdates::addCallableUpdate(
function()
use ( $that,
$retval, $latest ) {
898 $that->insertRedirectEntry(
$retval, $latest );
911 $dbw->startAtomic( __METHOD__ );
914 $dbw->replace(
'redirect',
917 'rd_from' => $this->
getId(),
927 $dbw->endAtomic( __METHOD__ );
951 if ( $rt->isExternal() ) {
952 if ( $rt->isLocal() ) {
956 $source = $this->mTitle->getFullURL(
'redirect=no' );
957 return $rt->getFullURL( [
'rdfrom' =>
$source ] );
965 if ( $rt->isSpecialPage() ) {
969 if ( $rt->isValidRedirectTarget() ) {
970 return $rt->getFullURL();
989 if (
$dbr->implicitGroupby() ) {
990 $realNameField =
'user_real_name';
992 $realNameField =
'MIN(user_real_name) AS user_real_name';
995 $tables = [
'revision',
'user' ];
998 'user_id' =>
'rev_user',
999 'user_name' =>
'rev_user_text',
1001 'timestamp' =>
'MAX(rev_timestamp)',
1004 $conds = [
'rev_page' => $this->
getId() ];
1010 $conds[] =
"rev_user != $user";
1012 $conds[] =
"rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1016 $conds[] =
"{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1019 'user' => [
'LEFT JOIN',
'rev_user = user_id' ],
1023 'GROUP BY' => [
'rev_user',
'rev_user_text' ],
1024 'ORDER BY' =>
'timestamp DESC',
1041 && ( $oldId ===
null || $oldId === 0 || $oldId === $this->
getLatest() )
1062 ': using parser cache: ' . ( $useParserCache ?
'yes' :
'no' ) .
"\n" );
1067 if ( $useParserCache ) {
1074 if ( $oldid ===
null || $oldid === 0 ) {
1081 return $pool->getParserOutput();
1094 Hooks::run(
'PageViewUpdates', [ $this,
$user ] );
1097 $user->clearNotification( $this->mTitle, $oldid );
1100 MWExceptionHandler::logException(
$e );
1112 if ( !Hooks::run(
'ArticlePurge', [ &$wikiPage ] ) ) {
1119 $title->invalidateCache();
1123 DeferredUpdates::addUpdate(
1125 DeferredUpdates::PRESEND
1137 if ( $text ===
null ) {
1163 $pageIdForInsert = $pageId ?: $dbw->nextSequenceValue(
'page_page_id_seq' );
1167 'page_id' => $pageIdForInsert,
1168 'page_namespace' => $this->mTitle->getNamespace(),
1169 'page_title' => $this->mTitle->getDBkey(),
1170 'page_restrictions' =>
'',
1171 'page_is_redirect' => 0,
1174 'page_touched' => $dbw->timestamp(),
1182 if ( $dbw->affectedRows() > 0 ) {
1183 $newid = $pageId ?: $dbw->insertId();
1184 $this->mId = $newid;
1185 $this->mTitle->resetArticleID( $newid );
1207 $lastRevIsRedirect =
null
1212 if ( (
int)$revision->getId() === 0 ) {
1213 throw new InvalidArgumentException(
1214 __METHOD__ .
': Revision has ID ' . var_export( $revision->getId(), 1 )
1218 $content = $revision->getContent();
1222 $conditions = [
'page_id' => $this->
getId() ];
1224 if ( !is_null( $lastRevision ) ) {
1226 $conditions[
'page_latest'] = $lastRevision;
1230 'page_latest' => $revision->getId(),
1231 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1232 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1233 'page_is_redirect' => $rt !==
null ? 1 : 0,
1238 $row[
'page_content_model'] = $revision->getContentModel();
1241 $dbw->update(
'page',
1246 $result = $dbw->affectedRows() > 0;
1250 $this->mLatest = $revision->getId();
1251 $this->mIsRedirect = (bool)$rt;
1259 $revision->getContentModel()
1281 $isRedirect = !is_null( $redirectTitle );
1283 if ( !$isRedirect && $lastRevIsRedirect ===
false ) {
1287 if ( $isRedirect ) {
1291 $where = [
'rd_from' => $this->
getId() ];
1292 $dbw->delete(
'redirect', $where, __METHOD__ );
1299 return ( $dbw->affectedRows() != 0 );
1314 $row = $dbw->selectRow(
1315 [
'revision',
'page' ],
1316 [
'rev_id',
'rev_timestamp',
'page_is_redirect' ],
1318 'page_id' => $this->
getId(),
1319 'page_latest=rev_id' ],
1323 if (
wfTimestamp(
TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1326 $prev = $row->rev_id;
1327 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1331 $lastRevIsRedirect =
null;
1387 if ( $edittime && $sectionId !==
'new' ) {
1394 &&
wfGetLB()->getServerCount() > 1
1395 &&
wfGetLB()->hasOrMadeRecentMasterChanges()
1401 $baseRevId =
$rev->getId();
1422 $sectionTitle =
'', $baseRevId =
null
1425 if ( strval( $sectionId ) ===
'' ) {
1430 throw new MWException(
"sections not supported for content model " .
1435 if ( is_null( $baseRevId ) || $sectionId ===
'new' ) {
1440 wfDebug( __METHOD__ .
" asked for bogus section (page: " .
1441 $this->
getId() .
"; section: $sectionId)\n" );
1445 $oldContent =
$rev->getContent();
1448 if ( !$oldContent ) {
1449 wfDebug( __METHOD__ .
": no page text\n" );
1453 $newContent = $oldContent->replaceSection( $sectionId,
$sectionContent, $sectionTitle );
1593 User $user =
null, $serialFormat =
null, $tags =
null
1598 if ( $this->mTitle->getText() ===
'' ) {
1599 throw new MWException(
'Something is trying to edit an article with an empty title' );
1602 if ( !
$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1603 return Status::newFatal(
'content-not-allowed-here',
1605 $this->mTitle->getPrefixedText()
1621 $hookStatus = Status::newGood( [] );
1625 if ( !Hooks::run(
'PageContentSave', $hook_args )
1628 if ( $hookStatus->isOK() ) {
1630 $hookStatus->fatal(
'edit-hook-aborted' );
1647 $pstContent = $editInfo->pstContent;
1651 'serialized' => $editInfo->pst,
1652 'serialFormat' => $serialFormat,
1653 'baseRevId' => $baseRevId,
1654 'oldRevision' => $old_revision,
1655 'oldContent' => $old_content,
1659 'tags' => ( $tags !== null ) ? (
array)$tags : []
1670 DeferredUpdates::addCallableUpdate(
function ()
use (
$user ) {
1671 $user->addAutopromoteOnceGroups(
'onEdit' );
1672 $user->addAutopromoteOnceGroups(
'onView' );
1696 $status = Status::newGood( [
'new' =>
false,
'revision' =>
null ] );
1700 $oldid = $meta[
'oldId'];
1702 $oldContent = $meta[
'oldContent'];
1707 $status->fatal(
'edit-gone-missing' );
1710 } elseif ( !$oldContent ) {
1712 throw new MWException(
"Could not find text for current revision {$oldid}." );
1717 'page' => $this->
getId(),
1718 'title' => $this->mTitle,
1720 'minor_edit' => $meta[
'minor'],
1721 'text' => $meta[
'serialized'],
1723 'parent_id' => $oldid,
1724 'user' =>
$user->getId(),
1725 'user_text' =>
$user->getName(),
1726 'timestamp' => $now,
1727 'content_model' =>
$content->getModel(),
1728 'content_format' => $meta[
'serialFormat'],
1731 $changed = !
$content->equals( $oldContent );
1737 $status->merge( $prepStatus );
1742 $dbw->startAtomic( __METHOD__ );
1747 if ( $latestNow != $oldid ) {
1748 $dbw->endAtomic( __METHOD__ );
1750 $status->fatal(
'edit-conflict' );
1761 $revisionId = $revision->insertOn( $dbw );
1763 if ( !$this->
updateRevisionOn( $dbw, $revision,
null, $meta[
'oldIsRedirect'] ) ) {
1764 $dbw->rollback( __METHOD__ );
1765 throw new MWException(
"Failed to update page row to use new revision." );
1768 Hooks::run(
'NewRevisionFromEditComplete',
1769 [ $this, $revision, $meta[
'baseRevId'],
$user ] );
1775 $this->mTitle->getUserPermissionsErrors(
'autopatrol',
$user ) );
1780 $revision->isMinor(),
1784 $this->getTimestamp(),
1787 $oldContent ? $oldContent->getSize() : 0,
1795 $user->incEditCount();
1797 $dbw->endAtomic( __METHOD__ );
1798 $this->mTimestamp = $now;
1807 $status->value[
'revision'] = $revision;
1809 $status->warning(
'edit-no-change' );
1812 $this->mTitle->invalidateCache( $now );
1817 $dbw->onTransactionIdle(
1825 $that->doEditUpdates(
1829 'changed' => $changed,
1830 'oldcountable' => $meta[
'oldCountable'],
1831 'oldrevision' => $meta[
'oldRevision']
1836 null,
null, &
$flags, $revision, &
$status, $meta[
'baseRevId'] ];
1838 Hooks::run(
'PageContentSaveComplete',
$params );
1862 $status = Status::newGood( [
'new' =>
true,
'revision' =>
null ] );
1867 $status->merge( $prepStatus );
1873 $dbw->startAtomic( __METHOD__ );
1877 if ( $newid ===
false ) {
1878 $dbw->endAtomic( __METHOD__ );
1879 $status->fatal(
'edit-already-exists' );
1892 'title' => $this->mTitle,
1894 'minor_edit' => $meta[
'minor'],
1895 'text' => $meta[
'serialized'],
1897 'user' =>
$user->getId(),
1898 'user_text' =>
$user->getName(),
1899 'timestamp' => $now,
1900 'content_model' =>
$content->getModel(),
1901 'content_format' => $meta[
'serialFormat'],
1905 $revisionId = $revision->insertOn( $dbw );
1908 $dbw->rollback( __METHOD__ );
1909 throw new MWException(
"Failed to update page row to use new revision." );
1912 Hooks::run(
'NewRevisionFromEditComplete', [ $this, $revision,
false,
$user ] );
1918 !count( $this->mTitle->getUserPermissionsErrors(
'autopatrol',
$user ) );
1923 $revision->isMinor(),
1935 $user->incEditCount();
1937 $dbw->endAtomic( __METHOD__ );
1938 $this->mTimestamp = $now;
1941 $status->value[
'revision'] = $revision;
1945 $dbw->onTransactionIdle(
1952 $that->doEditUpdates( $revision,
$user, [
'created' =>
true ] );
1957 Hooks::run(
'PageContentInsertComplete',
$params );
1961 Hooks::run(
'PageContentSaveComplete',
$params );
1985 if ( $this->
getTitle()->isConversionTable() ) {
1988 $options->disableContentConversion();
2027 $serialFormat =
null, $useCache =
true
2031 if ( is_object( $revision ) ) {
2032 $revid = $revision->getId();
2037 if ( $revid !==
null ) {
2048 if ( $serialFormat ===
null ) {
2049 $serialFormat =
$content->getContentHandler()->getDefaultFormat();
2052 if ( $this->mPreparedEdit
2053 && $this->mPreparedEdit->newContent
2054 && $this->mPreparedEdit->newContent->equals(
$content )
2055 && $this->mPreparedEdit->revid == $revid
2056 && $this->mPreparedEdit->format == $serialFormat
2069 Hooks::run(
'ArticlePrepareTextForEdit', [ $this, $popts ] );
2072 if ( $cachedEdit ) {
2073 $edit->timestamp = $cachedEdit->timestamp;
2078 $edit->revid = $revid;
2080 if ( $cachedEdit ) {
2081 $edit->pstContent = $cachedEdit->pstContent;
2084 ?
$content->preSaveTransform( $this->mTitle,
$user, $popts )
2088 $edit->format = $serialFormat;
2090 if ( $cachedEdit ) {
2091 $edit->output = $cachedEdit->output;
2098 $oldCallback = $edit->popts->getCurrentRevisionCallback();
2099 $edit->popts->setCurrentRevisionCallback(
2101 if (
$title->equals( $revision->getTitle() ) ) {
2104 return call_user_func( $oldCallback, $title, $parser );
2109 $edit->output = $edit->pstContent
2110 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2118 $edit->newText = $edit->newContent
2121 $edit->oldText = $edit->oldContent
2124 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) :
'';
2126 if ( $edit->output ) {
2131 $this->mPreparedEdit = $edit;
2164 'restored' =>
false,
2165 'oldrevision' =>
null,
2166 'oldcountable' => null
2173 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag(
'vary-revision' ) ) {
2174 wfDebug( __METHOD__ .
": No prepared edit or vary-revision is set...\n" );
2177 wfDebug( __METHOD__ .
": No vary-revision, using prepared edit...\n" );
2184 $editInfo->output, $this, $editInfo->popts,
2191 $updates =
$content->getSecondaryDataUpdates(
2192 $this->
getTitle(),
null, $recursive, $editInfo->output
2194 foreach ( $updates
as $update ) {
2196 $update->setRevision( $revision );
2197 $update->setTriggeringUser(
$user );
2199 DeferredUpdates::addUpdate( $update );
2212 'pageId' => $this->
getId(),
2222 Hooks::run(
'ArticleEditUpdates', [ &$wikiPage, &$editInfo,
$options[
'changed'] ] );
2224 if ( Hooks::run(
'ArticleEditUpdatesDeleteFromRecentchanges', [ &$wikiPage ] ) ) {
2226 if ( mt_rand( 0, 9 ) == 0 ) {
2231 if ( !$this->
exists() ) {
2235 $id = $this->
getId();
2236 $title = $this->mTitle->getPrefixedDBkey();
2237 $shortTitle = $this->mTitle->getDBkey();
2239 if (
$options[
'oldcountable'] ===
'no-change' ||
2245 } elseif (
$options[
'oldcountable'] !==
null ) {
2250 $edits =
$options[
'changed'] ? 1 : 0;
2251 $total =
$options[
'created'] ? 1 : 0;
2253 DeferredUpdates::addUpdate(
new SiteStatsUpdate( 0, $edits, $good, $total ) );
2261 && $shortTitle !=
$user->getTitleKey()
2262 && !( $revision->
isMinor() &&
$user->isAllowed(
'nominornewtalk' ) )
2264 $recipient = User::newFromName( $shortTitle,
false );
2265 if ( !$recipient ) {
2266 wfDebug( __METHOD__ .
": invalid username\n" );
2273 if ( Hooks::run(
'ArticleEditUpdateNewTalk', [ &$wikiPage, $recipient ] ) ) {
2274 if ( User::isIP( $shortTitle ) ) {
2276 $recipient->setNewtalk(
true, $revision );
2277 } elseif ( $recipient->isLoggedIn() ) {
2278 $recipient->setNewtalk(
true, $revision );
2280 wfDebug( __METHOD__ .
": don't need to notify a nonexistent user\n" );
2289 if ( $msgtext ===
false || $msgtext ===
null ) {
2296 $wgContLang->updateConversionTable( $this->mTitle );
2327 'page' => $this->
getId(),
2328 'user_text' => $user->
getName(),
2329 'user' =>
$user->getId(),
2333 'minor_edit' => $minor ? 1 : 0,
2338 Hooks::run(
'NewRevisionFromEditComplete', [ $this, $revision,
false,
$user ] );
2357 &$cascade, $reason,
User $user, $tags =
null
2366 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2367 $id = $this->
getId();
2378 $isProtected =
false;
2384 foreach ( $restrictionTypes
as $action ) {
2385 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2386 $expiry[$action] =
'infinity';
2388 if ( !isset(
$limit[$action] ) ) {
2390 } elseif (
$limit[$action] !=
'' ) {
2395 $current = implode(
'', $this->mTitle->getRestrictions( $action ) );
2396 if ( $current !=
'' ) {
2397 $isProtected =
true;
2400 if (
$limit[$action] != $current ) {
2402 } elseif (
$limit[$action] !=
'' ) {
2406 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2412 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2418 return Status::newGood();
2422 $revCommentMsg =
'unprotectedarticle';
2423 $logAction =
'unprotect';
2424 } elseif ( $isProtected ) {
2425 $revCommentMsg =
'modifiedarticleprotection';
2426 $logAction =
'modify';
2428 $revCommentMsg =
'protectedarticle';
2429 $logAction =
'protect';
2435 $logRelationsValues = [];
2436 $logRelationsField =
null;
2437 $logParamsDetails = [];
2440 $nullRevision =
null;
2446 if ( !Hooks::run(
'ArticleProtect', [ &$wikiPage, &
$user,
$limit, $reason ] ) ) {
2447 return Status::newGood();
2451 $editrestriction = isset(
$limit[
'edit'] )
2453 : $this->mTitle->getRestrictions(
'edit' );
2454 foreach ( array_keys( $editrestriction,
'sysop' )
as $key ) {
2455 $editrestriction[$key] =
'editprotected';
2457 foreach ( array_keys( $editrestriction,
'autoconfirmed' )
as $key ) {
2458 $editrestriction[$key] =
'editsemiprotected';
2462 foreach ( array_keys( $cascadingRestrictionLevels,
'sysop' )
as $key ) {
2463 $cascadingRestrictionLevels[$key] =
'editprotected';
2465 foreach ( array_keys( $cascadingRestrictionLevels,
'autoconfirmed' )
as $key ) {
2466 $cascadingRestrictionLevels[$key] =
'editsemiprotected';
2470 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2485 if ( $nullRevision ===
null ) {
2486 return Status::newFatal(
'no-null-revision', $this->mTitle->getPrefixedText() );
2489 $logRelationsField =
'pr_id';
2492 foreach (
$limit as $action => $restrictions ) {
2494 'page_restrictions',
2497 'pr_type' => $action
2501 if ( $restrictions !=
'' ) {
2502 $cascadeValue = ( $cascade && $action ==
'edit' ) ? 1 : 0;
2504 'page_restrictions',
2506 'pr_id' => $dbw->nextSequenceValue(
'page_restrictions_pr_id_seq' ),
2508 'pr_type' => $action,
2509 'pr_level' => $restrictions,
2510 'pr_cascade' => $cascadeValue,
2511 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2515 $logRelationsValues[] = $dbw->insertId();
2516 $logParamsDetails[] = [
2518 'level' => $restrictions,
2519 'expiry' => $expiry[$action],
2520 'cascade' => (bool)$cascadeValue,
2528 [
'page_restrictions' =>
'' ],
2529 [
'page_id' => $id ],
2536 Hooks::run(
'NewRevisionFromEditComplete',
2537 [ $this, $nullRevision, $latest,
$user ] );
2538 Hooks::run(
'ArticleProtectComplete', [ &$wikiPage, &
$user,
$limit, $reason ] );
2543 if (
$limit[
'create'] !=
'' ) {
2544 $dbw->replace(
'protected_titles',
2545 [ [
'pt_namespace',
'pt_title' ] ],
2547 'pt_namespace' => $this->mTitle->getNamespace(),
2548 'pt_title' => $this->mTitle->getDBkey(),
2549 'pt_create_perm' =>
$limit[
'create'],
2550 'pt_timestamp' => $dbw->timestamp(),
2551 'pt_expiry' => $dbw->encodeExpiry( $expiry[
'create'] ),
2552 'pt_user' =>
$user->getId(),
2553 'pt_reason' => $reason,
2556 $logParamsDetails[] = [
2558 'level' =>
$limit[
'create'],
2559 'expiry' => $expiry[
'create'],
2562 $dbw->delete(
'protected_titles',
2564 'pt_namespace' => $this->mTitle->getNamespace(),
2565 'pt_title' => $this->mTitle->getDBkey()
2571 $this->mTitle->flushRestrictions();
2574 if ( $logAction ==
'unprotect' ) {
2579 '4::description' => $protectDescriptionLog,
2580 '5:bool:cascade' => $cascade,
2581 'details' => $logParamsDetails,
2587 $logEntry->setTarget( $this->mTitle );
2588 $logEntry->setComment( $reason );
2589 $logEntry->setPerformer(
$user );
2590 $logEntry->setParameters(
$params );
2591 if ( !is_null( $nullRevision ) ) {
2592 $logEntry->setAssociatedRevId( $nullRevision->getId() );
2594 $logEntry->setTags( $tags );
2595 if ( $logRelationsField !==
null && count( $logRelationsValues ) ) {
2596 $logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2598 $logId = $logEntry->insert();
2599 $logEntry->publish( $logId );
2601 return Status::newGood( $logId );
2616 array $expiry, $cascade, $reason, $user =
null
2625 $this->mTitle->getPrefixedText()
2626 )->inContentLanguage()->text()
2629 $editComment .=
wfMessage(
'colon-separator' )->inContentLanguage()->text() . $reason;
2632 if ( $protectDescription ) {
2633 $editComment .=
wfMessage(
'word-separator' )->inContentLanguage()->text();
2634 $editComment .=
wfMessage(
'parentheses' )->params( $protectDescription )
2635 ->inContentLanguage()->text();
2638 $editComment .=
wfMessage(
'word-separator' )->inContentLanguage()->text();
2639 $editComment .=
wfMessage(
'brackets' )->params(
2640 wfMessage(
'protect-summary-cascade' )->inContentLanguage()->
text()
2641 )->inContentLanguage()->text();
2646 $nullRev->insertOn( $dbw );
2649 $oldLatest = $nullRev->getParentId();
2663 if ( $expiry !=
'infinity' ) {
2666 $wgContLang->timeanddate( $expiry,
false,
false ),
2669 )->inContentLanguage()->text();
2671 return wfMessage(
'protect-expiry-indefinite' )
2672 ->inContentLanguage()->text();
2684 $protectDescription =
'';
2686 foreach ( array_filter(
$limit )
as $action => $restrictions ) {
2687 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2688 # All possible message keys are listed here for easier grepping:
2689 # * restriction-create
2690 # * restriction-edit
2691 # * restriction-move
2692 # * restriction-upload
2693 $actionText =
wfMessage(
'restriction-' . $action )->inContentLanguage()->text();
2694 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2695 # with '' filtered out. All possible message keys are listed below:
2696 # * protect-level-autoconfirmed
2697 # * protect-level-sysop
2698 $restrictionsText =
wfMessage(
'protect-level-' . $restrictions )
2699 ->inContentLanguage()->text();
2703 if ( $protectDescription !==
'' ) {
2704 $protectDescription .=
wfMessage(
'word-separator' )->inContentLanguage()->text();
2706 $protectDescription .=
wfMessage(
'protect-summary-desc' )
2707 ->params( $actionText, $restrictionsText, $expiryText )
2708 ->inContentLanguage()->text();
2711 return $protectDescription;
2728 $protectDescriptionLog =
'';
2730 foreach ( array_filter(
$limit )
as $action => $restrictions ) {
2732 $protectDescriptionLog .=
$wgContLang->getDirMark() .
2733 "[$action=$restrictions] ($expiryText)";
2736 return trim( $protectDescriptionLog );
2749 if ( !is_array(
$limit ) ) {
2750 throw new MWException( __METHOD__ .
' given non-array restriction set' );
2756 foreach ( array_filter(
$limit )
as $action => $restrictions ) {
2757 $bits[] =
"$action=$restrictions";
2760 return implode(
':', $bits );
2780 $reason, $suppress =
false, $u1 =
null, $u2 =
null, &$error =
'',
User $user =
null
2804 $reason, $suppress =
false, $u1 =
null, $u2 =
null, &$error =
'',
User $user =
null
2812 if ( $this->mTitle->getDBkey() ===
'' ) {
2813 $status->error(
'cannotdelete',
2822 if ( !Hooks::run(
'ArticleDelete',
2823 [ &$wikiPage, &
$user, &$reason, &$error, &
$status, $suppress ]
2827 $status->fatal(
'delete-hook-aborted' );
2833 $dbw->startAtomic( __METHOD__ );
2836 $id = $this->
getId();
2842 if ( $id == 0 || $this->
getLatest() != $lockedLatest ) {
2843 $dbw->endAtomic( __METHOD__ );
2845 $status->error(
'cannotdelete',
2867 $bitfield =
'rev_deleted';
2884 'ar_namespace' =>
'page_namespace',
2885 'ar_title' =>
'page_title',
2886 'ar_comment' =>
'rev_comment',
2887 'ar_user' =>
'rev_user',
2888 'ar_user_text' =>
'rev_user_text',
2889 'ar_timestamp' =>
'rev_timestamp',
2890 'ar_minor_edit' =>
'rev_minor_edit',
2891 'ar_rev_id' =>
'rev_id',
2892 'ar_parent_id' =>
'rev_parent_id',
2893 'ar_text_id' =>
'rev_text_id',
2894 'ar_text' =>
'\'\
'',
2895 'ar_flags' =>
'\'\
'',
2896 'ar_len' =>
'rev_len',
2897 'ar_page_id' =>
'page_id',
2898 'ar_deleted' => $bitfield,
2899 'ar_sha1' =>
'rev_sha1',
2903 $row[
'ar_content_model'] =
'rev_content_model';
2904 $row[
'ar_content_format'] =
'rev_content_format';
2910 [
'page',
'revision' ],
2914 'page_id = rev_page'
2920 $dbw->delete(
'page', [
'page_id' => $id ], __METHOD__ );
2922 if ( !$dbw->cascadingDeletes() ) {
2923 $dbw->delete(
'revision', [
'rev_page' => $id ], __METHOD__ );
2930 $logtype = $suppress ?
'suppress' :
'delete';
2933 $logEntry->setPerformer(
$user );
2934 $logEntry->setTarget( $logTitle );
2935 $logEntry->setComment( $reason );
2936 $logid = $logEntry->insert();
2938 $dbw->onTransactionPreCommitOrIdle(
function ()
use ( $dbw, $logEntry, $logid ) {
2940 $logEntry->publish( $logid );
2943 $dbw->endAtomic( __METHOD__ );
2949 Hooks::run(
'ArticleDeleteComplete',
2955 $key =
wfMemcKey(
'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2956 $cache->set( $key, 1, $cache::TTL_DAY );
2972 'page_id' => $this->
getId(),
2975 'page_namespace' => $this->
getTitle()->getNamespace(),
2976 'page_title' => $this->
getTitle()->getDBkey()
2997 foreach ( $updates
as $update ) {
2998 DeferredUpdates::addUpdate( $update );
3005 if ( $this->mTitle->getNamespace() ==
NS_FILE ) {
3016 DeferredUpdates::addUpdate(
new SearchUpdate( $id, $this->mTitle ) );
3048 $fromP,
$summary, $token, $bot, &$resultDetails,
User $user, $tags =
null
3050 $resultDetails =
null;
3053 $editErrors = $this->mTitle->getUserPermissionsErrors(
'edit',
$user );
3054 $rollbackErrors = $this->mTitle->getUserPermissionsErrors(
'rollback',
$user );
3055 $errors = array_merge( $editErrors,
wfArrayDiff2( $rollbackErrors, $editErrors ) );
3057 if ( !
$user->matchEditToken( $token, [ $this->mTitle->getPrefixedText(), $fromP ] ) ) {
3058 $errors[] = [
'sessionfailure' ];
3061 if (
$user->pingLimiter(
'rollback' ) ||
$user->pingLimiter() ) {
3062 $errors[] = [
'actionthrottledtext' ];
3066 if ( !empty( $errors ) ) {
3094 &$resultDetails,
User $guser, $tags =
null
3101 return [ [
'readonlytext' ] ];
3106 if ( is_null( $current ) ) {
3108 return [ [
'notanarticle' ] ];
3111 $from = str_replace(
'_',
' ', $fromP );
3114 if (
$from != $current->getUserText() ) {
3115 $resultDetails = [
'current' => $current ];
3116 return [ [
'alreadyrolled',
3117 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3118 htmlspecialchars( $fromP ),
3119 htmlspecialchars( $current->getUserText() )
3126 $user_text = $dbw->addQuotes( $current->getUserText(
Revision::RAW ) );
3127 $s = $dbw->selectRow(
'revision',
3128 [
'rev_id',
'rev_timestamp',
'rev_deleted' ],
3129 [
'rev_page' => $current->getPage(),
3130 "rev_user != {$user} OR rev_user_text != {$user_text}"
3132 [
'USE INDEX' =>
'page_timestamp',
3133 'ORDER BY' =>
'rev_timestamp DESC' ]
3135 if (
$s ===
false ) {
3137 return [ [
'cantrollback' ] ];
3142 return [ [
'notvisiblerev' ] ];
3148 if (
$from ==
'' ) {
3157 $target->getUserText(),
$from,
$s->rev_id,
3159 $current->getId(),
$wgContLang->timeanddate( $current->getTimestamp() )
3176 if ( $guser->
isAllowed(
'minoredit' ) ) {
3180 if ( $bot && ( $guser->
isAllowedAny(
'markbotedits',
'bot' ) ) ) {
3186 $target->getContent(),
3198 if ( $bot && $guser->
isAllowed(
'markbotedits' ) ) {
3205 $set[
'rc_patrolled'] = 1;
3208 if ( count( $set ) ) {
3209 $dbw->update(
'recentchanges', $set,
3211 'rc_cur_id' => $current->getPage(),
3212 'rc_user_text' => $current->getUserText(),
3213 'rc_timestamp > ' . $dbw->addQuotes(
$s->rev_timestamp ),
3220 return $status->getErrorsArray();
3224 $statusRev = isset(
$status->value[
'revision'] )
3227 if ( !( $statusRev instanceof
Revision ) ) {
3228 $resultDetails = [
'current' => $current ];
3229 return [ [
'alreadyrolled',
3230 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3231 htmlspecialchars( $fromP ),
3232 htmlspecialchars( $current->getUserText() )
3236 $revId = $statusRev->getId();
3238 Hooks::run(
'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3242 'current' => $current,
3243 'target' => $target,
3263 $other =
$title->getOtherPage();
3265 $other->purgeSquid();
3269 $title->deleteTitleProtection();
3281 $other =
$title->getOtherPage();
3283 $other->purgeSquid();
3308 $user = User::newFromName(
$title->getText(),
false );
3310 $user->setNewtalk(
false );
3336 $revid = $revision ? $revision->getId() :
null;
3337 DeferredUpdates::addCallableUpdate(
function()
use (
$title, $revid ) {
3351 $id = $this->
getId();
3357 $res =
$dbr->select(
'categorylinks',
3358 [
'cl_to AS page_title, ' .
NS_CATEGORY .
' AS page_namespace' ],
3361 [
'cl_from' => $id ],
3375 $id = $this->
getId();
3382 $res =
$dbr->select( [
'categorylinks',
'page_props',
'page' ],
3384 [
'cl_from' => $id,
'pp_page=page_id',
'pp_propname' =>
'hiddencat',
3385 'page_namespace' =>
NS_CATEGORY,
'page_title=cl_to' ],
3388 if (
$res !==
false ) {
3389 foreach (
$res as $row ) {
3413 $oldContent = is_null( $oldtext ) ? null :
$handler->unserializeContent( $oldtext );
3414 $newContent = is_null( $newtext ) ? null :
$handler->unserializeContent( $newtext );
3416 return $handler->getAutosummary( $oldContent, $newContent,
$flags );
3439 $method = __METHOD__;
3443 $dbw->onTransactionPreCommitOrIdle(
3444 function ()
use ( $dbw, $that, $method, $added, $deleted ) {
3445 $ns = $that->getTitle()->getNamespace();
3447 $addFields = [
'cat_pages = cat_pages + 1' ];
3448 $removeFields = [
'cat_pages = cat_pages - 1' ];
3450 $addFields[] =
'cat_subcats = cat_subcats + 1';
3451 $removeFields[] =
'cat_subcats = cat_subcats - 1';
3453 $addFields[] =
'cat_files = cat_files + 1';
3454 $removeFields[] =
'cat_files = cat_files - 1';
3457 if ( count( $added ) ) {
3458 $existingAdded = $dbw->selectFieldValues(
3461 [
'cat_title' => $added ],
3468 if ( count( $existingAdded ) ) {
3472 [
'cat_title' => $existingAdded ],
3477 $missingAdded = array_diff( $added, $existingAdded );
3478 if ( count( $missingAdded ) ) {
3480 foreach ( $missingAdded
as $cat ) {
3482 'cat_title' => $cat,
3485 'cat_files' => ( $ns ==
NS_FILE ) ? 1 : 0,
3498 if ( count( $deleted ) ) {
3502 [
'cat_title' => $deleted ],
3507 foreach ( $added
as $catName ) {
3509 Hooks::run(
'CategoryAfterPageAdded', [ $cat, $that ] );
3512 foreach ( $deleted
as $catName ) {
3514 Hooks::run(
'CategoryAfterPageRemoved', [ $cat, $that ] );
3531 if ( !Hooks::run(
'OpportunisticLinksUpdate',
3540 'isOpportunistic' =>
true,
3544 if ( $this->mTitle->areRestrictionsCascading() ) {
3549 } elseif ( !$config->get(
'MiserMode' ) &&
$parserOutput->hasDynamicContent() ) {
3560 $key =
$cache->makeKey(
'dynamic-linksupdate',
'last', $this->
getId() );
3562 if (
$cache->add( $key, time(), $ttl ) ) {
3590 $updates =
$content->getDeletionUpdates( $this );
3593 Hooks::run(
'WikiPageDeletionUpdates', [ $this,
$content, &$updates ] );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
bool $wgPageLanguageUseDB
Enable page language feature Allows setting page language in database.
$wgCascadingRestrictionLevels
Restriction levels that can be used with cascading protection.
$wgUseAutomaticEditSummaries
If user doesn't specify any edit summary when making a an edit, MediaWiki will try to automatically c...
$wgUseRCPatrol
Use RC Patrolling to check for vandalism (from recent changes and watchlists) New pages and new files...
$wgUseNPPatrol
Use new page patrolling to check new pages on Special:Newpages.
$wgArticleCountMethod
Method used to determine if a page in a content namespace should be counted as a valid article.
$wgAjaxEditStash
Have clients send edits to be prepared when filling in edit summaries.
$wgRCWatchCategoryMembership
Treat category membership changes as a RecentChange.
$wgContentHandlerUseDB
Set to false to disable use of the database fields introduced by the ContentHandler facility.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfRandom()
Get a random decimal value between 0 and 1, in a way not likely to give duplicate values for any real...
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfIncrStats( $key, $count=1)
Increment a statistics counter.
wfGetLB( $wiki=false)
Get a load balancer object.
wfReadOnly()
Check whether the wiki is in read-only mode.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfMemcKey()
Make a cache key for the local wiki.
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
static checkCache(Title $title, Content $content, User $user)
Check that a prepared edit is in cache and still up-to-date.
Job to add recent change entries mentioning category membership changes.
static newFromName( $name)
Factory function.
Handles purging appropriate CDN URLs given a title (or titles)
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
static runLegacyHooks( $event, $args=[], $warn=null)
Call a legacy hook that uses text instead of Content objects.
static getLocalizedName( $name, Language $lang=null)
Returns the localized name for a given content model.
static getContentText(Content $content=null)
Convenience function for getting flat text from a Content object.
static deprecated( $func, $version, $component=false)
Logs a deprecation warning, visible if $wgDevelopmentWarnings, but only if self::$enableDeprecationWa...
static getDBOptions( $bitfield)
Get an appropriate DB index and options for a query.
Database error base class.
Overloads the relevant methods of the real ResultsWrapper so it doesn't go anywhere near an actual da...
Class to invalidate the HTML cache of all the pages linking to a given title.
static clearFileCache(Title $title)
Clear the file caches for a page for all actions.
static invalidateCache(Title $title, $revid=null)
Clear the info cache for a given Title.
static singleton( $wiki=false)
static singleton()
Get an instance of this class.
static queueRecursiveJobsForTable(Title $title, $table)
Queue a RefreshLinks job for any table.
Class for creating log entries manually, to inject them into the database.
static singleton()
Get the signleton instance of this class.
The Message class provides methods which fulfil two basic services:
static getMainStashInstance()
Get the cache object for the main stash.
static getLocalClusterInstance()
Get the main cluster-local cache object.
static singleton()
Get an instance of this object.
Set options of the Parser.
static newFromUserAndLang(User $user, Language $lang)
Get a ParserOptions object from a given user and language.
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...
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.
static newPrioritized(Title $title, array $params)
static newDynamic(Title $title, array $params)
static singleton()
Get a RepoGroup instance.
static getMain()
Static methods.
getContentHandler()
Returns the content handler appropriate for this revision's content model.
static newFromPageId( $pageId, $revId=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given page ID.
static selectFields()
Return the list of revision fields that should be selected to create a new revision.
static loadFromTimestamp( $db, $title, $timestamp)
Load the revision for the given title with the given timestamp.
static newNullRevision( $dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page's history.
getContent( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision content if it's available to the specified audience.
insertOn( $dbw)
Insert a new revision into the database, returning the new revision ID number on success and dies hor...
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Database independant search index updater.
Class for handling updates to the site_stats table.
static newFromResult( $res)
Represents a title within MediaWiki.
getNamespace()
Get the namespace index, i.e.
static & makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
getFragment()
Get the Title fragment (i.e.
static purgeExpiredRestrictions()
Purge expired restrictions from the page_restrictions table.
getDBkey()
Get the main part with underscores.
getInterwiki()
Get the interwiki prefix.
static newFromRow( $row)
Make a Title object from a DB row.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
getName()
Get the user name, or the IP of an anonymous user.
isAllowed( $action='')
Internal mechanics of testing a permission.
isAllowedAny()
Check if user is allowed to access a feature / make an action.
Special handling for category pages.
Special handling for file pages.
Class representing a MediaWiki article and history.
static newFromID( $id, $from='fromdb')
Constructor from a page id.
doUpdateRestrictions(array $limit, array $expiry, &$cascade, $reason, User $user, $tags=null)
Update the article's restriction field, and leave a log entry.
getContributors()
Get a list of users who have edited this article, not including the user who made the most recent rev...
doPurge()
Perform the actions of a page purging.
followRedirect()
Get the Title object or URL this page redirects to.
insertOn( $dbw, $pageId=null)
Insert a new empty page record for this article.
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
pageDataFromTitle( $dbr, $title, $options=[])
Fetch a page record matching the Title object's namespace and title using a sanitized title string.
checkFlags( $flags)
Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
static onArticleEdit(Title $title, Revision $revision=null)
Purge caches on page update etc.
getRevision()
Get the latest revision.
getLinksTimestamp()
Get the page_links_updated field.
getMinorEdit()
Returns true if last revision was marked as "minor edit".
getUndoContent(Revision $undo, Revision $undoafter=null)
Get the content that needs to be saved in order to undo all revisions between $undo and $undoafter.
clearCacheFields()
Clear the object cache fields.
clearPreparedEdit()
Clear the mPreparedEdit cache field, as may be needed by mutable content types.
getLatest()
Get the page_latest field.
doViewUpdates(User $user, $oldid=0)
Do standard deferred updates after page view (existing or missing page)
updateIfNewerOn( $dbw, $revision)
If the given revision is newer than the currently set page_latest, update the page record.
loadFromRow( $data, $from)
Load the object from a database row.
supportsSections()
Returns true if this page's content model supports sections.
getRedirectTarget()
If this page is a redirect, get its target.
setTimestamp( $ts)
Set the page timestamp (use only to avoid DB queries)
protectDescriptionLog(array $limit, array $expiry)
Builds the description to serve as comment for the log entry.
getUser( $audience=Revision::FOR_PUBLIC, User $user=null)
makeParserOptions( $context)
Get parser options suitable for rendering the primary article wikitext.
pageData( $dbr, $conditions, $options=[])
Fetch a page record with the given conditions.
getText( $audience=Revision::FOR_PUBLIC, User $user=null)
Get the text of the current revision.
doDeleteArticleReal( $reason, $suppress=false, $u1=null, $u2=null, &$error='', User $user=null)
Back-end article deletion Deletes the article with database consistency, writes logs,...
getOldestRevision()
Get the Revision object of the oldest revision.
replaceSectionAtRev( $sectionId, Content $sectionContent, $sectionTitle='', $baseRevId=null)
setLastEdit(Revision $revision)
Set the latest revision.
stdClass $mPreparedEdit
Map of cache fields (text, parser output, ect) for a proposed/new edit.
updateRevisionOn( $dbw, $revision, $lastRevision=null, $lastRevIsRedirect=null)
Update the page record to point to a newly saved revision.
shouldCheckParserCache(ParserOptions $parserOptions, $oldId)
Should the parser cache be used?
loadLastEdit()
Loads everything except the text This isn't necessary for all uses, so it's only done if needed.
getUserText( $audience=Revision::FOR_PUBLIC, User $user=null)
doModify(Content $content, $flags, User $user, $summary, array $meta)
getContentModel()
Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
pageDataFromId( $dbr, $id, $options=[])
Fetch a page record matching the requested ID.
doEditContent(Content $content, $summary, $flags=0, $baseRevId=false, User $user=null, $serialFormat=null, $tags=null)
Change an existing article or create a new article.
doEditUpdates(Revision $revision, User $user, array $options=[])
Do standard deferred updates after page edit.
insertRedirectEntry(Title $rt, $oldLatest=null)
Insert or update the redirect table entry for this page to indicate it redirects to $rt.
doDeleteArticle( $reason, $suppress=false, $u1=null, $u2=null, &$error='', User $user=null)
Same as doDeleteArticleReal(), but returns a simple boolean.
string $mTimestamp
Timestamp of the current revision or empty string if not loaded.
getHiddenCategories()
Returns a list of hidden categories this page is a member of.
getComment( $audience=Revision::FOR_PUBLIC, User $user=null)
static newFromRow( $row, $from='fromdb')
Constructor from a database row.
getAutoDeleteReason(&$hasHistory)
Auto-generates a deletion reason.
lockAndGetLatest()
Lock the page row for this title+id and return page_latest (or 0)
static flattenRestrictions( $limit)
Take an array of page restrictions and flatten it to a string suitable for insertion into the page_re...
updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect=null)
Add row to the redirect table if this is a redirect, remove otherwise.
prepareContentForEdit(Content $content, $revision=null, User $user=null, $serialFormat=null, $useCache=true)
Prepare content which is about to be saved.
hasViewableContent()
Check if this page is something we're going to be showing some sort of sensible content for.
triggerOpportunisticLinksUpdate(ParserOutput $parserOutput)
Opportunistically enqueue link update jobs given fresh parser output if useful.
getDeletionUpdates(Content $content=null)
Returns a list of updates to be performed when this page is deleted.
insertRedirect()
Insert an entry for this page into the redirect table if the content is a redirect.
updateCategoryCounts(array $added, array $deleted)
Update all the appropriate counts in the category table, given that we've added the categories $added...
getContent( $audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
getActionOverrides()
Returns overrides for action handlers.
doEdit( $text, $summary, $flags=0, $baseRevId=false, $user=null)
Change an existing article or create a new article.
int $mDataLoadedFrom
One of the READ_* constants.
static getAutosummary( $oldtext, $newtext, $flags)
Return an applicable autosummary if one exists for the given edit.
static onArticleDelete(Title $title)
Clears caches when article is deleted.
replaceSectionContent( $sectionId, Content $sectionContent, $sectionTitle='', $edittime=null)
static selectFields()
Return the list of revision fields that should be selected to create a new page.
insertProtectNullRevision( $revCommentMsg, array $limit, array $expiry, $cascade, $reason, $user=null)
Insert a new null revision for this page.
getTitle()
Get the title object of the article.
isRedirect()
Tests if the article content represents a redirect.
static onArticleCreate(Title $title)
The onArticle*() functions are supposed to be a kind of hooks which should be called whenever any of ...
commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser, $tags=null)
Backend implementation of doRollback(), please refer there for parameter and return value documentati...
getRedirectURL( $rt)
Get the Title object or URL to use for a redirect.
loadPageData( $from='fromdb')
Load the object from a given source by title.
doCreate(Content $content, $flags, User $user, $summary, array $meta)
checkTouched()
Loads page_touched and returns a value indicating if it should be used.
isCountable( $editInfo=false)
Determine whether a page would be suitable for being counted as an article in the site_stats table ba...
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...
doDeleteUpdates( $id, Content $content=null)
Do some database updates after deletion.
getContentHandler()
Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
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...
prepareTextForEdit( $text, $revid=null, User $user=null)
Prepare text which is about to be saved.
static convertSelectType( $type)
Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
getCreator( $audience=Revision::FOR_PUBLIC, User $user=null)
Get the User object of the user who created the page.
getParserOutput(ParserOptions $parserOptions, $oldid=null)
Get a ParserOutput for the given ParserOptions and revision ID.
protectDescription(array $limit, array $expiry)
Builds the description to serve as comment for the edit.
getTouched()
Get the page_touched field.
__construct(Title $title)
Constructor and clear the article.
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
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
when a variable name is used in a it is silently declared as a new local masking the global
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
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
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
const CONTENT_MODEL_WIKITEXT
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
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
the array() calling protocol came about after MediaWiki 1.4rc1.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
do that in ParserLimitReportFormat instead $parser
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
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
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
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
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<div ...>$1</div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
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
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
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
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
namespace and then decline to actually register it file or subcat img or subcat $title
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
it s the revision text itself In either if gzip is the revision text is gzipped $flags
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
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
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
returning false will NOT prevent logging $e
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
Base interface for content objects.
Interface for database access objects.
Interface for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
foreach( $res as $row) $serialized