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.
96 * @return WikiPage object of the appropriate type
98 public static function factory( Title
$title ) {
99 $ns = $title->getNamespace();
101 if ( $ns == NS_MEDIA
) {
102 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
103 } elseif ( $ns < 0 ) {
104 throw new MWException( "Invalid or virtual namespace $ns given." );
109 $page = new WikiFilePage( $title );
112 $page = new WikiCategoryPage( $title );
115 $page = new WikiPage( $title );
122 * Constructor from a page id
124 * @param $id Int article ID to load
125 * @param $from string|int one of the following values:
126 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
127 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
129 * @return WikiPage|null
131 public static function newFromID( $id, $from = 'fromdb' ) {
132 $from = self
::convertSelectType( $from );
133 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
134 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
138 return self
::newFromRow( $row, $from );
142 * Constructor from a database row
145 * @param $row object: database row containing at least fields returned
147 * @param $from string|int: source of $data:
148 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
149 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
150 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
153 public static function newFromRow( $row, $from = 'fromdb' ) {
154 $page = self
::factory( Title
::newFromRow( $row ) );
155 $page->loadFromRow( $row, $from );
160 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
162 * @param $type object|string|int
165 private static function convertSelectType( $type ) {
168 return self
::READ_NORMAL
;
170 return self
::READ_LATEST
;
172 return self
::READ_LOCKING
;
174 // It may already be an integer or whatever else
180 * Returns overrides for action handlers.
181 * Classes listed here will be used instead of the default one when
182 * (and only when) $wgActions[$action] === true. This allows subclasses
183 * to override the default behavior.
185 * @todo: move this UI stuff somewhere else
189 public function getActionOverrides() {
190 $content_handler = $this->getContentHandler();
191 return $content_handler->getActionOverrides();
195 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
197 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
199 * @return ContentHandler
203 public function getContentHandler() {
204 return ContentHandler
::getForModelID( $this->getContentModel() );
208 * Get the title object of the article
209 * @return Title object of this page
211 public function getTitle() {
212 return $this->mTitle
;
219 public function clear() {
220 $this->mDataLoaded
= false;
221 $this->mDataLoadedFrom
= self
::READ_NONE
;
223 $this->clearCacheFields();
227 * Clear the object cache fields
230 protected function clearCacheFields() {
231 $this->mCounter
= null;
232 $this->mRedirectTarget
= null; # Title object if set
233 $this->mLastRevision
= null; # Latest revision
234 $this->mTouched
= '19700101000000';
235 $this->mTimestamp
= '';
236 $this->mIsRedirect
= false;
237 $this->mLatest
= false;
238 $this->mPreparedEdit
= false;
242 * Return the list of revision fields that should be selected to create
247 public static function selectFields() {
248 global $wgContentHandlerUseDB;
264 if ( $wgContentHandlerUseDB ) {
265 $fields[] = 'page_content_model';
272 * Fetch a page record with the given conditions
273 * @param $dbr DatabaseBase object
274 * @param $conditions Array
275 * @param $options Array
276 * @return mixed Database result resource, or false on failure
278 protected function pageData( $dbr, $conditions, $options = array() ) {
279 $fields = self
::selectFields();
281 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
283 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
285 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
291 * Fetch a page record matching the Title object's namespace and title
292 * using a sanitized title string
294 * @param $dbr DatabaseBase object
295 * @param $title Title object
296 * @param $options Array
297 * @return mixed Database result resource, or false on failure
299 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
300 return $this->pageData( $dbr, array(
301 'page_namespace' => $title->getNamespace(),
302 'page_title' => $title->getDBkey() ), $options );
306 * Fetch a page record matching the requested ID
308 * @param $dbr DatabaseBase
310 * @param $options Array
311 * @return mixed Database result resource, or false on failure
313 public function pageDataFromId( $dbr, $id, $options = array() ) {
314 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
318 * Set the general counter, title etc data loaded from
321 * @param $from object|string|int One of the following:
322 * - A DB query result object
323 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
324 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
325 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
329 public function loadPageData( $from = 'fromdb' ) {
330 $from = self
::convertSelectType( $from );
331 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
332 // We already have the data from the correct location, no need to load it twice.
336 if ( $from === self
::READ_LOCKING
) {
337 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
338 } elseif ( $from === self
::READ_LATEST
) {
339 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
340 } elseif ( $from === self
::READ_NORMAL
) {
341 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
342 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
343 # Note that DB also stores the master position in the session and checks it.
344 $touched = $this->getCachedLastEditTime();
345 if ( $touched ) { // key set
346 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
347 $from = self
::READ_LATEST
;
348 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
352 // No idea from where the caller got this data, assume slave database.
354 $from = self
::READ_NORMAL
;
357 $this->loadFromRow( $data, $from );
361 * Load the object from a database row
364 * @param $data object: database row containing at least fields returned
366 * @param $from string|int One of the following:
367 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
368 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
369 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
370 * the master DB using SELECT FOR UPDATE
372 public function loadFromRow( $data, $from ) {
373 $lc = LinkCache
::singleton();
376 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
378 $this->mTitle
->loadFromRow( $data );
380 # Old-fashioned restrictions
381 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
383 $this->mCounter
= intval( $data->page_counter
);
384 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
385 $this->mIsRedirect
= intval( $data->page_is_redirect
);
386 $this->mLatest
= intval( $data->page_latest
);
387 // Bug 37225: $latest may no longer match the cached latest Revision object.
388 // Double-check the ID of any cached latest Revision object for consistency.
389 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
390 $this->mLastRevision
= null;
391 $this->mTimestamp
= '';
394 $lc->addBadLinkObj( $this->mTitle
);
396 $this->mTitle
->loadFromRow( false );
398 $this->clearCacheFields();
401 $this->mDataLoaded
= true;
402 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
406 * @return int Page ID
408 public function getId() {
409 return $this->mTitle
->getArticleID();
413 * @return bool Whether or not the page exists in the database
415 public function exists() {
416 return $this->mTitle
->exists();
420 * Check if this page is something we're going to be showing
421 * some sort of sensible content for. If we return false, page
422 * views (plain action=view) will return an HTTP 404 response,
423 * so spiders and robots can know they're following a bad link.
427 public function hasViewableContent() {
428 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
432 * @return int The view count for the page
434 public function getCount() {
435 if ( !$this->mDataLoaded
) {
436 $this->loadPageData();
439 return $this->mCounter
;
443 * Tests if the article content represents a redirect
447 public function isRedirect( ) {
448 $content = $this->getContent();
449 if ( !$content ) return false;
451 return $content->isRedirect();
455 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
457 * Will use the revisions actual content model if the page exists,
458 * and the page's default if the page doesn't exist yet.
464 public function getContentModel() {
465 if ( $this->exists() ) {
466 # look at the revision's actual content model
467 $rev = $this->getRevision();
469 if ( $rev !== null ) {
470 return $rev->getContentModel();
472 $title = $this->mTitle
->getPrefixedDBkey();
473 wfWarn( "Page $title exists but has no (visible) revisions!" );
477 # use the default model for this page
478 return $this->mTitle
->getContentModel();
482 * Loads page_touched and returns a value indicating if it should be used
483 * @return boolean true if not a redirect
485 public function checkTouched() {
486 if ( !$this->mDataLoaded
) {
487 $this->loadPageData();
489 return !$this->mIsRedirect
;
493 * Get the page_touched field
494 * @return string containing GMT timestamp
496 public function getTouched() {
497 if ( !$this->mDataLoaded
) {
498 $this->loadPageData();
500 return $this->mTouched
;
504 * Get the page_latest field
505 * @return integer rev_id of current revision
507 public function getLatest() {
508 if ( !$this->mDataLoaded
) {
509 $this->loadPageData();
511 return (int)$this->mLatest
;
515 * Get the Revision object of the oldest revision
516 * @return Revision|null
518 public function getOldestRevision() {
519 wfProfileIn( __METHOD__
);
521 // Try using the slave database first, then try the master
523 $db = wfGetDB( DB_SLAVE
);
524 $revSelectFields = Revision
::selectFields();
526 while ( $continue ) {
527 $row = $db->selectRow(
528 array( 'page', 'revision' ),
531 'page_namespace' => $this->mTitle
->getNamespace(),
532 'page_title' => $this->mTitle
->getDBkey(),
537 'ORDER BY' => 'rev_timestamp ASC'
544 $db = wfGetDB( DB_MASTER
);
549 wfProfileOut( __METHOD__
);
550 return $row ? Revision
::newFromRow( $row ) : null;
554 * Loads everything except the text
555 * This isn't necessary for all uses, so it's only done if needed.
557 protected function loadLastEdit() {
558 if ( $this->mLastRevision
!== null ) {
559 return; // already loaded
562 $latest = $this->getLatest();
564 return; // page doesn't exist or is missing page_latest info
567 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
568 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
569 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
570 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
571 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
572 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
573 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
574 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
575 if ( $revision ) { // sanity
576 $this->setLastEdit( $revision );
581 * Set the latest revision
583 protected function setLastEdit( Revision
$revision ) {
584 $this->mLastRevision
= $revision;
585 $this->mTimestamp
= $revision->getTimestamp();
589 * Get the latest revision
590 * @return Revision|null
592 public function getRevision() {
593 $this->loadLastEdit();
594 if ( $this->mLastRevision
) {
595 return $this->mLastRevision
;
601 * Get the content of the current revision. No side-effects...
603 * @param $audience Integer: one of:
604 * Revision::FOR_PUBLIC to be displayed to all users
605 * Revision::FOR_THIS_USER to be displayed to $wgUser
606 * Revision::RAW get the text regardless of permissions
607 * @return Content|null The content of the current revision
611 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
612 $this->loadLastEdit();
613 if ( $this->mLastRevision
) {
614 return $this->mLastRevision
->getContent( $audience );
620 * Get the text of the current revision. No side-effects...
622 * @param $audience Integer: one of:
623 * Revision::FOR_PUBLIC to be displayed to all users
624 * Revision::FOR_THIS_USER to be displayed to $wgUser
625 * Revision::RAW get the text regardless of permissions
626 * @return String|false The text of the current revision
627 * @deprecated as of 1.WD, getContent() should be used instead.
629 public function getText( $audience = Revision
::FOR_PUBLIC
) { #@todo: deprecated, replace usage!
630 wfDeprecated( __METHOD__
, '1.WD' );
632 $this->loadLastEdit();
633 if ( $this->mLastRevision
) {
634 return $this->mLastRevision
->getText( $audience );
640 * Get the text of the current revision. No side-effects...
642 * @return String|bool The text of the current revision. False on failure
643 * @deprecated as of 1.WD, getContent() should be used instead.
645 public function getRawText() {
646 wfDeprecated( __METHOD__
, '1.WD' );
648 return $this->getText( Revision
::RAW
);
652 * @return string MW timestamp of last article revision
654 public function getTimestamp() {
655 // Check if the field has been filled by WikiPage::setTimestamp()
656 if ( !$this->mTimestamp
) {
657 $this->loadLastEdit();
660 return wfTimestamp( TS_MW
, $this->mTimestamp
);
664 * Set the page timestamp (use only to avoid DB queries)
665 * @param $ts string MW timestamp of last article revision
668 public function setTimestamp( $ts ) {
669 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
673 * @param $audience Integer: one of:
674 * Revision::FOR_PUBLIC to be displayed to all users
675 * Revision::FOR_THIS_USER to be displayed to $wgUser
676 * Revision::RAW get the text regardless of permissions
677 * @return int user ID for the user that made the last article revision
679 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
680 $this->loadLastEdit();
681 if ( $this->mLastRevision
) {
682 return $this->mLastRevision
->getUser( $audience );
689 * Get the User object of the user who created the page
690 * @param $audience Integer: one of:
691 * Revision::FOR_PUBLIC to be displayed to all users
692 * Revision::FOR_THIS_USER to be displayed to $wgUser
693 * Revision::RAW get the text regardless of permissions
696 public function getCreator( $audience = Revision
::FOR_PUBLIC
) {
697 $revision = $this->getOldestRevision();
699 $userName = $revision->getUserText( $audience );
700 return User
::newFromName( $userName, false );
707 * @param $audience Integer: one of:
708 * Revision::FOR_PUBLIC to be displayed to all users
709 * Revision::FOR_THIS_USER to be displayed to $wgUser
710 * Revision::RAW get the text regardless of permissions
711 * @return string username of the user that made the last article revision
713 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
714 $this->loadLastEdit();
715 if ( $this->mLastRevision
) {
716 return $this->mLastRevision
->getUserText( $audience );
723 * @param $audience Integer: one of:
724 * Revision::FOR_PUBLIC to be displayed to all users
725 * Revision::FOR_THIS_USER to be displayed to $wgUser
726 * Revision::RAW get the text regardless of permissions
727 * @return string Comment stored for the last article revision
729 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
730 $this->loadLastEdit();
731 if ( $this->mLastRevision
) {
732 return $this->mLastRevision
->getComment( $audience );
739 * Returns true if last revision was marked as "minor edit"
741 * @return boolean Minor edit indicator for the last article revision.
743 public function getMinorEdit() {
744 $this->loadLastEdit();
745 if ( $this->mLastRevision
) {
746 return $this->mLastRevision
->isMinor();
753 * Get the cached timestamp for the last time the page changed.
754 * This is only used to help handle slave lag by comparing to page_touched.
755 * @return string MW timestamp
757 protected function getCachedLastEditTime() {
759 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
760 return $wgMemc->get( $key );
764 * Set the cached timestamp for the last time the page changed.
765 * This is only used to help handle slave lag by comparing to page_touched.
766 * @param $timestamp string
769 public function setCachedLastEditTime( $timestamp ) {
771 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
772 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
776 * Determine whether a page would be suitable for being counted as an
777 * article in the site_stats table based on the title & its content
779 * @param $editInfo Object|bool (false): object returned by prepareTextForEdit(),
780 * if false, the current database state will be used
783 public function isCountable( $editInfo = false ) {
784 global $wgArticleCountMethod;
786 if ( !$this->mTitle
->isContentPage() ) {
791 $content = $editInfo->pstContent
;
793 $content = $this->getContent();
796 if ( !$content ||
$content->isRedirect( ) ) {
802 if ( $wgArticleCountMethod === 'link' ) {
803 # nasty special case to avoid re-parsing to detect links
806 // ParserOutput::getLinks() is a 2D array of page links, so
807 // to be really correct we would need to recurse in the array
808 // but the main array should only have items in it if there are
810 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
812 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
813 array( 'pl_from' => $this->getId() ), __METHOD__
);
817 return $content->isCountable( $hasLinks );
821 * If this page is a redirect, get its target
823 * The target will be fetched from the redirect table if possible.
824 * If this page doesn't have an entry there, call insertRedirect()
825 * @return Title|mixed object, or null if this page is not a redirect
827 public function getRedirectTarget() {
828 if ( !$this->mTitle
->isRedirect() ) {
832 if ( $this->mRedirectTarget
!== null ) {
833 return $this->mRedirectTarget
;
836 # Query the redirect table
837 $dbr = wfGetDB( DB_SLAVE
);
838 $row = $dbr->selectRow( 'redirect',
839 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
840 array( 'rd_from' => $this->getId() ),
844 // rd_fragment and rd_interwiki were added later, populate them if empty
845 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
846 return $this->mRedirectTarget
= Title
::makeTitle(
847 $row->rd_namespace
, $row->rd_title
,
848 $row->rd_fragment
, $row->rd_interwiki
);
851 # This page doesn't have an entry in the redirect table
852 return $this->mRedirectTarget
= $this->insertRedirect();
856 * Insert an entry for this page into the redirect table.
858 * Don't call this function directly unless you know what you're doing.
859 * @return Title object or null if not a redirect
861 public function insertRedirect() {
862 // recurse through to only get the final target
863 $content = $this->getContent();
864 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
868 $this->insertRedirectEntry( $retval );
873 * Insert or update the redirect table entry for this page to indicate
874 * it redirects to $rt .
875 * @param $rt Title redirect target
877 public function insertRedirectEntry( $rt ) {
878 $dbw = wfGetDB( DB_MASTER
);
879 $dbw->replace( 'redirect', array( 'rd_from' ),
881 'rd_from' => $this->getId(),
882 'rd_namespace' => $rt->getNamespace(),
883 'rd_title' => $rt->getDBkey(),
884 'rd_fragment' => $rt->getFragment(),
885 'rd_interwiki' => $rt->getInterwiki(),
892 * Get the Title object or URL this page redirects to
894 * @return mixed false, Title of in-wiki target, or string with URL
896 public function followRedirect() {
897 return $this->getRedirectURL( $this->getRedirectTarget() );
901 * Get the Title object or URL to use for a redirect. We use Title
902 * objects for same-wiki, non-special redirects and URLs for everything
904 * @param $rt Title Redirect target
905 * @return mixed false, Title object of local target, or string with URL
907 public function getRedirectURL( $rt ) {
912 if ( $rt->isExternal() ) {
913 if ( $rt->isLocal() ) {
914 // Offsite wikis need an HTTP redirect.
916 // This can be hard to reverse and may produce loops,
917 // so they may be disabled in the site configuration.
918 $source = $this->mTitle
->getFullURL( 'redirect=no' );
919 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
921 // External pages pages without "local" bit set are not valid
927 if ( $rt->isSpecialPage() ) {
928 // Gotta handle redirects to special pages differently:
929 // Fill the HTTP response "Location" header and ignore
930 // the rest of the page we're on.
932 // Some pages are not valid targets
933 if ( $rt->isValidRedirectTarget() ) {
934 return $rt->getFullURL();
944 * Get a list of users who have edited this article, not including the user who made
945 * the most recent revision, which you can get from $article->getUser() if you want it
946 * @return UserArrayFromResult
948 public function getContributors() {
949 # @todo FIXME: This is expensive; cache this info somewhere.
951 $dbr = wfGetDB( DB_SLAVE
);
953 if ( $dbr->implicitGroupby() ) {
954 $realNameField = 'user_real_name';
956 $realNameField = 'MIN(user_real_name) AS user_real_name';
959 $tables = array( 'revision', 'user' );
962 'user_id' => 'rev_user',
963 'user_name' => 'rev_user_text',
965 'timestamp' => 'MAX(rev_timestamp)',
968 $conds = array( 'rev_page' => $this->getId() );
970 // The user who made the top revision gets credited as "this page was last edited by
971 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
972 $user = $this->getUser();
974 $conds[] = "rev_user != $user";
976 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
979 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
982 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
986 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
987 'ORDER BY' => 'timestamp DESC',
990 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
991 return new UserArrayFromResult( $res );
995 * Get the last N authors
996 * @param $num Integer: number of revisions to get
997 * @param $revLatest String: the latest rev_id, selected from the master (optional)
998 * @return array Array of authors, duplicates not removed
1000 public function getLastNAuthors( $num, $revLatest = 0 ) {
1001 wfProfileIn( __METHOD__
);
1002 // First try the slave
1003 // If that doesn't have the latest revision, try the master
1005 $db = wfGetDB( DB_SLAVE
);
1008 $res = $db->select( array( 'page', 'revision' ),
1009 array( 'rev_id', 'rev_user_text' ),
1011 'page_namespace' => $this->mTitle
->getNamespace(),
1012 'page_title' => $this->mTitle
->getDBkey(),
1013 'rev_page = page_id'
1016 'ORDER BY' => 'rev_timestamp DESC',
1022 wfProfileOut( __METHOD__
);
1026 $row = $db->fetchObject( $res );
1028 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1029 $db = wfGetDB( DB_MASTER
);
1034 } while ( $continue );
1036 $authors = array( $row->rev_user_text
);
1038 foreach ( $res as $row ) {
1039 $authors[] = $row->rev_user_text
;
1042 wfProfileOut( __METHOD__
);
1047 * Should the parser cache be used?
1049 * @param $parserOptions ParserOptions to check
1053 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1054 global $wgEnableParserCache;
1056 return $wgEnableParserCache
1057 && $parserOptions->getStubThreshold() == 0
1058 && $this->mTitle
->exists()
1059 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1060 && $this->getContentHandler()->isParserCacheSupported();
1064 * Get a ParserOutput for the given ParserOptions and revision ID.
1065 * The parser cache will be used if possible.
1068 * @param $parserOptions ParserOptions to use for the parse operation
1069 * @param $oldid Revision ID to get the text from, passing null or 0 will
1070 * get the current revision (default value)
1072 * @return ParserOutput or false if the revision was not found
1074 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1075 wfProfileIn( __METHOD__
);
1077 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1078 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1079 if ( $parserOptions->getStubThreshold() ) {
1080 wfIncrStats( 'pcache_miss_stub' );
1083 if ( $useParserCache ) {
1084 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1085 if ( $parserOutput !== false ) {
1086 wfProfileOut( __METHOD__
);
1087 return $parserOutput;
1091 if ( $oldid === null ||
$oldid === 0 ) {
1092 $oldid = $this->getLatest();
1095 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1098 wfProfileOut( __METHOD__
);
1100 return $pool->getParserOutput();
1104 * Do standard deferred updates after page view
1105 * @param $user User The relevant user
1107 public function doViewUpdates( User
$user ) {
1108 global $wgDisableCounters;
1109 if ( wfReadOnly() ) {
1113 # Don't update page view counters on views from bot users (bug 14044)
1114 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1115 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1116 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1119 # Update newtalk / watchlist notification status
1120 $user->clearNotification( $this->mTitle
);
1124 * Perform the actions of a page purging
1127 public function doPurge() {
1130 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1134 // Invalidate the cache
1135 $this->mTitle
->invalidateCache();
1138 if ( $wgUseSquid ) {
1139 // Commit the transaction before the purge is sent
1140 $dbw = wfGetDB( DB_MASTER
);
1141 $dbw->commit( __METHOD__
);
1144 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1145 $update->doUpdate();
1148 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1149 //@todo: move this logic to MessageCache
1151 if ( $this->mTitle
->exists() ) {
1152 // NOTE: use transclusion text for messages.
1153 // This is consistent with MessageCache::getMsgFromNamespace()
1155 $content = $this->getContent();
1156 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1158 if ( $text === null ) $text = false;
1163 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1169 * Insert a new empty page record for this article.
1170 * This *must* be followed up by creating a revision
1171 * and running $this->updateRevisionOn( ... );
1172 * or else the record will be left in a funky state.
1173 * Best if all done inside a transaction.
1175 * @param $dbw DatabaseBase
1176 * @return int The newly created page_id key, or false if the title already existed
1178 public function insertOn( $dbw ) {
1179 wfProfileIn( __METHOD__
);
1181 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1182 $dbw->insert( 'page', array(
1183 'page_id' => $page_id,
1184 'page_namespace' => $this->mTitle
->getNamespace(),
1185 'page_title' => $this->mTitle
->getDBkey(),
1186 'page_counter' => 0,
1187 'page_restrictions' => '',
1188 'page_is_redirect' => 0, # Will set this shortly...
1190 'page_random' => wfRandom(),
1191 'page_touched' => $dbw->timestamp(),
1192 'page_latest' => 0, # Fill this in shortly...
1193 'page_len' => 0, # Fill this in shortly...
1194 ), __METHOD__
, 'IGNORE' );
1196 $affected = $dbw->affectedRows();
1199 $newid = $dbw->insertId();
1200 $this->mTitle
->resetArticleID( $newid );
1202 wfProfileOut( __METHOD__
);
1204 return $affected ?
$newid : false;
1208 * Update the page record to point to a newly saved revision.
1210 * @param $dbw DatabaseBase: object
1211 * @param $revision Revision: For ID number, and text used to set
1212 * length and redirect status fields
1213 * @param $lastRevision Integer: if given, will not overwrite the page field
1214 * when different from the currently set value.
1215 * Giving 0 indicates the new page flag should be set
1217 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1218 * removing rows in redirect table.
1219 * @return bool true on success, false on failure
1222 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1223 global $wgContentHandlerUseDB;
1225 wfProfileIn( __METHOD__
);
1227 $content = $revision->getContent();
1228 $len = $content->getSize();
1229 $rt = $content->getUltimateRedirectTarget();
1231 $conditions = array( 'page_id' => $this->getId() );
1233 if ( !is_null( $lastRevision ) ) {
1234 # An extra check against threads stepping on each other
1235 $conditions['page_latest'] = $lastRevision;
1238 $now = wfTimestampNow();
1239 $row = array( /* SET */
1240 'page_latest' => $revision->getId(),
1241 'page_touched' => $dbw->timestamp( $now ),
1242 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1243 'page_is_redirect' => $rt !== null ?
1 : 0,
1247 if ( $wgContentHandlerUseDB ) {
1248 $row[ 'page_content_model' ] = $revision->getContentModel();
1251 $dbw->update( 'page',
1256 $result = $dbw->affectedRows() > 0;
1258 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1259 $this->setLastEdit( $revision );
1260 $this->setCachedLastEditTime( $now );
1261 $this->mLatest
= $revision->getId();
1262 $this->mIsRedirect
= (bool)$rt;
1263 # Update the LinkCache.
1264 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1265 $this->mLatest
, $revision->getContentModel() );
1268 wfProfileOut( __METHOD__
);
1273 * Add row to the redirect table if this is a redirect, remove otherwise.
1275 * @param $dbw DatabaseBase
1276 * @param $redirectTitle Title object pointing to the redirect target,
1277 * or NULL if this is not a redirect
1278 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1279 * removing rows in redirect table.
1280 * @return bool true on success, false on failure
1283 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1284 // Always update redirects (target link might have changed)
1285 // Update/Insert if we don't know if the last revision was a redirect or not
1286 // Delete if changing from redirect to non-redirect
1287 $isRedirect = !is_null( $redirectTitle );
1289 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1293 wfProfileIn( __METHOD__
);
1294 if ( $isRedirect ) {
1295 $this->insertRedirectEntry( $redirectTitle );
1297 // This is not a redirect, remove row from redirect table
1298 $where = array( 'rd_from' => $this->getId() );
1299 $dbw->delete( 'redirect', $where, __METHOD__
);
1302 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1303 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1305 wfProfileOut( __METHOD__
);
1307 return ( $dbw->affectedRows() != 0 );
1311 * If the given revision is newer than the currently set page_latest,
1312 * update the page record. Otherwise, do nothing.
1314 * @param $dbw DatabaseBase object
1315 * @param $revision Revision object
1318 public function updateIfNewerOn( $dbw, $revision ) {
1319 wfProfileIn( __METHOD__
);
1321 $row = $dbw->selectRow(
1322 array( 'revision', 'page' ),
1323 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1325 'page_id' => $this->getId(),
1326 'page_latest=rev_id' ),
1330 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1331 wfProfileOut( __METHOD__
);
1334 $prev = $row->rev_id
;
1335 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1337 # No or missing previous revision; mark the page as new
1339 $lastRevIsRedirect = null;
1342 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1344 wfProfileOut( __METHOD__
);
1349 * Get the content that needs to be saved in order to undo all revisions
1350 * between $undo and $undoafter. Revisions must belong to the same page,
1351 * must exist and must not be deleted
1352 * @param $undo Revision
1353 * @param $undoafter Revision Must be an earlier revision than $undo
1354 * @return mixed string on success, false on failure
1356 * Before we had the Content object, this was done in getUndoText
1358 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1359 $handler = $undo->getContentHandler();
1360 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1364 * Get the text that needs to be saved in order to undo all revisions
1365 * between $undo and $undoafter. Revisions must belong to the same page,
1366 * must exist and must not be deleted
1367 * @param $undo Revision
1368 * @param $undoafter Revision Must be an earlier revision than $undo
1369 * @return mixed string on success, false on failure
1370 * @deprecated since 1.WD: use ContentHandler::getUndoContent() instead.
1372 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1373 wfDeprecated( __METHOD__
, '1.WD' );
1375 $this->loadLastEdit();
1377 if ( $this->mLastRevision
) {
1378 if ( is_null( $undoafter ) ) {
1379 $undoafter = $undo->getPrevious();
1382 $handler = $this->getContentHandler();
1383 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1388 return ContentHandler
::getContentText( $undone );
1396 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1397 * @param $text String: new text of the section
1398 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1399 * @param $edittime String: revision timestamp or null to use the current revision
1400 * @return String new complete article text, or null if error
1402 * @deprecated since 1.WD, use replaceSectionContent() instead
1404 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1405 wfDeprecated( __METHOD__
, '1.WD' );
1407 if ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1408 // Whole-page edit; let the whole text through
1412 if ( !$this->supportsSections() ) {
1413 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1416 # could even make section title, but that's not required.
1417 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1419 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1421 return ContentHandler
::getContentText( $newContent );
1425 * Returns true iff this page's content model supports sections.
1427 * @return boolean whether sections are supported.
1429 * @todo: the skin should check this and not offer section functionality if sections are not supported.
1430 * @todo: the EditPage should check this and not offer section functionality if sections are not supported.
1432 public function supportsSections() {
1433 return $this->getContentHandler()->supportsSections();
1437 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1438 * @param $content Content: new content of the section
1439 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1440 * @param $edittime String: revision timestamp or null to use the current revision
1442 * @return Content new complete article content, or null if error
1446 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1447 wfProfileIn( __METHOD__
);
1449 if ( strval( $section ) == '' ) {
1450 // Whole-page edit; let the whole text through
1451 $newContent = $sectionContent;
1453 if ( !$this->supportsSections() ) {
1454 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1457 // Bug 30711: always use current version when adding a new section
1458 if ( is_null( $edittime ) ||
$section == 'new' ) {
1459 $oldContent = $this->getContent();
1460 if ( ! $oldContent ) {
1461 wfDebug( __METHOD__
. ": no page text\n" );
1462 wfProfileOut( __METHOD__
);
1466 $dbw = wfGetDB( DB_MASTER
);
1467 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1470 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1471 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1472 wfProfileOut( __METHOD__
);
1476 $oldContent = $rev->getContent();
1479 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1482 wfProfileOut( __METHOD__
);
1487 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1489 * @return Int updated $flags
1491 function checkFlags( $flags ) {
1492 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1493 if ( $this->mTitle
->getArticleID() ) {
1494 $flags |
= EDIT_UPDATE
;
1504 * Change an existing article or create a new article. Updates RC and all necessary caches,
1505 * optionally via the deferred update array.
1507 * @param $text String: new text
1508 * @param $summary String: edit summary
1509 * @param $flags Integer bitfield:
1511 * Article is known or assumed to be non-existent, create a new one
1513 * Article is known or assumed to be pre-existing, update it
1515 * Mark this edit minor, if the user is allowed to do so
1517 * Do not log the change in recentchanges
1519 * Mark the edit a "bot" edit regardless of user rights
1520 * EDIT_DEFER_UPDATES
1521 * Defer some of the updates until the end of index.php
1523 * Fill in blank summaries with generated text where possible
1525 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1526 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1527 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1528 * edit-already-exists error will be returned. These two conditions are also possible with
1529 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1531 * @param bool|int $baseRevId int the revision ID this edit was based off, if any
1532 * @param $user User the user doing the edit
1534 * @throws MWException
1535 * @return Status object. Possible errors:
1536 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1537 * edit-gone-missing: In update mode, but the article didn't exist
1538 * edit-conflict: In update mode, the article changed unexpectedly
1539 * edit-no-change: Warning that the text was the same as before
1540 * edit-already-exists: In creation mode, but the article already exists
1542 * Extensions may define additional errors.
1544 * $return->value will contain an associative array with members as follows:
1545 * new: Boolean indicating if the function attempted to create a new article
1546 * revision: The revision object for the inserted revision, or null
1548 * Compatibility note: this function previously returned a boolean value indicating success/failure
1550 * @deprecated since 1.WD: use doEditContent() instead.
1551 * @todo: use doEditContent() instead everywhere
1553 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1554 wfDeprecated( __METHOD__
, '1.WD' );
1556 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1558 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1562 * Change an existing article or create a new article. Updates RC and all necessary caches,
1563 * optionally via the deferred update array.
1565 * @param $content Content: new content
1566 * @param $summary String: edit summary
1567 * @param $flags Integer bitfield:
1569 * Article is known or assumed to be non-existent, create a new one
1571 * Article is known or assumed to be pre-existing, update it
1573 * Mark this edit minor, if the user is allowed to do so
1575 * Do not log the change in recentchanges
1577 * Mark the edit a "bot" edit regardless of user rights
1578 * EDIT_DEFER_UPDATES
1579 * Defer some of the updates until the end of index.php
1581 * Fill in blank summaries with generated text where possible
1583 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1584 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1585 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1586 * edit-already-exists error will be returned. These two conditions are also possible with
1587 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1589 * @param $baseRevId the revision ID this edit was based off, if any
1590 * @param $user User the user doing the edit
1591 * @param $serialisation_format String: format for storing the content in the database
1593 * @return Status object. Possible errors:
1594 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1595 * edit-gone-missing: In update mode, but the article didn't exist
1596 * edit-conflict: In update mode, the article changed unexpectedly
1597 * edit-no-change: Warning that the text was the same as before
1598 * edit-already-exists: In creation mode, but the article already exists
1600 * Extensions may define additional errors.
1602 * $return->value will contain an associative array with members as follows:
1603 * new: Boolean indicating if the function attempted to create a new article
1604 * revision: The revision object for the inserted revision, or null
1608 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1609 User
$user = null, $serialisation_format = null ) {
1610 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1612 # Low-level sanity check
1613 if ( $this->mTitle
->getText() === '' ) {
1614 throw new MWException( 'Something is trying to edit an article with an empty title' );
1617 wfProfileIn( __METHOD__
);
1619 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1620 wfProfileOut( __METHOD__
);
1621 return Status
::newFatal( 'content-not-allowed-here',
1622 ContentHandler
::getLocalizedName( $content->getModel() ),
1623 $this->getTitle()->getPrefixedText() );
1626 $user = is_null( $user ) ?
$wgUser : $user;
1627 $status = Status
::newGood( array() );
1629 // Load the data from the master database if needed.
1630 // The caller may already loaded it from the master or even loaded it using
1631 // SELECT FOR UPDATE, so do not override that using clear().
1632 $this->loadPageData( 'fromdbmaster' );
1634 $flags = $this->checkFlags( $flags );
1637 $hook_args = array( &$this, &$user, &$content, &$summary,
1638 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1640 if ( !wfRunHooks( 'ArticleContentSave', $hook_args )
1641 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1643 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1645 if ( $status->isOK() ) {
1646 $status->fatal( 'edit-hook-aborted' );
1649 wfProfileOut( __METHOD__
);
1653 # Silently ignore EDIT_MINOR if not allowed
1654 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1655 $bot = $flags & EDIT_FORCE_BOT
;
1657 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1659 $oldsize = $old_content ?
$old_content->getSize() : 0;
1660 $oldid = $this->getLatest();
1661 $oldIsRedirect = $this->isRedirect();
1662 $oldcountable = $this->isCountable();
1664 $handler = $content->getContentHandler();
1666 # Provide autosummaries if one is not provided and autosummaries are enabled.
1667 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1668 if ( !$old_content ) $old_content = null;
1669 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1672 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1673 $serialized = $editInfo->pst
;
1674 $content = $editInfo->pstContent
;
1675 $newsize = $content->getSize();
1677 $dbw = wfGetDB( DB_MASTER
);
1678 $now = wfTimestampNow();
1679 $this->mTimestamp
= $now;
1681 if ( $flags & EDIT_UPDATE
) {
1682 # Update article, but only if changed.
1683 $status->value
['new'] = false;
1686 # Article gone missing
1687 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1688 $status->fatal( 'edit-gone-missing' );
1690 wfProfileOut( __METHOD__
);
1692 } elseif ( !$old_content ) {
1693 # Sanity check for bug 37225
1694 wfProfileOut( __METHOD__
);
1695 throw new MWException( "Could not find text for current revision {$oldid}." );
1698 $revision = new Revision( array(
1699 'page' => $this->getId(),
1700 'comment' => $summary,
1701 'minor_edit' => $isminor,
1702 'text' => $serialized,
1704 'parent_id' => $oldid,
1705 'user' => $user->getId(),
1706 'user_text' => $user->getName(),
1707 'timestamp' => $now,
1708 'content_model' => $content->getModel(),
1709 'content_format' => $serialisation_format,
1710 ) ); #XXX: pass content object?!
1712 $changed = !$content->equals( $old_content );
1715 if ( !$content->isValid() ) {
1716 throw new MWException( "New content failed validity check!" );
1719 $dbw->begin( __METHOD__
);
1721 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1722 $status->merge( $prepStatus );
1724 if ( !$status->isOK() ) {
1727 wfProfileOut( __METHOD__
);
1731 $revisionId = $revision->insertOn( $dbw );
1735 # Note that we use $this->mLatest instead of fetching a value from the master DB
1736 # during the course of this function. This makes sure that EditPage can detect
1737 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1738 # before this function is called. A previous function used a separate query, this
1739 # creates a window where concurrent edits can cause an ignored edit conflict.
1740 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1743 # Belated edit conflict! Run away!!
1744 $status->fatal( 'edit-conflict' );
1746 $dbw->rollback( __METHOD__
);
1748 wfProfileOut( __METHOD__
);
1752 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1753 # Update recentchanges
1754 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1755 # Mark as patrolled if the user can do so
1756 $patrolled = $wgUseRCPatrol && !count(
1757 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1758 # Add RC row to the DB
1759 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1760 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1761 $revisionId, $patrolled
1764 # Log auto-patrolled edits
1766 PatrolLog
::record( $rc, true, $user );
1769 $user->incEditCount();
1770 $dbw->commit( __METHOD__
);
1772 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1773 // related variables correctly
1774 $revision->setId( $this->getLatest() );
1777 # Update links tables, site stats, etc.
1778 $this->doEditUpdates(
1782 'changed' => $changed,
1783 'oldcountable' => $oldcountable
1788 $status->warning( 'edit-no-change' );
1790 // Update page_touched, this is usually implicit in the page update
1791 // Other cache updates are done in onArticleEdit()
1792 $this->mTitle
->invalidateCache();
1795 # Create new article
1796 $status->value
['new'] = true;
1798 $dbw->begin( __METHOD__
);
1800 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1801 $status->merge( $prepStatus );
1803 if ( !$status->isOK() ) {
1806 wfProfileOut( __METHOD__
);
1810 $status->merge( $prepStatus );
1812 # Add the page record; stake our claim on this title!
1813 # This will return false if the article already exists
1814 $newid = $this->insertOn( $dbw );
1816 if ( $newid === false ) {
1817 $dbw->rollback( __METHOD__
);
1818 $status->fatal( 'edit-already-exists' );
1820 wfProfileOut( __METHOD__
);
1824 # Save the revision text...
1825 $revision = new Revision( array(
1827 'comment' => $summary,
1828 'minor_edit' => $isminor,
1829 'text' => $serialized,
1831 'user' => $user->getId(),
1832 'user_text' => $user->getName(),
1833 'timestamp' => $now,
1834 'content_model' => $content->getModel(),
1835 'content_format' => $serialisation_format,
1837 $revisionId = $revision->insertOn( $dbw );
1839 # Bug 37225: use accessor to get the text as Revision may trim it
1840 $content = $revision->getContent(); // sanity; get normalized version
1842 # Update the page record with revision data
1843 $this->updateRevisionOn( $dbw, $revision, 0 );
1845 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1847 # Update recentchanges
1848 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1849 # Mark as patrolled if the user can do so
1850 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1851 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1852 # Add RC row to the DB
1853 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1854 '', $content->getSize(), $revisionId, $patrolled );
1856 # Log auto-patrolled edits
1858 PatrolLog
::record( $rc, true, $user );
1861 $user->incEditCount();
1862 $dbw->commit( __METHOD__
);
1864 # Update links, etc.
1865 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1867 $hook_args = array( &$this, &$user, $content, $summary,
1868 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1870 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1871 wfRunHooks( 'ArticleContentInsertComplete', $hook_args );
1874 # Do updates right now unless deferral was requested
1875 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1876 DeferredUpdates
::doUpdates();
1879 // Return the new revision (or null) to the caller
1880 $status->value
['revision'] = $revision;
1882 $hook_args = array( &$this, &$user, $content, $summary,
1883 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1885 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1886 wfRunHooks( 'ArticleContentSaveComplete', $hook_args );
1888 # Promote user to any groups they meet the criteria for
1889 $user->addAutopromoteOnceGroups( 'onEdit' );
1891 wfProfileOut( __METHOD__
);
1896 * Get parser options suitable for rendering the primary article wikitext
1897 * @param User|string $user User object or 'canonical'
1898 * @return ParserOptions
1900 public function makeParserOptions( $user ) {
1902 if ( $user instanceof User
) { // settings per user (even anons)
1903 $options = ParserOptions
::newFromUser( $user );
1904 } else { // canonical settings
1905 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1907 $options->enableLimitReport(); // show inclusion/loop reports
1908 $options->setTidy( true ); // fix bad HTML
1913 * Prepare text which is about to be saved.
1914 * Returns a stdclass with source, pst and output members
1916 * @deprecated in 1.WD: use prepareContentForEdit instead.
1918 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1919 wfDeprecated( __METHOD__
, '1.WD' );
1920 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1921 return $this->prepareContentForEdit( $content, $revid , $user );
1925 * Prepare content which is about to be saved.
1926 * Returns a stdclass with source, pst and output members
1928 * @param \Content $content
1929 * @param null $revid
1930 * @param null|\User $user
1931 * @param null $serialization_format
1933 * @return bool|object
1937 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) {
1938 global $wgParser, $wgContLang, $wgUser;
1939 $user = is_null( $user ) ?
$wgUser : $user;
1940 // @TODO fixme: check $user->getId() here???
1942 if ( $this->mPreparedEdit
1943 && $this->mPreparedEdit
->newContent
1944 && $this->mPreparedEdit
->newContent
->equals( $content )
1945 && $this->mPreparedEdit
->revid
== $revid
1946 && $this->mPreparedEdit
->format
== $serialization_format
1947 #XXX: also check $user here?
1950 return $this->mPreparedEdit
;
1953 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1954 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1956 $edit = (object)array();
1957 $edit->revid
= $revid;
1959 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1960 $edit->pst
= $edit->pstContent
->serialize( $serialization_format ); #XXX: do we need this??
1961 $edit->format
= $serialization_format;
1963 $edit->popts
= $this->makeParserOptions( 'canonical' );
1965 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1967 $edit->newContent
= $content;
1968 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1970 #NOTE: B/C for hooks! don't use these fields!
1971 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
);
1972 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
1974 $this->mPreparedEdit
= $edit;
1980 * Do standard deferred updates after page edit.
1981 * Update links tables, site stats, search index and message cache.
1982 * Purges pages that include this page if the text was changed here.
1983 * Every 100th edit, prune the recent changes table.
1985 * @param $revision Revision object
1986 * @param $user User object that did the revision
1987 * @param $options Array of options, following indexes are used:
1988 * - changed: boolean, whether the revision changed the content (default true)
1989 * - created: boolean, whether the revision created the page (default false)
1990 * - oldcountable: boolean or null (default null):
1991 * - boolean: whether the page was counted as an article before that
1992 * revision, only used in changed is true and created is false
1993 * - null: don't change the article count
1995 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1996 global $wgEnableParserCache;
1998 wfProfileIn( __METHOD__
);
2000 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2001 $content = $revision->getContent();
2004 # Be careful not to double-PST: $text is usually already PST-ed once
2005 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2006 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2007 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2009 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2010 $editInfo = $this->mPreparedEdit
;
2013 # Save it to the parser cache
2014 if ( $wgEnableParserCache ) {
2015 $parserCache = ParserCache
::singleton();
2016 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2019 # Update the links tables and other secondary data
2020 $updates = $content->getSecondaryDataUpdates( $this->getTitle(), null, true, $editInfo->output
);
2021 DataUpdate
::runUpdates( $updates );
2023 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2025 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2026 if ( 0 == mt_rand( 0, 99 ) ) {
2027 // Flush old entries from the `recentchanges` table; we do this on
2028 // random requests so as to avoid an increase in writes for no good reason
2031 $dbw = wfGetDB( DB_MASTER
);
2032 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2035 array( "rc_timestamp < '$cutoff'" ),
2041 if ( !$this->mTitle
->exists() ) {
2042 wfProfileOut( __METHOD__
);
2046 $id = $this->getId();
2047 $title = $this->mTitle
->getPrefixedDBkey();
2048 $shortTitle = $this->mTitle
->getDBkey();
2050 if ( !$options['changed'] ) {
2053 } elseif ( $options['created'] ) {
2054 $good = (int)$this->isCountable( $editInfo );
2056 } elseif ( $options['oldcountable'] !== null ) {
2057 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2064 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2065 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
2066 #@TODO: let the search engine decide what to do with the content object
2068 # If this is another user's talk page, update newtalk.
2069 # Don't do this if $options['changed'] = false (null-edits) nor if
2070 # it's a minor edit and the user doesn't want notifications for those.
2071 if ( $options['changed']
2072 && $this->mTitle
->getNamespace() == NS_USER_TALK
2073 && $shortTitle != $user->getTitleKey()
2074 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2076 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2077 $other = User
::newFromName( $shortTitle, false );
2079 wfDebug( __METHOD__
. ": invalid username\n" );
2080 } elseif ( User
::isIP( $shortTitle ) ) {
2081 // An anonymous user
2082 $other->setNewtalk( true, $revision );
2083 } elseif ( $other->isLoggedIn() ) {
2084 $other->setNewtalk( true, $revision );
2086 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2091 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2092 #XXX: could skip pseudo-messages like js/css here, based on content model.
2093 $msgtext = $content->getWikitextForTransclusion();
2094 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
2096 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2099 if( $options['created'] ) {
2100 self
::onArticleCreate( $this->mTitle
);
2102 self
::onArticleEdit( $this->mTitle
);
2105 wfProfileOut( __METHOD__
);
2109 * Edit an article without doing all that other stuff
2110 * The article must already exist; link tables etc
2111 * are not updated, caches are not flushed.
2113 * @param $text String: text submitted
2114 * @param $user User The relevant user
2115 * @param $comment String: comment submitted
2116 * @param $minor Boolean: whereas it's a minor modification
2118 * @deprecated since 1.WD, use doEditContent() instead.
2120 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2121 wfDeprecated( __METHOD__
, "1.WD" );
2123 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2124 return $this->doQuickEditContent( $content, $user, $comment , $minor );
2128 * Edit an article without doing all that other stuff
2129 * The article must already exist; link tables etc
2130 * are not updated, caches are not flushed.
2132 * @param $content Content: content submitted
2133 * @param $user User The relevant user
2134 * @param $comment String: comment submitted
2135 * @param $serialisation_format String: format for storing the content in the database
2136 * @param $minor Boolean: whereas it's a minor modification
2138 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
2139 wfProfileIn( __METHOD__
);
2141 $serialized = $content->serialize( $serialisation_format );
2143 $dbw = wfGetDB( DB_MASTER
);
2144 $revision = new Revision( array(
2145 'page' => $this->getId(),
2146 'text' => $serialized,
2147 'length' => $content->getSize(),
2148 'comment' => $comment,
2149 'minor_edit' => $minor ?
1 : 0,
2150 ) ); #XXX: set the content object?
2151 $revision->insertOn( $dbw );
2152 $this->updateRevisionOn( $dbw, $revision );
2154 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2156 wfProfileOut( __METHOD__
);
2160 * Update the article's restriction field, and leave a log entry.
2161 * This works for protection both existing and non-existing pages.
2163 * @param $limit Array: set of restriction keys
2164 * @param $reason String
2165 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2166 * @param $expiry Array: per restriction type expiration
2167 * @param $user User The user updating the restrictions
2170 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2173 if ( wfReadOnly() ) {
2174 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2177 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2179 $id = $this->mTitle
->getArticleID();
2185 // Take this opportunity to purge out expired restrictions
2186 Title
::purgeExpiredRestrictions();
2188 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2189 # we expect a single selection, but the schema allows otherwise.
2190 $isProtected = false;
2194 $dbw = wfGetDB( DB_MASTER
);
2196 foreach ( $restrictionTypes as $action ) {
2197 if ( !isset( $expiry[$action] ) ) {
2198 $expiry[$action] = $dbw->getInfinity();
2200 if ( !isset( $limit[$action] ) ) {
2201 $limit[$action] = '';
2202 } elseif ( $limit[$action] != '' ) {
2206 # Get current restrictions on $action
2207 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2208 if ( $current != '' ) {
2209 $isProtected = true;
2212 if ( $limit[$action] != $current ) {
2214 } elseif ( $limit[$action] != '' ) {
2215 # Only check expiry change if the action is actually being
2216 # protected, since expiry does nothing on an not-protected
2218 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2224 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2228 # If nothing's changed, do nothing
2230 return Status
::newGood();
2233 if ( !$protect ) { # No protection at all means unprotection
2234 $revCommentMsg = 'unprotectedarticle';
2235 $logAction = 'unprotect';
2236 } elseif ( $isProtected ) {
2237 $revCommentMsg = 'modifiedarticleprotection';
2238 $logAction = 'modify';
2240 $revCommentMsg = 'protectedarticle';
2241 $logAction = 'protect';
2244 $encodedExpiry = array();
2245 $protectDescription = '';
2246 foreach ( $limit as $action => $restrictions ) {
2247 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2248 if ( $restrictions != '' ) {
2249 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2250 if ( $encodedExpiry[$action] != 'infinity' ) {
2251 $protectDescription .= wfMessage(
2253 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2254 $wgContLang->date( $expiry[$action], false, false ) ,
2255 $wgContLang->time( $expiry[$action], false, false )
2256 )->inContentLanguage()->text();
2258 $protectDescription .= wfMessage( 'protect-expiry-indefinite' )
2259 ->inContentLanguage()->text();
2262 $protectDescription .= ') ';
2265 $protectDescription = trim( $protectDescription );
2267 if ( $id ) { # Protection of existing page
2268 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2269 return Status
::newGood();
2272 # Only restrictions with the 'protect' right can cascade...
2273 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2274 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2276 # The schema allows multiple restrictions
2277 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2281 # Update restrictions table
2282 foreach ( $limit as $action => $restrictions ) {
2283 if ( $restrictions != '' ) {
2284 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2285 array( 'pr_page' => $id,
2286 'pr_type' => $action,
2287 'pr_level' => $restrictions,
2288 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2289 'pr_expiry' => $encodedExpiry[$action]
2294 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2295 'pr_type' => $action ), __METHOD__
);
2299 # Prepare a null revision to be added to the history
2300 $editComment = $wgContLang->ucfirst(
2303 $this->mTitle
->getPrefixedText()
2304 )->inContentLanguage()->text()
2307 $editComment .= ": $reason";
2309 if ( $protectDescription ) {
2310 $editComment .= " ($protectDescription)";
2313 // FIXME: Should use 'brackets' message.
2314 $editComment .= ' [' . wfMessage( 'protect-summary-cascade' )
2315 ->inContentLanguage()->text() . ']';
2318 # Insert a null revision
2319 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2320 $nullRevId = $nullRevision->insertOn( $dbw );
2322 $latest = $this->getLatest();
2323 # Update page record
2324 $dbw->update( 'page',
2326 'page_touched' => $dbw->timestamp(),
2327 'page_restrictions' => '',
2328 'page_latest' => $nullRevId
2329 ), array( /* WHERE */
2334 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2335 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2336 } else { # Protection of non-existing page (also known as "title protection")
2337 # Cascade protection is meaningless in this case
2340 if ( $limit['create'] != '' ) {
2341 $dbw->replace( 'protected_titles',
2342 array( array( 'pt_namespace', 'pt_title' ) ),
2344 'pt_namespace' => $this->mTitle
->getNamespace(),
2345 'pt_title' => $this->mTitle
->getDBkey(),
2346 'pt_create_perm' => $limit['create'],
2347 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2348 'pt_expiry' => $encodedExpiry['create'],
2349 'pt_user' => $user->getId(),
2350 'pt_reason' => $reason,
2354 $dbw->delete( 'protected_titles',
2356 'pt_namespace' => $this->mTitle
->getNamespace(),
2357 'pt_title' => $this->mTitle
->getDBkey()
2363 $this->mTitle
->flushRestrictions();
2365 if ( $logAction == 'unprotect' ) {
2366 $logParams = array();
2368 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2371 # Update the protection log
2372 $log = new LogPage( 'protect' );
2373 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2375 return Status
::newGood();
2379 * Take an array of page restrictions and flatten it to a string
2380 * suitable for insertion into the page_restrictions field.
2381 * @param $limit Array
2382 * @throws MWException
2385 protected static function flattenRestrictions( $limit ) {
2386 if ( !is_array( $limit ) ) {
2387 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2393 foreach ( $limit as $action => $restrictions ) {
2394 if ( $restrictions != '' ) {
2395 $bits[] = "$action=$restrictions";
2399 return implode( ':', $bits );
2403 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2404 * backwards compatibility, if you care about error reporting you should use
2405 * doDeleteArticleReal() instead.
2407 * Deletes the article with database consistency, writes logs, purges caches
2409 * @param $reason string delete reason for deletion log
2410 * @param $suppress boolean suppress all revisions and log the deletion in
2411 * the suppression log instead of the deletion log
2412 * @param $id int article ID
2413 * @param $commit boolean defaults to true, triggers transaction end
2414 * @param &$error Array of errors to append to
2415 * @param $user User The deleting user
2416 * @return boolean true if successful
2418 public function doDeleteArticle(
2419 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2421 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2422 return $status->isGood();
2426 * Back-end article deletion
2427 * Deletes the article with database consistency, writes logs, purges caches
2431 * @param $reason string delete reason for deletion log
2432 * @param $suppress boolean suppress all revisions and log the deletion in
2433 * the suppression log instead of the deletion log
2434 * @param $commit boolean defaults to true, triggers transaction end
2435 * @param &$error Array of errors to append to
2436 * @param $user User The deleting user
2437 * @return Status: Status object; if successful, $status->value is the log_id of the
2438 * deletion log entry. If the page couldn't be deleted because it wasn't
2439 * found, $status is a non-fatal 'cannotdelete' error
2441 public function doDeleteArticleReal(
2442 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2444 global $wgUser, $wgContentHandlerUseDB;
2446 wfDebug( __METHOD__
. "\n" );
2448 $status = Status
::newGood();
2450 if ( $this->mTitle
->getDBkey() === '' ) {
2451 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2455 $user = is_null( $user ) ?
$wgUser : $user;
2456 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2457 if ( $status->isOK() ) {
2458 // Hook aborted but didn't set a fatal status
2459 $status->fatal( 'delete-hook-aborted' );
2465 $this->loadPageData( 'forupdate' );
2466 $id = $this->getID();
2468 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2473 // Bitfields to further suppress the content
2476 // This should be 15...
2477 $bitfield |
= Revision
::DELETED_TEXT
;
2478 $bitfield |
= Revision
::DELETED_COMMENT
;
2479 $bitfield |
= Revision
::DELETED_USER
;
2480 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2482 $bitfield = 'rev_deleted';
2485 // we need to remember the old content so we can use it to generate all deletion updates.
2486 $content = $this->getContent( Revision
::RAW
);
2488 $dbw = wfGetDB( DB_MASTER
);
2489 $dbw->begin( __METHOD__
);
2490 // For now, shunt the revision data into the archive table.
2491 // Text is *not* removed from the text table; bulk storage
2492 // is left intact to avoid breaking block-compression or
2493 // immutable storage schemes.
2495 // For backwards compatibility, note that some older archive
2496 // table entries will have ar_text and ar_flags fields still.
2498 // In the future, we may keep revisions and mark them with
2499 // the rev_deleted field, which is reserved for this purpose.
2502 'ar_namespace' => 'page_namespace',
2503 'ar_title' => 'page_title',
2504 'ar_comment' => 'rev_comment',
2505 'ar_user' => 'rev_user',
2506 'ar_user_text' => 'rev_user_text',
2507 'ar_timestamp' => 'rev_timestamp',
2508 'ar_minor_edit' => 'rev_minor_edit',
2509 'ar_rev_id' => 'rev_id',
2510 'ar_parent_id' => 'rev_parent_id',
2511 'ar_text_id' => 'rev_text_id',
2512 'ar_text' => '\'\'', // Be explicit to appease
2513 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2514 'ar_len' => 'rev_len',
2515 'ar_page_id' => 'page_id',
2516 'ar_deleted' => $bitfield,
2517 'ar_sha1' => 'rev_sha1',
2520 if ( $wgContentHandlerUseDB ) {
2521 $row[ 'ar_content_model' ] = 'rev_content_model';
2522 $row[ 'ar_content_format' ] = 'rev_content_format';
2525 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2529 'page_id = rev_page'
2533 # Now that it's safely backed up, delete it
2534 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2535 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2538 $dbw->rollback( __METHOD__
);
2539 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2543 $this->doDeleteUpdates( $id, $content );
2545 # Log the deletion, if the page was suppressed, log it at Oversight instead
2546 $logtype = $suppress ?
'suppress' : 'delete';
2548 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2549 $logEntry->setPerformer( $user );
2550 $logEntry->setTarget( $this->mTitle
);
2551 $logEntry->setComment( $reason );
2552 $logid = $logEntry->insert();
2553 $logEntry->publish( $logid );
2556 $dbw->commit( __METHOD__
);
2559 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2560 $status->value
= $logid;
2565 * Do some database updates after deletion
2567 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2568 * @param $content Content: optional page content to be used when determining the required updates.
2569 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2571 public function doDeleteUpdates( $id, Content
$content = null ) {
2572 # update site status
2573 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2575 # remove secondary indexes, etc
2576 $updates = $this->getDeletionUpdates( $content );
2577 DataUpdate
::runUpdates( $updates );
2580 WikiPage
::onArticleDelete( $this->mTitle
);
2585 # Clear the cached article id so the interface doesn't act like we exist
2586 $this->mTitle
->resetArticleID( 0 );
2590 * Roll back the most recent consecutive set of edits to a page
2591 * from the same user; fails if there are no eligible edits to
2592 * roll back to, e.g. user is the sole contributor. This function
2593 * performs permissions checks on $user, then calls commitRollback()
2594 * to do the dirty work
2596 * @todo: seperate the business/permission stuff out from backend code
2598 * @param $fromP String: Name of the user whose edits to rollback.
2599 * @param $summary String: Custom summary. Set to default summary if empty.
2600 * @param $token String: Rollback token.
2601 * @param $bot Boolean: If true, mark all reverted edits as bot.
2603 * @param $resultDetails Array: contains result-specific array of additional values
2604 * 'alreadyrolled' : 'current' (rev)
2605 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2607 * @param $user User The user performing the rollback
2608 * @return array of errors, each error formatted as
2609 * array(messagekey, param1, param2, ...).
2610 * On success, the array is empty. This array can also be passed to
2611 * OutputPage::showPermissionsErrorPage().
2613 public function doRollback(
2614 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2616 $resultDetails = null;
2619 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2620 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2621 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2623 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2624 $errors[] = array( 'sessionfailure' );
2627 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2628 $errors[] = array( 'actionthrottledtext' );
2631 # If there were errors, bail out now
2632 if ( !empty( $errors ) ) {
2636 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2640 * Backend implementation of doRollback(), please refer there for parameter
2641 * and return value documentation
2643 * NOTE: This function does NOT check ANY permissions, it just commits the
2644 * rollback to the DB. Therefore, you should only call this function direct-
2645 * ly if you want to use custom permissions checks. If you don't, use
2646 * doRollback() instead.
2647 * @param $fromP String: Name of the user whose edits to rollback.
2648 * @param $summary String: Custom summary. Set to default summary if empty.
2649 * @param $bot Boolean: If true, mark all reverted edits as bot.
2651 * @param $resultDetails Array: contains result-specific array of additional values
2652 * @param $guser User The user performing the rollback
2655 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2656 global $wgUseRCPatrol, $wgContLang;
2658 $dbw = wfGetDB( DB_MASTER
);
2660 if ( wfReadOnly() ) {
2661 return array( array( 'readonlytext' ) );
2664 # Get the last editor
2665 $current = $this->getRevision();
2666 if ( is_null( $current ) ) {
2667 # Something wrong... no page?
2668 return array( array( 'notanarticle' ) );
2671 $from = str_replace( '_', ' ', $fromP );
2672 # User name given should match up with the top revision.
2673 # If the user was deleted then $from should be empty.
2674 if ( $from != $current->getUserText() ) {
2675 $resultDetails = array( 'current' => $current );
2676 return array( array( 'alreadyrolled',
2677 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2678 htmlspecialchars( $fromP ),
2679 htmlspecialchars( $current->getUserText() )
2683 # Get the last edit not by this guy...
2684 # Note: these may not be public values
2685 $user = intval( $current->getRawUser() );
2686 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2687 $s = $dbw->selectRow( 'revision',
2688 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2689 array( 'rev_page' => $current->getPage(),
2690 "rev_user != {$user} OR rev_user_text != {$user_text}"
2692 array( 'USE INDEX' => 'page_timestamp',
2693 'ORDER BY' => 'rev_timestamp DESC' )
2695 if ( $s === false ) {
2696 # No one else ever edited this page
2697 return array( array( 'cantrollback' ) );
2698 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2699 # Only admins can see this text
2700 return array( array( 'notvisiblerev' ) );
2704 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2705 # Mark all reverted edits as bot
2709 if ( $wgUseRCPatrol ) {
2710 # Mark all reverted edits as patrolled
2711 $set['rc_patrolled'] = 1;
2714 if ( count( $set ) ) {
2715 $dbw->update( 'recentchanges', $set,
2717 'rc_cur_id' => $current->getPage(),
2718 'rc_user_text' => $current->getUserText(),
2719 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2724 # Generate the edit summary if necessary
2725 $target = Revision
::newFromId( $s->rev_id
);
2726 if ( empty( $summary ) ) {
2727 if ( $from == '' ) { // no public user name
2728 $summary = wfMessage( 'revertpage-nouser' );
2730 $summary = wfMessage( 'revertpage' );
2734 # Allow the custom summary to use the same args as the default message
2736 $target->getUserText(), $from, $s->rev_id
,
2737 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2738 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2740 if( $summary instanceof Message
) {
2741 $summary = $summary->params( $args )->inContentLanguage()->text();
2743 $summary = wfMsgReplaceArgs( $summary, $args );
2746 # Truncate for whole multibyte characters.
2747 $summary = $wgContLang->truncate( $summary, 255 );
2750 $flags = EDIT_UPDATE
;
2752 if ( $guser->isAllowed( 'minoredit' ) ) {
2753 $flags |
= EDIT_MINOR
;
2756 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2757 $flags |
= EDIT_FORCE_BOT
;
2760 # Actually store the edit
2761 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2763 if ( !$status->isOK() ) {
2764 return $status->getErrorsArray();
2767 if ( !empty( $status->value
['revision'] ) ) {
2768 $revId = $status->value
['revision']->getId();
2773 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2775 $resultDetails = array(
2776 'summary' => $summary,
2777 'current' => $current,
2778 'target' => $target,
2786 * The onArticle*() functions are supposed to be a kind of hooks
2787 * which should be called whenever any of the specified actions
2790 * This is a good place to put code to clear caches, for instance.
2792 * This is called on page move and undelete, as well as edit
2794 * @param $title Title object
2796 public static function onArticleCreate( $title ) {
2797 # Update existence markers on article/talk tabs...
2798 if ( $title->isTalkPage() ) {
2799 $other = $title->getSubjectPage();
2801 $other = $title->getTalkPage();
2804 $other->invalidateCache();
2805 $other->purgeSquid();
2807 $title->touchLinks();
2808 $title->purgeSquid();
2809 $title->deleteTitleProtection();
2813 * Clears caches when article is deleted
2815 * @param $title Title
2817 public static function onArticleDelete( $title ) {
2818 # Update existence markers on article/talk tabs...
2819 if ( $title->isTalkPage() ) {
2820 $other = $title->getSubjectPage();
2822 $other = $title->getTalkPage();
2825 $other->invalidateCache();
2826 $other->purgeSquid();
2828 $title->touchLinks();
2829 $title->purgeSquid();
2832 HTMLFileCache
::clearFileCache( $title );
2835 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2836 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2840 if ( $title->getNamespace() == NS_FILE
) {
2841 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2842 $update->doUpdate();
2846 if ( $title->getNamespace() == NS_USER_TALK
) {
2847 $user = User
::newFromName( $title->getText(), false );
2849 $user->setNewtalk( false );
2854 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2858 * Purge caches on page update etc
2860 * @param $title Title object
2861 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2863 public static function onArticleEdit( $title ) {
2864 // Invalidate caches of articles which include this page
2865 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2868 // Invalidate the caches of all pages which redirect here
2869 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2871 # Purge squid for this page only
2872 $title->purgeSquid();
2874 # Clear file cache for this page only
2875 HTMLFileCache
::clearFileCache( $title );
2881 * Returns a list of hidden categories this page is a member of.
2882 * Uses the page_props and categorylinks tables.
2884 * @return Array of Title objects
2886 public function getHiddenCategories() {
2888 $id = $this->mTitle
->getArticleID();
2894 $dbr = wfGetDB( DB_SLAVE
);
2895 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2897 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2898 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2901 if ( $res !== false ) {
2902 foreach ( $res as $row ) {
2903 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2911 * Return an applicable autosummary if one exists for the given edit.
2912 * @param $oldtext String|null: the previous text of the page.
2913 * @param $newtext String|null: The submitted text of the page.
2914 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2915 * @return string An appropriate autosummary, or an empty string.
2917 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
2919 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2920 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2922 wfDeprecated( __METHOD__
, '1.WD' );
2924 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
2925 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
2926 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
2928 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2932 * Auto-generates a deletion reason
2934 * @param &$hasHistory Boolean: whether the page has a history
2935 * @return mixed String containing deletion reason or empty string, or boolean false
2936 * if no revision occurred
2938 public function getAutoDeleteReason( &$hasHistory ) {
2939 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2943 * Update all the appropriate counts in the category table, given that
2944 * we've added the categories $added and deleted the categories $deleted.
2946 * @param $added array The names of categories that were added
2947 * @param $deleted array The names of categories that were deleted
2949 public function updateCategoryCounts( $added, $deleted ) {
2950 $ns = $this->mTitle
->getNamespace();
2951 $dbw = wfGetDB( DB_MASTER
);
2953 # First make sure the rows exist. If one of the "deleted" ones didn't
2954 # exist, we might legitimately not create it, but it's simpler to just
2955 # create it and then give it a negative value, since the value is bogus
2958 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2959 $insertCats = array_merge( $added, $deleted );
2960 if ( !$insertCats ) {
2961 # Okay, nothing to do
2965 $insertRows = array();
2967 foreach ( $insertCats as $cat ) {
2968 $insertRows[] = array(
2969 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2973 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2975 $addFields = array( 'cat_pages = cat_pages + 1' );
2976 $removeFields = array( 'cat_pages = cat_pages - 1' );
2978 if ( $ns == NS_CATEGORY
) {
2979 $addFields[] = 'cat_subcats = cat_subcats + 1';
2980 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2981 } elseif ( $ns == NS_FILE
) {
2982 $addFields[] = 'cat_files = cat_files + 1';
2983 $removeFields[] = 'cat_files = cat_files - 1';
2990 array( 'cat_title' => $added ),
2999 array( 'cat_title' => $deleted ),
3006 * Updates cascading protections
3008 * @param $parserOutput ParserOutput object for the current version
3010 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3011 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3015 // templatelinks table may have become out of sync,
3016 // especially if using variable-based transclusions.
3017 // For paranoia, check if things have changed and if
3018 // so apply updates to the database. This will ensure
3019 // that cascaded protections apply as soon as the changes
3022 # Get templates from templatelinks
3023 $id = $this->mTitle
->getArticleID();
3025 $tlTemplates = array();
3027 $dbr = wfGetDB( DB_SLAVE
);
3028 $res = $dbr->select( array( 'templatelinks' ),
3029 array( 'tl_namespace', 'tl_title' ),
3030 array( 'tl_from' => $id ),
3034 foreach ( $res as $row ) {
3035 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3038 # Get templates from parser output.
3039 $poTemplates = array();
3040 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3041 foreach ( $templates as $dbk => $id ) {
3042 $poTemplates["$ns:$dbk"] = true;
3047 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3049 if ( count( $templates_diff ) > 0 ) {
3050 # Whee, link updates time.
3051 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3052 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3058 * Return a list of templates used by this article.
3059 * Uses the templatelinks table
3061 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3062 * @return Array of Title objects
3064 public function getUsedTemplates() {
3065 return $this->mTitle
->getTemplateLinksFrom();
3069 * Perform article updates on a special page creation.
3071 * @param $rev Revision object
3073 * @todo This is a shitty interface function. Kill it and replace the
3074 * other shitty functions like doEditUpdates and such so it's not needed
3076 * @deprecated since 1.18, use doEditUpdates()
3078 public function createUpdates( $rev ) {
3079 wfDeprecated( __METHOD__
, '1.18' );
3081 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3085 * This function is called right before saving the wikitext,
3086 * so we can do things like signatures and links-in-context.
3088 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3089 * @param $text String article contents
3090 * @param $user User object: user doing the edit
3091 * @param $popts ParserOptions object: parser options, default options for
3092 * the user loaded if null given
3093 * @return string article contents with altered wikitext markup (signatures
3094 * converted, {{subst:}}, templates, etc.)
3096 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3097 global $wgParser, $wgUser;
3099 wfDeprecated( __METHOD__
, '1.19' );
3101 $user = is_null( $user ) ?
$wgUser : $user;
3103 if ( $popts === null ) {
3104 $popts = ParserOptions
::newFromUser( $user );
3107 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3111 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3113 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3116 public function isBigDeletion() {
3117 wfDeprecated( __METHOD__
, '1.19' );
3118 return $this->mTitle
->isBigDeletion();
3122 * Get the approximate revision count of this page.
3124 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3127 public function estimateRevisionCount() {
3128 wfDeprecated( __METHOD__
, '1.19' );
3129 return $this->mTitle
->estimateRevisionCount();
3133 * Update the article's restriction field, and leave a log entry.
3135 * @deprecated since 1.19
3136 * @param $limit Array: set of restriction keys
3137 * @param $reason String
3138 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3139 * @param $expiry Array: per restriction type expiration
3140 * @param $user User The user updating the restrictions
3141 * @return bool true on success
3143 public function updateRestrictions(
3144 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3148 $user = is_null( $user ) ?
$wgUser : $user;
3150 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3154 * @deprecated since 1.18
3156 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3157 wfDeprecated( __METHOD__
, '1.18' );
3159 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3163 * @deprecated since 1.18
3165 public function viewUpdates() {
3166 wfDeprecated( __METHOD__
, '1.18' );
3168 return $this->doViewUpdates( $wgUser );
3172 * @deprecated since 1.18
3176 public function useParserCache( $oldid ) {
3177 wfDeprecated( __METHOD__
, '1.18' );
3179 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3183 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3184 * about this page from secondary data stores such as links tables.
3186 * @param Content|null $content optional Content object for determining the necessary updates
3187 * @return Array an array of DataUpdates objects
3189 public function getDeletionUpdates( Content
$content = null ) {
3191 // load content object, which may be used to determine the necessary updates
3192 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3193 $content = $this->getContent( Revision
::RAW
);
3199 $updates = $content->getDeletionUpdates( $this );
3202 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3208 class PoolWorkArticleView
extends PoolCounterWork
{
3226 * @var ParserOptions
3228 private $parserOptions;
3233 private $content = null;
3236 * @var ParserOutput|bool
3238 private $parserOutput = false;
3243 private $isDirty = false;
3248 private $error = false;
3254 * @param $revid Integer: ID of the revision being parsed
3255 * @param $useParserCache Boolean: whether to use the parser cache
3256 * @param $parserOptions parserOptions to use for the parse operation
3257 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3259 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3260 if ( is_string($content) ) { #BC: old style call
3261 $modelId = $page->getRevision()->getContentModel();
3262 $format = $page->getRevision()->getContentFormat();
3263 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3266 $this->page
= $page;
3267 $this->revid
= $revid;
3268 $this->cacheable
= $useParserCache;
3269 $this->parserOptions
= $parserOptions;
3270 $this->content
= $content;
3271 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3272 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3276 * Get the ParserOutput from this object, or false in case of failure
3278 * @return ParserOutput
3280 public function getParserOutput() {
3281 return $this->parserOutput
;
3285 * Get whether the ParserOutput is a dirty one (i.e. expired)
3289 public function getIsDirty() {
3290 return $this->isDirty
;
3294 * Get a Status object in case of error or false otherwise
3296 * @return Status|bool
3298 public function getError() {
3299 return $this->error
;
3306 global $wgUseFileCache;
3308 // @todo: several of the methods called on $this->page are not declared in Page, but present
3309 // in WikiPage and delegated by Article.
3311 $isCurrent = $this->revid
=== $this->page
->getLatest();
3313 if ( $this->content
!== null ) {
3314 $content = $this->content
;
3315 } elseif ( $isCurrent ) {
3316 #XXX: why use RAW audience here, and PUBLIC (default) below?
3317 $content = $this->page
->getContent( Revision
::RAW
);
3319 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3320 if ( $rev === null ) {
3324 #XXX: why use PUBLIC audience here (default), and RAW above?
3325 $content = $rev->getContent();
3328 $time = - microtime( true );
3329 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3330 $time +
= microtime( true );
3334 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3335 $this->page
->getTitle()->getPrefixedDBkey() ) );
3338 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3339 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3342 // Make sure file cache is not used on uncacheable content.
3343 // Output that has magic words in it can still use the parser cache
3344 // (if enabled), though it will generally expire sooner.
3345 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3346 $wgUseFileCache = false;
3350 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3359 function getCachedWork() {
3360 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3362 if ( $this->parserOutput
=== false ) {
3363 wfDebug( __METHOD__
. ": parser cache miss\n" );
3366 wfDebug( __METHOD__
. ": parser cache hit\n" );
3374 function fallback() {
3375 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3377 if ( $this->parserOutput
=== false ) {
3378 wfDebugLog( 'dirty', "dirty missing\n" );
3379 wfDebug( __METHOD__
. ": no dirty cache\n" );
3382 wfDebug( __METHOD__
. ": sending dirty output\n" );
3383 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3384 $this->isDirty
= true;
3390 * @param $status Status
3393 function error( $status ) {
3394 $this->error
= $status;