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
implements IDBAccessObject
{
37 // Constants for $mDataLoadedFrom and related
42 public $mTitle = null;
47 public $mDataLoaded = false; // !< Boolean
48 public $mIsRedirect = false; // !< Boolean
49 public $mLatest = false; // !< Integer (false means "not loaded")
50 public $mPreparedEdit = false; // !< Array
54 * @var int; one of the READ_* constants
56 protected $mDataLoadedFrom = self
::READ_NONE
;
61 protected $mRedirectTarget = null;
66 protected $mLastRevision = null;
69 * @var string; timestamp of the current revision or empty string if not loaded
71 protected $mTimestamp = '';
76 protected $mTouched = '19700101000000';
81 protected $mCounter = null;
84 * Constructor and clear the article
85 * @param $title Title Reference to a Title object.
87 public function __construct( Title
$title ) {
88 $this->mTitle
= $title;
92 * Create a WikiPage object of the appropriate class for the given title.
95 * @return WikiPage object of the appropriate type
97 public static function factory( Title
$title ) {
98 $ns = $title->getNamespace();
100 if ( $ns == NS_MEDIA
) {
101 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
102 } elseif ( $ns < 0 ) {
103 throw new MWException( "Invalid or virtual namespace $ns given." );
108 $page = new WikiFilePage( $title );
111 $page = new WikiCategoryPage( $title );
114 $page = new WikiPage( $title );
121 * Constructor from a page id
123 * @param $id Int article ID to load
124 * @param $from string|int one of the following values:
125 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
126 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
128 * @return WikiPage|null
130 public static function newFromID( $id, $from = 'fromdb' ) {
131 $from = self
::convertSelectType( $from );
132 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
133 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
137 return self
::newFromRow( $row, $from );
141 * Constructor from a database row
144 * @param $row object: database row containing at least fields returned
146 * @param $from string|int: source of $data:
147 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
148 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
149 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
152 public static function newFromRow( $row, $from = 'fromdb' ) {
153 $page = self
::factory( Title
::newFromRow( $row ) );
154 $page->loadFromRow( $row, $from );
159 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
161 * @param $type object|string|int
164 private static function convertSelectType( $type ) {
167 return self
::READ_NORMAL
;
169 return self
::READ_LATEST
;
171 return self
::READ_LOCKING
;
173 // It may already be an integer or whatever else
179 * Returns overrides for action handlers.
180 * Classes listed here will be used instead of the default one when
181 * (and only when) $wgActions[$action] === true. This allows subclasses
182 * to override the default behavior.
184 * @todo: move this UI stuff somewhere else
188 public function getActionOverrides() {
189 $content_handler = $this->getContentHandler();
190 return $content_handler->getActionOverrides();
194 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
196 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
198 * @return ContentHandler
202 public function getContentHandler() {
203 return ContentHandler
::getForModelID( $this->getContentModel() );
207 * Get the title object of the article
208 * @return Title object of this page
210 public function getTitle() {
211 return $this->mTitle
;
218 public function clear() {
219 $this->mDataLoaded
= false;
220 $this->mDataLoadedFrom
= self
::READ_NONE
;
222 $this->clearCacheFields();
226 * Clear the object cache fields
229 protected function clearCacheFields() {
230 $this->mCounter
= null;
231 $this->mRedirectTarget
= null; # Title object if set
232 $this->mLastRevision
= null; # Latest revision
233 $this->mTouched
= '19700101000000';
234 $this->mTimestamp
= '';
235 $this->mIsRedirect
= false;
236 $this->mLatest
= false;
237 $this->mPreparedEdit
= false;
241 * Return the list of revision fields that should be selected to create
246 public static function selectFields() {
247 global $wgContentHandlerUseDB;
263 if ( $wgContentHandlerUseDB ) {
264 $fields[] = 'page_content_model';
271 * Fetch a page record with the given conditions
272 * @param $dbr DatabaseBase object
273 * @param $conditions Array
274 * @param $options Array
275 * @return mixed Database result resource, or false on failure
277 protected function pageData( $dbr, $conditions, $options = array() ) {
278 $fields = self
::selectFields();
280 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
282 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
284 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
290 * Fetch a page record matching the Title object's namespace and title
291 * using a sanitized title string
293 * @param $dbr DatabaseBase object
294 * @param $title Title object
295 * @param $options Array
296 * @return mixed Database result resource, or false on failure
298 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
299 return $this->pageData( $dbr, array(
300 'page_namespace' => $title->getNamespace(),
301 'page_title' => $title->getDBkey() ), $options );
305 * Fetch a page record matching the requested ID
307 * @param $dbr DatabaseBase
309 * @param $options Array
310 * @return mixed Database result resource, or false on failure
312 public function pageDataFromId( $dbr, $id, $options = array() ) {
313 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
317 * Set the general counter, title etc data loaded from
320 * @param $from object|string|int One of the following:
321 * - A DB query result object
322 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
323 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
324 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
328 public function loadPageData( $from = 'fromdb' ) {
329 $from = self
::convertSelectType( $from );
330 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
331 // We already have the data from the correct location, no need to load it twice.
335 if ( $from === self
::READ_LOCKING
) {
336 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
337 } elseif ( $from === self
::READ_LATEST
) {
338 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
339 } elseif ( $from === self
::READ_NORMAL
) {
340 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
341 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
342 # Note that DB also stores the master position in the session and checks it.
343 $touched = $this->getCachedLastEditTime();
344 if ( $touched ) { // key set
345 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
346 $from = self
::READ_LATEST
;
347 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
351 // No idea from where the caller got this data, assume slave database.
353 $from = self
::READ_NORMAL
;
356 $this->loadFromRow( $data, $from );
360 * Load the object from a database row
363 * @param $data object: database row containing at least fields returned
365 * @param $from string|int One of the following:
366 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
367 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
368 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
369 * the master DB using SELECT FOR UPDATE
371 public function loadFromRow( $data, $from ) {
372 $lc = LinkCache
::singleton();
375 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
377 $this->mTitle
->loadFromRow( $data );
379 # Old-fashioned restrictions
380 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
382 $this->mCounter
= intval( $data->page_counter
);
383 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
384 $this->mIsRedirect
= intval( $data->page_is_redirect
);
385 $this->mLatest
= intval( $data->page_latest
);
386 // Bug 37225: $latest may no longer match the cached latest Revision object.
387 // Double-check the ID of any cached latest Revision object for consistency.
388 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
389 $this->mLastRevision
= null;
390 $this->mTimestamp
= '';
393 $lc->addBadLinkObj( $this->mTitle
);
395 $this->mTitle
->loadFromRow( false );
397 $this->clearCacheFields();
400 $this->mDataLoaded
= true;
401 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
405 * @return int Page ID
407 public function getId() {
408 return $this->mTitle
->getArticleID();
412 * @return bool Whether or not the page exists in the database
414 public function exists() {
415 return $this->mTitle
->exists();
419 * Check if this page is something we're going to be showing
420 * some sort of sensible content for. If we return false, page
421 * views (plain action=view) will return an HTTP 404 response,
422 * so spiders and robots can know they're following a bad link.
426 public function hasViewableContent() {
427 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
431 * @return int The view count for the page
433 public function getCount() {
434 if ( !$this->mDataLoaded
) {
435 $this->loadPageData();
438 return $this->mCounter
;
442 * Tests if the article content represents a redirect
446 public function isRedirect( ) {
447 $content = $this->getContent();
448 if ( !$content ) return false;
450 return $content->isRedirect();
454 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
456 * Will use the revisions actual content model if the page exists,
457 * and the page's default if the page doesn't exist yet.
463 public function getContentModel() {
464 if ( $this->exists() ) {
465 # look at the revision's actual content model
466 $rev = $this->getRevision();
468 if ( $rev !== null ) {
469 return $rev->getContentModel();
471 wfWarn( "Page exists but has no revision!" );
475 # use the default model for this page
476 return $this->mTitle
->getContentModel();
480 * Loads page_touched and returns a value indicating if it should be used
481 * @return boolean true if not a redirect
483 public function checkTouched() {
484 if ( !$this->mDataLoaded
) {
485 $this->loadPageData();
487 return !$this->mIsRedirect
;
491 * Get the page_touched field
492 * @return string containing GMT timestamp
494 public function getTouched() {
495 if ( !$this->mDataLoaded
) {
496 $this->loadPageData();
498 return $this->mTouched
;
502 * Get the page_latest field
503 * @return integer rev_id of current revision
505 public function getLatest() {
506 if ( !$this->mDataLoaded
) {
507 $this->loadPageData();
509 return (int)$this->mLatest
;
513 * Get the Revision object of the oldest revision
514 * @return Revision|null
516 public function getOldestRevision() {
517 wfProfileIn( __METHOD__
);
519 // Try using the slave database first, then try the master
521 $db = wfGetDB( DB_SLAVE
);
522 $revSelectFields = Revision
::selectFields();
524 while ( $continue ) {
525 $row = $db->selectRow(
526 array( 'page', 'revision' ),
529 'page_namespace' => $this->mTitle
->getNamespace(),
530 'page_title' => $this->mTitle
->getDBkey(),
535 'ORDER BY' => 'rev_timestamp ASC'
542 $db = wfGetDB( DB_MASTER
);
547 wfProfileOut( __METHOD__
);
548 return $row ? Revision
::newFromRow( $row ) : null;
552 * Loads everything except the text
553 * This isn't necessary for all uses, so it's only done if needed.
555 protected function loadLastEdit() {
556 if ( $this->mLastRevision
!== null ) {
557 return; // already loaded
560 $latest = $this->getLatest();
562 return; // page doesn't exist or is missing page_latest info
565 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
566 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
567 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
568 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
569 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
570 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
571 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
572 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
573 if ( $revision ) { // sanity
574 $this->setLastEdit( $revision );
579 * Set the latest revision
581 protected function setLastEdit( Revision
$revision ) {
582 $this->mLastRevision
= $revision;
583 $this->mTimestamp
= $revision->getTimestamp();
587 * Get the latest revision
588 * @return Revision|null
590 public function getRevision() {
591 $this->loadLastEdit();
592 if ( $this->mLastRevision
) {
593 return $this->mLastRevision
;
599 * Get the content of the current revision. No side-effects...
601 * @param $audience Integer: one of:
602 * Revision::FOR_PUBLIC to be displayed to all users
603 * Revision::FOR_THIS_USER to be displayed to $wgUser
604 * Revision::RAW get the text regardless of permissions
605 * @return Content|null The content of the current revision
609 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
610 $this->loadLastEdit();
611 if ( $this->mLastRevision
) {
612 return $this->mLastRevision
->getContent( $audience );
618 * Get the text of the current revision. No side-effects...
620 * @param $audience Integer: one of:
621 * Revision::FOR_PUBLIC to be displayed to all users
622 * Revision::FOR_THIS_USER to be displayed to $wgUser
623 * Revision::RAW get the text regardless of permissions
624 * @return String|false The text of the current revision
625 * @deprecated as of 1.WD, getContent() should be used instead.
627 public function getText( $audience = Revision
::FOR_PUBLIC
) { #@todo: deprecated, replace usage!
628 wfDeprecated( __METHOD__
, '1.WD' );
630 $this->loadLastEdit();
631 if ( $this->mLastRevision
) {
632 return $this->mLastRevision
->getText( $audience );
638 * Get the text of the current revision. No side-effects...
640 * @return String|bool The text of the current revision. False on failure
641 * @deprecated as of 1.WD, getContent() should be used instead.
643 public function getRawText() {
644 wfDeprecated( __METHOD__
, '1.WD' );
646 return $this->getText( Revision
::RAW
);
650 * @return string MW timestamp of last article revision
652 public function getTimestamp() {
653 // Check if the field has been filled by WikiPage::setTimestamp()
654 if ( !$this->mTimestamp
) {
655 $this->loadLastEdit();
658 return wfTimestamp( TS_MW
, $this->mTimestamp
);
662 * Set the page timestamp (use only to avoid DB queries)
663 * @param $ts string MW timestamp of last article revision
666 public function setTimestamp( $ts ) {
667 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
671 * @param $audience Integer: one of:
672 * Revision::FOR_PUBLIC to be displayed to all users
673 * Revision::FOR_THIS_USER to be displayed to $wgUser
674 * Revision::RAW get the text regardless of permissions
675 * @return int user ID for the user that made the last article revision
677 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
678 $this->loadLastEdit();
679 if ( $this->mLastRevision
) {
680 return $this->mLastRevision
->getUser( $audience );
687 * Get the User object of the user who created the page
688 * @param $audience Integer: one of:
689 * Revision::FOR_PUBLIC to be displayed to all users
690 * Revision::FOR_THIS_USER to be displayed to $wgUser
691 * Revision::RAW get the text regardless of permissions
694 public function getCreator( $audience = Revision
::FOR_PUBLIC
) {
695 $revision = $this->getOldestRevision();
697 $userName = $revision->getUserText( $audience );
698 return User
::newFromName( $userName, false );
705 * @param $audience Integer: one of:
706 * Revision::FOR_PUBLIC to be displayed to all users
707 * Revision::FOR_THIS_USER to be displayed to $wgUser
708 * Revision::RAW get the text regardless of permissions
709 * @return string username of the user that made the last article revision
711 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
712 $this->loadLastEdit();
713 if ( $this->mLastRevision
) {
714 return $this->mLastRevision
->getUserText( $audience );
721 * @param $audience Integer: one of:
722 * Revision::FOR_PUBLIC to be displayed to all users
723 * Revision::FOR_THIS_USER to be displayed to $wgUser
724 * Revision::RAW get the text regardless of permissions
725 * @return string Comment stored for the last article revision
727 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
728 $this->loadLastEdit();
729 if ( $this->mLastRevision
) {
730 return $this->mLastRevision
->getComment( $audience );
737 * Returns true if last revision was marked as "minor edit"
739 * @return boolean Minor edit indicator for the last article revision.
741 public function getMinorEdit() {
742 $this->loadLastEdit();
743 if ( $this->mLastRevision
) {
744 return $this->mLastRevision
->isMinor();
751 * Get the cached timestamp for the last time the page changed.
752 * This is only used to help handle slave lag by comparing to page_touched.
753 * @return string MW timestamp
755 protected function getCachedLastEditTime() {
757 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
758 return $wgMemc->get( $key );
762 * Set the cached timestamp for the last time the page changed.
763 * This is only used to help handle slave lag by comparing to page_touched.
764 * @param $timestamp string
767 public function setCachedLastEditTime( $timestamp ) {
769 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
770 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
774 * Determine whether a page would be suitable for being counted as an
775 * article in the site_stats table based on the title & its content
777 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
778 * if false, the current database state will be used
781 public function isCountable( $editInfo = false ) {
782 global $wgArticleCountMethod;
784 if ( !$this->mTitle
->isContentPage() ) {
789 $content = $editInfo->pstContent
;
791 $content = $this->getContent();
794 if ( !$content ||
$content->isRedirect( ) ) {
800 if ( $wgArticleCountMethod === 'link' ) {
801 # nasty special case to avoid re-parsing to detect links
804 // ParserOutput::getLinks() is a 2D array of page links, so
805 // to be really correct we would need to recurse in the array
806 // but the main array should only have items in it if there are
808 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
810 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
811 array( 'pl_from' => $this->getId() ), __METHOD__
);
815 return $content->isCountable( $hasLinks );
819 * If this page is a redirect, get its target
821 * The target will be fetched from the redirect table if possible.
822 * If this page doesn't have an entry there, call insertRedirect()
823 * @return Title|mixed object, or null if this page is not a redirect
825 public function getRedirectTarget() {
826 if ( !$this->mTitle
->isRedirect() ) {
830 if ( $this->mRedirectTarget
!== null ) {
831 return $this->mRedirectTarget
;
834 # Query the redirect table
835 $dbr = wfGetDB( DB_SLAVE
);
836 $row = $dbr->selectRow( 'redirect',
837 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
838 array( 'rd_from' => $this->getId() ),
842 // rd_fragment and rd_interwiki were added later, populate them if empty
843 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
844 return $this->mRedirectTarget
= Title
::makeTitle(
845 $row->rd_namespace
, $row->rd_title
,
846 $row->rd_fragment
, $row->rd_interwiki
);
849 # This page doesn't have an entry in the redirect table
850 return $this->mRedirectTarget
= $this->insertRedirect();
854 * Insert an entry for this page into the redirect table.
856 * Don't call this function directly unless you know what you're doing.
857 * @return Title object or null if not a redirect
859 public function insertRedirect() {
860 // recurse through to only get the final target
861 $content = $this->getContent();
862 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
866 $this->insertRedirectEntry( $retval );
871 * Insert or update the redirect table entry for this page to indicate
872 * it redirects to $rt .
873 * @param $rt Title redirect target
875 public function insertRedirectEntry( $rt ) {
876 $dbw = wfGetDB( DB_MASTER
);
877 $dbw->replace( 'redirect', array( 'rd_from' ),
879 'rd_from' => $this->getId(),
880 'rd_namespace' => $rt->getNamespace(),
881 'rd_title' => $rt->getDBkey(),
882 'rd_fragment' => $rt->getFragment(),
883 'rd_interwiki' => $rt->getInterwiki(),
890 * Get the Title object or URL this page redirects to
892 * @return mixed false, Title of in-wiki target, or string with URL
894 public function followRedirect() {
895 return $this->getRedirectURL( $this->getRedirectTarget() );
899 * Get the Title object or URL to use for a redirect. We use Title
900 * objects for same-wiki, non-special redirects and URLs for everything
902 * @param $rt Title Redirect target
903 * @return mixed false, Title object of local target, or string with URL
905 public function getRedirectURL( $rt ) {
910 if ( $rt->isExternal() ) {
911 if ( $rt->isLocal() ) {
912 // Offsite wikis need an HTTP redirect.
914 // This can be hard to reverse and may produce loops,
915 // so they may be disabled in the site configuration.
916 $source = $this->mTitle
->getFullURL( 'redirect=no' );
917 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
919 // External pages pages without "local" bit set are not valid
925 if ( $rt->isSpecialPage() ) {
926 // Gotta handle redirects to special pages differently:
927 // Fill the HTTP response "Location" header and ignore
928 // the rest of the page we're on.
930 // Some pages are not valid targets
931 if ( $rt->isValidRedirectTarget() ) {
932 return $rt->getFullURL();
942 * Get a list of users who have edited this article, not including the user who made
943 * the most recent revision, which you can get from $article->getUser() if you want it
944 * @return UserArrayFromResult
946 public function getContributors() {
947 # @todo FIXME: This is expensive; cache this info somewhere.
949 $dbr = wfGetDB( DB_SLAVE
);
951 if ( $dbr->implicitGroupby() ) {
952 $realNameField = 'user_real_name';
954 $realNameField = 'MIN(user_real_name) AS user_real_name';
957 $tables = array( 'revision', 'user' );
960 'user_id' => 'rev_user',
961 'user_name' => 'rev_user_text',
963 'timestamp' => 'MAX(rev_timestamp)',
966 $conds = array( 'rev_page' => $this->getId() );
968 // The user who made the top revision gets credited as "this page was last edited by
969 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
970 $user = $this->getUser();
972 $conds[] = "rev_user != $user";
974 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
977 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
980 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
984 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
985 'ORDER BY' => 'timestamp DESC',
988 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
989 return new UserArrayFromResult( $res );
993 * Get the last N authors
994 * @param $num Integer: number of revisions to get
995 * @param $revLatest String: the latest rev_id, selected from the master (optional)
996 * @return array Array of authors, duplicates not removed
998 public function getLastNAuthors( $num, $revLatest = 0 ) {
999 wfProfileIn( __METHOD__
);
1000 // First try the slave
1001 // If that doesn't have the latest revision, try the master
1003 $db = wfGetDB( DB_SLAVE
);
1006 $res = $db->select( array( 'page', 'revision' ),
1007 array( 'rev_id', 'rev_user_text' ),
1009 'page_namespace' => $this->mTitle
->getNamespace(),
1010 'page_title' => $this->mTitle
->getDBkey(),
1011 'rev_page = page_id'
1014 'ORDER BY' => 'rev_timestamp DESC',
1020 wfProfileOut( __METHOD__
);
1024 $row = $db->fetchObject( $res );
1026 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1027 $db = wfGetDB( DB_MASTER
);
1032 } while ( $continue );
1034 $authors = array( $row->rev_user_text
);
1036 foreach ( $res as $row ) {
1037 $authors[] = $row->rev_user_text
;
1040 wfProfileOut( __METHOD__
);
1045 * Should the parser cache be used?
1047 * @param $parserOptions ParserOptions to check
1051 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1052 global $wgEnableParserCache;
1054 return $wgEnableParserCache
1055 && $parserOptions->getStubThreshold() == 0
1056 && $this->mTitle
->exists()
1057 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1058 && $this->getContentHandler()->isParserCacheSupported();
1062 * Get a ParserOutput for the given ParserOptions and revision ID.
1063 * The parser cache will be used if possible.
1066 * @param $parserOptions ParserOptions to use for the parse operation
1067 * @param $oldid Revision ID to get the text from, passing null or 0 will
1068 * get the current revision (default value)
1070 * @return ParserOutput or false if the revision was not found
1072 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1073 wfProfileIn( __METHOD__
);
1075 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1076 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1077 if ( $parserOptions->getStubThreshold() ) {
1078 wfIncrStats( 'pcache_miss_stub' );
1081 if ( $useParserCache ) {
1082 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1083 if ( $parserOutput !== false ) {
1084 wfProfileOut( __METHOD__
);
1085 return $parserOutput;
1089 if ( $oldid === null ||
$oldid === 0 ) {
1090 $oldid = $this->getLatest();
1093 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1096 wfProfileOut( __METHOD__
);
1098 return $pool->getParserOutput();
1102 * Do standard deferred updates after page view
1103 * @param $user User The relevant user
1105 public function doViewUpdates( User
$user ) {
1106 global $wgDisableCounters;
1107 if ( wfReadOnly() ) {
1111 # Don't update page view counters on views from bot users (bug 14044)
1112 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1113 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1114 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1117 # Update newtalk / watchlist notification status
1118 $user->clearNotification( $this->mTitle
);
1122 * Perform the actions of a page purging
1125 public function doPurge() {
1128 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1132 // Invalidate the cache
1133 $this->mTitle
->invalidateCache();
1136 if ( $wgUseSquid ) {
1137 // Commit the transaction before the purge is sent
1138 $dbw = wfGetDB( DB_MASTER
);
1139 $dbw->commit( __METHOD__
);
1142 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1143 $update->doUpdate();
1146 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1147 //@todo: move this logic to MessageCache
1149 if ( $this->mTitle
->exists() ) {
1150 // NOTE: use transclusion text for messages.
1151 // This is consistent with MessageCache::getMsgFromNamespace()
1153 $content = $this->getContent();
1154 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1156 if ( $text === null ) $text = false;
1161 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1167 * Insert a new empty page record for this article.
1168 * This *must* be followed up by creating a revision
1169 * and running $this->updateRevisionOn( ... );
1170 * or else the record will be left in a funky state.
1171 * Best if all done inside a transaction.
1173 * @param $dbw DatabaseBase
1174 * @return int The newly created page_id key, or false if the title already existed
1176 public function insertOn( $dbw ) {
1177 wfProfileIn( __METHOD__
);
1179 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1180 $dbw->insert( 'page', array(
1181 'page_id' => $page_id,
1182 'page_namespace' => $this->mTitle
->getNamespace(),
1183 'page_title' => $this->mTitle
->getDBkey(),
1184 'page_counter' => 0,
1185 'page_restrictions' => '',
1186 'page_is_redirect' => 0, # Will set this shortly...
1188 'page_random' => wfRandom(),
1189 'page_touched' => $dbw->timestamp(),
1190 'page_latest' => 0, # Fill this in shortly...
1191 'page_len' => 0, # Fill this in shortly...
1192 ), __METHOD__
, 'IGNORE' );
1194 $affected = $dbw->affectedRows();
1197 $newid = $dbw->insertId();
1198 $this->mTitle
->resetArticleID( $newid );
1200 wfProfileOut( __METHOD__
);
1202 return $affected ?
$newid : false;
1206 * Update the page record to point to a newly saved revision.
1208 * @param $dbw DatabaseBase: object
1209 * @param $revision Revision: For ID number, and text used to set
1210 * length and redirect status fields
1211 * @param $lastRevision Integer: if given, will not overwrite the page field
1212 * when different from the currently set value.
1213 * Giving 0 indicates the new page flag should be set
1215 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1216 * removing rows in redirect table.
1217 * @return bool true on success, false on failure
1220 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1221 global $wgContentHandlerUseDB;
1223 wfProfileIn( __METHOD__
);
1225 $content = $revision->getContent();
1226 $len = $content->getSize();
1227 $rt = $content->getUltimateRedirectTarget();
1229 $conditions = array( 'page_id' => $this->getId() );
1231 if ( !is_null( $lastRevision ) ) {
1232 # An extra check against threads stepping on each other
1233 $conditions['page_latest'] = $lastRevision;
1236 $now = wfTimestampNow();
1237 $row = array( /* SET */
1238 'page_latest' => $revision->getId(),
1239 'page_touched' => $dbw->timestamp( $now ),
1240 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1241 'page_is_redirect' => $rt !== null ?
1 : 0,
1245 if ( $wgContentHandlerUseDB ) {
1246 $row[ 'page_content_model' ] = $revision->getContentModel();
1249 $dbw->update( 'page',
1254 $result = $dbw->affectedRows() > 0;
1256 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1257 $this->setLastEdit( $revision );
1258 $this->setCachedLastEditTime( $now );
1259 $this->mLatest
= $revision->getId();
1260 $this->mIsRedirect
= (bool)$rt;
1261 # Update the LinkCache.
1262 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1263 $this->mLatest
, $revision->getContentModel() );
1266 wfProfileOut( __METHOD__
);
1271 * Add row to the redirect table if this is a redirect, remove otherwise.
1273 * @param $dbw DatabaseBase
1274 * @param $redirectTitle Title object pointing to the redirect target,
1275 * or NULL if this is not a redirect
1276 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1277 * removing rows in redirect table.
1278 * @return bool true on success, false on failure
1281 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1282 // Always update redirects (target link might have changed)
1283 // Update/Insert if we don't know if the last revision was a redirect or not
1284 // Delete if changing from redirect to non-redirect
1285 $isRedirect = !is_null( $redirectTitle );
1287 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1291 wfProfileIn( __METHOD__
);
1292 if ( $isRedirect ) {
1293 $this->insertRedirectEntry( $redirectTitle );
1295 // This is not a redirect, remove row from redirect table
1296 $where = array( 'rd_from' => $this->getId() );
1297 $dbw->delete( 'redirect', $where, __METHOD__
);
1300 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1301 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1303 wfProfileOut( __METHOD__
);
1305 return ( $dbw->affectedRows() != 0 );
1309 * If the given revision is newer than the currently set page_latest,
1310 * update the page record. Otherwise, do nothing.
1312 * @param $dbw DatabaseBase object
1313 * @param $revision Revision object
1316 public function updateIfNewerOn( $dbw, $revision ) {
1317 wfProfileIn( __METHOD__
);
1319 $row = $dbw->selectRow(
1320 array( 'revision', 'page' ),
1321 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1323 'page_id' => $this->getId(),
1324 'page_latest=rev_id' ),
1328 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1329 wfProfileOut( __METHOD__
);
1332 $prev = $row->rev_id
;
1333 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1335 # No or missing previous revision; mark the page as new
1337 $lastRevIsRedirect = null;
1340 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1342 wfProfileOut( __METHOD__
);
1347 * Get the content that needs to be saved in order to undo all revisions
1348 * between $undo and $undoafter. Revisions must belong to the same page,
1349 * must exist and must not be deleted
1350 * @param $undo Revision
1351 * @param $undoafter Revision Must be an earlier revision than $undo
1352 * @return mixed string on success, false on failure
1354 * Before we had the Content object, this was done in getUndoText
1356 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1357 $handler = $undo->getContentHandler();
1358 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1362 * Get the text that needs to be saved in order to undo all revisions
1363 * between $undo and $undoafter. Revisions must belong to the same page,
1364 * must exist and must not be deleted
1365 * @param $undo Revision
1366 * @param $undoafter Revision Must be an earlier revision than $undo
1367 * @return mixed string on success, false on failure
1368 * @deprecated since 1.WD: use ContentHandler::getUndoContent() instead.
1370 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1371 wfDeprecated( __METHOD__
, '1.WD' );
1373 $this->loadLastEdit();
1375 if ( $this->mLastRevision
) {
1376 if ( is_null( $undoafter ) ) {
1377 $undoafter = $undo->getPrevious();
1380 $handler = $this->getContentHandler();
1381 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1386 return ContentHandler
::getContentText( $undone );
1394 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1395 * @param $text String: new text of the section
1396 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1397 * @param $edittime String: revision timestamp or null to use the current revision
1398 * @return String new complete article text, or null if error
1400 * @deprecated since 1.WD, use replaceSectionContent() instead
1402 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1403 wfDeprecated( __METHOD__
, '1.WD' );
1405 if ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1406 // Whole-page edit; let the whole text through
1410 if ( !$this->supportsSections() ) {
1411 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1414 # could even make section title, but that's not required.
1415 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1417 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1419 return ContentHandler
::getContentText( $newContent );
1423 * Returns true iff this page's content model supports sections.
1425 * @return boolean whether sections are supported.
1427 * @todo: the skin should check this and not offer section functionality if sections are not supported.
1428 * @todo: the EditPage should check this and not offer section functionality if sections are not supported.
1430 public function supportsSections() {
1431 return $this->getContentHandler()->supportsSections();
1435 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1436 * @param $content Content: new content of the section
1437 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1438 * @param $edittime String: revision timestamp or null to use the current revision
1440 * @return Content new complete article content, or null if error
1444 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1445 wfProfileIn( __METHOD__
);
1447 if ( strval( $section ) == '' ) {
1448 // Whole-page edit; let the whole text through
1449 $newContent = $sectionContent;
1451 if ( !$this->supportsSections() ) {
1452 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1455 // Bug 30711: always use current version when adding a new section
1456 if ( is_null( $edittime ) ||
$section == 'new' ) {
1457 $oldContent = $this->getContent();
1458 if ( ! $oldContent ) {
1459 wfDebug( __METHOD__
. ": no page text\n" );
1460 wfProfileOut( __METHOD__
);
1464 $dbw = wfGetDB( DB_MASTER
);
1465 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1468 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1469 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1470 wfProfileOut( __METHOD__
);
1474 $oldContent = $rev->getContent();
1477 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1480 wfProfileOut( __METHOD__
);
1485 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1487 * @return Int updated $flags
1489 function checkFlags( $flags ) {
1490 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1491 if ( $this->mTitle
->getArticleID() ) {
1492 $flags |
= EDIT_UPDATE
;
1502 * Change an existing article or create a new article. Updates RC and all necessary caches,
1503 * optionally via the deferred update array.
1505 * @param $text String: new text
1506 * @param $summary String: edit summary
1507 * @param $flags Integer bitfield:
1509 * Article is known or assumed to be non-existent, create a new one
1511 * Article is known or assumed to be pre-existing, update it
1513 * Mark this edit minor, if the user is allowed to do so
1515 * Do not log the change in recentchanges
1517 * Mark the edit a "bot" edit regardless of user rights
1518 * EDIT_DEFER_UPDATES
1519 * Defer some of the updates until the end of index.php
1521 * Fill in blank summaries with generated text where possible
1523 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1524 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1525 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1526 * edit-already-exists error will be returned. These two conditions are also possible with
1527 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1529 * @param $baseRevId int the revision ID this edit was based off, if any
1530 * @param $user User the user doing the edit
1532 * @return Status object. Possible errors:
1533 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1534 * edit-gone-missing: In update mode, but the article didn't exist
1535 * edit-conflict: In update mode, the article changed unexpectedly
1536 * edit-no-change: Warning that the text was the same as before
1537 * edit-already-exists: In creation mode, but the article already exists
1539 * Extensions may define additional errors.
1541 * $return->value will contain an associative array with members as follows:
1542 * new: Boolean indicating if the function attempted to create a new article
1543 * revision: The revision object for the inserted revision, or null
1545 * Compatibility note: this function previously returned a boolean value indicating success/failure
1547 * @deprecated since 1.WD: use doEditContent() instead.
1548 * @todo: use doEditContent() instead everywhere
1550 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1551 wfDeprecated( __METHOD__
, '1.WD' );
1553 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1555 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1559 * Change an existing article or create a new article. Updates RC and all necessary caches,
1560 * optionally via the deferred update array.
1562 * @param $content Content: new content
1563 * @param $summary String: edit summary
1564 * @param $flags Integer bitfield:
1566 * Article is known or assumed to be non-existent, create a new one
1568 * Article is known or assumed to be pre-existing, update it
1570 * Mark this edit minor, if the user is allowed to do so
1572 * Do not log the change in recentchanges
1574 * Mark the edit a "bot" edit regardless of user rights
1575 * EDIT_DEFER_UPDATES
1576 * Defer some of the updates until the end of index.php
1578 * Fill in blank summaries with generated text where possible
1580 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1581 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1582 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1583 * edit-already-exists error will be returned. These two conditions are also possible with
1584 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1586 * @param $baseRevId the revision ID this edit was based off, if any
1587 * @param $user User the user doing the edit
1588 * @param $serialisation_format String: format for storing the content in the database
1590 * @return Status object. Possible errors:
1591 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1592 * edit-gone-missing: In update mode, but the article didn't exist
1593 * edit-conflict: In update mode, the article changed unexpectedly
1594 * edit-no-change: Warning that the text was the same as before
1595 * edit-already-exists: In creation mode, but the article already exists
1597 * Extensions may define additional errors.
1599 * $return->value will contain an associative array with members as follows:
1600 * new: Boolean indicating if the function attempted to create a new article
1601 * revision: The revision object for the inserted revision, or null
1605 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1606 User
$user = null, $serialisation_format = null ) {
1607 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1609 # Low-level sanity check
1610 if ( $this->mTitle
->getText() === '' ) {
1611 throw new MWException( 'Something is trying to edit an article with an empty title' );
1614 wfProfileIn( __METHOD__
);
1616 $user = is_null( $user ) ?
$wgUser : $user;
1617 $status = Status
::newGood( array() );
1619 // Load the data from the master database if needed.
1620 // The caller may already loaded it from the master or even loaded it using
1621 // SELECT FOR UPDATE, so do not override that using clear().
1622 $this->loadPageData( 'fromdbmaster' );
1624 $flags = $this->checkFlags( $flags );
1627 $hook_args = array( &$this, &$user, &$content, &$summary,
1628 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1630 if ( !wfRunHooks( 'ArticleContentSave', $hook_args )
1631 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1633 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1635 if ( $status->isOK() ) {
1636 $status->fatal( 'edit-hook-aborted' );
1639 wfProfileOut( __METHOD__
);
1643 # Silently ignore EDIT_MINOR if not allowed
1644 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1645 $bot = $flags & EDIT_FORCE_BOT
;
1647 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1649 $oldsize = $old_content ?
$old_content->getSize() : 0;
1650 $oldid = $this->getLatest();
1651 $oldIsRedirect = $this->isRedirect();
1652 $oldcountable = $this->isCountable();
1654 $handler = $content->getContentHandler();
1656 # Provide autosummaries if one is not provided and autosummaries are enabled.
1657 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1658 if ( !$old_content ) $old_content = null;
1659 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1662 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1663 $serialized = $editInfo->pst
;
1664 $content = $editInfo->pstContent
;
1665 $newsize = $content->getSize();
1667 $dbw = wfGetDB( DB_MASTER
);
1668 $now = wfTimestampNow();
1669 $this->mTimestamp
= $now;
1671 if ( $flags & EDIT_UPDATE
) {
1672 # Update article, but only if changed.
1673 $status->value
['new'] = false;
1676 # Article gone missing
1677 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1678 $status->fatal( 'edit-gone-missing' );
1680 wfProfileOut( __METHOD__
);
1682 } elseif ( !$old_content ) {
1683 # Sanity check for bug 37225
1684 wfProfileOut( __METHOD__
);
1685 throw new MWException( "Could not find text for current revision {$oldid}." );
1688 $revision = new Revision( array(
1689 'page' => $this->getId(),
1690 'comment' => $summary,
1691 'minor_edit' => $isminor,
1692 'text' => $serialized,
1694 'parent_id' => $oldid,
1695 'user' => $user->getId(),
1696 'user_text' => $user->getName(),
1697 'timestamp' => $now,
1698 'content_model' => $content->getModel(),
1699 'content_format' => $serialisation_format,
1700 ) ); #XXX: pass content object?!
1702 # Bug 37225: use accessor to get the text as Revision may trim it.
1703 # After trimming, the text may be a duplicate of the current text.
1704 $content = $revision->getContent(); // sanity; EditPage should trim already
1706 $changed = !$content->equals( $old_content );
1709 if ( !$content->isValid() ) {
1710 throw new MWException( "New content failed validity check!" );
1713 $dbw->begin( __METHOD__
);
1715 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1716 $status->merge( $prepStatus );
1718 if ( !$status->isOK() ) {
1721 wfProfileOut( __METHOD__
);
1725 $revisionId = $revision->insertOn( $dbw );
1729 # Note that we use $this->mLatest instead of fetching a value from the master DB
1730 # during the course of this function. This makes sure that EditPage can detect
1731 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1732 # before this function is called. A previous function used a separate query, this
1733 # creates a window where concurrent edits can cause an ignored edit conflict.
1734 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1737 # Belated edit conflict! Run away!!
1738 $status->fatal( 'edit-conflict' );
1740 $dbw->rollback( __METHOD__
);
1742 wfProfileOut( __METHOD__
);
1746 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1747 # Update recentchanges
1748 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1749 # Mark as patrolled if the user can do so
1750 $patrolled = $wgUseRCPatrol && !count(
1751 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1752 # Add RC row to the DB
1753 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1754 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1755 $revisionId, $patrolled
1758 # Log auto-patrolled edits
1760 PatrolLog
::record( $rc, true, $user );
1763 $user->incEditCount();
1764 $dbw->commit( __METHOD__
);
1766 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1767 // related variables correctly
1768 $revision->setId( $this->getLatest() );
1771 # Update links tables, site stats, etc.
1772 $this->doEditUpdates(
1776 'changed' => $changed,
1777 'oldcountable' => $oldcountable
1782 $status->warning( 'edit-no-change' );
1784 // Update page_touched, this is usually implicit in the page update
1785 // Other cache updates are done in onArticleEdit()
1786 $this->mTitle
->invalidateCache();
1789 # Create new article
1790 $status->value
['new'] = true;
1792 $dbw->begin( __METHOD__
);
1794 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1795 $status->merge( $prepStatus );
1797 if ( !$status->isOK() ) {
1800 wfProfileOut( __METHOD__
);
1804 $status->merge( $prepStatus );
1806 # Add the page record; stake our claim on this title!
1807 # This will return false if the article already exists
1808 $newid = $this->insertOn( $dbw );
1810 if ( $newid === false ) {
1811 $dbw->rollback( __METHOD__
);
1812 $status->fatal( 'edit-already-exists' );
1814 wfProfileOut( __METHOD__
);
1818 # Save the revision text...
1819 $revision = new Revision( array(
1821 'comment' => $summary,
1822 'minor_edit' => $isminor,
1823 'text' => $serialized,
1825 'user' => $user->getId(),
1826 'user_text' => $user->getName(),
1827 'timestamp' => $now,
1828 'content_model' => $content->getModel(),
1829 'content_format' => $serialisation_format,
1831 $revisionId = $revision->insertOn( $dbw );
1833 # Bug 37225: use accessor to get the text as Revision may trim it
1834 $content = $revision->getContent(); // sanity; get normalized version
1836 # Update the page record with revision data
1837 $this->updateRevisionOn( $dbw, $revision, 0 );
1839 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1841 # Update recentchanges
1842 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1843 # Mark as patrolled if the user can do so
1844 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1845 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1846 # Add RC row to the DB
1847 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1848 '', $content->getSize(), $revisionId, $patrolled );
1850 # Log auto-patrolled edits
1852 PatrolLog
::record( $rc, true, $user );
1855 $user->incEditCount();
1856 $dbw->commit( __METHOD__
);
1858 # Update links, etc.
1859 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1861 $hook_args = array( &$this, &$user, $content, $summary,
1862 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1864 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1865 wfRunHooks( 'ArticleContentInsertComplete', $hook_args );
1868 # Do updates right now unless deferral was requested
1869 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1870 DeferredUpdates
::doUpdates();
1873 // Return the new revision (or null) to the caller
1874 $status->value
['revision'] = $revision;
1876 $hook_args = array( &$this, &$user, $content, $summary,
1877 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1879 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1880 wfRunHooks( 'ArticleContentSaveComplete', $hook_args );
1882 # Promote user to any groups they meet the criteria for
1883 $user->addAutopromoteOnceGroups( 'onEdit' );
1885 wfProfileOut( __METHOD__
);
1890 * Get parser options suitable for rendering the primary article wikitext
1891 * @param User|string $user User object or 'canonical'
1892 * @return ParserOptions
1894 public function makeParserOptions( $user ) {
1896 if ( $user instanceof User
) { // settings per user (even anons)
1897 $options = ParserOptions
::newFromUser( $user );
1898 } else { // canonical settings
1899 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1901 $options->enableLimitReport(); // show inclusion/loop reports
1902 $options->setTidy( true ); // fix bad HTML
1907 * Prepare text which is about to be saved.
1908 * Returns a stdclass with source, pst and output members
1910 * @deprecated in 1.WD: use prepareContentForEdit instead.
1912 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1913 wfDeprecated( __METHOD__
, '1.WD' );
1914 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1915 return $this->prepareContentForEdit( $content, $revid , $user );
1919 * Prepare content which is about to be saved.
1920 * Returns a stdclass with source, pst and output members
1922 * @param \Content $content
1923 * @param null $revid
1924 * @param null|\User $user
1925 * @param null $serialization_format
1927 * @return bool|object
1931 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) {
1932 global $wgParser, $wgContLang, $wgUser;
1933 $user = is_null( $user ) ?
$wgUser : $user;
1934 // @TODO fixme: check $user->getId() here???
1936 if ( $this->mPreparedEdit
1937 && $this->mPreparedEdit
->newContent
1938 && $this->mPreparedEdit
->newContent
->equals( $content )
1939 && $this->mPreparedEdit
->revid
== $revid
1940 && $this->mPreparedEdit
->format
== $serialization_format
1941 #XXX: also check $user here?
1944 return $this->mPreparedEdit
;
1947 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1948 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1950 $edit = (object)array();
1951 $edit->revid
= $revid;
1953 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1954 $edit->pst
= $edit->pstContent
->serialize( $serialization_format ); #XXX: do we need this??
1955 $edit->format
= $serialization_format;
1957 $edit->popts
= $this->makeParserOptions( 'canonical' );
1959 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1961 $edit->newContent
= $content;
1962 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1964 #NOTE: B/C for hooks! don't use these fields!
1965 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
);
1966 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
1968 $this->mPreparedEdit
= $edit;
1974 * Do standard deferred updates after page edit.
1975 * Update links tables, site stats, search index and message cache.
1976 * Purges pages that include this page if the text was changed here.
1977 * Every 100th edit, prune the recent changes table.
1979 * @param $revision Revision object
1980 * @param $user User object that did the revision
1981 * @param $options Array of options, following indexes are used:
1982 * - changed: boolean, whether the revision changed the content (default true)
1983 * - created: boolean, whether the revision created the page (default false)
1984 * - oldcountable: boolean or null (default null):
1985 * - boolean: whether the page was counted as an article before that
1986 * revision, only used in changed is true and created is false
1987 * - null: don't change the article count
1989 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1990 global $wgEnableParserCache;
1992 wfProfileIn( __METHOD__
);
1994 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1995 $content = $revision->getContent();
1998 # Be careful not to double-PST: $text is usually already PST-ed once
1999 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2000 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2001 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2003 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2004 $editInfo = $this->mPreparedEdit
;
2007 # Save it to the parser cache
2008 if ( $wgEnableParserCache ) {
2009 $parserCache = ParserCache
::singleton();
2010 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2013 # Update the links tables and other secondary data
2014 $updates = $content->getSecondaryDataUpdates( $this->getTitle(), null, true, $editInfo->output
);
2015 DataUpdate
::runUpdates( $updates );
2017 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2019 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2020 if ( 0 == mt_rand( 0, 99 ) ) {
2021 // Flush old entries from the `recentchanges` table; we do this on
2022 // random requests so as to avoid an increase in writes for no good reason
2025 $dbw = wfGetDB( DB_MASTER
);
2026 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2029 array( "rc_timestamp < '$cutoff'" ),
2035 if ( !$this->mTitle
->exists() ) {
2036 wfProfileOut( __METHOD__
);
2040 $id = $this->getId();
2041 $title = $this->mTitle
->getPrefixedDBkey();
2042 $shortTitle = $this->mTitle
->getDBkey();
2044 if ( !$options['changed'] ) {
2047 } elseif ( $options['created'] ) {
2048 $good = (int)$this->isCountable( $editInfo );
2050 } elseif ( $options['oldcountable'] !== null ) {
2051 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2058 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2059 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
2060 #@TODO: let the search engine decide what to do with the content object
2062 # If this is another user's talk page, update newtalk.
2063 # Don't do this if $options['changed'] = false (null-edits) nor if
2064 # it's a minor edit and the user doesn't want notifications for those.
2065 if ( $options['changed']
2066 && $this->mTitle
->getNamespace() == NS_USER_TALK
2067 && $shortTitle != $user->getTitleKey()
2068 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2070 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2071 $other = User
::newFromName( $shortTitle, false );
2073 wfDebug( __METHOD__
. ": invalid username\n" );
2074 } elseif ( User
::isIP( $shortTitle ) ) {
2075 // An anonymous user
2076 $other->setNewtalk( true, $revision );
2077 } elseif ( $other->isLoggedIn() ) {
2078 $other->setNewtalk( true, $revision );
2080 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2085 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2086 #XXX: could skip pseudo-messages like js/css here, based on content model.
2087 $msgtext = $content->getWikitextForTransclusion();
2088 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
2090 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2093 if( $options['created'] ) {
2094 self
::onArticleCreate( $this->mTitle
);
2096 self
::onArticleEdit( $this->mTitle
);
2099 wfProfileOut( __METHOD__
);
2103 * Edit an article without doing all that other stuff
2104 * The article must already exist; link tables etc
2105 * are not updated, caches are not flushed.
2107 * @param $text String: text submitted
2108 * @param $user User The relevant user
2109 * @param $comment String: comment submitted
2110 * @param $minor Boolean: whereas it's a minor modification
2112 * @deprecated since 1.WD, use doEditContent() instead.
2114 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2115 wfDeprecated( __METHOD__
, "1.WD" );
2117 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2118 return $this->doQuickEditContent( $content, $user, $comment , $minor );
2122 * Edit an article without doing all that other stuff
2123 * The article must already exist; link tables etc
2124 * are not updated, caches are not flushed.
2126 * @param $content Content: content submitted
2127 * @param $user User The relevant user
2128 * @param $comment String: comment submitted
2129 * @param $serialisation_format String: format for storing the content in the database
2130 * @param $minor Boolean: whereas it's a minor modification
2132 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
2133 wfProfileIn( __METHOD__
);
2135 $serialized = $content->serialize( $serialisation_format );
2137 $dbw = wfGetDB( DB_MASTER
);
2138 $revision = new Revision( array(
2139 'page' => $this->getId(),
2140 'text' => $serialized,
2141 'length' => $content->getSize(),
2142 'comment' => $comment,
2143 'minor_edit' => $minor ?
1 : 0,
2144 ) ); #XXX: set the content object?
2145 $revision->insertOn( $dbw );
2146 $this->updateRevisionOn( $dbw, $revision );
2148 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2150 wfProfileOut( __METHOD__
);
2154 * Update the article's restriction field, and leave a log entry.
2155 * This works for protection both existing and non-existing pages.
2157 * @param $limit Array: set of restriction keys
2158 * @param $reason String
2159 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2160 * @param $expiry Array: per restriction type expiration
2161 * @param $user User The user updating the restrictions
2164 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2167 if ( wfReadOnly() ) {
2168 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2171 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2173 $id = $this->mTitle
->getArticleID();
2179 // Take this opportunity to purge out expired restrictions
2180 Title
::purgeExpiredRestrictions();
2182 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2183 # we expect a single selection, but the schema allows otherwise.
2184 $isProtected = false;
2188 $dbw = wfGetDB( DB_MASTER
);
2190 foreach ( $restrictionTypes as $action ) {
2191 if ( !isset( $expiry[$action] ) ) {
2192 $expiry[$action] = $dbw->getInfinity();
2194 if ( !isset( $limit[$action] ) ) {
2195 $limit[$action] = '';
2196 } elseif ( $limit[$action] != '' ) {
2200 # Get current restrictions on $action
2201 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2202 if ( $current != '' ) {
2203 $isProtected = true;
2206 if ( $limit[$action] != $current ) {
2208 } elseif ( $limit[$action] != '' ) {
2209 # Only check expiry change if the action is actually being
2210 # protected, since expiry does nothing on an not-protected
2212 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2218 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2222 # If nothing's changed, do nothing
2224 return Status
::newGood();
2227 if ( !$protect ) { # No protection at all means unprotection
2228 $revCommentMsg = 'unprotectedarticle';
2229 $logAction = 'unprotect';
2230 } elseif ( $isProtected ) {
2231 $revCommentMsg = 'modifiedarticleprotection';
2232 $logAction = 'modify';
2234 $revCommentMsg = 'protectedarticle';
2235 $logAction = 'protect';
2238 $encodedExpiry = array();
2239 $protectDescription = '';
2240 foreach ( $limit as $action => $restrictions ) {
2241 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2242 if ( $restrictions != '' ) {
2243 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2244 if ( $encodedExpiry[$action] != 'infinity' ) {
2245 $protectDescription .= wfMsgForContent( 'protect-expiring',
2246 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2247 $wgContLang->date( $expiry[$action], false, false ) ,
2248 $wgContLang->time( $expiry[$action], false, false ) );
2250 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
2253 $protectDescription .= ') ';
2256 $protectDescription = trim( $protectDescription );
2258 if ( $id ) { # Protection of existing page
2259 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2260 return Status
::newGood();
2263 # Only restrictions with the 'protect' right can cascade...
2264 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2265 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2267 # The schema allows multiple restrictions
2268 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2272 # Update restrictions table
2273 foreach ( $limit as $action => $restrictions ) {
2274 if ( $restrictions != '' ) {
2275 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2276 array( 'pr_page' => $id,
2277 'pr_type' => $action,
2278 'pr_level' => $restrictions,
2279 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2280 'pr_expiry' => $encodedExpiry[$action]
2285 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2286 'pr_type' => $action ), __METHOD__
);
2290 # Prepare a null revision to be added to the history
2291 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2293 $editComment .= ": $reason";
2295 if ( $protectDescription ) {
2296 $editComment .= " ($protectDescription)";
2299 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2302 # Insert a null revision
2303 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2304 $nullRevId = $nullRevision->insertOn( $dbw );
2306 $latest = $this->getLatest();
2307 # Update page record
2308 $dbw->update( 'page',
2310 'page_touched' => $dbw->timestamp(),
2311 'page_restrictions' => '',
2312 'page_latest' => $nullRevId
2313 ), array( /* WHERE */
2318 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2319 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2320 } else { # Protection of non-existing page (also known as "title protection")
2321 # Cascade protection is meaningless in this case
2324 if ( $limit['create'] != '' ) {
2325 $dbw->replace( 'protected_titles',
2326 array( array( 'pt_namespace', 'pt_title' ) ),
2328 'pt_namespace' => $this->mTitle
->getNamespace(),
2329 'pt_title' => $this->mTitle
->getDBkey(),
2330 'pt_create_perm' => $limit['create'],
2331 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2332 'pt_expiry' => $encodedExpiry['create'],
2333 'pt_user' => $user->getId(),
2334 'pt_reason' => $reason,
2338 $dbw->delete( 'protected_titles',
2340 'pt_namespace' => $this->mTitle
->getNamespace(),
2341 'pt_title' => $this->mTitle
->getDBkey()
2347 $this->mTitle
->flushRestrictions();
2349 if ( $logAction == 'unprotect' ) {
2350 $logParams = array();
2352 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2355 # Update the protection log
2356 $log = new LogPage( 'protect' );
2357 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2359 return Status
::newGood();
2363 * Take an array of page restrictions and flatten it to a string
2364 * suitable for insertion into the page_restrictions field.
2365 * @param $limit Array
2368 protected static function flattenRestrictions( $limit ) {
2369 if ( !is_array( $limit ) ) {
2370 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2376 foreach ( $limit as $action => $restrictions ) {
2377 if ( $restrictions != '' ) {
2378 $bits[] = "$action=$restrictions";
2382 return implode( ':', $bits );
2386 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2387 * backwards compatibility, if you care about error reporting you should use
2388 * doDeleteArticleReal() instead.
2390 * Deletes the article with database consistency, writes logs, purges caches
2392 * @param $reason string delete reason for deletion log
2393 * @param $suppress boolean suppress all revisions and log the deletion in
2394 * the suppression log instead of the deletion log
2395 * @param $id int article ID
2396 * @param $commit boolean defaults to true, triggers transaction end
2397 * @param &$error Array of errors to append to
2398 * @param $user User The deleting user
2399 * @return boolean true if successful
2401 public function doDeleteArticle(
2402 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2404 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2405 return $status->isGood();
2409 * Back-end article deletion
2410 * Deletes the article with database consistency, writes logs, purges caches
2414 * @param $reason string delete reason for deletion log
2415 * @param $suppress boolean suppress all revisions and log the deletion in
2416 * the suppression log instead of the deletion log
2417 * @param $commit boolean defaults to true, triggers transaction end
2418 * @param &$error Array of errors to append to
2419 * @param $user User The deleting user
2420 * @return Status: Status object; if successful, $status->value is the log_id of the
2421 * deletion log entry. If the page couldn't be deleted because it wasn't
2422 * found, $status is a non-fatal 'cannotdelete' error
2424 public function doDeleteArticleReal(
2425 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2427 global $wgUser, $wgContentHandlerUseDB;
2429 wfDebug( __METHOD__
. "\n" );
2431 $status = Status
::newGood();
2433 if ( $this->mTitle
->getDBkey() === '' ) {
2434 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2438 $user = is_null( $user ) ?
$wgUser : $user;
2439 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2440 if ( $status->isOK() ) {
2441 // Hook aborted but didn't set a fatal status
2442 $status->fatal( 'delete-hook-aborted' );
2448 $this->loadPageData( 'forupdate' );
2449 $id = $this->getID();
2451 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2456 // Bitfields to further suppress the content
2459 // This should be 15...
2460 $bitfield |
= Revision
::DELETED_TEXT
;
2461 $bitfield |
= Revision
::DELETED_COMMENT
;
2462 $bitfield |
= Revision
::DELETED_USER
;
2463 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2465 $bitfield = 'rev_deleted';
2468 // we need to remember the old content so we can use it to generate all deletion updates.
2469 $content = $this->getContent( Revision
::RAW
);
2471 $dbw = wfGetDB( DB_MASTER
);
2472 $dbw->begin( __METHOD__
);
2473 // For now, shunt the revision data into the archive table.
2474 // Text is *not* removed from the text table; bulk storage
2475 // is left intact to avoid breaking block-compression or
2476 // immutable storage schemes.
2478 // For backwards compatibility, note that some older archive
2479 // table entries will have ar_text and ar_flags fields still.
2481 // In the future, we may keep revisions and mark them with
2482 // the rev_deleted field, which is reserved for this purpose.
2485 'ar_namespace' => 'page_namespace',
2486 'ar_title' => 'page_title',
2487 'ar_comment' => 'rev_comment',
2488 'ar_user' => 'rev_user',
2489 'ar_user_text' => 'rev_user_text',
2490 'ar_timestamp' => 'rev_timestamp',
2491 'ar_minor_edit' => 'rev_minor_edit',
2492 'ar_rev_id' => 'rev_id',
2493 'ar_parent_id' => 'rev_parent_id',
2494 'ar_text_id' => 'rev_text_id',
2495 'ar_text' => '\'\'', // Be explicit to appease
2496 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2497 'ar_len' => 'rev_len',
2498 'ar_page_id' => 'page_id',
2499 'ar_deleted' => $bitfield,
2500 'ar_sha1' => 'rev_sha1',
2503 if ( $wgContentHandlerUseDB ) {
2504 $row[ 'ar_content_model' ] = 'rev_content_model';
2505 $row[ 'ar_content_format' ] = 'rev_content_format';
2508 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2512 'page_id = rev_page'
2516 # Now that it's safely backed up, delete it
2517 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2518 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2521 $dbw->rollback( __METHOD__
);
2522 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2526 $this->doDeleteUpdates( $id, $content );
2528 # Log the deletion, if the page was suppressed, log it at Oversight instead
2529 $logtype = $suppress ?
'suppress' : 'delete';
2531 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2532 $logEntry->setPerformer( $user );
2533 $logEntry->setTarget( $this->mTitle
);
2534 $logEntry->setComment( $reason );
2535 $logid = $logEntry->insert();
2536 $logEntry->publish( $logid );
2539 $dbw->commit( __METHOD__
);
2542 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2543 $status->value
= $logid;
2548 * Do some database updates after deletion
2550 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2551 * @param $content Content: optional page content to be used when determining the required updates.
2552 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2554 public function doDeleteUpdates( $id, Content
$content = null ) {
2555 # update site status
2556 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2558 # remove secondary indexes, etc
2559 $updates = $this->getDeletionUpdates( $content );
2560 DataUpdate
::runUpdates( $updates );
2563 WikiPage
::onArticleDelete( $this->mTitle
);
2568 # Clear the cached article id so the interface doesn't act like we exist
2569 $this->mTitle
->resetArticleID( 0 );
2573 * Roll back the most recent consecutive set of edits to a page
2574 * from the same user; fails if there are no eligible edits to
2575 * roll back to, e.g. user is the sole contributor. This function
2576 * performs permissions checks on $user, then calls commitRollback()
2577 * to do the dirty work
2579 * @todo: seperate the business/permission stuff out from backend code
2581 * @param $fromP String: Name of the user whose edits to rollback.
2582 * @param $summary String: Custom summary. Set to default summary if empty.
2583 * @param $token String: Rollback token.
2584 * @param $bot Boolean: If true, mark all reverted edits as bot.
2586 * @param $resultDetails Array: contains result-specific array of additional values
2587 * 'alreadyrolled' : 'current' (rev)
2588 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2590 * @param $user User The user performing the rollback
2591 * @return array of errors, each error formatted as
2592 * array(messagekey, param1, param2, ...).
2593 * On success, the array is empty. This array can also be passed to
2594 * OutputPage::showPermissionsErrorPage().
2596 public function doRollback(
2597 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2599 $resultDetails = null;
2602 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2603 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2604 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2606 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2607 $errors[] = array( 'sessionfailure' );
2610 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2611 $errors[] = array( 'actionthrottledtext' );
2614 # If there were errors, bail out now
2615 if ( !empty( $errors ) ) {
2619 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2623 * Backend implementation of doRollback(), please refer there for parameter
2624 * and return value documentation
2626 * NOTE: This function does NOT check ANY permissions, it just commits the
2627 * rollback to the DB. Therefore, you should only call this function direct-
2628 * ly if you want to use custom permissions checks. If you don't, use
2629 * doRollback() instead.
2630 * @param $fromP String: Name of the user whose edits to rollback.
2631 * @param $summary String: Custom summary. Set to default summary if empty.
2632 * @param $bot Boolean: If true, mark all reverted edits as bot.
2634 * @param $resultDetails Array: contains result-specific array of additional values
2635 * @param $guser User The user performing the rollback
2638 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2639 global $wgUseRCPatrol, $wgContLang;
2641 $dbw = wfGetDB( DB_MASTER
);
2643 if ( wfReadOnly() ) {
2644 return array( array( 'readonlytext' ) );
2647 # Get the last editor
2648 $current = $this->getRevision();
2649 if ( is_null( $current ) ) {
2650 # Something wrong... no page?
2651 return array( array( 'notanarticle' ) );
2654 $from = str_replace( '_', ' ', $fromP );
2655 # User name given should match up with the top revision.
2656 # If the user was deleted then $from should be empty.
2657 if ( $from != $current->getUserText() ) {
2658 $resultDetails = array( 'current' => $current );
2659 return array( array( 'alreadyrolled',
2660 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2661 htmlspecialchars( $fromP ),
2662 htmlspecialchars( $current->getUserText() )
2666 # Get the last edit not by this guy...
2667 # Note: these may not be public values
2668 $user = intval( $current->getRawUser() );
2669 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2670 $s = $dbw->selectRow( 'revision',
2671 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2672 array( 'rev_page' => $current->getPage(),
2673 "rev_user != {$user} OR rev_user_text != {$user_text}"
2675 array( 'USE INDEX' => 'page_timestamp',
2676 'ORDER BY' => 'rev_timestamp DESC' )
2678 if ( $s === false ) {
2679 # No one else ever edited this page
2680 return array( array( 'cantrollback' ) );
2681 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2682 # Only admins can see this text
2683 return array( array( 'notvisiblerev' ) );
2687 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2688 # Mark all reverted edits as bot
2692 if ( $wgUseRCPatrol ) {
2693 # Mark all reverted edits as patrolled
2694 $set['rc_patrolled'] = 1;
2697 if ( count( $set ) ) {
2698 $dbw->update( 'recentchanges', $set,
2700 'rc_cur_id' => $current->getPage(),
2701 'rc_user_text' => $current->getUserText(),
2702 "rc_timestamp > '{$s->rev_timestamp}'",
2707 # Generate the edit summary if necessary
2708 $target = Revision
::newFromId( $s->rev_id
);
2709 if ( empty( $summary ) ) {
2710 if ( $from == '' ) { // no public user name
2711 $summary = wfMsgForContent( 'revertpage-nouser' );
2713 $summary = wfMsgForContent( 'revertpage' );
2717 # Allow the custom summary to use the same args as the default message
2719 $target->getUserText(), $from, $s->rev_id
,
2720 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2721 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2723 $summary = wfMsgReplaceArgs( $summary, $args );
2726 $flags = EDIT_UPDATE
;
2728 if ( $guser->isAllowed( 'minoredit' ) ) {
2729 $flags |
= EDIT_MINOR
;
2732 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2733 $flags |
= EDIT_FORCE_BOT
;
2736 # Actually store the edit
2737 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2738 if ( !empty( $status->value
['revision'] ) ) {
2739 $revId = $status->value
['revision']->getId();
2744 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2746 $resultDetails = array(
2747 'summary' => $summary,
2748 'current' => $current,
2749 'target' => $target,
2757 * The onArticle*() functions are supposed to be a kind of hooks
2758 * which should be called whenever any of the specified actions
2761 * This is a good place to put code to clear caches, for instance.
2763 * This is called on page move and undelete, as well as edit
2765 * @param $title Title object
2767 public static function onArticleCreate( $title ) {
2768 # Update existence markers on article/talk tabs...
2769 if ( $title->isTalkPage() ) {
2770 $other = $title->getSubjectPage();
2772 $other = $title->getTalkPage();
2775 $other->invalidateCache();
2776 $other->purgeSquid();
2778 $title->touchLinks();
2779 $title->purgeSquid();
2780 $title->deleteTitleProtection();
2784 * Clears caches when article is deleted
2786 * @param $title Title
2788 public static function onArticleDelete( $title ) {
2789 # Update existence markers on article/talk tabs...
2790 if ( $title->isTalkPage() ) {
2791 $other = $title->getSubjectPage();
2793 $other = $title->getTalkPage();
2796 $other->invalidateCache();
2797 $other->purgeSquid();
2799 $title->touchLinks();
2800 $title->purgeSquid();
2803 HTMLFileCache
::clearFileCache( $title );
2806 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2807 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2811 if ( $title->getNamespace() == NS_FILE
) {
2812 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2813 $update->doUpdate();
2817 if ( $title->getNamespace() == NS_USER_TALK
) {
2818 $user = User
::newFromName( $title->getText(), false );
2820 $user->setNewtalk( false );
2825 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2829 * Purge caches on page update etc
2831 * @param $title Title object
2832 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2834 public static function onArticleEdit( $title ) {
2835 // Invalidate caches of articles which include this page
2836 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2839 // Invalidate the caches of all pages which redirect here
2840 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2842 # Purge squid for this page only
2843 $title->purgeSquid();
2845 # Clear file cache for this page only
2846 HTMLFileCache
::clearFileCache( $title );
2852 * Returns a list of hidden categories this page is a member of.
2853 * Uses the page_props and categorylinks tables.
2855 * @return Array of Title objects
2857 public function getHiddenCategories() {
2859 $id = $this->mTitle
->getArticleID();
2865 $dbr = wfGetDB( DB_SLAVE
);
2866 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2868 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2869 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2872 if ( $res !== false ) {
2873 foreach ( $res as $row ) {
2874 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2882 * Return an applicable autosummary if one exists for the given edit.
2883 * @param $oldtext String|null: the previous text of the page.
2884 * @param $newtext String|null: The submitted text of the page.
2885 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2886 * @return string An appropriate autosummary, or an empty string.
2888 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
2890 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2891 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2893 wfDeprecated( __METHOD__
, '1.WD' );
2895 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
2896 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
2897 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
2899 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2903 * Auto-generates a deletion reason
2905 * @param &$hasHistory Boolean: whether the page has a history
2906 * @return mixed String containing deletion reason or empty string, or boolean false
2907 * if no revision occurred
2909 public function getAutoDeleteReason( &$hasHistory ) {
2910 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2914 * Update all the appropriate counts in the category table, given that
2915 * we've added the categories $added and deleted the categories $deleted.
2917 * @param $added array The names of categories that were added
2918 * @param $deleted array The names of categories that were deleted
2920 public function updateCategoryCounts( $added, $deleted ) {
2921 $ns = $this->mTitle
->getNamespace();
2922 $dbw = wfGetDB( DB_MASTER
);
2924 # First make sure the rows exist. If one of the "deleted" ones didn't
2925 # exist, we might legitimately not create it, but it's simpler to just
2926 # create it and then give it a negative value, since the value is bogus
2929 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2930 $insertCats = array_merge( $added, $deleted );
2931 if ( !$insertCats ) {
2932 # Okay, nothing to do
2936 $insertRows = array();
2938 foreach ( $insertCats as $cat ) {
2939 $insertRows[] = array(
2940 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2944 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2946 $addFields = array( 'cat_pages = cat_pages + 1' );
2947 $removeFields = array( 'cat_pages = cat_pages - 1' );
2949 if ( $ns == NS_CATEGORY
) {
2950 $addFields[] = 'cat_subcats = cat_subcats + 1';
2951 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2952 } elseif ( $ns == NS_FILE
) {
2953 $addFields[] = 'cat_files = cat_files + 1';
2954 $removeFields[] = 'cat_files = cat_files - 1';
2961 array( 'cat_title' => $added ),
2970 array( 'cat_title' => $deleted ),
2977 * Updates cascading protections
2979 * @param $parserOutput ParserOutput object for the current version
2981 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2982 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2986 // templatelinks table may have become out of sync,
2987 // especially if using variable-based transclusions.
2988 // For paranoia, check if things have changed and if
2989 // so apply updates to the database. This will ensure
2990 // that cascaded protections apply as soon as the changes
2993 # Get templates from templatelinks
2994 $id = $this->mTitle
->getArticleID();
2996 $tlTemplates = array();
2998 $dbr = wfGetDB( DB_SLAVE
);
2999 $res = $dbr->select( array( 'templatelinks' ),
3000 array( 'tl_namespace', 'tl_title' ),
3001 array( 'tl_from' => $id ),
3005 foreach ( $res as $row ) {
3006 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3009 # Get templates from parser output.
3010 $poTemplates = array();
3011 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3012 foreach ( $templates as $dbk => $id ) {
3013 $poTemplates["$ns:$dbk"] = true;
3018 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3020 if ( count( $templates_diff ) > 0 ) {
3021 # Whee, link updates time.
3022 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3023 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3029 * Return a list of templates used by this article.
3030 * Uses the templatelinks table
3032 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3033 * @return Array of Title objects
3035 public function getUsedTemplates() {
3036 return $this->mTitle
->getTemplateLinksFrom();
3040 * Perform article updates on a special page creation.
3042 * @param $rev Revision object
3044 * @todo This is a shitty interface function. Kill it and replace the
3045 * other shitty functions like doEditUpdates and such so it's not needed
3047 * @deprecated since 1.18, use doEditUpdates()
3049 public function createUpdates( $rev ) {
3050 wfDeprecated( __METHOD__
, '1.18' );
3052 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3056 * This function is called right before saving the wikitext,
3057 * so we can do things like signatures and links-in-context.
3059 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3060 * @param $text String article contents
3061 * @param $user User object: user doing the edit
3062 * @param $popts ParserOptions object: parser options, default options for
3063 * the user loaded if null given
3064 * @return string article contents with altered wikitext markup (signatures
3065 * converted, {{subst:}}, templates, etc.)
3067 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3068 global $wgParser, $wgUser;
3070 wfDeprecated( __METHOD__
, '1.19' );
3072 $user = is_null( $user ) ?
$wgUser : $user;
3074 if ( $popts === null ) {
3075 $popts = ParserOptions
::newFromUser( $user );
3078 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3082 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3084 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3087 public function isBigDeletion() {
3088 wfDeprecated( __METHOD__
, '1.19' );
3089 return $this->mTitle
->isBigDeletion();
3093 * Get the approximate revision count of this page.
3095 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3098 public function estimateRevisionCount() {
3099 wfDeprecated( __METHOD__
, '1.19' );
3100 return $this->mTitle
->estimateRevisionCount();
3104 * Update the article's restriction field, and leave a log entry.
3106 * @deprecated since 1.19
3107 * @param $limit Array: set of restriction keys
3108 * @param $reason String
3109 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3110 * @param $expiry Array: per restriction type expiration
3111 * @param $user User The user updating the restrictions
3112 * @return bool true on success
3114 public function updateRestrictions(
3115 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3119 $user = is_null( $user ) ?
$wgUser : $user;
3121 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3125 * @deprecated since 1.18
3127 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3128 wfDeprecated( __METHOD__
, '1.18' );
3130 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3134 * @deprecated since 1.18
3136 public function viewUpdates() {
3137 wfDeprecated( __METHOD__
, '1.18' );
3139 return $this->doViewUpdates( $wgUser );
3143 * @deprecated since 1.18
3146 public function useParserCache( $oldid ) {
3147 wfDeprecated( __METHOD__
, '1.18' );
3149 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3153 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3154 * about this page from secondary data stores such as links tables.
3156 * @param Content|null $content optional Content object for determining the necessary updates
3157 * @return Array an array of DataUpdates objects
3159 public function getDeletionUpdates( Content
$content = null ) {
3161 // load content object, which may be used to determine the necessary updates
3162 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3163 $content = $this->getContent( Revision
::RAW
);
3169 $updates = $content->getDeletionUpdates( $this->mTitle
);
3172 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3178 class PoolWorkArticleView
extends PoolCounterWork
{
3196 * @var ParserOptions
3198 private $parserOptions;
3203 private $content = null;
3206 * @var ParserOutput|bool
3208 private $parserOutput = false;
3213 private $isDirty = false;
3218 private $error = false;
3224 * @param $revid Integer: ID of the revision being parsed
3225 * @param $useParserCache Boolean: whether to use the parser cache
3226 * @param $parserOptions parserOptions to use for the parse operation
3227 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3229 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3230 if ( is_string($content) ) { #BC: old style call
3231 $modelId = $page->getRevision()->getContentModel();
3232 $format = $page->getRevision()->getContentFormat();
3233 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3236 $this->page
= $page;
3237 $this->revid
= $revid;
3238 $this->cacheable
= $useParserCache;
3239 $this->parserOptions
= $parserOptions;
3240 $this->content
= $content;
3241 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3242 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3246 * Get the ParserOutput from this object, or false in case of failure
3248 * @return ParserOutput
3250 public function getParserOutput() {
3251 return $this->parserOutput
;
3255 * Get whether the ParserOutput is a dirty one (i.e. expired)
3259 public function getIsDirty() {
3260 return $this->isDirty
;
3264 * Get a Status object in case of error or false otherwise
3266 * @return Status|bool
3268 public function getError() {
3269 return $this->error
;
3276 global $wgUseFileCache;
3278 // @todo: several of the methods called on $this->page are not declared in Page, but present
3279 // in WikiPage and delegated by Article.
3281 $isCurrent = $this->revid
=== $this->page
->getLatest();
3283 if ( $this->content
!== null ) {
3284 $content = $this->content
;
3285 } elseif ( $isCurrent ) {
3286 #XXX: why use RAW audience here, and PUBLIC (default) below?
3287 $content = $this->page
->getContent( Revision
::RAW
);
3289 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3290 if ( $rev === null ) {
3294 #XXX: why use PUBLIC audience here (default), and RAW above?
3295 $content = $rev->getContent();
3298 $time = - microtime( true );
3299 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3300 $time +
= microtime( true );
3304 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3305 $this->page
->getTitle()->getPrefixedDBkey() ) );
3308 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3309 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3312 // Make sure file cache is not used on uncacheable content.
3313 // Output that has magic words in it can still use the parser cache
3314 // (if enabled), though it will generally expire sooner.
3315 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3316 $wgUseFileCache = false;
3320 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3329 function getCachedWork() {
3330 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3332 if ( $this->parserOutput
=== false ) {
3333 wfDebug( __METHOD__
. ": parser cache miss\n" );
3336 wfDebug( __METHOD__
. ": parser cache hit\n" );
3344 function fallback() {
3345 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3347 if ( $this->parserOutput
=== false ) {
3348 wfDebugLog( 'dirty', "dirty missing\n" );
3349 wfDebug( __METHOD__
. ": no dirty cache\n" );
3352 wfDebug( __METHOD__
. ": sending dirty output\n" );
3353 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3354 $this->isDirty
= true;
3360 * @param $status Status
3363 function error( $status ) {
3364 $this->error
= $status;