3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
26 abstract class Page
{}
29 * Class representing a MediaWiki article and history.
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
34 * @internal documentation reviewed 15 Mar 2010
36 class WikiPage
extends Page
{
37 // doDeleteArticleReal() return values. Values less than zero indicate fatal errors,
38 // values greater than zero indicate that there were problems not resulting in page
42 * Delete operation aborted by hook
44 const DELETE_HOOK_ABORTED
= -1;
49 const DELETE_SUCCESS
= 0;
54 const DELETE_NO_PAGE
= 1;
57 * No revisions found to delete
59 const DELETE_NO_REVISIONS
= 2;
61 // Constants for $mDataLoadedFrom and related
64 * Data has not been loaded yet (or the object was cleared)
66 const DATA_NOT_LOADED
= 0;
69 * Data has been loaded from a slave database
71 const DATA_FROM_SLAVE
= 1;
74 * Data has been loaded from the master database
76 const DATA_FROM_MASTER
= 2;
79 * Data has been loaded from the master database using FOR UPDATE
81 const DATA_FOR_UPDATE
= 3;
86 public $mTitle = null;
91 public $mDataLoaded = false; // !< Boolean
92 public $mIsRedirect = false; // !< Boolean
93 public $mLatest = false; // !< Integer (false means "not loaded")
94 public $mPreparedEdit = false; // !< Array
98 * @var int; one of the DATA_* constants
100 protected $mDataLoadedFrom = self
::DATA_NOT_LOADED
;
105 protected $mRedirectTarget = null;
110 protected $mLastRevision = null;
113 * @var string; timestamp of the current revision or empty string if not loaded
115 protected $mTimestamp = '';
120 protected $mTouched = '19700101000000';
125 protected $mCounter = null;
128 * Constructor and clear the article
129 * @param $title Title Reference to a Title object.
131 public function __construct( Title
$title ) {
132 $this->mTitle
= $title;
136 * Create a WikiPage object of the appropriate class for the given title.
138 * @param $title Title
139 * @return WikiPage object of the appropriate type
141 public static function factory( Title
$title ) {
142 $ns = $title->getNamespace();
144 if ( $ns == NS_MEDIA
) {
145 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
146 } elseif ( $ns < 0 ) {
147 throw new MWException( "Invalid or virtual namespace $ns given." );
152 $page = new WikiFilePage( $title );
155 $page = new WikiCategoryPage( $title );
158 $page = new WikiPage( $title );
165 * Constructor from a page id
167 * @param $id Int article ID to load
168 * @param $from string|int one of the following values:
169 * - "fromdb" or self::DATA_FROM_SLAVE to select from a slave database
170 * - "fromdbmaster" or self::DATA_FROM_MASTER to select from the master database
172 * @return WikiPage|null
174 public static function newFromID( $id, $from = 'fromdb' ) {
175 $from = self
::convertSelectType( $from );
176 $db = wfGetDB( $from === self
::DATA_FROM_MASTER ? DB_MASTER
: DB_SLAVE
);
177 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
181 return self
::newFromRow( $row, $from );
185 * Constructor from a database row
188 * @param $row object: database row containing at least fields returned
190 * @param $from string|int: source of $data:
191 * - "fromdb" or self::DATA_FROM_SLAVE: from a slave DB
192 * - "fromdbmaster" or self::DATA_FROM_MASTER: from the master DB
193 * - "forupdate" or self::DATA_FOR_UPDATE: from the master DB using SELECT FOR UPDATE
196 public static function newFromRow( $row, $from = 'fromdb' ) {
197 $page = self
::factory( Title
::newFromRow( $row ) );
198 $page->loadFromRow( $row, $from );
203 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to DATA_* constants.
205 * @param $type object|string|int
208 private static function convertSelectType( $type ) {
211 return self
::DATA_FROM_SLAVE
;
213 return self
::DATA_FROM_MASTER
;
215 return self
::DATA_FOR_UPDATE
;
217 // It may already be an integer or whatever else
223 * Returns overrides for action handlers.
224 * Classes listed here will be used instead of the default one when
225 * (and only when) $wgActions[$action] === true. This allows subclasses
226 * to override the default behavior.
228 * @todo: move this UI stuff somewhere else
232 public function getActionOverrides() {
237 * Get the title object of the article
238 * @return Title object of this page
240 public function getTitle() {
241 return $this->mTitle
;
248 public function clear() {
249 $this->mDataLoaded
= false;
250 $this->mDataLoadedFrom
= self
::DATA_NOT_LOADED
;
252 $this->clearCacheFields();
256 * Clear the object cache fields
259 protected function clearCacheFields() {
260 $this->mCounter
= null;
261 $this->mRedirectTarget
= null; # Title object if set
262 $this->mLastRevision
= null; # Latest revision
263 $this->mTouched
= '19700101000000';
264 $this->mTimestamp
= '';
265 $this->mIsRedirect
= false;
266 $this->mLatest
= false;
267 $this->mPreparedEdit
= false;
271 * Return the list of revision fields that should be selected to create
276 public static function selectFields() {
293 * Fetch a page record with the given conditions
294 * @param $dbr DatabaseBase object
295 * @param $conditions Array
296 * @param $options Array
297 * @return mixed Database result resource, or false on failure
299 protected function pageData( $dbr, $conditions, $options = array() ) {
300 $fields = self
::selectFields();
302 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
304 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
306 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
312 * Fetch a page record matching the Title object's namespace and title
313 * using a sanitized title string
315 * @param $dbr DatabaseBase object
316 * @param $title Title object
317 * @param $options Array
318 * @return mixed Database result resource, or false on failure
320 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
321 return $this->pageData( $dbr, array(
322 'page_namespace' => $title->getNamespace(),
323 'page_title' => $title->getDBkey() ), $options );
327 * Fetch a page record matching the requested ID
329 * @param $dbr DatabaseBase
331 * @param $options Array
332 * @return mixed Database result resource, or false on failure
334 public function pageDataFromId( $dbr, $id, $options = array() ) {
335 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
339 * Set the general counter, title etc data loaded from
342 * @param $from object|string|int One of the following:
343 * - A DB query result object
344 * - "fromdb" or self::DATA_FROM_SLAVE to get from a slave DB
345 * - "fromdbmaster" or self::DATA_FROM_MASTER to get from the master DB
346 * - "forupdate" or self::DATA_FOR_UPDATE to get from the master DB using SELECT FOR UPDATE
350 public function loadPageData( $from = 'fromdb' ) {
351 $from = self
::convertSelectType( $from );
352 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
353 // We already have the data from the correct location, no need to load it twice.
357 if ( $from === self
::DATA_FOR_UPDATE
) {
358 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
359 } elseif ( $from === self
::DATA_FROM_MASTER
) {
360 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
361 } elseif ( $from === self
::DATA_FROM_SLAVE
) {
362 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
363 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
364 # Note that DB also stores the master position in the session and checks it.
365 $touched = $this->getCachedLastEditTime();
366 if ( $touched ) { // key set
367 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
368 $from = self
::DATA_FROM_MASTER
;
369 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
373 // No idea from where the caller got this data, assume slave database.
375 $from = self
::DATA_FROM_SLAVE
;
378 $this->loadFromRow( $data, $from );
382 * Load the object from a database row
385 * @param $data object: database row containing at least fields returned
387 * @param $from string|int One of the following:
388 * - "fromdb" or self::DATA_FROM_SLAVE if the data comes from a slave DB
389 * - "fromdbmaster" or self::DATA_FROM_MASTER if the data comes from the master DB
390 * - "forupdate" or self::DATA_FOR_UPDATE if the data comes from from
391 * the master DB using SELECT FOR UPDATE
393 public function loadFromRow( $data, $from ) {
394 $lc = LinkCache
::singleton();
397 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
399 $this->mTitle
->loadFromRow( $data );
401 # Old-fashioned restrictions
402 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
404 $this->mCounter
= intval( $data->page_counter
);
405 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
406 $this->mIsRedirect
= intval( $data->page_is_redirect
);
407 $this->mLatest
= intval( $data->page_latest
);
408 // Bug 37225: $latest may no longer match the cached latest Revision object.
409 // Double-check the ID of any cached latest Revision object for consistency.
410 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
411 $this->mLastRevision
= null;
412 $this->mTimestamp
= '';
415 $lc->addBadLinkObj( $this->mTitle
);
417 $this->mTitle
->loadFromRow( false );
419 $this->clearCacheFields();
422 $this->mDataLoaded
= true;
423 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
427 * @return int Page ID
429 public function getId() {
430 return $this->mTitle
->getArticleID();
434 * @return bool Whether or not the page exists in the database
436 public function exists() {
437 return $this->mTitle
->exists();
441 * Check if this page is something we're going to be showing
442 * some sort of sensible content for. If we return false, page
443 * views (plain action=view) will return an HTTP 404 response,
444 * so spiders and robots can know they're following a bad link.
448 public function hasViewableContent() {
449 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
453 * @return int The view count for the page
455 public function getCount() {
456 if ( !$this->mDataLoaded
) {
457 $this->loadPageData();
460 return $this->mCounter
;
464 * Tests if the article text represents a redirect
466 * @param $text mixed string containing article contents, or boolean
469 public function isRedirect( $text = false ) {
470 if ( $text === false ) {
471 if ( !$this->mDataLoaded
) {
472 $this->loadPageData();
475 return (bool)$this->mIsRedirect
;
477 return Title
::newFromRedirect( $text ) !== null;
482 * Loads page_touched and returns a value indicating if it should be used
483 * @return boolean true if not a redirect
485 public function checkTouched() {
486 if ( !$this->mDataLoaded
) {
487 $this->loadPageData();
489 return !$this->mIsRedirect
;
493 * Get the page_touched field
494 * @return string containing GMT timestamp
496 public function getTouched() {
497 if ( !$this->mDataLoaded
) {
498 $this->loadPageData();
500 return $this->mTouched
;
504 * Get the page_latest field
505 * @return integer rev_id of current revision
507 public function getLatest() {
508 if ( !$this->mDataLoaded
) {
509 $this->loadPageData();
511 return (int)$this->mLatest
;
515 * Get the Revision object of the oldest revision
516 * @return Revision|null
518 public function getOldestRevision() {
519 wfProfileIn( __METHOD__
);
521 // Try using the slave database first, then try the master
523 $db = wfGetDB( DB_SLAVE
);
524 $revSelectFields = Revision
::selectFields();
526 while ( $continue ) {
527 $row = $db->selectRow(
528 array( 'page', 'revision' ),
531 'page_namespace' => $this->mTitle
->getNamespace(),
532 'page_title' => $this->mTitle
->getDBkey(),
537 'ORDER BY' => 'rev_timestamp ASC'
544 $db = wfGetDB( DB_MASTER
);
549 wfProfileOut( __METHOD__
);
550 return $row ? Revision
::newFromRow( $row ) : null;
554 * Loads everything except the text
555 * This isn't necessary for all uses, so it's only done if needed.
557 protected function loadLastEdit() {
558 if ( $this->mLastRevision
!== null ) {
559 return; // already loaded
562 $latest = $this->getLatest();
564 return; // page doesn't exist or is missing page_latest info
567 $revision = Revision
::newFromPageId( $this->getId(), $latest );
568 if ( $revision ) { // sanity
569 $this->setLastEdit( $revision );
574 * Set the latest revision
576 protected function setLastEdit( Revision
$revision ) {
577 $this->mLastRevision
= $revision;
578 $this->mTimestamp
= $revision->getTimestamp();
582 * Get the latest revision
583 * @return Revision|null
585 public function getRevision() {
586 $this->loadLastEdit();
587 if ( $this->mLastRevision
) {
588 return $this->mLastRevision
;
594 * Get the text of the current revision. No side-effects...
596 * @param $audience Integer: one of:
597 * Revision::FOR_PUBLIC to be displayed to all users
598 * Revision::FOR_THIS_USER to be displayed to $wgUser
599 * Revision::RAW get the text regardless of permissions
600 * @return String|bool The text of the current revision. False on failure
602 public function getText( $audience = Revision
::FOR_PUBLIC
) {
603 $this->loadLastEdit();
604 if ( $this->mLastRevision
) {
605 return $this->mLastRevision
->getText( $audience );
611 * Get the text of the current revision. No side-effects...
613 * @return String|bool The text of the current revision. False on failure
615 public function getRawText() {
616 $this->loadLastEdit();
617 if ( $this->mLastRevision
) {
618 return $this->mLastRevision
->getRawText();
624 * @return string MW timestamp of last article revision
626 public function getTimestamp() {
627 // Check if the field has been filled by WikiPage::setTimestamp()
628 if ( !$this->mTimestamp
) {
629 $this->loadLastEdit();
632 return wfTimestamp( TS_MW
, $this->mTimestamp
);
636 * Set the page timestamp (use only to avoid DB queries)
637 * @param $ts string MW timestamp of last article revision
640 public function setTimestamp( $ts ) {
641 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
645 * @param $audience Integer: one of:
646 * Revision::FOR_PUBLIC to be displayed to all users
647 * Revision::FOR_THIS_USER to be displayed to $wgUser
648 * Revision::RAW get the text regardless of permissions
649 * @return int user ID for the user that made the last article revision
651 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
652 $this->loadLastEdit();
653 if ( $this->mLastRevision
) {
654 return $this->mLastRevision
->getUser( $audience );
661 * Get the User object of the user who created the page
662 * @param $audience Integer: one of:
663 * Revision::FOR_PUBLIC to be displayed to all users
664 * Revision::FOR_THIS_USER to be displayed to $wgUser
665 * Revision::RAW get the text regardless of permissions
668 public function getCreator( $audience = Revision
::FOR_PUBLIC
) {
669 $revision = $this->getOldestRevision();
671 $userName = $revision->getUserText( $audience );
672 return User
::newFromName( $userName, false );
679 * @param $audience Integer: one of:
680 * Revision::FOR_PUBLIC to be displayed to all users
681 * Revision::FOR_THIS_USER to be displayed to $wgUser
682 * Revision::RAW get the text regardless of permissions
683 * @return string username of the user that made the last article revision
685 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
686 $this->loadLastEdit();
687 if ( $this->mLastRevision
) {
688 return $this->mLastRevision
->getUserText( $audience );
695 * @param $audience Integer: one of:
696 * Revision::FOR_PUBLIC to be displayed to all users
697 * Revision::FOR_THIS_USER to be displayed to $wgUser
698 * Revision::RAW get the text regardless of permissions
699 * @return string Comment stored for the last article revision
701 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
702 $this->loadLastEdit();
703 if ( $this->mLastRevision
) {
704 return $this->mLastRevision
->getComment( $audience );
711 * Returns true if last revision was marked as "minor edit"
713 * @return boolean Minor edit indicator for the last article revision.
715 public function getMinorEdit() {
716 $this->loadLastEdit();
717 if ( $this->mLastRevision
) {
718 return $this->mLastRevision
->isMinor();
725 * Get the cached timestamp for the last time the page changed.
726 * This is only used to help handle slave lag by comparing to page_touched.
727 * @return string MW timestamp
729 protected function getCachedLastEditTime() {
731 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
732 return $wgMemc->get( $key );
736 * Set the cached timestamp for the last time the page changed.
737 * This is only used to help handle slave lag by comparing to page_touched.
738 * @param $timestamp string
741 public function setCachedLastEditTime( $timestamp ) {
743 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
744 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
748 * Determine whether a page would be suitable for being counted as an
749 * article in the site_stats table based on the title & its content
751 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
752 * if false, the current database state will be used
755 public function isCountable( $editInfo = false ) {
756 global $wgArticleCountMethod;
758 if ( !$this->mTitle
->isContentPage() ) {
762 $text = $editInfo ?
$editInfo->pst
: false;
764 if ( $this->isRedirect( $text ) ) {
768 switch ( $wgArticleCountMethod ) {
772 if ( $text === false ) {
773 $text = $this->getRawText();
775 return strpos( $text, ',' ) !== false;
778 // ParserOutput::getLinks() is a 2D array of page links, so
779 // to be really correct we would need to recurse in the array
780 // but the main array should only have items in it if there are
782 return (bool)count( $editInfo->output
->getLinks() );
784 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
785 array( 'pl_from' => $this->getId() ), __METHOD__
);
791 * If this page is a redirect, get its target
793 * The target will be fetched from the redirect table if possible.
794 * If this page doesn't have an entry there, call insertRedirect()
795 * @return Title|mixed object, or null if this page is not a redirect
797 public function getRedirectTarget() {
798 if ( !$this->mTitle
->isRedirect() ) {
802 if ( $this->mRedirectTarget
!== null ) {
803 return $this->mRedirectTarget
;
806 # Query the redirect table
807 $dbr = wfGetDB( DB_SLAVE
);
808 $row = $dbr->selectRow( 'redirect',
809 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
810 array( 'rd_from' => $this->getId() ),
814 // rd_fragment and rd_interwiki were added later, populate them if empty
815 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
816 return $this->mRedirectTarget
= Title
::makeTitle(
817 $row->rd_namespace
, $row->rd_title
,
818 $row->rd_fragment
, $row->rd_interwiki
);
821 # This page doesn't have an entry in the redirect table
822 return $this->mRedirectTarget
= $this->insertRedirect();
826 * Insert an entry for this page into the redirect table.
828 * Don't call this function directly unless you know what you're doing.
829 * @return Title object or null if not a redirect
831 public function insertRedirect() {
832 // recurse through to only get the final target
833 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
837 $this->insertRedirectEntry( $retval );
842 * Insert or update the redirect table entry for this page to indicate
843 * it redirects to $rt .
844 * @param $rt Title redirect target
846 public function insertRedirectEntry( $rt ) {
847 $dbw = wfGetDB( DB_MASTER
);
848 $dbw->replace( 'redirect', array( 'rd_from' ),
850 'rd_from' => $this->getId(),
851 'rd_namespace' => $rt->getNamespace(),
852 'rd_title' => $rt->getDBkey(),
853 'rd_fragment' => $rt->getFragment(),
854 'rd_interwiki' => $rt->getInterwiki(),
861 * Get the Title object or URL this page redirects to
863 * @return mixed false, Title of in-wiki target, or string with URL
865 public function followRedirect() {
866 return $this->getRedirectURL( $this->getRedirectTarget() );
870 * Get the Title object or URL to use for a redirect. We use Title
871 * objects for same-wiki, non-special redirects and URLs for everything
873 * @param $rt Title Redirect target
874 * @return mixed false, Title object of local target, or string with URL
876 public function getRedirectURL( $rt ) {
881 if ( $rt->isExternal() ) {
882 if ( $rt->isLocal() ) {
883 // Offsite wikis need an HTTP redirect.
885 // This can be hard to reverse and may produce loops,
886 // so they may be disabled in the site configuration.
887 $source = $this->mTitle
->getFullURL( 'redirect=no' );
888 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
890 // External pages pages without "local" bit set are not valid
896 if ( $rt->isSpecialPage() ) {
897 // Gotta handle redirects to special pages differently:
898 // Fill the HTTP response "Location" header and ignore
899 // the rest of the page we're on.
901 // Some pages are not valid targets
902 if ( $rt->isValidRedirectTarget() ) {
903 return $rt->getFullURL();
913 * Get a list of users who have edited this article, not including the user who made
914 * the most recent revision, which you can get from $article->getUser() if you want it
915 * @return UserArrayFromResult
917 public function getContributors() {
918 # @todo FIXME: This is expensive; cache this info somewhere.
920 $dbr = wfGetDB( DB_SLAVE
);
922 if ( $dbr->implicitGroupby() ) {
923 $realNameField = 'user_real_name';
925 $realNameField = 'MIN(user_real_name) AS user_real_name';
928 $tables = array( 'revision', 'user' );
931 'rev_user as user_id',
932 'rev_user_text AS user_name',
934 'MAX(rev_timestamp) AS timestamp',
937 $conds = array( 'rev_page' => $this->getId() );
939 // The user who made the top revision gets credited as "this page was last edited by
940 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
941 $user = $this->getUser();
943 $conds[] = "rev_user != $user";
945 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
948 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
951 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
955 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
956 'ORDER BY' => 'timestamp DESC',
959 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
960 return new UserArrayFromResult( $res );
964 * Get the last N authors
965 * @param $num Integer: number of revisions to get
966 * @param $revLatest String: the latest rev_id, selected from the master (optional)
967 * @return array Array of authors, duplicates not removed
969 public function getLastNAuthors( $num, $revLatest = 0 ) {
970 wfProfileIn( __METHOD__
);
971 // First try the slave
972 // If that doesn't have the latest revision, try the master
974 $db = wfGetDB( DB_SLAVE
);
977 $res = $db->select( array( 'page', 'revision' ),
978 array( 'rev_id', 'rev_user_text' ),
980 'page_namespace' => $this->mTitle
->getNamespace(),
981 'page_title' => $this->mTitle
->getDBkey(),
985 'ORDER BY' => 'rev_timestamp DESC',
991 wfProfileOut( __METHOD__
);
995 $row = $db->fetchObject( $res );
997 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
998 $db = wfGetDB( DB_MASTER
);
1003 } while ( $continue );
1005 $authors = array( $row->rev_user_text
);
1007 foreach ( $res as $row ) {
1008 $authors[] = $row->rev_user_text
;
1011 wfProfileOut( __METHOD__
);
1016 * Should the parser cache be used?
1018 * @param $parserOptions ParserOptions to check
1022 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1023 global $wgEnableParserCache;
1025 return $wgEnableParserCache
1026 && $parserOptions->getStubThreshold() == 0
1027 && $this->mTitle
->exists()
1028 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1029 && $this->mTitle
->isWikitextPage();
1033 * Get a ParserOutput for the given ParserOptions and revision ID.
1034 * The parser cache will be used if possible.
1037 * @param $parserOptions ParserOptions to use for the parse operation
1038 * @param $oldid Revision ID to get the text from, passing null or 0 will
1039 * get the current revision (default value)
1040 * @return ParserOutput or false if the revision was not found
1042 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1043 wfProfileIn( __METHOD__
);
1045 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1046 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1047 if ( $parserOptions->getStubThreshold() ) {
1048 wfIncrStats( 'pcache_miss_stub' );
1051 if ( $useParserCache ) {
1052 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1053 if ( $parserOutput !== false ) {
1054 wfProfileOut( __METHOD__
);
1055 return $parserOutput;
1059 if ( $oldid === null ||
$oldid === 0 ) {
1060 $oldid = $this->getLatest();
1063 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1066 wfProfileOut( __METHOD__
);
1068 return $pool->getParserOutput();
1072 * Do standard deferred updates after page view
1073 * @param $user User The relevant user
1075 public function doViewUpdates( User
$user ) {
1076 global $wgDisableCounters;
1077 if ( wfReadOnly() ) {
1081 # Don't update page view counters on views from bot users (bug 14044)
1082 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1083 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1084 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1087 # Update newtalk / watchlist notification status
1088 $user->clearNotification( $this->mTitle
);
1092 * Perform the actions of a page purging
1095 public function doPurge() {
1098 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1102 // Invalidate the cache
1103 $this->mTitle
->invalidateCache();
1106 if ( $wgUseSquid ) {
1107 // Commit the transaction before the purge is sent
1108 $dbw = wfGetDB( DB_MASTER
);
1109 $dbw->commit( __METHOD__
);
1112 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1113 $update->doUpdate();
1116 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1117 if ( $this->mTitle
->exists() ) {
1118 $text = $this->getRawText();
1123 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1129 * Insert a new empty page record for this article.
1130 * This *must* be followed up by creating a revision
1131 * and running $this->updateRevisionOn( ... );
1132 * or else the record will be left in a funky state.
1133 * Best if all done inside a transaction.
1135 * @param $dbw DatabaseBase
1136 * @return int The newly created page_id key, or false if the title already existed
1138 public function insertOn( $dbw ) {
1139 wfProfileIn( __METHOD__
);
1141 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1142 $dbw->insert( 'page', array(
1143 'page_id' => $page_id,
1144 'page_namespace' => $this->mTitle
->getNamespace(),
1145 'page_title' => $this->mTitle
->getDBkey(),
1146 'page_counter' => 0,
1147 'page_restrictions' => '',
1148 'page_is_redirect' => 0, # Will set this shortly...
1150 'page_random' => wfRandom(),
1151 'page_touched' => $dbw->timestamp(),
1152 'page_latest' => 0, # Fill this in shortly...
1153 'page_len' => 0, # Fill this in shortly...
1154 ), __METHOD__
, 'IGNORE' );
1156 $affected = $dbw->affectedRows();
1159 $newid = $dbw->insertId();
1160 $this->mTitle
->resetArticleID( $newid );
1162 wfProfileOut( __METHOD__
);
1164 return $affected ?
$newid : false;
1168 * Update the page record to point to a newly saved revision.
1170 * @param $dbw DatabaseBase: object
1171 * @param $revision Revision: For ID number, and text used to set
1172 * length and redirect status fields
1173 * @param $lastRevision Integer: if given, will not overwrite the page field
1174 * when different from the currently set value.
1175 * Giving 0 indicates the new page flag should be set
1177 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1178 * removing rows in redirect table.
1179 * @return bool true on success, false on failure
1182 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1183 wfProfileIn( __METHOD__
);
1185 $text = $revision->getText();
1186 $len = strlen( $text );
1187 $rt = Title
::newFromRedirectRecurse( $text );
1189 $conditions = array( 'page_id' => $this->getId() );
1191 if ( !is_null( $lastRevision ) ) {
1192 # An extra check against threads stepping on each other
1193 $conditions['page_latest'] = $lastRevision;
1196 $now = wfTimestampNow();
1197 $dbw->update( 'page',
1199 'page_latest' => $revision->getId(),
1200 'page_touched' => $dbw->timestamp( $now ),
1201 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1202 'page_is_redirect' => $rt !== null ?
1 : 0,
1208 $result = $dbw->affectedRows() != 0;
1210 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1211 $this->setLastEdit( $revision );
1212 $this->setCachedLastEditTime( $now );
1213 $this->mLatest
= $revision->getId();
1214 $this->mIsRedirect
= (bool)$rt;
1215 # Update the LinkCache.
1216 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1219 wfProfileOut( __METHOD__
);
1224 * Add row to the redirect table if this is a redirect, remove otherwise.
1226 * @param $dbw DatabaseBase
1227 * @param $redirectTitle Title object pointing to the redirect target,
1228 * or NULL if this is not a redirect
1229 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1230 * removing rows in redirect table.
1231 * @return bool true on success, false on failure
1234 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1235 // Always update redirects (target link might have changed)
1236 // Update/Insert if we don't know if the last revision was a redirect or not
1237 // Delete if changing from redirect to non-redirect
1238 $isRedirect = !is_null( $redirectTitle );
1240 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1244 wfProfileIn( __METHOD__
);
1245 if ( $isRedirect ) {
1246 $this->insertRedirectEntry( $redirectTitle );
1248 // This is not a redirect, remove row from redirect table
1249 $where = array( 'rd_from' => $this->getId() );
1250 $dbw->delete( 'redirect', $where, __METHOD__
);
1253 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1254 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1256 wfProfileOut( __METHOD__
);
1258 return ( $dbw->affectedRows() != 0 );
1262 * If the given revision is newer than the currently set page_latest,
1263 * update the page record. Otherwise, do nothing.
1265 * @param $dbw DatabaseBase object
1266 * @param $revision Revision object
1269 public function updateIfNewerOn( $dbw, $revision ) {
1270 wfProfileIn( __METHOD__
);
1272 $row = $dbw->selectRow(
1273 array( 'revision', 'page' ),
1274 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1276 'page_id' => $this->getId(),
1277 'page_latest=rev_id' ),
1281 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1282 wfProfileOut( __METHOD__
);
1285 $prev = $row->rev_id
;
1286 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1288 # No or missing previous revision; mark the page as new
1290 $lastRevIsRedirect = null;
1293 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1295 wfProfileOut( __METHOD__
);
1300 * Get the text that needs to be saved in order to undo all revisions
1301 * between $undo and $undoafter. Revisions must belong to the same page,
1302 * must exist and must not be deleted
1303 * @param $undo Revision
1304 * @param $undoafter Revision Must be an earlier revision than $undo
1305 * @return mixed string on success, false on failure
1307 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1308 $cur_text = $this->getRawText();
1309 if ( $cur_text === false ) {
1310 return false; // no page
1312 $undo_text = $undo->getText();
1313 $undoafter_text = $undoafter->getText();
1315 if ( $cur_text == $undo_text ) {
1316 # No use doing a merge if it's just a straight revert.
1317 return $undoafter_text;
1322 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1326 return $undone_text;
1330 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1331 * @param $text String: new text of the section
1332 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1333 * @param $edittime String: revision timestamp or null to use the current revision
1334 * @return string Complete article text, or null if error
1336 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1337 wfProfileIn( __METHOD__
);
1339 if ( strval( $section ) == '' ) {
1340 // Whole-page edit; let the whole text through
1342 // Bug 30711: always use current version when adding a new section
1343 if ( is_null( $edittime ) ||
$section == 'new' ) {
1344 $oldtext = $this->getRawText();
1345 if ( $oldtext === false ) {
1346 wfDebug( __METHOD__
. ": no page text\n" );
1347 wfProfileOut( __METHOD__
);
1351 $dbw = wfGetDB( DB_MASTER
);
1352 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1355 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1356 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1357 wfProfileOut( __METHOD__
);
1361 $oldtext = $rev->getText();
1364 if ( $section == 'new' ) {
1365 # Inserting a new section
1366 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1367 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1368 $text = strlen( trim( $oldtext ) ) > 0
1369 ?
"{$oldtext}\n\n{$subject}{$text}"
1370 : "{$subject}{$text}";
1373 # Replacing an existing section; roll out the big guns
1376 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1380 wfProfileOut( __METHOD__
);
1385 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1387 * @return Int updated $flags
1389 function checkFlags( $flags ) {
1390 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1391 if ( $this->mTitle
->getArticleID() ) {
1392 $flags |
= EDIT_UPDATE
;
1402 * Change an existing article or create a new article. Updates RC and all necessary caches,
1403 * optionally via the deferred update array.
1405 * @param $text String: new text
1406 * @param $summary String: edit summary
1407 * @param $flags Integer bitfield:
1409 * Article is known or assumed to be non-existent, create a new one
1411 * Article is known or assumed to be pre-existing, update it
1413 * Mark this edit minor, if the user is allowed to do so
1415 * Do not log the change in recentchanges
1417 * Mark the edit a "bot" edit regardless of user rights
1418 * EDIT_DEFER_UPDATES
1419 * Defer some of the updates until the end of index.php
1421 * Fill in blank summaries with generated text where possible
1423 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1424 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1425 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1426 * edit-already-exists error will be returned. These two conditions are also possible with
1427 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1429 * @param $baseRevId int the revision ID this edit was based off, if any
1430 * @param $user User the user doing the edit
1432 * @return Status object. Possible errors:
1433 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1434 * edit-gone-missing: In update mode, but the article didn't exist
1435 * edit-conflict: In update mode, the article changed unexpectedly
1436 * edit-no-change: Warning that the text was the same as before
1437 * edit-already-exists: In creation mode, but the article already exists
1439 * Extensions may define additional errors.
1441 * $return->value will contain an associative array with members as follows:
1442 * new: Boolean indicating if the function attempted to create a new article
1443 * revision: The revision object for the inserted revision, or null
1445 * Compatibility note: this function previously returned a boolean value indicating success/failure
1447 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1448 global $wgUser, $wgUseAutomaticEditSummaries;
1450 # Low-level sanity check
1451 if ( $this->mTitle
->getText() === '' ) {
1452 throw new MWException( 'Something is trying to edit an article with an empty title' );
1455 wfProfileIn( __METHOD__
);
1457 $user = is_null( $user ) ?
$wgUser : $user;
1458 $status = Status
::newGood( array() );
1460 // Load the data from the master database if needed.
1461 // The caller may already loaded it from the master or even loaded it using
1462 // SELECT FOR UPDATE, so do not override that using clear().
1463 $this->loadPageData( 'fromdbmaster' );
1465 $flags = $this->checkFlags( $flags );
1467 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1468 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1470 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1472 if ( $status->isOK() ) {
1473 $status->fatal( 'edit-hook-aborted' );
1476 wfProfileOut( __METHOD__
);
1480 # Silently ignore EDIT_MINOR if not allowed
1481 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1482 $bot = $flags & EDIT_FORCE_BOT
;
1484 $oldtext = $this->getRawText(); // current revision
1485 $oldsize = strlen( $oldtext );
1486 $oldid = $this->getLatest();
1487 $oldIsRedirect = $this->isRedirect();
1488 $oldcountable = $this->isCountable();
1490 # Provide autosummaries if one is not provided and autosummaries are enabled.
1491 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1492 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1495 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1496 $text = $editInfo->pst
;
1497 $newsize = strlen( $text );
1499 $dbw = wfGetDB( DB_MASTER
);
1500 $now = wfTimestampNow();
1501 $this->mTimestamp
= $now;
1503 if ( $flags & EDIT_UPDATE
) {
1504 # Update article, but only if changed.
1505 $status->value
['new'] = false;
1508 # Article gone missing
1509 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1510 $status->fatal( 'edit-gone-missing' );
1512 wfProfileOut( __METHOD__
);
1516 $revision = new Revision( array(
1517 'page' => $this->getId(),
1518 'comment' => $summary,
1519 'minor_edit' => $isminor,
1521 'parent_id' => $oldid,
1522 'user' => $user->getId(),
1523 'user_text' => $user->getName(),
1526 # Bug 37225: use accessor to get the text as Revision may trim it.
1527 # After trimming, the text may be a duplicate of the current text.
1528 $text = $revision->getText(); // sanity; EditPage should trim already
1530 $changed = ( strcmp( $text, $oldtext ) != 0 );
1533 $dbw->begin( __METHOD__
);
1534 $revisionId = $revision->insertOn( $dbw );
1538 # Note that we use $this->mLatest instead of fetching a value from the master DB
1539 # during the course of this function. This makes sure that EditPage can detect
1540 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1541 # before this function is called. A previous function used a separate query, this
1542 # creates a window where concurrent edits can cause an ignored edit conflict.
1543 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1546 /* Belated edit conflict! Run away!! */
1547 $status->fatal( 'edit-conflict' );
1550 $dbw->rollback( __METHOD__
);
1552 global $wgUseRCPatrol;
1553 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1554 # Update recentchanges
1555 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1556 # Mark as patrolled if the user can do so
1557 $patrolled = $wgUseRCPatrol && !count(
1558 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1559 # Add RC row to the DB
1560 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1561 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1562 $revisionId, $patrolled
1565 # Log auto-patrolled edits
1567 PatrolLog
::record( $rc, true, $user );
1570 $user->incEditCount();
1571 $dbw->commit( __METHOD__
);
1574 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1575 // related variables correctly
1576 $revision->setId( $this->getLatest() );
1579 // Now that ignore_user_abort is restored, we can respond to fatal errors
1580 if ( !$status->isOK() ) {
1581 wfProfileOut( __METHOD__
);
1585 # Update links tables, site stats, etc.
1586 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1587 'oldcountable' => $oldcountable ) );
1590 $status->warning( 'edit-no-change' );
1592 // Update page_touched, this is usually implicit in the page update
1593 // Other cache updates are done in onArticleEdit()
1594 $this->mTitle
->invalidateCache();
1597 # Create new article
1598 $status->value
['new'] = true;
1600 $dbw->begin( __METHOD__
);
1602 # Add the page record; stake our claim on this title!
1603 # This will return false if the article already exists
1604 $newid = $this->insertOn( $dbw );
1606 if ( $newid === false ) {
1607 $dbw->rollback( __METHOD__
);
1608 $status->fatal( 'edit-already-exists' );
1610 wfProfileOut( __METHOD__
);
1614 # Save the revision text...
1615 $revision = new Revision( array(
1617 'comment' => $summary,
1618 'minor_edit' => $isminor,
1620 'user' => $user->getId(),
1621 'user_text' => $user->getName(),
1624 $revisionId = $revision->insertOn( $dbw );
1626 # Bug 37225: use accessor to get the text as Revision may trim it
1627 $text = $revision->getText(); // sanity; EditPage should trim already
1629 # Update the page record with revision data
1630 $this->updateRevisionOn( $dbw, $revision, 0 );
1632 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1634 # Update recentchanges
1635 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1636 global $wgUseRCPatrol, $wgUseNPPatrol;
1638 # Mark as patrolled if the user can do so
1639 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1640 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1641 # Add RC row to the DB
1642 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1643 '', strlen( $text ), $revisionId, $patrolled );
1645 # Log auto-patrolled edits
1647 PatrolLog
::record( $rc, true, $user );
1650 $user->incEditCount();
1651 $dbw->commit( __METHOD__
);
1653 # Update links, etc.
1654 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1656 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1657 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1660 # Do updates right now unless deferral was requested
1661 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1662 DeferredUpdates
::doUpdates();
1665 // Return the new revision (or null) to the caller
1666 $status->value
['revision'] = $revision;
1668 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1669 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1671 # Promote user to any groups they meet the criteria for
1672 $user->addAutopromoteOnceGroups( 'onEdit' );
1674 wfProfileOut( __METHOD__
);
1679 * Get parser options suitable for rendering the primary article wikitext
1680 * @param User|string $user User object or 'canonical'
1681 * @return ParserOptions
1683 public function makeParserOptions( $user ) {
1685 if ( $user instanceof User
) { // settings per user (even anons)
1686 $options = ParserOptions
::newFromUser( $user );
1687 } else { // canonical settings
1688 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1690 $options->enableLimitReport(); // show inclusion/loop reports
1691 $options->setTidy( true ); // fix bad HTML
1696 * Prepare text which is about to be saved.
1697 * Returns a stdclass with source, pst and output members
1698 * @return bool|object
1700 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1701 global $wgParser, $wgContLang, $wgUser;
1702 $user = is_null( $user ) ?
$wgUser : $user;
1703 // @TODO fixme: check $user->getId() here???
1704 if ( $this->mPreparedEdit
1705 && $this->mPreparedEdit
->newText
== $text
1706 && $this->mPreparedEdit
->revid
== $revid
1709 return $this->mPreparedEdit
;
1712 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1713 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1715 $edit = (object)array();
1716 $edit->revid
= $revid;
1717 $edit->newText
= $text;
1718 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1719 $edit->popts
= $this->makeParserOptions( 'canonical' );
1720 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1721 $edit->oldText
= $this->getRawText();
1723 $this->mPreparedEdit
= $edit;
1729 * Do standard deferred updates after page edit.
1730 * Update links tables, site stats, search index and message cache.
1731 * Purges pages that include this page if the text was changed here.
1732 * Every 100th edit, prune the recent changes table.
1735 * @param $revision Revision object
1736 * @param $user User object that did the revision
1737 * @param $options Array of options, following indexes are used:
1738 * - changed: boolean, whether the revision changed the content (default true)
1739 * - created: boolean, whether the revision created the page (default false)
1740 * - oldcountable: boolean or null (default null):
1741 * - boolean: whether the page was counted as an article before that
1742 * revision, only used in changed is true and created is false
1743 * - null: don't change the article count
1745 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1746 global $wgEnableParserCache;
1748 wfProfileIn( __METHOD__
);
1750 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1751 $text = $revision->getText();
1754 # Be careful not to double-PST: $text is usually already PST-ed once
1755 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1756 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1757 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1759 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1760 $editInfo = $this->mPreparedEdit
;
1763 # Save it to the parser cache
1764 if ( $wgEnableParserCache ) {
1765 $parserCache = ParserCache
::singleton();
1766 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1769 # Update the links tables and other secondary data
1770 $updates = $editInfo->output
->getSecondaryDataUpdates( $this->mTitle
);
1771 DataUpdate
::runUpdates( $updates );
1773 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1775 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1776 if ( 0 == mt_rand( 0, 99 ) ) {
1777 // Flush old entries from the `recentchanges` table; we do this on
1778 // random requests so as to avoid an increase in writes for no good reason
1781 $dbw = wfGetDB( DB_MASTER
);
1782 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1785 array( "rc_timestamp < '$cutoff'" ),
1791 if ( !$this->mTitle
->exists() ) {
1792 wfProfileOut( __METHOD__
);
1796 $id = $this->getId();
1797 $title = $this->mTitle
->getPrefixedDBkey();
1798 $shortTitle = $this->mTitle
->getDBkey();
1800 if ( !$options['changed'] ) {
1803 } elseif ( $options['created'] ) {
1804 $good = (int)$this->isCountable( $editInfo );
1806 } elseif ( $options['oldcountable'] !== null ) {
1807 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1814 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1815 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1817 # If this is another user's talk page, update newtalk.
1818 # Don't do this if $options['changed'] = false (null-edits) nor if
1819 # it's a minor edit and the user doesn't want notifications for those.
1820 if ( $options['changed']
1821 && $this->mTitle
->getNamespace() == NS_USER_TALK
1822 && $shortTitle != $user->getTitleKey()
1823 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1825 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1826 $other = User
::newFromName( $shortTitle, false );
1828 wfDebug( __METHOD__
. ": invalid username\n" );
1829 } elseif ( User
::isIP( $shortTitle ) ) {
1830 // An anonymous user
1831 $other->setNewtalk( true );
1832 } elseif ( $other->isLoggedIn() ) {
1833 $other->setNewtalk( true );
1835 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1840 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1841 MessageCache
::singleton()->replace( $shortTitle, $text );
1844 if( $options['created'] ) {
1845 self
::onArticleCreate( $this->mTitle
);
1847 self
::onArticleEdit( $this->mTitle
);
1850 wfProfileOut( __METHOD__
);
1854 * Edit an article without doing all that other stuff
1855 * The article must already exist; link tables etc
1856 * are not updated, caches are not flushed.
1858 * @param $text String: text submitted
1859 * @param $user User The relevant user
1860 * @param $comment String: comment submitted
1861 * @param $minor Boolean: whereas it's a minor modification
1863 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1864 wfProfileIn( __METHOD__
);
1866 $dbw = wfGetDB( DB_MASTER
);
1867 $revision = new Revision( array(
1868 'page' => $this->getId(),
1870 'comment' => $comment,
1871 'minor_edit' => $minor ?
1 : 0,
1873 $revision->insertOn( $dbw );
1874 $this->updateRevisionOn( $dbw, $revision );
1876 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1878 wfProfileOut( __METHOD__
);
1882 * Update the article's restriction field, and leave a log entry.
1883 * This works for protection both existing and non-existing pages.
1885 * @param $limit Array: set of restriction keys
1886 * @param $reason String
1887 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1888 * @param $expiry Array: per restriction type expiration
1889 * @param $user User The user updating the restrictions
1892 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1895 if ( wfReadOnly() ) {
1896 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1899 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1901 $id = $this->mTitle
->getArticleID();
1907 // Take this opportunity to purge out expired restrictions
1908 Title
::purgeExpiredRestrictions();
1910 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1911 # we expect a single selection, but the schema allows otherwise.
1912 $isProtected = false;
1916 $dbw = wfGetDB( DB_MASTER
);
1918 foreach ( $restrictionTypes as $action ) {
1919 if ( !isset( $expiry[$action] ) ) {
1920 $expiry[$action] = $dbw->getInfinity();
1922 if ( !isset( $limit[$action] ) ) {
1923 $limit[$action] = '';
1924 } elseif ( $limit[$action] != '' ) {
1928 # Get current restrictions on $action
1929 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1930 if ( $current != '' ) {
1931 $isProtected = true;
1934 if ( $limit[$action] != $current ) {
1936 } elseif ( $limit[$action] != '' ) {
1937 # Only check expiry change if the action is actually being
1938 # protected, since expiry does nothing on an not-protected
1940 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1946 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1950 # If nothing's changed, do nothing
1952 return Status
::newGood();
1955 if ( !$protect ) { # No protection at all means unprotection
1956 $revCommentMsg = 'unprotectedarticle';
1957 $logAction = 'unprotect';
1958 } elseif ( $isProtected ) {
1959 $revCommentMsg = 'modifiedarticleprotection';
1960 $logAction = 'modify';
1962 $revCommentMsg = 'protectedarticle';
1963 $logAction = 'protect';
1966 $encodedExpiry = array();
1967 $protectDescription = '';
1968 foreach ( $limit as $action => $restrictions ) {
1969 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1970 if ( $restrictions != '' ) {
1971 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1972 if ( $encodedExpiry[$action] != 'infinity' ) {
1973 $protectDescription .= wfMsgForContent( 'protect-expiring',
1974 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1975 $wgContLang->date( $expiry[$action], false, false ) ,
1976 $wgContLang->time( $expiry[$action], false, false ) );
1978 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1981 $protectDescription .= ') ';
1984 $protectDescription = trim( $protectDescription );
1986 if ( $id ) { # Protection of existing page
1987 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1988 return Status
::newGood();
1991 # Only restrictions with the 'protect' right can cascade...
1992 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1993 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1995 # The schema allows multiple restrictions
1996 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2000 # Update restrictions table
2001 foreach ( $limit as $action => $restrictions ) {
2002 if ( $restrictions != '' ) {
2003 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2004 array( 'pr_page' => $id,
2005 'pr_type' => $action,
2006 'pr_level' => $restrictions,
2007 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2008 'pr_expiry' => $encodedExpiry[$action]
2013 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2014 'pr_type' => $action ), __METHOD__
);
2018 # Prepare a null revision to be added to the history
2019 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2021 $editComment .= ": $reason";
2023 if ( $protectDescription ) {
2024 $editComment .= " ($protectDescription)";
2027 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2030 # Insert a null revision
2031 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2032 $nullRevId = $nullRevision->insertOn( $dbw );
2034 $latest = $this->getLatest();
2035 # Update page record
2036 $dbw->update( 'page',
2038 'page_touched' => $dbw->timestamp(),
2039 'page_restrictions' => '',
2040 'page_latest' => $nullRevId
2041 ), array( /* WHERE */
2046 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2047 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2048 } else { # Protection of non-existing page (also known as "title protection")
2049 # Cascade protection is meaningless in this case
2052 if ( $limit['create'] != '' ) {
2053 $dbw->replace( 'protected_titles',
2054 array( array( 'pt_namespace', 'pt_title' ) ),
2056 'pt_namespace' => $this->mTitle
->getNamespace(),
2057 'pt_title' => $this->mTitle
->getDBkey(),
2058 'pt_create_perm' => $limit['create'],
2059 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2060 'pt_expiry' => $encodedExpiry['create'],
2061 'pt_user' => $user->getId(),
2062 'pt_reason' => $reason,
2066 $dbw->delete( 'protected_titles',
2068 'pt_namespace' => $this->mTitle
->getNamespace(),
2069 'pt_title' => $this->mTitle
->getDBkey()
2075 $this->mTitle
->flushRestrictions();
2077 if ( $logAction == 'unprotect' ) {
2078 $logParams = array();
2080 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2083 # Update the protection log
2084 $log = new LogPage( 'protect' );
2085 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2087 return Status
::newGood();
2091 * Take an array of page restrictions and flatten it to a string
2092 * suitable for insertion into the page_restrictions field.
2093 * @param $limit Array
2096 protected static function flattenRestrictions( $limit ) {
2097 if ( !is_array( $limit ) ) {
2098 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2104 foreach ( $limit as $action => $restrictions ) {
2105 if ( $restrictions != '' ) {
2106 $bits[] = "$action=$restrictions";
2110 return implode( ':', $bits );
2114 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2115 * Deletes the article with database consistency, writes logs, purges caches
2117 * @param $reason string delete reason for deletion log
2118 * @param $suppress int bitfield
2119 * Revision::DELETED_TEXT
2120 * Revision::DELETED_COMMENT
2121 * Revision::DELETED_USER
2122 * Revision::DELETED_RESTRICTED
2123 * @param $id int article ID
2124 * @param $commit boolean defaults to true, triggers transaction end
2125 * @param &$error Array of errors to append to
2126 * @param $user User The deleting user
2127 * @return boolean true if successful
2129 public function doDeleteArticle(
2130 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2132 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2133 == WikiPage
::DELETE_SUCCESS
;
2137 * Back-end article deletion
2138 * Deletes the article with database consistency, writes logs, purges caches
2140 * @param $reason string delete reason for deletion log
2141 * @param $suppress int bitfield
2142 * Revision::DELETED_TEXT
2143 * Revision::DELETED_COMMENT
2144 * Revision::DELETED_USER
2145 * Revision::DELETED_RESTRICTED
2146 * @param $id int article ID
2147 * @param $commit boolean defaults to true, triggers transaction end
2148 * @param &$error Array of errors to append to
2149 * @param $user User The deleting user
2150 * @return int: One of WikiPage::DELETE_* constants
2152 public function doDeleteArticleReal(
2153 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2157 wfDebug( __METHOD__
. "\n" );
2159 if ( $this->mTitle
->getDBkey() === '' ) {
2160 return WikiPage
::DELETE_NO_PAGE
;
2163 $user = is_null( $user ) ?
$wgUser : $user;
2164 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2165 return WikiPage
::DELETE_HOOK_ABORTED
;
2169 $this->loadPageData( 'forupdate' );
2170 $id = $this->getID();
2172 return WikiPage
::DELETE_NO_PAGE
;
2176 // Bitfields to further suppress the content
2179 // This should be 15...
2180 $bitfield |
= Revision
::DELETED_TEXT
;
2181 $bitfield |
= Revision
::DELETED_COMMENT
;
2182 $bitfield |
= Revision
::DELETED_USER
;
2183 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2185 $bitfield = 'rev_deleted';
2188 $dbw = wfGetDB( DB_MASTER
);
2189 $dbw->begin( __METHOD__
);
2190 // For now, shunt the revision data into the archive table.
2191 // Text is *not* removed from the text table; bulk storage
2192 // is left intact to avoid breaking block-compression or
2193 // immutable storage schemes.
2195 // For backwards compatibility, note that some older archive
2196 // table entries will have ar_text and ar_flags fields still.
2198 // In the future, we may keep revisions and mark them with
2199 // the rev_deleted field, which is reserved for this purpose.
2200 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2202 'ar_namespace' => 'page_namespace',
2203 'ar_title' => 'page_title',
2204 'ar_comment' => 'rev_comment',
2205 'ar_user' => 'rev_user',
2206 'ar_user_text' => 'rev_user_text',
2207 'ar_timestamp' => 'rev_timestamp',
2208 'ar_minor_edit' => 'rev_minor_edit',
2209 'ar_rev_id' => 'rev_id',
2210 'ar_parent_id' => 'rev_parent_id',
2211 'ar_text_id' => 'rev_text_id',
2212 'ar_text' => '\'\'', // Be explicit to appease
2213 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2214 'ar_len' => 'rev_len',
2215 'ar_page_id' => 'page_id',
2216 'ar_deleted' => $bitfield,
2217 'ar_sha1' => 'rev_sha1'
2220 'page_id = rev_page'
2224 # Now that it's safely backed up, delete it
2225 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2226 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2229 $dbw->rollback( __METHOD__
);
2230 return WikiPage
::DELETE_NO_REVISIONS
;
2233 $this->doDeleteUpdates( $id );
2235 # Log the deletion, if the page was suppressed, log it at Oversight instead
2236 $logtype = $suppress ?
'suppress' : 'delete';
2238 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2239 $logEntry->setPerformer( $user );
2240 $logEntry->setTarget( $this->mTitle
);
2241 $logEntry->setComment( $reason );
2242 $logid = $logEntry->insert();
2243 $logEntry->publish( $logid );
2246 $dbw->commit( __METHOD__
);
2249 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2250 return WikiPage
::DELETE_SUCCESS
;
2254 * Do some database updates after deletion
2256 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2258 public function doDeleteUpdates( $id ) {
2259 # update site status
2260 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2262 # remove secondary indexes, etc
2263 $updates = $this->getDeletionUpdates( );
2264 DataUpdate
::runUpdates( $updates );
2267 WikiPage
::onArticleDelete( $this->mTitle
);
2272 # Clear the cached article id so the interface doesn't act like we exist
2273 $this->mTitle
->resetArticleID( 0 );
2276 public function getDeletionUpdates() {
2278 new LinksDeletionUpdate( $this ),
2281 //@todo: make a hook to add update objects
2282 //NOTE: deletion updates will be determined by the ContentHandler in the future
2287 * Roll back the most recent consecutive set of edits to a page
2288 * from the same user; fails if there are no eligible edits to
2289 * roll back to, e.g. user is the sole contributor. This function
2290 * performs permissions checks on $user, then calls commitRollback()
2291 * to do the dirty work
2293 * @todo: seperate the business/permission stuff out from backend code
2295 * @param $fromP String: Name of the user whose edits to rollback.
2296 * @param $summary String: Custom summary. Set to default summary if empty.
2297 * @param $token String: Rollback token.
2298 * @param $bot Boolean: If true, mark all reverted edits as bot.
2300 * @param $resultDetails Array: contains result-specific array of additional values
2301 * 'alreadyrolled' : 'current' (rev)
2302 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2304 * @param $user User The user performing the rollback
2305 * @return array of errors, each error formatted as
2306 * array(messagekey, param1, param2, ...).
2307 * On success, the array is empty. This array can also be passed to
2308 * OutputPage::showPermissionsErrorPage().
2310 public function doRollback(
2311 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2313 $resultDetails = null;
2316 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2317 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2318 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2320 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2321 $errors[] = array( 'sessionfailure' );
2324 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2325 $errors[] = array( 'actionthrottledtext' );
2328 # If there were errors, bail out now
2329 if ( !empty( $errors ) ) {
2333 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2337 * Backend implementation of doRollback(), please refer there for parameter
2338 * and return value documentation
2340 * NOTE: This function does NOT check ANY permissions, it just commits the
2341 * rollback to the DB. Therefore, you should only call this function direct-
2342 * ly if you want to use custom permissions checks. If you don't, use
2343 * doRollback() instead.
2344 * @param $fromP String: Name of the user whose edits to rollback.
2345 * @param $summary String: Custom summary. Set to default summary if empty.
2346 * @param $bot Boolean: If true, mark all reverted edits as bot.
2348 * @param $resultDetails Array: contains result-specific array of additional values
2349 * @param $guser User The user performing the rollback
2352 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2353 global $wgUseRCPatrol, $wgContLang;
2355 $dbw = wfGetDB( DB_MASTER
);
2357 if ( wfReadOnly() ) {
2358 return array( array( 'readonlytext' ) );
2361 # Get the last editor
2362 $current = $this->getRevision();
2363 if ( is_null( $current ) ) {
2364 # Something wrong... no page?
2365 return array( array( 'notanarticle' ) );
2368 $from = str_replace( '_', ' ', $fromP );
2369 # User name given should match up with the top revision.
2370 # If the user was deleted then $from should be empty.
2371 if ( $from != $current->getUserText() ) {
2372 $resultDetails = array( 'current' => $current );
2373 return array( array( 'alreadyrolled',
2374 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2375 htmlspecialchars( $fromP ),
2376 htmlspecialchars( $current->getUserText() )
2380 # Get the last edit not by this guy...
2381 # Note: these may not be public values
2382 $user = intval( $current->getRawUser() );
2383 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2384 $s = $dbw->selectRow( 'revision',
2385 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2386 array( 'rev_page' => $current->getPage(),
2387 "rev_user != {$user} OR rev_user_text != {$user_text}"
2389 array( 'USE INDEX' => 'page_timestamp',
2390 'ORDER BY' => 'rev_timestamp DESC' )
2392 if ( $s === false ) {
2393 # No one else ever edited this page
2394 return array( array( 'cantrollback' ) );
2395 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2396 # Only admins can see this text
2397 return array( array( 'notvisiblerev' ) );
2401 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2402 # Mark all reverted edits as bot
2406 if ( $wgUseRCPatrol ) {
2407 # Mark all reverted edits as patrolled
2408 $set['rc_patrolled'] = 1;
2411 if ( count( $set ) ) {
2412 $dbw->update( 'recentchanges', $set,
2414 'rc_cur_id' => $current->getPage(),
2415 'rc_user_text' => $current->getUserText(),
2416 "rc_timestamp > '{$s->rev_timestamp}'",
2421 # Generate the edit summary if necessary
2422 $target = Revision
::newFromId( $s->rev_id
);
2423 if ( empty( $summary ) ) {
2424 if ( $from == '' ) { // no public user name
2425 $summary = wfMsgForContent( 'revertpage-nouser' );
2427 $summary = wfMsgForContent( 'revertpage' );
2431 # Allow the custom summary to use the same args as the default message
2433 $target->getUserText(), $from, $s->rev_id
,
2434 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2435 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2437 $summary = wfMsgReplaceArgs( $summary, $args );
2440 $flags = EDIT_UPDATE
;
2442 if ( $guser->isAllowed( 'minoredit' ) ) {
2443 $flags |
= EDIT_MINOR
;
2446 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2447 $flags |
= EDIT_FORCE_BOT
;
2450 # Actually store the edit
2451 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2452 if ( !empty( $status->value
['revision'] ) ) {
2453 $revId = $status->value
['revision']->getId();
2458 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2460 $resultDetails = array(
2461 'summary' => $summary,
2462 'current' => $current,
2463 'target' => $target,
2471 * The onArticle*() functions are supposed to be a kind of hooks
2472 * which should be called whenever any of the specified actions
2475 * This is a good place to put code to clear caches, for instance.
2477 * This is called on page move and undelete, as well as edit
2479 * @param $title Title object
2481 public static function onArticleCreate( $title ) {
2482 # Update existence markers on article/talk tabs...
2483 if ( $title->isTalkPage() ) {
2484 $other = $title->getSubjectPage();
2486 $other = $title->getTalkPage();
2489 $other->invalidateCache();
2490 $other->purgeSquid();
2492 $title->touchLinks();
2493 $title->purgeSquid();
2494 $title->deleteTitleProtection();
2498 * Clears caches when article is deleted
2500 * @param $title Title
2502 public static function onArticleDelete( $title ) {
2503 # Update existence markers on article/talk tabs...
2504 if ( $title->isTalkPage() ) {
2505 $other = $title->getSubjectPage();
2507 $other = $title->getTalkPage();
2510 $other->invalidateCache();
2511 $other->purgeSquid();
2513 $title->touchLinks();
2514 $title->purgeSquid();
2517 HTMLFileCache
::clearFileCache( $title );
2520 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2521 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2525 if ( $title->getNamespace() == NS_FILE
) {
2526 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2527 $update->doUpdate();
2531 if ( $title->getNamespace() == NS_USER_TALK
) {
2532 $user = User
::newFromName( $title->getText(), false );
2534 $user->setNewtalk( false );
2539 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2543 * Purge caches on page update etc
2545 * @param $title Title object
2546 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2548 public static function onArticleEdit( $title ) {
2549 // Invalidate caches of articles which include this page
2550 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2553 // Invalidate the caches of all pages which redirect here
2554 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2556 # Purge squid for this page only
2557 $title->purgeSquid();
2559 # Clear file cache for this page only
2560 HTMLFileCache
::clearFileCache( $title );
2566 * Returns a list of hidden categories this page is a member of.
2567 * Uses the page_props and categorylinks tables.
2569 * @return Array of Title objects
2571 public function getHiddenCategories() {
2573 $id = $this->mTitle
->getArticleID();
2579 $dbr = wfGetDB( DB_SLAVE
);
2580 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2582 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2583 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2586 if ( $res !== false ) {
2587 foreach ( $res as $row ) {
2588 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2596 * Return an applicable autosummary if one exists for the given edit.
2597 * @param $oldtext String: the previous text of the page.
2598 * @param $newtext String: The submitted text of the page.
2599 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2600 * @return string An appropriate autosummary, or an empty string.
2602 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2605 # Decide what kind of autosummary is needed.
2607 # Redirect autosummaries
2608 $ot = Title
::newFromRedirect( $oldtext );
2609 $rt = Title
::newFromRedirect( $newtext );
2611 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2612 $truncatedtext = $wgContLang->truncate(
2613 str_replace( "\n", ' ', $newtext ),
2615 - strlen( wfMsgForContent( 'autoredircomment' ) )
2616 - strlen( $rt->getFullText() )
2618 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2621 # New page autosummaries
2622 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2623 # If they're making a new article, give its text, truncated, in the summary.
2625 $truncatedtext = $wgContLang->truncate(
2626 str_replace( "\n", ' ', $newtext ),
2627 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2629 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2632 # Blanking autosummaries
2633 if ( $oldtext != '' && $newtext == '' ) {
2634 return wfMsgForContent( 'autosumm-blank' );
2635 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2636 # Removing more than 90% of the article
2638 $truncatedtext = $wgContLang->truncate(
2640 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2642 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2645 # If we reach this point, there's no applicable autosummary for our case, so our
2646 # autosummary is empty.
2651 * Auto-generates a deletion reason
2653 * @param &$hasHistory Boolean: whether the page has a history
2654 * @return mixed String containing deletion reason or empty string, or boolean false
2655 * if no revision occurred
2657 public function getAutoDeleteReason( &$hasHistory ) {
2660 // Get the last revision
2661 $rev = $this->getRevision();
2663 if ( is_null( $rev ) ) {
2667 // Get the article's contents
2668 $contents = $rev->getText();
2671 // If the page is blank, use the text from the previous revision,
2672 // which can only be blank if there's a move/import/protect dummy revision involved
2673 if ( $contents == '' ) {
2674 $prev = $rev->getPrevious();
2677 $contents = $prev->getText();
2682 $dbw = wfGetDB( DB_MASTER
);
2684 // Find out if there was only one contributor
2685 // Only scan the last 20 revisions
2686 $res = $dbw->select( 'revision', 'rev_user_text',
2687 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2689 array( 'LIMIT' => 20 )
2692 if ( $res === false ) {
2693 // This page has no revisions, which is very weird
2697 $hasHistory = ( $res->numRows() > 1 );
2698 $row = $dbw->fetchObject( $res );
2700 if ( $row ) { // $row is false if the only contributor is hidden
2701 $onlyAuthor = $row->rev_user_text
;
2702 // Try to find a second contributor
2703 foreach ( $res as $row ) {
2704 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2705 $onlyAuthor = false;
2710 $onlyAuthor = false;
2713 // Generate the summary with a '$1' placeholder
2715 // The current revision is blank and the one before is also
2716 // blank. It's just not our lucky day
2717 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2719 if ( $onlyAuthor ) {
2720 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2722 $reason = wfMsgForContent( 'excontent', '$1' );
2726 if ( $reason == '-' ) {
2727 // Allow these UI messages to be blanked out cleanly
2731 // Replace newlines with spaces to prevent uglyness
2732 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2733 // Calculate the maximum amount of chars to get
2734 // Max content length = max comment length - length of the comment (excl. $1)
2735 $maxLength = 255 - ( strlen( $reason ) - 2 );
2736 $contents = $wgContLang->truncate( $contents, $maxLength );
2737 // Remove possible unfinished links
2738 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2739 // Now replace the '$1' placeholder
2740 $reason = str_replace( '$1', $contents, $reason );
2746 * Update all the appropriate counts in the category table, given that
2747 * we've added the categories $added and deleted the categories $deleted.
2749 * @param $added array The names of categories that were added
2750 * @param $deleted array The names of categories that were deleted
2752 public function updateCategoryCounts( $added, $deleted ) {
2753 $ns = $this->mTitle
->getNamespace();
2754 $dbw = wfGetDB( DB_MASTER
);
2756 # First make sure the rows exist. If one of the "deleted" ones didn't
2757 # exist, we might legitimately not create it, but it's simpler to just
2758 # create it and then give it a negative value, since the value is bogus
2761 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2762 $insertCats = array_merge( $added, $deleted );
2763 if ( !$insertCats ) {
2764 # Okay, nothing to do
2768 $insertRows = array();
2770 foreach ( $insertCats as $cat ) {
2771 $insertRows[] = array(
2772 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2776 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2778 $addFields = array( 'cat_pages = cat_pages + 1' );
2779 $removeFields = array( 'cat_pages = cat_pages - 1' );
2781 if ( $ns == NS_CATEGORY
) {
2782 $addFields[] = 'cat_subcats = cat_subcats + 1';
2783 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2784 } elseif ( $ns == NS_FILE
) {
2785 $addFields[] = 'cat_files = cat_files + 1';
2786 $removeFields[] = 'cat_files = cat_files - 1';
2793 array( 'cat_title' => $added ),
2802 array( 'cat_title' => $deleted ),
2809 * Updates cascading protections
2811 * @param $parserOutput ParserOutput object for the current version
2813 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2814 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2818 // templatelinks table may have become out of sync,
2819 // especially if using variable-based transclusions.
2820 // For paranoia, check if things have changed and if
2821 // so apply updates to the database. This will ensure
2822 // that cascaded protections apply as soon as the changes
2825 # Get templates from templatelinks
2826 $id = $this->mTitle
->getArticleID();
2828 $tlTemplates = array();
2830 $dbr = wfGetDB( DB_SLAVE
);
2831 $res = $dbr->select( array( 'templatelinks' ),
2832 array( 'tl_namespace', 'tl_title' ),
2833 array( 'tl_from' => $id ),
2837 foreach ( $res as $row ) {
2838 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2841 # Get templates from parser output.
2842 $poTemplates = array();
2843 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2844 foreach ( $templates as $dbk => $id ) {
2845 $poTemplates["$ns:$dbk"] = true;
2850 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2852 if ( count( $templates_diff ) > 0 ) {
2853 # Whee, link updates time.
2854 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
2855 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2861 * Return a list of templates used by this article.
2862 * Uses the templatelinks table
2864 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2865 * @return Array of Title objects
2867 public function getUsedTemplates() {
2868 return $this->mTitle
->getTemplateLinksFrom();
2872 * Perform article updates on a special page creation.
2874 * @param $rev Revision object
2876 * @todo This is a shitty interface function. Kill it and replace the
2877 * other shitty functions like doEditUpdates and such so it's not needed
2879 * @deprecated since 1.18, use doEditUpdates()
2881 public function createUpdates( $rev ) {
2882 wfDeprecated( __METHOD__
, '1.18' );
2884 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2888 * This function is called right before saving the wikitext,
2889 * so we can do things like signatures and links-in-context.
2891 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2892 * @param $text String article contents
2893 * @param $user User object: user doing the edit
2894 * @param $popts ParserOptions object: parser options, default options for
2895 * the user loaded if null given
2896 * @return string article contents with altered wikitext markup (signatures
2897 * converted, {{subst:}}, templates, etc.)
2899 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2900 global $wgParser, $wgUser;
2902 wfDeprecated( __METHOD__
, '1.19' );
2904 $user = is_null( $user ) ?
$wgUser : $user;
2906 if ( $popts === null ) {
2907 $popts = ParserOptions
::newFromUser( $user );
2910 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2914 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2916 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2919 public function isBigDeletion() {
2920 wfDeprecated( __METHOD__
, '1.19' );
2921 return $this->mTitle
->isBigDeletion();
2925 * Get the approximate revision count of this page.
2927 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2930 public function estimateRevisionCount() {
2931 wfDeprecated( __METHOD__
, '1.19' );
2932 return $this->mTitle
->estimateRevisionCount();
2936 * Update the article's restriction field, and leave a log entry.
2938 * @deprecated since 1.19
2939 * @param $limit Array: set of restriction keys
2940 * @param $reason String
2941 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2942 * @param $expiry Array: per restriction type expiration
2943 * @param $user User The user updating the restrictions
2944 * @return bool true on success
2946 public function updateRestrictions(
2947 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2951 $user = is_null( $user ) ?
$wgUser : $user;
2953 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2957 * @deprecated since 1.18
2959 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2960 wfDeprecated( __METHOD__
, '1.18' );
2962 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2966 * @deprecated since 1.18
2968 public function viewUpdates() {
2969 wfDeprecated( __METHOD__
, '1.18' );
2971 return $this->doViewUpdates( $wgUser );
2975 * @deprecated since 1.18
2978 public function useParserCache( $oldid ) {
2979 wfDeprecated( __METHOD__
, '1.18' );
2981 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2985 class PoolWorkArticleView
extends PoolCounterWork
{
3003 * @var ParserOptions
3005 private $parserOptions;
3013 * @var ParserOutput|bool
3015 private $parserOutput = false;
3020 private $isDirty = false;
3025 private $error = false;
3031 * @param $revid Integer: ID of the revision being parsed
3032 * @param $useParserCache Boolean: whether to use the parser cache
3033 * @param $parserOptions parserOptions to use for the parse operation
3034 * @param $text String: text to parse or null to load it
3036 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
3037 $this->page
= $page;
3038 $this->revid
= $revid;
3039 $this->cacheable
= $useParserCache;
3040 $this->parserOptions
= $parserOptions;
3041 $this->text
= $text;
3042 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3043 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3047 * Get the ParserOutput from this object, or false in case of failure
3049 * @return ParserOutput
3051 public function getParserOutput() {
3052 return $this->parserOutput
;
3056 * Get whether the ParserOutput is a dirty one (i.e. expired)
3060 public function getIsDirty() {
3061 return $this->isDirty
;
3065 * Get a Status object in case of error or false otherwise
3067 * @return Status|bool
3069 public function getError() {
3070 return $this->error
;
3077 global $wgParser, $wgUseFileCache;
3079 $isCurrent = $this->revid
=== $this->page
->getLatest();
3081 if ( $this->text
!== null ) {
3082 $text = $this->text
;
3083 } elseif ( $isCurrent ) {
3084 $text = $this->page
->getRawText();
3086 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3087 if ( $rev === null ) {
3090 $text = $rev->getText();
3093 $time = - microtime( true );
3094 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
3095 $this->parserOptions
, true, true, $this->revid
);
3096 $time +
= microtime( true );
3100 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3101 $this->page
->getTitle()->getPrefixedDBkey() ) );
3104 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3105 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3108 // Make sure file cache is not used on uncacheable content.
3109 // Output that has magic words in it can still use the parser cache
3110 // (if enabled), though it will generally expire sooner.
3111 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3112 $wgUseFileCache = false;
3116 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3125 function getCachedWork() {
3126 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3128 if ( $this->parserOutput
=== false ) {
3129 wfDebug( __METHOD__
. ": parser cache miss\n" );
3132 wfDebug( __METHOD__
. ": parser cache hit\n" );
3140 function fallback() {
3141 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3143 if ( $this->parserOutput
=== false ) {
3144 wfDebugLog( 'dirty', "dirty missing\n" );
3145 wfDebug( __METHOD__
. ": no dirty cache\n" );
3148 wfDebug( __METHOD__
. ": sending dirty output\n" );
3149 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3150 $this->isDirty
= true;
3156 * @param $status Status
3159 function error( $status ) {
3160 $this->error
= $status;