3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
26 abstract class Page
{}
29 * Class representing a MediaWiki article and history.
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
34 * @internal documentation reviewed 15 Mar 2010
36 class WikiPage
extends Page
{
37 // Constants for $mDataLoadedFrom and related
40 * Data has not been loaded yet (or the object was cleared)
42 const DATA_NOT_LOADED
= 0;
45 * Data has been loaded from a slave database
47 const DATA_FROM_SLAVE
= 1;
50 * Data has been loaded from the master database
52 const DATA_FROM_MASTER
= 2;
55 * Data has been loaded from the master database using FOR UPDATE
57 const DATA_FOR_UPDATE
= 3;
62 public $mTitle = null;
67 public $mDataLoaded = false; // !< Boolean
68 public $mIsRedirect = false; // !< Boolean
69 public $mLatest = false; // !< Integer (false means "not loaded")
70 public $mPreparedEdit = false; // !< Array
74 * @var int; one of the DATA_* constants
76 protected $mDataLoadedFrom = self
::DATA_NOT_LOADED
;
81 protected $mRedirectTarget = null;
86 protected $mLastRevision = null;
89 * @var string; timestamp of the current revision or empty string if not loaded
91 protected $mTimestamp = '';
96 protected $mTouched = '19700101000000';
101 protected $mCounter = null;
104 * Constructor and clear the article
105 * @param $title Title Reference to a Title object.
107 public function __construct( Title
$title ) {
108 $this->mTitle
= $title;
112 * Create a WikiPage object of the appropriate class for the given title.
114 * @param $title Title
115 * @return WikiPage object of the appropriate type
117 public static function factory( Title
$title ) {
118 $ns = $title->getNamespace();
120 if ( $ns == NS_MEDIA
) {
121 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
122 } elseif ( $ns < 0 ) {
123 throw new MWException( "Invalid or virtual namespace $ns given." );
128 $page = new WikiFilePage( $title );
131 $page = new WikiCategoryPage( $title );
134 $page = new WikiPage( $title );
141 * Constructor from a page id
143 * @param $id Int article ID to load
144 * @param $from string|int one of the following values:
145 * - "fromdb" or self::DATA_FROM_SLAVE to select from a slave database
146 * - "fromdbmaster" or self::DATA_FROM_MASTER to select from the master database
148 * @return WikiPage|null
150 public static function newFromID( $id, $from = 'fromdb' ) {
151 $from = self
::convertSelectType( $from );
152 $db = wfGetDB( $from === self
::DATA_FROM_MASTER ? DB_MASTER
: DB_SLAVE
);
153 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
157 return self
::newFromRow( $row, $from );
161 * Constructor from a database row
164 * @param $row object: database row containing at least fields returned
166 * @param $from string|int: source of $data:
167 * - "fromdb" or self::DATA_FROM_SLAVE: from a slave DB
168 * - "fromdbmaster" or self::DATA_FROM_MASTER: from the master DB
169 * - "forupdate" or self::DATA_FOR_UPDATE: from the master DB using SELECT FOR UPDATE
172 public static function newFromRow( $row, $from = 'fromdb' ) {
173 $page = self
::factory( Title
::newFromRow( $row ) );
174 $page->loadFromRow( $row, $from );
179 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to DATA_* constants.
181 * @param $type object|string|int
184 private static function convertSelectType( $type ) {
187 return self
::DATA_FROM_SLAVE
;
189 return self
::DATA_FROM_MASTER
;
191 return self
::DATA_FOR_UPDATE
;
193 // It may already be an integer or whatever else
199 * Returns overrides for action handlers.
200 * Classes listed here will be used instead of the default one when
201 * (and only when) $wgActions[$action] === true. This allows subclasses
202 * to override the default behavior.
204 * @todo: move this UI stuff somewhere else
208 public function getActionOverrides() {
213 * Get the title object of the article
214 * @return Title object of this page
216 public function getTitle() {
217 return $this->mTitle
;
224 public function clear() {
225 $this->mDataLoaded
= false;
226 $this->mDataLoadedFrom
= self
::DATA_NOT_LOADED
;
228 $this->clearCacheFields();
232 * Clear the object cache fields
235 protected function clearCacheFields() {
236 $this->mCounter
= null;
237 $this->mRedirectTarget
= null; # Title object if set
238 $this->mLastRevision
= null; # Latest revision
239 $this->mTouched
= '19700101000000';
240 $this->mTimestamp
= '';
241 $this->mIsRedirect
= false;
242 $this->mLatest
= false;
243 $this->mPreparedEdit
= false;
247 * Return the list of revision fields that should be selected to create
252 public static function selectFields() {
269 * Fetch a page record with the given conditions
270 * @param $dbr DatabaseBase object
271 * @param $conditions Array
272 * @param $options Array
273 * @return mixed Database result resource, or false on failure
275 protected function pageData( $dbr, $conditions, $options = array() ) {
276 $fields = self
::selectFields();
278 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
280 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
282 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
288 * Fetch a page record matching the Title object's namespace and title
289 * using a sanitized title string
291 * @param $dbr DatabaseBase object
292 * @param $title Title object
293 * @param $options Array
294 * @return mixed Database result resource, or false on failure
296 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
297 return $this->pageData( $dbr, array(
298 'page_namespace' => $title->getNamespace(),
299 'page_title' => $title->getDBkey() ), $options );
303 * Fetch a page record matching the requested ID
305 * @param $dbr DatabaseBase
307 * @param $options Array
308 * @return mixed Database result resource, or false on failure
310 public function pageDataFromId( $dbr, $id, $options = array() ) {
311 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
315 * Set the general counter, title etc data loaded from
318 * @param $from object|string|int One of the following:
319 * - A DB query result object
320 * - "fromdb" or self::DATA_FROM_SLAVE to get from a slave DB
321 * - "fromdbmaster" or self::DATA_FROM_MASTER to get from the master DB
322 * - "forupdate" or self::DATA_FOR_UPDATE to get from the master DB using SELECT FOR UPDATE
326 public function loadPageData( $from = 'fromdb' ) {
327 $from = self
::convertSelectType( $from );
328 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
329 // We already have the data from the correct location, no need to load it twice.
333 if ( $from === self
::DATA_FOR_UPDATE
) {
334 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
335 } elseif ( $from === self
::DATA_FROM_MASTER
) {
336 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
337 } elseif ( $from === self
::DATA_FROM_SLAVE
) {
338 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
339 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
340 # Note that DB also stores the master position in the session and checks it.
341 $touched = $this->getCachedLastEditTime();
342 if ( $touched ) { // key set
343 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
344 $from = self
::DATA_FROM_MASTER
;
345 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
349 // No idea from where the caller got this data, assume slave database.
351 $from = self
::DATA_FROM_SLAVE
;
354 $this->loadFromRow( $data, $from );
358 * Load the object from a database row
361 * @param $data object: database row containing at least fields returned
363 * @param $from string|int One of the following:
364 * - "fromdb" or self::DATA_FROM_SLAVE if the data comes from a slave DB
365 * - "fromdbmaster" or self::DATA_FROM_MASTER if the data comes from the master DB
366 * - "forupdate" or self::DATA_FOR_UPDATE if the data comes from from
367 * the master DB using SELECT FOR UPDATE
369 public function loadFromRow( $data, $from ) {
370 $lc = LinkCache
::singleton();
373 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
375 $this->mTitle
->loadFromRow( $data );
377 # Old-fashioned restrictions
378 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
380 $this->mCounter
= intval( $data->page_counter
);
381 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
382 $this->mIsRedirect
= intval( $data->page_is_redirect
);
383 $this->mLatest
= intval( $data->page_latest
);
384 // Bug 37225: $latest may no longer match the cached latest Revision object.
385 // Double-check the ID of any cached latest Revision object for consistency.
386 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
387 $this->mLastRevision
= null;
388 $this->mTimestamp
= '';
391 $lc->addBadLinkObj( $this->mTitle
);
393 $this->mTitle
->loadFromRow( false );
395 $this->clearCacheFields();
398 $this->mDataLoaded
= true;
399 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
403 * @return int Page ID
405 public function getId() {
406 return $this->mTitle
->getArticleID();
410 * @return bool Whether or not the page exists in the database
412 public function exists() {
413 return $this->mTitle
->exists();
417 * Check if this page is something we're going to be showing
418 * some sort of sensible content for. If we return false, page
419 * views (plain action=view) will return an HTTP 404 response,
420 * so spiders and robots can know they're following a bad link.
424 public function hasViewableContent() {
425 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
429 * @return int The view count for the page
431 public function getCount() {
432 if ( !$this->mDataLoaded
) {
433 $this->loadPageData();
436 return $this->mCounter
;
440 * Tests if the article text represents a redirect
442 * @param $text mixed string containing article contents, or boolean
445 public function isRedirect( $text = false ) {
446 if ( $text === false ) {
447 if ( !$this->mDataLoaded
) {
448 $this->loadPageData();
451 return (bool)$this->mIsRedirect
;
453 return Title
::newFromRedirect( $text ) !== null;
458 * Loads page_touched and returns a value indicating if it should be used
459 * @return boolean true if not a redirect
461 public function checkTouched() {
462 if ( !$this->mDataLoaded
) {
463 $this->loadPageData();
465 return !$this->mIsRedirect
;
469 * Get the page_touched field
470 * @return string containing GMT timestamp
472 public function getTouched() {
473 if ( !$this->mDataLoaded
) {
474 $this->loadPageData();
476 return $this->mTouched
;
480 * Get the page_latest field
481 * @return integer rev_id of current revision
483 public function getLatest() {
484 if ( !$this->mDataLoaded
) {
485 $this->loadPageData();
487 return (int)$this->mLatest
;
491 * Get the Revision object of the oldest revision
492 * @return Revision|null
494 public function getOldestRevision() {
495 wfProfileIn( __METHOD__
);
497 // Try using the slave database first, then try the master
499 $db = wfGetDB( DB_SLAVE
);
500 $revSelectFields = Revision
::selectFields();
502 while ( $continue ) {
503 $row = $db->selectRow(
504 array( 'page', 'revision' ),
507 'page_namespace' => $this->mTitle
->getNamespace(),
508 'page_title' => $this->mTitle
->getDBkey(),
513 'ORDER BY' => 'rev_timestamp ASC'
520 $db = wfGetDB( DB_MASTER
);
525 wfProfileOut( __METHOD__
);
526 return $row ? Revision
::newFromRow( $row ) : null;
530 * Loads everything except the text
531 * This isn't necessary for all uses, so it's only done if needed.
533 protected function loadLastEdit() {
534 if ( $this->mLastRevision
!== null ) {
535 return; // already loaded
538 $latest = $this->getLatest();
540 return; // page doesn't exist or is missing page_latest info
543 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
544 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
545 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
546 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
547 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
548 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
549 $flags = ( $this->mDataLoadedFrom
== self
::DATA_FOR_UPDATE
) ? Revision
::LOCKING_READ
: 0;
550 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
551 if ( $revision ) { // sanity
552 $this->setLastEdit( $revision );
557 * Set the latest revision
559 protected function setLastEdit( Revision
$revision ) {
560 $this->mLastRevision
= $revision;
561 $this->mTimestamp
= $revision->getTimestamp();
565 * Get the latest revision
566 * @return Revision|null
568 public function getRevision() {
569 $this->loadLastEdit();
570 if ( $this->mLastRevision
) {
571 return $this->mLastRevision
;
577 * Get the text of the current revision. No side-effects...
579 * @param $audience Integer: one of:
580 * Revision::FOR_PUBLIC to be displayed to all users
581 * Revision::FOR_THIS_USER to be displayed to $wgUser
582 * Revision::RAW get the text regardless of permissions
583 * @return String|bool The text of the current revision. False on failure
585 public function getText( $audience = Revision
::FOR_PUBLIC
) {
586 $this->loadLastEdit();
587 if ( $this->mLastRevision
) {
588 return $this->mLastRevision
->getText( $audience );
594 * Get the text of the current revision. No side-effects...
596 * @return String|bool The text of the current revision. False on failure
598 public function getRawText() {
599 $this->loadLastEdit();
600 if ( $this->mLastRevision
) {
601 return $this->mLastRevision
->getRawText();
607 * @return string MW timestamp of last article revision
609 public function getTimestamp() {
610 // Check if the field has been filled by WikiPage::setTimestamp()
611 if ( !$this->mTimestamp
) {
612 $this->loadLastEdit();
615 return wfTimestamp( TS_MW
, $this->mTimestamp
);
619 * Set the page timestamp (use only to avoid DB queries)
620 * @param $ts string MW timestamp of last article revision
623 public function setTimestamp( $ts ) {
624 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
628 * @param $audience Integer: one of:
629 * Revision::FOR_PUBLIC to be displayed to all users
630 * Revision::FOR_THIS_USER to be displayed to $wgUser
631 * Revision::RAW get the text regardless of permissions
632 * @return int user ID for the user that made the last article revision
634 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
635 $this->loadLastEdit();
636 if ( $this->mLastRevision
) {
637 return $this->mLastRevision
->getUser( $audience );
644 * Get the User object of the user who created the page
645 * @param $audience Integer: one of:
646 * Revision::FOR_PUBLIC to be displayed to all users
647 * Revision::FOR_THIS_USER to be displayed to $wgUser
648 * Revision::RAW get the text regardless of permissions
651 public function getCreator( $audience = Revision
::FOR_PUBLIC
) {
652 $revision = $this->getOldestRevision();
654 $userName = $revision->getUserText( $audience );
655 return User
::newFromName( $userName, false );
662 * @param $audience Integer: one of:
663 * Revision::FOR_PUBLIC to be displayed to all users
664 * Revision::FOR_THIS_USER to be displayed to $wgUser
665 * Revision::RAW get the text regardless of permissions
666 * @return string username of the user that made the last article revision
668 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
669 $this->loadLastEdit();
670 if ( $this->mLastRevision
) {
671 return $this->mLastRevision
->getUserText( $audience );
678 * @param $audience Integer: one of:
679 * Revision::FOR_PUBLIC to be displayed to all users
680 * Revision::FOR_THIS_USER to be displayed to $wgUser
681 * Revision::RAW get the text regardless of permissions
682 * @return string Comment stored for the last article revision
684 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
685 $this->loadLastEdit();
686 if ( $this->mLastRevision
) {
687 return $this->mLastRevision
->getComment( $audience );
694 * Returns true if last revision was marked as "minor edit"
696 * @return boolean Minor edit indicator for the last article revision.
698 public function getMinorEdit() {
699 $this->loadLastEdit();
700 if ( $this->mLastRevision
) {
701 return $this->mLastRevision
->isMinor();
708 * Get the cached timestamp for the last time the page changed.
709 * This is only used to help handle slave lag by comparing to page_touched.
710 * @return string MW timestamp
712 protected function getCachedLastEditTime() {
714 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
715 return $wgMemc->get( $key );
719 * Set the cached timestamp for the last time the page changed.
720 * This is only used to help handle slave lag by comparing to page_touched.
721 * @param $timestamp string
724 public function setCachedLastEditTime( $timestamp ) {
726 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
727 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
731 * Determine whether a page would be suitable for being counted as an
732 * article in the site_stats table based on the title & its content
734 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
735 * if false, the current database state will be used
738 public function isCountable( $editInfo = false ) {
739 global $wgArticleCountMethod;
741 if ( !$this->mTitle
->isContentPage() ) {
745 $text = $editInfo ?
$editInfo->pst
: false;
747 if ( $this->isRedirect( $text ) ) {
751 switch ( $wgArticleCountMethod ) {
755 if ( $text === false ) {
756 $text = $this->getRawText();
758 return strpos( $text, ',' ) !== false;
761 // ParserOutput::getLinks() is a 2D array of page links, so
762 // to be really correct we would need to recurse in the array
763 // but the main array should only have items in it if there are
765 return (bool)count( $editInfo->output
->getLinks() );
767 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
768 array( 'pl_from' => $this->getId() ), __METHOD__
);
774 * If this page is a redirect, get its target
776 * The target will be fetched from the redirect table if possible.
777 * If this page doesn't have an entry there, call insertRedirect()
778 * @return Title|mixed object, or null if this page is not a redirect
780 public function getRedirectTarget() {
781 if ( !$this->mTitle
->isRedirect() ) {
785 if ( $this->mRedirectTarget
!== null ) {
786 return $this->mRedirectTarget
;
789 # Query the redirect table
790 $dbr = wfGetDB( DB_SLAVE
);
791 $row = $dbr->selectRow( 'redirect',
792 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
793 array( 'rd_from' => $this->getId() ),
797 // rd_fragment and rd_interwiki were added later, populate them if empty
798 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
799 return $this->mRedirectTarget
= Title
::makeTitle(
800 $row->rd_namespace
, $row->rd_title
,
801 $row->rd_fragment
, $row->rd_interwiki
);
804 # This page doesn't have an entry in the redirect table
805 return $this->mRedirectTarget
= $this->insertRedirect();
809 * Insert an entry for this page into the redirect table.
811 * Don't call this function directly unless you know what you're doing.
812 * @return Title object or null if not a redirect
814 public function insertRedirect() {
815 // recurse through to only get the final target
816 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
820 $this->insertRedirectEntry( $retval );
825 * Insert or update the redirect table entry for this page to indicate
826 * it redirects to $rt .
827 * @param $rt Title redirect target
829 public function insertRedirectEntry( $rt ) {
830 $dbw = wfGetDB( DB_MASTER
);
831 $dbw->replace( 'redirect', array( 'rd_from' ),
833 'rd_from' => $this->getId(),
834 'rd_namespace' => $rt->getNamespace(),
835 'rd_title' => $rt->getDBkey(),
836 'rd_fragment' => $rt->getFragment(),
837 'rd_interwiki' => $rt->getInterwiki(),
844 * Get the Title object or URL this page redirects to
846 * @return mixed false, Title of in-wiki target, or string with URL
848 public function followRedirect() {
849 return $this->getRedirectURL( $this->getRedirectTarget() );
853 * Get the Title object or URL to use for a redirect. We use Title
854 * objects for same-wiki, non-special redirects and URLs for everything
856 * @param $rt Title Redirect target
857 * @return mixed false, Title object of local target, or string with URL
859 public function getRedirectURL( $rt ) {
864 if ( $rt->isExternal() ) {
865 if ( $rt->isLocal() ) {
866 // Offsite wikis need an HTTP redirect.
868 // This can be hard to reverse and may produce loops,
869 // so they may be disabled in the site configuration.
870 $source = $this->mTitle
->getFullURL( 'redirect=no' );
871 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
873 // External pages pages without "local" bit set are not valid
879 if ( $rt->isSpecialPage() ) {
880 // Gotta handle redirects to special pages differently:
881 // Fill the HTTP response "Location" header and ignore
882 // the rest of the page we're on.
884 // Some pages are not valid targets
885 if ( $rt->isValidRedirectTarget() ) {
886 return $rt->getFullURL();
896 * Get a list of users who have edited this article, not including the user who made
897 * the most recent revision, which you can get from $article->getUser() if you want it
898 * @return UserArrayFromResult
900 public function getContributors() {
901 # @todo FIXME: This is expensive; cache this info somewhere.
903 $dbr = wfGetDB( DB_SLAVE
);
905 if ( $dbr->implicitGroupby() ) {
906 $realNameField = 'user_real_name';
908 $realNameField = 'MIN(user_real_name) AS user_real_name';
911 $tables = array( 'revision', 'user' );
914 'rev_user as user_id',
915 'rev_user_text AS user_name',
917 'MAX(rev_timestamp) AS timestamp',
920 $conds = array( 'rev_page' => $this->getId() );
922 // The user who made the top revision gets credited as "this page was last edited by
923 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
924 $user = $this->getUser();
926 $conds[] = "rev_user != $user";
928 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
931 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
934 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
938 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
939 'ORDER BY' => 'timestamp DESC',
942 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
943 return new UserArrayFromResult( $res );
947 * Get the last N authors
948 * @param $num Integer: number of revisions to get
949 * @param $revLatest String: the latest rev_id, selected from the master (optional)
950 * @return array Array of authors, duplicates not removed
952 public function getLastNAuthors( $num, $revLatest = 0 ) {
953 wfProfileIn( __METHOD__
);
954 // First try the slave
955 // If that doesn't have the latest revision, try the master
957 $db = wfGetDB( DB_SLAVE
);
960 $res = $db->select( array( 'page', 'revision' ),
961 array( 'rev_id', 'rev_user_text' ),
963 'page_namespace' => $this->mTitle
->getNamespace(),
964 'page_title' => $this->mTitle
->getDBkey(),
968 'ORDER BY' => 'rev_timestamp DESC',
974 wfProfileOut( __METHOD__
);
978 $row = $db->fetchObject( $res );
980 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
981 $db = wfGetDB( DB_MASTER
);
986 } while ( $continue );
988 $authors = array( $row->rev_user_text
);
990 foreach ( $res as $row ) {
991 $authors[] = $row->rev_user_text
;
994 wfProfileOut( __METHOD__
);
999 * Should the parser cache be used?
1001 * @param $parserOptions ParserOptions to check
1005 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1006 global $wgEnableParserCache;
1008 return $wgEnableParserCache
1009 && $parserOptions->getStubThreshold() == 0
1010 && $this->mTitle
->exists()
1011 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1012 && $this->mTitle
->isWikitextPage();
1016 * Get a ParserOutput for the given ParserOptions and revision ID.
1017 * The parser cache will be used if possible.
1020 * @param $parserOptions ParserOptions to use for the parse operation
1021 * @param $oldid Revision ID to get the text from, passing null or 0 will
1022 * get the current revision (default value)
1023 * @return ParserOutput or false if the revision was not found
1025 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1026 wfProfileIn( __METHOD__
);
1028 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1029 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1030 if ( $parserOptions->getStubThreshold() ) {
1031 wfIncrStats( 'pcache_miss_stub' );
1034 if ( $useParserCache ) {
1035 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1036 if ( $parserOutput !== false ) {
1037 wfProfileOut( __METHOD__
);
1038 return $parserOutput;
1042 if ( $oldid === null ||
$oldid === 0 ) {
1043 $oldid = $this->getLatest();
1046 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1049 wfProfileOut( __METHOD__
);
1051 return $pool->getParserOutput();
1055 * Do standard deferred updates after page view
1056 * @param $user User The relevant user
1058 public function doViewUpdates( User
$user ) {
1059 global $wgDisableCounters;
1060 if ( wfReadOnly() ) {
1064 # Don't update page view counters on views from bot users (bug 14044)
1065 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1066 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1067 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1070 # Update newtalk / watchlist notification status
1071 $user->clearNotification( $this->mTitle
);
1075 * Perform the actions of a page purging
1078 public function doPurge() {
1081 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1085 // Invalidate the cache
1086 $this->mTitle
->invalidateCache();
1089 if ( $wgUseSquid ) {
1090 // Commit the transaction before the purge is sent
1091 $dbw = wfGetDB( DB_MASTER
);
1092 $dbw->commit( __METHOD__
);
1095 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1096 $update->doUpdate();
1099 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1100 if ( $this->mTitle
->exists() ) {
1101 $text = $this->getRawText();
1106 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1112 * Insert a new empty page record for this article.
1113 * This *must* be followed up by creating a revision
1114 * and running $this->updateRevisionOn( ... );
1115 * or else the record will be left in a funky state.
1116 * Best if all done inside a transaction.
1118 * @param $dbw DatabaseBase
1119 * @return int The newly created page_id key, or false if the title already existed
1121 public function insertOn( $dbw ) {
1122 wfProfileIn( __METHOD__
);
1124 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1125 $dbw->insert( 'page', array(
1126 'page_id' => $page_id,
1127 'page_namespace' => $this->mTitle
->getNamespace(),
1128 'page_title' => $this->mTitle
->getDBkey(),
1129 'page_counter' => 0,
1130 'page_restrictions' => '',
1131 'page_is_redirect' => 0, # Will set this shortly...
1133 'page_random' => wfRandom(),
1134 'page_touched' => $dbw->timestamp(),
1135 'page_latest' => 0, # Fill this in shortly...
1136 'page_len' => 0, # Fill this in shortly...
1137 ), __METHOD__
, 'IGNORE' );
1139 $affected = $dbw->affectedRows();
1142 $newid = $dbw->insertId();
1143 $this->mTitle
->resetArticleID( $newid );
1145 wfProfileOut( __METHOD__
);
1147 return $affected ?
$newid : false;
1151 * Update the page record to point to a newly saved revision.
1153 * @param $dbw DatabaseBase: object
1154 * @param $revision Revision: For ID number, and text used to set
1155 * length and redirect status fields
1156 * @param $lastRevision Integer: if given, will not overwrite the page field
1157 * when different from the currently set value.
1158 * Giving 0 indicates the new page flag should be set
1160 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1161 * removing rows in redirect table.
1162 * @return bool true on success, false on failure
1165 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1166 wfProfileIn( __METHOD__
);
1168 $text = $revision->getText();
1169 $len = strlen( $text );
1170 $rt = Title
::newFromRedirectRecurse( $text );
1172 $conditions = array( 'page_id' => $this->getId() );
1174 if ( !is_null( $lastRevision ) ) {
1175 # An extra check against threads stepping on each other
1176 $conditions['page_latest'] = $lastRevision;
1179 $now = wfTimestampNow();
1180 $dbw->update( 'page',
1182 'page_latest' => $revision->getId(),
1183 'page_touched' => $dbw->timestamp( $now ),
1184 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1185 'page_is_redirect' => $rt !== null ?
1 : 0,
1191 $result = $dbw->affectedRows() > 0;
1193 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1194 $this->setLastEdit( $revision );
1195 $this->setCachedLastEditTime( $now );
1196 $this->mLatest
= $revision->getId();
1197 $this->mIsRedirect
= (bool)$rt;
1198 # Update the LinkCache.
1199 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1202 wfProfileOut( __METHOD__
);
1207 * Add row to the redirect table if this is a redirect, remove otherwise.
1209 * @param $dbw DatabaseBase
1210 * @param $redirectTitle Title object pointing to the redirect target,
1211 * or NULL if this is not a redirect
1212 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1213 * removing rows in redirect table.
1214 * @return bool true on success, false on failure
1217 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1218 // Always update redirects (target link might have changed)
1219 // Update/Insert if we don't know if the last revision was a redirect or not
1220 // Delete if changing from redirect to non-redirect
1221 $isRedirect = !is_null( $redirectTitle );
1223 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1227 wfProfileIn( __METHOD__
);
1228 if ( $isRedirect ) {
1229 $this->insertRedirectEntry( $redirectTitle );
1231 // This is not a redirect, remove row from redirect table
1232 $where = array( 'rd_from' => $this->getId() );
1233 $dbw->delete( 'redirect', $where, __METHOD__
);
1236 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1237 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1239 wfProfileOut( __METHOD__
);
1241 return ( $dbw->affectedRows() != 0 );
1245 * If the given revision is newer than the currently set page_latest,
1246 * update the page record. Otherwise, do nothing.
1248 * @param $dbw DatabaseBase object
1249 * @param $revision Revision object
1252 public function updateIfNewerOn( $dbw, $revision ) {
1253 wfProfileIn( __METHOD__
);
1255 $row = $dbw->selectRow(
1256 array( 'revision', 'page' ),
1257 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1259 'page_id' => $this->getId(),
1260 'page_latest=rev_id' ),
1264 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1265 wfProfileOut( __METHOD__
);
1268 $prev = $row->rev_id
;
1269 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1271 # No or missing previous revision; mark the page as new
1273 $lastRevIsRedirect = null;
1276 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1278 wfProfileOut( __METHOD__
);
1283 * Get the text that needs to be saved in order to undo all revisions
1284 * between $undo and $undoafter. Revisions must belong to the same page,
1285 * must exist and must not be deleted
1286 * @param $undo Revision
1287 * @param $undoafter Revision Must be an earlier revision than $undo
1288 * @return mixed string on success, false on failure
1290 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1291 $cur_text = $this->getRawText();
1292 if ( $cur_text === false ) {
1293 return false; // no page
1295 $undo_text = $undo->getText();
1296 $undoafter_text = $undoafter->getText();
1298 if ( $cur_text == $undo_text ) {
1299 # No use doing a merge if it's just a straight revert.
1300 return $undoafter_text;
1305 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1309 return $undone_text;
1313 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1314 * @param $text String: new text of the section
1315 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1316 * @param $edittime String: revision timestamp or null to use the current revision
1317 * @return string Complete article text, or null if error
1319 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1320 wfProfileIn( __METHOD__
);
1322 if ( strval( $section ) == '' ) {
1323 // Whole-page edit; let the whole text through
1325 // Bug 30711: always use current version when adding a new section
1326 if ( is_null( $edittime ) ||
$section == 'new' ) {
1327 $oldtext = $this->getRawText();
1328 if ( $oldtext === false ) {
1329 wfDebug( __METHOD__
. ": no page text\n" );
1330 wfProfileOut( __METHOD__
);
1334 $dbw = wfGetDB( DB_MASTER
);
1335 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1338 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1339 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1340 wfProfileOut( __METHOD__
);
1344 $oldtext = $rev->getText();
1347 if ( $section == 'new' ) {
1348 # Inserting a new section
1349 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1350 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1351 $text = strlen( trim( $oldtext ) ) > 0
1352 ?
"{$oldtext}\n\n{$subject}{$text}"
1353 : "{$subject}{$text}";
1356 # Replacing an existing section; roll out the big guns
1359 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1363 wfProfileOut( __METHOD__
);
1368 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1370 * @return Int updated $flags
1372 function checkFlags( $flags ) {
1373 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1374 if ( $this->mTitle
->getArticleID() ) {
1375 $flags |
= EDIT_UPDATE
;
1385 * Change an existing article or create a new article. Updates RC and all necessary caches,
1386 * optionally via the deferred update array.
1388 * @param $text String: new text
1389 * @param $summary String: edit summary
1390 * @param $flags Integer bitfield:
1392 * Article is known or assumed to be non-existent, create a new one
1394 * Article is known or assumed to be pre-existing, update it
1396 * Mark this edit minor, if the user is allowed to do so
1398 * Do not log the change in recentchanges
1400 * Mark the edit a "bot" edit regardless of user rights
1401 * EDIT_DEFER_UPDATES
1402 * Defer some of the updates until the end of index.php
1404 * Fill in blank summaries with generated text where possible
1406 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1407 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1408 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1409 * edit-already-exists error will be returned. These two conditions are also possible with
1410 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1412 * @param $baseRevId int the revision ID this edit was based off, if any
1413 * @param $user User the user doing the edit
1415 * @return Status object. Possible errors:
1416 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1417 * edit-gone-missing: In update mode, but the article didn't exist
1418 * edit-conflict: In update mode, the article changed unexpectedly
1419 * edit-no-change: Warning that the text was the same as before
1420 * edit-already-exists: In creation mode, but the article already exists
1422 * Extensions may define additional errors.
1424 * $return->value will contain an associative array with members as follows:
1425 * new: Boolean indicating if the function attempted to create a new article
1426 * revision: The revision object for the inserted revision, or null
1428 * Compatibility note: this function previously returned a boolean value indicating success/failure
1430 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1431 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1433 # Low-level sanity check
1434 if ( $this->mTitle
->getText() === '' ) {
1435 throw new MWException( 'Something is trying to edit an article with an empty title' );
1438 wfProfileIn( __METHOD__
);
1440 $user = is_null( $user ) ?
$wgUser : $user;
1441 $status = Status
::newGood( array() );
1443 // Load the data from the master database if needed.
1444 // The caller may already loaded it from the master or even loaded it using
1445 // SELECT FOR UPDATE, so do not override that using clear().
1446 $this->loadPageData( 'fromdbmaster' );
1448 $flags = $this->checkFlags( $flags );
1450 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1451 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1453 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1455 if ( $status->isOK() ) {
1456 $status->fatal( 'edit-hook-aborted' );
1459 wfProfileOut( __METHOD__
);
1463 # Silently ignore EDIT_MINOR if not allowed
1464 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1465 $bot = $flags & EDIT_FORCE_BOT
;
1467 $oldtext = $this->getRawText(); // current revision
1468 $oldsize = strlen( $oldtext );
1469 $oldid = $this->getLatest();
1470 $oldIsRedirect = $this->isRedirect();
1471 $oldcountable = $this->isCountable();
1473 # Provide autosummaries if one is not provided and autosummaries are enabled.
1474 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1475 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1478 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1479 $text = $editInfo->pst
;
1480 $newsize = strlen( $text );
1482 $dbw = wfGetDB( DB_MASTER
);
1483 $now = wfTimestampNow();
1484 $this->mTimestamp
= $now;
1486 if ( $flags & EDIT_UPDATE
) {
1487 # Update article, but only if changed.
1488 $status->value
['new'] = false;
1491 # Article gone missing
1492 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1493 $status->fatal( 'edit-gone-missing' );
1495 wfProfileOut( __METHOD__
);
1497 } elseif ( $oldtext === false ) {
1498 # Sanity check for bug 37225
1499 wfProfileOut( __METHOD__
);
1500 throw new MWException( "Could not find text for current revision {$oldid}." );
1503 $revision = new Revision( array(
1504 'page' => $this->getId(),
1505 'comment' => $summary,
1506 'minor_edit' => $isminor,
1508 'parent_id' => $oldid,
1509 'user' => $user->getId(),
1510 'user_text' => $user->getName(),
1513 # Bug 37225: use accessor to get the text as Revision may trim it.
1514 # After trimming, the text may be a duplicate of the current text.
1515 $text = $revision->getText(); // sanity; EditPage should trim already
1517 $changed = ( strcmp( $text, $oldtext ) != 0 );
1520 $dbw->begin( __METHOD__
);
1521 $revisionId = $revision->insertOn( $dbw );
1525 # Note that we use $this->mLatest instead of fetching a value from the master DB
1526 # during the course of this function. This makes sure that EditPage can detect
1527 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1528 # before this function is called. A previous function used a separate query, this
1529 # creates a window where concurrent edits can cause an ignored edit conflict.
1530 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1533 # Belated edit conflict! Run away!!
1534 $status->fatal( 'edit-conflict' );
1536 $dbw->rollback( __METHOD__
);
1538 wfProfileOut( __METHOD__
);
1542 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1543 # Update recentchanges
1544 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1545 # Mark as patrolled if the user can do so
1546 $patrolled = $wgUseRCPatrol && !count(
1547 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1548 # Add RC row to the DB
1549 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1550 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1551 $revisionId, $patrolled
1554 # Log auto-patrolled edits
1556 PatrolLog
::record( $rc, true, $user );
1559 $user->incEditCount();
1560 $dbw->commit( __METHOD__
);
1562 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1563 // related variables correctly
1564 $revision->setId( $this->getLatest() );
1567 # Update links tables, site stats, etc.
1568 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1569 'oldcountable' => $oldcountable ) );
1572 $status->warning( 'edit-no-change' );
1574 // Update page_touched, this is usually implicit in the page update
1575 // Other cache updates are done in onArticleEdit()
1576 $this->mTitle
->invalidateCache();
1579 # Create new article
1580 $status->value
['new'] = true;
1582 $dbw->begin( __METHOD__
);
1584 # Add the page record; stake our claim on this title!
1585 # This will return false if the article already exists
1586 $newid = $this->insertOn( $dbw );
1588 if ( $newid === false ) {
1589 $dbw->rollback( __METHOD__
);
1590 $status->fatal( 'edit-already-exists' );
1592 wfProfileOut( __METHOD__
);
1596 # Save the revision text...
1597 $revision = new Revision( array(
1599 'comment' => $summary,
1600 'minor_edit' => $isminor,
1602 'user' => $user->getId(),
1603 'user_text' => $user->getName(),
1606 $revisionId = $revision->insertOn( $dbw );
1608 # Bug 37225: use accessor to get the text as Revision may trim it
1609 $text = $revision->getText(); // sanity; EditPage should trim already
1611 # Update the page record with revision data
1612 $this->updateRevisionOn( $dbw, $revision, 0 );
1614 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1616 # Update recentchanges
1617 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1618 # Mark as patrolled if the user can do so
1619 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1620 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1621 # Add RC row to the DB
1622 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1623 '', strlen( $text ), $revisionId, $patrolled );
1625 # Log auto-patrolled edits
1627 PatrolLog
::record( $rc, true, $user );
1630 $user->incEditCount();
1631 $dbw->commit( __METHOD__
);
1633 # Update links, etc.
1634 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1636 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1637 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1640 # Do updates right now unless deferral was requested
1641 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1642 DeferredUpdates
::doUpdates();
1645 // Return the new revision (or null) to the caller
1646 $status->value
['revision'] = $revision;
1648 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1649 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1651 # Promote user to any groups they meet the criteria for
1652 $user->addAutopromoteOnceGroups( 'onEdit' );
1654 wfProfileOut( __METHOD__
);
1659 * Get parser options suitable for rendering the primary article wikitext
1660 * @param User|string $user User object or 'canonical'
1661 * @return ParserOptions
1663 public function makeParserOptions( $user ) {
1665 if ( $user instanceof User
) { // settings per user (even anons)
1666 $options = ParserOptions
::newFromUser( $user );
1667 } else { // canonical settings
1668 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1670 $options->enableLimitReport(); // show inclusion/loop reports
1671 $options->setTidy( true ); // fix bad HTML
1676 * Prepare text which is about to be saved.
1677 * Returns a stdclass with source, pst and output members
1678 * @return bool|object
1680 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1681 global $wgParser, $wgContLang, $wgUser;
1682 $user = is_null( $user ) ?
$wgUser : $user;
1683 // @TODO fixme: check $user->getId() here???
1684 if ( $this->mPreparedEdit
1685 && $this->mPreparedEdit
->newText
== $text
1686 && $this->mPreparedEdit
->revid
== $revid
1689 return $this->mPreparedEdit
;
1692 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1693 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1695 $edit = (object)array();
1696 $edit->revid
= $revid;
1697 $edit->newText
= $text;
1698 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1699 $edit->popts
= $this->makeParserOptions( 'canonical' );
1700 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1701 $edit->oldText
= $this->getRawText();
1703 $this->mPreparedEdit
= $edit;
1709 * Do standard deferred updates after page edit.
1710 * Update links tables, site stats, search index and message cache.
1711 * Purges pages that include this page if the text was changed here.
1712 * Every 100th edit, prune the recent changes table.
1715 * @param $revision Revision object
1716 * @param $user User object that did the revision
1717 * @param $options Array of options, following indexes are used:
1718 * - changed: boolean, whether the revision changed the content (default true)
1719 * - created: boolean, whether the revision created the page (default false)
1720 * - oldcountable: boolean or null (default null):
1721 * - boolean: whether the page was counted as an article before that
1722 * revision, only used in changed is true and created is false
1723 * - null: don't change the article count
1725 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1726 global $wgEnableParserCache;
1728 wfProfileIn( __METHOD__
);
1730 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1731 $text = $revision->getText();
1734 # Be careful not to double-PST: $text is usually already PST-ed once
1735 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1736 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1737 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1739 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1740 $editInfo = $this->mPreparedEdit
;
1743 # Save it to the parser cache
1744 if ( $wgEnableParserCache ) {
1745 $parserCache = ParserCache
::singleton();
1746 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1749 # Update the links tables and other secondary data
1750 $updates = $editInfo->output
->getSecondaryDataUpdates( $this->mTitle
);
1751 DataUpdate
::runUpdates( $updates );
1753 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1755 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1756 if ( 0 == mt_rand( 0, 99 ) ) {
1757 // Flush old entries from the `recentchanges` table; we do this on
1758 // random requests so as to avoid an increase in writes for no good reason
1761 $dbw = wfGetDB( DB_MASTER
);
1762 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1765 array( "rc_timestamp < '$cutoff'" ),
1771 if ( !$this->mTitle
->exists() ) {
1772 wfProfileOut( __METHOD__
);
1776 $id = $this->getId();
1777 $title = $this->mTitle
->getPrefixedDBkey();
1778 $shortTitle = $this->mTitle
->getDBkey();
1780 if ( !$options['changed'] ) {
1783 } elseif ( $options['created'] ) {
1784 $good = (int)$this->isCountable( $editInfo );
1786 } elseif ( $options['oldcountable'] !== null ) {
1787 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1794 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1795 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1797 # If this is another user's talk page, update newtalk.
1798 # Don't do this if $options['changed'] = false (null-edits) nor if
1799 # it's a minor edit and the user doesn't want notifications for those.
1800 if ( $options['changed']
1801 && $this->mTitle
->getNamespace() == NS_USER_TALK
1802 && $shortTitle != $user->getTitleKey()
1803 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1805 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1806 $other = User
::newFromName( $shortTitle, false );
1808 wfDebug( __METHOD__
. ": invalid username\n" );
1809 } elseif ( User
::isIP( $shortTitle ) ) {
1810 // An anonymous user
1811 $other->setNewtalk( true );
1812 } elseif ( $other->isLoggedIn() ) {
1813 $other->setNewtalk( true );
1815 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1820 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1821 MessageCache
::singleton()->replace( $shortTitle, $text );
1824 if( $options['created'] ) {
1825 self
::onArticleCreate( $this->mTitle
);
1827 self
::onArticleEdit( $this->mTitle
);
1830 wfProfileOut( __METHOD__
);
1834 * Edit an article without doing all that other stuff
1835 * The article must already exist; link tables etc
1836 * are not updated, caches are not flushed.
1838 * @param $text String: text submitted
1839 * @param $user User The relevant user
1840 * @param $comment String: comment submitted
1841 * @param $minor Boolean: whereas it's a minor modification
1843 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1844 wfProfileIn( __METHOD__
);
1846 $dbw = wfGetDB( DB_MASTER
);
1847 $revision = new Revision( array(
1848 'page' => $this->getId(),
1850 'comment' => $comment,
1851 'minor_edit' => $minor ?
1 : 0,
1853 $revision->insertOn( $dbw );
1854 $this->updateRevisionOn( $dbw, $revision );
1856 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1858 wfProfileOut( __METHOD__
);
1862 * Update the article's restriction field, and leave a log entry.
1863 * This works for protection both existing and non-existing pages.
1865 * @param $limit Array: set of restriction keys
1866 * @param $reason String
1867 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1868 * @param $expiry Array: per restriction type expiration
1869 * @param $user User The user updating the restrictions
1872 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1875 if ( wfReadOnly() ) {
1876 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1879 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1881 $id = $this->mTitle
->getArticleID();
1887 // Take this opportunity to purge out expired restrictions
1888 Title
::purgeExpiredRestrictions();
1890 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1891 # we expect a single selection, but the schema allows otherwise.
1892 $isProtected = false;
1896 $dbw = wfGetDB( DB_MASTER
);
1898 foreach ( $restrictionTypes as $action ) {
1899 if ( !isset( $expiry[$action] ) ) {
1900 $expiry[$action] = $dbw->getInfinity();
1902 if ( !isset( $limit[$action] ) ) {
1903 $limit[$action] = '';
1904 } elseif ( $limit[$action] != '' ) {
1908 # Get current restrictions on $action
1909 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1910 if ( $current != '' ) {
1911 $isProtected = true;
1914 if ( $limit[$action] != $current ) {
1916 } elseif ( $limit[$action] != '' ) {
1917 # Only check expiry change if the action is actually being
1918 # protected, since expiry does nothing on an not-protected
1920 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1926 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1930 # If nothing's changed, do nothing
1932 return Status
::newGood();
1935 if ( !$protect ) { # No protection at all means unprotection
1936 $revCommentMsg = 'unprotectedarticle';
1937 $logAction = 'unprotect';
1938 } elseif ( $isProtected ) {
1939 $revCommentMsg = 'modifiedarticleprotection';
1940 $logAction = 'modify';
1942 $revCommentMsg = 'protectedarticle';
1943 $logAction = 'protect';
1946 $encodedExpiry = array();
1947 $protectDescription = '';
1948 foreach ( $limit as $action => $restrictions ) {
1949 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1950 if ( $restrictions != '' ) {
1951 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1952 if ( $encodedExpiry[$action] != 'infinity' ) {
1953 $protectDescription .= wfMsgForContent( 'protect-expiring',
1954 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1955 $wgContLang->date( $expiry[$action], false, false ) ,
1956 $wgContLang->time( $expiry[$action], false, false ) );
1958 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1961 $protectDescription .= ') ';
1964 $protectDescription = trim( $protectDescription );
1966 if ( $id ) { # Protection of existing page
1967 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1968 return Status
::newGood();
1971 # Only restrictions with the 'protect' right can cascade...
1972 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1973 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1975 # The schema allows multiple restrictions
1976 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1980 # Update restrictions table
1981 foreach ( $limit as $action => $restrictions ) {
1982 if ( $restrictions != '' ) {
1983 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1984 array( 'pr_page' => $id,
1985 'pr_type' => $action,
1986 'pr_level' => $restrictions,
1987 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1988 'pr_expiry' => $encodedExpiry[$action]
1993 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1994 'pr_type' => $action ), __METHOD__
);
1998 # Prepare a null revision to be added to the history
1999 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2001 $editComment .= ": $reason";
2003 if ( $protectDescription ) {
2004 $editComment .= " ($protectDescription)";
2007 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2010 # Insert a null revision
2011 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2012 $nullRevId = $nullRevision->insertOn( $dbw );
2014 $latest = $this->getLatest();
2015 # Update page record
2016 $dbw->update( 'page',
2018 'page_touched' => $dbw->timestamp(),
2019 'page_restrictions' => '',
2020 'page_latest' => $nullRevId
2021 ), array( /* WHERE */
2026 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2027 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2028 } else { # Protection of non-existing page (also known as "title protection")
2029 # Cascade protection is meaningless in this case
2032 if ( $limit['create'] != '' ) {
2033 $dbw->replace( 'protected_titles',
2034 array( array( 'pt_namespace', 'pt_title' ) ),
2036 'pt_namespace' => $this->mTitle
->getNamespace(),
2037 'pt_title' => $this->mTitle
->getDBkey(),
2038 'pt_create_perm' => $limit['create'],
2039 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2040 'pt_expiry' => $encodedExpiry['create'],
2041 'pt_user' => $user->getId(),
2042 'pt_reason' => $reason,
2046 $dbw->delete( 'protected_titles',
2048 'pt_namespace' => $this->mTitle
->getNamespace(),
2049 'pt_title' => $this->mTitle
->getDBkey()
2055 $this->mTitle
->flushRestrictions();
2057 if ( $logAction == 'unprotect' ) {
2058 $logParams = array();
2060 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2063 # Update the protection log
2064 $log = new LogPage( 'protect' );
2065 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2067 return Status
::newGood();
2071 * Take an array of page restrictions and flatten it to a string
2072 * suitable for insertion into the page_restrictions field.
2073 * @param $limit Array
2076 protected static function flattenRestrictions( $limit ) {
2077 if ( !is_array( $limit ) ) {
2078 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2084 foreach ( $limit as $action => $restrictions ) {
2085 if ( $restrictions != '' ) {
2086 $bits[] = "$action=$restrictions";
2090 return implode( ':', $bits );
2094 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2095 * backwards compatibility, if you care about error reporting you should use
2096 * doDeleteArticleReal() instead.
2098 * Deletes the article with database consistency, writes logs, purges caches
2100 * @param $reason string delete reason for deletion log
2101 * @param $suppress int bitfield
2102 * Revision::DELETED_TEXT
2103 * Revision::DELETED_COMMENT
2104 * Revision::DELETED_USER
2105 * Revision::DELETED_RESTRICTED
2106 * @param $id int article ID
2107 * @param $commit boolean defaults to true, triggers transaction end
2108 * @param &$error Array of errors to append to
2109 * @param $user User The deleting user
2110 * @return boolean true if successful
2112 public function doDeleteArticle(
2113 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2115 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2116 return $status->isGood();
2120 * Back-end article deletion
2121 * Deletes the article with database consistency, writes logs, purges caches
2123 * @param $reason string delete reason for deletion log
2124 * @param $suppress int bitfield
2125 * Revision::DELETED_TEXT
2126 * Revision::DELETED_COMMENT
2127 * Revision::DELETED_USER
2128 * Revision::DELETED_RESTRICTED
2129 * @param $id int article ID
2130 * @param $commit boolean defaults to true, triggers transaction end
2131 * @param &$error Array of errors to append to
2132 * @param $user User The deleting user
2133 * @return Status: Status object; if successful, $status->value is the log_id of the
2134 * deletion log entry. If the page couldn't be deleted because it wasn't
2135 * found, $status is a non-fatal 'cannotdelete' error
2137 public function doDeleteArticleReal(
2138 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2142 wfDebug( __METHOD__
. "\n" );
2144 $status = Status
::newGood();
2146 if ( $this->mTitle
->getDBkey() === '' ) {
2147 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2151 $user = is_null( $user ) ?
$wgUser : $user;
2152 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2153 if ( $status->isOK() ) {
2154 // Hook aborted but didn't set a fatal status
2155 $status->fatal( 'delete-hook-aborted' );
2161 $this->loadPageData( 'forupdate' );
2162 $id = $this->getID();
2164 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2169 // Bitfields to further suppress the content
2172 // This should be 15...
2173 $bitfield |
= Revision
::DELETED_TEXT
;
2174 $bitfield |
= Revision
::DELETED_COMMENT
;
2175 $bitfield |
= Revision
::DELETED_USER
;
2176 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2178 $bitfield = 'rev_deleted';
2181 $dbw = wfGetDB( DB_MASTER
);
2182 $dbw->begin( __METHOD__
);
2183 // For now, shunt the revision data into the archive table.
2184 // Text is *not* removed from the text table; bulk storage
2185 // is left intact to avoid breaking block-compression or
2186 // immutable storage schemes.
2188 // For backwards compatibility, note that some older archive
2189 // table entries will have ar_text and ar_flags fields still.
2191 // In the future, we may keep revisions and mark them with
2192 // the rev_deleted field, which is reserved for this purpose.
2193 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2195 'ar_namespace' => 'page_namespace',
2196 'ar_title' => 'page_title',
2197 'ar_comment' => 'rev_comment',
2198 'ar_user' => 'rev_user',
2199 'ar_user_text' => 'rev_user_text',
2200 'ar_timestamp' => 'rev_timestamp',
2201 'ar_minor_edit' => 'rev_minor_edit',
2202 'ar_rev_id' => 'rev_id',
2203 'ar_parent_id' => 'rev_parent_id',
2204 'ar_text_id' => 'rev_text_id',
2205 'ar_text' => '\'\'', // Be explicit to appease
2206 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2207 'ar_len' => 'rev_len',
2208 'ar_page_id' => 'page_id',
2209 'ar_deleted' => $bitfield,
2210 'ar_sha1' => 'rev_sha1'
2213 'page_id = rev_page'
2217 # Now that it's safely backed up, delete it
2218 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2219 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2222 $dbw->rollback( __METHOD__
);
2223 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2227 $this->doDeleteUpdates( $id );
2229 # Log the deletion, if the page was suppressed, log it at Oversight instead
2230 $logtype = $suppress ?
'suppress' : 'delete';
2232 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2233 $logEntry->setPerformer( $user );
2234 $logEntry->setTarget( $this->mTitle
);
2235 $logEntry->setComment( $reason );
2236 $logid = $logEntry->insert();
2237 $logEntry->publish( $logid );
2240 $dbw->commit( __METHOD__
);
2243 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2244 $status->value
= $logid;
2249 * Do some database updates after deletion
2251 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2253 public function doDeleteUpdates( $id ) {
2254 # update site status
2255 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2257 # remove secondary indexes, etc
2258 $updates = $this->getDeletionUpdates( );
2259 DataUpdate
::runUpdates( $updates );
2262 WikiPage
::onArticleDelete( $this->mTitle
);
2267 # Clear the cached article id so the interface doesn't act like we exist
2268 $this->mTitle
->resetArticleID( 0 );
2271 public function getDeletionUpdates() {
2273 new LinksDeletionUpdate( $this ),
2276 //@todo: make a hook to add update objects
2277 //NOTE: deletion updates will be determined by the ContentHandler in the future
2282 * Roll back the most recent consecutive set of edits to a page
2283 * from the same user; fails if there are no eligible edits to
2284 * roll back to, e.g. user is the sole contributor. This function
2285 * performs permissions checks on $user, then calls commitRollback()
2286 * to do the dirty work
2288 * @todo: seperate the business/permission stuff out from backend code
2290 * @param $fromP String: Name of the user whose edits to rollback.
2291 * @param $summary String: Custom summary. Set to default summary if empty.
2292 * @param $token String: Rollback token.
2293 * @param $bot Boolean: If true, mark all reverted edits as bot.
2295 * @param $resultDetails Array: contains result-specific array of additional values
2296 * 'alreadyrolled' : 'current' (rev)
2297 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2299 * @param $user User The user performing the rollback
2300 * @return array of errors, each error formatted as
2301 * array(messagekey, param1, param2, ...).
2302 * On success, the array is empty. This array can also be passed to
2303 * OutputPage::showPermissionsErrorPage().
2305 public function doRollback(
2306 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2308 $resultDetails = null;
2311 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2312 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2313 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2315 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2316 $errors[] = array( 'sessionfailure' );
2319 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2320 $errors[] = array( 'actionthrottledtext' );
2323 # If there were errors, bail out now
2324 if ( !empty( $errors ) ) {
2328 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2332 * Backend implementation of doRollback(), please refer there for parameter
2333 * and return value documentation
2335 * NOTE: This function does NOT check ANY permissions, it just commits the
2336 * rollback to the DB. Therefore, you should only call this function direct-
2337 * ly if you want to use custom permissions checks. If you don't, use
2338 * doRollback() instead.
2339 * @param $fromP String: Name of the user whose edits to rollback.
2340 * @param $summary String: Custom summary. Set to default summary if empty.
2341 * @param $bot Boolean: If true, mark all reverted edits as bot.
2343 * @param $resultDetails Array: contains result-specific array of additional values
2344 * @param $guser User The user performing the rollback
2347 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2348 global $wgUseRCPatrol, $wgContLang;
2350 $dbw = wfGetDB( DB_MASTER
);
2352 if ( wfReadOnly() ) {
2353 return array( array( 'readonlytext' ) );
2356 # Get the last editor
2357 $current = $this->getRevision();
2358 if ( is_null( $current ) ) {
2359 # Something wrong... no page?
2360 return array( array( 'notanarticle' ) );
2363 $from = str_replace( '_', ' ', $fromP );
2364 # User name given should match up with the top revision.
2365 # If the user was deleted then $from should be empty.
2366 if ( $from != $current->getUserText() ) {
2367 $resultDetails = array( 'current' => $current );
2368 return array( array( 'alreadyrolled',
2369 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2370 htmlspecialchars( $fromP ),
2371 htmlspecialchars( $current->getUserText() )
2375 # Get the last edit not by this guy...
2376 # Note: these may not be public values
2377 $user = intval( $current->getRawUser() );
2378 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2379 $s = $dbw->selectRow( 'revision',
2380 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2381 array( 'rev_page' => $current->getPage(),
2382 "rev_user != {$user} OR rev_user_text != {$user_text}"
2384 array( 'USE INDEX' => 'page_timestamp',
2385 'ORDER BY' => 'rev_timestamp DESC' )
2387 if ( $s === false ) {
2388 # No one else ever edited this page
2389 return array( array( 'cantrollback' ) );
2390 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2391 # Only admins can see this text
2392 return array( array( 'notvisiblerev' ) );
2396 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2397 # Mark all reverted edits as bot
2401 if ( $wgUseRCPatrol ) {
2402 # Mark all reverted edits as patrolled
2403 $set['rc_patrolled'] = 1;
2406 if ( count( $set ) ) {
2407 $dbw->update( 'recentchanges', $set,
2409 'rc_cur_id' => $current->getPage(),
2410 'rc_user_text' => $current->getUserText(),
2411 "rc_timestamp > '{$s->rev_timestamp}'",
2416 # Generate the edit summary if necessary
2417 $target = Revision
::newFromId( $s->rev_id
);
2418 if ( empty( $summary ) ) {
2419 if ( $from == '' ) { // no public user name
2420 $summary = wfMsgForContent( 'revertpage-nouser' );
2422 $summary = wfMsgForContent( 'revertpage' );
2426 # Allow the custom summary to use the same args as the default message
2428 $target->getUserText(), $from, $s->rev_id
,
2429 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2430 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2432 $summary = wfMsgReplaceArgs( $summary, $args );
2435 $flags = EDIT_UPDATE
;
2437 if ( $guser->isAllowed( 'minoredit' ) ) {
2438 $flags |
= EDIT_MINOR
;
2441 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2442 $flags |
= EDIT_FORCE_BOT
;
2445 # Actually store the edit
2446 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2447 if ( !empty( $status->value
['revision'] ) ) {
2448 $revId = $status->value
['revision']->getId();
2453 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2455 $resultDetails = array(
2456 'summary' => $summary,
2457 'current' => $current,
2458 'target' => $target,
2466 * The onArticle*() functions are supposed to be a kind of hooks
2467 * which should be called whenever any of the specified actions
2470 * This is a good place to put code to clear caches, for instance.
2472 * This is called on page move and undelete, as well as edit
2474 * @param $title Title object
2476 public static function onArticleCreate( $title ) {
2477 # Update existence markers on article/talk tabs...
2478 if ( $title->isTalkPage() ) {
2479 $other = $title->getSubjectPage();
2481 $other = $title->getTalkPage();
2484 $other->invalidateCache();
2485 $other->purgeSquid();
2487 $title->touchLinks();
2488 $title->purgeSquid();
2489 $title->deleteTitleProtection();
2493 * Clears caches when article is deleted
2495 * @param $title Title
2497 public static function onArticleDelete( $title ) {
2498 # Update existence markers on article/talk tabs...
2499 if ( $title->isTalkPage() ) {
2500 $other = $title->getSubjectPage();
2502 $other = $title->getTalkPage();
2505 $other->invalidateCache();
2506 $other->purgeSquid();
2508 $title->touchLinks();
2509 $title->purgeSquid();
2512 HTMLFileCache
::clearFileCache( $title );
2515 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2516 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2520 if ( $title->getNamespace() == NS_FILE
) {
2521 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2522 $update->doUpdate();
2526 if ( $title->getNamespace() == NS_USER_TALK
) {
2527 $user = User
::newFromName( $title->getText(), false );
2529 $user->setNewtalk( false );
2534 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2538 * Purge caches on page update etc
2540 * @param $title Title object
2541 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2543 public static function onArticleEdit( $title ) {
2544 // Invalidate caches of articles which include this page
2545 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2548 // Invalidate the caches of all pages which redirect here
2549 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2551 # Purge squid for this page only
2552 $title->purgeSquid();
2554 # Clear file cache for this page only
2555 HTMLFileCache
::clearFileCache( $title );
2561 * Returns a list of hidden categories this page is a member of.
2562 * Uses the page_props and categorylinks tables.
2564 * @return Array of Title objects
2566 public function getHiddenCategories() {
2568 $id = $this->mTitle
->getArticleID();
2574 $dbr = wfGetDB( DB_SLAVE
);
2575 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2577 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2578 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2581 if ( $res !== false ) {
2582 foreach ( $res as $row ) {
2583 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2591 * Return an applicable autosummary if one exists for the given edit.
2592 * @param $oldtext String: the previous text of the page.
2593 * @param $newtext String: The submitted text of the page.
2594 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2595 * @return string An appropriate autosummary, or an empty string.
2597 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2600 # Decide what kind of autosummary is needed.
2602 # Redirect autosummaries
2603 $ot = Title
::newFromRedirect( $oldtext );
2604 $rt = Title
::newFromRedirect( $newtext );
2606 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2607 $truncatedtext = $wgContLang->truncate(
2608 str_replace( "\n", ' ', $newtext ),
2610 - strlen( wfMsgForContent( 'autoredircomment' ) )
2611 - strlen( $rt->getFullText() )
2613 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2616 # New page autosummaries
2617 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2618 # If they're making a new article, give its text, truncated, in the summary.
2620 $truncatedtext = $wgContLang->truncate(
2621 str_replace( "\n", ' ', $newtext ),
2622 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2624 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2627 # Blanking autosummaries
2628 if ( $oldtext != '' && $newtext == '' ) {
2629 return wfMsgForContent( 'autosumm-blank' );
2630 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2631 # Removing more than 90% of the article
2633 $truncatedtext = $wgContLang->truncate(
2635 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2637 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2640 # If we reach this point, there's no applicable autosummary for our case, so our
2641 # autosummary is empty.
2646 * Auto-generates a deletion reason
2648 * @param &$hasHistory Boolean: whether the page has a history
2649 * @return mixed String containing deletion reason or empty string, or boolean false
2650 * if no revision occurred
2652 public function getAutoDeleteReason( &$hasHistory ) {
2655 // Get the last revision
2656 $rev = $this->getRevision();
2658 if ( is_null( $rev ) ) {
2662 // Get the article's contents
2663 $contents = $rev->getText();
2666 // If the page is blank, use the text from the previous revision,
2667 // which can only be blank if there's a move/import/protect dummy revision involved
2668 if ( $contents == '' ) {
2669 $prev = $rev->getPrevious();
2672 $contents = $prev->getText();
2677 $dbw = wfGetDB( DB_MASTER
);
2679 // Find out if there was only one contributor
2680 // Only scan the last 20 revisions
2681 $res = $dbw->select( 'revision', 'rev_user_text',
2682 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2684 array( 'LIMIT' => 20 )
2687 if ( $res === false ) {
2688 // This page has no revisions, which is very weird
2692 $hasHistory = ( $res->numRows() > 1 );
2693 $row = $dbw->fetchObject( $res );
2695 if ( $row ) { // $row is false if the only contributor is hidden
2696 $onlyAuthor = $row->rev_user_text
;
2697 // Try to find a second contributor
2698 foreach ( $res as $row ) {
2699 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2700 $onlyAuthor = false;
2705 $onlyAuthor = false;
2708 // Generate the summary with a '$1' placeholder
2710 // The current revision is blank and the one before is also
2711 // blank. It's just not our lucky day
2712 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2714 if ( $onlyAuthor ) {
2715 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2717 $reason = wfMsgForContent( 'excontent', '$1' );
2721 if ( $reason == '-' ) {
2722 // Allow these UI messages to be blanked out cleanly
2726 // Replace newlines with spaces to prevent uglyness
2727 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2728 // Calculate the maximum amount of chars to get
2729 // Max content length = max comment length - length of the comment (excl. $1)
2730 $maxLength = 255 - ( strlen( $reason ) - 2 );
2731 $contents = $wgContLang->truncate( $contents, $maxLength );
2732 // Remove possible unfinished links
2733 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2734 // Now replace the '$1' placeholder
2735 $reason = str_replace( '$1', $contents, $reason );
2741 * Update all the appropriate counts in the category table, given that
2742 * we've added the categories $added and deleted the categories $deleted.
2744 * @param $added array The names of categories that were added
2745 * @param $deleted array The names of categories that were deleted
2747 public function updateCategoryCounts( $added, $deleted ) {
2748 $ns = $this->mTitle
->getNamespace();
2749 $dbw = wfGetDB( DB_MASTER
);
2751 # First make sure the rows exist. If one of the "deleted" ones didn't
2752 # exist, we might legitimately not create it, but it's simpler to just
2753 # create it and then give it a negative value, since the value is bogus
2756 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2757 $insertCats = array_merge( $added, $deleted );
2758 if ( !$insertCats ) {
2759 # Okay, nothing to do
2763 $insertRows = array();
2765 foreach ( $insertCats as $cat ) {
2766 $insertRows[] = array(
2767 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2771 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2773 $addFields = array( 'cat_pages = cat_pages + 1' );
2774 $removeFields = array( 'cat_pages = cat_pages - 1' );
2776 if ( $ns == NS_CATEGORY
) {
2777 $addFields[] = 'cat_subcats = cat_subcats + 1';
2778 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2779 } elseif ( $ns == NS_FILE
) {
2780 $addFields[] = 'cat_files = cat_files + 1';
2781 $removeFields[] = 'cat_files = cat_files - 1';
2788 array( 'cat_title' => $added ),
2797 array( 'cat_title' => $deleted ),
2804 * Updates cascading protections
2806 * @param $parserOutput ParserOutput object for the current version
2808 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2809 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2813 // templatelinks table may have become out of sync,
2814 // especially if using variable-based transclusions.
2815 // For paranoia, check if things have changed and if
2816 // so apply updates to the database. This will ensure
2817 // that cascaded protections apply as soon as the changes
2820 # Get templates from templatelinks
2821 $id = $this->mTitle
->getArticleID();
2823 $tlTemplates = array();
2825 $dbr = wfGetDB( DB_SLAVE
);
2826 $res = $dbr->select( array( 'templatelinks' ),
2827 array( 'tl_namespace', 'tl_title' ),
2828 array( 'tl_from' => $id ),
2832 foreach ( $res as $row ) {
2833 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2836 # Get templates from parser output.
2837 $poTemplates = array();
2838 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2839 foreach ( $templates as $dbk => $id ) {
2840 $poTemplates["$ns:$dbk"] = true;
2845 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2847 if ( count( $templates_diff ) > 0 ) {
2848 # Whee, link updates time.
2849 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
2850 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2856 * Return a list of templates used by this article.
2857 * Uses the templatelinks table
2859 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2860 * @return Array of Title objects
2862 public function getUsedTemplates() {
2863 return $this->mTitle
->getTemplateLinksFrom();
2867 * Perform article updates on a special page creation.
2869 * @param $rev Revision object
2871 * @todo This is a shitty interface function. Kill it and replace the
2872 * other shitty functions like doEditUpdates and such so it's not needed
2874 * @deprecated since 1.18, use doEditUpdates()
2876 public function createUpdates( $rev ) {
2877 wfDeprecated( __METHOD__
, '1.18' );
2879 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2883 * This function is called right before saving the wikitext,
2884 * so we can do things like signatures and links-in-context.
2886 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2887 * @param $text String article contents
2888 * @param $user User object: user doing the edit
2889 * @param $popts ParserOptions object: parser options, default options for
2890 * the user loaded if null given
2891 * @return string article contents with altered wikitext markup (signatures
2892 * converted, {{subst:}}, templates, etc.)
2894 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2895 global $wgParser, $wgUser;
2897 wfDeprecated( __METHOD__
, '1.19' );
2899 $user = is_null( $user ) ?
$wgUser : $user;
2901 if ( $popts === null ) {
2902 $popts = ParserOptions
::newFromUser( $user );
2905 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2909 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2911 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2914 public function isBigDeletion() {
2915 wfDeprecated( __METHOD__
, '1.19' );
2916 return $this->mTitle
->isBigDeletion();
2920 * Get the approximate revision count of this page.
2922 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2925 public function estimateRevisionCount() {
2926 wfDeprecated( __METHOD__
, '1.19' );
2927 return $this->mTitle
->estimateRevisionCount();
2931 * Update the article's restriction field, and leave a log entry.
2933 * @deprecated since 1.19
2934 * @param $limit Array: set of restriction keys
2935 * @param $reason String
2936 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2937 * @param $expiry Array: per restriction type expiration
2938 * @param $user User The user updating the restrictions
2939 * @return bool true on success
2941 public function updateRestrictions(
2942 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2946 $user = is_null( $user ) ?
$wgUser : $user;
2948 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2952 * @deprecated since 1.18
2954 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2955 wfDeprecated( __METHOD__
, '1.18' );
2957 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2961 * @deprecated since 1.18
2963 public function viewUpdates() {
2964 wfDeprecated( __METHOD__
, '1.18' );
2966 return $this->doViewUpdates( $wgUser );
2970 * @deprecated since 1.18
2973 public function useParserCache( $oldid ) {
2974 wfDeprecated( __METHOD__
, '1.18' );
2976 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2980 class PoolWorkArticleView
extends PoolCounterWork
{
2998 * @var ParserOptions
3000 private $parserOptions;
3008 * @var ParserOutput|bool
3010 private $parserOutput = false;
3015 private $isDirty = false;
3020 private $error = false;
3026 * @param $revid Integer: ID of the revision being parsed
3027 * @param $useParserCache Boolean: whether to use the parser cache
3028 * @param $parserOptions parserOptions to use for the parse operation
3029 * @param $text String: text to parse or null to load it
3031 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
3032 $this->page
= $page;
3033 $this->revid
= $revid;
3034 $this->cacheable
= $useParserCache;
3035 $this->parserOptions
= $parserOptions;
3036 $this->text
= $text;
3037 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3038 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3042 * Get the ParserOutput from this object, or false in case of failure
3044 * @return ParserOutput
3046 public function getParserOutput() {
3047 return $this->parserOutput
;
3051 * Get whether the ParserOutput is a dirty one (i.e. expired)
3055 public function getIsDirty() {
3056 return $this->isDirty
;
3060 * Get a Status object in case of error or false otherwise
3062 * @return Status|bool
3064 public function getError() {
3065 return $this->error
;
3072 global $wgParser, $wgUseFileCache;
3074 $isCurrent = $this->revid
=== $this->page
->getLatest();
3076 if ( $this->text
!== null ) {
3077 $text = $this->text
;
3078 } elseif ( $isCurrent ) {
3079 $text = $this->page
->getRawText();
3081 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3082 if ( $rev === null ) {
3085 $text = $rev->getText();
3088 $time = - microtime( true );
3089 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
3090 $this->parserOptions
, true, true, $this->revid
);
3091 $time +
= microtime( true );
3095 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3096 $this->page
->getTitle()->getPrefixedDBkey() ) );
3099 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3100 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3103 // Make sure file cache is not used on uncacheable content.
3104 // Output that has magic words in it can still use the parser cache
3105 // (if enabled), though it will generally expire sooner.
3106 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3107 $wgUseFileCache = false;
3111 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3120 function getCachedWork() {
3121 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3123 if ( $this->parserOutput
=== false ) {
3124 wfDebug( __METHOD__
. ": parser cache miss\n" );
3127 wfDebug( __METHOD__
. ": parser cache hit\n" );
3135 function fallback() {
3136 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3138 if ( $this->parserOutput
=== false ) {
3139 wfDebugLog( 'dirty', "dirty missing\n" );
3140 wfDebug( __METHOD__
. ": no dirty cache\n" );
3143 wfDebug( __METHOD__
. ": sending dirty output\n" );
3144 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3145 $this->isDirty
= true;
3151 * @param $status Status
3154 function error( $status ) {
3155 $this->error
= $status;