3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
26 abstract class Page
{}
29 * Class representing a MediaWiki article and history.
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
34 * @internal documentation reviewed 15 Mar 2010
36 class WikiPage
extends Page
{
37 // doDeleteArticleReal() return values. Values less than zero indicate fatal errors,
38 // values greater than zero indicate that there were problems not resulting in page
42 * Delete operation aborted by hook
44 const DELETE_HOOK_ABORTED
= -1;
49 const DELETE_SUCCESS
= 0;
54 const DELETE_NO_PAGE
= 1;
57 * No revisions found to delete
59 const DELETE_NO_REVISIONS
= 2;
61 // Constants for $mDataLoadedFrom and related
64 * Data has not been loaded yet (or the object was cleared)
66 const DATA_NOT_LOADED
= 0;
69 * Data has been loaded from a slave database
71 const DATA_FROM_SLAVE
= 1;
74 * Data has been loaded from the master database
76 const DATA_FROM_MASTER
= 2;
79 * Data has been loaded from the master database using FOR UPDATE
81 const DATA_FOR_UPDATE
= 3;
86 public $mTitle = null;
91 public $mDataLoaded = false; // !< Boolean
92 public $mIsRedirect = false; // !< Boolean
93 public $mLatest = false; // !< Integer (false means "not loaded")
94 public $mPreparedEdit = false; // !< Array
98 * @var int; one of the DATA_* constants
100 protected $mDataLoadedFrom = self
::DATA_NOT_LOADED
;
105 protected $mRedirectTarget = null;
110 protected $mLastRevision = null;
113 * @var string; timestamp of the current revision or empty string if not loaded
115 protected $mTimestamp = '';
120 protected $mTouched = '19700101000000';
125 protected $mCounter = null;
128 * Constructor and clear the article
129 * @param $title Title Reference to a Title object.
131 public function __construct( Title
$title ) {
132 $this->mTitle
= $title;
136 * Create a WikiPage object of the appropriate class for the given title.
138 * @param $title Title
139 * @return WikiPage object of the appropriate type
141 public static function factory( Title
$title ) {
142 $ns = $title->getNamespace();
144 if ( $ns == NS_MEDIA
) {
145 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
146 } elseif ( $ns < 0 ) {
147 throw new MWException( "Invalid or virtual namespace $ns given." );
152 $page = new WikiFilePage( $title );
155 $page = new WikiCategoryPage( $title );
158 $page = new WikiPage( $title );
165 * Constructor from a page id
167 * @param $id Int article ID to load
168 * @param $from string|int one of the following values:
169 * - "fromdb" or self::DATA_FROM_SLAVE to select from a slave database
170 * - "fromdbmaster" or self::DATA_FROM_MASTER to select from the master database
172 * @return WikiPage|null
174 public static function newFromID( $id, $from = 'fromdb' ) {
175 $from = self
::convertSelectType( $from );
176 $db = wfGetDB( $from === self
::DATA_FROM_MASTER ? DB_MASTER
: DB_SLAVE
);
177 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
181 return self
::newFromRow( $row, $from );
185 * Constructor from a database row
188 * @param $row object: database row containing at least fields returned
190 * @param $from string|int: source of $data:
191 * - "fromdb" or self::DATA_FROM_SLAVE: from a slave DB
192 * - "fromdbmaster" or self::DATA_FROM_MASTER: from the master DB
193 * - "forupdate" or self::DATA_FOR_UPDATE: from the master DB using SELECT FOR UPDATE
196 public static function newFromRow( $row, $from = 'fromdb' ) {
197 $page = self
::factory( Title
::newFromRow( $row ) );
198 $page->loadFromRow( $row, $from );
203 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to DATA_* constants.
205 * @param $type object|string|int
208 private static function convertSelectType( $type ) {
211 return self
::DATA_FROM_SLAVE
;
213 return self
::DATA_FROM_MASTER
;
215 return self
::DATA_FOR_UPDATE
;
217 // It may already be an integer or whatever else
223 * Returns overrides for action handlers.
224 * Classes listed here will be used instead of the default one when
225 * (and only when) $wgActions[$action] === true. This allows subclasses
226 * to override the default behavior.
228 * @todo: move this UI stuff somewhere else
232 public function getActionOverrides() {
233 $content_handler = $this->getContentHandler();
234 return $content_handler->getActionOverrides();
238 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
240 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
242 * @return ContentHandler
246 public function getContentHandler() {
247 return ContentHandler
::getForModelID( $this->getContentModel() );
251 * Get the title object of the article
252 * @return Title object of this page
254 public function getTitle() {
255 return $this->mTitle
;
261 public function clear() {
262 $this->mDataLoaded
= false;
263 $this->mDataLoadedFrom
= self
::DATA_NOT_LOADED
;
265 $this->mCounter
= null;
266 $this->mRedirectTarget
= null; # Title object if set
267 $this->mLastRevision
= null; # Latest revision
268 $this->mTouched
= '19700101000000';
269 $this->mTimestamp
= '';
270 $this->mIsRedirect
= false;
271 $this->mLatest
= false;
272 $this->mPreparedEdit
= false;
276 * Return the list of revision fields that should be selected to create
281 public static function selectFields() {
282 global $wgContentHandlerUseDB;
298 if ( $wgContentHandlerUseDB ) {
299 $fields[] = 'page_content_model';
306 * Fetch a page record with the given conditions
307 * @param $dbr DatabaseBase object
308 * @param $conditions Array
309 * @param $options Array
310 * @return mixed Database result resource, or false on failure
312 protected function pageData( $dbr, $conditions, $options = array() ) {
313 $fields = self
::selectFields();
315 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
317 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
319 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
325 * Fetch a page record matching the Title object's namespace and title
326 * using a sanitized title string
328 * @param $dbr DatabaseBase object
329 * @param $title Title object
330 * @param $options Array
331 * @return mixed Database result resource, or false on failure
333 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
334 return $this->pageData( $dbr, array(
335 'page_namespace' => $title->getNamespace(),
336 'page_title' => $title->getDBkey() ), $options );
340 * Fetch a page record matching the requested ID
342 * @param $dbr DatabaseBase
344 * @param $options Array
345 * @return mixed Database result resource, or false on failure
347 public function pageDataFromId( $dbr, $id, $options = array() ) {
348 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
352 * Set the general counter, title etc data loaded from
355 * @param $from object|string|int One of the following:
356 * - A DB query result object
357 * - "fromdb" or self::DATA_FROM_SLAVE to get from a slave DB
358 * - "fromdbmaster" or self::DATA_FROM_MASTER to get from the master DB
359 * - "forupdate" or self::DATA_FOR_UPDATE to get from the master DB using SELECT FOR UPDATE
363 public function loadPageData( $from = 'fromdb' ) {
364 $from = self
::convertSelectType( $from );
365 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
366 // We already have the data from the correct location, no need to load it twice.
370 if ( $from === self
::DATA_FOR_UPDATE
) {
371 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
372 } elseif ( $from === self
::DATA_FROM_MASTER
) {
373 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
374 } elseif ( $from === self
::DATA_FROM_SLAVE
) {
375 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
376 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
377 # Note that DB also stores the master position in the session and checks it.
378 $touched = $this->getCachedLastEditTime();
379 if ( $touched ) { // key set
380 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
381 $from = self
::DATA_FROM_MASTER
;
382 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
386 // No idea from where the caller got this data, assume slave database.
388 $from = self
::DATA_FROM_SLAVE
;
391 $this->loadFromRow( $data, $from );
395 * Load the object from a database row
398 * @param $data object: database row containing at least fields returned
400 * @param $from string|int One of the following:
401 * - "fromdb" or self::DATA_FROM_SLAVE if the data comes from a slave DB
402 * - "fromdbmaster" or self::DATA_FROM_MASTER if the data comes from the master DB
403 * - "forupdate" or self::DATA_FOR_UPDATE if the data comes from from
404 * the master DB using SELECT FOR UPDATE
406 public function loadFromRow( $data, $from ) {
407 $lc = LinkCache
::singleton();
410 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
412 $this->mTitle
->loadFromRow( $data );
414 # Old-fashioned restrictions
415 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
417 $this->mCounter
= intval( $data->page_counter
);
418 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
419 $this->mIsRedirect
= intval( $data->page_is_redirect
);
420 $this->mLatest
= intval( $data->page_latest
);
422 $lc->addBadLinkObj( $this->mTitle
);
424 $this->mTitle
->loadFromRow( false );
427 $this->mDataLoaded
= true;
428 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
432 * @return int Page ID
434 public function getId() {
435 return $this->mTitle
->getArticleID();
439 * @return bool Whether or not the page exists in the database
441 public function exists() {
442 return $this->mTitle
->exists();
446 * Check if this page is something we're going to be showing
447 * some sort of sensible content for. If we return false, page
448 * views (plain action=view) will return an HTTP 404 response,
449 * so spiders and robots can know they're following a bad link.
453 public function hasViewableContent() {
454 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
458 * @return int The view count for the page
460 public function getCount() {
461 if ( !$this->mDataLoaded
) {
462 $this->loadPageData();
465 return $this->mCounter
;
469 * Tests if the article content represents a redirect
473 public function isRedirect( ) {
474 $content = $this->getContent();
475 if ( !$content ) return false;
477 return $content->isRedirect();
481 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
483 * Will use the revisions actual content model if the page exists,
484 * and the page's default if the page doesn't exist yet.
490 public function getContentModel() {
491 if ( $this->exists() ) {
492 # look at the revision's actual content model
493 $rev = $this->getRevision();
495 if ( $rev !== null ) {
496 return $rev->getContentModel();
498 wfWarn( "Page exists but has no revision!" );
502 # use the default model for this page
503 return $this->mTitle
->getContentModel();
507 * Loads page_touched and returns a value indicating if it should be used
508 * @return boolean true if not a redirect
510 public function checkTouched() {
511 if ( !$this->mDataLoaded
) {
512 $this->loadPageData();
514 return !$this->mIsRedirect
;
518 * Get the page_touched field
519 * @return string containing GMT timestamp
521 public function getTouched() {
522 if ( !$this->mDataLoaded
) {
523 $this->loadPageData();
525 return $this->mTouched
;
529 * Get the page_latest field
530 * @return integer rev_id of current revision
532 public function getLatest() {
533 if ( !$this->mDataLoaded
) {
534 $this->loadPageData();
536 return (int)$this->mLatest
;
540 * Get the Revision object of the oldest revision
541 * @return Revision|null
543 public function getOldestRevision() {
544 wfProfileIn( __METHOD__
);
546 // Try using the slave database first, then try the master
548 $db = wfGetDB( DB_SLAVE
);
549 $revSelectFields = Revision
::selectFields();
551 while ( $continue ) {
552 $row = $db->selectRow(
553 array( 'page', 'revision' ),
556 'page_namespace' => $this->mTitle
->getNamespace(),
557 'page_title' => $this->mTitle
->getDBkey(),
562 'ORDER BY' => 'rev_timestamp ASC'
569 $db = wfGetDB( DB_MASTER
);
574 wfProfileOut( __METHOD__
);
575 return $row ? Revision
::newFromRow( $row ) : null;
579 * Loads everything except the text
580 * This isn't necessary for all uses, so it's only done if needed.
582 protected function loadLastEdit() {
583 if ( $this->mLastRevision
!== null ) {
584 return; // already loaded
587 $latest = $this->getLatest();
589 return; // page doesn't exist or is missing page_latest info
592 $revision = Revision
::newFromPageId( $this->getId(), $latest );
593 if ( $revision ) { // sanity
594 $this->setLastEdit( $revision );
599 * Set the latest revision
601 protected function setLastEdit( Revision
$revision ) {
602 $this->mLastRevision
= $revision;
603 $this->mTimestamp
= $revision->getTimestamp();
607 * Get the latest revision
608 * @return Revision|null
610 public function getRevision() {
611 $this->loadLastEdit();
612 if ( $this->mLastRevision
) {
613 return $this->mLastRevision
;
619 * Get the content of the current revision. No side-effects...
621 * @param $audience Integer: one of:
622 * Revision::FOR_PUBLIC to be displayed to all users
623 * Revision::FOR_THIS_USER to be displayed to $wgUser
624 * Revision::RAW get the text regardless of permissions
625 * @return Content|null The content of the current revision
629 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
630 $this->loadLastEdit();
631 if ( $this->mLastRevision
) {
632 return $this->mLastRevision
->getContent( $audience );
638 * Get the text of the current revision. No side-effects...
640 * @param $audience Integer: one of:
641 * Revision::FOR_PUBLIC to be displayed to all users
642 * Revision::FOR_THIS_USER to be displayed to $wgUser
643 * Revision::RAW get the text regardless of permissions
644 * @return String|false The text of the current revision
645 * @deprecated as of 1.WD, getContent() should be used instead.
647 public function getText( $audience = Revision
::FOR_PUBLIC
) { #@todo: deprecated, replace usage!
648 wfDeprecated( __METHOD__
, '1.WD' );
650 $this->loadLastEdit();
651 if ( $this->mLastRevision
) {
652 return $this->mLastRevision
->getText( $audience );
658 * Get the text of the current revision. No side-effects...
660 * @return String|bool The text of the current revision. False on failure
661 * @deprecated as of 1.WD, getContent() should be used instead.
663 public function getRawText() {
664 wfDeprecated( __METHOD__
, '1.WD' );
666 return $this->getText( Revision
::RAW
);
670 * @return string MW timestamp of last article revision
672 public function getTimestamp() {
673 // Check if the field has been filled by WikiPage::setTimestamp()
674 if ( !$this->mTimestamp
) {
675 $this->loadLastEdit();
678 return wfTimestamp( TS_MW
, $this->mTimestamp
);
682 * Set the page timestamp (use only to avoid DB queries)
683 * @param $ts string MW timestamp of last article revision
686 public function setTimestamp( $ts ) {
687 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
691 * @param $audience Integer: one of:
692 * Revision::FOR_PUBLIC to be displayed to all users
693 * Revision::FOR_THIS_USER to be displayed to $wgUser
694 * Revision::RAW get the text regardless of permissions
695 * @return int user ID for the user that made the last article revision
697 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
698 $this->loadLastEdit();
699 if ( $this->mLastRevision
) {
700 return $this->mLastRevision
->getUser( $audience );
707 * Get the User object of the user who created the page
708 * @param $audience Integer: one of:
709 * Revision::FOR_PUBLIC to be displayed to all users
710 * Revision::FOR_THIS_USER to be displayed to $wgUser
711 * Revision::RAW get the text regardless of permissions
714 public function getCreator( $audience = Revision
::FOR_PUBLIC
) {
715 $revision = $this->getOldestRevision();
717 $userName = $revision->getUserText( $audience );
718 return User
::newFromName( $userName, false );
725 * @param $audience Integer: one of:
726 * Revision::FOR_PUBLIC to be displayed to all users
727 * Revision::FOR_THIS_USER to be displayed to $wgUser
728 * Revision::RAW get the text regardless of permissions
729 * @return string username of the user that made the last article revision
731 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
732 $this->loadLastEdit();
733 if ( $this->mLastRevision
) {
734 return $this->mLastRevision
->getUserText( $audience );
741 * @param $audience Integer: one of:
742 * Revision::FOR_PUBLIC to be displayed to all users
743 * Revision::FOR_THIS_USER to be displayed to $wgUser
744 * Revision::RAW get the text regardless of permissions
745 * @return string Comment stored for the last article revision
747 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
748 $this->loadLastEdit();
749 if ( $this->mLastRevision
) {
750 return $this->mLastRevision
->getComment( $audience );
757 * Returns true if last revision was marked as "minor edit"
759 * @return boolean Minor edit indicator for the last article revision.
761 public function getMinorEdit() {
762 $this->loadLastEdit();
763 if ( $this->mLastRevision
) {
764 return $this->mLastRevision
->isMinor();
771 * Get the cached timestamp for the last time the page changed.
772 * This is only used to help handle slave lag by comparing to page_touched.
773 * @return string MW timestamp
775 protected function getCachedLastEditTime() {
777 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
778 return $wgMemc->get( $key );
782 * Set the cached timestamp for the last time the page changed.
783 * This is only used to help handle slave lag by comparing to page_touched.
784 * @param $timestamp string
787 public function setCachedLastEditTime( $timestamp ) {
789 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
790 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
794 * Determine whether a page would be suitable for being counted as an
795 * article in the site_stats table based on the title & its content
797 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
798 * if false, the current database state will be used
801 public function isCountable( $editInfo = false ) {
802 global $wgArticleCountMethod;
804 if ( !$this->mTitle
->isContentPage() ) {
809 $content = $editInfo->pstContent
;
811 $content = $this->getContent();
814 if ( !$content ||
$content->isRedirect( ) ) {
820 if ( $wgArticleCountMethod === 'link' ) {
821 # nasty special case to avoid re-parsing to detect links
824 // ParserOutput::getLinks() is a 2D array of page links, so
825 // to be really correct we would need to recurse in the array
826 // but the main array should only have items in it if there are
828 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
830 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
831 array( 'pl_from' => $this->getId() ), __METHOD__
);
835 return $content->isCountable( $hasLinks );
839 * If this page is a redirect, get its target
841 * The target will be fetched from the redirect table if possible.
842 * If this page doesn't have an entry there, call insertRedirect()
843 * @return Title|mixed object, or null if this page is not a redirect
845 public function getRedirectTarget() {
846 if ( !$this->mTitle
->isRedirect() ) {
850 if ( $this->mRedirectTarget
!== null ) {
851 return $this->mRedirectTarget
;
854 # Query the redirect table
855 $dbr = wfGetDB( DB_SLAVE
);
856 $row = $dbr->selectRow( 'redirect',
857 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
858 array( 'rd_from' => $this->getId() ),
862 // rd_fragment and rd_interwiki were added later, populate them if empty
863 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
864 return $this->mRedirectTarget
= Title
::makeTitle(
865 $row->rd_namespace
, $row->rd_title
,
866 $row->rd_fragment
, $row->rd_interwiki
);
869 # This page doesn't have an entry in the redirect table
870 return $this->mRedirectTarget
= $this->insertRedirect();
874 * Insert an entry for this page into the redirect table.
876 * Don't call this function directly unless you know what you're doing.
877 * @return Title object or null if not a redirect
879 public function insertRedirect() {
880 // recurse through to only get the final target
881 $content = $this->getContent();
882 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
886 $this->insertRedirectEntry( $retval );
891 * Insert or update the redirect table entry for this page to indicate
892 * it redirects to $rt .
893 * @param $rt Title redirect target
895 public function insertRedirectEntry( $rt ) {
896 $dbw = wfGetDB( DB_MASTER
);
897 $dbw->replace( 'redirect', array( 'rd_from' ),
899 'rd_from' => $this->getId(),
900 'rd_namespace' => $rt->getNamespace(),
901 'rd_title' => $rt->getDBkey(),
902 'rd_fragment' => $rt->getFragment(),
903 'rd_interwiki' => $rt->getInterwiki(),
910 * Get the Title object or URL this page redirects to
912 * @return mixed false, Title of in-wiki target, or string with URL
914 public function followRedirect() {
915 return $this->getRedirectURL( $this->getRedirectTarget() );
919 * Get the Title object or URL to use for a redirect. We use Title
920 * objects for same-wiki, non-special redirects and URLs for everything
922 * @param $rt Title Redirect target
923 * @return mixed false, Title object of local target, or string with URL
925 public function getRedirectURL( $rt ) {
930 if ( $rt->isExternal() ) {
931 if ( $rt->isLocal() ) {
932 // Offsite wikis need an HTTP redirect.
934 // This can be hard to reverse and may produce loops,
935 // so they may be disabled in the site configuration.
936 $source = $this->mTitle
->getFullURL( 'redirect=no' );
937 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
939 // External pages pages without "local" bit set are not valid
945 if ( $rt->isSpecialPage() ) {
946 // Gotta handle redirects to special pages differently:
947 // Fill the HTTP response "Location" header and ignore
948 // the rest of the page we're on.
950 // Some pages are not valid targets
951 if ( $rt->isValidRedirectTarget() ) {
952 return $rt->getFullURL();
962 * Get a list of users who have edited this article, not including the user who made
963 * the most recent revision, which you can get from $article->getUser() if you want it
964 * @return UserArrayFromResult
966 public function getContributors() {
967 # @todo FIXME: This is expensive; cache this info somewhere.
969 $dbr = wfGetDB( DB_SLAVE
);
971 if ( $dbr->implicitGroupby() ) {
972 $realNameField = 'user_real_name';
974 $realNameField = 'MIN(user_real_name) AS user_real_name';
977 $tables = array( 'revision', 'user' );
980 'rev_user as user_id',
981 'rev_user_text AS user_name',
983 'MAX(rev_timestamp) AS timestamp',
986 $conds = array( 'rev_page' => $this->getId() );
988 // The user who made the top revision gets credited as "this page was last edited by
989 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
990 $user = $this->getUser();
992 $conds[] = "rev_user != $user";
994 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
997 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1000 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1004 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1005 'ORDER BY' => 'timestamp DESC',
1008 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1009 return new UserArrayFromResult( $res );
1013 * Get the last N authors
1014 * @param $num Integer: number of revisions to get
1015 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1016 * @return array Array of authors, duplicates not removed
1018 public function getLastNAuthors( $num, $revLatest = 0 ) {
1019 wfProfileIn( __METHOD__
);
1020 // First try the slave
1021 // If that doesn't have the latest revision, try the master
1023 $db = wfGetDB( DB_SLAVE
);
1026 $res = $db->select( array( 'page', 'revision' ),
1027 array( 'rev_id', 'rev_user_text' ),
1029 'page_namespace' => $this->mTitle
->getNamespace(),
1030 'page_title' => $this->mTitle
->getDBkey(),
1031 'rev_page = page_id'
1034 'ORDER BY' => 'rev_timestamp DESC',
1040 wfProfileOut( __METHOD__
);
1044 $row = $db->fetchObject( $res );
1046 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1047 $db = wfGetDB( DB_MASTER
);
1052 } while ( $continue );
1054 $authors = array( $row->rev_user_text
);
1056 foreach ( $res as $row ) {
1057 $authors[] = $row->rev_user_text
;
1060 wfProfileOut( __METHOD__
);
1065 * Should the parser cache be used?
1067 * @param $parserOptions ParserOptions to check
1071 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1072 global $wgEnableParserCache;
1074 return $wgEnableParserCache
1075 && $parserOptions->getStubThreshold() == 0
1076 && $this->mTitle
->exists()
1077 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1078 && $this->getContentHandler()->isParserCacheSupported();
1082 * Get a ParserOutput for the given ParserOptions and revision ID.
1083 * The parser cache will be used if possible.
1086 * @param $parserOptions ParserOptions to use for the parse operation
1087 * @param $oldid Revision ID to get the text from, passing null or 0 will
1088 * get the current revision (default value)
1090 * @return ParserOutput or false if the revision was not found
1092 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1093 wfProfileIn( __METHOD__
);
1095 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1096 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1097 if ( $parserOptions->getStubThreshold() ) {
1098 wfIncrStats( 'pcache_miss_stub' );
1101 if ( $useParserCache ) {
1102 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1103 if ( $parserOutput !== false ) {
1104 wfProfileOut( __METHOD__
);
1105 return $parserOutput;
1109 if ( $oldid === null ||
$oldid === 0 ) {
1110 $oldid = $this->getLatest();
1113 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1116 wfProfileOut( __METHOD__
);
1118 return $pool->getParserOutput();
1122 * Do standard deferred updates after page view
1123 * @param $user User The relevant user
1125 public function doViewUpdates( User
$user ) {
1126 global $wgDisableCounters;
1127 if ( wfReadOnly() ) {
1131 # Don't update page view counters on views from bot users (bug 14044)
1132 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1133 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1134 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1137 # Update newtalk / watchlist notification status
1138 $user->clearNotification( $this->mTitle
);
1142 * Perform the actions of a page purging
1145 public function doPurge() {
1148 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1152 // Invalidate the cache
1153 $this->mTitle
->invalidateCache();
1156 if ( $wgUseSquid ) {
1157 // Commit the transaction before the purge is sent
1158 $dbw = wfGetDB( DB_MASTER
);
1159 $dbw->commit( __METHOD__
);
1162 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1163 $update->doUpdate();
1166 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1167 //@todo: move this logic to MessageCache
1169 if ( $this->mTitle
->exists() ) {
1170 // NOTE: use transclusion text for messages.
1171 // This is consistent with MessageCache::getMsgFromNamespace()
1173 $content = $this->getContent();
1174 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1176 if ( $text === null ) $text = false;
1181 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1187 * Insert a new empty page record for this article.
1188 * This *must* be followed up by creating a revision
1189 * and running $this->updateRevisionOn( ... );
1190 * or else the record will be left in a funky state.
1191 * Best if all done inside a transaction.
1193 * @param $dbw DatabaseBase
1194 * @return int The newly created page_id key, or false if the title already existed
1196 public function insertOn( $dbw ) {
1197 wfProfileIn( __METHOD__
);
1199 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1200 $dbw->insert( 'page', array(
1201 'page_id' => $page_id,
1202 'page_namespace' => $this->mTitle
->getNamespace(),
1203 'page_title' => $this->mTitle
->getDBkey(),
1204 'page_counter' => 0,
1205 'page_restrictions' => '',
1206 'page_is_redirect' => 0, # Will set this shortly...
1208 'page_random' => wfRandom(),
1209 'page_touched' => $dbw->timestamp(),
1210 'page_latest' => 0, # Fill this in shortly...
1211 'page_len' => 0, # Fill this in shortly...
1212 ), __METHOD__
, 'IGNORE' );
1214 $affected = $dbw->affectedRows();
1217 $newid = $dbw->insertId();
1218 $this->mTitle
->resetArticleID( $newid );
1220 wfProfileOut( __METHOD__
);
1222 return $affected ?
$newid : false;
1226 * Update the page record to point to a newly saved revision.
1228 * @param $dbw DatabaseBase: object
1229 * @param $revision Revision: For ID number, and text used to set
1230 * length and redirect status fields
1231 * @param $lastRevision Integer: if given, will not overwrite the page field
1232 * when different from the currently set value.
1233 * Giving 0 indicates the new page flag should be set
1235 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1236 * removing rows in redirect table.
1237 * @return bool true on success, false on failure
1240 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1241 global $wgContentHandlerUseDB;
1243 wfProfileIn( __METHOD__
);
1245 $content = $revision->getContent();
1246 $len = $content->getSize();
1247 $rt = $content->getUltimateRedirectTarget();
1249 $conditions = array( 'page_id' => $this->getId() );
1251 if ( !is_null( $lastRevision ) ) {
1252 # An extra check against threads stepping on each other
1253 $conditions['page_latest'] = $lastRevision;
1256 $now = wfTimestampNow();
1257 $row = array( /* SET */
1258 'page_latest' => $revision->getId(),
1259 'page_touched' => $dbw->timestamp( $now ),
1260 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1261 'page_is_redirect' => $rt !== null ?
1 : 0,
1265 if ( $wgContentHandlerUseDB ) {
1266 $row[ 'page_content_model' ] = $revision->getContentModel();
1269 $dbw->update( 'page',
1274 $result = $dbw->affectedRows() != 0;
1276 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1277 $this->setLastEdit( $revision );
1278 $this->setCachedLastEditTime( $now );
1279 $this->mLatest
= $revision->getId();
1280 $this->mIsRedirect
= (bool)$rt;
1281 # Update the LinkCache.
1282 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
, $revision->getContentModel() );
1285 wfProfileOut( __METHOD__
);
1290 * Add row to the redirect table if this is a redirect, remove otherwise.
1292 * @param $dbw DatabaseBase
1293 * @param $redirectTitle Title object pointing to the redirect target,
1294 * or NULL if this is not a redirect
1295 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1296 * removing rows in redirect table.
1297 * @return bool true on success, false on failure
1300 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1301 // Always update redirects (target link might have changed)
1302 // Update/Insert if we don't know if the last revision was a redirect or not
1303 // Delete if changing from redirect to non-redirect
1304 $isRedirect = !is_null( $redirectTitle );
1306 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1310 wfProfileIn( __METHOD__
);
1311 if ( $isRedirect ) {
1312 $this->insertRedirectEntry( $redirectTitle );
1314 // This is not a redirect, remove row from redirect table
1315 $where = array( 'rd_from' => $this->getId() );
1316 $dbw->delete( 'redirect', $where, __METHOD__
);
1319 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1320 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1322 wfProfileOut( __METHOD__
);
1324 return ( $dbw->affectedRows() != 0 );
1328 * If the given revision is newer than the currently set page_latest,
1329 * update the page record. Otherwise, do nothing.
1331 * @param $dbw DatabaseBase object
1332 * @param $revision Revision object
1335 public function updateIfNewerOn( $dbw, $revision ) {
1336 wfProfileIn( __METHOD__
);
1338 $row = $dbw->selectRow(
1339 array( 'revision', 'page' ),
1340 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1342 'page_id' => $this->getId(),
1343 'page_latest=rev_id' ),
1347 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1348 wfProfileOut( __METHOD__
);
1351 $prev = $row->rev_id
;
1352 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1354 # No or missing previous revision; mark the page as new
1356 $lastRevIsRedirect = null;
1359 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1361 wfProfileOut( __METHOD__
);
1366 * Get the text that needs to be saved in order to undo all revisions
1367 * between $undo and $undoafter. Revisions must belong to the same page,
1368 * must exist and must not be deleted
1369 * @param $undo Revision
1370 * @param $undoafter Revision Must be an earlier revision than $undo
1371 * @return mixed string on success, false on failure
1372 * @deprecated since 1.WD: use ContentHandler::getUndoContent() instead.
1374 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1375 wfDeprecated( __METHOD__
, '1.WD' );
1377 $this->loadLastEdit();
1379 if ( $this->mLastRevision
) {
1380 if ( is_null( $undoafter ) ) {
1381 $undoafter = $undo->getPrevious();
1384 $handler = $this->getContentHandler();
1385 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1390 return ContentHandler
::getContentText( $undone );
1398 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1399 * @param $text String: new text of the section
1400 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1401 * @param $edittime String: revision timestamp or null to use the current revision
1402 * @return String new complete article text, or null if error
1404 * @deprecated since 1.WD, use replaceSectionContent() instead
1406 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1407 wfDeprecated( __METHOD__
, '1.WD' );
1409 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1411 #TODO: check ContentHandler::supportsSections(). throw exception??
1412 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1413 #TODO: check $newContent == false. throw exception??
1415 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1419 * Returns true iff this page's content model supports sections.
1421 * @return boolean whether sections are supported.
1423 * @todo: the skin should check this and not offer section functionality if sections are not supported.
1425 public function supportsSections() {
1426 return $this->getContentHandler()->supportsSections();
1430 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1431 * @param $content Content: new content of the section
1432 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1433 * @param $edittime String: revision timestamp or null to use the current revision
1435 * @return Content new complete article content, or null if error
1439 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1440 wfProfileIn( __METHOD__
);
1442 if ( strval( $section ) == '' ) {
1443 // Whole-page edit; let the whole text through
1444 $newContent = $sectionContent;
1446 // Bug 30711: always use current version when adding a new section
1447 if ( is_null( $edittime ) ||
$section == 'new' ) {
1448 $oldContent = $this->getContent();
1449 if ( ! $oldContent ) {
1450 wfDebug( __METHOD__
. ": no page text\n" );
1451 wfProfileOut( __METHOD__
);
1455 $dbw = wfGetDB( DB_MASTER
);
1456 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1459 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1460 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1461 wfProfileOut( __METHOD__
);
1465 $oldContent = $rev->getContent();
1468 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1471 wfProfileOut( __METHOD__
);
1476 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1478 * @return Int updated $flags
1480 function checkFlags( $flags ) {
1481 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1482 if ( $this->mTitle
->getArticleID() ) {
1483 $flags |
= EDIT_UPDATE
;
1493 * Change an existing article or create a new article. Updates RC and all necessary caches,
1494 * optionally via the deferred update array.
1496 * @param $text String: new text
1497 * @param $summary String: edit summary
1498 * @param $flags Integer bitfield:
1500 * Article is known or assumed to be non-existent, create a new one
1502 * Article is known or assumed to be pre-existing, update it
1504 * Mark this edit minor, if the user is allowed to do so
1506 * Do not log the change in recentchanges
1508 * Mark the edit a "bot" edit regardless of user rights
1509 * EDIT_DEFER_UPDATES
1510 * Defer some of the updates until the end of index.php
1512 * Fill in blank summaries with generated text where possible
1514 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1515 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1516 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1517 * edit-already-exists error will be returned. These two conditions are also possible with
1518 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1520 * @param $baseRevId int the revision ID this edit was based off, if any
1521 * @param $user User the user doing the edit
1523 * @return Status object. Possible errors:
1524 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1525 * edit-gone-missing: In update mode, but the article didn't exist
1526 * edit-conflict: In update mode, the article changed unexpectedly
1527 * edit-no-change: Warning that the text was the same as before
1528 * edit-already-exists: In creation mode, but the article already exists
1530 * Extensions may define additional errors.
1532 * $return->value will contain an associative array with members as follows:
1533 * new: Boolean indicating if the function attempted to create a new article
1534 * revision: The revision object for the inserted revision, or null
1536 * Compatibility note: this function previously returned a boolean value indicating success/failure
1538 * @deprecated since 1.WD: use doEditContent() instead.
1540 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #@todo: use doEditContent() instead
1541 wfDeprecated( __METHOD__
, '1.WD' );
1543 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1545 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1549 * Change an existing article or create a new article. Updates RC and all necessary caches,
1550 * optionally via the deferred update array.
1552 * @param $content Content: new content
1553 * @param $summary String: edit summary
1554 * @param $flags Integer bitfield:
1556 * Article is known or assumed to be non-existent, create a new one
1558 * Article is known or assumed to be pre-existing, update it
1560 * Mark this edit minor, if the user is allowed to do so
1562 * Do not log the change in recentchanges
1564 * Mark the edit a "bot" edit regardless of user rights
1565 * EDIT_DEFER_UPDATES
1566 * Defer some of the updates until the end of index.php
1568 * Fill in blank summaries with generated text where possible
1570 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1571 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1572 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1573 * edit-already-exists error will be returned. These two conditions are also possible with
1574 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1576 * @param $baseRevId the revision ID this edit was based off, if any
1577 * @param $user User the user doing the edit
1578 * @param $serialisation_format String: format for storing the content in the database
1580 * @return Status object. Possible errors:
1581 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1582 * edit-gone-missing: In update mode, but the article didn't exist
1583 * edit-conflict: In update mode, the article changed unexpectedly
1584 * edit-no-change: Warning that the text was the same as before
1585 * edit-already-exists: In creation mode, but the article already exists
1587 * Extensions may define additional errors.
1589 * $return->value will contain an associative array with members as follows:
1590 * new: Boolean indicating if the function attempted to create a new article
1591 * revision: The revision object for the inserted revision, or null
1595 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1596 User
$user = null, $serialisation_format = null ) {
1597 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1599 # Low-level sanity check
1600 if ( $this->mTitle
->getText() === '' ) {
1601 throw new MWException( 'Something is trying to edit an article with an empty title' );
1604 wfProfileIn( __METHOD__
);
1606 $user = is_null( $user ) ?
$wgUser : $user;
1607 $status = Status
::newGood( array() );
1609 // Load the data from the master database if needed.
1610 // The caller may already loaded it from the master or even loaded it using
1611 // SELECT FOR UPDATE, so do not override that using clear().
1612 $this->loadPageData( 'fromdbmaster' );
1614 $flags = $this->checkFlags( $flags );
1617 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary,
1618 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1620 if ( $hook_ok && Hooks
::isRegistered( 'ArticleSave' ) ) { # avoid serialization overhead if the hook isn't present
1621 $content_text = $content->serialize();
1622 $txt = $content_text; # clone
1624 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary,
1625 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ); #TODO: survey extensions using this hook
1627 if ( $txt !== $content_text ) {
1628 # if the text changed, unserialize the new version to create an updated Content object.
1629 $content = $content->getContentHandler()->unserializeContent( $txt );
1634 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1636 if ( $status->isOK() ) {
1637 $status->fatal( 'edit-hook-aborted' );
1640 wfProfileOut( __METHOD__
);
1644 # Silently ignore EDIT_MINOR if not allowed
1645 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1646 $bot = $flags & EDIT_FORCE_BOT
;
1648 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1650 $oldsize = $old_content ?
$old_content->getSize() : 0;
1651 $oldid = $this->getLatest();
1652 $oldIsRedirect = $this->isRedirect();
1653 $oldcountable = $this->isCountable();
1655 $handler = $content->getContentHandler();
1657 # Provide autosummaries if one is not provided and autosummaries are enabled.
1658 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1659 if ( !$old_content ) $old_content = null;
1660 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1663 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1664 $serialized = $editInfo->pst
;
1665 $content = $editInfo->pstContent
;
1666 $newsize = $content->getSize();
1668 $dbw = wfGetDB( DB_MASTER
);
1669 $now = wfTimestampNow();
1670 $this->mTimestamp
= $now;
1672 if ( $flags & EDIT_UPDATE
) {
1673 # Update article, but only if changed.
1674 $status->value
['new'] = false;
1677 # Article gone missing
1678 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1679 $status->fatal( 'edit-gone-missing' );
1681 wfProfileOut( __METHOD__
);
1685 # Make sure the revision is either completely inserted or not inserted at all
1686 if ( !$wgDBtransactions ) {
1687 $userAbort = ignore_user_abort( true );
1690 $revision = new Revision( array(
1691 'page' => $this->getId(),
1692 'comment' => $summary,
1693 'minor_edit' => $isminor,
1694 'text' => $serialized,
1696 'parent_id' => $oldid,
1697 'user' => $user->getId(),
1698 'user_text' => $user->getName(),
1699 'timestamp' => $now,
1700 'content_model' => $content->getModel(),
1701 'content_format' => $serialisation_format,
1702 ) ); #XXX: pass content object?!
1704 $changed = !$content->equals( $old_content );
1707 if ( !$content->isValid() ) {
1708 throw new MWException( "New content failed validity check!" );
1711 $dbw->begin( __METHOD__
);
1712 $revisionId = $revision->insertOn( $dbw );
1716 # Note that we use $this->mLatest instead of fetching a value from the master DB
1717 # during the course of this function. This makes sure that EditPage can detect
1718 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1719 # before this function is called. A previous function used a separate query, this
1720 # creates a window where concurrent edits can cause an ignored edit conflict.
1721 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1724 /* Belated edit conflict! Run away!! */
1725 $status->fatal( 'edit-conflict' );
1727 # Delete the invalid revision if the DB is not transactional
1728 if ( !$wgDBtransactions ) {
1729 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1733 $dbw->rollback( __METHOD__
);
1735 global $wgUseRCPatrol;
1736 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1737 # Update recentchanges
1738 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1739 # Mark as patrolled if the user can do so
1740 $patrolled = $wgUseRCPatrol && !count(
1741 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1742 # Add RC row to the DB
1743 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1744 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1745 $revisionId, $patrolled
1748 # Log auto-patrolled edits
1750 PatrolLog
::record( $rc, true, $user );
1753 $user->incEditCount();
1754 $dbw->commit( __METHOD__
);
1757 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1758 // related variables correctly
1759 $revision->setId( $this->getLatest() );
1762 if ( !$wgDBtransactions ) {
1763 ignore_user_abort( $userAbort );
1766 // Now that ignore_user_abort is restored, we can respond to fatal errors
1767 if ( !$status->isOK() ) {
1768 wfProfileOut( __METHOD__
);
1772 # Update links tables, site stats, etc.
1773 $this->doEditUpdates(
1777 'changed' => $changed,
1778 'oldcountable' => $oldcountable
1783 $status->warning( 'edit-no-change' );
1785 // Update page_touched, this is usually implicit in the page update
1786 // Other cache updates are done in onArticleEdit()
1787 $this->mTitle
->invalidateCache();
1790 # Create new article
1791 $status->value
['new'] = true;
1793 $dbw->begin( __METHOD__
);
1795 # Add the page record; stake our claim on this title!
1796 # This will return false if the article already exists
1797 $newid = $this->insertOn( $dbw );
1799 if ( $newid === false ) {
1800 $dbw->rollback( __METHOD__
);
1801 $status->fatal( 'edit-already-exists' );
1803 wfProfileOut( __METHOD__
);
1807 # Save the revision text...
1808 $revision = new Revision( array(
1810 'comment' => $summary,
1811 'minor_edit' => $isminor,
1812 'text' => $serialized,
1814 'user' => $user->getId(),
1815 'user_text' => $user->getName(),
1816 'timestamp' => $now,
1817 'content_model' => $content->getModel(),
1818 'content_format' => $serialisation_format,
1820 $revisionId = $revision->insertOn( $dbw );
1822 # Update the page record with revision data
1823 $this->updateRevisionOn( $dbw, $revision, 0 );
1825 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1827 # Update recentchanges
1828 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1829 global $wgUseRCPatrol, $wgUseNPPatrol;
1831 # Mark as patrolled if the user can do so
1832 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1833 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1834 # Add RC row to the DB
1835 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1836 '', $content->getSize(), $revisionId, $patrolled );
1838 # Log auto-patrolled edits
1840 PatrolLog
::record( $rc, true, $user );
1843 $user->incEditCount();
1844 $dbw->commit( __METHOD__
);
1846 # Update links, etc.
1847 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1849 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary,
1850 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1852 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary,
1853 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1856 # Do updates right now unless deferral was requested
1857 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1858 DeferredUpdates
::doUpdates();
1861 // Return the new revision (or null) to the caller
1862 $status->value
['revision'] = $revision;
1864 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary,
1865 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1867 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary,
1868 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1870 # Promote user to any groups they meet the criteria for
1871 $user->addAutopromoteOnceGroups( 'onEdit' );
1873 wfProfileOut( __METHOD__
);
1878 * Get parser options suitable for rendering the primary article wikitext
1879 * @param User|string $user User object or 'canonical'
1880 * @return ParserOptions
1882 public function makeParserOptions( $user ) {
1884 if ( $user instanceof User
) { // settings per user (even anons)
1885 $options = ParserOptions
::newFromUser( $user );
1886 } else { // canonical settings
1887 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1889 $options->enableLimitReport(); // show inclusion/loop reports
1890 $options->setTidy( true ); // fix bad HTML
1895 * Prepare text which is about to be saved.
1896 * Returns a stdclass with source, pst and output members
1898 * @deprecated in 1.WD: use prepareContentForEdit instead.
1900 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1901 wfDeprecated( __METHOD__
, '1.WD' );
1902 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1903 return $this->prepareContentForEdit( $content, $revid , $user );
1907 * Prepare content which is about to be saved.
1908 * Returns a stdclass with source, pst and output members
1910 * @param \Content $content
1911 * @param null $revid
1912 * @param null|\User $user
1913 * @param null $serialization_format
1915 * @return bool|object
1919 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) {
1920 global $wgParser, $wgContLang, $wgUser;
1921 $user = is_null( $user ) ?
$wgUser : $user;
1922 // @TODO fixme: check $user->getId() here???
1924 if ( $this->mPreparedEdit
1925 && $this->mPreparedEdit
->newContent
1926 && $this->mPreparedEdit
->newContent
->equals( $content )
1927 && $this->mPreparedEdit
->revid
== $revid
1928 && $this->mPreparedEdit
->format
== $serialization_format
1929 #XXX: also check $user here?
1932 return $this->mPreparedEdit
;
1935 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1936 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1938 $edit = (object)array();
1939 $edit->revid
= $revid;
1941 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1942 $edit->pst
= $edit->pstContent
->serialize( $serialization_format ); #XXX: do we need this??
1943 $edit->format
= $serialization_format;
1945 $edit->popts
= $this->makeParserOptions( 'canonical' );
1947 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1949 $edit->newContent
= $content;
1950 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1952 #NOTE: B/C for hooks! don't use these fields!
1953 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
);
1954 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
1956 $this->mPreparedEdit
= $edit;
1962 * Do standard deferred updates after page edit.
1963 * Update links tables, site stats, search index and message cache.
1964 * Purges pages that include this page if the text was changed here.
1965 * Every 100th edit, prune the recent changes table.
1967 * @param $revision Revision object
1968 * @param $user User object that did the revision
1969 * @param $options Array of options, following indexes are used:
1970 * - changed: boolean, whether the revision changed the content (default true)
1971 * - created: boolean, whether the revision created the page (default false)
1972 * - oldcountable: boolean or null (default null):
1973 * - boolean: whether the page was counted as an article before that
1974 * revision, only used in changed is true and created is false
1975 * - null: don't change the article count
1977 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1978 global $wgEnableParserCache;
1980 wfProfileIn( __METHOD__
);
1982 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1983 $content = $revision->getContent();
1986 # Be careful not to double-PST: $text is usually already PST-ed once
1987 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1988 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1989 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1991 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1992 $editInfo = $this->mPreparedEdit
;
1995 # Save it to the parser cache
1996 if ( $wgEnableParserCache ) {
1997 $parserCache = ParserCache
::singleton();
1998 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2001 # Update the links tables and other secondary data
2002 $contentHandler = $revision->getContentHandler();
2003 $updates = $contentHandler->getSecondaryDataUpdates( $content, $this->getTitle(), null, true, $editInfo->output
);
2004 DataUpdate
::runUpdates( $updates );
2006 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2008 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2009 if ( 0 == mt_rand( 0, 99 ) ) {
2010 // Flush old entries from the `recentchanges` table; we do this on
2011 // random requests so as to avoid an increase in writes for no good reason
2014 $dbw = wfGetDB( DB_MASTER
);
2015 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2018 array( "rc_timestamp < '$cutoff'" ),
2024 if ( !$this->mTitle
->exists() ) {
2025 wfProfileOut( __METHOD__
);
2029 $id = $this->getId();
2030 $title = $this->mTitle
->getPrefixedDBkey();
2031 $shortTitle = $this->mTitle
->getDBkey();
2033 if ( !$options['changed'] ) {
2036 } elseif ( $options['created'] ) {
2037 $good = (int)$this->isCountable( $editInfo );
2039 } elseif ( $options['oldcountable'] !== null ) {
2040 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2047 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2048 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) ); #TODO: let the search engine decide what to do with the content object
2050 # If this is another user's talk page, update newtalk.
2051 # Don't do this if $options['changed'] = false (null-edits) nor if
2052 # it's a minor edit and the user doesn't want notifications for those.
2053 if ( $options['changed']
2054 && $this->mTitle
->getNamespace() == NS_USER_TALK
2055 && $shortTitle != $user->getTitleKey()
2056 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2058 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2059 $other = User
::newFromName( $shortTitle, false );
2061 wfDebug( __METHOD__
. ": invalid username\n" );
2062 } elseif ( User
::isIP( $shortTitle ) ) {
2063 // An anonymous user
2064 $other->setNewtalk( true );
2065 } elseif ( $other->isLoggedIn() ) {
2066 $other->setNewtalk( true );
2068 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2073 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2074 $msgtext = $content->getWikitextForTransclusion(); #XXX: could skip pseudo-messages like js/css here, based on content model.
2075 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
2077 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2080 if( $options['created'] ) {
2081 self
::onArticleCreate( $this->mTitle
);
2083 self
::onArticleEdit( $this->mTitle
);
2086 wfProfileOut( __METHOD__
);
2090 * Edit an article without doing all that other stuff
2091 * The article must already exist; link tables etc
2092 * are not updated, caches are not flushed.
2094 * @param $text String: text submitted
2095 * @param $user User The relevant user
2096 * @param $comment String: comment submitted
2097 * @param $minor Boolean: whereas it's a minor modification
2099 * @deprecated since 1.WD, use doEditContent() instead.
2101 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2102 wfDeprecated( __METHOD__
, "1.WD" );
2104 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2105 return $this->doQuickEditContent( $content, $user, $comment , $minor );
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 $content Content: content submitted
2114 * @param $user User The relevant user
2115 * @param $comment String: comment submitted
2116 * @param $serialisation_format String: format for storing the content in the database
2117 * @param $minor Boolean: whereas it's a minor modification
2119 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
2120 wfProfileIn( __METHOD__
);
2122 $serialized = $content->serialize( $serialisation_format );
2124 $dbw = wfGetDB( DB_MASTER
);
2125 $revision = new Revision( array(
2126 'page' => $this->getId(),
2127 'text' => $serialized,
2128 'length' => $content->getSize(),
2129 'comment' => $comment,
2130 'minor_edit' => $minor ?
1 : 0,
2131 ) ); #XXX: set the content object?
2132 $revision->insertOn( $dbw );
2133 $this->updateRevisionOn( $dbw, $revision );
2135 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2137 wfProfileOut( __METHOD__
);
2141 * Update the article's restriction field, and leave a log entry.
2142 * This works for protection both existing and non-existing pages.
2144 * @param $limit Array: set of restriction keys
2145 * @param $reason String
2146 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2147 * @param $expiry Array: per restriction type expiration
2148 * @param $user User The user updating the restrictions
2151 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2154 if ( wfReadOnly() ) {
2155 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2158 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2160 $id = $this->mTitle
->getArticleID();
2166 // Take this opportunity to purge out expired restrictions
2167 Title
::purgeExpiredRestrictions();
2169 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2170 # we expect a single selection, but the schema allows otherwise.
2171 $isProtected = false;
2175 $dbw = wfGetDB( DB_MASTER
);
2177 foreach ( $restrictionTypes as $action ) {
2178 if ( !isset( $expiry[$action] ) ) {
2179 $expiry[$action] = $dbw->getInfinity();
2181 if ( !isset( $limit[$action] ) ) {
2182 $limit[$action] = '';
2183 } elseif ( $limit[$action] != '' ) {
2187 # Get current restrictions on $action
2188 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2189 if ( $current != '' ) {
2190 $isProtected = true;
2193 if ( $limit[$action] != $current ) {
2195 } elseif ( $limit[$action] != '' ) {
2196 # Only check expiry change if the action is actually being
2197 # protected, since expiry does nothing on an not-protected
2199 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2205 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2209 # If nothing's changed, do nothing
2211 return Status
::newGood();
2214 if ( !$protect ) { # No protection at all means unprotection
2215 $revCommentMsg = 'unprotectedarticle';
2216 $logAction = 'unprotect';
2217 } elseif ( $isProtected ) {
2218 $revCommentMsg = 'modifiedarticleprotection';
2219 $logAction = 'modify';
2221 $revCommentMsg = 'protectedarticle';
2222 $logAction = 'protect';
2225 $encodedExpiry = array();
2226 $protectDescription = '';
2227 foreach ( $limit as $action => $restrictions ) {
2228 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2229 if ( $restrictions != '' ) {
2230 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2231 if ( $encodedExpiry[$action] != 'infinity' ) {
2232 $protectDescription .= wfMsgForContent( 'protect-expiring',
2233 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2234 $wgContLang->date( $expiry[$action], false, false ) ,
2235 $wgContLang->time( $expiry[$action], false, false ) );
2237 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
2240 $protectDescription .= ') ';
2243 $protectDescription = trim( $protectDescription );
2245 if ( $id ) { # Protection of existing page
2246 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2247 return Status
::newGood();
2250 # Only restrictions with the 'protect' right can cascade...
2251 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2252 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2254 # The schema allows multiple restrictions
2255 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2259 # Update restrictions table
2260 foreach ( $limit as $action => $restrictions ) {
2261 if ( $restrictions != '' ) {
2262 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2263 array( 'pr_page' => $id,
2264 'pr_type' => $action,
2265 'pr_level' => $restrictions,
2266 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2267 'pr_expiry' => $encodedExpiry[$action]
2272 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2273 'pr_type' => $action ), __METHOD__
);
2277 # Prepare a null revision to be added to the history
2278 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2280 $editComment .= ": $reason";
2282 if ( $protectDescription ) {
2283 $editComment .= " ($protectDescription)";
2286 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2289 # Insert a null revision
2290 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2291 $nullRevId = $nullRevision->insertOn( $dbw );
2293 $latest = $this->getLatest();
2294 # Update page record
2295 $dbw->update( 'page',
2297 'page_touched' => $dbw->timestamp(),
2298 'page_restrictions' => '',
2299 'page_latest' => $nullRevId
2300 ), array( /* WHERE */
2305 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2306 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2307 } else { # Protection of non-existing page (also known as "title protection")
2308 # Cascade protection is meaningless in this case
2311 if ( $limit['create'] != '' ) {
2312 $dbw->replace( 'protected_titles',
2313 array( array( 'pt_namespace', 'pt_title' ) ),
2315 'pt_namespace' => $this->mTitle
->getNamespace(),
2316 'pt_title' => $this->mTitle
->getDBkey(),
2317 'pt_create_perm' => $limit['create'],
2318 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2319 'pt_expiry' => $encodedExpiry['create'],
2320 'pt_user' => $user->getId(),
2321 'pt_reason' => $reason,
2325 $dbw->delete( 'protected_titles',
2327 'pt_namespace' => $this->mTitle
->getNamespace(),
2328 'pt_title' => $this->mTitle
->getDBkey()
2334 $this->mTitle
->flushRestrictions();
2336 if ( $logAction == 'unprotect' ) {
2337 $logParams = array();
2339 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2342 # Update the protection log
2343 $log = new LogPage( 'protect' );
2344 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2346 return Status
::newGood();
2350 * Take an array of page restrictions and flatten it to a string
2351 * suitable for insertion into the page_restrictions field.
2352 * @param $limit Array
2355 protected static function flattenRestrictions( $limit ) {
2356 if ( !is_array( $limit ) ) {
2357 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2363 foreach ( $limit as $action => $restrictions ) {
2364 if ( $restrictions != '' ) {
2365 $bits[] = "$action=$restrictions";
2369 return implode( ':', $bits );
2373 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2374 * Deletes the article with database consistency, writes logs, purges caches
2376 * @param $reason string delete reason for deletion log
2377 * @param $suppress int bitfield
2378 * Revision::DELETED_TEXT
2379 * Revision::DELETED_COMMENT
2380 * Revision::DELETED_USER
2381 * Revision::DELETED_RESTRICTED
2382 * @param $id int article ID
2383 * @param $commit boolean defaults to true, triggers transaction end
2384 * @param &$error Array of errors to append to
2385 * @param $user User The deleting user
2386 * @return boolean true if successful
2388 public function doDeleteArticle(
2389 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2391 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2392 == WikiPage
::DELETE_SUCCESS
;
2396 * Back-end article deletion
2397 * Deletes the article with database consistency, writes logs, purges caches
2399 * @param $reason string delete reason for deletion log
2400 * @param $suppress int bitfield
2401 * Revision::DELETED_TEXT
2402 * Revision::DELETED_COMMENT
2403 * Revision::DELETED_USER
2404 * Revision::DELETED_RESTRICTED
2405 * @param $id int article ID
2406 * @param $commit boolean defaults to true, triggers transaction end
2407 * @param &$error Array of errors to append to
2408 * @param $user User The deleting user
2409 * @return int: One of WikiPage::DELETE_* constants
2411 public function doDeleteArticleReal(
2412 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2414 global $wgUser, $wgContentHandlerUseDB;
2416 wfDebug( __METHOD__
. "\n" );
2418 if ( $this->mTitle
->getDBkey() === '' ) {
2419 return WikiPage
::DELETE_NO_PAGE
;
2422 $user = is_null( $user ) ?
$wgUser : $user;
2423 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2424 return WikiPage
::DELETE_HOOK_ABORTED
;
2428 $this->loadPageData( 'forupdate' );
2429 $id = $this->getID();
2431 return WikiPage
::DELETE_NO_PAGE
;
2435 // Bitfields to further suppress the content
2438 // This should be 15...
2439 $bitfield |
= Revision
::DELETED_TEXT
;
2440 $bitfield |
= Revision
::DELETED_COMMENT
;
2441 $bitfield |
= Revision
::DELETED_USER
;
2442 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2444 $bitfield = 'rev_deleted';
2447 // we need to remember the old content so we can use it to generate all deletion updates.
2448 $content = $this->getContent( Revision
::RAW
);
2450 $dbw = wfGetDB( DB_MASTER
);
2451 $dbw->begin( __METHOD__
);
2452 // For now, shunt the revision data into the archive table.
2453 // Text is *not* removed from the text table; bulk storage
2454 // is left intact to avoid breaking block-compression or
2455 // immutable storage schemes.
2457 // For backwards compatibility, note that some older archive
2458 // table entries will have ar_text and ar_flags fields still.
2460 // In the future, we may keep revisions and mark them with
2461 // the rev_deleted field, which is reserved for this purpose.
2464 'ar_namespace' => 'page_namespace',
2465 'ar_title' => 'page_title',
2466 'ar_comment' => 'rev_comment',
2467 'ar_user' => 'rev_user',
2468 'ar_user_text' => 'rev_user_text',
2469 'ar_timestamp' => 'rev_timestamp',
2470 'ar_minor_edit' => 'rev_minor_edit',
2471 'ar_rev_id' => 'rev_id',
2472 'ar_parent_id' => 'rev_parent_id',
2473 'ar_text_id' => 'rev_text_id',
2474 'ar_text' => '\'\'', // Be explicit to appease
2475 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2476 'ar_len' => 'rev_len',
2477 'ar_page_id' => 'page_id',
2478 'ar_deleted' => $bitfield,
2479 'ar_sha1' => 'rev_sha1',
2482 if ( $wgContentHandlerUseDB ) {
2483 $row[ 'ar_content_model' ] = 'rev_content_model';
2484 $row[ 'ar_content_format' ] = 'rev_content_format';
2487 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2491 'page_id = rev_page'
2495 # Now that it's safely backed up, delete it
2496 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2497 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2500 $dbw->rollback( __METHOD__
);
2501 return WikiPage
::DELETE_NO_REVISIONS
;
2504 $this->doDeleteUpdates( $id, $content );
2506 # Log the deletion, if the page was suppressed, log it at Oversight instead
2507 $logtype = $suppress ?
'suppress' : 'delete';
2509 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2510 $logEntry->setPerformer( $user );
2511 $logEntry->setTarget( $this->mTitle
);
2512 $logEntry->setComment( $reason );
2513 $logid = $logEntry->insert();
2514 $logEntry->publish( $logid );
2517 $dbw->commit( __METHOD__
);
2520 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2521 return WikiPage
::DELETE_SUCCESS
;
2525 * Do some database updates after deletion
2527 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2528 * @param $content Content: optional page content to be used when determining the required updates.
2529 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2531 public function doDeleteUpdates( $id, Content
$content = null ) {
2532 # update site status
2533 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2535 # remove secondary indexes, etc
2536 $updates = $this->getDeletionUpdates( $content );
2537 DataUpdate
::runUpdates( $updates );
2540 WikiPage
::onArticleDelete( $this->mTitle
);
2545 # Clear the cached article id so the interface doesn't act like we exist
2546 $this->mTitle
->resetArticleID( 0 );
2550 * Roll back the most recent consecutive set of edits to a page
2551 * from the same user; fails if there are no eligible edits to
2552 * roll back to, e.g. user is the sole contributor. This function
2553 * performs permissions checks on $user, then calls commitRollback()
2554 * to do the dirty work
2556 * @todo: seperate the business/permission stuff out from backend code
2558 * @param $fromP String: Name of the user whose edits to rollback.
2559 * @param $summary String: Custom summary. Set to default summary if empty.
2560 * @param $token String: Rollback token.
2561 * @param $bot Boolean: If true, mark all reverted edits as bot.
2563 * @param $resultDetails Array: contains result-specific array of additional values
2564 * 'alreadyrolled' : 'current' (rev)
2565 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2567 * @param $user User The user performing the rollback
2568 * @return array of errors, each error formatted as
2569 * array(messagekey, param1, param2, ...).
2570 * On success, the array is empty. This array can also be passed to
2571 * OutputPage::showPermissionsErrorPage().
2573 public function doRollback(
2574 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2576 $resultDetails = null;
2579 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2580 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2581 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2583 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2584 $errors[] = array( 'sessionfailure' );
2587 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2588 $errors[] = array( 'actionthrottledtext' );
2591 # If there were errors, bail out now
2592 if ( !empty( $errors ) ) {
2596 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2600 * Backend implementation of doRollback(), please refer there for parameter
2601 * and return value documentation
2603 * NOTE: This function does NOT check ANY permissions, it just commits the
2604 * rollback to the DB. Therefore, you should only call this function direct-
2605 * ly if you want to use custom permissions checks. If you don't, use
2606 * doRollback() instead.
2607 * @param $fromP String: Name of the user whose edits to rollback.
2608 * @param $summary String: Custom summary. Set to default summary if empty.
2609 * @param $bot Boolean: If true, mark all reverted edits as bot.
2611 * @param $resultDetails Array: contains result-specific array of additional values
2612 * @param $guser User The user performing the rollback
2615 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2616 global $wgUseRCPatrol, $wgContLang;
2618 $dbw = wfGetDB( DB_MASTER
);
2620 if ( wfReadOnly() ) {
2621 return array( array( 'readonlytext' ) );
2624 # Get the last editor
2625 $current = $this->getRevision();
2626 if ( is_null( $current ) ) {
2627 # Something wrong... no page?
2628 return array( array( 'notanarticle' ) );
2631 $from = str_replace( '_', ' ', $fromP );
2632 # User name given should match up with the top revision.
2633 # If the user was deleted then $from should be empty.
2634 if ( $from != $current->getUserText() ) {
2635 $resultDetails = array( 'current' => $current );
2636 return array( array( 'alreadyrolled',
2637 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2638 htmlspecialchars( $fromP ),
2639 htmlspecialchars( $current->getUserText() )
2643 # Get the last edit not by this guy...
2644 # Note: these may not be public values
2645 $user = intval( $current->getRawUser() );
2646 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2647 $s = $dbw->selectRow( 'revision',
2648 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2649 array( 'rev_page' => $current->getPage(),
2650 "rev_user != {$user} OR rev_user_text != {$user_text}"
2652 array( 'USE INDEX' => 'page_timestamp',
2653 'ORDER BY' => 'rev_timestamp DESC' )
2655 if ( $s === false ) {
2656 # No one else ever edited this page
2657 return array( array( 'cantrollback' ) );
2658 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2659 # Only admins can see this text
2660 return array( array( 'notvisiblerev' ) );
2664 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2665 # Mark all reverted edits as bot
2669 if ( $wgUseRCPatrol ) {
2670 # Mark all reverted edits as patrolled
2671 $set['rc_patrolled'] = 1;
2674 if ( count( $set ) ) {
2675 $dbw->update( 'recentchanges', $set,
2677 'rc_cur_id' => $current->getPage(),
2678 'rc_user_text' => $current->getUserText(),
2679 "rc_timestamp > '{$s->rev_timestamp}'",
2684 # Generate the edit summary if necessary
2685 $target = Revision
::newFromId( $s->rev_id
);
2686 if ( empty( $summary ) ) {
2687 if ( $from == '' ) { // no public user name
2688 $summary = wfMsgForContent( 'revertpage-nouser' );
2690 $summary = wfMsgForContent( 'revertpage' );
2694 # Allow the custom summary to use the same args as the default message
2696 $target->getUserText(), $from, $s->rev_id
,
2697 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2698 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2700 $summary = wfMsgReplaceArgs( $summary, $args );
2703 $flags = EDIT_UPDATE
;
2705 if ( $guser->isAllowed( 'minoredit' ) ) {
2706 $flags |
= EDIT_MINOR
;
2709 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2710 $flags |
= EDIT_FORCE_BOT
;
2713 # Actually store the edit
2714 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2715 if ( !empty( $status->value
['revision'] ) ) {
2716 $revId = $status->value
['revision']->getId();
2721 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2723 $resultDetails = array(
2724 'summary' => $summary,
2725 'current' => $current,
2726 'target' => $target,
2734 * The onArticle*() functions are supposed to be a kind of hooks
2735 * which should be called whenever any of the specified actions
2738 * This is a good place to put code to clear caches, for instance.
2740 * This is called on page move and undelete, as well as edit
2742 * @param $title Title object
2744 public static function onArticleCreate( $title ) {
2745 # Update existence markers on article/talk tabs...
2746 if ( $title->isTalkPage() ) {
2747 $other = $title->getSubjectPage();
2749 $other = $title->getTalkPage();
2752 $other->invalidateCache();
2753 $other->purgeSquid();
2755 $title->touchLinks();
2756 $title->purgeSquid();
2757 $title->deleteTitleProtection();
2761 * Clears caches when article is deleted
2763 * @param $title Title
2765 public static function onArticleDelete( $title ) {
2766 # Update existence markers on article/talk tabs...
2767 if ( $title->isTalkPage() ) {
2768 $other = $title->getSubjectPage();
2770 $other = $title->getTalkPage();
2773 $other->invalidateCache();
2774 $other->purgeSquid();
2776 $title->touchLinks();
2777 $title->purgeSquid();
2780 HTMLFileCache
::clearFileCache( $title );
2783 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2784 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2788 if ( $title->getNamespace() == NS_FILE
) {
2789 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2790 $update->doUpdate();
2794 if ( $title->getNamespace() == NS_USER_TALK
) {
2795 $user = User
::newFromName( $title->getText(), false );
2797 $user->setNewtalk( false );
2802 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2806 * Purge caches on page update etc
2808 * @param $title Title object
2809 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2811 public static function onArticleEdit( $title ) {
2812 // Invalidate caches of articles which include this page
2813 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2816 // Invalidate the caches of all pages which redirect here
2817 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2819 # Purge squid for this page only
2820 $title->purgeSquid();
2822 # Clear file cache for this page only
2823 HTMLFileCache
::clearFileCache( $title );
2829 * Returns a list of hidden categories this page is a member of.
2830 * Uses the page_props and categorylinks tables.
2832 * @return Array of Title objects
2834 public function getHiddenCategories() {
2836 $id = $this->mTitle
->getArticleID();
2842 $dbr = wfGetDB( DB_SLAVE
);
2843 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2845 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2846 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2849 if ( $res !== false ) {
2850 foreach ( $res as $row ) {
2851 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2859 * Return an applicable autosummary if one exists for the given edit.
2860 * @param $oldtext String|null: the previous text of the page.
2861 * @param $newtext String|null: The submitted text of the page.
2862 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2863 * @return string An appropriate autosummary, or an empty string.
2864 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
2866 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2867 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2869 wfDeprecated( __METHOD__
, '1.WD' );
2871 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
2872 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
2873 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
2875 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2879 * Auto-generates a deletion reason
2881 * @param &$hasHistory Boolean: whether the page has a history
2882 * @return mixed String containing deletion reason or empty string, or boolean false
2883 * if no revision occurred
2884 * @deprecated since 1.WD, use ContentHandler::getAutoDeleteReason() instead
2886 public function getAutoDeleteReason( &$hasHistory ) {
2887 #NOTE: stub for backwards-compatibility.
2889 wfDeprecated( __METHOD__
, '1.WD' );
2891 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2892 return $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2896 * Update all the appropriate counts in the category table, given that
2897 * we've added the categories $added and deleted the categories $deleted.
2899 * @param $added array The names of categories that were added
2900 * @param $deleted array The names of categories that were deleted
2902 public function updateCategoryCounts( $added, $deleted ) {
2903 $ns = $this->mTitle
->getNamespace();
2904 $dbw = wfGetDB( DB_MASTER
);
2906 # First make sure the rows exist. If one of the "deleted" ones didn't
2907 # exist, we might legitimately not create it, but it's simpler to just
2908 # create it and then give it a negative value, since the value is bogus
2911 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2912 $insertCats = array_merge( $added, $deleted );
2913 if ( !$insertCats ) {
2914 # Okay, nothing to do
2918 $insertRows = array();
2920 foreach ( $insertCats as $cat ) {
2921 $insertRows[] = array(
2922 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2926 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2928 $addFields = array( 'cat_pages = cat_pages + 1' );
2929 $removeFields = array( 'cat_pages = cat_pages - 1' );
2931 if ( $ns == NS_CATEGORY
) {
2932 $addFields[] = 'cat_subcats = cat_subcats + 1';
2933 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2934 } elseif ( $ns == NS_FILE
) {
2935 $addFields[] = 'cat_files = cat_files + 1';
2936 $removeFields[] = 'cat_files = cat_files - 1';
2943 array( 'cat_title' => $added ),
2952 array( 'cat_title' => $deleted ),
2959 * Updates cascading protections
2961 * @param $parserOutput ParserOutput object for the current version
2963 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2964 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2968 // templatelinks table may have become out of sync,
2969 // especially if using variable-based transclusions.
2970 // For paranoia, check if things have changed and if
2971 // so apply updates to the database. This will ensure
2972 // that cascaded protections apply as soon as the changes
2975 # Get templates from templatelinks
2976 $id = $this->mTitle
->getArticleID();
2978 $tlTemplates = array();
2980 $dbr = wfGetDB( DB_SLAVE
);
2981 $res = $dbr->select( array( 'templatelinks' ),
2982 array( 'tl_namespace', 'tl_title' ),
2983 array( 'tl_from' => $id ),
2987 foreach ( $res as $row ) {
2988 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2991 # Get templates from parser output.
2992 $poTemplates = array();
2993 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2994 foreach ( $templates as $dbk => $id ) {
2995 $poTemplates["$ns:$dbk"] = true;
3000 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3002 if ( count( $templates_diff ) > 0 ) {
3003 # Whee, link updates time.
3004 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3005 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3011 * Return a list of templates used by this article.
3012 * Uses the templatelinks table
3014 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3015 * @return Array of Title objects
3017 public function getUsedTemplates() {
3018 return $this->mTitle
->getTemplateLinksFrom();
3022 * Perform article updates on a special page creation.
3024 * @param $rev Revision object
3026 * @todo This is a shitty interface function. Kill it and replace the
3027 * other shitty functions like doEditUpdates and such so it's not needed
3029 * @deprecated since 1.18, use doEditUpdates()
3031 public function createUpdates( $rev ) {
3032 wfDeprecated( __METHOD__
, '1.18' );
3034 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3038 * This function is called right before saving the wikitext,
3039 * so we can do things like signatures and links-in-context.
3041 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3042 * @param $text String article contents
3043 * @param $user User object: user doing the edit
3044 * @param $popts ParserOptions object: parser options, default options for
3045 * the user loaded if null given
3046 * @return string article contents with altered wikitext markup (signatures
3047 * converted, {{subst:}}, templates, etc.)
3049 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3050 global $wgParser, $wgUser;
3052 wfDeprecated( __METHOD__
, '1.19' );
3054 $user = is_null( $user ) ?
$wgUser : $user;
3056 if ( $popts === null ) {
3057 $popts = ParserOptions
::newFromUser( $user );
3060 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3064 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3066 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3069 public function isBigDeletion() {
3070 wfDeprecated( __METHOD__
, '1.19' );
3071 return $this->mTitle
->isBigDeletion();
3075 * Get the approximate revision count of this page.
3077 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3080 public function estimateRevisionCount() {
3081 wfDeprecated( __METHOD__
, '1.19' );
3082 return $this->mTitle
->estimateRevisionCount();
3086 * Update the article's restriction field, and leave a log entry.
3088 * @deprecated since 1.19
3089 * @param $limit Array: set of restriction keys
3090 * @param $reason String
3091 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3092 * @param $expiry Array: per restriction type expiration
3093 * @param $user User The user updating the restrictions
3094 * @return bool true on success
3096 public function updateRestrictions(
3097 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3101 $user = is_null( $user ) ?
$wgUser : $user;
3103 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3107 * @deprecated since 1.18
3109 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3110 wfDeprecated( __METHOD__
, '1.18' );
3112 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3116 * @deprecated since 1.18
3118 public function viewUpdates() {
3119 wfDeprecated( __METHOD__
, '1.18' );
3121 return $this->doViewUpdates( $wgUser );
3125 * @deprecated since 1.18
3128 public function useParserCache( $oldid ) {
3129 wfDeprecated( __METHOD__
, '1.18' );
3131 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3135 * Returns a list of updates to be performed when this page is deleted. The updates should remove any infomration
3136 * about this page from secondary data stores such as links tables.
3138 * @param Content|null $content optional Content object for determining the necessary updates
3139 * @return Array an array of DataUpdates objects
3141 public function getDeletionUpdates( Content
$content = null ) {
3143 // load content object, which may be used to determine the necessary updates
3144 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3145 $content = $this->getContent( Revision
::RAW
);
3148 $updates = $this->getContentHandler()->getDeletionUpdates( $content, $this->mTitle
);
3150 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, &$updates ) );
3156 class PoolWorkArticleView
extends PoolCounterWork
{
3174 * @var ParserOptions
3176 private $parserOptions;
3181 private $content = null;
3184 * @var ParserOutput|bool
3186 private $parserOutput = false;
3191 private $isDirty = false;
3196 private $error = false;
3202 * @param $revid Integer: ID of the revision being parsed
3203 * @param $useParserCache Boolean: whether to use the parser cache
3204 * @param $parserOptions parserOptions to use for the parse operation
3205 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3207 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3208 if ( is_string($content) ) { #BC: old style call
3209 $modelId = $page->getRevision()->getContentModel();
3210 $format = $page->getRevision()->getContentFormat();
3211 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3214 $this->page
= $page;
3215 $this->revid
= $revid;
3216 $this->cacheable
= $useParserCache;
3217 $this->parserOptions
= $parserOptions;
3218 $this->content
= $content;
3219 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3220 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3224 * Get the ParserOutput from this object, or false in case of failure
3226 * @return ParserOutput
3228 public function getParserOutput() {
3229 return $this->parserOutput
;
3233 * Get whether the ParserOutput is a dirty one (i.e. expired)
3237 public function getIsDirty() {
3238 return $this->isDirty
;
3242 * Get a Status object in case of error or false otherwise
3244 * @return Status|bool
3246 public function getError() {
3247 return $this->error
;
3254 global $wgUseFileCache;
3256 // @todo: several of the methods called on $this->page are not declared in Page, but present in WikiPage and delegated by Article.
3258 $isCurrent = $this->revid
=== $this->page
->getLatest();
3260 if ( $this->content
!== null ) {
3261 $content = $this->content
;
3262 } elseif ( $isCurrent ) {
3263 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
3265 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3266 if ( $rev === null ) {
3269 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
3272 $time = - microtime( true );
3273 // TODO: page might not have this method? Hard to tell what page is supposed to be here...
3274 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3275 $time +
= microtime( true );
3279 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3280 $this->page
->getTitle()->getPrefixedDBkey() ) );
3283 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3284 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3287 // Make sure file cache is not used on uncacheable content.
3288 // Output that has magic words in it can still use the parser cache
3289 // (if enabled), though it will generally expire sooner.
3290 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3291 $wgUseFileCache = false;
3295 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3304 function getCachedWork() {
3305 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3307 if ( $this->parserOutput
=== false ) {
3308 wfDebug( __METHOD__
. ": parser cache miss\n" );
3311 wfDebug( __METHOD__
. ": parser cache hit\n" );
3319 function fallback() {
3320 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3322 if ( $this->parserOutput
=== false ) {
3323 wfDebugLog( 'dirty', "dirty missing\n" );
3324 wfDebug( __METHOD__
. ": no dirty cache\n" );
3327 wfDebug( __METHOD__
. ": sending dirty output\n" );
3328 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3329 $this->isDirty
= true;
3335 * @param $status Status
3338 function error( $status ) {
3339 $this->error
= $status;