3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
26 abstract class Page
{}
29 * Class representing a MediaWiki article and history.
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
34 * @internal documentation reviewed 15 Mar 2010
36 class WikiPage
extends Page
implements IDBAccessObject
{
37 // Constants for $mDataLoadedFrom and related
42 public $mTitle = null;
47 public $mDataLoaded = false; // !< Boolean
48 public $mIsRedirect = false; // !< Boolean
49 public $mLatest = false; // !< Integer (false means "not loaded")
50 public $mPreparedEdit = false; // !< Array
54 * @var int; one of the READ_* constants
56 protected $mDataLoadedFrom = self
::READ_NONE
;
61 protected $mRedirectTarget = null;
66 protected $mLastRevision = null;
69 * @var string; timestamp of the current revision or empty string if not loaded
71 protected $mTimestamp = '';
76 protected $mTouched = '19700101000000';
81 protected $mCounter = null;
84 * Constructor and clear the article
85 * @param $title Title Reference to a Title object.
87 public function __construct( Title
$title ) {
88 $this->mTitle
= $title;
92 * Create a WikiPage object of the appropriate class for the given title.
95 * @return WikiPage object of the appropriate type
97 public static function factory( Title
$title ) {
98 $ns = $title->getNamespace();
100 if ( $ns == NS_MEDIA
) {
101 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
102 } elseif ( $ns < 0 ) {
103 throw new MWException( "Invalid or virtual namespace $ns given." );
108 $page = new WikiFilePage( $title );
111 $page = new WikiCategoryPage( $title );
114 $page = new WikiPage( $title );
121 * Constructor from a page id
123 * @param $id Int article ID to load
124 * @param $from string|int one of the following values:
125 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
126 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
128 * @return WikiPage|null
130 public static function newFromID( $id, $from = 'fromdb' ) {
131 $from = self
::convertSelectType( $from );
132 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
133 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
137 return self
::newFromRow( $row, $from );
141 * Constructor from a database row
144 * @param $row object: database row containing at least fields returned
146 * @param $from string|int: source of $data:
147 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
148 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
149 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
152 public static function newFromRow( $row, $from = 'fromdb' ) {
153 $page = self
::factory( Title
::newFromRow( $row ) );
154 $page->loadFromRow( $row, $from );
159 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
161 * @param $type object|string|int
164 private static function convertSelectType( $type ) {
167 return self
::READ_NORMAL
;
169 return self
::READ_LATEST
;
171 return self
::READ_LOCKING
;
173 // It may already be an integer or whatever else
179 * Returns overrides for action handlers.
180 * Classes listed here will be used instead of the default one when
181 * (and only when) $wgActions[$action] === true. This allows subclasses
182 * to override the default behavior.
184 * @todo: move this UI stuff somewhere else
188 public function getActionOverrides() {
193 * Get the title object of the article
194 * @return Title object of this page
196 public function getTitle() {
197 return $this->mTitle
;
204 public function clear() {
205 $this->mDataLoaded
= false;
206 $this->mDataLoadedFrom
= self
::READ_NONE
;
208 $this->clearCacheFields();
212 * Clear the object cache fields
215 protected function clearCacheFields() {
216 $this->mCounter
= null;
217 $this->mRedirectTarget
= null; # Title object if set
218 $this->mLastRevision
= null; # Latest revision
219 $this->mTouched
= '19700101000000';
220 $this->mTimestamp
= '';
221 $this->mIsRedirect
= false;
222 $this->mLatest
= false;
223 $this->mPreparedEdit
= false;
227 * Return the list of revision fields that should be selected to create
232 public static function selectFields() {
249 * Fetch a page record with the given conditions
250 * @param $dbr DatabaseBase object
251 * @param $conditions Array
252 * @param $options Array
253 * @return mixed Database result resource, or false on failure
255 protected function pageData( $dbr, $conditions, $options = array() ) {
256 $fields = self
::selectFields();
258 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
260 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
262 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
268 * Fetch a page record matching the Title object's namespace and title
269 * using a sanitized title string
271 * @param $dbr DatabaseBase object
272 * @param $title Title object
273 * @param $options Array
274 * @return mixed Database result resource, or false on failure
276 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
277 return $this->pageData( $dbr, array(
278 'page_namespace' => $title->getNamespace(),
279 'page_title' => $title->getDBkey() ), $options );
283 * Fetch a page record matching the requested ID
285 * @param $dbr DatabaseBase
287 * @param $options Array
288 * @return mixed Database result resource, or false on failure
290 public function pageDataFromId( $dbr, $id, $options = array() ) {
291 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
295 * Set the general counter, title etc data loaded from
298 * @param $from object|string|int One of the following:
299 * - A DB query result object
300 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
301 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
302 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
306 public function loadPageData( $from = 'fromdb' ) {
307 $from = self
::convertSelectType( $from );
308 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
309 // We already have the data from the correct location, no need to load it twice.
313 if ( $from === self
::READ_LOCKING
) {
314 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
315 } elseif ( $from === self
::READ_LATEST
) {
316 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
317 } elseif ( $from === self
::READ_NORMAL
) {
318 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
319 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
320 # Note that DB also stores the master position in the session and checks it.
321 $touched = $this->getCachedLastEditTime();
322 if ( $touched ) { // key set
323 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
324 $from = self
::READ_LATEST
;
325 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
329 // No idea from where the caller got this data, assume slave database.
331 $from = self
::READ_NORMAL
;
334 $this->loadFromRow( $data, $from );
338 * Load the object from a database row
341 * @param $data object: database row containing at least fields returned
343 * @param $from string|int One of the following:
344 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
345 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
346 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
347 * the master DB using SELECT FOR UPDATE
349 public function loadFromRow( $data, $from ) {
350 $lc = LinkCache
::singleton();
353 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
355 $this->mTitle
->loadFromRow( $data );
357 # Old-fashioned restrictions
358 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
360 $this->mCounter
= intval( $data->page_counter
);
361 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
362 $this->mIsRedirect
= intval( $data->page_is_redirect
);
363 $this->mLatest
= intval( $data->page_latest
);
364 // Bug 37225: $latest may no longer match the cached latest Revision object.
365 // Double-check the ID of any cached latest Revision object for consistency.
366 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
367 $this->mLastRevision
= null;
368 $this->mTimestamp
= '';
371 $lc->addBadLinkObj( $this->mTitle
);
373 $this->mTitle
->loadFromRow( false );
375 $this->clearCacheFields();
378 $this->mDataLoaded
= true;
379 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
383 * @return int Page ID
385 public function getId() {
386 return $this->mTitle
->getArticleID();
390 * @return bool Whether or not the page exists in the database
392 public function exists() {
393 return $this->mTitle
->exists();
397 * Check if this page is something we're going to be showing
398 * some sort of sensible content for. If we return false, page
399 * views (plain action=view) will return an HTTP 404 response,
400 * so spiders and robots can know they're following a bad link.
404 public function hasViewableContent() {
405 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
409 * @return int The view count for the page
411 public function getCount() {
412 if ( !$this->mDataLoaded
) {
413 $this->loadPageData();
416 return $this->mCounter
;
420 * Tests if the article text represents a redirect
422 * @param $text mixed string containing article contents, or boolean
425 public function isRedirect( $text = false ) {
426 if ( $text === false ) {
427 if ( !$this->mDataLoaded
) {
428 $this->loadPageData();
431 return (bool)$this->mIsRedirect
;
433 return Title
::newFromRedirect( $text ) !== null;
438 * Loads page_touched and returns a value indicating if it should be used
439 * @return boolean true if not a redirect
441 public function checkTouched() {
442 if ( !$this->mDataLoaded
) {
443 $this->loadPageData();
445 return !$this->mIsRedirect
;
449 * Get the page_touched field
450 * @return string containing GMT timestamp
452 public function getTouched() {
453 if ( !$this->mDataLoaded
) {
454 $this->loadPageData();
456 return $this->mTouched
;
460 * Get the page_latest field
461 * @return integer rev_id of current revision
463 public function getLatest() {
464 if ( !$this->mDataLoaded
) {
465 $this->loadPageData();
467 return (int)$this->mLatest
;
471 * Get the Revision object of the oldest revision
472 * @return Revision|null
474 public function getOldestRevision() {
475 wfProfileIn( __METHOD__
);
477 // Try using the slave database first, then try the master
479 $db = wfGetDB( DB_SLAVE
);
480 $revSelectFields = Revision
::selectFields();
482 while ( $continue ) {
483 $row = $db->selectRow(
484 array( 'page', 'revision' ),
487 'page_namespace' => $this->mTitle
->getNamespace(),
488 'page_title' => $this->mTitle
->getDBkey(),
493 'ORDER BY' => 'rev_timestamp ASC'
500 $db = wfGetDB( DB_MASTER
);
505 wfProfileOut( __METHOD__
);
506 return $row ? Revision
::newFromRow( $row ) : null;
510 * Loads everything except the text
511 * This isn't necessary for all uses, so it's only done if needed.
513 protected function loadLastEdit() {
514 if ( $this->mLastRevision
!== null ) {
515 return; // already loaded
518 $latest = $this->getLatest();
520 return; // page doesn't exist or is missing page_latest info
523 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
524 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
525 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
526 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
527 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
528 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
529 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
530 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
531 if ( $revision ) { // sanity
532 $this->setLastEdit( $revision );
537 * Set the latest revision
539 protected function setLastEdit( Revision
$revision ) {
540 $this->mLastRevision
= $revision;
541 $this->mTimestamp
= $revision->getTimestamp();
545 * Get the latest revision
546 * @return Revision|null
548 public function getRevision() {
549 $this->loadLastEdit();
550 if ( $this->mLastRevision
) {
551 return $this->mLastRevision
;
557 * Get the text of the current revision. No side-effects...
559 * @param $audience Integer: one of:
560 * Revision::FOR_PUBLIC to be displayed to all users
561 * Revision::FOR_THIS_USER to be displayed to $wgUser
562 * Revision::RAW get the text regardless of permissions
563 * @return String|bool The text of the current revision. False on failure
565 public function getText( $audience = Revision
::FOR_PUBLIC
) {
566 $this->loadLastEdit();
567 if ( $this->mLastRevision
) {
568 return $this->mLastRevision
->getText( $audience );
574 * Get the text of the current revision. No side-effects...
576 * @return String|bool The text of the current revision. False on failure
578 public function getRawText() {
579 $this->loadLastEdit();
580 if ( $this->mLastRevision
) {
581 return $this->mLastRevision
->getRawText();
587 * @return string MW timestamp of last article revision
589 public function getTimestamp() {
590 // Check if the field has been filled by WikiPage::setTimestamp()
591 if ( !$this->mTimestamp
) {
592 $this->loadLastEdit();
595 return wfTimestamp( TS_MW
, $this->mTimestamp
);
599 * Set the page timestamp (use only to avoid DB queries)
600 * @param $ts string MW timestamp of last article revision
603 public function setTimestamp( $ts ) {
604 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
608 * @param $audience Integer: one of:
609 * Revision::FOR_PUBLIC to be displayed to all users
610 * Revision::FOR_THIS_USER to be displayed to $wgUser
611 * Revision::RAW get the text regardless of permissions
612 * @return int user ID for the user that made the last article revision
614 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
615 $this->loadLastEdit();
616 if ( $this->mLastRevision
) {
617 return $this->mLastRevision
->getUser( $audience );
624 * Get the User object of the user who created the page
625 * @param $audience Integer: one of:
626 * Revision::FOR_PUBLIC to be displayed to all users
627 * Revision::FOR_THIS_USER to be displayed to $wgUser
628 * Revision::RAW get the text regardless of permissions
631 public function getCreator( $audience = Revision
::FOR_PUBLIC
) {
632 $revision = $this->getOldestRevision();
634 $userName = $revision->getUserText( $audience );
635 return User
::newFromName( $userName, false );
642 * @param $audience Integer: one of:
643 * Revision::FOR_PUBLIC to be displayed to all users
644 * Revision::FOR_THIS_USER to be displayed to $wgUser
645 * Revision::RAW get the text regardless of permissions
646 * @return string username of the user that made the last article revision
648 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
649 $this->loadLastEdit();
650 if ( $this->mLastRevision
) {
651 return $this->mLastRevision
->getUserText( $audience );
658 * @param $audience Integer: one of:
659 * Revision::FOR_PUBLIC to be displayed to all users
660 * Revision::FOR_THIS_USER to be displayed to $wgUser
661 * Revision::RAW get the text regardless of permissions
662 * @return string Comment stored for the last article revision
664 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
665 $this->loadLastEdit();
666 if ( $this->mLastRevision
) {
667 return $this->mLastRevision
->getComment( $audience );
674 * Returns true if last revision was marked as "minor edit"
676 * @return boolean Minor edit indicator for the last article revision.
678 public function getMinorEdit() {
679 $this->loadLastEdit();
680 if ( $this->mLastRevision
) {
681 return $this->mLastRevision
->isMinor();
688 * Get the cached timestamp for the last time the page changed.
689 * This is only used to help handle slave lag by comparing to page_touched.
690 * @return string MW timestamp
692 protected function getCachedLastEditTime() {
694 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
695 return $wgMemc->get( $key );
699 * Set the cached timestamp for the last time the page changed.
700 * This is only used to help handle slave lag by comparing to page_touched.
701 * @param $timestamp string
704 public function setCachedLastEditTime( $timestamp ) {
706 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
707 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
711 * Determine whether a page would be suitable for being counted as an
712 * article in the site_stats table based on the title & its content
714 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
715 * if false, the current database state will be used
718 public function isCountable( $editInfo = false ) {
719 global $wgArticleCountMethod;
721 if ( !$this->mTitle
->isContentPage() ) {
725 $text = $editInfo ?
$editInfo->pst
: false;
727 if ( $this->isRedirect( $text ) ) {
731 switch ( $wgArticleCountMethod ) {
735 if ( $text === false ) {
736 $text = $this->getRawText();
738 return strpos( $text, ',' ) !== false;
741 // ParserOutput::getLinks() is a 2D array of page links, so
742 // to be really correct we would need to recurse in the array
743 // but the main array should only have items in it if there are
745 return (bool)count( $editInfo->output
->getLinks() );
747 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
748 array( 'pl_from' => $this->getId() ), __METHOD__
);
754 * If this page is a redirect, get its target
756 * The target will be fetched from the redirect table if possible.
757 * If this page doesn't have an entry there, call insertRedirect()
758 * @return Title|mixed object, or null if this page is not a redirect
760 public function getRedirectTarget() {
761 if ( !$this->mTitle
->isRedirect() ) {
765 if ( $this->mRedirectTarget
!== null ) {
766 return $this->mRedirectTarget
;
769 # Query the redirect table
770 $dbr = wfGetDB( DB_SLAVE
);
771 $row = $dbr->selectRow( 'redirect',
772 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
773 array( 'rd_from' => $this->getId() ),
777 // rd_fragment and rd_interwiki were added later, populate them if empty
778 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
779 return $this->mRedirectTarget
= Title
::makeTitle(
780 $row->rd_namespace
, $row->rd_title
,
781 $row->rd_fragment
, $row->rd_interwiki
);
784 # This page doesn't have an entry in the redirect table
785 return $this->mRedirectTarget
= $this->insertRedirect();
789 * Insert an entry for this page into the redirect table.
791 * Don't call this function directly unless you know what you're doing.
792 * @return Title object or null if not a redirect
794 public function insertRedirect() {
795 // recurse through to only get the final target
796 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
800 $this->insertRedirectEntry( $retval );
805 * Insert or update the redirect table entry for this page to indicate
806 * it redirects to $rt .
807 * @param $rt Title redirect target
809 public function insertRedirectEntry( $rt ) {
810 $dbw = wfGetDB( DB_MASTER
);
811 $dbw->replace( 'redirect', array( 'rd_from' ),
813 'rd_from' => $this->getId(),
814 'rd_namespace' => $rt->getNamespace(),
815 'rd_title' => $rt->getDBkey(),
816 'rd_fragment' => $rt->getFragment(),
817 'rd_interwiki' => $rt->getInterwiki(),
824 * Get the Title object or URL this page redirects to
826 * @return mixed false, Title of in-wiki target, or string with URL
828 public function followRedirect() {
829 return $this->getRedirectURL( $this->getRedirectTarget() );
833 * Get the Title object or URL to use for a redirect. We use Title
834 * objects for same-wiki, non-special redirects and URLs for everything
836 * @param $rt Title Redirect target
837 * @return mixed false, Title object of local target, or string with URL
839 public function getRedirectURL( $rt ) {
844 if ( $rt->isExternal() ) {
845 if ( $rt->isLocal() ) {
846 // Offsite wikis need an HTTP redirect.
848 // This can be hard to reverse and may produce loops,
849 // so they may be disabled in the site configuration.
850 $source = $this->mTitle
->getFullURL( 'redirect=no' );
851 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
853 // External pages pages without "local" bit set are not valid
859 if ( $rt->isSpecialPage() ) {
860 // Gotta handle redirects to special pages differently:
861 // Fill the HTTP response "Location" header and ignore
862 // the rest of the page we're on.
864 // Some pages are not valid targets
865 if ( $rt->isValidRedirectTarget() ) {
866 return $rt->getFullURL();
876 * Get a list of users who have edited this article, not including the user who made
877 * the most recent revision, which you can get from $article->getUser() if you want it
878 * @return UserArrayFromResult
880 public function getContributors() {
881 # @todo FIXME: This is expensive; cache this info somewhere.
883 $dbr = wfGetDB( DB_SLAVE
);
885 if ( $dbr->implicitGroupby() ) {
886 $realNameField = 'user_real_name';
888 $realNameField = 'MIN(user_real_name) AS user_real_name';
891 $tables = array( 'revision', 'user' );
894 'user_id' => 'rev_user',
895 'user_name' => 'rev_user_text',
897 'timestamp' => 'MAX(rev_timestamp)',
900 $conds = array( 'rev_page' => $this->getId() );
902 // The user who made the top revision gets credited as "this page was last edited by
903 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
904 $user = $this->getUser();
906 $conds[] = "rev_user != $user";
908 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
911 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
914 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
918 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
919 'ORDER BY' => 'timestamp DESC',
922 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
923 return new UserArrayFromResult( $res );
927 * Get the last N authors
928 * @param $num Integer: number of revisions to get
929 * @param $revLatest String: the latest rev_id, selected from the master (optional)
930 * @return array Array of authors, duplicates not removed
932 public function getLastNAuthors( $num, $revLatest = 0 ) {
933 wfProfileIn( __METHOD__
);
934 // First try the slave
935 // If that doesn't have the latest revision, try the master
937 $db = wfGetDB( DB_SLAVE
);
940 $res = $db->select( array( 'page', 'revision' ),
941 array( 'rev_id', 'rev_user_text' ),
943 'page_namespace' => $this->mTitle
->getNamespace(),
944 'page_title' => $this->mTitle
->getDBkey(),
948 'ORDER BY' => 'rev_timestamp DESC',
954 wfProfileOut( __METHOD__
);
958 $row = $db->fetchObject( $res );
960 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
961 $db = wfGetDB( DB_MASTER
);
966 } while ( $continue );
968 $authors = array( $row->rev_user_text
);
970 foreach ( $res as $row ) {
971 $authors[] = $row->rev_user_text
;
974 wfProfileOut( __METHOD__
);
979 * Should the parser cache be used?
981 * @param $parserOptions ParserOptions to check
985 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
986 global $wgEnableParserCache;
988 return $wgEnableParserCache
989 && $parserOptions->getStubThreshold() == 0
990 && $this->mTitle
->exists()
991 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
992 && $this->mTitle
->isWikitextPage();
996 * Get a ParserOutput for the given ParserOptions and revision ID.
997 * The parser cache will be used if possible.
1000 * @param $parserOptions ParserOptions to use for the parse operation
1001 * @param $oldid Revision ID to get the text from, passing null or 0 will
1002 * get the current revision (default value)
1003 * @return ParserOutput or false if the revision was not found
1005 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1006 wfProfileIn( __METHOD__
);
1008 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1009 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1010 if ( $parserOptions->getStubThreshold() ) {
1011 wfIncrStats( 'pcache_miss_stub' );
1014 if ( $useParserCache ) {
1015 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1016 if ( $parserOutput !== false ) {
1017 wfProfileOut( __METHOD__
);
1018 return $parserOutput;
1022 if ( $oldid === null ||
$oldid === 0 ) {
1023 $oldid = $this->getLatest();
1026 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1029 wfProfileOut( __METHOD__
);
1031 return $pool->getParserOutput();
1035 * Do standard deferred updates after page view
1036 * @param $user User The relevant user
1038 public function doViewUpdates( User
$user ) {
1039 global $wgDisableCounters;
1040 if ( wfReadOnly() ) {
1044 # Don't update page view counters on views from bot users (bug 14044)
1045 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1046 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1047 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1050 # Update newtalk / watchlist notification status
1051 $user->clearNotification( $this->mTitle
);
1055 * Perform the actions of a page purging
1058 public function doPurge() {
1061 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1065 // Invalidate the cache
1066 $this->mTitle
->invalidateCache();
1069 if ( $wgUseSquid ) {
1070 // Commit the transaction before the purge is sent
1071 $dbw = wfGetDB( DB_MASTER
);
1072 $dbw->commit( __METHOD__
);
1075 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1076 $update->doUpdate();
1079 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1080 if ( $this->mTitle
->exists() ) {
1081 $text = $this->getRawText();
1086 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1092 * Insert a new empty page record for this article.
1093 * This *must* be followed up by creating a revision
1094 * and running $this->updateRevisionOn( ... );
1095 * or else the record will be left in a funky state.
1096 * Best if all done inside a transaction.
1098 * @param $dbw DatabaseBase
1099 * @return int The newly created page_id key, or false if the title already existed
1101 public function insertOn( $dbw ) {
1102 wfProfileIn( __METHOD__
);
1104 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1105 $dbw->insert( 'page', array(
1106 'page_id' => $page_id,
1107 'page_namespace' => $this->mTitle
->getNamespace(),
1108 'page_title' => $this->mTitle
->getDBkey(),
1109 'page_counter' => 0,
1110 'page_restrictions' => '',
1111 'page_is_redirect' => 0, # Will set this shortly...
1113 'page_random' => wfRandom(),
1114 'page_touched' => $dbw->timestamp(),
1115 'page_latest' => 0, # Fill this in shortly...
1116 'page_len' => 0, # Fill this in shortly...
1117 ), __METHOD__
, 'IGNORE' );
1119 $affected = $dbw->affectedRows();
1122 $newid = $dbw->insertId();
1123 $this->mTitle
->resetArticleID( $newid );
1125 wfProfileOut( __METHOD__
);
1127 return $affected ?
$newid : false;
1131 * Update the page record to point to a newly saved revision.
1133 * @param $dbw DatabaseBase: object
1134 * @param $revision Revision: For ID number, and text used to set
1135 * length and redirect status fields
1136 * @param $lastRevision Integer: if given, will not overwrite the page field
1137 * when different from the currently set value.
1138 * Giving 0 indicates the new page flag should be set
1140 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1141 * removing rows in redirect table.
1142 * @return bool true on success, false on failure
1145 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1146 wfProfileIn( __METHOD__
);
1148 $text = $revision->getText();
1149 $len = strlen( $text );
1150 $rt = Title
::newFromRedirectRecurse( $text );
1152 $conditions = array( 'page_id' => $this->getId() );
1154 if ( !is_null( $lastRevision ) ) {
1155 # An extra check against threads stepping on each other
1156 $conditions['page_latest'] = $lastRevision;
1159 $now = wfTimestampNow();
1160 $dbw->update( 'page',
1162 'page_latest' => $revision->getId(),
1163 'page_touched' => $dbw->timestamp( $now ),
1164 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1165 'page_is_redirect' => $rt !== null ?
1 : 0,
1171 $result = $dbw->affectedRows() > 0;
1173 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1174 $this->setLastEdit( $revision );
1175 $this->setCachedLastEditTime( $now );
1176 $this->mLatest
= $revision->getId();
1177 $this->mIsRedirect
= (bool)$rt;
1178 # Update the LinkCache.
1179 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1182 wfProfileOut( __METHOD__
);
1187 * Add row to the redirect table if this is a redirect, remove otherwise.
1189 * @param $dbw DatabaseBase
1190 * @param $redirectTitle Title object pointing to the redirect target,
1191 * or NULL if this is not a redirect
1192 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1193 * removing rows in redirect table.
1194 * @return bool true on success, false on failure
1197 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1198 // Always update redirects (target link might have changed)
1199 // Update/Insert if we don't know if the last revision was a redirect or not
1200 // Delete if changing from redirect to non-redirect
1201 $isRedirect = !is_null( $redirectTitle );
1203 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1207 wfProfileIn( __METHOD__
);
1208 if ( $isRedirect ) {
1209 $this->insertRedirectEntry( $redirectTitle );
1211 // This is not a redirect, remove row from redirect table
1212 $where = array( 'rd_from' => $this->getId() );
1213 $dbw->delete( 'redirect', $where, __METHOD__
);
1216 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1217 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1219 wfProfileOut( __METHOD__
);
1221 return ( $dbw->affectedRows() != 0 );
1225 * If the given revision is newer than the currently set page_latest,
1226 * update the page record. Otherwise, do nothing.
1228 * @param $dbw DatabaseBase object
1229 * @param $revision Revision object
1232 public function updateIfNewerOn( $dbw, $revision ) {
1233 wfProfileIn( __METHOD__
);
1235 $row = $dbw->selectRow(
1236 array( 'revision', 'page' ),
1237 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1239 'page_id' => $this->getId(),
1240 'page_latest=rev_id' ),
1244 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1245 wfProfileOut( __METHOD__
);
1248 $prev = $row->rev_id
;
1249 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1251 # No or missing previous revision; mark the page as new
1253 $lastRevIsRedirect = null;
1256 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1258 wfProfileOut( __METHOD__
);
1263 * Get the text that needs to be saved in order to undo all revisions
1264 * between $undo and $undoafter. Revisions must belong to the same page,
1265 * must exist and must not be deleted
1266 * @param $undo Revision
1267 * @param $undoafter Revision Must be an earlier revision than $undo
1268 * @return mixed string on success, false on failure
1270 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1271 $cur_text = $this->getRawText();
1272 if ( $cur_text === false ) {
1273 return false; // no page
1275 $undo_text = $undo->getText();
1276 $undoafter_text = $undoafter->getText();
1278 if ( $cur_text == $undo_text ) {
1279 # No use doing a merge if it's just a straight revert.
1280 return $undoafter_text;
1285 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1289 return $undone_text;
1293 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1294 * @param $text String: new text of the section
1295 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1296 * @param $edittime String: revision timestamp or null to use the current revision
1297 * @return string Complete article text, or null if error
1299 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1300 wfProfileIn( __METHOD__
);
1302 if ( strval( $section ) == '' ) {
1303 // Whole-page edit; let the whole text through
1305 // Bug 30711: always use current version when adding a new section
1306 if ( is_null( $edittime ) ||
$section == 'new' ) {
1307 $oldtext = $this->getRawText();
1308 if ( $oldtext === false ) {
1309 wfDebug( __METHOD__
. ": no page text\n" );
1310 wfProfileOut( __METHOD__
);
1314 $dbw = wfGetDB( DB_MASTER
);
1315 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1318 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1319 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1320 wfProfileOut( __METHOD__
);
1324 $oldtext = $rev->getText();
1327 if ( $section == 'new' ) {
1328 # Inserting a new section
1329 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1330 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1331 $text = strlen( trim( $oldtext ) ) > 0
1332 ?
"{$oldtext}\n\n{$subject}{$text}"
1333 : "{$subject}{$text}";
1336 # Replacing an existing section; roll out the big guns
1339 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1343 wfProfileOut( __METHOD__
);
1348 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1350 * @return Int updated $flags
1352 function checkFlags( $flags ) {
1353 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1354 if ( $this->mTitle
->getArticleID() ) {
1355 $flags |
= EDIT_UPDATE
;
1365 * Change an existing article or create a new article. Updates RC and all necessary caches,
1366 * optionally via the deferred update array.
1368 * @param $text String: new text
1369 * @param $summary String: edit summary
1370 * @param $flags Integer bitfield:
1372 * Article is known or assumed to be non-existent, create a new one
1374 * Article is known or assumed to be pre-existing, update it
1376 * Mark this edit minor, if the user is allowed to do so
1378 * Do not log the change in recentchanges
1380 * Mark the edit a "bot" edit regardless of user rights
1381 * EDIT_DEFER_UPDATES
1382 * Defer some of the updates until the end of index.php
1384 * Fill in blank summaries with generated text where possible
1386 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1387 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1388 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1389 * edit-already-exists error will be returned. These two conditions are also possible with
1390 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1392 * @param $baseRevId int the revision ID this edit was based off, if any
1393 * @param $user User the user doing the edit
1395 * @return Status object. Possible errors:
1396 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1397 * edit-gone-missing: In update mode, but the article didn't exist
1398 * edit-conflict: In update mode, the article changed unexpectedly
1399 * edit-no-change: Warning that the text was the same as before
1400 * edit-already-exists: In creation mode, but the article already exists
1402 * Extensions may define additional errors.
1404 * $return->value will contain an associative array with members as follows:
1405 * new: Boolean indicating if the function attempted to create a new article
1406 * revision: The revision object for the inserted revision, or null
1408 * Compatibility note: this function previously returned a boolean value indicating success/failure
1410 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1411 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1413 # Low-level sanity check
1414 if ( $this->mTitle
->getText() === '' ) {
1415 throw new MWException( 'Something is trying to edit an article with an empty title' );
1418 wfProfileIn( __METHOD__
);
1420 $user = is_null( $user ) ?
$wgUser : $user;
1421 $status = Status
::newGood( array() );
1423 // Load the data from the master database if needed.
1424 // The caller may already loaded it from the master or even loaded it using
1425 // SELECT FOR UPDATE, so do not override that using clear().
1426 $this->loadPageData( 'fromdbmaster' );
1428 $flags = $this->checkFlags( $flags );
1430 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1431 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1433 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1435 if ( $status->isOK() ) {
1436 $status->fatal( 'edit-hook-aborted' );
1439 wfProfileOut( __METHOD__
);
1443 # Silently ignore EDIT_MINOR if not allowed
1444 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1445 $bot = $flags & EDIT_FORCE_BOT
;
1447 $oldtext = $this->getRawText(); // current revision
1448 $oldsize = strlen( $oldtext );
1449 $oldid = $this->getLatest();
1450 $oldIsRedirect = $this->isRedirect();
1451 $oldcountable = $this->isCountable();
1453 # Provide autosummaries if one is not provided and autosummaries are enabled.
1454 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1455 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1458 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1459 $text = $editInfo->pst
;
1460 $newsize = strlen( $text );
1462 $dbw = wfGetDB( DB_MASTER
);
1463 $now = wfTimestampNow();
1464 $this->mTimestamp
= $now;
1466 if ( $flags & EDIT_UPDATE
) {
1467 # Update article, but only if changed.
1468 $status->value
['new'] = false;
1471 # Article gone missing
1472 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1473 $status->fatal( 'edit-gone-missing' );
1475 wfProfileOut( __METHOD__
);
1477 } elseif ( $oldtext === false ) {
1478 # Sanity check for bug 37225
1479 wfProfileOut( __METHOD__
);
1480 throw new MWException( "Could not find text for current revision {$oldid}." );
1483 $revision = new Revision( array(
1484 'page' => $this->getId(),
1485 'comment' => $summary,
1486 'minor_edit' => $isminor,
1488 'parent_id' => $oldid,
1489 'user' => $user->getId(),
1490 'user_text' => $user->getName(),
1493 # Bug 37225: use accessor to get the text as Revision may trim it.
1494 # After trimming, the text may be a duplicate of the current text.
1495 $text = $revision->getText(); // sanity; EditPage should trim already
1497 $changed = ( strcmp( $text, $oldtext ) != 0 );
1500 $dbw->begin( __METHOD__
);
1501 $revisionId = $revision->insertOn( $dbw );
1505 # Note that we use $this->mLatest instead of fetching a value from the master DB
1506 # during the course of this function. This makes sure that EditPage can detect
1507 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1508 # before this function is called. A previous function used a separate query, this
1509 # creates a window where concurrent edits can cause an ignored edit conflict.
1510 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1513 # Belated edit conflict! Run away!!
1514 $status->fatal( 'edit-conflict' );
1516 $dbw->rollback( __METHOD__
);
1518 wfProfileOut( __METHOD__
);
1522 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1523 # Update recentchanges
1524 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1525 # Mark as patrolled if the user can do so
1526 $patrolled = $wgUseRCPatrol && !count(
1527 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1528 # Add RC row to the DB
1529 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1530 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1531 $revisionId, $patrolled
1534 # Log auto-patrolled edits
1536 PatrolLog
::record( $rc, true, $user );
1539 $user->incEditCount();
1540 $dbw->commit( __METHOD__
);
1542 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1543 // related variables correctly
1544 $revision->setId( $this->getLatest() );
1547 # Update links tables, site stats, etc.
1548 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1549 'oldcountable' => $oldcountable ) );
1552 $status->warning( 'edit-no-change' );
1554 // Update page_touched, this is usually implicit in the page update
1555 // Other cache updates are done in onArticleEdit()
1556 $this->mTitle
->invalidateCache();
1559 # Create new article
1560 $status->value
['new'] = true;
1562 $dbw->begin( __METHOD__
);
1564 # Add the page record; stake our claim on this title!
1565 # This will return false if the article already exists
1566 $newid = $this->insertOn( $dbw );
1568 if ( $newid === false ) {
1569 $dbw->rollback( __METHOD__
);
1570 $status->fatal( 'edit-already-exists' );
1572 wfProfileOut( __METHOD__
);
1576 # Save the revision text...
1577 $revision = new Revision( array(
1579 'comment' => $summary,
1580 'minor_edit' => $isminor,
1582 'user' => $user->getId(),
1583 'user_text' => $user->getName(),
1586 $revisionId = $revision->insertOn( $dbw );
1588 # Bug 37225: use accessor to get the text as Revision may trim it
1589 $text = $revision->getText(); // sanity; EditPage should trim already
1591 # Update the page record with revision data
1592 $this->updateRevisionOn( $dbw, $revision, 0 );
1594 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1596 # Update recentchanges
1597 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1598 # Mark as patrolled if the user can do so
1599 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1600 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1601 # Add RC row to the DB
1602 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1603 '', strlen( $text ), $revisionId, $patrolled );
1605 # Log auto-patrolled edits
1607 PatrolLog
::record( $rc, true, $user );
1610 $user->incEditCount();
1611 $dbw->commit( __METHOD__
);
1613 # Update links, etc.
1614 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1616 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1617 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1620 # Do updates right now unless deferral was requested
1621 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1622 DeferredUpdates
::doUpdates();
1625 // Return the new revision (or null) to the caller
1626 $status->value
['revision'] = $revision;
1628 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1629 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1631 # Promote user to any groups they meet the criteria for
1632 $user->addAutopromoteOnceGroups( 'onEdit' );
1634 wfProfileOut( __METHOD__
);
1639 * Get parser options suitable for rendering the primary article wikitext
1640 * @param User|string $user User object or 'canonical'
1641 * @return ParserOptions
1643 public function makeParserOptions( $user ) {
1645 if ( $user instanceof User
) { // settings per user (even anons)
1646 $options = ParserOptions
::newFromUser( $user );
1647 } else { // canonical settings
1648 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1650 $options->enableLimitReport(); // show inclusion/loop reports
1651 $options->setTidy( true ); // fix bad HTML
1656 * Prepare text which is about to be saved.
1657 * Returns a stdclass with source, pst and output members
1658 * @return bool|object
1660 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1661 global $wgParser, $wgContLang, $wgUser;
1662 $user = is_null( $user ) ?
$wgUser : $user;
1663 // @TODO fixme: check $user->getId() here???
1664 if ( $this->mPreparedEdit
1665 && $this->mPreparedEdit
->newText
== $text
1666 && $this->mPreparedEdit
->revid
== $revid
1669 return $this->mPreparedEdit
;
1672 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1673 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1675 $edit = (object)array();
1676 $edit->revid
= $revid;
1677 $edit->newText
= $text;
1678 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1679 $edit->popts
= $this->makeParserOptions( 'canonical' );
1680 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1681 $edit->oldText
= $this->getRawText();
1683 $this->mPreparedEdit
= $edit;
1689 * Do standard deferred updates after page edit.
1690 * Update links tables, site stats, search index and message cache.
1691 * Purges pages that include this page if the text was changed here.
1692 * Every 100th edit, prune the recent changes table.
1695 * @param $revision Revision object
1696 * @param $user User object that did the revision
1697 * @param $options Array of options, following indexes are used:
1698 * - changed: boolean, whether the revision changed the content (default true)
1699 * - created: boolean, whether the revision created the page (default false)
1700 * - oldcountable: boolean or null (default null):
1701 * - boolean: whether the page was counted as an article before that
1702 * revision, only used in changed is true and created is false
1703 * - null: don't change the article count
1705 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1706 global $wgEnableParserCache;
1708 wfProfileIn( __METHOD__
);
1710 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1711 $text = $revision->getText();
1714 # Be careful not to double-PST: $text is usually already PST-ed once
1715 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1716 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1717 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1719 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1720 $editInfo = $this->mPreparedEdit
;
1723 # Save it to the parser cache
1724 if ( $wgEnableParserCache ) {
1725 $parserCache = ParserCache
::singleton();
1726 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1729 # Update the links tables and other secondary data
1730 $updates = $editInfo->output
->getSecondaryDataUpdates( $this->mTitle
);
1731 DataUpdate
::runUpdates( $updates );
1733 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1735 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1736 if ( 0 == mt_rand( 0, 99 ) ) {
1737 // Flush old entries from the `recentchanges` table; we do this on
1738 // random requests so as to avoid an increase in writes for no good reason
1741 $dbw = wfGetDB( DB_MASTER
);
1742 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1745 array( "rc_timestamp < '$cutoff'" ),
1751 if ( !$this->mTitle
->exists() ) {
1752 wfProfileOut( __METHOD__
);
1756 $id = $this->getId();
1757 $title = $this->mTitle
->getPrefixedDBkey();
1758 $shortTitle = $this->mTitle
->getDBkey();
1760 if ( !$options['changed'] ) {
1763 } elseif ( $options['created'] ) {
1764 $good = (int)$this->isCountable( $editInfo );
1766 } elseif ( $options['oldcountable'] !== null ) {
1767 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1774 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1775 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1777 # If this is another user's talk page, update newtalk.
1778 # Don't do this if $options['changed'] = false (null-edits) nor if
1779 # it's a minor edit and the user doesn't want notifications for those.
1780 if ( $options['changed']
1781 && $this->mTitle
->getNamespace() == NS_USER_TALK
1782 && $shortTitle != $user->getTitleKey()
1783 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1785 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1786 $other = User
::newFromName( $shortTitle, false );
1788 wfDebug( __METHOD__
. ": invalid username\n" );
1789 } elseif ( User
::isIP( $shortTitle ) ) {
1790 // An anonymous user
1791 $other->setNewtalk( true, $revision );
1792 } elseif ( $other->isLoggedIn() ) {
1793 $other->setNewtalk( true, $revision );
1795 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1800 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1801 MessageCache
::singleton()->replace( $shortTitle, $text );
1804 if( $options['created'] ) {
1805 self
::onArticleCreate( $this->mTitle
);
1807 self
::onArticleEdit( $this->mTitle
);
1810 wfProfileOut( __METHOD__
);
1814 * Edit an article without doing all that other stuff
1815 * The article must already exist; link tables etc
1816 * are not updated, caches are not flushed.
1818 * @param $text String: text submitted
1819 * @param $user User The relevant user
1820 * @param $comment String: comment submitted
1821 * @param $minor Boolean: whereas it's a minor modification
1823 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1824 wfProfileIn( __METHOD__
);
1826 $dbw = wfGetDB( DB_MASTER
);
1827 $revision = new Revision( array(
1828 'page' => $this->getId(),
1830 'comment' => $comment,
1831 'minor_edit' => $minor ?
1 : 0,
1833 $revision->insertOn( $dbw );
1834 $this->updateRevisionOn( $dbw, $revision );
1836 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1838 wfProfileOut( __METHOD__
);
1842 * Update the article's restriction field, and leave a log entry.
1843 * This works for protection both existing and non-existing pages.
1845 * @param $limit Array: set of restriction keys
1846 * @param $reason String
1847 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1848 * @param $expiry Array: per restriction type expiration
1849 * @param $user User The user updating the restrictions
1852 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1855 if ( wfReadOnly() ) {
1856 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1859 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1861 $id = $this->mTitle
->getArticleID();
1867 // Take this opportunity to purge out expired restrictions
1868 Title
::purgeExpiredRestrictions();
1870 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1871 # we expect a single selection, but the schema allows otherwise.
1872 $isProtected = false;
1876 $dbw = wfGetDB( DB_MASTER
);
1878 foreach ( $restrictionTypes as $action ) {
1879 if ( !isset( $expiry[$action] ) ) {
1880 $expiry[$action] = $dbw->getInfinity();
1882 if ( !isset( $limit[$action] ) ) {
1883 $limit[$action] = '';
1884 } elseif ( $limit[$action] != '' ) {
1888 # Get current restrictions on $action
1889 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1890 if ( $current != '' ) {
1891 $isProtected = true;
1894 if ( $limit[$action] != $current ) {
1896 } elseif ( $limit[$action] != '' ) {
1897 # Only check expiry change if the action is actually being
1898 # protected, since expiry does nothing on an not-protected
1900 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1906 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1910 # If nothing's changed, do nothing
1912 return Status
::newGood();
1915 if ( !$protect ) { # No protection at all means unprotection
1916 $revCommentMsg = 'unprotectedarticle';
1917 $logAction = 'unprotect';
1918 } elseif ( $isProtected ) {
1919 $revCommentMsg = 'modifiedarticleprotection';
1920 $logAction = 'modify';
1922 $revCommentMsg = 'protectedarticle';
1923 $logAction = 'protect';
1926 $encodedExpiry = array();
1927 $protectDescription = '';
1928 foreach ( $limit as $action => $restrictions ) {
1929 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1930 if ( $restrictions != '' ) {
1931 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1932 if ( $encodedExpiry[$action] != 'infinity' ) {
1933 $protectDescription .= wfMsgForContent( 'protect-expiring',
1934 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1935 $wgContLang->date( $expiry[$action], false, false ) ,
1936 $wgContLang->time( $expiry[$action], false, false ) );
1938 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1941 $protectDescription .= ') ';
1944 $protectDescription = trim( $protectDescription );
1946 if ( $id ) { # Protection of existing page
1947 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1948 return Status
::newGood();
1951 # Only restrictions with the 'protect' right can cascade...
1952 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1953 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1955 # The schema allows multiple restrictions
1956 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1960 # Update restrictions table
1961 foreach ( $limit as $action => $restrictions ) {
1962 if ( $restrictions != '' ) {
1963 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1964 array( 'pr_page' => $id,
1965 'pr_type' => $action,
1966 'pr_level' => $restrictions,
1967 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1968 'pr_expiry' => $encodedExpiry[$action]
1973 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1974 'pr_type' => $action ), __METHOD__
);
1978 # Prepare a null revision to be added to the history
1979 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1981 $editComment .= ": $reason";
1983 if ( $protectDescription ) {
1984 $editComment .= " ($protectDescription)";
1987 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1990 # Insert a null revision
1991 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1992 $nullRevId = $nullRevision->insertOn( $dbw );
1994 $latest = $this->getLatest();
1995 # Update page record
1996 $dbw->update( 'page',
1998 'page_touched' => $dbw->timestamp(),
1999 'page_restrictions' => '',
2000 'page_latest' => $nullRevId
2001 ), array( /* WHERE */
2006 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2007 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2008 } else { # Protection of non-existing page (also known as "title protection")
2009 # Cascade protection is meaningless in this case
2012 if ( $limit['create'] != '' ) {
2013 $dbw->replace( 'protected_titles',
2014 array( array( 'pt_namespace', 'pt_title' ) ),
2016 'pt_namespace' => $this->mTitle
->getNamespace(),
2017 'pt_title' => $this->mTitle
->getDBkey(),
2018 'pt_create_perm' => $limit['create'],
2019 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2020 'pt_expiry' => $encodedExpiry['create'],
2021 'pt_user' => $user->getId(),
2022 'pt_reason' => $reason,
2026 $dbw->delete( 'protected_titles',
2028 'pt_namespace' => $this->mTitle
->getNamespace(),
2029 'pt_title' => $this->mTitle
->getDBkey()
2035 $this->mTitle
->flushRestrictions();
2037 if ( $logAction == 'unprotect' ) {
2038 $logParams = array();
2040 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2043 # Update the protection log
2044 $log = new LogPage( 'protect' );
2045 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2047 return Status
::newGood();
2051 * Take an array of page restrictions and flatten it to a string
2052 * suitable for insertion into the page_restrictions field.
2053 * @param $limit Array
2056 protected static function flattenRestrictions( $limit ) {
2057 if ( !is_array( $limit ) ) {
2058 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2064 foreach ( $limit as $action => $restrictions ) {
2065 if ( $restrictions != '' ) {
2066 $bits[] = "$action=$restrictions";
2070 return implode( ':', $bits );
2074 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2075 * backwards compatibility, if you care about error reporting you should use
2076 * doDeleteArticleReal() instead.
2078 * Deletes the article with database consistency, writes logs, purges caches
2080 * @param $reason string delete reason for deletion log
2081 * @param $suppress boolean suppress all revisions and log the deletion in
2082 * the suppression log instead of the deletion log
2083 * @param $id int article ID
2084 * @param $commit boolean defaults to true, triggers transaction end
2085 * @param &$error Array of errors to append to
2086 * @param $user User The deleting user
2087 * @return boolean true if successful
2089 public function doDeleteArticle(
2090 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2092 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2093 return $status->isGood();
2097 * Back-end article deletion
2098 * Deletes the article with database consistency, writes logs, purges caches
2102 * @param $reason string delete reason for deletion log
2103 * @param $suppress boolean suppress all revisions and log the deletion in
2104 * the suppression log instead of the deletion log
2105 * @param $commit boolean defaults to true, triggers transaction end
2106 * @param &$error Array of errors to append to
2107 * @param $user User The deleting user
2108 * @return Status: Status object; if successful, $status->value is the log_id of the
2109 * deletion log entry. If the page couldn't be deleted because it wasn't
2110 * found, $status is a non-fatal 'cannotdelete' error
2112 public function doDeleteArticleReal(
2113 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2117 wfDebug( __METHOD__
. "\n" );
2119 $status = Status
::newGood();
2121 if ( $this->mTitle
->getDBkey() === '' ) {
2122 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2126 $user = is_null( $user ) ?
$wgUser : $user;
2127 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2128 if ( $status->isOK() ) {
2129 // Hook aborted but didn't set a fatal status
2130 $status->fatal( 'delete-hook-aborted' );
2136 $this->loadPageData( 'forupdate' );
2137 $id = $this->getID();
2139 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2144 // Bitfields to further suppress the content
2147 // This should be 15...
2148 $bitfield |
= Revision
::DELETED_TEXT
;
2149 $bitfield |
= Revision
::DELETED_COMMENT
;
2150 $bitfield |
= Revision
::DELETED_USER
;
2151 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2153 $bitfield = 'rev_deleted';
2156 $dbw = wfGetDB( DB_MASTER
);
2157 $dbw->begin( __METHOD__
);
2158 // For now, shunt the revision data into the archive table.
2159 // Text is *not* removed from the text table; bulk storage
2160 // is left intact to avoid breaking block-compression or
2161 // immutable storage schemes.
2163 // For backwards compatibility, note that some older archive
2164 // table entries will have ar_text and ar_flags fields still.
2166 // In the future, we may keep revisions and mark them with
2167 // the rev_deleted field, which is reserved for this purpose.
2168 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2170 'ar_namespace' => 'page_namespace',
2171 'ar_title' => 'page_title',
2172 'ar_comment' => 'rev_comment',
2173 'ar_user' => 'rev_user',
2174 'ar_user_text' => 'rev_user_text',
2175 'ar_timestamp' => 'rev_timestamp',
2176 'ar_minor_edit' => 'rev_minor_edit',
2177 'ar_rev_id' => 'rev_id',
2178 'ar_parent_id' => 'rev_parent_id',
2179 'ar_text_id' => 'rev_text_id',
2180 'ar_text' => '\'\'', // Be explicit to appease
2181 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2182 'ar_len' => 'rev_len',
2183 'ar_page_id' => 'page_id',
2184 'ar_deleted' => $bitfield,
2185 'ar_sha1' => 'rev_sha1'
2188 'page_id = rev_page'
2192 # Now that it's safely backed up, delete it
2193 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2194 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2197 $dbw->rollback( __METHOD__
);
2198 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2202 $this->doDeleteUpdates( $id );
2204 # Log the deletion, if the page was suppressed, log it at Oversight instead
2205 $logtype = $suppress ?
'suppress' : 'delete';
2207 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2208 $logEntry->setPerformer( $user );
2209 $logEntry->setTarget( $this->mTitle
);
2210 $logEntry->setComment( $reason );
2211 $logid = $logEntry->insert();
2212 $logEntry->publish( $logid );
2215 $dbw->commit( __METHOD__
);
2218 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2219 $status->value
= $logid;
2224 * Do some database updates after deletion
2226 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2228 public function doDeleteUpdates( $id ) {
2229 # update site status
2230 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2232 # remove secondary indexes, etc
2233 $updates = $this->getDeletionUpdates( );
2234 DataUpdate
::runUpdates( $updates );
2237 WikiPage
::onArticleDelete( $this->mTitle
);
2242 # Clear the cached article id so the interface doesn't act like we exist
2243 $this->mTitle
->resetArticleID( 0 );
2246 public function getDeletionUpdates() {
2248 new LinksDeletionUpdate( $this ),
2251 //@todo: make a hook to add update objects
2252 //NOTE: deletion updates will be determined by the ContentHandler in the future
2257 * Roll back the most recent consecutive set of edits to a page
2258 * from the same user; fails if there are no eligible edits to
2259 * roll back to, e.g. user is the sole contributor. This function
2260 * performs permissions checks on $user, then calls commitRollback()
2261 * to do the dirty work
2263 * @todo: seperate the business/permission stuff out from backend code
2265 * @param $fromP String: Name of the user whose edits to rollback.
2266 * @param $summary String: Custom summary. Set to default summary if empty.
2267 * @param $token String: Rollback token.
2268 * @param $bot Boolean: If true, mark all reverted edits as bot.
2270 * @param $resultDetails Array: contains result-specific array of additional values
2271 * 'alreadyrolled' : 'current' (rev)
2272 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2274 * @param $user User The user performing the rollback
2275 * @return array of errors, each error formatted as
2276 * array(messagekey, param1, param2, ...).
2277 * On success, the array is empty. This array can also be passed to
2278 * OutputPage::showPermissionsErrorPage().
2280 public function doRollback(
2281 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2283 $resultDetails = null;
2286 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2287 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2288 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2290 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2291 $errors[] = array( 'sessionfailure' );
2294 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2295 $errors[] = array( 'actionthrottledtext' );
2298 # If there were errors, bail out now
2299 if ( !empty( $errors ) ) {
2303 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2307 * Backend implementation of doRollback(), please refer there for parameter
2308 * and return value documentation
2310 * NOTE: This function does NOT check ANY permissions, it just commits the
2311 * rollback to the DB. Therefore, you should only call this function direct-
2312 * ly if you want to use custom permissions checks. If you don't, use
2313 * doRollback() instead.
2314 * @param $fromP String: Name of the user whose edits to rollback.
2315 * @param $summary String: Custom summary. Set to default summary if empty.
2316 * @param $bot Boolean: If true, mark all reverted edits as bot.
2318 * @param $resultDetails Array: contains result-specific array of additional values
2319 * @param $guser User The user performing the rollback
2322 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2323 global $wgUseRCPatrol, $wgContLang;
2325 $dbw = wfGetDB( DB_MASTER
);
2327 if ( wfReadOnly() ) {
2328 return array( array( 'readonlytext' ) );
2331 # Get the last editor
2332 $current = $this->getRevision();
2333 if ( is_null( $current ) ) {
2334 # Something wrong... no page?
2335 return array( array( 'notanarticle' ) );
2338 $from = str_replace( '_', ' ', $fromP );
2339 # User name given should match up with the top revision.
2340 # If the user was deleted then $from should be empty.
2341 if ( $from != $current->getUserText() ) {
2342 $resultDetails = array( 'current' => $current );
2343 return array( array( 'alreadyrolled',
2344 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2345 htmlspecialchars( $fromP ),
2346 htmlspecialchars( $current->getUserText() )
2350 # Get the last edit not by this guy...
2351 # Note: these may not be public values
2352 $user = intval( $current->getRawUser() );
2353 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2354 $s = $dbw->selectRow( 'revision',
2355 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2356 array( 'rev_page' => $current->getPage(),
2357 "rev_user != {$user} OR rev_user_text != {$user_text}"
2359 array( 'USE INDEX' => 'page_timestamp',
2360 'ORDER BY' => 'rev_timestamp DESC' )
2362 if ( $s === false ) {
2363 # No one else ever edited this page
2364 return array( array( 'cantrollback' ) );
2365 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2366 # Only admins can see this text
2367 return array( array( 'notvisiblerev' ) );
2371 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2372 # Mark all reverted edits as bot
2376 if ( $wgUseRCPatrol ) {
2377 # Mark all reverted edits as patrolled
2378 $set['rc_patrolled'] = 1;
2381 if ( count( $set ) ) {
2382 $dbw->update( 'recentchanges', $set,
2384 'rc_cur_id' => $current->getPage(),
2385 'rc_user_text' => $current->getUserText(),
2386 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2391 # Generate the edit summary if necessary
2392 $target = Revision
::newFromId( $s->rev_id
);
2393 if ( empty( $summary ) ) {
2394 if ( $from == '' ) { // no public user name
2395 $summary = wfMsgForContent( 'revertpage-nouser' );
2397 $summary = wfMsgForContent( 'revertpage' );
2401 # Allow the custom summary to use the same args as the default message
2403 $target->getUserText(), $from, $s->rev_id
,
2404 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2405 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2407 $summary = wfMsgReplaceArgs( $summary, $args );
2409 # Truncate for whole multibyte characters.
2410 $summary = $wgContLang->truncate( $summary, 255 );
2413 $flags = EDIT_UPDATE
;
2415 if ( $guser->isAllowed( 'minoredit' ) ) {
2416 $flags |
= EDIT_MINOR
;
2419 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2420 $flags |
= EDIT_FORCE_BOT
;
2423 # Actually store the edit
2424 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2425 if ( !empty( $status->value
['revision'] ) ) {
2426 $revId = $status->value
['revision']->getId();
2431 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2433 $resultDetails = array(
2434 'summary' => $summary,
2435 'current' => $current,
2436 'target' => $target,
2444 * The onArticle*() functions are supposed to be a kind of hooks
2445 * which should be called whenever any of the specified actions
2448 * This is a good place to put code to clear caches, for instance.
2450 * This is called on page move and undelete, as well as edit
2452 * @param $title Title object
2454 public static function onArticleCreate( $title ) {
2455 # Update existence markers on article/talk tabs...
2456 if ( $title->isTalkPage() ) {
2457 $other = $title->getSubjectPage();
2459 $other = $title->getTalkPage();
2462 $other->invalidateCache();
2463 $other->purgeSquid();
2465 $title->touchLinks();
2466 $title->purgeSquid();
2467 $title->deleteTitleProtection();
2471 * Clears caches when article is deleted
2473 * @param $title Title
2475 public static function onArticleDelete( $title ) {
2476 # Update existence markers on article/talk tabs...
2477 if ( $title->isTalkPage() ) {
2478 $other = $title->getSubjectPage();
2480 $other = $title->getTalkPage();
2483 $other->invalidateCache();
2484 $other->purgeSquid();
2486 $title->touchLinks();
2487 $title->purgeSquid();
2490 HTMLFileCache
::clearFileCache( $title );
2493 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2494 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2498 if ( $title->getNamespace() == NS_FILE
) {
2499 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2500 $update->doUpdate();
2504 if ( $title->getNamespace() == NS_USER_TALK
) {
2505 $user = User
::newFromName( $title->getText(), false );
2507 $user->setNewtalk( false );
2512 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2516 * Purge caches on page update etc
2518 * @param $title Title object
2519 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2521 public static function onArticleEdit( $title ) {
2522 // Invalidate caches of articles which include this page
2523 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2526 // Invalidate the caches of all pages which redirect here
2527 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2529 # Purge squid for this page only
2530 $title->purgeSquid();
2532 # Clear file cache for this page only
2533 HTMLFileCache
::clearFileCache( $title );
2539 * Returns a list of hidden categories this page is a member of.
2540 * Uses the page_props and categorylinks tables.
2542 * @return Array of Title objects
2544 public function getHiddenCategories() {
2546 $id = $this->mTitle
->getArticleID();
2552 $dbr = wfGetDB( DB_SLAVE
);
2553 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2555 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2556 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2559 if ( $res !== false ) {
2560 foreach ( $res as $row ) {
2561 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2569 * Return an applicable autosummary if one exists for the given edit.
2570 * @param $oldtext String: the previous text of the page.
2571 * @param $newtext String: The submitted text of the page.
2572 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2573 * @return string An appropriate autosummary, or an empty string.
2575 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2578 # Decide what kind of autosummary is needed.
2580 # Redirect autosummaries
2581 $ot = Title
::newFromRedirect( $oldtext );
2582 $rt = Title
::newFromRedirect( $newtext );
2584 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2585 $truncatedtext = $wgContLang->truncate(
2586 str_replace( "\n", ' ', $newtext ),
2588 - strlen( wfMsgForContent( 'autoredircomment' ) )
2589 - strlen( $rt->getFullText() )
2591 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2594 # New page autosummaries
2595 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2596 # If they're making a new article, give its text, truncated, in the summary.
2598 $truncatedtext = $wgContLang->truncate(
2599 str_replace( "\n", ' ', $newtext ),
2600 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2602 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2605 # Blanking autosummaries
2606 if ( $oldtext != '' && $newtext == '' ) {
2607 return wfMsgForContent( 'autosumm-blank' );
2608 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2609 # Removing more than 90% of the article
2611 $truncatedtext = $wgContLang->truncate(
2613 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2615 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2618 # If we reach this point, there's no applicable autosummary for our case, so our
2619 # autosummary is empty.
2624 * Auto-generates a deletion reason
2626 * @param &$hasHistory Boolean: whether the page has a history
2627 * @return mixed String containing deletion reason or empty string, or boolean false
2628 * if no revision occurred
2630 public function getAutoDeleteReason( &$hasHistory ) {
2633 // Get the last revision
2634 $rev = $this->getRevision();
2636 if ( is_null( $rev ) ) {
2640 // Get the article's contents
2641 $contents = $rev->getText();
2644 // If the page is blank, use the text from the previous revision,
2645 // which can only be blank if there's a move/import/protect dummy revision involved
2646 if ( $contents == '' ) {
2647 $prev = $rev->getPrevious();
2650 $contents = $prev->getText();
2655 $dbw = wfGetDB( DB_MASTER
);
2657 // Find out if there was only one contributor
2658 // Only scan the last 20 revisions
2659 $res = $dbw->select( 'revision', 'rev_user_text',
2660 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2662 array( 'LIMIT' => 20 )
2665 if ( $res === false ) {
2666 // This page has no revisions, which is very weird
2670 $hasHistory = ( $res->numRows() > 1 );
2671 $row = $dbw->fetchObject( $res );
2673 if ( $row ) { // $row is false if the only contributor is hidden
2674 $onlyAuthor = $row->rev_user_text
;
2675 // Try to find a second contributor
2676 foreach ( $res as $row ) {
2677 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2678 $onlyAuthor = false;
2683 $onlyAuthor = false;
2686 // Generate the summary with a '$1' placeholder
2688 // The current revision is blank and the one before is also
2689 // blank. It's just not our lucky day
2690 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2692 if ( $onlyAuthor ) {
2693 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2695 $reason = wfMsgForContent( 'excontent', '$1' );
2699 if ( $reason == '-' ) {
2700 // Allow these UI messages to be blanked out cleanly
2704 // Replace newlines with spaces to prevent uglyness
2705 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2706 // Calculate the maximum amount of chars to get
2707 // Max content length = max comment length - length of the comment (excl. $1)
2708 $maxLength = 255 - ( strlen( $reason ) - 2 );
2709 $contents = $wgContLang->truncate( $contents, $maxLength );
2710 // Remove possible unfinished links
2711 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2712 // Now replace the '$1' placeholder
2713 $reason = str_replace( '$1', $contents, $reason );
2719 * Update all the appropriate counts in the category table, given that
2720 * we've added the categories $added and deleted the categories $deleted.
2722 * @param $added array The names of categories that were added
2723 * @param $deleted array The names of categories that were deleted
2725 public function updateCategoryCounts( $added, $deleted ) {
2726 $ns = $this->mTitle
->getNamespace();
2727 $dbw = wfGetDB( DB_MASTER
);
2729 # First make sure the rows exist. If one of the "deleted" ones didn't
2730 # exist, we might legitimately not create it, but it's simpler to just
2731 # create it and then give it a negative value, since the value is bogus
2734 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2735 $insertCats = array_merge( $added, $deleted );
2736 if ( !$insertCats ) {
2737 # Okay, nothing to do
2741 $insertRows = array();
2743 foreach ( $insertCats as $cat ) {
2744 $insertRows[] = array(
2745 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2749 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2751 $addFields = array( 'cat_pages = cat_pages + 1' );
2752 $removeFields = array( 'cat_pages = cat_pages - 1' );
2754 if ( $ns == NS_CATEGORY
) {
2755 $addFields[] = 'cat_subcats = cat_subcats + 1';
2756 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2757 } elseif ( $ns == NS_FILE
) {
2758 $addFields[] = 'cat_files = cat_files + 1';
2759 $removeFields[] = 'cat_files = cat_files - 1';
2766 array( 'cat_title' => $added ),
2775 array( 'cat_title' => $deleted ),
2782 * Updates cascading protections
2784 * @param $parserOutput ParserOutput object for the current version
2786 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2787 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2791 // templatelinks table may have become out of sync,
2792 // especially if using variable-based transclusions.
2793 // For paranoia, check if things have changed and if
2794 // so apply updates to the database. This will ensure
2795 // that cascaded protections apply as soon as the changes
2798 # Get templates from templatelinks
2799 $id = $this->mTitle
->getArticleID();
2801 $tlTemplates = array();
2803 $dbr = wfGetDB( DB_SLAVE
);
2804 $res = $dbr->select( array( 'templatelinks' ),
2805 array( 'tl_namespace', 'tl_title' ),
2806 array( 'tl_from' => $id ),
2810 foreach ( $res as $row ) {
2811 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2814 # Get templates from parser output.
2815 $poTemplates = array();
2816 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2817 foreach ( $templates as $dbk => $id ) {
2818 $poTemplates["$ns:$dbk"] = true;
2823 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2825 if ( count( $templates_diff ) > 0 ) {
2826 # Whee, link updates time.
2827 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
2828 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2834 * Return a list of templates used by this article.
2835 * Uses the templatelinks table
2837 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2838 * @return Array of Title objects
2840 public function getUsedTemplates() {
2841 return $this->mTitle
->getTemplateLinksFrom();
2845 * Perform article updates on a special page creation.
2847 * @param $rev Revision object
2849 * @todo This is a shitty interface function. Kill it and replace the
2850 * other shitty functions like doEditUpdates and such so it's not needed
2852 * @deprecated since 1.18, use doEditUpdates()
2854 public function createUpdates( $rev ) {
2855 wfDeprecated( __METHOD__
, '1.18' );
2857 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2861 * This function is called right before saving the wikitext,
2862 * so we can do things like signatures and links-in-context.
2864 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2865 * @param $text String article contents
2866 * @param $user User object: user doing the edit
2867 * @param $popts ParserOptions object: parser options, default options for
2868 * the user loaded if null given
2869 * @return string article contents with altered wikitext markup (signatures
2870 * converted, {{subst:}}, templates, etc.)
2872 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2873 global $wgParser, $wgUser;
2875 wfDeprecated( __METHOD__
, '1.19' );
2877 $user = is_null( $user ) ?
$wgUser : $user;
2879 if ( $popts === null ) {
2880 $popts = ParserOptions
::newFromUser( $user );
2883 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2887 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2889 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2892 public function isBigDeletion() {
2893 wfDeprecated( __METHOD__
, '1.19' );
2894 return $this->mTitle
->isBigDeletion();
2898 * Get the approximate revision count of this page.
2900 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2903 public function estimateRevisionCount() {
2904 wfDeprecated( __METHOD__
, '1.19' );
2905 return $this->mTitle
->estimateRevisionCount();
2909 * Update the article's restriction field, and leave a log entry.
2911 * @deprecated since 1.19
2912 * @param $limit Array: set of restriction keys
2913 * @param $reason String
2914 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2915 * @param $expiry Array: per restriction type expiration
2916 * @param $user User The user updating the restrictions
2917 * @return bool true on success
2919 public function updateRestrictions(
2920 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2924 $user = is_null( $user ) ?
$wgUser : $user;
2926 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2930 * @deprecated since 1.18
2932 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2933 wfDeprecated( __METHOD__
, '1.18' );
2935 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2939 * @deprecated since 1.18
2941 public function viewUpdates() {
2942 wfDeprecated( __METHOD__
, '1.18' );
2944 return $this->doViewUpdates( $wgUser );
2948 * @deprecated since 1.18
2951 public function useParserCache( $oldid ) {
2952 wfDeprecated( __METHOD__
, '1.18' );
2954 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2958 class PoolWorkArticleView
extends PoolCounterWork
{
2976 * @var ParserOptions
2978 private $parserOptions;
2986 * @var ParserOutput|bool
2988 private $parserOutput = false;
2993 private $isDirty = false;
2998 private $error = false;
3004 * @param $revid Integer: ID of the revision being parsed
3005 * @param $useParserCache Boolean: whether to use the parser cache
3006 * @param $parserOptions parserOptions to use for the parse operation
3007 * @param $text String: text to parse or null to load it
3009 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
3010 $this->page
= $page;
3011 $this->revid
= $revid;
3012 $this->cacheable
= $useParserCache;
3013 $this->parserOptions
= $parserOptions;
3014 $this->text
= $text;
3015 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3016 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3020 * Get the ParserOutput from this object, or false in case of failure
3022 * @return ParserOutput
3024 public function getParserOutput() {
3025 return $this->parserOutput
;
3029 * Get whether the ParserOutput is a dirty one (i.e. expired)
3033 public function getIsDirty() {
3034 return $this->isDirty
;
3038 * Get a Status object in case of error or false otherwise
3040 * @return Status|bool
3042 public function getError() {
3043 return $this->error
;
3050 global $wgParser, $wgUseFileCache;
3052 $isCurrent = $this->revid
=== $this->page
->getLatest();
3054 if ( $this->text
!== null ) {
3055 $text = $this->text
;
3056 } elseif ( $isCurrent ) {
3057 $text = $this->page
->getRawText();
3059 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3060 if ( $rev === null ) {
3063 $text = $rev->getText();
3066 $time = - microtime( true );
3067 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
3068 $this->parserOptions
, true, true, $this->revid
);
3069 $time +
= microtime( true );
3073 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3074 $this->page
->getTitle()->getPrefixedDBkey() ) );
3077 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3078 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3081 // Make sure file cache is not used on uncacheable content.
3082 // Output that has magic words in it can still use the parser cache
3083 // (if enabled), though it will generally expire sooner.
3084 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3085 $wgUseFileCache = false;
3089 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3098 function getCachedWork() {
3099 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3101 if ( $this->parserOutput
=== false ) {
3102 wfDebug( __METHOD__
. ": parser cache miss\n" );
3105 wfDebug( __METHOD__
. ": parser cache hit\n" );
3113 function fallback() {
3114 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3116 if ( $this->parserOutput
=== false ) {
3117 wfDebugLog( 'dirty', "dirty missing\n" );
3118 wfDebug( __METHOD__
. ": no dirty cache\n" );
3121 wfDebug( __METHOD__
. ": sending dirty output\n" );
3122 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3123 $this->isDirty
= true;
3129 * @param $status Status
3132 function error( $status ) {
3133 $this->error
= $status;