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
;
247 public function clear() {
248 $this->mDataLoaded
= false;
249 $this->mDataLoadedFrom
= self
::DATA_NOT_LOADED
;
251 $this->mCounter
= null;
252 $this->mRedirectTarget
= null; # Title object if set
253 $this->mLastRevision
= null; # Latest revision
254 $this->mTouched
= '19700101000000';
255 $this->mTimestamp
= '';
256 $this->mIsRedirect
= false;
257 $this->mLatest
= false;
258 $this->mPreparedEdit
= false;
262 * Return the list of revision fields that should be selected to create
267 public static function selectFields() {
284 * Fetch a page record with the given conditions
285 * @param $dbr DatabaseBase object
286 * @param $conditions Array
287 * @param $options Array
288 * @return mixed Database result resource, or false on failure
290 protected function pageData( $dbr, $conditions, $options = array() ) {
291 $fields = self
::selectFields();
293 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
295 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
297 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
303 * Fetch a page record matching the Title object's namespace and title
304 * using a sanitized title string
306 * @param $dbr DatabaseBase object
307 * @param $title Title object
308 * @param $options Array
309 * @return mixed Database result resource, or false on failure
311 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
312 return $this->pageData( $dbr, array(
313 'page_namespace' => $title->getNamespace(),
314 'page_title' => $title->getDBkey() ), $options );
318 * Fetch a page record matching the requested ID
320 * @param $dbr DatabaseBase
322 * @param $options Array
323 * @return mixed Database result resource, or false on failure
325 public function pageDataFromId( $dbr, $id, $options = array() ) {
326 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
330 * Set the general counter, title etc data loaded from
333 * @param $from object|string|int One of the following:
334 * - A DB query result object
335 * - "fromdb" or self::DATA_FROM_SLAVE to get from a slave DB
336 * - "fromdbmaster" or self::DATA_FROM_MASTER to get from the master DB
337 * - "forupdate" or self::DATA_FOR_UPDATE to get from the master DB using SELECT FOR UPDATE
341 public function loadPageData( $from = 'fromdb' ) {
342 $from = self
::convertSelectType( $from );
343 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
344 // We already have the data from the correct location, no need to load it twice.
348 if ( $from === self
::DATA_FOR_UPDATE
) {
349 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
350 } elseif ( $from === self
::DATA_FROM_MASTER
) {
351 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
352 } elseif ( $from === self
::DATA_FROM_SLAVE
) {
353 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
354 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
355 # Note that DB also stores the master position in the session and checks it.
356 $touched = $this->getCachedLastEditTime();
357 if ( $touched ) { // key set
358 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
359 $from = self
::DATA_FROM_MASTER
;
360 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
364 // No idea from where the caller got this data, assume slave database.
366 $from = self
::DATA_FROM_SLAVE
;
369 $this->loadFromRow( $data, $from );
373 * Load the object from a database row
376 * @param $data object: database row containing at least fields returned
378 * @param $from string|int One of the following:
379 * - "fromdb" or self::DATA_FROM_SLAVE if the data comes from a slave DB
380 * - "fromdbmaster" or self::DATA_FROM_MASTER if the data comes from the master DB
381 * - "forupdate" or self::DATA_FOR_UPDATE if the data comes from from
382 * the master DB using SELECT FOR UPDATE
384 public function loadFromRow( $data, $from ) {
385 $lc = LinkCache
::singleton();
388 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
390 $this->mTitle
->loadFromRow( $data );
392 # Old-fashioned restrictions
393 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
395 $this->mCounter
= intval( $data->page_counter
);
396 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
397 $this->mIsRedirect
= intval( $data->page_is_redirect
);
398 $this->mLatest
= intval( $data->page_latest
);
400 $lc->addBadLinkObj( $this->mTitle
);
402 $this->mTitle
->loadFromRow( false );
405 $this->mDataLoaded
= true;
406 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
410 * @return int Page ID
412 public function getId() {
413 return $this->mTitle
->getArticleID();
417 * @return bool Whether or not the page exists in the database
419 public function exists() {
420 return $this->mTitle
->exists();
424 * Check if this page is something we're going to be showing
425 * some sort of sensible content for. If we return false, page
426 * views (plain action=view) will return an HTTP 404 response,
427 * so spiders and robots can know they're following a bad link.
431 public function hasViewableContent() {
432 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
436 * @return int The view count for the page
438 public function getCount() {
439 if ( !$this->mDataLoaded
) {
440 $this->loadPageData();
443 return $this->mCounter
;
447 * Tests if the article text represents a redirect
449 * @param $text mixed string containing article contents, or boolean
452 public function isRedirect( $text = false ) {
453 if ( $text === false ) {
454 if ( !$this->mDataLoaded
) {
455 $this->loadPageData();
458 return (bool)$this->mIsRedirect
;
460 return Title
::newFromRedirect( $text ) !== null;
465 * Loads page_touched and returns a value indicating if it should be used
466 * @return boolean true if not a redirect
468 public function checkTouched() {
469 if ( !$this->mDataLoaded
) {
470 $this->loadPageData();
472 return !$this->mIsRedirect
;
476 * Get the page_touched field
477 * @return string containing GMT timestamp
479 public function getTouched() {
480 if ( !$this->mDataLoaded
) {
481 $this->loadPageData();
483 return $this->mTouched
;
487 * Get the page_latest field
488 * @return integer rev_id of current revision
490 public function getLatest() {
491 if ( !$this->mDataLoaded
) {
492 $this->loadPageData();
494 return (int)$this->mLatest
;
498 * Loads everything except the text
499 * This isn't necessary for all uses, so it's only done if needed.
501 protected function loadLastEdit() {
502 if ( $this->mLastRevision
!== null ) {
503 return; // already loaded
506 $latest = $this->getLatest();
508 return; // page doesn't exist or is missing page_latest info
511 $revision = Revision
::newFromPageId( $this->getId(), $latest );
512 if ( $revision ) { // sanity
513 $this->setLastEdit( $revision );
518 * Set the latest revision
520 protected function setLastEdit( Revision
$revision ) {
521 $this->mLastRevision
= $revision;
522 $this->mTimestamp
= $revision->getTimestamp();
526 * Get the latest revision
527 * @return Revision|null
529 public function getRevision() {
530 $this->loadLastEdit();
531 if ( $this->mLastRevision
) {
532 return $this->mLastRevision
;
538 * Get the text of the current revision. No side-effects...
540 * @param $audience Integer: one of:
541 * Revision::FOR_PUBLIC to be displayed to all users
542 * Revision::FOR_THIS_USER to be displayed to $wgUser
543 * Revision::RAW get the text regardless of permissions
544 * @return String|bool The text of the current revision. False on failure
546 public function getText( $audience = Revision
::FOR_PUBLIC
) {
547 $this->loadLastEdit();
548 if ( $this->mLastRevision
) {
549 return $this->mLastRevision
->getText( $audience );
555 * Get the text of the current revision. No side-effects...
557 * @return String|bool The text of the current revision. False on failure
559 public function getRawText() {
560 $this->loadLastEdit();
561 if ( $this->mLastRevision
) {
562 return $this->mLastRevision
->getRawText();
568 * @return string MW timestamp of last article revision
570 public function getTimestamp() {
571 // Check if the field has been filled by WikiPage::setTimestamp()
572 if ( !$this->mTimestamp
) {
573 $this->loadLastEdit();
576 return wfTimestamp( TS_MW
, $this->mTimestamp
);
580 * Set the page timestamp (use only to avoid DB queries)
581 * @param $ts string MW timestamp of last article revision
584 public function setTimestamp( $ts ) {
585 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
589 * @param $audience Integer: one of:
590 * Revision::FOR_PUBLIC to be displayed to all users
591 * Revision::FOR_THIS_USER to be displayed to $wgUser
592 * Revision::RAW get the text regardless of permissions
593 * @return int user ID for the user that made the last article revision
595 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
596 $this->loadLastEdit();
597 if ( $this->mLastRevision
) {
598 return $this->mLastRevision
->getUser( $audience );
605 * @param $audience Integer: one of:
606 * Revision::FOR_PUBLIC to be displayed to all users
607 * Revision::FOR_THIS_USER to be displayed to $wgUser
608 * Revision::RAW get the text regardless of permissions
609 * @return string username of the user that made the last article revision
611 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
612 $this->loadLastEdit();
613 if ( $this->mLastRevision
) {
614 return $this->mLastRevision
->getUserText( $audience );
621 * @param $audience Integer: one of:
622 * Revision::FOR_PUBLIC to be displayed to all users
623 * Revision::FOR_THIS_USER to be displayed to $wgUser
624 * Revision::RAW get the text regardless of permissions
625 * @return string Comment stored for the last article revision
627 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
628 $this->loadLastEdit();
629 if ( $this->mLastRevision
) {
630 return $this->mLastRevision
->getComment( $audience );
637 * Returns true if last revision was marked as "minor edit"
639 * @return boolean Minor edit indicator for the last article revision.
641 public function getMinorEdit() {
642 $this->loadLastEdit();
643 if ( $this->mLastRevision
) {
644 return $this->mLastRevision
->isMinor();
651 * Get the cached timestamp for the last time the page changed.
652 * This is only used to help handle slave lag by comparing to page_touched.
653 * @return string MW timestamp
655 protected function getCachedLastEditTime() {
657 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
658 return $wgMemc->get( $key );
662 * Set the cached timestamp for the last time the page changed.
663 * This is only used to help handle slave lag by comparing to page_touched.
664 * @param $timestamp string
667 public function setCachedLastEditTime( $timestamp ) {
669 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
670 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
674 * Determine whether a page would be suitable for being counted as an
675 * article in the site_stats table based on the title & its content
677 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
678 * if false, the current database state will be used
681 public function isCountable( $editInfo = false ) {
682 global $wgArticleCountMethod;
684 if ( !$this->mTitle
->isContentPage() ) {
688 $text = $editInfo ?
$editInfo->pst
: false;
690 if ( $this->isRedirect( $text ) ) {
694 switch ( $wgArticleCountMethod ) {
698 if ( $text === false ) {
699 $text = $this->getRawText();
701 return strpos( $text, ',' ) !== false;
704 // ParserOutput::getLinks() is a 2D array of page links, so
705 // to be really correct we would need to recurse in the array
706 // but the main array should only have items in it if there are
708 return (bool)count( $editInfo->output
->getLinks() );
710 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
711 array( 'pl_from' => $this->getId() ), __METHOD__
);
717 * If this page is a redirect, get its target
719 * The target will be fetched from the redirect table if possible.
720 * If this page doesn't have an entry there, call insertRedirect()
721 * @return Title|mixed object, or null if this page is not a redirect
723 public function getRedirectTarget() {
724 if ( !$this->mTitle
->isRedirect() ) {
728 if ( $this->mRedirectTarget
!== null ) {
729 return $this->mRedirectTarget
;
732 # Query the redirect table
733 $dbr = wfGetDB( DB_SLAVE
);
734 $row = $dbr->selectRow( 'redirect',
735 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
736 array( 'rd_from' => $this->getId() ),
740 // rd_fragment and rd_interwiki were added later, populate them if empty
741 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
742 return $this->mRedirectTarget
= Title
::makeTitle(
743 $row->rd_namespace
, $row->rd_title
,
744 $row->rd_fragment
, $row->rd_interwiki
);
747 # This page doesn't have an entry in the redirect table
748 return $this->mRedirectTarget
= $this->insertRedirect();
752 * Insert an entry for this page into the redirect table.
754 * Don't call this function directly unless you know what you're doing.
755 * @return Title object or null if not a redirect
757 public function insertRedirect() {
758 // recurse through to only get the final target
759 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
763 $this->insertRedirectEntry( $retval );
768 * Insert or update the redirect table entry for this page to indicate
769 * it redirects to $rt .
770 * @param $rt Title redirect target
772 public function insertRedirectEntry( $rt ) {
773 $dbw = wfGetDB( DB_MASTER
);
774 $dbw->replace( 'redirect', array( 'rd_from' ),
776 'rd_from' => $this->getId(),
777 'rd_namespace' => $rt->getNamespace(),
778 'rd_title' => $rt->getDBkey(),
779 'rd_fragment' => $rt->getFragment(),
780 'rd_interwiki' => $rt->getInterwiki(),
787 * Get the Title object or URL this page redirects to
789 * @return mixed false, Title of in-wiki target, or string with URL
791 public function followRedirect() {
792 return $this->getRedirectURL( $this->getRedirectTarget() );
796 * Get the Title object or URL to use for a redirect. We use Title
797 * objects for same-wiki, non-special redirects and URLs for everything
799 * @param $rt Title Redirect target
800 * @return mixed false, Title object of local target, or string with URL
802 public function getRedirectURL( $rt ) {
807 if ( $rt->isExternal() ) {
808 if ( $rt->isLocal() ) {
809 // Offsite wikis need an HTTP redirect.
811 // This can be hard to reverse and may produce loops,
812 // so they may be disabled in the site configuration.
813 $source = $this->mTitle
->getFullURL( 'redirect=no' );
814 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
816 // External pages pages without "local" bit set are not valid
822 if ( $rt->isSpecialPage() ) {
823 // Gotta handle redirects to special pages differently:
824 // Fill the HTTP response "Location" header and ignore
825 // the rest of the page we're on.
827 // Some pages are not valid targets
828 if ( $rt->isValidRedirectTarget() ) {
829 return $rt->getFullURL();
839 * Get a list of users who have edited this article, not including the user who made
840 * the most recent revision, which you can get from $article->getUser() if you want it
841 * @return UserArrayFromResult
843 public function getContributors() {
844 # @todo FIXME: This is expensive; cache this info somewhere.
846 $dbr = wfGetDB( DB_SLAVE
);
848 if ( $dbr->implicitGroupby() ) {
849 $realNameField = 'user_real_name';
851 $realNameField = 'MIN(user_real_name) AS user_real_name';
854 $tables = array( 'revision', 'user' );
857 'rev_user as user_id',
858 'rev_user_text AS user_name',
860 'MAX(rev_timestamp) AS timestamp',
863 $conds = array( 'rev_page' => $this->getId() );
865 // The user who made the top revision gets credited as "this page was last edited by
866 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
867 $user = $this->getUser();
869 $conds[] = "rev_user != $user";
871 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
874 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
877 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
881 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
882 'ORDER BY' => 'timestamp DESC',
885 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
886 return new UserArrayFromResult( $res );
890 * Get the last N authors
891 * @param $num Integer: number of revisions to get
892 * @param $revLatest String: the latest rev_id, selected from the master (optional)
893 * @return array Array of authors, duplicates not removed
895 public function getLastNAuthors( $num, $revLatest = 0 ) {
896 wfProfileIn( __METHOD__
);
897 // First try the slave
898 // If that doesn't have the latest revision, try the master
900 $db = wfGetDB( DB_SLAVE
);
903 $res = $db->select( array( 'page', 'revision' ),
904 array( 'rev_id', 'rev_user_text' ),
906 'page_namespace' => $this->mTitle
->getNamespace(),
907 'page_title' => $this->mTitle
->getDBkey(),
911 'ORDER BY' => 'rev_timestamp DESC',
917 wfProfileOut( __METHOD__
);
921 $row = $db->fetchObject( $res );
923 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
924 $db = wfGetDB( DB_MASTER
);
929 } while ( $continue );
931 $authors = array( $row->rev_user_text
);
933 foreach ( $res as $row ) {
934 $authors[] = $row->rev_user_text
;
937 wfProfileOut( __METHOD__
);
942 * Should the parser cache be used?
944 * @param $parserOptions ParserOptions to check
948 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
949 global $wgEnableParserCache;
951 return $wgEnableParserCache
952 && $parserOptions->getStubThreshold() == 0
953 && $this->mTitle
->exists()
954 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
955 && $this->mTitle
->isWikitextPage();
959 * Get a ParserOutput for the given ParserOptions and revision ID.
960 * The parser cache will be used if possible.
963 * @param $parserOptions ParserOptions to use for the parse operation
964 * @param $oldid Revision ID to get the text from, passing null or 0 will
965 * get the current revision (default value)
966 * @return ParserOutput or false if the revision was not found
968 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
969 wfProfileIn( __METHOD__
);
971 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
972 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
973 if ( $parserOptions->getStubThreshold() ) {
974 wfIncrStats( 'pcache_miss_stub' );
977 if ( $useParserCache ) {
978 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
979 if ( $parserOutput !== false ) {
980 wfProfileOut( __METHOD__
);
981 return $parserOutput;
985 if ( $oldid === null ||
$oldid === 0 ) {
986 $oldid = $this->getLatest();
989 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
992 wfProfileOut( __METHOD__
);
994 return $pool->getParserOutput();
998 * Do standard deferred updates after page view
999 * @param $user User The relevant user
1001 public function doViewUpdates( User
$user ) {
1002 global $wgDisableCounters;
1003 if ( wfReadOnly() ) {
1007 # Don't update page view counters on views from bot users (bug 14044)
1008 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1009 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1010 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1013 # Update newtalk / watchlist notification status
1014 $user->clearNotification( $this->mTitle
);
1018 * Perform the actions of a page purging
1021 public function doPurge() {
1024 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1028 // Invalidate the cache
1029 $this->mTitle
->invalidateCache();
1032 if ( $wgUseSquid ) {
1033 // Commit the transaction before the purge is sent
1034 $dbw = wfGetDB( DB_MASTER
);
1035 $dbw->commit( __METHOD__
);
1038 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1039 $update->doUpdate();
1042 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1043 if ( $this->mTitle
->exists() ) {
1044 $text = $this->getRawText();
1049 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1055 * Insert a new empty page record for this article.
1056 * This *must* be followed up by creating a revision
1057 * and running $this->updateRevisionOn( ... );
1058 * or else the record will be left in a funky state.
1059 * Best if all done inside a transaction.
1061 * @param $dbw DatabaseBase
1062 * @return int The newly created page_id key, or false if the title already existed
1064 public function insertOn( $dbw ) {
1065 wfProfileIn( __METHOD__
);
1067 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1068 $dbw->insert( 'page', array(
1069 'page_id' => $page_id,
1070 'page_namespace' => $this->mTitle
->getNamespace(),
1071 'page_title' => $this->mTitle
->getDBkey(),
1072 'page_counter' => 0,
1073 'page_restrictions' => '',
1074 'page_is_redirect' => 0, # Will set this shortly...
1076 'page_random' => wfRandom(),
1077 'page_touched' => $dbw->timestamp(),
1078 'page_latest' => 0, # Fill this in shortly...
1079 'page_len' => 0, # Fill this in shortly...
1080 ), __METHOD__
, 'IGNORE' );
1082 $affected = $dbw->affectedRows();
1085 $newid = $dbw->insertId();
1086 $this->mTitle
->resetArticleID( $newid );
1088 wfProfileOut( __METHOD__
);
1090 return $affected ?
$newid : false;
1094 * Update the page record to point to a newly saved revision.
1096 * @param $dbw DatabaseBase: object
1097 * @param $revision Revision: For ID number, and text used to set
1098 * length and redirect status fields
1099 * @param $lastRevision Integer: if given, will not overwrite the page field
1100 * when different from the currently set value.
1101 * Giving 0 indicates the new page flag should be set
1103 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1104 * removing rows in redirect table.
1105 * @return bool true on success, false on failure
1108 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1109 wfProfileIn( __METHOD__
);
1111 $text = $revision->getText();
1112 $len = strlen( $text );
1113 $rt = Title
::newFromRedirectRecurse( $text );
1115 $conditions = array( 'page_id' => $this->getId() );
1117 if ( !is_null( $lastRevision ) ) {
1118 # An extra check against threads stepping on each other
1119 $conditions['page_latest'] = $lastRevision;
1122 $now = wfTimestampNow();
1123 $dbw->update( 'page',
1125 'page_latest' => $revision->getId(),
1126 'page_touched' => $dbw->timestamp( $now ),
1127 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1128 'page_is_redirect' => $rt !== null ?
1 : 0,
1134 $result = $dbw->affectedRows() != 0;
1136 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1137 $this->setLastEdit( $revision );
1138 $this->setCachedLastEditTime( $now );
1139 $this->mLatest
= $revision->getId();
1140 $this->mIsRedirect
= (bool)$rt;
1141 # Update the LinkCache.
1142 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1145 wfProfileOut( __METHOD__
);
1150 * Add row to the redirect table if this is a redirect, remove otherwise.
1152 * @param $dbw DatabaseBase
1153 * @param $redirectTitle Title object pointing to the redirect target,
1154 * or NULL if this is not a redirect
1155 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1156 * removing rows in redirect table.
1157 * @return bool true on success, false on failure
1160 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1161 // Always update redirects (target link might have changed)
1162 // Update/Insert if we don't know if the last revision was a redirect or not
1163 // Delete if changing from redirect to non-redirect
1164 $isRedirect = !is_null( $redirectTitle );
1166 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1170 wfProfileIn( __METHOD__
);
1171 if ( $isRedirect ) {
1172 $this->insertRedirectEntry( $redirectTitle );
1174 // This is not a redirect, remove row from redirect table
1175 $where = array( 'rd_from' => $this->getId() );
1176 $dbw->delete( 'redirect', $where, __METHOD__
);
1179 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1180 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1182 wfProfileOut( __METHOD__
);
1184 return ( $dbw->affectedRows() != 0 );
1188 * If the given revision is newer than the currently set page_latest,
1189 * update the page record. Otherwise, do nothing.
1191 * @param $dbw DatabaseBase object
1192 * @param $revision Revision object
1195 public function updateIfNewerOn( $dbw, $revision ) {
1196 wfProfileIn( __METHOD__
);
1198 $row = $dbw->selectRow(
1199 array( 'revision', 'page' ),
1200 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1202 'page_id' => $this->getId(),
1203 'page_latest=rev_id' ),
1207 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1208 wfProfileOut( __METHOD__
);
1211 $prev = $row->rev_id
;
1212 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1214 # No or missing previous revision; mark the page as new
1216 $lastRevIsRedirect = null;
1219 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1221 wfProfileOut( __METHOD__
);
1226 * Get the text that needs to be saved in order to undo all revisions
1227 * between $undo and $undoafter. Revisions must belong to the same page,
1228 * must exist and must not be deleted
1229 * @param $undo Revision
1230 * @param $undoafter Revision Must be an earlier revision than $undo
1231 * @return mixed string on success, false on failure
1233 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1234 $cur_text = $this->getRawText();
1235 if ( $cur_text === false ) {
1236 return false; // no page
1238 $undo_text = $undo->getText();
1239 $undoafter_text = $undoafter->getText();
1241 if ( $cur_text == $undo_text ) {
1242 # No use doing a merge if it's just a straight revert.
1243 return $undoafter_text;
1248 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1252 return $undone_text;
1256 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1257 * @param $text String: new text of the section
1258 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1259 * @param $edittime String: revision timestamp or null to use the current revision
1260 * @return string Complete article text, or null if error
1262 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1263 wfProfileIn( __METHOD__
);
1265 if ( strval( $section ) == '' ) {
1266 // Whole-page edit; let the whole text through
1268 // Bug 30711: always use current version when adding a new section
1269 if ( is_null( $edittime ) ||
$section == 'new' ) {
1270 $oldtext = $this->getRawText();
1271 if ( $oldtext === false ) {
1272 wfDebug( __METHOD__
. ": no page text\n" );
1273 wfProfileOut( __METHOD__
);
1277 $dbw = wfGetDB( DB_MASTER
);
1278 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1281 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1282 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1283 wfProfileOut( __METHOD__
);
1287 $oldtext = $rev->getText();
1290 if ( $section == 'new' ) {
1291 # Inserting a new section
1292 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1293 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1294 $text = strlen( trim( $oldtext ) ) > 0
1295 ?
"{$oldtext}\n\n{$subject}{$text}"
1296 : "{$subject}{$text}";
1299 # Replacing an existing section; roll out the big guns
1302 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1306 wfProfileOut( __METHOD__
);
1311 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1313 * @return Int updated $flags
1315 function checkFlags( $flags ) {
1316 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1317 if ( $this->mTitle
->getArticleID() ) {
1318 $flags |
= EDIT_UPDATE
;
1328 * Change an existing article or create a new article. Updates RC and all necessary caches,
1329 * optionally via the deferred update array.
1331 * @param $text String: new text
1332 * @param $summary String: edit summary
1333 * @param $flags Integer bitfield:
1335 * Article is known or assumed to be non-existent, create a new one
1337 * Article is known or assumed to be pre-existing, update it
1339 * Mark this edit minor, if the user is allowed to do so
1341 * Do not log the change in recentchanges
1343 * Mark the edit a "bot" edit regardless of user rights
1344 * EDIT_DEFER_UPDATES
1345 * Defer some of the updates until the end of index.php
1347 * Fill in blank summaries with generated text where possible
1349 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1350 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1351 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1352 * edit-already-exists error will be returned. These two conditions are also possible with
1353 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1355 * @param $baseRevId int the revision ID this edit was based off, if any
1356 * @param $user User the user doing the edit
1358 * @return Status object. Possible errors:
1359 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1360 * edit-gone-missing: In update mode, but the article didn't exist
1361 * edit-conflict: In update mode, the article changed unexpectedly
1362 * edit-no-change: Warning that the text was the same as before
1363 * edit-already-exists: In creation mode, but the article already exists
1365 * Extensions may define additional errors.
1367 * $return->value will contain an associative array with members as follows:
1368 * new: Boolean indicating if the function attempted to create a new article
1369 * revision: The revision object for the inserted revision, or null
1371 * Compatibility note: this function previously returned a boolean value indicating success/failure
1373 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1374 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1376 # Low-level sanity check
1377 if ( $this->mTitle
->getText() === '' ) {
1378 throw new MWException( 'Something is trying to edit an article with an empty title' );
1381 wfProfileIn( __METHOD__
);
1383 $user = is_null( $user ) ?
$wgUser : $user;
1384 $status = Status
::newGood( array() );
1386 // Load the data from the master database if needed.
1387 // The caller may already loaded it from the master or even loaded it using
1388 // SELECT FOR UPDATE, so do not override that using clear().
1389 $this->loadPageData( 'fromdbmaster' );
1391 $flags = $this->checkFlags( $flags );
1393 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1394 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1396 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1398 if ( $status->isOK() ) {
1399 $status->fatal( 'edit-hook-aborted' );
1402 wfProfileOut( __METHOD__
);
1406 # Silently ignore EDIT_MINOR if not allowed
1407 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1408 $bot = $flags & EDIT_FORCE_BOT
;
1410 $oldtext = $this->getRawText(); // current revision
1411 $oldsize = strlen( $oldtext );
1412 $oldid = $this->getLatest();
1413 $oldIsRedirect = $this->isRedirect();
1414 $oldcountable = $this->isCountable();
1416 # Provide autosummaries if one is not provided and autosummaries are enabled.
1417 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1418 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1421 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1422 $text = $editInfo->pst
;
1423 $newsize = strlen( $text );
1425 $dbw = wfGetDB( DB_MASTER
);
1426 $now = wfTimestampNow();
1427 $this->mTimestamp
= $now;
1429 if ( $flags & EDIT_UPDATE
) {
1430 # Update article, but only if changed.
1431 $status->value
['new'] = false;
1434 # Article gone missing
1435 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1436 $status->fatal( 'edit-gone-missing' );
1438 wfProfileOut( __METHOD__
);
1442 # Make sure the revision is either completely inserted or not inserted at all
1443 if ( !$wgDBtransactions ) {
1444 $userAbort = ignore_user_abort( true );
1447 $revision = new Revision( array(
1448 'page' => $this->getId(),
1449 'comment' => $summary,
1450 'minor_edit' => $isminor,
1452 'parent_id' => $oldid,
1453 'user' => $user->getId(),
1454 'user_text' => $user->getName(),
1458 $changed = ( strcmp( $text, $oldtext ) != 0 );
1461 $dbw->begin( __METHOD__
);
1462 $revisionId = $revision->insertOn( $dbw );
1466 # Note that we use $this->mLatest instead of fetching a value from the master DB
1467 # during the course of this function. This makes sure that EditPage can detect
1468 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1469 # before this function is called. A previous function used a separate query, this
1470 # creates a window where concurrent edits can cause an ignored edit conflict.
1471 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1474 /* Belated edit conflict! Run away!! */
1475 $status->fatal( 'edit-conflict' );
1477 # Delete the invalid revision if the DB is not transactional
1478 if ( !$wgDBtransactions ) {
1479 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1483 $dbw->rollback( __METHOD__
);
1485 global $wgUseRCPatrol;
1486 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1487 # Update recentchanges
1488 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1489 # Mark as patrolled if the user can do so
1490 $patrolled = $wgUseRCPatrol && !count(
1491 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1492 # Add RC row to the DB
1493 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1494 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1495 $revisionId, $patrolled
1498 # Log auto-patrolled edits
1500 PatrolLog
::record( $rc, true, $user );
1503 $user->incEditCount();
1504 $dbw->commit( __METHOD__
);
1507 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1508 // related variables correctly
1509 $revision->setId( $this->getLatest() );
1512 if ( !$wgDBtransactions ) {
1513 ignore_user_abort( $userAbort );
1516 // Now that ignore_user_abort is restored, we can respond to fatal errors
1517 if ( !$status->isOK() ) {
1518 wfProfileOut( __METHOD__
);
1522 # Update links tables, site stats, etc.
1523 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1524 'oldcountable' => $oldcountable ) );
1527 $status->warning( 'edit-no-change' );
1529 // Update page_touched, this is usually implicit in the page update
1530 // Other cache updates are done in onArticleEdit()
1531 $this->mTitle
->invalidateCache();
1534 # Create new article
1535 $status->value
['new'] = true;
1537 $dbw->begin( __METHOD__
);
1539 # Add the page record; stake our claim on this title!
1540 # This will return false if the article already exists
1541 $newid = $this->insertOn( $dbw );
1543 if ( $newid === false ) {
1544 $dbw->rollback( __METHOD__
);
1545 $status->fatal( 'edit-already-exists' );
1547 wfProfileOut( __METHOD__
);
1551 # Save the revision text...
1552 $revision = new Revision( array(
1554 'comment' => $summary,
1555 'minor_edit' => $isminor,
1557 'user' => $user->getId(),
1558 'user_text' => $user->getName(),
1561 $revisionId = $revision->insertOn( $dbw );
1563 # Update the page record with revision data
1564 $this->updateRevisionOn( $dbw, $revision, 0 );
1566 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1568 # Update recentchanges
1569 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1570 global $wgUseRCPatrol, $wgUseNPPatrol;
1572 # Mark as patrolled if the user can do so
1573 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1574 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1575 # Add RC row to the DB
1576 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1577 '', strlen( $text ), $revisionId, $patrolled );
1579 # Log auto-patrolled edits
1581 PatrolLog
::record( $rc, true, $user );
1584 $user->incEditCount();
1585 $dbw->commit( __METHOD__
);
1587 # Update links, etc.
1588 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1590 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1591 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1594 # Do updates right now unless deferral was requested
1595 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1596 DeferredUpdates
::doUpdates();
1599 // Return the new revision (or null) to the caller
1600 $status->value
['revision'] = $revision;
1602 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1603 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1605 # Promote user to any groups they meet the criteria for
1606 $user->addAutopromoteOnceGroups( 'onEdit' );
1608 wfProfileOut( __METHOD__
);
1613 * Get parser options suitable for rendering the primary article wikitext
1614 * @param User|string $user User object or 'canonical'
1615 * @return ParserOptions
1617 public function makeParserOptions( $user ) {
1619 if ( $user instanceof User
) { // settings per user (even anons)
1620 $options = ParserOptions
::newFromUser( $user );
1621 } else { // canonical settings
1622 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1624 $options->enableLimitReport(); // show inclusion/loop reports
1625 $options->setTidy( true ); // fix bad HTML
1630 * Prepare text which is about to be saved.
1631 * Returns a stdclass with source, pst and output members
1632 * @return bool|object
1634 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1635 global $wgParser, $wgContLang, $wgUser;
1636 $user = is_null( $user ) ?
$wgUser : $user;
1637 // @TODO fixme: check $user->getId() here???
1638 if ( $this->mPreparedEdit
1639 && $this->mPreparedEdit
->newText
== $text
1640 && $this->mPreparedEdit
->revid
== $revid
1643 return $this->mPreparedEdit
;
1646 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1647 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1649 $edit = (object)array();
1650 $edit->revid
= $revid;
1651 $edit->newText
= $text;
1652 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1653 $edit->popts
= $this->makeParserOptions( 'canonical' );
1654 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1655 $edit->oldText
= $this->getRawText();
1657 $this->mPreparedEdit
= $edit;
1663 * Do standard deferred updates after page edit.
1664 * Update links tables, site stats, search index and message cache.
1665 * Purges pages that include this page if the text was changed here.
1666 * Every 100th edit, prune the recent changes table.
1669 * @param $revision Revision object
1670 * @param $user User object that did the revision
1671 * @param $options Array of options, following indexes are used:
1672 * - changed: boolean, whether the revision changed the content (default true)
1673 * - created: boolean, whether the revision created the page (default false)
1674 * - oldcountable: boolean or null (default null):
1675 * - boolean: whether the page was counted as an article before that
1676 * revision, only used in changed is true and created is false
1677 * - null: don't change the article count
1679 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1680 global $wgEnableParserCache;
1682 wfProfileIn( __METHOD__
);
1684 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1685 $text = $revision->getText();
1688 # Be careful not to double-PST: $text is usually already PST-ed once
1689 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1690 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1691 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1693 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1694 $editInfo = $this->mPreparedEdit
;
1697 # Save it to the parser cache
1698 if ( $wgEnableParserCache ) {
1699 $parserCache = ParserCache
::singleton();
1700 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1703 # Update the links tables
1704 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1707 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1709 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1710 if ( 0 == mt_rand( 0, 99 ) ) {
1711 // Flush old entries from the `recentchanges` table; we do this on
1712 // random requests so as to avoid an increase in writes for no good reason
1715 $dbw = wfGetDB( DB_MASTER
);
1716 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1719 array( "rc_timestamp < '$cutoff'" ),
1725 if ( !$this->mTitle
->exists() ) {
1726 wfProfileOut( __METHOD__
);
1730 $id = $this->getId();
1731 $title = $this->mTitle
->getPrefixedDBkey();
1732 $shortTitle = $this->mTitle
->getDBkey();
1734 if ( !$options['changed'] ) {
1737 } elseif ( $options['created'] ) {
1738 $good = (int)$this->isCountable( $editInfo );
1740 } elseif ( $options['oldcountable'] !== null ) {
1741 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1748 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1749 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1751 # If this is another user's talk page, update newtalk.
1752 # Don't do this if $options['changed'] = false (null-edits) nor if
1753 # it's a minor edit and the user doesn't want notifications for those.
1754 if ( $options['changed']
1755 && $this->mTitle
->getNamespace() == NS_USER_TALK
1756 && $shortTitle != $user->getTitleKey()
1757 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1759 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1760 $other = User
::newFromName( $shortTitle, false );
1762 wfDebug( __METHOD__
. ": invalid username\n" );
1763 } elseif ( User
::isIP( $shortTitle ) ) {
1764 // An anonymous user
1765 $other->setNewtalk( true );
1766 } elseif ( $other->isLoggedIn() ) {
1767 $other->setNewtalk( true );
1769 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1774 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1775 MessageCache
::singleton()->replace( $shortTitle, $text );
1778 if( $options['created'] ) {
1779 self
::onArticleCreate( $this->mTitle
);
1781 self
::onArticleEdit( $this->mTitle
);
1784 wfProfileOut( __METHOD__
);
1788 * Edit an article without doing all that other stuff
1789 * The article must already exist; link tables etc
1790 * are not updated, caches are not flushed.
1792 * @param $text String: text submitted
1793 * @param $user User The relevant user
1794 * @param $comment String: comment submitted
1795 * @param $minor Boolean: whereas it's a minor modification
1797 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1798 wfProfileIn( __METHOD__
);
1800 $dbw = wfGetDB( DB_MASTER
);
1801 $revision = new Revision( array(
1802 'page' => $this->getId(),
1804 'comment' => $comment,
1805 'minor_edit' => $minor ?
1 : 0,
1807 $revision->insertOn( $dbw );
1808 $this->updateRevisionOn( $dbw, $revision );
1810 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1812 wfProfileOut( __METHOD__
);
1816 * Update the article's restriction field, and leave a log entry.
1817 * This works for protection both existing and non-existing pages.
1819 * @param $limit Array: set of restriction keys
1820 * @param $reason String
1821 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1822 * @param $expiry Array: per restriction type expiration
1823 * @param $user User The user updating the restrictions
1826 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1829 if ( wfReadOnly() ) {
1830 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1833 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1835 $id = $this->mTitle
->getArticleID();
1841 // Take this opportunity to purge out expired restrictions
1842 Title
::purgeExpiredRestrictions();
1844 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1845 # we expect a single selection, but the schema allows otherwise.
1846 $isProtected = false;
1850 $dbw = wfGetDB( DB_MASTER
);
1852 foreach ( $restrictionTypes as $action ) {
1853 if ( !isset( $expiry[$action] ) ) {
1854 $expiry[$action] = $dbw->getInfinity();
1856 if ( !isset( $limit[$action] ) ) {
1857 $limit[$action] = '';
1858 } elseif ( $limit[$action] != '' ) {
1862 # Get current restrictions on $action
1863 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1864 if ( $current != '' ) {
1865 $isProtected = true;
1868 if ( $limit[$action] != $current ) {
1870 } elseif ( $limit[$action] != '' ) {
1871 # Only check expiry change if the action is actually being
1872 # protected, since expiry does nothing on an not-protected
1874 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1880 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1884 # If nothing's changed, do nothing
1886 return Status
::newGood();
1889 if ( !$protect ) { # No protection at all means unprotection
1890 $revCommentMsg = 'unprotectedarticle';
1891 $logAction = 'unprotect';
1892 } elseif ( $isProtected ) {
1893 $revCommentMsg = 'modifiedarticleprotection';
1894 $logAction = 'modify';
1896 $revCommentMsg = 'protectedarticle';
1897 $logAction = 'protect';
1900 $encodedExpiry = array();
1901 $protectDescription = '';
1902 foreach ( $limit as $action => $restrictions ) {
1903 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1904 if ( $restrictions != '' ) {
1905 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1906 if ( $encodedExpiry[$action] != 'infinity' ) {
1907 $protectDescription .= wfMsgForContent( 'protect-expiring',
1908 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1909 $wgContLang->date( $expiry[$action], false, false ) ,
1910 $wgContLang->time( $expiry[$action], false, false ) );
1912 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1915 $protectDescription .= ') ';
1918 $protectDescription = trim( $protectDescription );
1920 if ( $id ) { # Protection of existing page
1921 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1922 return Status
::newGood();
1925 # Only restrictions with the 'protect' right can cascade...
1926 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1927 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1929 # The schema allows multiple restrictions
1930 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1934 # Update restrictions table
1935 foreach ( $limit as $action => $restrictions ) {
1936 if ( $restrictions != '' ) {
1937 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1938 array( 'pr_page' => $id,
1939 'pr_type' => $action,
1940 'pr_level' => $restrictions,
1941 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1942 'pr_expiry' => $encodedExpiry[$action]
1947 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1948 'pr_type' => $action ), __METHOD__
);
1952 # Prepare a null revision to be added to the history
1953 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1955 $editComment .= ": $reason";
1957 if ( $protectDescription ) {
1958 $editComment .= " ($protectDescription)";
1961 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1964 # Insert a null revision
1965 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1966 $nullRevId = $nullRevision->insertOn( $dbw );
1968 $latest = $this->getLatest();
1969 # Update page record
1970 $dbw->update( 'page',
1972 'page_touched' => $dbw->timestamp(),
1973 'page_restrictions' => '',
1974 'page_latest' => $nullRevId
1975 ), array( /* WHERE */
1980 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1981 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1982 } else { # Protection of non-existing page (also known as "title protection")
1983 # Cascade protection is meaningless in this case
1986 if ( $limit['create'] != '' ) {
1987 $dbw->replace( 'protected_titles',
1988 array( array( 'pt_namespace', 'pt_title' ) ),
1990 'pt_namespace' => $this->mTitle
->getNamespace(),
1991 'pt_title' => $this->mTitle
->getDBkey(),
1992 'pt_create_perm' => $limit['create'],
1993 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1994 'pt_expiry' => $encodedExpiry['create'],
1995 'pt_user' => $user->getId(),
1996 'pt_reason' => $reason,
2000 $dbw->delete( 'protected_titles',
2002 'pt_namespace' => $this->mTitle
->getNamespace(),
2003 'pt_title' => $this->mTitle
->getDBkey()
2009 $this->mTitle
->flushRestrictions();
2011 if ( $logAction == 'unprotect' ) {
2012 $logParams = array();
2014 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2017 # Update the protection log
2018 $log = new LogPage( 'protect' );
2019 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2021 return Status
::newGood();
2025 * Take an array of page restrictions and flatten it to a string
2026 * suitable for insertion into the page_restrictions field.
2027 * @param $limit Array
2030 protected static function flattenRestrictions( $limit ) {
2031 if ( !is_array( $limit ) ) {
2032 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2038 foreach ( $limit as $action => $restrictions ) {
2039 if ( $restrictions != '' ) {
2040 $bits[] = "$action=$restrictions";
2044 return implode( ':', $bits );
2048 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2049 * Deletes the article with database consistency, writes logs, purges caches
2051 * @param $reason string delete reason for deletion log
2052 * @param $suppress int bitfield
2053 * Revision::DELETED_TEXT
2054 * Revision::DELETED_COMMENT
2055 * Revision::DELETED_USER
2056 * Revision::DELETED_RESTRICTED
2057 * @param $id int article ID
2058 * @param $commit boolean defaults to true, triggers transaction end
2059 * @param &$error Array of errors to append to
2060 * @param $user User The deleting user
2061 * @return boolean true if successful
2063 public function doDeleteArticle(
2064 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2066 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2067 == WikiPage
::DELETE_SUCCESS
;
2071 * Back-end article deletion
2072 * Deletes the article with database consistency, writes logs, purges caches
2074 * @param $reason string delete reason for deletion log
2075 * @param $suppress int bitfield
2076 * Revision::DELETED_TEXT
2077 * Revision::DELETED_COMMENT
2078 * Revision::DELETED_USER
2079 * Revision::DELETED_RESTRICTED
2080 * @param $id int article ID
2081 * @param $commit boolean defaults to true, triggers transaction end
2082 * @param &$error Array of errors to append to
2083 * @param $user User The deleting user
2084 * @return int: One of WikiPage::DELETE_* constants
2086 public function doDeleteArticleReal(
2087 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2091 wfDebug( __METHOD__
. "\n" );
2093 if ( $this->mTitle
->getDBkey() === '' ) {
2094 return WikiPage
::DELETE_NO_PAGE
;
2097 $user = is_null( $user ) ?
$wgUser : $user;
2098 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2099 return WikiPage
::DELETE_HOOK_ABORTED
;
2103 $this->loadPageData( 'forupdate' );
2104 $id = $this->getID();
2106 return WikiPage
::DELETE_NO_PAGE
;
2110 // Bitfields to further suppress the content
2113 // This should be 15...
2114 $bitfield |
= Revision
::DELETED_TEXT
;
2115 $bitfield |
= Revision
::DELETED_COMMENT
;
2116 $bitfield |
= Revision
::DELETED_USER
;
2117 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2119 $bitfield = 'rev_deleted';
2122 $dbw = wfGetDB( DB_MASTER
);
2123 $dbw->begin( __METHOD__
);
2124 // For now, shunt the revision data into the archive table.
2125 // Text is *not* removed from the text table; bulk storage
2126 // is left intact to avoid breaking block-compression or
2127 // immutable storage schemes.
2129 // For backwards compatibility, note that some older archive
2130 // table entries will have ar_text and ar_flags fields still.
2132 // In the future, we may keep revisions and mark them with
2133 // the rev_deleted field, which is reserved for this purpose.
2134 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2136 'ar_namespace' => 'page_namespace',
2137 'ar_title' => 'page_title',
2138 'ar_comment' => 'rev_comment',
2139 'ar_user' => 'rev_user',
2140 'ar_user_text' => 'rev_user_text',
2141 'ar_timestamp' => 'rev_timestamp',
2142 'ar_minor_edit' => 'rev_minor_edit',
2143 'ar_rev_id' => 'rev_id',
2144 'ar_parent_id' => 'rev_parent_id',
2145 'ar_text_id' => 'rev_text_id',
2146 'ar_text' => '\'\'', // Be explicit to appease
2147 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2148 'ar_len' => 'rev_len',
2149 'ar_page_id' => 'page_id',
2150 'ar_deleted' => $bitfield,
2151 'ar_sha1' => 'rev_sha1'
2154 'page_id = rev_page'
2158 # Now that it's safely backed up, delete it
2159 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2160 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2163 $dbw->rollback( __METHOD__
);
2164 return WikiPage
::DELETE_NO_REVISIONS
;
2167 $this->doDeleteUpdates( $id );
2169 # Log the deletion, if the page was suppressed, log it at Oversight instead
2170 $logtype = $suppress ?
'suppress' : 'delete';
2172 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2173 $logEntry->setPerformer( $user );
2174 $logEntry->setTarget( $this->mTitle
);
2175 $logEntry->setComment( $reason );
2176 $logid = $logEntry->insert();
2177 $logEntry->publish( $logid );
2180 $dbw->commit( __METHOD__
);
2183 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2184 return WikiPage
::DELETE_SUCCESS
;
2188 * Do some database updates after deletion
2190 * @param $id Int: page_id value of the page being deleted
2192 public function doDeleteUpdates( $id ) {
2193 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2195 $dbw = wfGetDB( DB_MASTER
);
2197 # Delete restrictions for it
2198 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2200 # Fix category table counts
2202 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2204 foreach ( $res as $row ) {
2205 $cats [] = $row->cl_to
;
2208 $this->updateCategoryCounts( array(), $cats );
2210 # If using cascading deletes, we can skip some explicit deletes
2211 if ( !$dbw->cascadingDeletes() ) {
2212 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2214 # Delete outgoing links
2215 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2216 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2217 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2218 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2219 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2220 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2221 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2222 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2223 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2226 # If using cleanup triggers, we can skip some manual deletes
2227 if ( !$dbw->cleanupTriggers() ) {
2228 # Clean up recentchanges entries...
2229 $dbw->delete( 'recentchanges',
2230 array( 'rc_type != ' . RC_LOG
,
2231 'rc_namespace' => $this->mTitle
->getNamespace(),
2232 'rc_title' => $this->mTitle
->getDBkey() ),
2234 $dbw->delete( 'recentchanges',
2235 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2240 self
::onArticleDelete( $this->mTitle
);
2245 # Clear the cached article id so the interface doesn't act like we exist
2246 $this->mTitle
->resetArticleID( 0 );
2250 * Roll back the most recent consecutive set of edits to a page
2251 * from the same user; fails if there are no eligible edits to
2252 * roll back to, e.g. user is the sole contributor. This function
2253 * performs permissions checks on $user, then calls commitRollback()
2254 * to do the dirty work
2256 * @todo: seperate the business/permission stuff out from backend code
2258 * @param $fromP String: Name of the user whose edits to rollback.
2259 * @param $summary String: Custom summary. Set to default summary if empty.
2260 * @param $token String: Rollback token.
2261 * @param $bot Boolean: If true, mark all reverted edits as bot.
2263 * @param $resultDetails Array: contains result-specific array of additional values
2264 * 'alreadyrolled' : 'current' (rev)
2265 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2267 * @param $user User The user performing the rollback
2268 * @return array of errors, each error formatted as
2269 * array(messagekey, param1, param2, ...).
2270 * On success, the array is empty. This array can also be passed to
2271 * OutputPage::showPermissionsErrorPage().
2273 public function doRollback(
2274 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2276 $resultDetails = null;
2279 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2280 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2281 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2283 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2284 $errors[] = array( 'sessionfailure' );
2287 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2288 $errors[] = array( 'actionthrottledtext' );
2291 # If there were errors, bail out now
2292 if ( !empty( $errors ) ) {
2296 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2300 * Backend implementation of doRollback(), please refer there for parameter
2301 * and return value documentation
2303 * NOTE: This function does NOT check ANY permissions, it just commits the
2304 * rollback to the DB. Therefore, you should only call this function direct-
2305 * ly if you want to use custom permissions checks. If you don't, use
2306 * doRollback() instead.
2307 * @param $fromP String: Name of the user whose edits to rollback.
2308 * @param $summary String: Custom summary. Set to default summary if empty.
2309 * @param $bot Boolean: If true, mark all reverted edits as bot.
2311 * @param $resultDetails Array: contains result-specific array of additional values
2312 * @param $guser User The user performing the rollback
2315 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2316 global $wgUseRCPatrol, $wgContLang;
2318 $dbw = wfGetDB( DB_MASTER
);
2320 if ( wfReadOnly() ) {
2321 return array( array( 'readonlytext' ) );
2324 # Get the last editor
2325 $current = $this->getRevision();
2326 if ( is_null( $current ) ) {
2327 # Something wrong... no page?
2328 return array( array( 'notanarticle' ) );
2331 $from = str_replace( '_', ' ', $fromP );
2332 # User name given should match up with the top revision.
2333 # If the user was deleted then $from should be empty.
2334 if ( $from != $current->getUserText() ) {
2335 $resultDetails = array( 'current' => $current );
2336 return array( array( 'alreadyrolled',
2337 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2338 htmlspecialchars( $fromP ),
2339 htmlspecialchars( $current->getUserText() )
2343 # Get the last edit not by this guy...
2344 # Note: these may not be public values
2345 $user = intval( $current->getRawUser() );
2346 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2347 $s = $dbw->selectRow( 'revision',
2348 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2349 array( 'rev_page' => $current->getPage(),
2350 "rev_user != {$user} OR rev_user_text != {$user_text}"
2352 array( 'USE INDEX' => 'page_timestamp',
2353 'ORDER BY' => 'rev_timestamp DESC' )
2355 if ( $s === false ) {
2356 # No one else ever edited this page
2357 return array( array( 'cantrollback' ) );
2358 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2359 # Only admins can see this text
2360 return array( array( 'notvisiblerev' ) );
2364 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2365 # Mark all reverted edits as bot
2369 if ( $wgUseRCPatrol ) {
2370 # Mark all reverted edits as patrolled
2371 $set['rc_patrolled'] = 1;
2374 if ( count( $set ) ) {
2375 $dbw->update( 'recentchanges', $set,
2377 'rc_cur_id' => $current->getPage(),
2378 'rc_user_text' => $current->getUserText(),
2379 "rc_timestamp > '{$s->rev_timestamp}'",
2384 # Generate the edit summary if necessary
2385 $target = Revision
::newFromId( $s->rev_id
);
2386 if ( empty( $summary ) ) {
2387 if ( $from == '' ) { // no public user name
2388 $summary = wfMsgForContent( 'revertpage-nouser' );
2390 $summary = wfMsgForContent( 'revertpage' );
2394 # Allow the custom summary to use the same args as the default message
2396 $target->getUserText(), $from, $s->rev_id
,
2397 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2398 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2400 $summary = wfMsgReplaceArgs( $summary, $args );
2403 $flags = EDIT_UPDATE
;
2405 if ( $guser->isAllowed( 'minoredit' ) ) {
2406 $flags |
= EDIT_MINOR
;
2409 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2410 $flags |
= EDIT_FORCE_BOT
;
2413 # Actually store the edit
2414 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2415 if ( !empty( $status->value
['revision'] ) ) {
2416 $revId = $status->value
['revision']->getId();
2421 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2423 $resultDetails = array(
2424 'summary' => $summary,
2425 'current' => $current,
2426 'target' => $target,
2434 * The onArticle*() functions are supposed to be a kind of hooks
2435 * which should be called whenever any of the specified actions
2438 * This is a good place to put code to clear caches, for instance.
2440 * This is called on page move and undelete, as well as edit
2442 * @param $title Title object
2444 public static function onArticleCreate( $title ) {
2445 # Update existence markers on article/talk tabs...
2446 if ( $title->isTalkPage() ) {
2447 $other = $title->getSubjectPage();
2449 $other = $title->getTalkPage();
2452 $other->invalidateCache();
2453 $other->purgeSquid();
2455 $title->touchLinks();
2456 $title->purgeSquid();
2457 $title->deleteTitleProtection();
2461 * Clears caches when article is deleted
2463 * @param $title Title
2465 public static function onArticleDelete( $title ) {
2466 # Update existence markers on article/talk tabs...
2467 if ( $title->isTalkPage() ) {
2468 $other = $title->getSubjectPage();
2470 $other = $title->getTalkPage();
2473 $other->invalidateCache();
2474 $other->purgeSquid();
2476 $title->touchLinks();
2477 $title->purgeSquid();
2480 HTMLFileCache
::clearFileCache( $title );
2483 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2484 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2488 if ( $title->getNamespace() == NS_FILE
) {
2489 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2490 $update->doUpdate();
2494 if ( $title->getNamespace() == NS_USER_TALK
) {
2495 $user = User
::newFromName( $title->getText(), false );
2497 $user->setNewtalk( false );
2502 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2506 * Purge caches on page update etc
2508 * @param $title Title object
2509 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2511 public static function onArticleEdit( $title ) {
2512 // Invalidate caches of articles which include this page
2513 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2516 // Invalidate the caches of all pages which redirect here
2517 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2519 # Purge squid for this page only
2520 $title->purgeSquid();
2522 # Clear file cache for this page only
2523 HTMLFileCache
::clearFileCache( $title );
2529 * Returns a list of hidden categories this page is a member of.
2530 * Uses the page_props and categorylinks tables.
2532 * @return Array of Title objects
2534 public function getHiddenCategories() {
2536 $id = $this->mTitle
->getArticleID();
2542 $dbr = wfGetDB( DB_SLAVE
);
2543 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2545 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2546 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2549 if ( $res !== false ) {
2550 foreach ( $res as $row ) {
2551 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2559 * Return an applicable autosummary if one exists for the given edit.
2560 * @param $oldtext String: the previous text of the page.
2561 * @param $newtext String: The submitted text of the page.
2562 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2563 * @return string An appropriate autosummary, or an empty string.
2565 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2568 # Decide what kind of autosummary is needed.
2570 # Redirect autosummaries
2571 $ot = Title
::newFromRedirect( $oldtext );
2572 $rt = Title
::newFromRedirect( $newtext );
2574 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2575 $truncatedtext = $wgContLang->truncate(
2576 str_replace( "\n", ' ', $newtext ),
2578 - strlen( wfMsgForContent( 'autoredircomment' ) )
2579 - strlen( $rt->getFullText() )
2581 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2584 # New page autosummaries
2585 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2586 # If they're making a new article, give its text, truncated, in the summary.
2588 $truncatedtext = $wgContLang->truncate(
2589 str_replace( "\n", ' ', $newtext ),
2590 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2592 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2595 # Blanking autosummaries
2596 if ( $oldtext != '' && $newtext == '' ) {
2597 return wfMsgForContent( 'autosumm-blank' );
2598 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2599 # Removing more than 90% of the article
2601 $truncatedtext = $wgContLang->truncate(
2603 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2605 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2608 # If we reach this point, there's no applicable autosummary for our case, so our
2609 # autosummary is empty.
2614 * Auto-generates a deletion reason
2616 * @param &$hasHistory Boolean: whether the page has a history
2617 * @return mixed String containing deletion reason or empty string, or boolean false
2618 * if no revision occurred
2620 public function getAutoDeleteReason( &$hasHistory ) {
2623 // Get the last revision
2624 $rev = $this->getRevision();
2626 if ( is_null( $rev ) ) {
2630 // Get the article's contents
2631 $contents = $rev->getText();
2634 // If the page is blank, use the text from the previous revision,
2635 // which can only be blank if there's a move/import/protect dummy revision involved
2636 if ( $contents == '' ) {
2637 $prev = $rev->getPrevious();
2640 $contents = $prev->getText();
2645 $dbw = wfGetDB( DB_MASTER
);
2647 // Find out if there was only one contributor
2648 // Only scan the last 20 revisions
2649 $res = $dbw->select( 'revision', 'rev_user_text',
2650 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2652 array( 'LIMIT' => 20 )
2655 if ( $res === false ) {
2656 // This page has no revisions, which is very weird
2660 $hasHistory = ( $res->numRows() > 1 );
2661 $row = $dbw->fetchObject( $res );
2663 if ( $row ) { // $row is false if the only contributor is hidden
2664 $onlyAuthor = $row->rev_user_text
;
2665 // Try to find a second contributor
2666 foreach ( $res as $row ) {
2667 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2668 $onlyAuthor = false;
2673 $onlyAuthor = false;
2676 // Generate the summary with a '$1' placeholder
2678 // The current revision is blank and the one before is also
2679 // blank. It's just not our lucky day
2680 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2682 if ( $onlyAuthor ) {
2683 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2685 $reason = wfMsgForContent( 'excontent', '$1' );
2689 if ( $reason == '-' ) {
2690 // Allow these UI messages to be blanked out cleanly
2694 // Replace newlines with spaces to prevent uglyness
2695 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2696 // Calculate the maximum amount of chars to get
2697 // Max content length = max comment length - length of the comment (excl. $1)
2698 $maxLength = 255 - ( strlen( $reason ) - 2 );
2699 $contents = $wgContLang->truncate( $contents, $maxLength );
2700 // Remove possible unfinished links
2701 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2702 // Now replace the '$1' placeholder
2703 $reason = str_replace( '$1', $contents, $reason );
2709 * Update all the appropriate counts in the category table, given that
2710 * we've added the categories $added and deleted the categories $deleted.
2712 * @param $added array The names of categories that were added
2713 * @param $deleted array The names of categories that were deleted
2715 public function updateCategoryCounts( $added, $deleted ) {
2716 $ns = $this->mTitle
->getNamespace();
2717 $dbw = wfGetDB( DB_MASTER
);
2719 # First make sure the rows exist. If one of the "deleted" ones didn't
2720 # exist, we might legitimately not create it, but it's simpler to just
2721 # create it and then give it a negative value, since the value is bogus
2724 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2725 $insertCats = array_merge( $added, $deleted );
2726 if ( !$insertCats ) {
2727 # Okay, nothing to do
2731 $insertRows = array();
2733 foreach ( $insertCats as $cat ) {
2734 $insertRows[] = array(
2735 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2739 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2741 $addFields = array( 'cat_pages = cat_pages + 1' );
2742 $removeFields = array( 'cat_pages = cat_pages - 1' );
2744 if ( $ns == NS_CATEGORY
) {
2745 $addFields[] = 'cat_subcats = cat_subcats + 1';
2746 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2747 } elseif ( $ns == NS_FILE
) {
2748 $addFields[] = 'cat_files = cat_files + 1';
2749 $removeFields[] = 'cat_files = cat_files - 1';
2756 array( 'cat_title' => $added ),
2765 array( 'cat_title' => $deleted ),
2772 * Updates cascading protections
2774 * @param $parserOutput ParserOutput object for the current version
2776 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2777 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2781 // templatelinks table may have become out of sync,
2782 // especially if using variable-based transclusions.
2783 // For paranoia, check if things have changed and if
2784 // so apply updates to the database. This will ensure
2785 // that cascaded protections apply as soon as the changes
2788 # Get templates from templatelinks
2789 $id = $this->mTitle
->getArticleID();
2791 $tlTemplates = array();
2793 $dbr = wfGetDB( DB_SLAVE
);
2794 $res = $dbr->select( array( 'templatelinks' ),
2795 array( 'tl_namespace', 'tl_title' ),
2796 array( 'tl_from' => $id ),
2800 foreach ( $res as $row ) {
2801 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2804 # Get templates from parser output.
2805 $poTemplates = array();
2806 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2807 foreach ( $templates as $dbk => $id ) {
2808 $poTemplates["$ns:$dbk"] = true;
2813 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2815 if ( count( $templates_diff ) > 0 ) {
2816 # Whee, link updates time.
2817 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2823 * Return a list of templates used by this article.
2824 * Uses the templatelinks table
2826 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2827 * @return Array of Title objects
2829 public function getUsedTemplates() {
2830 return $this->mTitle
->getTemplateLinksFrom();
2834 * Perform article updates on a special page creation.
2836 * @param $rev Revision object
2838 * @todo This is a shitty interface function. Kill it and replace the
2839 * other shitty functions like doEditUpdates and such so it's not needed
2841 * @deprecated since 1.18, use doEditUpdates()
2843 public function createUpdates( $rev ) {
2844 wfDeprecated( __METHOD__
, '1.18' );
2846 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2850 * This function is called right before saving the wikitext,
2851 * so we can do things like signatures and links-in-context.
2853 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2854 * @param $text String article contents
2855 * @param $user User object: user doing the edit
2856 * @param $popts ParserOptions object: parser options, default options for
2857 * the user loaded if null given
2858 * @return string article contents with altered wikitext markup (signatures
2859 * converted, {{subst:}}, templates, etc.)
2861 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2862 global $wgParser, $wgUser;
2864 wfDeprecated( __METHOD__
, '1.19' );
2866 $user = is_null( $user ) ?
$wgUser : $user;
2868 if ( $popts === null ) {
2869 $popts = ParserOptions
::newFromUser( $user );
2872 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2876 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2878 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2881 public function isBigDeletion() {
2882 wfDeprecated( __METHOD__
, '1.19' );
2883 return $this->mTitle
->isBigDeletion();
2887 * Get the approximate revision count of this page.
2889 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2892 public function estimateRevisionCount() {
2893 wfDeprecated( __METHOD__
, '1.19' );
2894 return $this->mTitle
->estimateRevisionCount();
2898 * Update the article's restriction field, and leave a log entry.
2900 * @deprecated since 1.19
2901 * @param $limit Array: set of restriction keys
2902 * @param $reason String
2903 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2904 * @param $expiry Array: per restriction type expiration
2905 * @param $user User The user updating the restrictions
2906 * @return bool true on success
2908 public function updateRestrictions(
2909 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2913 $user = is_null( $user ) ?
$wgUser : $user;
2915 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2919 * @deprecated since 1.18
2921 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2922 wfDeprecated( __METHOD__
, '1.18' );
2924 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2928 * @deprecated since 1.18
2930 public function viewUpdates() {
2931 wfDeprecated( __METHOD__
, '1.18' );
2933 return $this->doViewUpdates( $wgUser );
2937 * @deprecated since 1.18
2940 public function useParserCache( $oldid ) {
2941 wfDeprecated( __METHOD__
, '1.18' );
2943 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2947 class PoolWorkArticleView
extends PoolCounterWork
{
2965 * @var ParserOptions
2967 private $parserOptions;
2975 * @var ParserOutput|bool
2977 private $parserOutput = false;
2982 private $isDirty = false;
2987 private $error = false;
2993 * @param $revid Integer: ID of the revision being parsed
2994 * @param $useParserCache Boolean: whether to use the parser cache
2995 * @param $parserOptions parserOptions to use for the parse operation
2996 * @param $text String: text to parse or null to load it
2998 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2999 $this->page
= $page;
3000 $this->revid
= $revid;
3001 $this->cacheable
= $useParserCache;
3002 $this->parserOptions
= $parserOptions;
3003 $this->text
= $text;
3004 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3005 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3009 * Get the ParserOutput from this object, or false in case of failure
3011 * @return ParserOutput
3013 public function getParserOutput() {
3014 return $this->parserOutput
;
3018 * Get whether the ParserOutput is a dirty one (i.e. expired)
3022 public function getIsDirty() {
3023 return $this->isDirty
;
3027 * Get a Status object in case of error or false otherwise
3029 * @return Status|bool
3031 public function getError() {
3032 return $this->error
;
3039 global $wgParser, $wgUseFileCache;
3041 $isCurrent = $this->revid
=== $this->page
->getLatest();
3043 if ( $this->text
!== null ) {
3044 $text = $this->text
;
3045 } elseif ( $isCurrent ) {
3046 $text = $this->page
->getRawText();
3048 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3049 if ( $rev === null ) {
3052 $text = $rev->getText();
3055 $time = - microtime( true );
3056 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
3057 $this->parserOptions
, true, true, $this->revid
);
3058 $time +
= microtime( true );
3062 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3063 $this->page
->getTitle()->getPrefixedDBkey() ) );
3066 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3067 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3070 // Make sure file cache is not used on uncacheable content.
3071 // Output that has magic words in it can still use the parser cache
3072 // (if enabled), though it will generally expire sooner.
3073 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3074 $wgUseFileCache = false;
3078 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3087 function getCachedWork() {
3088 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3090 if ( $this->parserOutput
=== false ) {
3091 wfDebug( __METHOD__
. ": parser cache miss\n" );
3094 wfDebug( __METHOD__
. ": parser cache hit\n" );
3102 function fallback() {
3103 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3105 if ( $this->parserOutput
=== false ) {
3106 wfDebugLog( 'dirty', "dirty missing\n" );
3107 wfDebug( __METHOD__
. ": no dirty cache\n" );
3110 wfDebug( __METHOD__
. ": sending dirty output\n" );
3111 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3112 $this->isDirty
= true;
3118 * @param $status Status
3121 function error( $status ) {
3122 $this->error
= $status;