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 text represents a redirect
471 * @param $text mixed string containing article contents, or boolean
474 public function isRedirect( $text = false ) {
475 if ( $text === false ) $content = $this->getContent();
476 else $content = ContentHandler
::makeContent( $text, $this->mTitle
); # TODO: allow model and format to be provided; or better, expect a Content object
479 if ( empty( $content ) ) return false;
480 else return $content->isRedirect();
484 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
486 * Will use the revisions actual content model if the page exists,
487 * and the page's default if the page doesn't exist yet.
493 public function getContentModel() {
494 if ( $this->exists() ) {
495 # look at the revision's actual content model
496 $rev = $this->getRevision();
498 if ( $rev !== null ) {
499 return $rev->getContentModel();
501 wfWarn( "Page exists but has no revision!" );
505 # use the default model for this page
506 return $this->mTitle
->getContentModel();
510 * Loads page_touched and returns a value indicating if it should be used
511 * @return boolean true if not a redirect
513 public function checkTouched() {
514 if ( !$this->mDataLoaded
) {
515 $this->loadPageData();
517 return !$this->mIsRedirect
;
521 * Get the page_touched field
522 * @return string containing GMT timestamp
524 public function getTouched() {
525 if ( !$this->mDataLoaded
) {
526 $this->loadPageData();
528 return $this->mTouched
;
532 * Get the page_latest field
533 * @return integer rev_id of current revision
535 public function getLatest() {
536 if ( !$this->mDataLoaded
) {
537 $this->loadPageData();
539 return (int)$this->mLatest
;
543 * Get the Revision object of the oldest revision
544 * @return Revision|null
546 public function getOldestRevision() {
547 wfProfileIn( __METHOD__
);
549 // Try using the slave database first, then try the master
551 $db = wfGetDB( DB_SLAVE
);
552 $revSelectFields = Revision
::selectFields();
554 while ( $continue ) {
555 $row = $db->selectRow(
556 array( 'page', 'revision' ),
559 'page_namespace' => $this->mTitle
->getNamespace(),
560 'page_title' => $this->mTitle
->getDBkey(),
565 'ORDER BY' => 'rev_timestamp ASC'
572 $db = wfGetDB( DB_MASTER
);
577 wfProfileOut( __METHOD__
);
578 return $row ? Revision
::newFromRow( $row ) : null;
582 * Loads everything except the text
583 * This isn't necessary for all uses, so it's only done if needed.
585 protected function loadLastEdit() {
586 if ( $this->mLastRevision
!== null ) {
587 return; // already loaded
590 $latest = $this->getLatest();
592 return; // page doesn't exist or is missing page_latest info
595 $revision = Revision
::newFromPageId( $this->getId(), $latest );
596 if ( $revision ) { // sanity
597 $this->setLastEdit( $revision );
602 * Set the latest revision
604 protected function setLastEdit( Revision
$revision ) {
605 $this->mLastRevision
= $revision;
606 $this->mTimestamp
= $revision->getTimestamp();
610 * Get the latest revision
611 * @return Revision|null
613 public function getRevision() {
614 $this->loadLastEdit();
615 if ( $this->mLastRevision
) {
616 return $this->mLastRevision
;
622 * Get the content of the current revision. No side-effects...
624 * @param $audience Integer: one of:
625 * Revision::FOR_PUBLIC to be displayed to all users
626 * Revision::FOR_THIS_USER to be displayed to $wgUser
627 * Revision::RAW get the text regardless of permissions
628 * @return Content|null The content of the current revision
632 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
633 $this->loadLastEdit();
634 if ( $this->mLastRevision
) {
635 return $this->mLastRevision
->getContent( $audience );
641 * Get the text of the current revision. No side-effects...
643 * @param $audience Integer: one of:
644 * Revision::FOR_PUBLIC to be displayed to all users
645 * Revision::FOR_THIS_USER to be displayed to $wgUser
646 * Revision::RAW get the text regardless of permissions
647 * @return String|false The text of the current revision
648 * @deprecated as of 1.WD, getContent() should be used instead.
650 public function getText( $audience = Revision
::FOR_PUBLIC
) { #@todo: deprecated, replace usage!
651 wfDeprecated( __METHOD__
, '1.WD' );
653 $this->loadLastEdit();
654 if ( $this->mLastRevision
) {
655 return $this->mLastRevision
->getText( $audience );
661 * Get the text of the current revision. No side-effects...
663 * @return String|bool The text of the current revision. False on failure
664 * @deprecated as of 1.WD, getContent() should be used instead.
666 public function getRawText() { #@todo: deprecated, replace usage!
667 wfDeprecated( __METHOD__
, '1.WD' );
669 return $this->getText( Revision
::RAW
);
673 * @return string MW timestamp of last article revision
675 public function getTimestamp() {
676 // Check if the field has been filled by WikiPage::setTimestamp()
677 if ( !$this->mTimestamp
) {
678 $this->loadLastEdit();
681 return wfTimestamp( TS_MW
, $this->mTimestamp
);
685 * Set the page timestamp (use only to avoid DB queries)
686 * @param $ts string MW timestamp of last article revision
689 public function setTimestamp( $ts ) {
690 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
694 * @param $audience Integer: one of:
695 * Revision::FOR_PUBLIC to be displayed to all users
696 * Revision::FOR_THIS_USER to be displayed to $wgUser
697 * Revision::RAW get the text regardless of permissions
698 * @return int user ID for the user that made the last article revision
700 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
701 $this->loadLastEdit();
702 if ( $this->mLastRevision
) {
703 return $this->mLastRevision
->getUser( $audience );
710 * Get the User object of the user who created the page
711 * @param $audience Integer: one of:
712 * Revision::FOR_PUBLIC to be displayed to all users
713 * Revision::FOR_THIS_USER to be displayed to $wgUser
714 * Revision::RAW get the text regardless of permissions
717 public function getCreator( $audience = Revision
::FOR_PUBLIC
) {
718 $revision = $this->getOldestRevision();
720 $userName = $revision->getUserText( $audience );
721 return User
::newFromName( $userName, false );
728 * @param $audience Integer: one of:
729 * Revision::FOR_PUBLIC to be displayed to all users
730 * Revision::FOR_THIS_USER to be displayed to $wgUser
731 * Revision::RAW get the text regardless of permissions
732 * @return string username of the user that made the last article revision
734 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
735 $this->loadLastEdit();
736 if ( $this->mLastRevision
) {
737 return $this->mLastRevision
->getUserText( $audience );
744 * @param $audience Integer: one of:
745 * Revision::FOR_PUBLIC to be displayed to all users
746 * Revision::FOR_THIS_USER to be displayed to $wgUser
747 * Revision::RAW get the text regardless of permissions
748 * @return string Comment stored for the last article revision
750 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
751 $this->loadLastEdit();
752 if ( $this->mLastRevision
) {
753 return $this->mLastRevision
->getComment( $audience );
760 * Returns true if last revision was marked as "minor edit"
762 * @return boolean Minor edit indicator for the last article revision.
764 public function getMinorEdit() {
765 $this->loadLastEdit();
766 if ( $this->mLastRevision
) {
767 return $this->mLastRevision
->isMinor();
774 * Get the cached timestamp for the last time the page changed.
775 * This is only used to help handle slave lag by comparing to page_touched.
776 * @return string MW timestamp
778 protected function getCachedLastEditTime() {
780 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
781 return $wgMemc->get( $key );
785 * Set the cached timestamp for the last time the page changed.
786 * This is only used to help handle slave lag by comparing to page_touched.
787 * @param $timestamp string
790 public function setCachedLastEditTime( $timestamp ) {
792 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
793 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
797 * Determine whether a page would be suitable for being counted as an
798 * article in the site_stats table based on the title & its content
800 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
801 * if false, the current database state will be used
804 public function isCountable( $editInfo = false ) {
805 global $wgArticleCountMethod;
807 if ( !$this->mTitle
->isContentPage() ) {
812 $content = $editInfo->pstContent
;
814 $content = $this->getContent();
817 if ( !$content ||
$content->isRedirect( ) ) {
823 if ( $wgArticleCountMethod === 'link' ) {
824 # nasty special case to avoid re-parsing to detect links
827 // ParserOutput::getLinks() is a 2D array of page links, so
828 // to be really correct we would need to recurse in the array
829 // but the main array should only have items in it if there are
831 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
833 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
834 array( 'pl_from' => $this->getId() ), __METHOD__
);
838 return $content->isCountable( $hasLinks );
842 * If this page is a redirect, get its target
844 * The target will be fetched from the redirect table if possible.
845 * If this page doesn't have an entry there, call insertRedirect()
846 * @return Title|mixed object, or null if this page is not a redirect
848 public function getRedirectTarget() {
849 if ( !$this->mTitle
->isRedirect() ) {
853 if ( $this->mRedirectTarget
!== null ) {
854 return $this->mRedirectTarget
;
857 # Query the redirect table
858 $dbr = wfGetDB( DB_SLAVE
);
859 $row = $dbr->selectRow( 'redirect',
860 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
861 array( 'rd_from' => $this->getId() ),
865 // rd_fragment and rd_interwiki were added later, populate them if empty
866 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
867 return $this->mRedirectTarget
= Title
::makeTitle(
868 $row->rd_namespace
, $row->rd_title
,
869 $row->rd_fragment
, $row->rd_interwiki
);
872 # This page doesn't have an entry in the redirect table
873 return $this->mRedirectTarget
= $this->insertRedirect();
877 * Insert an entry for this page into the redirect table.
879 * Don't call this function directly unless you know what you're doing.
880 * @return Title object or null if not a redirect
882 public function insertRedirect() {
883 // recurse through to only get the final target
884 $content = $this->getContent();
885 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
889 $this->insertRedirectEntry( $retval );
894 * Insert or update the redirect table entry for this page to indicate
895 * it redirects to $rt .
896 * @param $rt Title redirect target
898 public function insertRedirectEntry( $rt ) {
899 $dbw = wfGetDB( DB_MASTER
);
900 $dbw->replace( 'redirect', array( 'rd_from' ),
902 'rd_from' => $this->getId(),
903 'rd_namespace' => $rt->getNamespace(),
904 'rd_title' => $rt->getDBkey(),
905 'rd_fragment' => $rt->getFragment(),
906 'rd_interwiki' => $rt->getInterwiki(),
913 * Get the Title object or URL this page redirects to
915 * @return mixed false, Title of in-wiki target, or string with URL
917 public function followRedirect() {
918 return $this->getRedirectURL( $this->getRedirectTarget() );
922 * Get the Title object or URL to use for a redirect. We use Title
923 * objects for same-wiki, non-special redirects and URLs for everything
925 * @param $rt Title Redirect target
926 * @return mixed false, Title object of local target, or string with URL
928 public function getRedirectURL( $rt ) {
933 if ( $rt->isExternal() ) {
934 if ( $rt->isLocal() ) {
935 // Offsite wikis need an HTTP redirect.
937 // This can be hard to reverse and may produce loops,
938 // so they may be disabled in the site configuration.
939 $source = $this->mTitle
->getFullURL( 'redirect=no' );
940 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
942 // External pages pages without "local" bit set are not valid
948 if ( $rt->isSpecialPage() ) {
949 // Gotta handle redirects to special pages differently:
950 // Fill the HTTP response "Location" header and ignore
951 // the rest of the page we're on.
953 // Some pages are not valid targets
954 if ( $rt->isValidRedirectTarget() ) {
955 return $rt->getFullURL();
965 * Get a list of users who have edited this article, not including the user who made
966 * the most recent revision, which you can get from $article->getUser() if you want it
967 * @return UserArrayFromResult
969 public function getContributors() {
970 # @todo FIXME: This is expensive; cache this info somewhere.
972 $dbr = wfGetDB( DB_SLAVE
);
974 if ( $dbr->implicitGroupby() ) {
975 $realNameField = 'user_real_name';
977 $realNameField = 'MIN(user_real_name) AS user_real_name';
980 $tables = array( 'revision', 'user' );
983 'rev_user as user_id',
984 'rev_user_text AS user_name',
986 'MAX(rev_timestamp) AS timestamp',
989 $conds = array( 'rev_page' => $this->getId() );
991 // The user who made the top revision gets credited as "this page was last edited by
992 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
993 $user = $this->getUser();
995 $conds[] = "rev_user != $user";
997 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1000 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1003 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1007 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1008 'ORDER BY' => 'timestamp DESC',
1011 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1012 return new UserArrayFromResult( $res );
1016 * Get the last N authors
1017 * @param $num Integer: number of revisions to get
1018 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1019 * @return array Array of authors, duplicates not removed
1021 public function getLastNAuthors( $num, $revLatest = 0 ) {
1022 wfProfileIn( __METHOD__
);
1023 // First try the slave
1024 // If that doesn't have the latest revision, try the master
1026 $db = wfGetDB( DB_SLAVE
);
1029 $res = $db->select( array( 'page', 'revision' ),
1030 array( 'rev_id', 'rev_user_text' ),
1032 'page_namespace' => $this->mTitle
->getNamespace(),
1033 'page_title' => $this->mTitle
->getDBkey(),
1034 'rev_page = page_id'
1037 'ORDER BY' => 'rev_timestamp DESC',
1043 wfProfileOut( __METHOD__
);
1047 $row = $db->fetchObject( $res );
1049 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1050 $db = wfGetDB( DB_MASTER
);
1055 } while ( $continue );
1057 $authors = array( $row->rev_user_text
);
1059 foreach ( $res as $row ) {
1060 $authors[] = $row->rev_user_text
;
1063 wfProfileOut( __METHOD__
);
1068 * Should the parser cache be used?
1070 * @param $parserOptions ParserOptions to check
1074 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1075 global $wgEnableParserCache;
1077 return $wgEnableParserCache
1078 && $parserOptions->getStubThreshold() == 0
1079 && $this->mTitle
->exists()
1080 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1081 && $this->getContentHandler()->isParserCacheSupported();
1085 * Get a ParserOutput for the given ParserOptions and revision ID.
1086 * The parser cache will be used if possible.
1089 * @param $parserOptions ParserOptions to use for the parse operation
1090 * @param $oldid Revision ID to get the text from, passing null or 0 will
1091 * get the current revision (default value)
1093 * @return ParserOutput or false if the revision was not found
1095 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1096 wfProfileIn( __METHOD__
);
1098 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1099 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1100 if ( $parserOptions->getStubThreshold() ) {
1101 wfIncrStats( 'pcache_miss_stub' );
1104 if ( $useParserCache ) {
1105 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1106 if ( $parserOutput !== false ) {
1107 wfProfileOut( __METHOD__
);
1108 return $parserOutput;
1112 if ( $oldid === null ||
$oldid === 0 ) {
1113 $oldid = $this->getLatest();
1116 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache, null );
1119 wfProfileOut( __METHOD__
);
1121 return $pool->getParserOutput();
1125 * Do standard deferred updates after page view
1126 * @param $user User The relevant user
1128 public function doViewUpdates( User
$user ) {
1129 global $wgDisableCounters;
1130 if ( wfReadOnly() ) {
1134 # Don't update page view counters on views from bot users (bug 14044)
1135 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1136 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1137 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1140 # Update newtalk / watchlist notification status
1141 $user->clearNotification( $this->mTitle
);
1145 * Perform the actions of a page purging
1148 public function doPurge() {
1151 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1155 // Invalidate the cache
1156 $this->mTitle
->invalidateCache();
1159 if ( $wgUseSquid ) {
1160 // Commit the transaction before the purge is sent
1161 $dbw = wfGetDB( DB_MASTER
);
1162 $dbw->commit( __METHOD__
);
1165 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1166 $update->doUpdate();
1169 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1170 if ( $this->mTitle
->exists() ) {
1171 $text = ContentHandler
::getContentText( $this->getContent() );
1176 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1182 * Insert a new empty page record for this article.
1183 * This *must* be followed up by creating a revision
1184 * and running $this->updateRevisionOn( ... );
1185 * or else the record will be left in a funky state.
1186 * Best if all done inside a transaction.
1188 * @param $dbw DatabaseBase
1189 * @return int The newly created page_id key, or false if the title already existed
1191 public function insertOn( $dbw ) {
1192 wfProfileIn( __METHOD__
);
1194 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1195 $dbw->insert( 'page', array(
1196 'page_id' => $page_id,
1197 'page_namespace' => $this->mTitle
->getNamespace(),
1198 'page_title' => $this->mTitle
->getDBkey(),
1199 'page_counter' => 0,
1200 'page_restrictions' => '',
1201 'page_is_redirect' => 0, # Will set this shortly...
1203 'page_random' => wfRandom(),
1204 'page_touched' => $dbw->timestamp(),
1205 'page_latest' => 0, # Fill this in shortly...
1206 'page_len' => 0, # Fill this in shortly...
1207 ), __METHOD__
, 'IGNORE' );
1209 $affected = $dbw->affectedRows();
1212 $newid = $dbw->insertId();
1213 $this->mTitle
->resetArticleID( $newid );
1215 wfProfileOut( __METHOD__
);
1217 return $affected ?
$newid : false;
1221 * Update the page record to point to a newly saved revision.
1223 * @param $dbw DatabaseBase: object
1224 * @param $revision Revision: For ID number, and text used to set
1225 * length and redirect status fields
1226 * @param $lastRevision Integer: if given, will not overwrite the page field
1227 * when different from the currently set value.
1228 * Giving 0 indicates the new page flag should be set
1230 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1231 * removing rows in redirect table.
1232 * @return bool true on success, false on failure
1235 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1236 global $wgContentHandlerUseDB;
1238 wfProfileIn( __METHOD__
);
1240 $content = $revision->getContent();
1241 $len = $content->getSize();
1242 $rt = $content->getUltimateRedirectTarget();
1244 $conditions = array( 'page_id' => $this->getId() );
1246 if ( !is_null( $lastRevision ) ) {
1247 # An extra check against threads stepping on each other
1248 $conditions['page_latest'] = $lastRevision;
1251 $now = wfTimestampNow();
1252 $row = array( /* SET */
1253 'page_latest' => $revision->getId(),
1254 'page_touched' => $dbw->timestamp( $now ),
1255 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1256 'page_is_redirect' => $rt !== null ?
1 : 0,
1260 if ( $wgContentHandlerUseDB ) {
1261 $row[ 'page_content_model' ] = $revision->getContentModel();
1264 $dbw->update( 'page',
1269 $result = $dbw->affectedRows() != 0;
1271 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1272 $this->setLastEdit( $revision );
1273 $this->setCachedLastEditTime( $now );
1274 $this->mLatest
= $revision->getId();
1275 $this->mIsRedirect
= (bool)$rt;
1276 # Update the LinkCache.
1277 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1280 wfProfileOut( __METHOD__
);
1285 * Add row to the redirect table if this is a redirect, remove otherwise.
1287 * @param $dbw DatabaseBase
1288 * @param $redirectTitle Title object pointing to the redirect target,
1289 * or NULL if this is not a redirect
1290 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1291 * removing rows in redirect table.
1292 * @return bool true on success, false on failure
1295 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1296 // Always update redirects (target link might have changed)
1297 // Update/Insert if we don't know if the last revision was a redirect or not
1298 // Delete if changing from redirect to non-redirect
1299 $isRedirect = !is_null( $redirectTitle );
1301 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1305 wfProfileIn( __METHOD__
);
1306 if ( $isRedirect ) {
1307 $this->insertRedirectEntry( $redirectTitle );
1309 // This is not a redirect, remove row from redirect table
1310 $where = array( 'rd_from' => $this->getId() );
1311 $dbw->delete( 'redirect', $where, __METHOD__
);
1314 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1315 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1317 wfProfileOut( __METHOD__
);
1319 return ( $dbw->affectedRows() != 0 );
1323 * If the given revision is newer than the currently set page_latest,
1324 * update the page record. Otherwise, do nothing.
1326 * @param $dbw DatabaseBase object
1327 * @param $revision Revision object
1330 public function updateIfNewerOn( $dbw, $revision ) {
1331 wfProfileIn( __METHOD__
);
1333 $row = $dbw->selectRow(
1334 array( 'revision', 'page' ),
1335 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1337 'page_id' => $this->getId(),
1338 'page_latest=rev_id' ),
1342 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1343 wfProfileOut( __METHOD__
);
1346 $prev = $row->rev_id
;
1347 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1349 # No or missing previous revision; mark the page as new
1351 $lastRevIsRedirect = null;
1354 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1356 wfProfileOut( __METHOD__
);
1361 * Get the text that needs to be saved in order to undo all revisions
1362 * between $undo and $undoafter. Revisions must belong to the same page,
1363 * must exist and must not be deleted
1364 * @param $undo Revision
1365 * @param $undoafter Revision Must be an earlier revision than $undo
1366 * @return mixed string on success, false on failure
1367 * @deprecated since 1.WD: use ContentHandler::getUndoContent() instead.
1369 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1370 wfDeprecated( __METHOD__
, '1.WD' );
1372 $this->loadLastEdit();
1374 if ( $this->mLastRevision
) {
1375 if ( is_null( $undoafter ) ) {
1376 $undoafter = $undo->getPrevious();
1379 $handler = $this->getContentHandler();
1380 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1385 return ContentHandler
::getContentText( $undone );
1393 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1394 * @param $text String: new text of the section
1395 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1396 * @param $edittime String: revision timestamp or null to use the current revision
1397 * @return String new complete article text, or null if error
1399 * @deprecated since 1.WD, use replaceSectionContent() instead
1401 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1402 wfDeprecated( __METHOD__
, '1.WD' );
1404 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1406 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1408 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1412 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1413 * @param $content Content: new content of the section
1414 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1415 * @param $edittime String: revision timestamp or null to use the current revision
1417 * @return Content new complete article content, or null if error
1421 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1422 wfProfileIn( __METHOD__
);
1424 if ( strval( $section ) == '' ) {
1425 // Whole-page edit; let the whole text through
1426 $newContent = $sectionContent;
1428 // Bug 30711: always use current version when adding a new section
1429 if ( is_null( $edittime ) ||
$section == 'new' ) {
1430 $oldContent = $this->getContent();
1431 if ( ! $oldContent ) {
1432 wfDebug( __METHOD__
. ": no page text\n" );
1433 wfProfileOut( __METHOD__
);
1437 $dbw = wfGetDB( DB_MASTER
);
1438 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1441 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1442 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1443 wfProfileOut( __METHOD__
);
1447 $oldContent = $rev->getContent();
1450 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1453 wfProfileOut( __METHOD__
);
1458 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1460 * @return Int updated $flags
1462 function checkFlags( $flags ) {
1463 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1464 if ( $this->mTitle
->getArticleID() ) {
1465 $flags |
= EDIT_UPDATE
;
1475 * Change an existing article or create a new article. Updates RC and all necessary caches,
1476 * optionally via the deferred update array.
1478 * @param $text String: new text
1479 * @param $summary String: edit summary
1480 * @param $flags Integer bitfield:
1482 * Article is known or assumed to be non-existent, create a new one
1484 * Article is known or assumed to be pre-existing, update it
1486 * Mark this edit minor, if the user is allowed to do so
1488 * Do not log the change in recentchanges
1490 * Mark the edit a "bot" edit regardless of user rights
1491 * EDIT_DEFER_UPDATES
1492 * Defer some of the updates until the end of index.php
1494 * Fill in blank summaries with generated text where possible
1496 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1497 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1498 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1499 * edit-already-exists error will be returned. These two conditions are also possible with
1500 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1502 * @param $baseRevId int the revision ID this edit was based off, if any
1503 * @param $user User the user doing the edit
1505 * @return Status object. Possible errors:
1506 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1507 * edit-gone-missing: In update mode, but the article didn't exist
1508 * edit-conflict: In update mode, the article changed unexpectedly
1509 * edit-no-change: Warning that the text was the same as before
1510 * edit-already-exists: In creation mode, but the article already exists
1512 * Extensions may define additional errors.
1514 * $return->value will contain an associative array with members as follows:
1515 * new: Boolean indicating if the function attempted to create a new article
1516 * revision: The revision object for the inserted revision, or null
1518 * Compatibility note: this function previously returned a boolean value indicating success/failure
1520 * @deprecated since 1.WD: use doEditContent() instead.
1522 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #@todo: use doEditContent() instead
1523 wfDeprecated( __METHOD__
, '1.WD' );
1525 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1527 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1531 * Change an existing article or create a new article. Updates RC and all necessary caches,
1532 * optionally via the deferred update array.
1534 * @param $content Content: new content
1535 * @param $summary String: edit summary
1536 * @param $flags Integer bitfield:
1538 * Article is known or assumed to be non-existent, create a new one
1540 * Article is known or assumed to be pre-existing, update it
1542 * Mark this edit minor, if the user is allowed to do so
1544 * Do not log the change in recentchanges
1546 * Mark the edit a "bot" edit regardless of user rights
1547 * EDIT_DEFER_UPDATES
1548 * Defer some of the updates until the end of index.php
1550 * Fill in blank summaries with generated text where possible
1552 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1553 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1554 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1555 * edit-already-exists error will be returned. These two conditions are also possible with
1556 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1558 * @param $baseRevId the revision ID this edit was based off, if any
1559 * @param $user User the user doing the edit
1560 * @param $serialisation_format String: format for storing the content in the database
1562 * @return Status object. Possible errors:
1563 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1564 * edit-gone-missing: In update mode, but the article didn't exist
1565 * edit-conflict: In update mode, the article changed unexpectedly
1566 * edit-no-change: Warning that the text was the same as before
1567 * edit-already-exists: In creation mode, but the article already exists
1569 * Extensions may define additional errors.
1571 * $return->value will contain an associative array with members as follows:
1572 * new: Boolean indicating if the function attempted to create a new article
1573 * revision: The revision object for the inserted revision, or null
1577 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1578 User
$user = null, $serialisation_format = null ) {
1579 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1581 # Low-level sanity check
1582 if ( $this->mTitle
->getText() === '' ) {
1583 throw new MWException( 'Something is trying to edit an article with an empty title' );
1586 wfProfileIn( __METHOD__
);
1588 $user = is_null( $user ) ?
$wgUser : $user;
1589 $status = Status
::newGood( array() );
1591 // Load the data from the master database if needed.
1592 // The caller may already loaded it from the master or even loaded it using
1593 // SELECT FOR UPDATE, so do not override that using clear().
1594 $this->loadPageData( 'fromdbmaster' );
1596 $flags = $this->checkFlags( $flags );
1599 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary,
1600 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1602 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { # avoid serialization overhead if the hook isn't present
1603 $content_text = $content->serialize();
1604 $txt = $content_text; # clone
1606 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary,
1607 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1609 if ( $txt !== $content_text ) {
1610 # if the text changed, unserialize the new version to create an updated Content object.
1611 $content = $content->getContentHandler()->unserializeContent( $txt );
1616 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1618 if ( $status->isOK() ) {
1619 $status->fatal( 'edit-hook-aborted' );
1622 wfProfileOut( __METHOD__
);
1626 # Silently ignore EDIT_MINOR if not allowed
1627 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1628 $bot = $flags & EDIT_FORCE_BOT
;
1630 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1632 $oldsize = $old_content ?
$old_content->getSize() : 0;
1633 $oldid = $this->getLatest();
1634 $oldIsRedirect = $this->isRedirect();
1635 $oldcountable = $this->isCountable();
1637 $handler = $content->getContentHandler();
1639 # Provide autosummaries if one is not provided and autosummaries are enabled.
1640 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1641 if ( !$old_content ) $old_content = null;
1642 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1645 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1646 $serialized = $editInfo->pst
;
1647 $content = $editInfo->pstContent
;
1648 $newsize = $content->getSize();
1650 $dbw = wfGetDB( DB_MASTER
);
1651 $now = wfTimestampNow();
1652 $this->mTimestamp
= $now;
1654 if ( $flags & EDIT_UPDATE
) {
1655 # Update article, but only if changed.
1656 $status->value
['new'] = false;
1659 # Article gone missing
1660 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1661 $status->fatal( 'edit-gone-missing' );
1663 wfProfileOut( __METHOD__
);
1667 # Make sure the revision is either completely inserted or not inserted at all
1668 if ( !$wgDBtransactions ) {
1669 $userAbort = ignore_user_abort( true );
1672 $revision = new Revision( array(
1673 'page' => $this->getId(),
1674 'comment' => $summary,
1675 'minor_edit' => $isminor,
1676 'text' => $serialized,
1678 'parent_id' => $oldid,
1679 'user' => $user->getId(),
1680 'user_text' => $user->getName(),
1681 'timestamp' => $now,
1682 'content_model' => $content->getModel(),
1683 'content_format' => $serialisation_format,
1686 $changed = !$content->equals( $old_content );
1690 if ( $content->isValid() ) {
1694 $dbw->begin( __METHOD__
);
1695 $revisionId = $revision->insertOn( $dbw );
1699 # Note that we use $this->mLatest instead of fetching a value from the master DB
1700 # during the course of this function. This makes sure that EditPage can detect
1701 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1702 # before this function is called. A previous function used a separate query, this
1703 # creates a window where concurrent edits can cause an ignored edit conflict.
1704 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1707 /* Belated edit conflict! Run away!! */
1708 $status->fatal( 'edit-conflict' );
1710 # Delete the invalid revision if the DB is not transactional
1711 if ( !$wgDBtransactions ) {
1712 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1716 $dbw->rollback( __METHOD__
);
1718 global $wgUseRCPatrol;
1719 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1720 # Update recentchanges
1721 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1722 # Mark as patrolled if the user can do so
1723 $patrolled = $wgUseRCPatrol && !count(
1724 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1725 # Add RC row to the DB
1726 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1727 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1728 $revisionId, $patrolled
1731 # Log auto-patrolled edits
1733 PatrolLog
::record( $rc, true, $user );
1736 $user->incEditCount();
1737 $dbw->commit( __METHOD__
);
1740 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1741 // related variables correctly
1742 $revision->setId( $this->getLatest() );
1745 if ( !$wgDBtransactions ) {
1746 ignore_user_abort( $userAbort );
1749 // Now that ignore_user_abort is restored, we can respond to fatal errors
1750 if ( !$status->isOK() ) {
1751 wfProfileOut( __METHOD__
);
1755 // TODO: create content diff to pass to update objects that might need it
1757 # Update links tables, site stats, etc.
1758 $this->doEditUpdates(
1762 'changed' => $changed,
1763 'oldcountable' => $oldcountable
1768 $status->warning( 'edit-no-change' );
1770 // Update page_touched, this is usually implicit in the page update
1771 // Other cache updates are done in onArticleEdit()
1772 $this->mTitle
->invalidateCache();
1775 # Create new article
1776 $status->value
['new'] = true;
1778 $dbw->begin( __METHOD__
);
1780 # Add the page record; stake our claim on this title!
1781 # This will return false if the article already exists
1782 $newid = $this->insertOn( $dbw );
1784 if ( $newid === false ) {
1785 $dbw->rollback( __METHOD__
);
1786 $status->fatal( 'edit-already-exists' );
1788 wfProfileOut( __METHOD__
);
1792 # Save the revision text...
1793 $revision = new Revision( array(
1795 'comment' => $summary,
1796 'minor_edit' => $isminor,
1797 'text' => $serialized,
1799 'user' => $user->getId(),
1800 'user_text' => $user->getName(),
1801 'timestamp' => $now,
1802 'content_model' => $content->getModel(),
1803 'content_format' => $serialisation_format,
1805 $revisionId = $revision->insertOn( $dbw );
1807 # Update the page record with revision data
1808 $this->updateRevisionOn( $dbw, $revision, 0 );
1810 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1812 # Update recentchanges
1813 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1814 global $wgUseRCPatrol, $wgUseNPPatrol;
1816 # Mark as patrolled if the user can do so
1817 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1818 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1819 # Add RC row to the DB
1820 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1821 '', $content->getSize(), $revisionId, $patrolled );
1823 # Log auto-patrolled edits
1825 PatrolLog
::record( $rc, true, $user );
1828 $user->incEditCount();
1829 $dbw->commit( __METHOD__
);
1831 # Update links, etc.
1832 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1834 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary,
1835 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1837 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary,
1838 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1841 # Do updates right now unless deferral was requested
1842 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1843 DeferredUpdates
::doUpdates();
1846 // Return the new revision (or null) to the caller
1847 $status->value
['revision'] = $revision;
1849 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary,
1850 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1852 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary,
1853 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1855 # Promote user to any groups they meet the criteria for
1856 $user->addAutopromoteOnceGroups( 'onEdit' );
1858 wfProfileOut( __METHOD__
);
1863 * Get parser options suitable for rendering the primary article wikitext
1864 * @param User|string $user User object or 'canonical'
1865 * @return ParserOptions
1867 public function makeParserOptions( $user ) {
1869 if ( $user instanceof User
) { // settings per user (even anons)
1870 $options = ParserOptions
::newFromUser( $user );
1871 } else { // canonical settings
1872 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1874 $options->enableLimitReport(); // show inclusion/loop reports
1875 $options->setTidy( true ); // fix bad HTML
1880 * Prepare text which is about to be saved.
1881 * Returns a stdclass with source, pst and output members
1883 * @deprecated in 1.WD: use prepareContentForEdit instead.
1885 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1886 wfDeprecated( __METHOD__
, '1.WD' );
1887 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1888 return $this->prepareContentForEdit( $content, $revid , $user );
1892 * Prepare content which is about to be saved.
1893 * Returns a stdclass with source, pst and output members
1895 * @param \Content $content
1896 * @param null $revid
1897 * @param null|\User $user
1898 * @param null $serialization_format
1900 * @return bool|object
1904 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) {
1905 global $wgParser, $wgContLang, $wgUser;
1906 $user = is_null( $user ) ?
$wgUser : $user;
1907 // @TODO fixme: check $user->getId() here???
1909 if ( $this->mPreparedEdit
1910 && $this->mPreparedEdit
->newContent
1911 && $this->mPreparedEdit
->newContent
->equals( $content )
1912 && $this->mPreparedEdit
->revid
== $revid
1913 && $this->mPreparedEdit
->format
== $serialization_format
1914 #XXX: also check $user here?
1917 return $this->mPreparedEdit
;
1920 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1921 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1923 $edit = (object)array();
1924 $edit->revid
= $revid;
1926 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1927 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1928 $edit->format
= $serialization_format;
1930 $edit->popts
= $this->makeParserOptions( 'canonical' );
1932 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1934 $edit->newContent
= $content;
1935 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1937 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1938 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1940 $this->mPreparedEdit
= $edit;
1946 * Do standard deferred updates after page edit.
1947 * Update links tables, site stats, search index and message cache.
1948 * Purges pages that include this page if the text was changed here.
1949 * Every 100th edit, prune the recent changes table.
1951 * @param $revision Revision object
1952 * @param $user User object that did the revision
1953 * @param $options Array of options, following indexes are used:
1954 * - changed: boolean, whether the revision changed the content (default true)
1955 * - created: boolean, whether the revision created the page (default false)
1956 * - oldcountable: boolean or null (default null):
1957 * - boolean: whether the page was counted as an article before that
1958 * revision, only used in changed is true and created is false
1959 * - null: don't change the article count
1961 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1962 global $wgEnableParserCache;
1964 wfProfileIn( __METHOD__
);
1966 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1967 $content = $revision->getContent();
1970 # Be careful not to double-PST: $text is usually already PST-ed once
1971 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1972 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1973 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1975 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1976 $editInfo = $this->mPreparedEdit
;
1979 # Save it to the parser cache
1980 if ( $wgEnableParserCache ) {
1981 $parserCache = ParserCache
::singleton();
1982 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1985 # Update the links tables and other secondary data
1986 $updates = $editInfo->output
->getSecondaryDataUpdates( $this->getTitle() );
1987 DataUpdate
::runUpdates( $updates );
1989 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1991 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1992 if ( 0 == mt_rand( 0, 99 ) ) {
1993 // Flush old entries from the `recentchanges` table; we do this on
1994 // random requests so as to avoid an increase in writes for no good reason
1997 $dbw = wfGetDB( DB_MASTER
);
1998 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2001 array( "rc_timestamp < '$cutoff'" ),
2007 if ( !$this->mTitle
->exists() ) {
2008 wfProfileOut( __METHOD__
);
2012 $id = $this->getId();
2013 $title = $this->mTitle
->getPrefixedDBkey();
2014 $shortTitle = $this->mTitle
->getDBkey();
2016 if ( !$options['changed'] ) {
2019 } elseif ( $options['created'] ) {
2020 $good = (int)$this->isCountable( $editInfo );
2022 } elseif ( $options['oldcountable'] !== null ) {
2023 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2030 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2031 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
2033 # If this is another user's talk page, update newtalk.
2034 # Don't do this if $options['changed'] = false (null-edits) nor if
2035 # it's a minor edit and the user doesn't want notifications for those.
2036 if ( $options['changed']
2037 && $this->mTitle
->getNamespace() == NS_USER_TALK
2038 && $shortTitle != $user->getTitleKey()
2039 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2041 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2042 $other = User
::newFromName( $shortTitle, false );
2044 wfDebug( __METHOD__
. ": invalid username\n" );
2045 } elseif ( User
::isIP( $shortTitle ) ) {
2046 // An anonymous user
2047 $other->setNewtalk( true );
2048 } elseif ( $other->isLoggedIn() ) {
2049 $other->setNewtalk( true );
2051 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2056 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2057 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
2058 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
2060 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2063 if( $options['created'] ) {
2064 self
::onArticleCreate( $this->mTitle
);
2066 self
::onArticleEdit( $this->mTitle
);
2069 wfProfileOut( __METHOD__
);
2073 * Edit an article without doing all that other stuff
2074 * The article must already exist; link tables etc
2075 * are not updated, caches are not flushed.
2077 * @param $text String: text submitted
2078 * @param $user User The relevant user
2079 * @param $comment String: comment submitted
2080 * @param $minor Boolean: whereas it's a minor modification
2082 * @deprecated since 1.WD, use doEditContent() instead.
2084 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2085 wfDeprecated( __METHOD__
, "1.WD" );
2087 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2088 return $this->doQuickEditContent( $content, $user, $comment , $minor );
2092 * Edit an article without doing all that other stuff
2093 * The article must already exist; link tables etc
2094 * are not updated, caches are not flushed.
2096 * @param $content Content: content submitted
2097 * @param $user User The relevant user
2098 * @param $comment String: comment submitted
2099 * @param $serialisation_format String: format for storing the content in the database
2100 * @param $minor Boolean: whereas it's a minor modification
2102 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
2103 wfProfileIn( __METHOD__
);
2105 $serialized = $content->serialize( $serialisation_format );
2107 $dbw = wfGetDB( DB_MASTER
);
2108 $revision = new Revision( array(
2109 'page' => $this->getId(),
2110 'text' => $serialized,
2111 'length' => $content->getSize(),
2112 'comment' => $comment,
2113 'minor_edit' => $minor ?
1 : 0,
2115 $revision->insertOn( $dbw );
2116 $this->updateRevisionOn( $dbw, $revision );
2118 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2120 wfProfileOut( __METHOD__
);
2124 * Update the article's restriction field, and leave a log entry.
2125 * This works for protection both existing and non-existing pages.
2127 * @param $limit Array: set of restriction keys
2128 * @param $reason String
2129 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2130 * @param $expiry Array: per restriction type expiration
2131 * @param $user User The user updating the restrictions
2134 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2137 if ( wfReadOnly() ) {
2138 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2141 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2143 $id = $this->mTitle
->getArticleID();
2149 // Take this opportunity to purge out expired restrictions
2150 Title
::purgeExpiredRestrictions();
2152 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2153 # we expect a single selection, but the schema allows otherwise.
2154 $isProtected = false;
2158 $dbw = wfGetDB( DB_MASTER
);
2160 foreach ( $restrictionTypes as $action ) {
2161 if ( !isset( $expiry[$action] ) ) {
2162 $expiry[$action] = $dbw->getInfinity();
2164 if ( !isset( $limit[$action] ) ) {
2165 $limit[$action] = '';
2166 } elseif ( $limit[$action] != '' ) {
2170 # Get current restrictions on $action
2171 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2172 if ( $current != '' ) {
2173 $isProtected = true;
2176 if ( $limit[$action] != $current ) {
2178 } elseif ( $limit[$action] != '' ) {
2179 # Only check expiry change if the action is actually being
2180 # protected, since expiry does nothing on an not-protected
2182 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2188 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2192 # If nothing's changed, do nothing
2194 return Status
::newGood();
2197 if ( !$protect ) { # No protection at all means unprotection
2198 $revCommentMsg = 'unprotectedarticle';
2199 $logAction = 'unprotect';
2200 } elseif ( $isProtected ) {
2201 $revCommentMsg = 'modifiedarticleprotection';
2202 $logAction = 'modify';
2204 $revCommentMsg = 'protectedarticle';
2205 $logAction = 'protect';
2208 $encodedExpiry = array();
2209 $protectDescription = '';
2210 foreach ( $limit as $action => $restrictions ) {
2211 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2212 if ( $restrictions != '' ) {
2213 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2214 if ( $encodedExpiry[$action] != 'infinity' ) {
2215 $protectDescription .= wfMsgForContent( 'protect-expiring',
2216 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2217 $wgContLang->date( $expiry[$action], false, false ) ,
2218 $wgContLang->time( $expiry[$action], false, false ) );
2220 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
2223 $protectDescription .= ') ';
2226 $protectDescription = trim( $protectDescription );
2228 if ( $id ) { # Protection of existing page
2229 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2230 return Status
::newGood();
2233 # Only restrictions with the 'protect' right can cascade...
2234 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2235 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2237 # The schema allows multiple restrictions
2238 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2242 # Update restrictions table
2243 foreach ( $limit as $action => $restrictions ) {
2244 if ( $restrictions != '' ) {
2245 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2246 array( 'pr_page' => $id,
2247 'pr_type' => $action,
2248 'pr_level' => $restrictions,
2249 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2250 'pr_expiry' => $encodedExpiry[$action]
2255 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2256 'pr_type' => $action ), __METHOD__
);
2260 # Prepare a null revision to be added to the history
2261 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2263 $editComment .= ": $reason";
2265 if ( $protectDescription ) {
2266 $editComment .= " ($protectDescription)";
2269 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2272 # Insert a null revision
2273 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2274 $nullRevId = $nullRevision->insertOn( $dbw );
2276 $latest = $this->getLatest();
2277 # Update page record
2278 $dbw->update( 'page',
2280 'page_touched' => $dbw->timestamp(),
2281 'page_restrictions' => '',
2282 'page_latest' => $nullRevId
2283 ), array( /* WHERE */
2288 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2289 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2290 } else { # Protection of non-existing page (also known as "title protection")
2291 # Cascade protection is meaningless in this case
2294 if ( $limit['create'] != '' ) {
2295 $dbw->replace( 'protected_titles',
2296 array( array( 'pt_namespace', 'pt_title' ) ),
2298 'pt_namespace' => $this->mTitle
->getNamespace(),
2299 'pt_title' => $this->mTitle
->getDBkey(),
2300 'pt_create_perm' => $limit['create'],
2301 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2302 'pt_expiry' => $encodedExpiry['create'],
2303 'pt_user' => $user->getId(),
2304 'pt_reason' => $reason,
2308 $dbw->delete( 'protected_titles',
2310 'pt_namespace' => $this->mTitle
->getNamespace(),
2311 'pt_title' => $this->mTitle
->getDBkey()
2317 $this->mTitle
->flushRestrictions();
2319 if ( $logAction == 'unprotect' ) {
2320 $logParams = array();
2322 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2325 # Update the protection log
2326 $log = new LogPage( 'protect' );
2327 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2329 return Status
::newGood();
2333 * Take an array of page restrictions and flatten it to a string
2334 * suitable for insertion into the page_restrictions field.
2335 * @param $limit Array
2338 protected static function flattenRestrictions( $limit ) {
2339 if ( !is_array( $limit ) ) {
2340 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2346 foreach ( $limit as $action => $restrictions ) {
2347 if ( $restrictions != '' ) {
2348 $bits[] = "$action=$restrictions";
2352 return implode( ':', $bits );
2356 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2357 * Deletes the article with database consistency, writes logs, purges caches
2359 * @param $reason string delete reason for deletion log
2360 * @param $suppress int bitfield
2361 * Revision::DELETED_TEXT
2362 * Revision::DELETED_COMMENT
2363 * Revision::DELETED_USER
2364 * Revision::DELETED_RESTRICTED
2365 * @param $id int article ID
2366 * @param $commit boolean defaults to true, triggers transaction end
2367 * @param &$error Array of errors to append to
2368 * @param $user User The deleting user
2369 * @return boolean true if successful
2371 public function doDeleteArticle(
2372 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2374 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2375 == WikiPage
::DELETE_SUCCESS
;
2379 * Back-end article deletion
2380 * Deletes the article with database consistency, writes logs, purges caches
2382 * @param $reason string delete reason for deletion log
2383 * @param $suppress int bitfield
2384 * Revision::DELETED_TEXT
2385 * Revision::DELETED_COMMENT
2386 * Revision::DELETED_USER
2387 * Revision::DELETED_RESTRICTED
2388 * @param $id int article ID
2389 * @param $commit boolean defaults to true, triggers transaction end
2390 * @param &$error Array of errors to append to
2391 * @param $user User The deleting user
2392 * @return int: One of WikiPage::DELETE_* constants
2394 public function doDeleteArticleReal(
2395 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2397 global $wgUser, $wgContentHandlerUseDB;
2399 wfDebug( __METHOD__
. "\n" );
2401 if ( $this->mTitle
->getDBkey() === '' ) {
2402 return WikiPage
::DELETE_NO_PAGE
;
2405 $user = is_null( $user ) ?
$wgUser : $user;
2406 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2407 return WikiPage
::DELETE_HOOK_ABORTED
;
2411 $this->loadPageData( 'forupdate' );
2412 $id = $this->getID();
2414 return WikiPage
::DELETE_NO_PAGE
;
2418 // Bitfields to further suppress the content
2421 // This should be 15...
2422 $bitfield |
= Revision
::DELETED_TEXT
;
2423 $bitfield |
= Revision
::DELETED_COMMENT
;
2424 $bitfield |
= Revision
::DELETED_USER
;
2425 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2427 $bitfield = 'rev_deleted';
2430 $dbw = wfGetDB( DB_MASTER
);
2431 $dbw->begin( __METHOD__
);
2432 // For now, shunt the revision data into the archive table.
2433 // Text is *not* removed from the text table; bulk storage
2434 // is left intact to avoid breaking block-compression or
2435 // immutable storage schemes.
2437 // For backwards compatibility, note that some older archive
2438 // table entries will have ar_text and ar_flags fields still.
2440 // In the future, we may keep revisions and mark them with
2441 // the rev_deleted field, which is reserved for this purpose.
2444 'ar_namespace' => 'page_namespace',
2445 'ar_title' => 'page_title',
2446 'ar_comment' => 'rev_comment',
2447 'ar_user' => 'rev_user',
2448 'ar_user_text' => 'rev_user_text',
2449 'ar_timestamp' => 'rev_timestamp',
2450 'ar_minor_edit' => 'rev_minor_edit',
2451 'ar_rev_id' => 'rev_id',
2452 'ar_parent_id' => 'rev_parent_id',
2453 'ar_text_id' => 'rev_text_id',
2454 'ar_text' => '\'\'', // Be explicit to appease
2455 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2456 'ar_len' => 'rev_len',
2457 'ar_page_id' => 'page_id',
2458 'ar_deleted' => $bitfield,
2459 'ar_sha1' => 'rev_sha1',
2462 if ( $wgContentHandlerUseDB ) {
2463 $row[ 'ar_content_model' ] = 'rev_content_model';
2464 $row[ 'ar_content_format' ] = 'rev_content_format';
2467 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2471 'page_id = rev_page'
2475 # Now that it's safely backed up, delete it
2476 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2477 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2480 $dbw->rollback( __METHOD__
);
2481 return WikiPage
::DELETE_NO_REVISIONS
;
2484 $this->doDeleteUpdates( $id );
2486 # Log the deletion, if the page was suppressed, log it at Oversight instead
2487 $logtype = $suppress ?
'suppress' : 'delete';
2489 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2490 $logEntry->setPerformer( $user );
2491 $logEntry->setTarget( $this->mTitle
);
2492 $logEntry->setComment( $reason );
2493 $logid = $logEntry->insert();
2494 $logEntry->publish( $logid );
2497 $dbw->commit( __METHOD__
);
2500 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2501 return WikiPage
::DELETE_SUCCESS
;
2505 * Do some database updates after deletion
2507 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2509 public function doDeleteUpdates( $id ) {
2510 # update site status
2511 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2513 # remove secondary indexes, etc
2514 $updates = $this->getDeletionUpdates( );
2515 DataUpdate
::runUpdates( $updates );
2518 WikiPage
::onArticleDelete( $this->mTitle
);
2523 # Clear the cached article id so the interface doesn't act like we exist
2524 $this->mTitle
->resetArticleID( 0 );
2528 * Roll back the most recent consecutive set of edits to a page
2529 * from the same user; fails if there are no eligible edits to
2530 * roll back to, e.g. user is the sole contributor. This function
2531 * performs permissions checks on $user, then calls commitRollback()
2532 * to do the dirty work
2534 * @todo: seperate the business/permission stuff out from backend code
2536 * @param $fromP String: Name of the user whose edits to rollback.
2537 * @param $summary String: Custom summary. Set to default summary if empty.
2538 * @param $token String: Rollback token.
2539 * @param $bot Boolean: If true, mark all reverted edits as bot.
2541 * @param $resultDetails Array: contains result-specific array of additional values
2542 * 'alreadyrolled' : 'current' (rev)
2543 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2545 * @param $user User The user performing the rollback
2546 * @return array of errors, each error formatted as
2547 * array(messagekey, param1, param2, ...).
2548 * On success, the array is empty. This array can also be passed to
2549 * OutputPage::showPermissionsErrorPage().
2551 public function doRollback(
2552 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2554 $resultDetails = null;
2557 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2558 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2559 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2561 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2562 $errors[] = array( 'sessionfailure' );
2565 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2566 $errors[] = array( 'actionthrottledtext' );
2569 # If there were errors, bail out now
2570 if ( !empty( $errors ) ) {
2574 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2578 * Backend implementation of doRollback(), please refer there for parameter
2579 * and return value documentation
2581 * NOTE: This function does NOT check ANY permissions, it just commits the
2582 * rollback to the DB. Therefore, you should only call this function direct-
2583 * ly if you want to use custom permissions checks. If you don't, use
2584 * doRollback() instead.
2585 * @param $fromP String: Name of the user whose edits to rollback.
2586 * @param $summary String: Custom summary. Set to default summary if empty.
2587 * @param $bot Boolean: If true, mark all reverted edits as bot.
2589 * @param $resultDetails Array: contains result-specific array of additional values
2590 * @param $guser User The user performing the rollback
2593 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2594 global $wgUseRCPatrol, $wgContLang;
2596 $dbw = wfGetDB( DB_MASTER
);
2598 if ( wfReadOnly() ) {
2599 return array( array( 'readonlytext' ) );
2602 # Get the last editor
2603 $current = $this->getRevision();
2604 if ( is_null( $current ) ) {
2605 # Something wrong... no page?
2606 return array( array( 'notanarticle' ) );
2609 $from = str_replace( '_', ' ', $fromP );
2610 # User name given should match up with the top revision.
2611 # If the user was deleted then $from should be empty.
2612 if ( $from != $current->getUserText() ) {
2613 $resultDetails = array( 'current' => $current );
2614 return array( array( 'alreadyrolled',
2615 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2616 htmlspecialchars( $fromP ),
2617 htmlspecialchars( $current->getUserText() )
2621 # Get the last edit not by this guy...
2622 # Note: these may not be public values
2623 $user = intval( $current->getRawUser() );
2624 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2625 $s = $dbw->selectRow( 'revision',
2626 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2627 array( 'rev_page' => $current->getPage(),
2628 "rev_user != {$user} OR rev_user_text != {$user_text}"
2630 array( 'USE INDEX' => 'page_timestamp',
2631 'ORDER BY' => 'rev_timestamp DESC' )
2633 if ( $s === false ) {
2634 # No one else ever edited this page
2635 return array( array( 'cantrollback' ) );
2636 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2637 # Only admins can see this text
2638 return array( array( 'notvisiblerev' ) );
2642 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2643 # Mark all reverted edits as bot
2647 if ( $wgUseRCPatrol ) {
2648 # Mark all reverted edits as patrolled
2649 $set['rc_patrolled'] = 1;
2652 if ( count( $set ) ) {
2653 $dbw->update( 'recentchanges', $set,
2655 'rc_cur_id' => $current->getPage(),
2656 'rc_user_text' => $current->getUserText(),
2657 "rc_timestamp > '{$s->rev_timestamp}'",
2662 # Generate the edit summary if necessary
2663 $target = Revision
::newFromId( $s->rev_id
);
2664 if ( empty( $summary ) ) {
2665 if ( $from == '' ) { // no public user name
2666 $summary = wfMsgForContent( 'revertpage-nouser' );
2668 $summary = wfMsgForContent( 'revertpage' );
2672 # Allow the custom summary to use the same args as the default message
2674 $target->getUserText(), $from, $s->rev_id
,
2675 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2676 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2678 $summary = wfMsgReplaceArgs( $summary, $args );
2681 $flags = EDIT_UPDATE
;
2683 if ( $guser->isAllowed( 'minoredit' ) ) {
2684 $flags |
= EDIT_MINOR
;
2687 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2688 $flags |
= EDIT_FORCE_BOT
;
2691 # Actually store the edit
2692 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2693 if ( !empty( $status->value
['revision'] ) ) {
2694 $revId = $status->value
['revision']->getId();
2699 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2701 $resultDetails = array(
2702 'summary' => $summary,
2703 'current' => $current,
2704 'target' => $target,
2712 * The onArticle*() functions are supposed to be a kind of hooks
2713 * which should be called whenever any of the specified actions
2716 * This is a good place to put code to clear caches, for instance.
2718 * This is called on page move and undelete, as well as edit
2720 * @param $title Title object
2722 public static function onArticleCreate( $title ) {
2723 # Update existence markers on article/talk tabs...
2724 if ( $title->isTalkPage() ) {
2725 $other = $title->getSubjectPage();
2727 $other = $title->getTalkPage();
2730 $other->invalidateCache();
2731 $other->purgeSquid();
2733 $title->touchLinks();
2734 $title->purgeSquid();
2735 $title->deleteTitleProtection();
2739 * Clears caches when article is deleted
2741 * @param $title Title
2743 public static function onArticleDelete( $title ) {
2744 # Update existence markers on article/talk tabs...
2745 if ( $title->isTalkPage() ) {
2746 $other = $title->getSubjectPage();
2748 $other = $title->getTalkPage();
2751 $other->invalidateCache();
2752 $other->purgeSquid();
2754 $title->touchLinks();
2755 $title->purgeSquid();
2758 HTMLFileCache
::clearFileCache( $title );
2761 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2762 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2766 if ( $title->getNamespace() == NS_FILE
) {
2767 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2768 $update->doUpdate();
2772 if ( $title->getNamespace() == NS_USER_TALK
) {
2773 $user = User
::newFromName( $title->getText(), false );
2775 $user->setNewtalk( false );
2780 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2784 * Purge caches on page update etc
2786 * @param $title Title object
2787 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2789 public static function onArticleEdit( $title ) {
2790 // Invalidate caches of articles which include this page
2791 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2794 // Invalidate the caches of all pages which redirect here
2795 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2797 # Purge squid for this page only
2798 $title->purgeSquid();
2800 # Clear file cache for this page only
2801 HTMLFileCache
::clearFileCache( $title );
2807 * Returns a list of hidden categories this page is a member of.
2808 * Uses the page_props and categorylinks tables.
2810 * @return Array of Title objects
2812 public function getHiddenCategories() {
2814 $id = $this->mTitle
->getArticleID();
2820 $dbr = wfGetDB( DB_SLAVE
);
2821 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2823 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2824 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2827 if ( $res !== false ) {
2828 foreach ( $res as $row ) {
2829 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2837 * Return an applicable autosummary if one exists for the given edit.
2838 * @param $oldtext String|null: the previous text of the page.
2839 * @param $newtext String|null: The submitted text of the page.
2840 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2841 * @return string An appropriate autosummary, or an empty string.
2842 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
2844 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2845 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2847 wfDeprecated( __METHOD__
, '1.WD' );
2849 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
2850 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
2851 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
2853 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2857 * Auto-generates a deletion reason
2859 * @param &$hasHistory Boolean: whether the page has a history
2860 * @return mixed String containing deletion reason or empty string, or boolean false
2861 * if no revision occurred
2862 * @deprecated since 1.WD, use ContentHandler::getAutoDeleteReason() instead
2864 public function getAutoDeleteReason( &$hasHistory ) {
2865 #NOTE: stub for backwards-compatibility.
2867 wfDeprecated( __METHOD__
, '1.WD' );
2869 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2870 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2873 // Get the last revision
2874 $rev = $this->getRevision();
2876 if ( is_null( $rev ) ) {
2880 // Get the article's contents
2881 $contents = $rev->getText();
2884 // If the page is blank, use the text from the previous revision,
2885 // which can only be blank if there's a move/import/protect dummy revision involved
2886 if ( $contents == '' ) {
2887 $prev = $rev->getPrevious();
2890 $contents = $prev->getText();
2895 $dbw = wfGetDB( DB_MASTER
);
2897 // Find out if there was only one contributor
2898 // Only scan the last 20 revisions
2899 $res = $dbw->select( 'revision', 'rev_user_text',
2900 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2902 array( 'LIMIT' => 20 )
2905 if ( $res === false ) {
2906 // This page has no revisions, which is very weird
2910 $hasHistory = ( $res->numRows() > 1 );
2911 $row = $dbw->fetchObject( $res );
2913 if ( $row ) { // $row is false if the only contributor is hidden
2914 $onlyAuthor = $row->rev_user_text
;
2915 // Try to find a second contributor
2916 foreach ( $res as $row ) {
2917 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2918 $onlyAuthor = false;
2923 $onlyAuthor = false;
2926 // Generate the summary with a '$1' placeholder
2928 // The current revision is blank and the one before is also
2929 // blank. It's just not our lucky day
2930 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2932 if ( $onlyAuthor ) {
2933 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2935 $reason = wfMsgForContent( 'excontent', '$1' );
2939 if ( $reason == '-' ) {
2940 // Allow these UI messages to be blanked out cleanly
2944 // Replace newlines with spaces to prevent uglyness
2945 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2946 // Calculate the maximum amount of chars to get
2947 // Max content length = max comment length - length of the comment (excl. $1)
2948 $maxLength = 255 - ( strlen( $reason ) - 2 );
2949 $contents = $wgContLang->truncate( $contents, $maxLength );
2950 // Remove possible unfinished links
2951 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2952 // Now replace the '$1' placeholder
2953 $reason = str_replace( '$1', $contents, $reason );
2959 * Update all the appropriate counts in the category table, given that
2960 * we've added the categories $added and deleted the categories $deleted.
2962 * @param $added array The names of categories that were added
2963 * @param $deleted array The names of categories that were deleted
2965 public function updateCategoryCounts( $added, $deleted ) {
2966 $ns = $this->mTitle
->getNamespace();
2967 $dbw = wfGetDB( DB_MASTER
);
2969 # First make sure the rows exist. If one of the "deleted" ones didn't
2970 # exist, we might legitimately not create it, but it's simpler to just
2971 # create it and then give it a negative value, since the value is bogus
2974 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2975 $insertCats = array_merge( $added, $deleted );
2976 if ( !$insertCats ) {
2977 # Okay, nothing to do
2981 $insertRows = array();
2983 foreach ( $insertCats as $cat ) {
2984 $insertRows[] = array(
2985 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2989 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2991 $addFields = array( 'cat_pages = cat_pages + 1' );
2992 $removeFields = array( 'cat_pages = cat_pages - 1' );
2994 if ( $ns == NS_CATEGORY
) {
2995 $addFields[] = 'cat_subcats = cat_subcats + 1';
2996 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2997 } elseif ( $ns == NS_FILE
) {
2998 $addFields[] = 'cat_files = cat_files + 1';
2999 $removeFields[] = 'cat_files = cat_files - 1';
3006 array( 'cat_title' => $added ),
3015 array( 'cat_title' => $deleted ),
3022 * Updates cascading protections
3024 * @param $parserOutput ParserOutput object for the current version
3026 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3027 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3031 // templatelinks table may have become out of sync,
3032 // especially if using variable-based transclusions.
3033 // For paranoia, check if things have changed and if
3034 // so apply updates to the database. This will ensure
3035 // that cascaded protections apply as soon as the changes
3038 # Get templates from templatelinks
3039 $id = $this->mTitle
->getArticleID();
3041 $tlTemplates = array();
3043 $dbr = wfGetDB( DB_SLAVE
);
3044 $res = $dbr->select( array( 'templatelinks' ),
3045 array( 'tl_namespace', 'tl_title' ),
3046 array( 'tl_from' => $id ),
3050 foreach ( $res as $row ) {
3051 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3054 # Get templates from parser output.
3055 $poTemplates = array();
3056 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3057 foreach ( $templates as $dbk => $id ) {
3058 $poTemplates["$ns:$dbk"] = true;
3063 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3065 if ( count( $templates_diff ) > 0 ) {
3066 # Whee, link updates time.
3067 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3068 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3074 * Return a list of templates used by this article.
3075 * Uses the templatelinks table
3077 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3078 * @return Array of Title objects
3080 public function getUsedTemplates() {
3081 return $this->mTitle
->getTemplateLinksFrom();
3085 * Perform article updates on a special page creation.
3087 * @param $rev Revision object
3089 * @todo This is a shitty interface function. Kill it and replace the
3090 * other shitty functions like doEditUpdates and such so it's not needed
3092 * @deprecated since 1.18, use doEditUpdates()
3094 public function createUpdates( $rev ) {
3095 wfDeprecated( __METHOD__
, '1.18' );
3097 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3101 * This function is called right before saving the wikitext,
3102 * so we can do things like signatures and links-in-context.
3104 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3105 * @param $text String article contents
3106 * @param $user User object: user doing the edit
3107 * @param $popts ParserOptions object: parser options, default options for
3108 * the user loaded if null given
3109 * @return string article contents with altered wikitext markup (signatures
3110 * converted, {{subst:}}, templates, etc.)
3112 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3113 global $wgParser, $wgUser;
3115 wfDeprecated( __METHOD__
, '1.19' );
3117 $user = is_null( $user ) ?
$wgUser : $user;
3119 if ( $popts === null ) {
3120 $popts = ParserOptions
::newFromUser( $user );
3123 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3127 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3129 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3132 public function isBigDeletion() {
3133 wfDeprecated( __METHOD__
, '1.19' );
3134 return $this->mTitle
->isBigDeletion();
3138 * Get the approximate revision count of this page.
3140 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3143 public function estimateRevisionCount() {
3144 wfDeprecated( __METHOD__
, '1.19' );
3145 return $this->mTitle
->estimateRevisionCount();
3149 * Update the article's restriction field, and leave a log entry.
3151 * @deprecated since 1.19
3152 * @param $limit Array: set of restriction keys
3153 * @param $reason String
3154 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3155 * @param $expiry Array: per restriction type expiration
3156 * @param $user User The user updating the restrictions
3157 * @return bool true on success
3159 public function updateRestrictions(
3160 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3164 $user = is_null( $user ) ?
$wgUser : $user;
3166 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3170 * @deprecated since 1.18
3172 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3173 wfDeprecated( __METHOD__
, '1.18' );
3175 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3179 * @deprecated since 1.18
3181 public function viewUpdates() {
3182 wfDeprecated( __METHOD__
, '1.18' );
3184 return $this->doViewUpdates( $wgUser );
3188 * @deprecated since 1.18
3191 public function useParserCache( $oldid ) {
3192 wfDeprecated( __METHOD__
, '1.18' );
3194 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3197 public function getDeletionUpdates() {
3198 $updates = $this->getContentHandler()->getDeletionUpdates( $this );
3200 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, &$updates ) );
3206 class PoolWorkArticleView
extends PoolCounterWork
{
3224 * @var ParserOptions
3226 private $parserOptions;
3231 private $content = null;
3234 * @var ParserOutput|bool
3236 private $parserOutput = false;
3241 private $isDirty = false;
3246 private $error = false;
3252 * @param $revid Integer: ID of the revision being parsed
3253 * @param $useParserCache Boolean: whether to use the parser cache
3254 * @param $parserOptions parserOptions to use for the parse operation
3255 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3257 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3258 if ( is_string($content) ) { #BC: old style call
3259 $modelId = $page->getRevision()->getContentModel();
3260 $format = $page->getRevision()->getContentFormat();
3261 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3264 $this->page
= $page;
3265 $this->revid
= $revid;
3266 $this->cacheable
= $useParserCache;
3267 $this->parserOptions
= $parserOptions;
3268 $this->content
= $content;
3269 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3270 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3274 * Get the ParserOutput from this object, or false in case of failure
3276 * @return ParserOutput
3278 public function getParserOutput() {
3279 return $this->parserOutput
;
3283 * Get whether the ParserOutput is a dirty one (i.e. expired)
3287 public function getIsDirty() {
3288 return $this->isDirty
;
3292 * Get a Status object in case of error or false otherwise
3294 * @return Status|bool
3296 public function getError() {
3297 return $this->error
;
3304 global $wgUseFileCache;
3306 // @todo: several of the methods called on $this->page are not declared in Page, but present in WikiPage and delegated by Article.
3308 $isCurrent = $this->revid
=== $this->page
->getLatest();
3310 if ( $this->content
!== null ) {
3311 $content = $this->content
;
3312 } elseif ( $isCurrent ) {
3313 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
3315 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3316 if ( $rev === null ) {
3319 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
3322 $time = - microtime( true );
3323 // TODO: page might not have this method? Hard to tell what page is supposed to be here...
3324 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3325 $time +
= microtime( true );
3329 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3330 $this->page
->getTitle()->getPrefixedDBkey() ) );
3333 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3334 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3337 // Make sure file cache is not used on uncacheable content.
3338 // Output that has magic words in it can still use the parser cache
3339 // (if enabled), though it will generally expire sooner.
3340 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3341 $wgUseFileCache = false;
3345 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3354 function getCachedWork() {
3355 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3357 if ( $this->parserOutput
=== false ) {
3358 wfDebug( __METHOD__
. ": parser cache miss\n" );
3361 wfDebug( __METHOD__
. ": parser cache hit\n" );
3369 function fallback() {
3370 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3372 if ( $this->parserOutput
=== false ) {
3373 wfDebugLog( 'dirty', "dirty missing\n" );
3374 wfDebug( __METHOD__
. ": no dirty cache\n" );
3377 wfDebug( __METHOD__
. ": sending dirty output\n" );
3378 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3379 $this->isDirty
= true;
3385 * @param $status Status
3388 function error( $status ) {
3389 $this->error
= $status;