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)
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
implements Page
, IDBAccessObject
{
37 // Constants for $mDataLoadedFrom and related
42 public $mTitle = null;
47 public $mDataLoaded = false; // !< Boolean
48 public $mIsRedirect = false; // !< Boolean
49 public $mLatest = false; // !< Integer (false means "not loaded")
50 public $mPreparedEdit = false; // !< Array
56 protected $mId = null;
59 * @var int; one of the READ_* constants
61 protected $mDataLoadedFrom = self
::READ_NONE
;
66 protected $mRedirectTarget = null;
71 protected $mLastRevision = null;
74 * @var string; timestamp of the current revision or empty string if not loaded
76 protected $mTimestamp = '';
81 protected $mTouched = '19700101000000';
86 protected $mCounter = null;
89 * Constructor and clear the article
90 * @param $title Title Reference to a Title object.
92 public function __construct( Title
$title ) {
93 $this->mTitle
= $title;
97 * Create a WikiPage object of the appropriate class for the given title.
100 * @throws MWException
101 * @return WikiPage object of the appropriate type
103 public static function factory( Title
$title ) {
104 $ns = $title->getNamespace();
106 if ( $ns == NS_MEDIA
) {
107 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
108 } elseif ( $ns < 0 ) {
109 throw new MWException( "Invalid or virtual namespace $ns given." );
114 $page = new WikiFilePage( $title );
117 $page = new WikiCategoryPage( $title );
120 $page = new WikiPage( $title );
127 * Constructor from a page id
129 * @param $id Int article ID to load
130 * @param $from string|int one of the following values:
131 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
132 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
134 * @return WikiPage|null
136 public static function newFromID( $id, $from = 'fromdb' ) {
137 $from = self
::convertSelectType( $from );
138 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
139 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
143 return self
::newFromRow( $row, $from );
147 * Constructor from a database row
150 * @param $row object: database row containing at least fields returned
152 * @param $from string|int: source of $data:
153 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
154 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
155 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
158 public static function newFromRow( $row, $from = 'fromdb' ) {
159 $page = self
::factory( Title
::newFromRow( $row ) );
160 $page->loadFromRow( $row, $from );
165 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
167 * @param $type object|string|int
170 private static function convertSelectType( $type ) {
173 return self
::READ_NORMAL
;
175 return self
::READ_LATEST
;
177 return self
::READ_LOCKING
;
179 // It may already be an integer or whatever else
185 * Returns overrides for action handlers.
186 * Classes listed here will be used instead of the default one when
187 * (and only when) $wgActions[$action] === true. This allows subclasses
188 * to override the default behavior.
190 * @todo: move this UI stuff somewhere else
194 public function getActionOverrides() {
195 $content_handler = $this->getContentHandler();
196 return $content_handler->getActionOverrides();
200 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
202 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
204 * @return ContentHandler
208 public function getContentHandler() {
209 return ContentHandler
::getForModelID( $this->getContentModel() );
213 * Get the title object of the article
214 * @return Title object of this page
216 public function getTitle() {
217 return $this->mTitle
;
224 public function clear() {
225 $this->mDataLoaded
= false;
226 $this->mDataLoadedFrom
= self
::READ_NONE
;
228 $this->clearCacheFields();
232 * Clear the object cache fields
235 protected function clearCacheFields() {
237 $this->mCounter
= null;
238 $this->mRedirectTarget
= null; // Title object if set
239 $this->mLastRevision
= null; // Latest revision
240 $this->mTouched
= '19700101000000';
241 $this->mTimestamp
= '';
242 $this->mIsRedirect
= false;
243 $this->mLatest
= false;
244 $this->mPreparedEdit
= false;
248 * Return the list of revision fields that should be selected to create
253 public static function selectFields() {
254 global $wgContentHandlerUseDB;
270 if ( $wgContentHandlerUseDB ) {
271 $fields[] = 'page_content_model';
278 * Fetch a page record with the given conditions
279 * @param $dbr DatabaseBase object
280 * @param $conditions Array
281 * @param $options Array
282 * @return mixed Database result resource, or false on failure
284 protected function pageData( $dbr, $conditions, $options = array() ) {
285 $fields = self
::selectFields();
287 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
289 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
291 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
297 * Fetch a page record matching the Title object's namespace and title
298 * using a sanitized title string
300 * @param $dbr DatabaseBase object
301 * @param $title Title object
302 * @param $options Array
303 * @return mixed Database result resource, or false on failure
305 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
306 return $this->pageData( $dbr, array(
307 'page_namespace' => $title->getNamespace(),
308 'page_title' => $title->getDBkey() ), $options );
312 * Fetch a page record matching the requested ID
314 * @param $dbr DatabaseBase
316 * @param $options Array
317 * @return mixed Database result resource, or false on failure
319 public function pageDataFromId( $dbr, $id, $options = array() ) {
320 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
324 * Set the general counter, title etc data loaded from
327 * @param $from object|string|int One of the following:
328 * - A DB query result object
329 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
330 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
331 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
335 public function loadPageData( $from = 'fromdb' ) {
336 $from = self
::convertSelectType( $from );
337 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
338 // We already have the data from the correct location, no need to load it twice.
342 if ( $from === self
::READ_LOCKING
) {
343 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
344 } elseif ( $from === self
::READ_LATEST
) {
345 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
346 } elseif ( $from === self
::READ_NORMAL
) {
347 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
348 // Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
349 // Note that DB also stores the master position in the session and checks it.
350 $touched = $this->getCachedLastEditTime();
351 if ( $touched ) { // key set
352 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
353 $from = self
::READ_LATEST
;
354 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
358 // No idea from where the caller got this data, assume slave database.
360 $from = self
::READ_NORMAL
;
363 $this->loadFromRow( $data, $from );
367 * Load the object from a database row
370 * @param $data object: database row containing at least fields returned
372 * @param $from string|int One of the following:
373 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
374 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
375 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
376 * the master DB using SELECT FOR UPDATE
378 public function loadFromRow( $data, $from ) {
379 $lc = LinkCache
::singleton();
382 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
384 $this->mTitle
->loadFromRow( $data );
386 // Old-fashioned restrictions
387 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
389 $this->mId
= intval( $data->page_id
);
390 $this->mCounter
= intval( $data->page_counter
);
391 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
392 $this->mIsRedirect
= intval( $data->page_is_redirect
);
393 $this->mLatest
= intval( $data->page_latest
);
394 // Bug 37225: $latest may no longer match the cached latest Revision object.
395 // Double-check the ID of any cached latest Revision object for consistency.
396 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
397 $this->mLastRevision
= null;
398 $this->mTimestamp
= '';
401 $lc->addBadLinkObj( $this->mTitle
);
403 $this->mTitle
->loadFromRow( false );
405 $this->clearCacheFields();
410 $this->mDataLoaded
= true;
411 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
415 * @return int Page ID
417 public function getId() {
418 if ( !$this->mDataLoaded
) {
419 $this->loadPageData();
425 * @return bool Whether or not the page exists in the database
427 public function exists() {
428 if ( !$this->mDataLoaded
) {
429 $this->loadPageData();
431 return $this->mId
> 0;
435 * Check if this page is something we're going to be showing
436 * some sort of sensible content for. If we return false, page
437 * views (plain action=view) will return an HTTP 404 response,
438 * so spiders and robots can know they're following a bad link.
442 public function hasViewableContent() {
443 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
447 * @return int The view count for the page
449 public function getCount() {
450 if ( !$this->mDataLoaded
) {
451 $this->loadPageData();
454 return $this->mCounter
;
458 * Tests if the article content represents a redirect
462 public function isRedirect( ) {
463 $content = $this->getContent();
464 if ( !$content ) return false;
466 return $content->isRedirect();
470 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
472 * Will use the revisions actual content model if the page exists,
473 * and the page's default if the page doesn't exist yet.
479 public function getContentModel() {
480 if ( $this->exists() ) {
481 // look at the revision's actual content model
482 $rev = $this->getRevision();
484 if ( $rev !== null ) {
485 return $rev->getContentModel();
487 $title = $this->mTitle
->getPrefixedDBkey();
488 wfWarn( "Page $title exists but has no (visible) revisions!" );
492 // use the default model for this page
493 return $this->mTitle
->getContentModel();
497 * Loads page_touched and returns a value indicating if it should be used
498 * @return boolean true if not a redirect
500 public function checkTouched() {
501 if ( !$this->mDataLoaded
) {
502 $this->loadPageData();
504 return !$this->mIsRedirect
;
508 * Get the page_touched field
509 * @return string containing GMT timestamp
511 public function getTouched() {
512 if ( !$this->mDataLoaded
) {
513 $this->loadPageData();
515 return $this->mTouched
;
519 * Get the page_latest field
520 * @return integer rev_id of current revision
522 public function getLatest() {
523 if ( !$this->mDataLoaded
) {
524 $this->loadPageData();
526 return (int)$this->mLatest
;
530 * Get the Revision object of the oldest revision
531 * @return Revision|null
533 public function getOldestRevision() {
534 wfProfileIn( __METHOD__
);
536 // Try using the slave database first, then try the master
538 $db = wfGetDB( DB_SLAVE
);
539 $revSelectFields = Revision
::selectFields();
541 while ( $continue ) {
542 $row = $db->selectRow(
543 array( 'page', 'revision' ),
546 'page_namespace' => $this->mTitle
->getNamespace(),
547 'page_title' => $this->mTitle
->getDBkey(),
552 'ORDER BY' => 'rev_timestamp ASC'
559 $db = wfGetDB( DB_MASTER
);
564 wfProfileOut( __METHOD__
);
565 return $row ? Revision
::newFromRow( $row ) : null;
569 * Loads everything except the text
570 * This isn't necessary for all uses, so it's only done if needed.
572 protected function loadLastEdit() {
573 if ( $this->mLastRevision
!== null ) {
574 return; // already loaded
577 $latest = $this->getLatest();
579 return; // page doesn't exist or is missing page_latest info
582 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
583 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
584 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
585 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
586 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
587 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
588 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
589 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
590 if ( $revision ) { // sanity
591 $this->setLastEdit( $revision );
596 * Set the latest revision
598 protected function setLastEdit( Revision
$revision ) {
599 $this->mLastRevision
= $revision;
600 $this->mTimestamp
= $revision->getTimestamp();
604 * Get the latest revision
605 * @return Revision|null
607 public function getRevision() {
608 $this->loadLastEdit();
609 if ( $this->mLastRevision
) {
610 return $this->mLastRevision
;
616 * Get the content of the current revision. No side-effects...
618 * @param $audience Integer: one of:
619 * Revision::FOR_PUBLIC to be displayed to all users
620 * Revision::FOR_THIS_USER to be displayed to $wgUser
621 * Revision::RAW get the text regardless of permissions
622 * @param $user User object to check for, only if FOR_THIS_USER is passed
623 * to the $audience parameter
624 * @return Content|null The content of the current revision
628 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
629 $this->loadLastEdit();
630 if ( $this->mLastRevision
) {
631 return $this->mLastRevision
->getContent( $audience, $user );
637 * Get the text of the current revision. No side-effects...
639 * @param $audience Integer: one of:
640 * Revision::FOR_PUBLIC to be displayed to all users
641 * Revision::FOR_THIS_USER to be displayed to the given user
642 * Revision::RAW get the text regardless of permissions
643 * @param $user User object to check for, only if FOR_THIS_USER is passed
644 * to the $audience parameter
645 * @return String|false The text of the current revision
646 * @deprecated as of 1.21, getContent() should be used instead.
648 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) { // @todo: deprecated, replace usage!
649 ContentHandler
::deprecated( __METHOD__
, '1.21' );
651 $this->loadLastEdit();
652 if ( $this->mLastRevision
) {
653 return $this->mLastRevision
->getText( $audience, $user );
659 * Get the text of the current revision. No side-effects...
661 * @return String|bool The text of the current revision. False on failure
662 * @deprecated as of 1.21, getContent() should be used instead.
664 public function getRawText() {
665 ContentHandler
::deprecated( __METHOD__
, '1.21' );
667 return $this->getText( Revision
::RAW
);
671 * @return string MW timestamp of last article revision
673 public function getTimestamp() {
674 // Check if the field has been filled by WikiPage::setTimestamp()
675 if ( !$this->mTimestamp
) {
676 $this->loadLastEdit();
679 return wfTimestamp( TS_MW
, $this->mTimestamp
);
683 * Set the page timestamp (use only to avoid DB queries)
684 * @param $ts string MW timestamp of last article revision
687 public function setTimestamp( $ts ) {
688 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
692 * @param $audience Integer: one of:
693 * Revision::FOR_PUBLIC to be displayed to all users
694 * Revision::FOR_THIS_USER to be displayed to the given user
695 * Revision::RAW get the text regardless of permissions
696 * @param $user User object to check for, only if FOR_THIS_USER is passed
697 * to the $audience parameter
698 * @return int user ID for the user that made the last article revision
700 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
701 $this->loadLastEdit();
702 if ( $this->mLastRevision
) {
703 return $this->mLastRevision
->getUser( $audience, $user );
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 the given user
714 * Revision::RAW get the text regardless of permissions
715 * @param $user User object to check for, only if FOR_THIS_USER is passed
716 * to the $audience parameter
719 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
720 $revision = $this->getOldestRevision();
722 $userName = $revision->getUserText( $audience, $user );
723 return User
::newFromName( $userName, false );
730 * @param $audience Integer: one of:
731 * Revision::FOR_PUBLIC to be displayed to all users
732 * Revision::FOR_THIS_USER to be displayed to the given user
733 * Revision::RAW get the text regardless of permissions
734 * @param $user User object to check for, only if FOR_THIS_USER is passed
735 * to the $audience parameter
736 * @return string username of the user that made the last article revision
738 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
739 $this->loadLastEdit();
740 if ( $this->mLastRevision
) {
741 return $this->mLastRevision
->getUserText( $audience, $user );
748 * @param $audience Integer: one of:
749 * Revision::FOR_PUBLIC to be displayed to all users
750 * Revision::FOR_THIS_USER to be displayed to the given user
751 * Revision::RAW get the text regardless of permissions
752 * @param $user User object to check for, only if FOR_THIS_USER is passed
753 * to the $audience parameter
754 * @return string Comment stored for the last article revision
756 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
757 $this->loadLastEdit();
758 if ( $this->mLastRevision
) {
759 return $this->mLastRevision
->getComment( $audience, $user );
766 * Returns true if last revision was marked as "minor edit"
768 * @return boolean Minor edit indicator for the last article revision.
770 public function getMinorEdit() {
771 $this->loadLastEdit();
772 if ( $this->mLastRevision
) {
773 return $this->mLastRevision
->isMinor();
780 * Get the cached timestamp for the last time the page changed.
781 * This is only used to help handle slave lag by comparing to page_touched.
782 * @return string MW timestamp
784 protected function getCachedLastEditTime() {
786 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
787 return $wgMemc->get( $key );
791 * Set the cached timestamp for the last time the page changed.
792 * This is only used to help handle slave lag by comparing to page_touched.
793 * @param $timestamp string
796 public function setCachedLastEditTime( $timestamp ) {
798 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
799 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
803 * Determine whether a page would be suitable for being counted as an
804 * article in the site_stats table based on the title & its content
806 * @param $editInfo Object|bool (false): object returned by prepareTextForEdit(),
807 * if false, the current database state will be used
810 public function isCountable( $editInfo = false ) {
811 global $wgArticleCountMethod;
813 if ( !$this->mTitle
->isContentPage() ) {
818 $content = $editInfo->pstContent
;
820 $content = $this->getContent();
823 if ( !$content ||
$content->isRedirect( ) ) {
829 if ( $wgArticleCountMethod === 'link' ) {
830 // nasty special case to avoid re-parsing to detect links
833 // ParserOutput::getLinks() is a 2D array of page links, so
834 // to be really correct we would need to recurse in the array
835 // but the main array should only have items in it if there are
837 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
839 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
840 array( 'pl_from' => $this->getId() ), __METHOD__
);
844 return $content->isCountable( $hasLinks );
848 * If this page is a redirect, get its target
850 * The target will be fetched from the redirect table if possible.
851 * If this page doesn't have an entry there, call insertRedirect()
852 * @return Title|mixed object, or null if this page is not a redirect
854 public function getRedirectTarget() {
855 if ( !$this->mTitle
->isRedirect() ) {
859 if ( $this->mRedirectTarget
!== null ) {
860 return $this->mRedirectTarget
;
863 // Query the redirect table
864 $dbr = wfGetDB( DB_SLAVE
);
865 $row = $dbr->selectRow( 'redirect',
866 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
867 array( 'rd_from' => $this->getId() ),
871 // rd_fragment and rd_interwiki were added later, populate them if empty
872 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
873 return $this->mRedirectTarget
= Title
::makeTitle(
874 $row->rd_namespace
, $row->rd_title
,
875 $row->rd_fragment
, $row->rd_interwiki
);
878 // This page doesn't have an entry in the redirect table
879 return $this->mRedirectTarget
= $this->insertRedirect();
883 * Insert an entry for this page into the redirect table.
885 * Don't call this function directly unless you know what you're doing.
886 * @return Title object or null if not a redirect
888 public function insertRedirect() {
889 // recurse through to only get the final target
890 $content = $this->getContent();
891 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
895 $this->insertRedirectEntry( $retval );
900 * Insert or update the redirect table entry for this page to indicate
901 * it redirects to $rt .
902 * @param $rt Title redirect target
904 public function insertRedirectEntry( $rt ) {
905 $dbw = wfGetDB( DB_MASTER
);
906 $dbw->replace( 'redirect', array( 'rd_from' ),
908 'rd_from' => $this->getId(),
909 'rd_namespace' => $rt->getNamespace(),
910 'rd_title' => $rt->getDBkey(),
911 'rd_fragment' => $rt->getFragment(),
912 'rd_interwiki' => $rt->getInterwiki(),
919 * Get the Title object or URL this page redirects to
921 * @return mixed false, Title of in-wiki target, or string with URL
923 public function followRedirect() {
924 return $this->getRedirectURL( $this->getRedirectTarget() );
928 * Get the Title object or URL to use for a redirect. We use Title
929 * objects for same-wiki, non-special redirects and URLs for everything
931 * @param $rt Title Redirect target
932 * @return mixed false, Title object of local target, or string with URL
934 public function getRedirectURL( $rt ) {
939 if ( $rt->isExternal() ) {
940 if ( $rt->isLocal() ) {
941 // Offsite wikis need an HTTP redirect.
943 // This can be hard to reverse and may produce loops,
944 // so they may be disabled in the site configuration.
945 $source = $this->mTitle
->getFullURL( 'redirect=no' );
946 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
948 // External pages pages without "local" bit set are not valid
954 if ( $rt->isSpecialPage() ) {
955 // Gotta handle redirects to special pages differently:
956 // Fill the HTTP response "Location" header and ignore
957 // the rest of the page we're on.
959 // Some pages are not valid targets
960 if ( $rt->isValidRedirectTarget() ) {
961 return $rt->getFullURL();
971 * Get a list of users who have edited this article, not including the user who made
972 * the most recent revision, which you can get from $article->getUser() if you want it
973 * @return UserArrayFromResult
975 public function getContributors() {
976 // @todo FIXME: This is expensive; cache this info somewhere.
978 $dbr = wfGetDB( DB_SLAVE
);
980 if ( $dbr->implicitGroupby() ) {
981 $realNameField = 'user_real_name';
983 $realNameField = 'MIN(user_real_name) AS user_real_name';
986 $tables = array( 'revision', 'user' );
989 'user_id' => 'rev_user',
990 'user_name' => 'rev_user_text',
992 'timestamp' => 'MAX(rev_timestamp)',
995 $conds = array( 'rev_page' => $this->getId() );
997 // The user who made the top revision gets credited as "this page was last edited by
998 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
999 $user = $this->getUser();
1001 $conds[] = "rev_user != $user";
1003 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1006 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1009 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1013 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1014 'ORDER BY' => 'timestamp DESC',
1017 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1018 return new UserArrayFromResult( $res );
1022 * Get the last N authors
1023 * @param $num Integer: number of revisions to get
1024 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1025 * @return array Array of authors, duplicates not removed
1027 public function getLastNAuthors( $num, $revLatest = 0 ) {
1028 wfProfileIn( __METHOD__
);
1029 // First try the slave
1030 // If that doesn't have the latest revision, try the master
1032 $db = wfGetDB( DB_SLAVE
);
1035 $res = $db->select( array( 'page', 'revision' ),
1036 array( 'rev_id', 'rev_user_text' ),
1038 'page_namespace' => $this->mTitle
->getNamespace(),
1039 'page_title' => $this->mTitle
->getDBkey(),
1040 'rev_page = page_id'
1043 'ORDER BY' => 'rev_timestamp DESC',
1049 wfProfileOut( __METHOD__
);
1053 $row = $db->fetchObject( $res );
1055 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1056 $db = wfGetDB( DB_MASTER
);
1061 } while ( $continue );
1063 $authors = array( $row->rev_user_text
);
1065 foreach ( $res as $row ) {
1066 $authors[] = $row->rev_user_text
;
1069 wfProfileOut( __METHOD__
);
1074 * Should the parser cache be used?
1076 * @param $parserOptions ParserOptions to check
1080 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1081 global $wgEnableParserCache;
1083 return $wgEnableParserCache
1084 && $parserOptions->getStubThreshold() == 0
1086 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1087 && $this->getContentHandler()->isParserCacheSupported();
1091 * Get a ParserOutput for the given ParserOptions and revision ID.
1092 * The parser cache will be used if possible.
1095 * @param $parserOptions ParserOptions to use for the parse operation
1096 * @param $oldid Revision ID to get the text from, passing null or 0 will
1097 * get the current revision (default value)
1099 * @return ParserOutput or false if the revision was not found
1101 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1102 wfProfileIn( __METHOD__
);
1104 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1105 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1106 if ( $parserOptions->getStubThreshold() ) {
1107 wfIncrStats( 'pcache_miss_stub' );
1110 if ( $useParserCache ) {
1111 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1112 if ( $parserOutput !== false ) {
1113 wfProfileOut( __METHOD__
);
1114 return $parserOutput;
1118 if ( $oldid === null ||
$oldid === 0 ) {
1119 $oldid = $this->getLatest();
1122 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1125 wfProfileOut( __METHOD__
);
1127 return $pool->getParserOutput();
1131 * Do standard deferred updates after page view
1132 * @param $user User The relevant user
1134 public function doViewUpdates( User
$user ) {
1135 global $wgDisableCounters;
1136 if ( wfReadOnly() ) {
1140 // Don't update page view counters on views from bot users (bug 14044)
1141 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->exists() ) {
1142 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1143 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1146 // Update newtalk / watchlist notification status
1147 $user->clearNotification( $this->mTitle
);
1151 * Perform the actions of a page purging
1154 public function doPurge() {
1157 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1161 // Invalidate the cache
1162 $this->mTitle
->invalidateCache();
1165 if ( $wgUseSquid ) {
1166 // Commit the transaction before the purge is sent
1167 $dbw = wfGetDB( DB_MASTER
);
1168 $dbw->commit( __METHOD__
);
1171 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1172 $update->doUpdate();
1175 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1176 // @todo: move this logic to MessageCache
1178 if ( $this->exists() ) {
1179 // NOTE: use transclusion text for messages.
1180 // This is consistent with MessageCache::getMsgFromNamespace()
1182 $content = $this->getContent();
1183 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1185 if ( $text === null ) $text = false;
1190 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1196 * Insert a new empty page record for this article.
1197 * This *must* be followed up by creating a revision
1198 * and running $this->updateRevisionOn( ... );
1199 * or else the record will be left in a funky state.
1200 * Best if all done inside a transaction.
1202 * @param $dbw DatabaseBase
1203 * @return int The newly created page_id key, or false if the title already existed
1205 public function insertOn( $dbw ) {
1206 wfProfileIn( __METHOD__
);
1208 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1209 $dbw->insert( 'page', array(
1210 'page_id' => $page_id,
1211 'page_namespace' => $this->mTitle
->getNamespace(),
1212 'page_title' => $this->mTitle
->getDBkey(),
1213 'page_counter' => 0,
1214 'page_restrictions' => '',
1215 'page_is_redirect' => 0, // Will set this shortly...
1217 'page_random' => wfRandom(),
1218 'page_touched' => $dbw->timestamp(),
1219 'page_latest' => 0, // Fill this in shortly...
1220 'page_len' => 0, // Fill this in shortly...
1221 ), __METHOD__
, 'IGNORE' );
1223 $affected = $dbw->affectedRows();
1226 $newid = $dbw->insertId();
1227 $this->mId
= $newid;
1228 $this->mTitle
->resetArticleID( $newid );
1230 wfProfileOut( __METHOD__
);
1232 return $affected ?
$newid : false;
1236 * Update the page record to point to a newly saved revision.
1238 * @param $dbw DatabaseBase: object
1239 * @param $revision Revision: For ID number, and text used to set
1240 * length and redirect status fields
1241 * @param $lastRevision Integer: if given, will not overwrite the page field
1242 * when different from the currently set value.
1243 * Giving 0 indicates the new page flag should be set
1245 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1246 * removing rows in redirect table.
1247 * @return bool true on success, false on failure
1250 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1251 global $wgContentHandlerUseDB;
1253 wfProfileIn( __METHOD__
);
1255 $content = $revision->getContent();
1256 $len = $content ?
$content->getSize() : 0;
1257 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1259 $conditions = array( 'page_id' => $this->getId() );
1261 if ( !is_null( $lastRevision ) ) {
1262 // An extra check against threads stepping on each other
1263 $conditions['page_latest'] = $lastRevision;
1266 $now = wfTimestampNow();
1267 $row = array( /* SET */
1268 'page_latest' => $revision->getId(),
1269 'page_touched' => $dbw->timestamp( $now ),
1270 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1271 'page_is_redirect' => $rt !== null ?
1 : 0,
1275 if ( $wgContentHandlerUseDB ) {
1276 $row[ 'page_content_model' ] = $revision->getContentModel();
1279 $dbw->update( 'page',
1284 $result = $dbw->affectedRows() > 0;
1286 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1287 $this->setLastEdit( $revision );
1288 $this->setCachedLastEditTime( $now );
1289 $this->mLatest
= $revision->getId();
1290 $this->mIsRedirect
= (bool)$rt;
1291 // Update the LinkCache.
1292 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1293 $this->mLatest
, $revision->getContentModel() );
1296 wfProfileOut( __METHOD__
);
1301 * Add row to the redirect table if this is a redirect, remove otherwise.
1303 * @param $dbw DatabaseBase
1304 * @param $redirectTitle Title object pointing to the redirect target,
1305 * or NULL if this is not a redirect
1306 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1307 * removing rows in redirect table.
1308 * @return bool true on success, false on failure
1311 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1312 // Always update redirects (target link might have changed)
1313 // Update/Insert if we don't know if the last revision was a redirect or not
1314 // Delete if changing from redirect to non-redirect
1315 $isRedirect = !is_null( $redirectTitle );
1317 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1321 wfProfileIn( __METHOD__
);
1322 if ( $isRedirect ) {
1323 $this->insertRedirectEntry( $redirectTitle );
1325 // This is not a redirect, remove row from redirect table
1326 $where = array( 'rd_from' => $this->getId() );
1327 $dbw->delete( 'redirect', $where, __METHOD__
);
1330 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1331 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1333 wfProfileOut( __METHOD__
);
1335 return ( $dbw->affectedRows() != 0 );
1339 * If the given revision is newer than the currently set page_latest,
1340 * update the page record. Otherwise, do nothing.
1342 * @param $dbw DatabaseBase object
1343 * @param $revision Revision object
1346 public function updateIfNewerOn( $dbw, $revision ) {
1347 wfProfileIn( __METHOD__
);
1349 $row = $dbw->selectRow(
1350 array( 'revision', 'page' ),
1351 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1353 'page_id' => $this->getId(),
1354 'page_latest=rev_id' ),
1358 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1359 wfProfileOut( __METHOD__
);
1362 $prev = $row->rev_id
;
1363 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1365 // No or missing previous revision; mark the page as new
1367 $lastRevIsRedirect = null;
1370 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1372 wfProfileOut( __METHOD__
);
1377 * Get the content that needs to be saved in order to undo all revisions
1378 * between $undo and $undoafter. Revisions must belong to the same page,
1379 * must exist and must not be deleted
1380 * @param $undo Revision
1381 * @param $undoafter Revision Must be an earlier revision than $undo
1382 * @return mixed string on success, false on failure
1384 * Before we had the Content object, this was done in getUndoText
1386 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1387 $handler = $undo->getContentHandler();
1388 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1392 * Get the text that needs to be saved in order to undo all revisions
1393 * between $undo and $undoafter. Revisions must belong to the same page,
1394 * must exist and must not be deleted
1395 * @param $undo Revision
1396 * @param $undoafter Revision Must be an earlier revision than $undo
1397 * @return mixed string on success, false on failure
1398 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1400 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1401 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1403 $this->loadLastEdit();
1405 if ( $this->mLastRevision
) {
1406 if ( is_null( $undoafter ) ) {
1407 $undoafter = $undo->getPrevious();
1410 $handler = $this->getContentHandler();
1411 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1416 return ContentHandler
::getContentText( $undone );
1424 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1425 * @param $text String: new text of the section
1426 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1427 * @param $edittime String: revision timestamp or null to use the current revision
1428 * @throws MWException
1429 * @return String new complete article text, or null if error
1431 * @deprecated since 1.21, use replaceSectionContent() instead
1433 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1434 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1436 if ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1437 // Whole-page edit; let the whole text through
1441 if ( !$this->supportsSections() ) {
1442 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1445 // could even make section title, but that's not required.
1446 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1448 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1450 return ContentHandler
::getContentText( $newContent );
1454 * Returns true iff this page's content model supports sections.
1456 * @return boolean whether sections are supported.
1458 * @todo: the skin should check this and not offer section functionality if sections are not supported.
1459 * @todo: the EditPage should check this and not offer section functionality if sections are not supported.
1461 public function supportsSections() {
1462 return $this->getContentHandler()->supportsSections();
1466 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1467 * @param $sectionContent Content: new content of the section
1468 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1469 * @param $edittime String: revision timestamp or null to use the current revision
1471 * @throws MWException
1472 * @return Content new complete article content, or null if error
1476 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1477 wfProfileIn( __METHOD__
);
1479 if ( strval( $section ) == '' ) {
1480 // Whole-page edit; let the whole text through
1481 $newContent = $sectionContent;
1483 if ( !$this->supportsSections() ) {
1484 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1487 // Bug 30711: always use current version when adding a new section
1488 if ( is_null( $edittime ) ||
$section == 'new' ) {
1489 $oldContent = $this->getContent();
1491 $dbw = wfGetDB( DB_MASTER
);
1492 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1495 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1496 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1497 wfProfileOut( __METHOD__
);
1501 $oldContent = $rev->getContent();
1504 if ( ! $oldContent ) {
1505 wfDebug( __METHOD__
. ": no page text\n" );
1506 wfProfileOut( __METHOD__
);
1510 // FIXME: $oldContent might be null?
1511 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1514 wfProfileOut( __METHOD__
);
1519 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1521 * @return Int updated $flags
1523 function checkFlags( $flags ) {
1524 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1525 if ( $this->exists() ) {
1526 $flags |
= EDIT_UPDATE
;
1536 * Change an existing article or create a new article. Updates RC and all necessary caches,
1537 * optionally via the deferred update array.
1539 * @param $text String: new text
1540 * @param $summary String: edit summary
1541 * @param $flags Integer bitfield:
1543 * Article is known or assumed to be non-existent, create a new one
1545 * Article is known or assumed to be pre-existing, update it
1547 * Mark this edit minor, if the user is allowed to do so
1549 * Do not log the change in recentchanges
1551 * Mark the edit a "bot" edit regardless of user rights
1552 * EDIT_DEFER_UPDATES
1553 * Defer some of the updates until the end of index.php
1555 * Fill in blank summaries with generated text where possible
1557 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1558 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1559 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1560 * edit-already-exists error will be returned. These two conditions are also possible with
1561 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1563 * @param bool|int $baseRevId int the revision ID this edit was based off, if any
1564 * @param $user User the user doing the edit
1566 * @throws MWException
1567 * @return Status object. Possible errors:
1568 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1569 * edit-gone-missing: In update mode, but the article didn't exist
1570 * edit-conflict: In update mode, the article changed unexpectedly
1571 * edit-no-change: Warning that the text was the same as before
1572 * edit-already-exists: In creation mode, but the article already exists
1574 * Extensions may define additional errors.
1576 * $return->value will contain an associative array with members as follows:
1577 * new: Boolean indicating if the function attempted to create a new article
1578 * revision: The revision object for the inserted revision, or null
1580 * Compatibility note: this function previously returned a boolean value indicating success/failure
1582 * @deprecated since 1.21: use doEditContent() instead.
1584 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1585 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1587 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1589 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1593 * Change an existing article or create a new article. Updates RC and all necessary caches,
1594 * optionally via the deferred update array.
1596 * @param $content Content: new content
1597 * @param $summary String: edit summary
1598 * @param $flags Integer bitfield:
1600 * Article is known or assumed to be non-existent, create a new one
1602 * Article is known or assumed to be pre-existing, update it
1604 * Mark this edit minor, if the user is allowed to do so
1606 * Do not log the change in recentchanges
1608 * Mark the edit a "bot" edit regardless of user rights
1609 * EDIT_DEFER_UPDATES
1610 * Defer some of the updates until the end of index.php
1612 * Fill in blank summaries with generated text where possible
1614 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1615 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1616 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1617 * edit-already-exists error will be returned. These two conditions are also possible with
1618 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1620 * @param bool|\the $baseRevId the revision ID this edit was based off, if any
1621 * @param $user User the user doing the edit
1622 * @param $serialisation_format String: format for storing the content in the database
1624 * @throws MWException
1625 * @return Status object. Possible errors:
1626 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1627 * edit-gone-missing: In update mode, but the article didn't exist
1628 * edit-conflict: In update mode, the article changed unexpectedly
1629 * edit-no-change: Warning that the text was the same as before
1630 * edit-already-exists: In creation mode, but the article already exists
1632 * Extensions may define additional errors.
1634 * $return->value will contain an associative array with members as follows:
1635 * new: Boolean indicating if the function attempted to create a new article
1636 * revision: The revision object for the inserted revision, or null
1640 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1641 User
$user = null, $serialisation_format = null ) {
1642 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1644 // Low-level sanity check
1645 if ( $this->mTitle
->getText() === '' ) {
1646 throw new MWException( 'Something is trying to edit an article with an empty title' );
1649 wfProfileIn( __METHOD__
);
1651 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1652 wfProfileOut( __METHOD__
);
1653 return Status
::newFatal( 'content-not-allowed-here',
1654 ContentHandler
::getLocalizedName( $content->getModel() ),
1655 $this->getTitle()->getPrefixedText() );
1658 $user = is_null( $user ) ?
$wgUser : $user;
1659 $status = Status
::newGood( array() );
1661 // Load the data from the master database if needed.
1662 // The caller may already loaded it from the master or even loaded it using
1663 // SELECT FOR UPDATE, so do not override that using clear().
1664 $this->loadPageData( 'fromdbmaster' );
1666 $flags = $this->checkFlags( $flags );
1669 $hook_args = array( &$this, &$user, &$content, &$summary,
1670 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1672 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1673 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1675 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1677 if ( $status->isOK() ) {
1678 $status->fatal( 'edit-hook-aborted' );
1681 wfProfileOut( __METHOD__
);
1685 // Silently ignore EDIT_MINOR if not allowed
1686 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1687 $bot = $flags & EDIT_FORCE_BOT
;
1689 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1691 $oldsize = $old_content ?
$old_content->getSize() : 0;
1692 $oldid = $this->getLatest();
1693 $oldIsRedirect = $this->isRedirect();
1694 $oldcountable = $this->isCountable();
1696 $handler = $content->getContentHandler();
1698 // Provide autosummaries if one is not provided and autosummaries are enabled.
1699 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1700 if ( !$old_content ) $old_content = null;
1701 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1704 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1705 $serialized = $editInfo->pst
;
1706 $content = $editInfo->pstContent
;
1707 $newsize = $content->getSize();
1709 $dbw = wfGetDB( DB_MASTER
);
1710 $now = wfTimestampNow();
1711 $this->mTimestamp
= $now;
1713 if ( $flags & EDIT_UPDATE
) {
1714 // Update article, but only if changed.
1715 $status->value
['new'] = false;
1718 // Article gone missing
1719 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1720 $status->fatal( 'edit-gone-missing' );
1722 wfProfileOut( __METHOD__
);
1724 } elseif ( !$old_content ) {
1725 // Sanity check for bug 37225
1726 wfProfileOut( __METHOD__
);
1727 throw new MWException( "Could not find text for current revision {$oldid}." );
1730 $revision = new Revision( array(
1731 'page' => $this->getId(),
1732 'title' => $this->getTitle(), // for determining the default content model
1733 'comment' => $summary,
1734 'minor_edit' => $isminor,
1735 'text' => $serialized,
1737 'parent_id' => $oldid,
1738 'user' => $user->getId(),
1739 'user_text' => $user->getName(),
1740 'timestamp' => $now,
1741 'content_model' => $content->getModel(),
1742 'content_format' => $serialisation_format,
1743 ) ); // XXX: pass content object?!
1745 $changed = !$content->equals( $old_content );
1748 if ( !$content->isValid() ) {
1749 throw new MWException( "New content failed validity check!" );
1752 $dbw->begin( __METHOD__
);
1754 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1755 $status->merge( $prepStatus );
1757 if ( !$status->isOK() ) {
1758 $dbw->rollback( __METHOD__
);
1760 wfProfileOut( __METHOD__
);
1764 $revisionId = $revision->insertOn( $dbw );
1768 // Note that we use $this->mLatest instead of fetching a value from the master DB
1769 // during the course of this function. This makes sure that EditPage can detect
1770 // edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1771 // before this function is called. A previous function used a separate query, this
1772 // creates a window where concurrent edits can cause an ignored edit conflict.
1773 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1776 // Belated edit conflict! Run away!!
1777 $status->fatal( 'edit-conflict' );
1779 $dbw->rollback( __METHOD__
);
1781 wfProfileOut( __METHOD__
);
1785 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1786 // Update recentchanges
1787 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1788 // Mark as patrolled if the user can do so
1789 $patrolled = $wgUseRCPatrol && !count(
1790 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1791 // Add RC row to the DB
1792 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1793 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1794 $revisionId, $patrolled
1797 // Log auto-patrolled edits
1799 PatrolLog
::record( $rc, true, $user );
1802 $user->incEditCount();
1803 $dbw->commit( __METHOD__
);
1805 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1806 // related variables correctly
1807 $revision->setId( $this->getLatest() );
1810 // Update links tables, site stats, etc.
1811 $this->doEditUpdates(
1815 'changed' => $changed,
1816 'oldcountable' => $oldcountable
1821 $status->warning( 'edit-no-change' );
1823 // Update page_touched, this is usually implicit in the page update
1824 // Other cache updates are done in onArticleEdit()
1825 $this->mTitle
->invalidateCache();
1828 // Create new article
1829 $status->value
['new'] = true;
1831 $dbw->begin( __METHOD__
);
1833 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1834 $status->merge( $prepStatus );
1836 if ( !$status->isOK() ) {
1837 $dbw->rollback( __METHOD__
);
1839 wfProfileOut( __METHOD__
);
1843 $status->merge( $prepStatus );
1845 // Add the page record; stake our claim on this title!
1846 // This will return false if the article already exists
1847 $newid = $this->insertOn( $dbw );
1849 if ( $newid === false ) {
1850 $dbw->rollback( __METHOD__
);
1851 $status->fatal( 'edit-already-exists' );
1853 wfProfileOut( __METHOD__
);
1857 // Save the revision text...
1858 $revision = new Revision( array(
1860 'title' => $this->getTitle(), // for determining the default content model
1861 'comment' => $summary,
1862 'minor_edit' => $isminor,
1863 'text' => $serialized,
1865 'user' => $user->getId(),
1866 'user_text' => $user->getName(),
1867 'timestamp' => $now,
1868 'content_model' => $content->getModel(),
1869 'content_format' => $serialisation_format,
1871 $revisionId = $revision->insertOn( $dbw );
1873 // Bug 37225: use accessor to get the text as Revision may trim it
1874 $content = $revision->getContent(); // sanity; get normalized version
1877 $newsize = $content->getSize();
1880 // Update the page record with revision data
1881 $this->updateRevisionOn( $dbw, $revision, 0 );
1883 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1885 // Update recentchanges
1886 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1887 // Mark as patrolled if the user can do so
1888 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1889 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1890 // Add RC row to the DB
1891 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1892 '', $newsize, $revisionId, $patrolled );
1894 // Log auto-patrolled edits
1896 PatrolLog
::record( $rc, true, $user );
1899 $user->incEditCount();
1900 $dbw->commit( __METHOD__
);
1902 // Update links, etc.
1903 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1905 $hook_args = array( &$this, &$user, $content, $summary,
1906 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1908 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1909 wfRunHooks( 'PageContentInsertComplete', $hook_args );
1912 // Do updates right now unless deferral was requested
1913 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1914 DeferredUpdates
::doUpdates();
1917 // Return the new revision (or null) to the caller
1918 $status->value
['revision'] = $revision;
1920 $hook_args = array( &$this, &$user, $content, $summary,
1921 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1923 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1924 wfRunHooks( 'PageContentSaveComplete', $hook_args );
1926 // Promote user to any groups they meet the criteria for
1927 $user->addAutopromoteOnceGroups( 'onEdit' );
1929 wfProfileOut( __METHOD__
);
1934 * Get parser options suitable for rendering the primary article wikitext
1936 * @see ContentHandler::makeParserOptions
1938 * @param IContextSource|User|string $context One of the following:
1939 * - IContextSource: Use the User and the Language of the provided
1941 * - User: Use the provided User object and $wgLang for the language,
1942 * so use an IContextSource object if possible.
1943 * - 'canonical': Canonical options (anonymous user with default
1944 * preferences and content language).
1945 * @return ParserOptions
1947 public function makeParserOptions( $context ) {
1948 $options = $this->getContentHandler()->makeParserOptions( $context );
1950 if ( $this->getTitle()->isConversionTable() ) {
1951 //@todo: ConversionTable should become a separate content model, so we don't need special cases like this one.
1952 $options->disableContentConversion();
1959 * Prepare text which is about to be saved.
1960 * Returns a stdclass with source, pst and output members
1962 * @deprecated in 1.21: use prepareContentForEdit instead.
1964 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1965 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1966 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1967 return $this->prepareContentForEdit( $content, $revid, $user );
1971 * Prepare content which is about to be saved.
1972 * Returns a stdclass with source, pst and output members
1974 * @param \Content $content
1975 * @param null $revid
1976 * @param null|\User $user
1977 * @param null $serialization_format
1979 * @return bool|object
1983 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) {
1984 global $wgContLang, $wgUser;
1985 $user = is_null( $user ) ?
$wgUser : $user;
1986 //XXX: check $user->getId() here???
1988 if ( $this->mPreparedEdit
1989 && $this->mPreparedEdit
->newContent
1990 && $this->mPreparedEdit
->newContent
->equals( $content )
1991 && $this->mPreparedEdit
->revid
== $revid
1992 && $this->mPreparedEdit
->format
== $serialization_format
1993 // XXX: also check $user here?
1996 return $this->mPreparedEdit
;
1999 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2000 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2002 $edit = (object)array();
2003 $edit->revid
= $revid;
2005 $edit->pstContent
= $content ?
$content->preSaveTransform( $this->mTitle
, $user, $popts ) : null;
2007 $edit->format
= $serialization_format;
2008 $edit->popts
= $this->makeParserOptions( 'canonical' );
2009 $edit->output
= $edit->pstContent ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
) : null;
2011 $edit->newContent
= $content;
2012 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2014 // NOTE: B/C for hooks! don't use these fields!
2015 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2016 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2017 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialization_format ) : '';
2019 $this->mPreparedEdit
= $edit;
2024 * Do standard deferred updates after page edit.
2025 * Update links tables, site stats, search index and message cache.
2026 * Purges pages that include this page if the text was changed here.
2027 * Every 100th edit, prune the recent changes table.
2029 * @param $revision Revision object
2030 * @param $user User object that did the revision
2031 * @param $options Array of options, following indexes are used:
2032 * - changed: boolean, whether the revision changed the content (default true)
2033 * - created: boolean, whether the revision created the page (default false)
2034 * - oldcountable: boolean or null (default null):
2035 * - boolean: whether the page was counted as an article before that
2036 * revision, only used in changed is true and created is false
2037 * - null: don't change the article count
2039 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2040 global $wgEnableParserCache;
2042 wfProfileIn( __METHOD__
);
2044 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2045 $content = $revision->getContent();
2048 // Be careful not to double-PST: $text is usually already PST-ed once
2049 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2050 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2051 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2053 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2054 $editInfo = $this->mPreparedEdit
;
2057 // Save it to the parser cache
2058 if ( $wgEnableParserCache ) {
2059 $parserCache = ParserCache
::singleton();
2060 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2063 // Update the links tables and other secondary data
2065 $updates = $content->getSecondaryDataUpdates( $this->getTitle(), null, true, $editInfo->output
);
2066 DataUpdate
::runUpdates( $updates );
2069 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2071 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2072 if ( 0 == mt_rand( 0, 99 ) ) {
2073 // Flush old entries from the `recentchanges` table; we do this on
2074 // random requests so as to avoid an increase in writes for no good reason
2077 $dbw = wfGetDB( DB_MASTER
);
2078 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2081 array( 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ),
2087 if ( !$this->exists() ) {
2088 wfProfileOut( __METHOD__
);
2092 $id = $this->getId();
2093 $title = $this->mTitle
->getPrefixedDBkey();
2094 $shortTitle = $this->mTitle
->getDBkey();
2096 if ( !$options['changed'] ) {
2099 } elseif ( $options['created'] ) {
2100 $good = (int)$this->isCountable( $editInfo );
2102 } elseif ( $options['oldcountable'] !== null ) {
2103 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2110 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2111 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
2112 // @TODO: let the search engine decide what to do with the content object
2114 // If this is another user's talk page, update newtalk.
2115 // Don't do this if $options['changed'] = false (null-edits) nor if
2116 // it's a minor edit and the user doesn't want notifications for those.
2117 if ( $options['changed']
2118 && $this->mTitle
->getNamespace() == NS_USER_TALK
2119 && $shortTitle != $user->getTitleKey()
2120 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2122 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2123 $other = User
::newFromName( $shortTitle, false );
2125 wfDebug( __METHOD__
. ": invalid username\n" );
2126 } elseif ( User
::isIP( $shortTitle ) ) {
2127 // An anonymous user
2128 $other->setNewtalk( true, $revision );
2129 } elseif ( $other->isLoggedIn() ) {
2130 $other->setNewtalk( true, $revision );
2132 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2137 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2138 // XXX: could skip pseudo-messages like js/css here, based on content model.
2139 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2140 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
2142 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2145 if( $options['created'] ) {
2146 self
::onArticleCreate( $this->mTitle
);
2148 self
::onArticleEdit( $this->mTitle
);
2151 wfProfileOut( __METHOD__
);
2155 * Edit an article without doing all that other stuff
2156 * The article must already exist; link tables etc
2157 * are not updated, caches are not flushed.
2159 * @param $text String: text submitted
2160 * @param $user User The relevant user
2161 * @param $comment String: comment submitted
2162 * @param $minor Boolean: whereas it's a minor modification
2164 * @deprecated since 1.21, use doEditContent() instead.
2166 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2167 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2169 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2170 return $this->doQuickEditContent( $content, $user, $comment, $minor );
2174 * Edit an article without doing all that other stuff
2175 * The article must already exist; link tables etc
2176 * are not updated, caches are not flushed.
2178 * @param $content Content: content submitted
2179 * @param $user User The relevant user
2180 * @param $comment String: comment submitted
2181 * @param $serialisation_format String: format for storing the content in the database
2182 * @param $minor Boolean: whereas it's a minor modification
2184 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
2185 wfProfileIn( __METHOD__
);
2187 $serialized = $content->serialize( $serialisation_format );
2189 $dbw = wfGetDB( DB_MASTER
);
2190 $revision = new Revision( array(
2191 'title' => $this->getTitle(), // for determining the default content model
2192 'page' => $this->getId(),
2193 'text' => $serialized,
2194 'length' => $content->getSize(),
2195 'comment' => $comment,
2196 'minor_edit' => $minor ?
1 : 0,
2197 ) ); // XXX: set the content object?
2198 $revision->insertOn( $dbw );
2199 $this->updateRevisionOn( $dbw, $revision );
2201 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2203 wfProfileOut( __METHOD__
);
2207 * Update the article's restriction field, and leave a log entry.
2208 * This works for protection both existing and non-existing pages.
2210 * @param $limit Array: set of restriction keys
2211 * @param $reason String
2212 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2213 * @param $expiry Array: per restriction type expiration
2214 * @param $user User The user updating the restrictions
2217 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2220 if ( wfReadOnly() ) {
2221 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2224 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2226 $id = $this->getId();
2232 // Take this opportunity to purge out expired restrictions
2233 Title
::purgeExpiredRestrictions();
2235 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2236 // we expect a single selection, but the schema allows otherwise.
2237 $isProtected = false;
2241 $dbw = wfGetDB( DB_MASTER
);
2243 foreach ( $restrictionTypes as $action ) {
2244 if ( !isset( $expiry[$action] ) ) {
2245 $expiry[$action] = $dbw->getInfinity();
2247 if ( !isset( $limit[$action] ) ) {
2248 $limit[$action] = '';
2249 } elseif ( $limit[$action] != '' ) {
2253 // Get current restrictions on $action
2254 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2255 if ( $current != '' ) {
2256 $isProtected = true;
2259 if ( $limit[$action] != $current ) {
2261 } elseif ( $limit[$action] != '' ) {
2262 // Only check expiry change if the action is actually being
2263 // protected, since expiry does nothing on an not-protected
2265 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2271 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2275 // If nothing's changed, do nothing
2277 return Status
::newGood();
2280 if ( !$protect ) { // No protection at all means unprotection
2281 $revCommentMsg = 'unprotectedarticle';
2282 $logAction = 'unprotect';
2283 } elseif ( $isProtected ) {
2284 $revCommentMsg = 'modifiedarticleprotection';
2285 $logAction = 'modify';
2287 $revCommentMsg = 'protectedarticle';
2288 $logAction = 'protect';
2291 $encodedExpiry = array();
2292 $protectDescription = '';
2293 # Some bots may parse IRC lines, which are generated from log entries which contain plain
2294 # protect description text. Keep them in old format to avoid breaking compatibility.
2295 # TODO: Fix protection log to store structured description and format it on-the-fly.
2296 $protectDescriptionLog = '';
2297 foreach ( $limit as $action => $restrictions ) {
2298 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2299 if ( $restrictions != '' ) {
2300 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2301 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2302 # All possible message keys are listed here for easier grepping:
2303 # * restriction-create
2304 # * restriction-edit
2305 # * restriction-move
2306 # * restriction-upload
2307 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2308 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2309 # with '' filtered out. All possible message keys are listed below:
2310 # * protect-level-autoconfirmed
2311 # * protect-level-sysop
2312 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2313 if ( $encodedExpiry[$action] != 'infinity' ) {
2314 $expiryText = wfMessage(
2316 $wgContLang->timeanddate( $expiry[$action], false, false ),
2317 $wgContLang->date( $expiry[$action], false, false ),
2318 $wgContLang->time( $expiry[$action], false, false )
2319 )->inContentLanguage()->text();
2321 $expiryText = wfMessage( 'protect-expiry-indefinite' )
2322 ->inContentLanguage()->text();
2325 if ( $protectDescription !== '' ) {
2326 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2328 $protectDescription .= wfMessage( 'protect-summary-desc' )
2329 ->params( $actionText, $restrictionsText, $expiryText )
2330 ->inContentLanguage()->text();
2331 $protectDescriptionLog .= $expiryText . ') ';
2334 $protectDescriptionLog = trim( $protectDescriptionLog );
2336 if ( $id ) { // Protection of existing page
2337 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2338 return Status
::newGood();
2341 // Only restrictions with the 'protect' right can cascade...
2342 // Otherwise, people who cannot normally protect can "protect" pages via transclusion
2343 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2345 // The schema allows multiple restrictions
2346 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2350 // Update restrictions table
2351 foreach ( $limit as $action => $restrictions ) {
2352 if ( $restrictions != '' ) {
2353 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2354 array( 'pr_page' => $id,
2355 'pr_type' => $action,
2356 'pr_level' => $restrictions,
2357 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2358 'pr_expiry' => $encodedExpiry[$action]
2363 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2364 'pr_type' => $action ), __METHOD__
);
2368 // Prepare a null revision to be added to the history
2369 $editComment = $wgContLang->ucfirst(
2372 $this->mTitle
->getPrefixedText()
2373 )->inContentLanguage()->text()
2376 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2378 if ( $protectDescription ) {
2379 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2380 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2383 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2384 $editComment .= wfMessage( 'brackets' )->params(
2385 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2386 )->inContentLanguage()->text();
2389 // Insert a null revision
2390 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2391 $nullRevId = $nullRevision->insertOn( $dbw );
2393 $latest = $this->getLatest();
2394 // Update page record
2395 $dbw->update( 'page',
2397 'page_touched' => $dbw->timestamp(),
2398 'page_restrictions' => '',
2399 'page_latest' => $nullRevId
2400 ), array( /* WHERE */
2405 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2406 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2407 } else { // Protection of non-existing page (also known as "title protection")
2408 // Cascade protection is meaningless in this case
2411 if ( $limit['create'] != '' ) {
2412 $dbw->replace( 'protected_titles',
2413 array( array( 'pt_namespace', 'pt_title' ) ),
2415 'pt_namespace' => $this->mTitle
->getNamespace(),
2416 'pt_title' => $this->mTitle
->getDBkey(),
2417 'pt_create_perm' => $limit['create'],
2418 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2419 'pt_expiry' => $encodedExpiry['create'],
2420 'pt_user' => $user->getId(),
2421 'pt_reason' => $reason,
2425 $dbw->delete( 'protected_titles',
2427 'pt_namespace' => $this->mTitle
->getNamespace(),
2428 'pt_title' => $this->mTitle
->getDBkey()
2434 $this->mTitle
->flushRestrictions();
2436 if ( $logAction == 'unprotect' ) {
2437 $logParams = array();
2439 $logParams = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2442 // Update the protection log
2443 $log = new LogPage( 'protect' );
2444 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2446 return Status
::newGood();
2450 * Take an array of page restrictions and flatten it to a string
2451 * suitable for insertion into the page_restrictions field.
2452 * @param $limit Array
2453 * @throws MWException
2456 protected static function flattenRestrictions( $limit ) {
2457 if ( !is_array( $limit ) ) {
2458 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2464 foreach ( $limit as $action => $restrictions ) {
2465 if ( $restrictions != '' ) {
2466 $bits[] = "$action=$restrictions";
2470 return implode( ':', $bits );
2474 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2475 * backwards compatibility, if you care about error reporting you should use
2476 * doDeleteArticleReal() instead.
2478 * Deletes the article with database consistency, writes logs, purges caches
2480 * @param $reason string delete reason for deletion log
2481 * @param $suppress boolean suppress all revisions and log the deletion in
2482 * the suppression log instead of the deletion log
2483 * @param $id int article ID
2484 * @param $commit boolean defaults to true, triggers transaction end
2485 * @param &$error Array of errors to append to
2486 * @param $user User The deleting user
2487 * @return boolean true if successful
2489 public function doDeleteArticle(
2490 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2492 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2493 return $status->isGood();
2497 * Back-end article deletion
2498 * Deletes the article with database consistency, writes logs, purges caches
2502 * @param $reason string delete reason for deletion log
2503 * @param $suppress boolean suppress all revisions and log the deletion in
2504 * the suppression log instead of the deletion log
2505 * @param $id int article ID
2506 * @param $commit boolean defaults to true, triggers transaction end
2507 * @param &$error Array of errors to append to
2508 * @param $user User The deleting user
2509 * @return Status: Status object; if successful, $status->value is the log_id of the
2510 * deletion log entry. If the page couldn't be deleted because it wasn't
2511 * found, $status is a non-fatal 'cannotdelete' error
2513 public function doDeleteArticleReal(
2514 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2516 global $wgUser, $wgContentHandlerUseDB;
2518 wfDebug( __METHOD__
. "\n" );
2520 $status = Status
::newGood();
2522 if ( $this->mTitle
->getDBkey() === '' ) {
2523 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2527 $user = is_null( $user ) ?
$wgUser : $user;
2528 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2529 if ( $status->isOK() ) {
2530 // Hook aborted but didn't set a fatal status
2531 $status->fatal( 'delete-hook-aborted' );
2537 $this->loadPageData( 'forupdate' );
2538 $id = $this->getID();
2540 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2545 // Bitfields to further suppress the content
2548 // This should be 15...
2549 $bitfield |
= Revision
::DELETED_TEXT
;
2550 $bitfield |
= Revision
::DELETED_COMMENT
;
2551 $bitfield |
= Revision
::DELETED_USER
;
2552 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2554 $bitfield = 'rev_deleted';
2557 // we need to remember the old content so we can use it to generate all deletion updates.
2558 $content = $this->getContent( Revision
::RAW
);
2560 $dbw = wfGetDB( DB_MASTER
);
2561 $dbw->begin( __METHOD__
);
2562 // For now, shunt the revision data into the archive table.
2563 // Text is *not* removed from the text table; bulk storage
2564 // is left intact to avoid breaking block-compression or
2565 // immutable storage schemes.
2567 // For backwards compatibility, note that some older archive
2568 // table entries will have ar_text and ar_flags fields still.
2570 // In the future, we may keep revisions and mark them with
2571 // the rev_deleted field, which is reserved for this purpose.
2574 'ar_namespace' => 'page_namespace',
2575 'ar_title' => 'page_title',
2576 'ar_comment' => 'rev_comment',
2577 'ar_user' => 'rev_user',
2578 'ar_user_text' => 'rev_user_text',
2579 'ar_timestamp' => 'rev_timestamp',
2580 'ar_minor_edit' => 'rev_minor_edit',
2581 'ar_rev_id' => 'rev_id',
2582 'ar_parent_id' => 'rev_parent_id',
2583 'ar_text_id' => 'rev_text_id',
2584 'ar_text' => '\'\'', // Be explicit to appease
2585 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2586 'ar_len' => 'rev_len',
2587 'ar_page_id' => 'page_id',
2588 'ar_deleted' => $bitfield,
2589 'ar_sha1' => 'rev_sha1',
2592 if ( $wgContentHandlerUseDB ) {
2593 $row[ 'ar_content_model' ] = 'rev_content_model';
2594 $row[ 'ar_content_format' ] = 'rev_content_format';
2597 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2601 'page_id = rev_page'
2605 // Now that it's safely backed up, delete it
2606 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2607 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2610 $dbw->rollback( __METHOD__
);
2611 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2615 $this->doDeleteUpdates( $id, $content );
2617 // Log the deletion, if the page was suppressed, log it at Oversight instead
2618 $logtype = $suppress ?
'suppress' : 'delete';
2620 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2621 $logEntry->setPerformer( $user );
2622 $logEntry->setTarget( $this->mTitle
);
2623 $logEntry->setComment( $reason );
2624 $logid = $logEntry->insert();
2625 $logEntry->publish( $logid );
2628 $dbw->commit( __METHOD__
);
2631 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2632 $status->value
= $logid;
2637 * Do some database updates after deletion
2639 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2640 * @param $content Content: optional page content to be used when determining the required updates.
2641 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2643 public function doDeleteUpdates( $id, Content
$content = null ) {
2644 // update site status
2645 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2647 // remove secondary indexes, etc
2648 $updates = $this->getDeletionUpdates( $content );
2649 DataUpdate
::runUpdates( $updates );
2652 WikiPage
::onArticleDelete( $this->mTitle
);
2654 // Reset this object and the Title object
2655 $this->loadFromRow( false, self
::READ_LATEST
);
2659 * Roll back the most recent consecutive set of edits to a page
2660 * from the same user; fails if there are no eligible edits to
2661 * roll back to, e.g. user is the sole contributor. This function
2662 * performs permissions checks on $user, then calls commitRollback()
2663 * to do the dirty work
2665 * @todo: seperate the business/permission stuff out from backend code
2667 * @param $fromP String: Name of the user whose edits to rollback.
2668 * @param $summary String: Custom summary. Set to default summary if empty.
2669 * @param $token String: Rollback token.
2670 * @param $bot Boolean: If true, mark all reverted edits as bot.
2672 * @param $resultDetails Array: contains result-specific array of additional values
2673 * 'alreadyrolled' : 'current' (rev)
2674 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2676 * @param $user User The user performing the rollback
2677 * @return array of errors, each error formatted as
2678 * array(messagekey, param1, param2, ...).
2679 * On success, the array is empty. This array can also be passed to
2680 * OutputPage::showPermissionsErrorPage().
2682 public function doRollback(
2683 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2685 $resultDetails = null;
2687 // Check permissions
2688 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2689 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2690 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2692 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2693 $errors[] = array( 'sessionfailure' );
2696 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2697 $errors[] = array( 'actionthrottledtext' );
2700 // If there were errors, bail out now
2701 if ( !empty( $errors ) ) {
2705 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2709 * Backend implementation of doRollback(), please refer there for parameter
2710 * and return value documentation
2712 * NOTE: This function does NOT check ANY permissions, it just commits the
2713 * rollback to the DB. Therefore, you should only call this function direct-
2714 * ly if you want to use custom permissions checks. If you don't, use
2715 * doRollback() instead.
2716 * @param $fromP String: Name of the user whose edits to rollback.
2717 * @param $summary String: Custom summary. Set to default summary if empty.
2718 * @param $bot Boolean: If true, mark all reverted edits as bot.
2720 * @param $resultDetails Array: contains result-specific array of additional values
2721 * @param $guser User The user performing the rollback
2724 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2725 global $wgUseRCPatrol, $wgContLang;
2727 $dbw = wfGetDB( DB_MASTER
);
2729 if ( wfReadOnly() ) {
2730 return array( array( 'readonlytext' ) );
2733 // Get the last editor
2734 $current = $this->getRevision();
2735 if ( is_null( $current ) ) {
2736 // Something wrong... no page?
2737 return array( array( 'notanarticle' ) );
2740 $from = str_replace( '_', ' ', $fromP );
2741 // User name given should match up with the top revision.
2742 // If the user was deleted then $from should be empty.
2743 if ( $from != $current->getUserText() ) {
2744 $resultDetails = array( 'current' => $current );
2745 return array( array( 'alreadyrolled',
2746 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2747 htmlspecialchars( $fromP ),
2748 htmlspecialchars( $current->getUserText() )
2752 // Get the last edit not by this guy...
2753 // Note: these may not be public values
2754 $user = intval( $current->getRawUser() );
2755 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2756 $s = $dbw->selectRow( 'revision',
2757 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2758 array( 'rev_page' => $current->getPage(),
2759 "rev_user != {$user} OR rev_user_text != {$user_text}"
2761 array( 'USE INDEX' => 'page_timestamp',
2762 'ORDER BY' => 'rev_timestamp DESC' )
2764 if ( $s === false ) {
2765 // No one else ever edited this page
2766 return array( array( 'cantrollback' ) );
2767 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2768 // Only admins can see this text
2769 return array( array( 'notvisiblerev' ) );
2773 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2774 // Mark all reverted edits as bot
2778 if ( $wgUseRCPatrol ) {
2779 // Mark all reverted edits as patrolled
2780 $set['rc_patrolled'] = 1;
2783 if ( count( $set ) ) {
2784 $dbw->update( 'recentchanges', $set,
2786 'rc_cur_id' => $current->getPage(),
2787 'rc_user_text' => $current->getUserText(),
2788 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2793 // Generate the edit summary if necessary
2794 $target = Revision
::newFromId( $s->rev_id
);
2795 if ( empty( $summary ) ) {
2796 if ( $from == '' ) { // no public user name
2797 $summary = wfMessage( 'revertpage-nouser' );
2799 $summary = wfMessage( 'revertpage' );
2803 // Allow the custom summary to use the same args as the default message
2805 $target->getUserText(), $from, $s->rev_id
,
2806 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2807 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2809 if( $summary instanceof Message
) {
2810 $summary = $summary->params( $args )->inContentLanguage()->text();
2812 $summary = wfMsgReplaceArgs( $summary, $args );
2815 // Trim spaces on user supplied text
2816 $summary = trim( $summary );
2818 // Truncate for whole multibyte characters.
2819 $summary = $wgContLang->truncate( $summary, 255 );
2822 $flags = EDIT_UPDATE
;
2824 if ( $guser->isAllowed( 'minoredit' ) ) {
2825 $flags |
= EDIT_MINOR
;
2828 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2829 $flags |
= EDIT_FORCE_BOT
;
2832 // Actually store the edit
2833 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2835 if ( !$status->isOK() ) {
2836 return $status->getErrorsArray();
2839 if ( !empty( $status->value
['revision'] ) ) {
2840 $revId = $status->value
['revision']->getId();
2845 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2847 $resultDetails = array(
2848 'summary' => $summary,
2849 'current' => $current,
2850 'target' => $target,
2858 * The onArticle*() functions are supposed to be a kind of hooks
2859 * which should be called whenever any of the specified actions
2862 * This is a good place to put code to clear caches, for instance.
2864 * This is called on page move and undelete, as well as edit
2866 * @param $title Title object
2868 public static function onArticleCreate( $title ) {
2869 // Update existence markers on article/talk tabs...
2870 if ( $title->isTalkPage() ) {
2871 $other = $title->getSubjectPage();
2873 $other = $title->getTalkPage();
2876 $other->invalidateCache();
2877 $other->purgeSquid();
2879 $title->touchLinks();
2880 $title->purgeSquid();
2881 $title->deleteTitleProtection();
2885 * Clears caches when article is deleted
2887 * @param $title Title
2889 public static function onArticleDelete( $title ) {
2890 // Update existence markers on article/talk tabs...
2891 if ( $title->isTalkPage() ) {
2892 $other = $title->getSubjectPage();
2894 $other = $title->getTalkPage();
2897 $other->invalidateCache();
2898 $other->purgeSquid();
2900 $title->touchLinks();
2901 $title->purgeSquid();
2904 HTMLFileCache
::clearFileCache( $title );
2907 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2908 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2912 if ( $title->getNamespace() == NS_FILE
) {
2913 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2914 $update->doUpdate();
2918 if ( $title->getNamespace() == NS_USER_TALK
) {
2919 $user = User
::newFromName( $title->getText(), false );
2921 $user->setNewtalk( false );
2926 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2930 * Purge caches on page update etc
2932 * @param $title Title object
2933 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2935 public static function onArticleEdit( $title ) {
2936 // Invalidate caches of articles which include this page
2937 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2939 // Invalidate the caches of all pages which redirect here
2940 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2942 // Purge squid for this page only
2943 $title->purgeSquid();
2945 // Clear file cache for this page only
2946 HTMLFileCache
::clearFileCache( $title );
2952 * Returns a list of hidden categories this page is a member of.
2953 * Uses the page_props and categorylinks tables.
2955 * @return Array of Title objects
2957 public function getHiddenCategories() {
2959 $id = $this->getId();
2965 $dbr = wfGetDB( DB_SLAVE
);
2966 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2968 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2969 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2972 if ( $res !== false ) {
2973 foreach ( $res as $row ) {
2974 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2982 * Return an applicable autosummary if one exists for the given edit.
2983 * @param $oldtext String|null: the previous text of the page.
2984 * @param $newtext String|null: The submitted text of the page.
2985 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2986 * @return string An appropriate autosummary, or an empty string.
2988 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
2990 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2991 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2993 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2995 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
2996 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
2997 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
2999 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3003 * Auto-generates a deletion reason
3005 * @param &$hasHistory Boolean: whether the page has a history
3006 * @return mixed String containing deletion reason or empty string, or boolean false
3007 * if no revision occurred
3009 public function getAutoDeleteReason( &$hasHistory ) {
3010 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3014 * Update all the appropriate counts in the category table, given that
3015 * we've added the categories $added and deleted the categories $deleted.
3017 * @param $added array The names of categories that were added
3018 * @param $deleted array The names of categories that were deleted
3020 public function updateCategoryCounts( $added, $deleted ) {
3021 $ns = $this->mTitle
->getNamespace();
3022 $dbw = wfGetDB( DB_MASTER
);
3024 // First make sure the rows exist. If one of the "deleted" ones didn't
3025 // exist, we might legitimately not create it, but it's simpler to just
3026 // create it and then give it a negative value, since the value is bogus
3029 // Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3030 $insertCats = array_merge( $added, $deleted );
3031 if ( !$insertCats ) {
3032 // Okay, nothing to do
3036 $insertRows = array();
3038 foreach ( $insertCats as $cat ) {
3039 $insertRows[] = array(
3040 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
3044 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
3046 $addFields = array( 'cat_pages = cat_pages + 1' );
3047 $removeFields = array( 'cat_pages = cat_pages - 1' );
3049 if ( $ns == NS_CATEGORY
) {
3050 $addFields[] = 'cat_subcats = cat_subcats + 1';
3051 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3052 } elseif ( $ns == NS_FILE
) {
3053 $addFields[] = 'cat_files = cat_files + 1';
3054 $removeFields[] = 'cat_files = cat_files - 1';
3061 array( 'cat_title' => $added ),
3070 array( 'cat_title' => $deleted ),
3077 * Updates cascading protections
3079 * @param $parserOutput ParserOutput object for the current version
3081 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3082 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3086 // templatelinks table may have become out of sync,
3087 // especially if using variable-based transclusions.
3088 // For paranoia, check if things have changed and if
3089 // so apply updates to the database. This will ensure
3090 // that cascaded protections apply as soon as the changes
3093 // Get templates from templatelinks
3094 $id = $this->getId();
3096 $tlTemplates = array();
3098 $dbr = wfGetDB( DB_SLAVE
);
3099 $res = $dbr->select( array( 'templatelinks' ),
3100 array( 'tl_namespace', 'tl_title' ),
3101 array( 'tl_from' => $id ),
3105 foreach ( $res as $row ) {
3106 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3109 // Get templates from parser output.
3110 $poTemplates = array();
3111 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3112 foreach ( $templates as $dbk => $id ) {
3113 $poTemplates["$ns:$dbk"] = true;
3118 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3120 if ( count( $templates_diff ) > 0 ) {
3121 // Whee, link updates time.
3122 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3123 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3129 * Return a list of templates used by this article.
3130 * Uses the templatelinks table
3132 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3133 * @return Array of Title objects
3135 public function getUsedTemplates() {
3136 return $this->mTitle
->getTemplateLinksFrom();
3140 * Perform article updates on a special page creation.
3142 * @param $rev Revision object
3144 * @todo This is a shitty interface function. Kill it and replace the
3145 * other shitty functions like doEditUpdates and such so it's not needed
3147 * @deprecated since 1.18, use doEditUpdates()
3149 public function createUpdates( $rev ) {
3150 wfDeprecated( __METHOD__
, '1.18' );
3152 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3156 * This function is called right before saving the wikitext,
3157 * so we can do things like signatures and links-in-context.
3159 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3160 * @param $text String article contents
3161 * @param $user User object: user doing the edit
3162 * @param $popts ParserOptions object: parser options, default options for
3163 * the user loaded if null given
3164 * @return string article contents with altered wikitext markup (signatures
3165 * converted, {{subst:}}, templates, etc.)
3167 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3168 global $wgParser, $wgUser;
3170 wfDeprecated( __METHOD__
, '1.19' );
3172 $user = is_null( $user ) ?
$wgUser : $user;
3174 if ( $popts === null ) {
3175 $popts = ParserOptions
::newFromUser( $user );
3178 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3182 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3184 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3187 public function isBigDeletion() {
3188 wfDeprecated( __METHOD__
, '1.19' );
3189 return $this->mTitle
->isBigDeletion();
3193 * Get the approximate revision count of this page.
3195 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3198 public function estimateRevisionCount() {
3199 wfDeprecated( __METHOD__
, '1.19' );
3200 return $this->mTitle
->estimateRevisionCount();
3204 * Update the article's restriction field, and leave a log entry.
3206 * @deprecated since 1.19
3207 * @param $limit Array: set of restriction keys
3208 * @param $reason String
3209 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3210 * @param $expiry Array: per restriction type expiration
3211 * @param $user User The user updating the restrictions
3212 * @return bool true on success
3214 public function updateRestrictions(
3215 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3219 $user = is_null( $user ) ?
$wgUser : $user;
3221 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3225 * @deprecated since 1.18
3227 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3228 wfDeprecated( __METHOD__
, '1.18' );
3230 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3234 * @deprecated since 1.18
3236 public function viewUpdates() {
3237 wfDeprecated( __METHOD__
, '1.18' );
3239 return $this->doViewUpdates( $wgUser );
3243 * @deprecated since 1.18
3247 public function useParserCache( $oldid ) {
3248 wfDeprecated( __METHOD__
, '1.18' );
3250 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3254 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3255 * about this page from secondary data stores such as links tables.
3257 * @param Content|null $content optional Content object for determining the necessary updates
3258 * @return Array an array of DataUpdates objects
3260 public function getDeletionUpdates( Content
$content = null ) {
3262 // load content object, which may be used to determine the necessary updates
3263 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3264 $content = $this->getContent( Revision
::RAW
);
3270 $updates = $content->getDeletionUpdates( $this );
3273 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3279 class PoolWorkArticleView
extends PoolCounterWork
{
3297 * @var ParserOptions
3299 private $parserOptions;
3304 private $content = null;
3307 * @var ParserOutput|bool
3309 private $parserOutput = false;
3314 private $isDirty = false;
3319 private $error = false;
3325 * @param $revid Integer: ID of the revision being parsed
3326 * @param $useParserCache Boolean: whether to use the parser cache
3327 * @param $parserOptions parserOptions to use for the parse operation
3328 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3330 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3331 if ( is_string( $content ) ) { // BC: old style call
3332 $modelId = $page->getRevision()->getContentModel();
3333 $format = $page->getRevision()->getContentFormat();
3334 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3337 $this->page
= $page;
3338 $this->revid
= $revid;
3339 $this->cacheable
= $useParserCache;
3340 $this->parserOptions
= $parserOptions;
3341 $this->content
= $content;
3342 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3343 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3347 * Get the ParserOutput from this object, or false in case of failure
3349 * @return ParserOutput
3351 public function getParserOutput() {
3352 return $this->parserOutput
;
3356 * Get whether the ParserOutput is a dirty one (i.e. expired)
3360 public function getIsDirty() {
3361 return $this->isDirty
;
3365 * Get a Status object in case of error or false otherwise
3367 * @return Status|bool
3369 public function getError() {
3370 return $this->error
;
3377 global $wgUseFileCache;
3379 // @todo: several of the methods called on $this->page are not declared in Page, but present
3380 // in WikiPage and delegated by Article.
3382 $isCurrent = $this->revid
=== $this->page
->getLatest();
3384 if ( $this->content
!== null ) {
3385 $content = $this->content
;
3386 } elseif ( $isCurrent ) {
3387 // XXX: why use RAW audience here, and PUBLIC (default) below?
3388 $content = $this->page
->getContent( Revision
::RAW
);
3390 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3392 if ( $rev === null ) {
3395 // XXX: why use PUBLIC audience here (default), and RAW above?
3396 $content = $rev->getContent();
3400 if ( $content === null ) {
3404 $time = - microtime( true );
3405 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3406 $time +
= microtime( true );
3410 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3411 $this->page
->getTitle()->getPrefixedDBkey() ) );
3414 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3415 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3418 // Make sure file cache is not used on uncacheable content.
3419 // Output that has magic words in it can still use the parser cache
3420 // (if enabled), though it will generally expire sooner.
3421 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3422 $wgUseFileCache = false;
3426 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3435 function getCachedWork() {
3436 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3438 if ( $this->parserOutput
=== false ) {
3439 wfDebug( __METHOD__
. ": parser cache miss\n" );
3442 wfDebug( __METHOD__
. ": parser cache hit\n" );
3450 function fallback() {
3451 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3453 if ( $this->parserOutput
=== false ) {
3454 wfDebugLog( 'dirty', "dirty missing\n" );
3455 wfDebug( __METHOD__
. ": no dirty cache\n" );
3458 wfDebug( __METHOD__
. ": sending dirty output\n" );
3459 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3460 $this->isDirty
= true;
3466 * @param $status Status
3469 function error( $status ) {
3470 $this->error
= $status;