3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
8 * Class representing a MediaWiki article and history.
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
13 * @internal documentation reviewed 15 Mar 2010
15 class WikiPage
extends Page
{
16 // doDeleteArticleReal() return values. Values less than zero indicate fatal errors,
17 // values greater than zero indicate that there were problems not resulting in page
21 * Delete operation aborted by hook
23 const DELETE_HOOK_ABORTED
= -1;
28 const DELETE_SUCCESS
= 0;
33 const DELETE_NO_PAGE
= 1;
36 * No revisions found to delete
38 const DELETE_NO_REVISIONS
= 2;
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
51 public $mPreparedEdit = false; // !< Array
57 protected $mRedirectTarget = null;
62 protected $mLastRevision = null;
65 * @var string; timestamp of the current revision or empty string if not loaded
67 protected $mTimestamp = '';
72 protected $mTouched = '19700101000000';
77 protected $mCounter = null;
80 * Constructor and clear the article
81 * @param $title Title Reference to a Title object.
83 public function __construct( Title
$title ) {
84 $this->mTitle
= $title;
88 * Create a WikiPage object of the appropriate class for the given title.
91 * @return WikiPage object of the appropriate type
93 public static function factory( Title
$title ) {
94 $ns = $title->getNamespace();
96 if ( $ns == NS_MEDIA
) {
97 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
98 } elseif ( $ns < 0 ) {
99 throw new MWException( "Invalid or virtual namespace $ns given." );
104 $page = new WikiFilePage( $title );
107 $page = new WikiCategoryPage( $title );
110 $page = new WikiPage( $title );
117 * Constructor from a page id
119 * @param $id Int article ID to load
121 * @return WikiPage|null
123 public static function newFromID( $id ) {
124 $dbr = wfGetDB( DB_SLAVE
);
125 $row = $dbr->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
129 return self
::newFromRow( $row );
133 * Constructor from a database row
136 * @param $row object: database row containing at least fields returned
140 public static function newFromRow( $row ) {
141 $page = self
::factory( Title
::newFromRow( $row ) );
142 $page->loadFromRow( $row );
147 * Returns overrides for action handlers.
148 * Classes listed here will be used instead of the default one when
149 * (and only when) $wgActions[$action] === true. This allows subclasses
150 * to override the default behavior.
152 * @todo: move this UI stuff somewhere else
156 public function getActionOverrides() {
161 * Get the title object of the article
162 * @return Title object of this page
164 public function getTitle() {
165 return $this->mTitle
;
171 public function clear() {
172 $this->mDataLoaded
= false;
174 $this->mCounter
= null;
175 $this->mRedirectTarget
= null; # Title object if set
176 $this->mLastRevision
= null; # Latest revision
177 $this->mTouched
= '19700101000000';
178 $this->mTimestamp
= '';
179 $this->mIsRedirect
= false;
180 $this->mLatest
= false;
181 $this->mPreparedEdit
= false;
185 * Return the list of revision fields that should be selected to create
190 public static function selectFields() {
207 * Fetch a page record with the given conditions
208 * @param $dbr DatabaseBase object
209 * @param $conditions Array
210 * @return mixed Database result resource, or false on failure
212 protected function pageData( $dbr, $conditions ) {
213 $fields = self
::selectFields();
215 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
217 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
219 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
225 * Fetch a page record matching the Title object's namespace and title
226 * using a sanitized title string
228 * @param $dbr DatabaseBase object
229 * @param $title Title object
230 * @return mixed Database result resource, or false on failure
232 public function pageDataFromTitle( $dbr, $title ) {
233 return $this->pageData( $dbr, array(
234 'page_namespace' => $title->getNamespace(),
235 'page_title' => $title->getDBkey() ) );
239 * Fetch a page record matching the requested ID
241 * @param $dbr DatabaseBase
243 * @return mixed Database result resource, or false on failure
245 public function pageDataFromId( $dbr, $id ) {
246 return $this->pageData( $dbr, array( 'page_id' => $id ) );
250 * Set the general counter, title etc data loaded from
253 * @param $data Object|String One of the following:
254 * A DB query result object or...
255 * "fromdb" to get from a slave DB or...
256 * "fromdbmaster" to get from the master DB
259 public function loadPageData( $data = 'fromdb' ) {
260 if ( $data === 'fromdbmaster' ) {
261 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
262 } elseif ( $data === 'fromdb' ) { // slave
263 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
264 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
265 # Note that DB also stores the master position in the session and checks it.
266 $touched = $this->getCachedLastEditTime();
267 if ( $touched ) { // key set
268 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
269 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
274 $this->loadFromRow( $data );
278 * Load the object from a database row
281 * @param $data object: database row containing at least fields returned
284 public function loadFromRow( $data ) {
285 $lc = LinkCache
::singleton();
288 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
290 $this->mTitle
->loadFromRow( $data );
292 # Old-fashioned restrictions
293 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
295 $this->mCounter
= intval( $data->page_counter
);
296 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
297 $this->mIsRedirect
= intval( $data->page_is_redirect
);
298 $this->mLatest
= intval( $data->page_latest
);
300 $lc->addBadLinkObj( $this->mTitle
);
302 $this->mTitle
->loadFromRow( false );
305 $this->mDataLoaded
= true;
309 * @return int Page ID
311 public function getId() {
312 return $this->mTitle
->getArticleID();
316 * @return bool Whether or not the page exists in the database
318 public function exists() {
319 return $this->mTitle
->exists();
323 * Check if this page is something we're going to be showing
324 * some sort of sensible content for. If we return false, page
325 * views (plain action=view) will return an HTTP 404 response,
326 * so spiders and robots can know they're following a bad link.
330 public function hasViewableContent() {
331 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
335 * @return int The view count for the page
337 public function getCount() {
338 if ( !$this->mDataLoaded
) {
339 $this->loadPageData();
342 return $this->mCounter
;
346 * Tests if the article text represents a redirect
348 * @param $text mixed string containing article contents, or boolean
351 public function isRedirect( $text = false ) {
352 if ( $text === false ) {
353 if ( !$this->mDataLoaded
) {
354 $this->loadPageData();
357 return (bool)$this->mIsRedirect
;
359 return Title
::newFromRedirect( $text ) !== null;
364 * Loads page_touched and returns a value indicating if it should be used
365 * @return boolean true if not a redirect
367 public function checkTouched() {
368 if ( !$this->mDataLoaded
) {
369 $this->loadPageData();
371 return !$this->mIsRedirect
;
375 * Get the page_touched field
376 * @return string containing GMT timestamp
378 public function getTouched() {
379 if ( !$this->mDataLoaded
) {
380 $this->loadPageData();
382 return $this->mTouched
;
386 * Get the page_latest field
387 * @return integer rev_id of current revision
389 public function getLatest() {
390 if ( !$this->mDataLoaded
) {
391 $this->loadPageData();
393 return (int)$this->mLatest
;
397 * Loads everything except the text
398 * This isn't necessary for all uses, so it's only done if needed.
400 protected function loadLastEdit() {
401 if ( $this->mLastRevision
!== null ) {
402 return; // already loaded
405 $latest = $this->getLatest();
407 return; // page doesn't exist or is missing page_latest info
410 $revision = Revision
::newFromPageId( $this->getId(), $latest );
411 if ( $revision ) { // sanity
412 $this->setLastEdit( $revision );
417 * Set the latest revision
419 protected function setLastEdit( Revision
$revision ) {
420 $this->mLastRevision
= $revision;
421 $this->mTimestamp
= $revision->getTimestamp();
425 * Get the latest revision
426 * @return Revision|null
428 public function getRevision() {
429 $this->loadLastEdit();
430 if ( $this->mLastRevision
) {
431 return $this->mLastRevision
;
437 * Get the text of the current revision. No side-effects...
439 * @param $audience Integer: one of:
440 * Revision::FOR_PUBLIC to be displayed to all users
441 * Revision::FOR_THIS_USER to be displayed to $wgUser
442 * Revision::RAW get the text regardless of permissions
443 * @return String|bool The text of the current revision. False on failure
445 public function getText( $audience = Revision
::FOR_PUBLIC
) {
446 $this->loadLastEdit();
447 if ( $this->mLastRevision
) {
448 return $this->mLastRevision
->getText( $audience );
454 * Get the text of the current revision. No side-effects...
456 * @return String|bool The text of the current revision. False on failure
458 public function getRawText() {
459 $this->loadLastEdit();
460 if ( $this->mLastRevision
) {
461 return $this->mLastRevision
->getRawText();
467 * @return string MW timestamp of last article revision
469 public function getTimestamp() {
470 // Check if the field has been filled by WikiPage::setTimestamp()
471 if ( !$this->mTimestamp
) {
472 $this->loadLastEdit();
475 return wfTimestamp( TS_MW
, $this->mTimestamp
);
479 * Set the page timestamp (use only to avoid DB queries)
480 * @param $ts string MW timestamp of last article revision
483 public function setTimestamp( $ts ) {
484 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
488 * @param $audience Integer: one of:
489 * Revision::FOR_PUBLIC to be displayed to all users
490 * Revision::FOR_THIS_USER to be displayed to $wgUser
491 * Revision::RAW get the text regardless of permissions
492 * @return int user ID for the user that made the last article revision
494 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
495 $this->loadLastEdit();
496 if ( $this->mLastRevision
) {
497 return $this->mLastRevision
->getUser( $audience );
504 * @param $audience Integer: one of:
505 * Revision::FOR_PUBLIC to be displayed to all users
506 * Revision::FOR_THIS_USER to be displayed to $wgUser
507 * Revision::RAW get the text regardless of permissions
508 * @return string username of the user that made the last article revision
510 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
511 $this->loadLastEdit();
512 if ( $this->mLastRevision
) {
513 return $this->mLastRevision
->getUserText( $audience );
520 * @param $audience Integer: one of:
521 * Revision::FOR_PUBLIC to be displayed to all users
522 * Revision::FOR_THIS_USER to be displayed to $wgUser
523 * Revision::RAW get the text regardless of permissions
524 * @return string Comment stored for the last article revision
526 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
527 $this->loadLastEdit();
528 if ( $this->mLastRevision
) {
529 return $this->mLastRevision
->getComment( $audience );
536 * Returns true if last revision was marked as "minor edit"
538 * @return boolean Minor edit indicator for the last article revision.
540 public function getMinorEdit() {
541 $this->loadLastEdit();
542 if ( $this->mLastRevision
) {
543 return $this->mLastRevision
->isMinor();
550 * Get the cached timestamp for the last time the page changed.
551 * This is only used to help handle slave lag by comparing to page_touched.
552 * @return string MW timestamp
554 protected function getCachedLastEditTime() {
556 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
557 return $wgMemc->get( $key );
561 * Set the cached timestamp for the last time the page changed.
562 * This is only used to help handle slave lag by comparing to page_touched.
563 * @param $timestamp string
566 public function setCachedLastEditTime( $timestamp ) {
568 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
569 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
573 * Determine whether a page would be suitable for being counted as an
574 * article in the site_stats table based on the title & its content
576 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
577 * if false, the current database state will be used
580 public function isCountable( $editInfo = false ) {
581 global $wgArticleCountMethod;
583 if ( !$this->mTitle
->isContentPage() ) {
587 $text = $editInfo ?
$editInfo->pst
: false;
589 if ( $this->isRedirect( $text ) ) {
593 switch ( $wgArticleCountMethod ) {
597 if ( $text === false ) {
598 $text = $this->getRawText();
600 return strpos( $text, ',' ) !== false;
603 // ParserOutput::getLinks() is a 2D array of page links, so
604 // to be really correct we would need to recurse in the array
605 // but the main array should only have items in it if there are
607 return (bool)count( $editInfo->output
->getLinks() );
609 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
610 array( 'pl_from' => $this->getId() ), __METHOD__
);
616 * If this page is a redirect, get its target
618 * The target will be fetched from the redirect table if possible.
619 * If this page doesn't have an entry there, call insertRedirect()
620 * @return Title|mixed object, or null if this page is not a redirect
622 public function getRedirectTarget() {
623 if ( !$this->mTitle
->isRedirect() ) {
627 if ( $this->mRedirectTarget
!== null ) {
628 return $this->mRedirectTarget
;
631 # Query the redirect table
632 $dbr = wfGetDB( DB_SLAVE
);
633 $row = $dbr->selectRow( 'redirect',
634 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
635 array( 'rd_from' => $this->getId() ),
639 // rd_fragment and rd_interwiki were added later, populate them if empty
640 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
641 return $this->mRedirectTarget
= Title
::makeTitle(
642 $row->rd_namespace
, $row->rd_title
,
643 $row->rd_fragment
, $row->rd_interwiki
);
646 # This page doesn't have an entry in the redirect table
647 return $this->mRedirectTarget
= $this->insertRedirect();
651 * Insert an entry for this page into the redirect table.
653 * Don't call this function directly unless you know what you're doing.
654 * @return Title object or null if not a redirect
656 public function insertRedirect() {
657 // recurse through to only get the final target
658 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
662 $this->insertRedirectEntry( $retval );
667 * Insert or update the redirect table entry for this page to indicate
668 * it redirects to $rt .
669 * @param $rt Title redirect target
671 public function insertRedirectEntry( $rt ) {
672 $dbw = wfGetDB( DB_MASTER
);
673 $dbw->replace( 'redirect', array( 'rd_from' ),
675 'rd_from' => $this->getId(),
676 'rd_namespace' => $rt->getNamespace(),
677 'rd_title' => $rt->getDBkey(),
678 'rd_fragment' => $rt->getFragment(),
679 'rd_interwiki' => $rt->getInterwiki(),
686 * Get the Title object or URL this page redirects to
688 * @return mixed false, Title of in-wiki target, or string with URL
690 public function followRedirect() {
691 return $this->getRedirectURL( $this->getRedirectTarget() );
695 * Get the Title object or URL to use for a redirect. We use Title
696 * objects for same-wiki, non-special redirects and URLs for everything
698 * @param $rt Title Redirect target
699 * @return mixed false, Title object of local target, or string with URL
701 public function getRedirectURL( $rt ) {
706 if ( $rt->isExternal() ) {
707 if ( $rt->isLocal() ) {
708 // Offsite wikis need an HTTP redirect.
710 // This can be hard to reverse and may produce loops,
711 // so they may be disabled in the site configuration.
712 $source = $this->mTitle
->getFullURL( 'redirect=no' );
713 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
715 // External pages pages without "local" bit set are not valid
721 if ( $rt->isSpecialPage() ) {
722 // Gotta handle redirects to special pages differently:
723 // Fill the HTTP response "Location" header and ignore
724 // the rest of the page we're on.
726 // Some pages are not valid targets
727 if ( $rt->isValidRedirectTarget() ) {
728 return $rt->getFullURL();
738 * Get a list of users who have edited this article, not including the user who made
739 * the most recent revision, which you can get from $article->getUser() if you want it
740 * @return UserArrayFromResult
742 public function getContributors() {
743 # @todo FIXME: This is expensive; cache this info somewhere.
745 $dbr = wfGetDB( DB_SLAVE
);
747 if ( $dbr->implicitGroupby() ) {
748 $realNameField = 'user_real_name';
750 $realNameField = 'MIN(user_real_name) AS user_real_name';
753 $tables = array( 'revision', 'user' );
756 'rev_user as user_id',
757 'rev_user_text AS user_name',
759 'MAX(rev_timestamp) AS timestamp',
762 $conds = array( 'rev_page' => $this->getId() );
764 // The user who made the top revision gets credited as "this page was last edited by
765 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
766 $user = $this->getUser();
768 $conds[] = "rev_user != $user";
770 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
773 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
776 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
780 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
781 'ORDER BY' => 'timestamp DESC',
784 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
785 return new UserArrayFromResult( $res );
789 * Get the last N authors
790 * @param $num Integer: number of revisions to get
791 * @param $revLatest String: the latest rev_id, selected from the master (optional)
792 * @return array Array of authors, duplicates not removed
794 public function getLastNAuthors( $num, $revLatest = 0 ) {
795 wfProfileIn( __METHOD__
);
796 // First try the slave
797 // If that doesn't have the latest revision, try the master
799 $db = wfGetDB( DB_SLAVE
);
802 $res = $db->select( array( 'page', 'revision' ),
803 array( 'rev_id', 'rev_user_text' ),
805 'page_namespace' => $this->mTitle
->getNamespace(),
806 'page_title' => $this->mTitle
->getDBkey(),
810 'ORDER BY' => 'rev_timestamp DESC',
816 wfProfileOut( __METHOD__
);
820 $row = $db->fetchObject( $res );
822 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
823 $db = wfGetDB( DB_MASTER
);
828 } while ( $continue );
830 $authors = array( $row->rev_user_text
);
832 foreach ( $res as $row ) {
833 $authors[] = $row->rev_user_text
;
836 wfProfileOut( __METHOD__
);
841 * Should the parser cache be used?
843 * @param $parserOptions ParserOptions to check
847 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
848 global $wgEnableParserCache;
850 return $wgEnableParserCache
851 && $parserOptions->getStubThreshold() == 0
852 && $this->mTitle
->exists()
853 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
854 && $this->mTitle
->isWikitextPage();
858 * Get a ParserOutput for the given ParserOptions and revision ID.
859 * The parser cache will be used if possible.
862 * @param $parserOptions ParserOptions to use for the parse operation
863 * @param $oldid Revision ID to get the text from, passing null or 0 will
864 * get the current revision (default value)
865 * @return ParserOutput or false if the revision was not found
867 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
868 wfProfileIn( __METHOD__
);
870 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
871 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
872 if ( $parserOptions->getStubThreshold() ) {
873 wfIncrStats( 'pcache_miss_stub' );
876 if ( $useParserCache ) {
877 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
878 if ( $parserOutput !== false ) {
879 wfProfileOut( __METHOD__
);
880 return $parserOutput;
884 if ( $oldid === null ||
$oldid === 0 ) {
885 $oldid = $this->getLatest();
888 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
891 wfProfileOut( __METHOD__
);
893 return $pool->getParserOutput();
897 * Do standard deferred updates after page view
898 * @param $user User The relevant user
900 public function doViewUpdates( User
$user ) {
901 global $wgDisableCounters;
902 if ( wfReadOnly() ) {
906 # Don't update page view counters on views from bot users (bug 14044)
907 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
908 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
909 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
912 # Update newtalk / watchlist notification status
913 $user->clearNotification( $this->mTitle
);
917 * Perform the actions of a page purging
920 public function doPurge() {
923 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
927 // Invalidate the cache
928 $this->mTitle
->invalidateCache();
932 // Commit the transaction before the purge is sent
933 $dbw = wfGetDB( DB_MASTER
);
934 $dbw->commit( __METHOD__
);
937 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
941 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
942 if ( $this->mTitle
->exists() ) {
943 $text = $this->getRawText();
948 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
954 * Insert a new empty page record for this article.
955 * This *must* be followed up by creating a revision
956 * and running $this->updateRevisionOn( ... );
957 * or else the record will be left in a funky state.
958 * Best if all done inside a transaction.
960 * @param $dbw DatabaseBase
961 * @return int The newly created page_id key, or false if the title already existed
963 public function insertOn( $dbw ) {
964 wfProfileIn( __METHOD__
);
966 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
967 $dbw->insert( 'page', array(
968 'page_id' => $page_id,
969 'page_namespace' => $this->mTitle
->getNamespace(),
970 'page_title' => $this->mTitle
->getDBkey(),
972 'page_restrictions' => '',
973 'page_is_redirect' => 0, # Will set this shortly...
975 'page_random' => wfRandom(),
976 'page_touched' => $dbw->timestamp(),
977 'page_latest' => 0, # Fill this in shortly...
978 'page_len' => 0, # Fill this in shortly...
979 ), __METHOD__
, 'IGNORE' );
981 $affected = $dbw->affectedRows();
984 $newid = $dbw->insertId();
985 $this->mTitle
->resetArticleID( $newid );
987 wfProfileOut( __METHOD__
);
989 return $affected ?
$newid : false;
993 * Update the page record to point to a newly saved revision.
995 * @param $dbw DatabaseBase: object
996 * @param $revision Revision: For ID number, and text used to set
997 * length and redirect status fields
998 * @param $lastRevision Integer: if given, will not overwrite the page field
999 * when different from the currently set value.
1000 * Giving 0 indicates the new page flag should be set
1002 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1003 * removing rows in redirect table.
1004 * @return bool true on success, false on failure
1007 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1008 wfProfileIn( __METHOD__
);
1010 $text = $revision->getText();
1011 $len = strlen( $text );
1012 $rt = Title
::newFromRedirectRecurse( $text );
1014 $conditions = array( 'page_id' => $this->getId() );
1016 if ( !is_null( $lastRevision ) ) {
1017 # An extra check against threads stepping on each other
1018 $conditions['page_latest'] = $lastRevision;
1021 $now = wfTimestampNow();
1022 $dbw->update( 'page',
1024 'page_latest' => $revision->getId(),
1025 'page_touched' => $dbw->timestamp( $now ),
1026 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1027 'page_is_redirect' => $rt !== null ?
1 : 0,
1033 $result = $dbw->affectedRows() != 0;
1035 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1036 $this->setLastEdit( $revision );
1037 $this->setCachedLastEditTime( $now );
1038 $this->mLatest
= $revision->getId();
1039 $this->mIsRedirect
= (bool)$rt;
1040 # Update the LinkCache.
1041 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1044 wfProfileOut( __METHOD__
);
1049 * Add row to the redirect table if this is a redirect, remove otherwise.
1051 * @param $dbw DatabaseBase
1052 * @param $redirectTitle Title object pointing to the redirect target,
1053 * or NULL if this is not a redirect
1054 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1055 * removing rows in redirect table.
1056 * @return bool true on success, false on failure
1059 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1060 // Always update redirects (target link might have changed)
1061 // Update/Insert if we don't know if the last revision was a redirect or not
1062 // Delete if changing from redirect to non-redirect
1063 $isRedirect = !is_null( $redirectTitle );
1065 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1069 wfProfileIn( __METHOD__
);
1070 if ( $isRedirect ) {
1071 $this->insertRedirectEntry( $redirectTitle );
1073 // This is not a redirect, remove row from redirect table
1074 $where = array( 'rd_from' => $this->getId() );
1075 $dbw->delete( 'redirect', $where, __METHOD__
);
1078 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1079 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1081 wfProfileOut( __METHOD__
);
1083 return ( $dbw->affectedRows() != 0 );
1087 * If the given revision is newer than the currently set page_latest,
1088 * update the page record. Otherwise, do nothing.
1090 * @param $dbw DatabaseBase object
1091 * @param $revision Revision object
1094 public function updateIfNewerOn( $dbw, $revision ) {
1095 wfProfileIn( __METHOD__
);
1097 $row = $dbw->selectRow(
1098 array( 'revision', 'page' ),
1099 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1101 'page_id' => $this->getId(),
1102 'page_latest=rev_id' ),
1106 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1107 wfProfileOut( __METHOD__
);
1110 $prev = $row->rev_id
;
1111 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1113 # No or missing previous revision; mark the page as new
1115 $lastRevIsRedirect = null;
1118 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1120 wfProfileOut( __METHOD__
);
1125 * Get the text that needs to be saved in order to undo all revisions
1126 * between $undo and $undoafter. Revisions must belong to the same page,
1127 * must exist and must not be deleted
1128 * @param $undo Revision
1129 * @param $undoafter Revision Must be an earlier revision than $undo
1130 * @return mixed string on success, false on failure
1132 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1133 $cur_text = $this->getRawText();
1134 if ( $cur_text === false ) {
1135 return false; // no page
1137 $undo_text = $undo->getText();
1138 $undoafter_text = $undoafter->getText();
1140 if ( $cur_text == $undo_text ) {
1141 # No use doing a merge if it's just a straight revert.
1142 return $undoafter_text;
1147 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1151 return $undone_text;
1155 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1156 * @param $text String: new text of the section
1157 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1158 * @param $edittime String: revision timestamp or null to use the current revision
1159 * @return string Complete article text, or null if error
1161 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1162 wfProfileIn( __METHOD__
);
1164 if ( strval( $section ) == '' ) {
1165 // Whole-page edit; let the whole text through
1167 // Bug 30711: always use current version when adding a new section
1168 if ( is_null( $edittime ) ||
$section == 'new' ) {
1169 $oldtext = $this->getRawText();
1170 if ( $oldtext === false ) {
1171 wfDebug( __METHOD__
. ": no page text\n" );
1172 wfProfileOut( __METHOD__
);
1176 $dbw = wfGetDB( DB_MASTER
);
1177 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1180 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1181 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1182 wfProfileOut( __METHOD__
);
1186 $oldtext = $rev->getText();
1189 if ( $section == 'new' ) {
1190 # Inserting a new section
1191 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1192 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1193 $text = strlen( trim( $oldtext ) ) > 0
1194 ?
"{$oldtext}\n\n{$subject}{$text}"
1195 : "{$subject}{$text}";
1198 # Replacing an existing section; roll out the big guns
1201 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1205 wfProfileOut( __METHOD__
);
1210 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1212 * @return Int updated $flags
1214 function checkFlags( $flags ) {
1215 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1216 if ( $this->mTitle
->getArticleID() ) {
1217 $flags |
= EDIT_UPDATE
;
1227 * Change an existing article or create a new article. Updates RC and all necessary caches,
1228 * optionally via the deferred update array.
1230 * @param $text String: new text
1231 * @param $summary String: edit summary
1232 * @param $flags Integer bitfield:
1234 * Article is known or assumed to be non-existent, create a new one
1236 * Article is known or assumed to be pre-existing, update it
1238 * Mark this edit minor, if the user is allowed to do so
1240 * Do not log the change in recentchanges
1242 * Mark the edit a "bot" edit regardless of user rights
1243 * EDIT_DEFER_UPDATES
1244 * Defer some of the updates until the end of index.php
1246 * Fill in blank summaries with generated text where possible
1248 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1249 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1250 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1251 * edit-already-exists error will be returned. These two conditions are also possible with
1252 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1254 * @param $baseRevId int the revision ID this edit was based off, if any
1255 * @param $user User the user doing the edit
1257 * @return Status object. Possible errors:
1258 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1259 * edit-gone-missing: In update mode, but the article didn't exist
1260 * edit-conflict: In update mode, the article changed unexpectedly
1261 * edit-no-change: Warning that the text was the same as before
1262 * edit-already-exists: In creation mode, but the article already exists
1264 * Extensions may define additional errors.
1266 * $return->value will contain an associative array with members as follows:
1267 * new: Boolean indicating if the function attempted to create a new article
1268 * revision: The revision object for the inserted revision, or null
1270 * Compatibility note: this function previously returned a boolean value indicating success/failure
1272 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1273 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1275 # Low-level sanity check
1276 if ( $this->mTitle
->getText() === '' ) {
1277 throw new MWException( 'Something is trying to edit an article with an empty title' );
1280 wfProfileIn( __METHOD__
);
1282 $user = is_null( $user ) ?
$wgUser : $user;
1283 $status = Status
::newGood( array() );
1285 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1286 $this->loadPageData( 'fromdbmaster' );
1288 $flags = $this->checkFlags( $flags );
1290 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1291 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1293 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1295 if ( $status->isOK() ) {
1296 $status->fatal( 'edit-hook-aborted' );
1299 wfProfileOut( __METHOD__
);
1303 # Silently ignore EDIT_MINOR if not allowed
1304 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1305 $bot = $flags & EDIT_FORCE_BOT
;
1307 $oldtext = $this->getRawText(); // current revision
1308 $oldsize = strlen( $oldtext );
1309 $oldid = $this->getLatest();
1310 $oldIsRedirect = $this->isRedirect();
1311 $oldcountable = $this->isCountable();
1313 # Provide autosummaries if one is not provided and autosummaries are enabled.
1314 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1315 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1318 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1319 $text = $editInfo->pst
;
1320 $newsize = strlen( $text );
1322 $dbw = wfGetDB( DB_MASTER
);
1323 $now = wfTimestampNow();
1324 $this->mTimestamp
= $now;
1326 if ( $flags & EDIT_UPDATE
) {
1327 # Update article, but only if changed.
1328 $status->value
['new'] = false;
1331 # Article gone missing
1332 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1333 $status->fatal( 'edit-gone-missing' );
1335 wfProfileOut( __METHOD__
);
1339 # Make sure the revision is either completely inserted or not inserted at all
1340 if ( !$wgDBtransactions ) {
1341 $userAbort = ignore_user_abort( true );
1344 $revision = new Revision( array(
1345 'page' => $this->getId(),
1346 'comment' => $summary,
1347 'minor_edit' => $isminor,
1349 'parent_id' => $oldid,
1350 'user' => $user->getId(),
1351 'user_text' => $user->getName(),
1355 $changed = ( strcmp( $text, $oldtext ) != 0 );
1358 $dbw->begin( __METHOD__
);
1359 $revisionId = $revision->insertOn( $dbw );
1363 # Note that we use $this->mLatest instead of fetching a value from the master DB
1364 # during the course of this function. This makes sure that EditPage can detect
1365 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1366 # before this function is called. A previous function used a separate query, this
1367 # creates a window where concurrent edits can cause an ignored edit conflict.
1368 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1371 /* Belated edit conflict! Run away!! */
1372 $status->fatal( 'edit-conflict' );
1374 # Delete the invalid revision if the DB is not transactional
1375 if ( !$wgDBtransactions ) {
1376 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1380 $dbw->rollback( __METHOD__
);
1382 global $wgUseRCPatrol;
1383 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1384 # Update recentchanges
1385 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1386 # Mark as patrolled if the user can do so
1387 $patrolled = $wgUseRCPatrol && !count(
1388 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1389 # Add RC row to the DB
1390 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1391 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1392 $revisionId, $patrolled
1395 # Log auto-patrolled edits
1397 PatrolLog
::record( $rc, true, $user );
1400 $user->incEditCount();
1401 $dbw->commit( __METHOD__
);
1404 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1405 // related variables correctly
1406 $revision->setId( $this->getLatest() );
1409 if ( !$wgDBtransactions ) {
1410 ignore_user_abort( $userAbort );
1413 // Now that ignore_user_abort is restored, we can respond to fatal errors
1414 if ( !$status->isOK() ) {
1415 wfProfileOut( __METHOD__
);
1419 # Update links tables, site stats, etc.
1420 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1421 'oldcountable' => $oldcountable ) );
1424 $status->warning( 'edit-no-change' );
1426 // Update page_touched, this is usually implicit in the page update
1427 // Other cache updates are done in onArticleEdit()
1428 $this->mTitle
->invalidateCache();
1431 # Create new article
1432 $status->value
['new'] = true;
1434 $dbw->begin( __METHOD__
);
1436 # Add the page record; stake our claim on this title!
1437 # This will return false if the article already exists
1438 $newid = $this->insertOn( $dbw );
1440 if ( $newid === false ) {
1441 $dbw->rollback( __METHOD__
);
1442 $status->fatal( 'edit-already-exists' );
1444 wfProfileOut( __METHOD__
);
1448 # Save the revision text...
1449 $revision = new Revision( array(
1451 'comment' => $summary,
1452 'minor_edit' => $isminor,
1454 'user' => $user->getId(),
1455 'user_text' => $user->getName(),
1458 $revisionId = $revision->insertOn( $dbw );
1460 # Update the page record with revision data
1461 $this->updateRevisionOn( $dbw, $revision, 0 );
1463 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1465 # Update recentchanges
1466 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1467 global $wgUseRCPatrol, $wgUseNPPatrol;
1469 # Mark as patrolled if the user can do so
1470 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1471 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1472 # Add RC row to the DB
1473 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1474 '', strlen( $text ), $revisionId, $patrolled );
1476 # Log auto-patrolled edits
1478 PatrolLog
::record( $rc, true, $user );
1481 $user->incEditCount();
1482 $dbw->commit( __METHOD__
);
1484 # Update links, etc.
1485 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1487 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1488 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1491 # Do updates right now unless deferral was requested
1492 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1493 DeferredUpdates
::doUpdates();
1496 // Return the new revision (or null) to the caller
1497 $status->value
['revision'] = $revision;
1499 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1500 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1502 # Promote user to any groups they meet the criteria for
1503 $user->addAutopromoteOnceGroups( 'onEdit' );
1505 wfProfileOut( __METHOD__
);
1510 * Get parser options suitable for rendering the primary article wikitext
1511 * @param User|string $user User object or 'canonical'
1512 * @return ParserOptions
1514 public function makeParserOptions( $user ) {
1516 if ( $user instanceof User
) { // settings per user (even anons)
1517 $options = ParserOptions
::newFromUser( $user );
1518 } else { // canonical settings
1519 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1521 $options->enableLimitReport(); // show inclusion/loop reports
1522 $options->setTidy( true ); // fix bad HTML
1527 * Prepare text which is about to be saved.
1528 * Returns a stdclass with source, pst and output members
1529 * @return bool|object
1531 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1532 global $wgParser, $wgContLang, $wgUser;
1533 $user = is_null( $user ) ?
$wgUser : $user;
1534 // @TODO fixme: check $user->getId() here???
1535 if ( $this->mPreparedEdit
1536 && $this->mPreparedEdit
->newText
== $text
1537 && $this->mPreparedEdit
->revid
== $revid
1540 return $this->mPreparedEdit
;
1543 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1544 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1546 $edit = (object)array();
1547 $edit->revid
= $revid;
1548 $edit->newText
= $text;
1549 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1550 $edit->popts
= $this->makeParserOptions( 'canonical' );
1551 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1552 $edit->oldText
= $this->getRawText();
1554 $this->mPreparedEdit
= $edit;
1560 * Do standard deferred updates after page edit.
1561 * Update links tables, site stats, search index and message cache.
1562 * Purges pages that include this page if the text was changed here.
1563 * Every 100th edit, prune the recent changes table.
1566 * @param $revision Revision object
1567 * @param $user User object that did the revision
1568 * @param $options Array of options, following indexes are used:
1569 * - changed: boolean, whether the revision changed the content (default true)
1570 * - created: boolean, whether the revision created the page (default false)
1571 * - oldcountable: boolean or null (default null):
1572 * - boolean: whether the page was counted as an article before that
1573 * revision, only used in changed is true and created is false
1574 * - null: don't change the article count
1576 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1577 global $wgEnableParserCache;
1579 wfProfileIn( __METHOD__
);
1581 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1582 $text = $revision->getText();
1585 # Be careful not to double-PST: $text is usually already PST-ed once
1586 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1587 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1588 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1590 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1591 $editInfo = $this->mPreparedEdit
;
1594 # Save it to the parser cache
1595 if ( $wgEnableParserCache ) {
1596 $parserCache = ParserCache
::singleton();
1597 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1600 # Update the links tables
1601 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1604 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1606 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1607 if ( 0 == mt_rand( 0, 99 ) ) {
1608 // Flush old entries from the `recentchanges` table; we do this on
1609 // random requests so as to avoid an increase in writes for no good reason
1612 $dbw = wfGetDB( DB_MASTER
);
1613 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1616 array( "rc_timestamp < '$cutoff'" ),
1622 if ( !$this->mTitle
->exists() ) {
1623 wfProfileOut( __METHOD__
);
1627 $id = $this->getId();
1628 $title = $this->mTitle
->getPrefixedDBkey();
1629 $shortTitle = $this->mTitle
->getDBkey();
1631 if ( !$options['changed'] ) {
1634 } elseif ( $options['created'] ) {
1635 $good = (int)$this->isCountable( $editInfo );
1637 } elseif ( $options['oldcountable'] !== null ) {
1638 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1645 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1646 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1648 # If this is another user's talk page, update newtalk.
1649 # Don't do this if $options['changed'] = false (null-edits) nor if
1650 # it's a minor edit and the user doesn't want notifications for those.
1651 if ( $options['changed']
1652 && $this->mTitle
->getNamespace() == NS_USER_TALK
1653 && $shortTitle != $user->getTitleKey()
1654 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1656 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1657 $other = User
::newFromName( $shortTitle, false );
1659 wfDebug( __METHOD__
. ": invalid username\n" );
1660 } elseif ( User
::isIP( $shortTitle ) ) {
1661 // An anonymous user
1662 $other->setNewtalk( true );
1663 } elseif ( $other->isLoggedIn() ) {
1664 $other->setNewtalk( true );
1666 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1671 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1672 MessageCache
::singleton()->replace( $shortTitle, $text );
1675 if( $options['created'] ) {
1676 self
::onArticleCreate( $this->mTitle
);
1678 self
::onArticleEdit( $this->mTitle
);
1681 wfProfileOut( __METHOD__
);
1685 * Edit an article without doing all that other stuff
1686 * The article must already exist; link tables etc
1687 * are not updated, caches are not flushed.
1689 * @param $text String: text submitted
1690 * @param $user User The relevant user
1691 * @param $comment String: comment submitted
1692 * @param $minor Boolean: whereas it's a minor modification
1694 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1695 wfProfileIn( __METHOD__
);
1697 $dbw = wfGetDB( DB_MASTER
);
1698 $revision = new Revision( array(
1699 'page' => $this->getId(),
1701 'comment' => $comment,
1702 'minor_edit' => $minor ?
1 : 0,
1704 $revision->insertOn( $dbw );
1705 $this->updateRevisionOn( $dbw, $revision );
1707 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1709 wfProfileOut( __METHOD__
);
1713 * Update the article's restriction field, and leave a log entry.
1714 * This works for protection both existing and non-existing pages.
1716 * @param $limit Array: set of restriction keys
1717 * @param $reason String
1718 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1719 * @param $expiry Array: per restriction type expiration
1720 * @param $user User The user updating the restrictions
1723 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1726 if ( wfReadOnly() ) {
1727 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1730 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1732 $id = $this->mTitle
->getArticleID();
1738 // Take this opportunity to purge out expired restrictions
1739 Title
::purgeExpiredRestrictions();
1741 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1742 # we expect a single selection, but the schema allows otherwise.
1743 $isProtected = false;
1747 $dbw = wfGetDB( DB_MASTER
);
1749 foreach ( $restrictionTypes as $action ) {
1750 if ( !isset( $expiry[$action] ) ) {
1751 $expiry[$action] = $dbw->getInfinity();
1753 if ( !isset( $limit[$action] ) ) {
1754 $limit[$action] = '';
1755 } elseif ( $limit[$action] != '' ) {
1759 # Get current restrictions on $action
1760 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1761 if ( $current != '' ) {
1762 $isProtected = true;
1765 if ( $limit[$action] != $current ) {
1767 } elseif ( $limit[$action] != '' ) {
1768 # Only check expiry change if the action is actually being
1769 # protected, since expiry does nothing on an not-protected
1771 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1777 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1781 # If nothing's changed, do nothing
1783 return Status
::newGood();
1786 if ( !$protect ) { # No protection at all means unprotection
1787 $revCommentMsg = 'unprotectedarticle';
1788 $logAction = 'unprotect';
1789 } elseif ( $isProtected ) {
1790 $revCommentMsg = 'modifiedarticleprotection';
1791 $logAction = 'modify';
1793 $revCommentMsg = 'protectedarticle';
1794 $logAction = 'protect';
1797 $encodedExpiry = array();
1798 $protectDescription = '';
1799 foreach ( $limit as $action => $restrictions ) {
1800 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1801 if ( $restrictions != '' ) {
1802 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1803 if ( $encodedExpiry[$action] != 'infinity' ) {
1804 $protectDescription .= wfMsgForContent( 'protect-expiring',
1805 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1806 $wgContLang->date( $expiry[$action], false, false ) ,
1807 $wgContLang->time( $expiry[$action], false, false ) );
1809 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1812 $protectDescription .= ') ';
1815 $protectDescription = trim( $protectDescription );
1817 if ( $id ) { # Protection of existing page
1818 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1819 return Status
::newGood();
1822 # Only restrictions with the 'protect' right can cascade...
1823 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1824 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1826 # The schema allows multiple restrictions
1827 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1831 # Update restrictions table
1832 foreach ( $limit as $action => $restrictions ) {
1833 if ( $restrictions != '' ) {
1834 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1835 array( 'pr_page' => $id,
1836 'pr_type' => $action,
1837 'pr_level' => $restrictions,
1838 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1839 'pr_expiry' => $encodedExpiry[$action]
1844 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1845 'pr_type' => $action ), __METHOD__
);
1849 # Prepare a null revision to be added to the history
1850 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1852 $editComment .= ": $reason";
1854 if ( $protectDescription ) {
1855 $editComment .= " ($protectDescription)";
1858 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1861 # Insert a null revision
1862 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1863 $nullRevId = $nullRevision->insertOn( $dbw );
1865 $latest = $this->getLatest();
1866 # Update page record
1867 $dbw->update( 'page',
1869 'page_touched' => $dbw->timestamp(),
1870 'page_restrictions' => '',
1871 'page_latest' => $nullRevId
1872 ), array( /* WHERE */
1877 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1878 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1879 } else { # Protection of non-existing page (also known as "title protection")
1880 # Cascade protection is meaningless in this case
1883 if ( $limit['create'] != '' ) {
1884 $dbw->replace( 'protected_titles',
1885 array( array( 'pt_namespace', 'pt_title' ) ),
1887 'pt_namespace' => $this->mTitle
->getNamespace(),
1888 'pt_title' => $this->mTitle
->getDBkey(),
1889 'pt_create_perm' => $limit['create'],
1890 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1891 'pt_expiry' => $encodedExpiry['create'],
1892 'pt_user' => $user->getId(),
1893 'pt_reason' => $reason,
1897 $dbw->delete( 'protected_titles',
1899 'pt_namespace' => $this->mTitle
->getNamespace(),
1900 'pt_title' => $this->mTitle
->getDBkey()
1906 $this->mTitle
->flushRestrictions();
1908 if ( $logAction == 'unprotect' ) {
1909 $logParams = array();
1911 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1914 # Update the protection log
1915 $log = new LogPage( 'protect' );
1916 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1918 return Status
::newGood();
1922 * Take an array of page restrictions and flatten it to a string
1923 * suitable for insertion into the page_restrictions field.
1924 * @param $limit Array
1927 protected static function flattenRestrictions( $limit ) {
1928 if ( !is_array( $limit ) ) {
1929 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1935 foreach ( $limit as $action => $restrictions ) {
1936 if ( $restrictions != '' ) {
1937 $bits[] = "$action=$restrictions";
1941 return implode( ':', $bits );
1945 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
1946 * Deletes the article with database consistency, writes logs, purges caches
1948 * @param $reason string delete reason for deletion log
1949 * @param $suppress int bitfield
1950 * Revision::DELETED_TEXT
1951 * Revision::DELETED_COMMENT
1952 * Revision::DELETED_USER
1953 * Revision::DELETED_RESTRICTED
1954 * @param $id int article ID
1955 * @param $commit boolean defaults to true, triggers transaction end
1956 * @param &$error Array of errors to append to
1957 * @param $user User The deleting user
1958 * @return boolean true if successful
1960 public function doDeleteArticle(
1961 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1963 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
1964 == WikiPage
::DELETE_SUCCESS
;
1968 * Back-end article deletion
1969 * Deletes the article with database consistency, writes logs, purges caches
1971 * @param $reason string delete reason for deletion log
1972 * @param $suppress int bitfield
1973 * Revision::DELETED_TEXT
1974 * Revision::DELETED_COMMENT
1975 * Revision::DELETED_USER
1976 * Revision::DELETED_RESTRICTED
1977 * @param $id int article ID
1978 * @param $commit boolean defaults to true, triggers transaction end
1979 * @param &$error Array of errors to append to
1980 * @param $user User The deleting user
1981 * @return int: One of WikiPage::DELETE_* constants
1983 public function doDeleteArticleReal(
1984 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1987 $user = is_null( $user ) ?
$wgUser : $user;
1989 wfDebug( __METHOD__
. "\n" );
1991 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1992 return WikiPage
::DELETE_HOOK_ABORTED
;
1994 $dbw = wfGetDB( DB_MASTER
);
1995 $t = $this->mTitle
->getDBkey();
1996 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1998 if ( $t === '' ||
$id == 0 ) {
1999 return WikiPage
::DELETE_NO_PAGE
;
2002 // Bitfields to further suppress the content
2005 // This should be 15...
2006 $bitfield |
= Revision
::DELETED_TEXT
;
2007 $bitfield |
= Revision
::DELETED_COMMENT
;
2008 $bitfield |
= Revision
::DELETED_USER
;
2009 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2011 $bitfield = 'rev_deleted';
2014 $dbw->begin( __METHOD__
);
2015 // For now, shunt the revision data into the archive table.
2016 // Text is *not* removed from the text table; bulk storage
2017 // is left intact to avoid breaking block-compression or
2018 // immutable storage schemes.
2020 // For backwards compatibility, note that some older archive
2021 // table entries will have ar_text and ar_flags fields still.
2023 // In the future, we may keep revisions and mark them with
2024 // the rev_deleted field, which is reserved for this purpose.
2025 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2027 'ar_namespace' => 'page_namespace',
2028 'ar_title' => 'page_title',
2029 'ar_comment' => 'rev_comment',
2030 'ar_user' => 'rev_user',
2031 'ar_user_text' => 'rev_user_text',
2032 'ar_timestamp' => 'rev_timestamp',
2033 'ar_minor_edit' => 'rev_minor_edit',
2034 'ar_rev_id' => 'rev_id',
2035 'ar_parent_id' => 'rev_parent_id',
2036 'ar_text_id' => 'rev_text_id',
2037 'ar_text' => '\'\'', // Be explicit to appease
2038 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2039 'ar_len' => 'rev_len',
2040 'ar_page_id' => 'page_id',
2041 'ar_deleted' => $bitfield,
2042 'ar_sha1' => 'rev_sha1'
2045 'page_id = rev_page'
2049 # Now that it's safely backed up, delete it
2050 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2051 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2054 $dbw->rollback( __METHOD__
);
2055 return WikiPage
::DELETE_NO_REVISIONS
;
2058 $this->doDeleteUpdates( $id );
2060 # Log the deletion, if the page was suppressed, log it at Oversight instead
2061 $logtype = $suppress ?
'suppress' : 'delete';
2063 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2064 $logEntry->setPerformer( $user );
2065 $logEntry->setTarget( $this->mTitle
);
2066 $logEntry->setComment( $reason );
2067 $logid = $logEntry->insert();
2068 $logEntry->publish( $logid );
2071 $dbw->commit( __METHOD__
);
2074 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2075 return WikiPage
::DELETE_SUCCESS
;
2079 * Do some database updates after deletion
2081 * @param $id Int: page_id value of the page being deleted
2083 public function doDeleteUpdates( $id ) {
2084 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2086 $dbw = wfGetDB( DB_MASTER
);
2088 # Delete restrictions for it
2089 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2091 # Fix category table counts
2093 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2095 foreach ( $res as $row ) {
2096 $cats [] = $row->cl_to
;
2099 $this->updateCategoryCounts( array(), $cats );
2101 # If using cascading deletes, we can skip some explicit deletes
2102 if ( !$dbw->cascadingDeletes() ) {
2103 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2105 # Delete outgoing links
2106 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2107 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2108 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2109 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2110 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2111 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2112 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2113 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2114 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2117 # If using cleanup triggers, we can skip some manual deletes
2118 if ( !$dbw->cleanupTriggers() ) {
2119 # Clean up recentchanges entries...
2120 $dbw->delete( 'recentchanges',
2121 array( 'rc_type != ' . RC_LOG
,
2122 'rc_namespace' => $this->mTitle
->getNamespace(),
2123 'rc_title' => $this->mTitle
->getDBkey() ),
2125 $dbw->delete( 'recentchanges',
2126 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2131 self
::onArticleDelete( $this->mTitle
);
2136 # Clear the cached article id so the interface doesn't act like we exist
2137 $this->mTitle
->resetArticleID( 0 );
2141 * Roll back the most recent consecutive set of edits to a page
2142 * from the same user; fails if there are no eligible edits to
2143 * roll back to, e.g. user is the sole contributor. This function
2144 * performs permissions checks on $user, then calls commitRollback()
2145 * to do the dirty work
2147 * @todo: seperate the business/permission stuff out from backend code
2149 * @param $fromP String: Name of the user whose edits to rollback.
2150 * @param $summary String: Custom summary. Set to default summary if empty.
2151 * @param $token String: Rollback token.
2152 * @param $bot Boolean: If true, mark all reverted edits as bot.
2154 * @param $resultDetails Array: contains result-specific array of additional values
2155 * 'alreadyrolled' : 'current' (rev)
2156 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2158 * @param $user User The user performing the rollback
2159 * @return array of errors, each error formatted as
2160 * array(messagekey, param1, param2, ...).
2161 * On success, the array is empty. This array can also be passed to
2162 * OutputPage::showPermissionsErrorPage().
2164 public function doRollback(
2165 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2167 $resultDetails = null;
2170 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2171 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2172 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2174 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2175 $errors[] = array( 'sessionfailure' );
2178 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2179 $errors[] = array( 'actionthrottledtext' );
2182 # If there were errors, bail out now
2183 if ( !empty( $errors ) ) {
2187 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2191 * Backend implementation of doRollback(), please refer there for parameter
2192 * and return value documentation
2194 * NOTE: This function does NOT check ANY permissions, it just commits the
2195 * rollback to the DB. Therefore, you should only call this function direct-
2196 * ly if you want to use custom permissions checks. If you don't, use
2197 * doRollback() instead.
2198 * @param $fromP String: Name of the user whose edits to rollback.
2199 * @param $summary String: Custom summary. Set to default summary if empty.
2200 * @param $bot Boolean: If true, mark all reverted edits as bot.
2202 * @param $resultDetails Array: contains result-specific array of additional values
2203 * @param $guser User The user performing the rollback
2206 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2207 global $wgUseRCPatrol, $wgContLang;
2209 $dbw = wfGetDB( DB_MASTER
);
2211 if ( wfReadOnly() ) {
2212 return array( array( 'readonlytext' ) );
2215 # Get the last editor
2216 $current = $this->getRevision();
2217 if ( is_null( $current ) ) {
2218 # Something wrong... no page?
2219 return array( array( 'notanarticle' ) );
2222 $from = str_replace( '_', ' ', $fromP );
2223 # User name given should match up with the top revision.
2224 # If the user was deleted then $from should be empty.
2225 if ( $from != $current->getUserText() ) {
2226 $resultDetails = array( 'current' => $current );
2227 return array( array( 'alreadyrolled',
2228 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2229 htmlspecialchars( $fromP ),
2230 htmlspecialchars( $current->getUserText() )
2234 # Get the last edit not by this guy...
2235 # Note: these may not be public values
2236 $user = intval( $current->getRawUser() );
2237 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2238 $s = $dbw->selectRow( 'revision',
2239 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2240 array( 'rev_page' => $current->getPage(),
2241 "rev_user != {$user} OR rev_user_text != {$user_text}"
2243 array( 'USE INDEX' => 'page_timestamp',
2244 'ORDER BY' => 'rev_timestamp DESC' )
2246 if ( $s === false ) {
2247 # No one else ever edited this page
2248 return array( array( 'cantrollback' ) );
2249 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2250 # Only admins can see this text
2251 return array( array( 'notvisiblerev' ) );
2255 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2256 # Mark all reverted edits as bot
2260 if ( $wgUseRCPatrol ) {
2261 # Mark all reverted edits as patrolled
2262 $set['rc_patrolled'] = 1;
2265 if ( count( $set ) ) {
2266 $dbw->update( 'recentchanges', $set,
2268 'rc_cur_id' => $current->getPage(),
2269 'rc_user_text' => $current->getUserText(),
2270 "rc_timestamp > '{$s->rev_timestamp}'",
2275 # Generate the edit summary if necessary
2276 $target = Revision
::newFromId( $s->rev_id
);
2277 if ( empty( $summary ) ) {
2278 if ( $from == '' ) { // no public user name
2279 $summary = wfMsgForContent( 'revertpage-nouser' );
2281 $summary = wfMsgForContent( 'revertpage' );
2285 # Allow the custom summary to use the same args as the default message
2287 $target->getUserText(), $from, $s->rev_id
,
2288 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2289 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2291 $summary = wfMsgReplaceArgs( $summary, $args );
2294 $flags = EDIT_UPDATE
;
2296 if ( $guser->isAllowed( 'minoredit' ) ) {
2297 $flags |
= EDIT_MINOR
;
2300 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2301 $flags |
= EDIT_FORCE_BOT
;
2304 # Actually store the edit
2305 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2306 if ( !empty( $status->value
['revision'] ) ) {
2307 $revId = $status->value
['revision']->getId();
2312 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2314 $resultDetails = array(
2315 'summary' => $summary,
2316 'current' => $current,
2317 'target' => $target,
2325 * The onArticle*() functions are supposed to be a kind of hooks
2326 * which should be called whenever any of the specified actions
2329 * This is a good place to put code to clear caches, for instance.
2331 * This is called on page move and undelete, as well as edit
2333 * @param $title Title object
2335 public static function onArticleCreate( $title ) {
2336 # Update existence markers on article/talk tabs...
2337 if ( $title->isTalkPage() ) {
2338 $other = $title->getSubjectPage();
2340 $other = $title->getTalkPage();
2343 $other->invalidateCache();
2344 $other->purgeSquid();
2346 $title->touchLinks();
2347 $title->purgeSquid();
2348 $title->deleteTitleProtection();
2352 * Clears caches when article is deleted
2354 * @param $title Title
2356 public static function onArticleDelete( $title ) {
2357 # Update existence markers on article/talk tabs...
2358 if ( $title->isTalkPage() ) {
2359 $other = $title->getSubjectPage();
2361 $other = $title->getTalkPage();
2364 $other->invalidateCache();
2365 $other->purgeSquid();
2367 $title->touchLinks();
2368 $title->purgeSquid();
2371 HTMLFileCache
::clearFileCache( $title );
2374 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2375 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2379 if ( $title->getNamespace() == NS_FILE
) {
2380 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2381 $update->doUpdate();
2385 if ( $title->getNamespace() == NS_USER_TALK
) {
2386 $user = User
::newFromName( $title->getText(), false );
2388 $user->setNewtalk( false );
2393 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2397 * Purge caches on page update etc
2399 * @param $title Title object
2400 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2402 public static function onArticleEdit( $title ) {
2403 // Invalidate caches of articles which include this page
2404 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2407 // Invalidate the caches of all pages which redirect here
2408 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2410 # Purge squid for this page only
2411 $title->purgeSquid();
2413 # Clear file cache for this page only
2414 HTMLFileCache
::clearFileCache( $title );
2420 * Returns a list of hidden categories this page is a member of.
2421 * Uses the page_props and categorylinks tables.
2423 * @return Array of Title objects
2425 public function getHiddenCategories() {
2427 $id = $this->mTitle
->getArticleID();
2433 $dbr = wfGetDB( DB_SLAVE
);
2434 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2436 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2437 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2440 if ( $res !== false ) {
2441 foreach ( $res as $row ) {
2442 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2450 * Return an applicable autosummary if one exists for the given edit.
2451 * @param $oldtext String: the previous text of the page.
2452 * @param $newtext String: The submitted text of the page.
2453 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2454 * @return string An appropriate autosummary, or an empty string.
2456 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2459 # Decide what kind of autosummary is needed.
2461 # Redirect autosummaries
2462 $ot = Title
::newFromRedirect( $oldtext );
2463 $rt = Title
::newFromRedirect( $newtext );
2465 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2466 $truncatedtext = $wgContLang->truncate(
2467 str_replace( "\n", ' ', $newtext ),
2469 - strlen( wfMsgForContent( 'autoredircomment' ) )
2470 - strlen( $rt->getFullText() )
2472 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2475 # New page autosummaries
2476 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2477 # If they're making a new article, give its text, truncated, in the summary.
2479 $truncatedtext = $wgContLang->truncate(
2480 str_replace( "\n", ' ', $newtext ),
2481 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2483 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2486 # Blanking autosummaries
2487 if ( $oldtext != '' && $newtext == '' ) {
2488 return wfMsgForContent( 'autosumm-blank' );
2489 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2490 # Removing more than 90% of the article
2492 $truncatedtext = $wgContLang->truncate(
2494 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2496 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2499 # If we reach this point, there's no applicable autosummary for our case, so our
2500 # autosummary is empty.
2505 * Auto-generates a deletion reason
2507 * @param &$hasHistory Boolean: whether the page has a history
2508 * @return mixed String containing deletion reason or empty string, or boolean false
2509 * if no revision occurred
2511 public function getAutoDeleteReason( &$hasHistory ) {
2514 // Get the last revision
2515 $rev = $this->getRevision();
2517 if ( is_null( $rev ) ) {
2521 // Get the article's contents
2522 $contents = $rev->getText();
2525 // If the page is blank, use the text from the previous revision,
2526 // which can only be blank if there's a move/import/protect dummy revision involved
2527 if ( $contents == '' ) {
2528 $prev = $rev->getPrevious();
2531 $contents = $prev->getText();
2536 $dbw = wfGetDB( DB_MASTER
);
2538 // Find out if there was only one contributor
2539 // Only scan the last 20 revisions
2540 $res = $dbw->select( 'revision', 'rev_user_text',
2541 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2543 array( 'LIMIT' => 20 )
2546 if ( $res === false ) {
2547 // This page has no revisions, which is very weird
2551 $hasHistory = ( $res->numRows() > 1 );
2552 $row = $dbw->fetchObject( $res );
2554 if ( $row ) { // $row is false if the only contributor is hidden
2555 $onlyAuthor = $row->rev_user_text
;
2556 // Try to find a second contributor
2557 foreach ( $res as $row ) {
2558 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2559 $onlyAuthor = false;
2564 $onlyAuthor = false;
2567 // Generate the summary with a '$1' placeholder
2569 // The current revision is blank and the one before is also
2570 // blank. It's just not our lucky day
2571 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2573 if ( $onlyAuthor ) {
2574 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2576 $reason = wfMsgForContent( 'excontent', '$1' );
2580 if ( $reason == '-' ) {
2581 // Allow these UI messages to be blanked out cleanly
2585 // Replace newlines with spaces to prevent uglyness
2586 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2587 // Calculate the maximum amount of chars to get
2588 // Max content length = max comment length - length of the comment (excl. $1)
2589 $maxLength = 255 - ( strlen( $reason ) - 2 );
2590 $contents = $wgContLang->truncate( $contents, $maxLength );
2591 // Remove possible unfinished links
2592 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2593 // Now replace the '$1' placeholder
2594 $reason = str_replace( '$1', $contents, $reason );
2600 * Update all the appropriate counts in the category table, given that
2601 * we've added the categories $added and deleted the categories $deleted.
2603 * @param $added array The names of categories that were added
2604 * @param $deleted array The names of categories that were deleted
2606 public function updateCategoryCounts( $added, $deleted ) {
2607 $ns = $this->mTitle
->getNamespace();
2608 $dbw = wfGetDB( DB_MASTER
);
2610 # First make sure the rows exist. If one of the "deleted" ones didn't
2611 # exist, we might legitimately not create it, but it's simpler to just
2612 # create it and then give it a negative value, since the value is bogus
2615 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2616 $insertCats = array_merge( $added, $deleted );
2617 if ( !$insertCats ) {
2618 # Okay, nothing to do
2622 $insertRows = array();
2624 foreach ( $insertCats as $cat ) {
2625 $insertRows[] = array(
2626 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2630 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2632 $addFields = array( 'cat_pages = cat_pages + 1' );
2633 $removeFields = array( 'cat_pages = cat_pages - 1' );
2635 if ( $ns == NS_CATEGORY
) {
2636 $addFields[] = 'cat_subcats = cat_subcats + 1';
2637 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2638 } elseif ( $ns == NS_FILE
) {
2639 $addFields[] = 'cat_files = cat_files + 1';
2640 $removeFields[] = 'cat_files = cat_files - 1';
2647 array( 'cat_title' => $added ),
2656 array( 'cat_title' => $deleted ),
2663 * Updates cascading protections
2665 * @param $parserOutput ParserOutput object for the current version
2667 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2668 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2672 // templatelinks table may have become out of sync,
2673 // especially if using variable-based transclusions.
2674 // For paranoia, check if things have changed and if
2675 // so apply updates to the database. This will ensure
2676 // that cascaded protections apply as soon as the changes
2679 # Get templates from templatelinks
2680 $id = $this->mTitle
->getArticleID();
2682 $tlTemplates = array();
2684 $dbr = wfGetDB( DB_SLAVE
);
2685 $res = $dbr->select( array( 'templatelinks' ),
2686 array( 'tl_namespace', 'tl_title' ),
2687 array( 'tl_from' => $id ),
2691 foreach ( $res as $row ) {
2692 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2695 # Get templates from parser output.
2696 $poTemplates = array();
2697 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2698 foreach ( $templates as $dbk => $id ) {
2699 $poTemplates["$ns:$dbk"] = true;
2704 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2706 if ( count( $templates_diff ) > 0 ) {
2707 # Whee, link updates time.
2708 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2714 * Return a list of templates used by this article.
2715 * Uses the templatelinks table
2717 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2718 * @return Array of Title objects
2720 public function getUsedTemplates() {
2721 return $this->mTitle
->getTemplateLinksFrom();
2725 * Perform article updates on a special page creation.
2727 * @param $rev Revision object
2729 * @todo This is a shitty interface function. Kill it and replace the
2730 * other shitty functions like doEditUpdates and such so it's not needed
2732 * @deprecated since 1.18, use doEditUpdates()
2734 public function createUpdates( $rev ) {
2735 wfDeprecated( __METHOD__
, '1.18' );
2737 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2741 * This function is called right before saving the wikitext,
2742 * so we can do things like signatures and links-in-context.
2744 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2745 * @param $text String article contents
2746 * @param $user User object: user doing the edit
2747 * @param $popts ParserOptions object: parser options, default options for
2748 * the user loaded if null given
2749 * @return string article contents with altered wikitext markup (signatures
2750 * converted, {{subst:}}, templates, etc.)
2752 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2753 global $wgParser, $wgUser;
2755 wfDeprecated( __METHOD__
, '1.19' );
2757 $user = is_null( $user ) ?
$wgUser : $user;
2759 if ( $popts === null ) {
2760 $popts = ParserOptions
::newFromUser( $user );
2763 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2767 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2769 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2772 public function isBigDeletion() {
2773 wfDeprecated( __METHOD__
, '1.19' );
2774 return $this->mTitle
->isBigDeletion();
2778 * Get the approximate revision count of this page.
2780 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2783 public function estimateRevisionCount() {
2784 wfDeprecated( __METHOD__
, '1.19' );
2785 return $this->mTitle
->estimateRevisionCount();
2789 * Update the article's restriction field, and leave a log entry.
2791 * @deprecated since 1.19
2792 * @param $limit Array: set of restriction keys
2793 * @param $reason String
2794 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2795 * @param $expiry Array: per restriction type expiration
2796 * @param $user User The user updating the restrictions
2797 * @return bool true on success
2799 public function updateRestrictions(
2800 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2804 $user = is_null( $user ) ?
$wgUser : $user;
2806 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2810 * @deprecated since 1.18
2812 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2813 wfDeprecated( __METHOD__
, '1.18' );
2815 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2819 * @deprecated since 1.18
2821 public function viewUpdates() {
2822 wfDeprecated( __METHOD__
, '1.18' );
2824 return $this->doViewUpdates( $wgUser );
2828 * @deprecated since 1.18
2831 public function useParserCache( $oldid ) {
2832 wfDeprecated( __METHOD__
, '1.18' );
2834 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2838 class PoolWorkArticleView
extends PoolCounterWork
{
2856 * @var ParserOptions
2858 private $parserOptions;
2866 * @var ParserOutput|bool
2868 private $parserOutput = false;
2873 private $isDirty = false;
2878 private $error = false;
2884 * @param $revid Integer: ID of the revision being parsed
2885 * @param $useParserCache Boolean: whether to use the parser cache
2886 * @param $parserOptions parserOptions to use for the parse operation
2887 * @param $text String: text to parse or null to load it
2889 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2890 $this->page
= $page;
2891 $this->revid
= $revid;
2892 $this->cacheable
= $useParserCache;
2893 $this->parserOptions
= $parserOptions;
2894 $this->text
= $text;
2895 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2896 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2900 * Get the ParserOutput from this object, or false in case of failure
2902 * @return ParserOutput
2904 public function getParserOutput() {
2905 return $this->parserOutput
;
2909 * Get whether the ParserOutput is a dirty one (i.e. expired)
2913 public function getIsDirty() {
2914 return $this->isDirty
;
2918 * Get a Status object in case of error or false otherwise
2920 * @return Status|bool
2922 public function getError() {
2923 return $this->error
;
2930 global $wgParser, $wgUseFileCache;
2932 $isCurrent = $this->revid
=== $this->page
->getLatest();
2934 if ( $this->text
!== null ) {
2935 $text = $this->text
;
2936 } elseif ( $isCurrent ) {
2937 $text = $this->page
->getRawText();
2939 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2940 if ( $rev === null ) {
2943 $text = $rev->getText();
2946 $time = - microtime( true );
2947 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2948 $this->parserOptions
, true, true, $this->revid
);
2949 $time +
= microtime( true );
2953 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2954 $this->page
->getTitle()->getPrefixedDBkey() ) );
2957 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2958 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2961 // Make sure file cache is not used on uncacheable content.
2962 // Output that has magic words in it can still use the parser cache
2963 // (if enabled), though it will generally expire sooner.
2964 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2965 $wgUseFileCache = false;
2969 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2978 function getCachedWork() {
2979 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2981 if ( $this->parserOutput
=== false ) {
2982 wfDebug( __METHOD__
. ": parser cache miss\n" );
2985 wfDebug( __METHOD__
. ": parser cache hit\n" );
2993 function fallback() {
2994 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2996 if ( $this->parserOutput
=== false ) {
2997 wfDebugLog( 'dirty', "dirty missing\n" );
2998 wfDebug( __METHOD__
. ": no dirty cache\n" );
3001 wfDebug( __METHOD__
. ": sending dirty output\n" );
3002 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3003 $this->isDirty
= true;
3009 * @param $status Status
3012 function error( $status ) {
3013 $this->error
= $status;