3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
8 * Class representing a MediaWiki article and history.
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
13 * @internal documentation reviewed 15 Mar 2010
15 class WikiPage
extends Page
{
16 // doDeleteArticleReal() return values. Values less than zero indicate fatal errors,
17 // values greater than zero indicate that there were problems not resulting in page
21 * Delete operation aborted by hook
23 const DELETE_HOOK_ABORTED
= -1;
28 const DELETE_SUCCESS
= 0;
33 const DELETE_NO_PAGE
= 1;
36 * No revisions found to delete
38 const DELETE_NO_REVISIONS
= 2;
40 // Constants for $mDataLoadedFrom and related
43 * Data has not been loaded yet (or the object was cleared)
45 const DATA_NOT_LOADED
= 0;
48 * Data has been loaded from a slave database
50 const DATA_FROM_SLAVE
= 1;
53 * Data has been loaded from the master database
55 const DATA_FROM_MASTER
= 2;
58 * Data has been loaded from the master database using FOR UPDATE
60 const DATA_FOR_UPDATE
= 3;
65 public $mTitle = null;
70 public $mDataLoaded = false; // !< Boolean
71 public $mIsRedirect = false; // !< Boolean
72 public $mLatest = false; // !< Integer (false means "not loaded")
73 public $mPreparedEdit = false; // !< Array
77 * @var int; one of the DATA_* constants
79 protected $mDataLoadedFrom = self
::DATA_NOT_LOADED
;
84 protected $mRedirectTarget = null;
89 protected $mLastRevision = null;
92 * @var string; timestamp of the current revision or empty string if not loaded
94 protected $mTimestamp = '';
99 protected $mTouched = '19700101000000';
104 protected $mCounter = null;
107 * Constructor and clear the article
108 * @param $title Title Reference to a Title object.
110 public function __construct( Title
$title ) {
111 $this->mTitle
= $title;
115 * Create a WikiPage object of the appropriate class for the given title.
117 * @param $title Title
118 * @return WikiPage object of the appropriate type
120 public static function factory( Title
$title ) {
121 $ns = $title->getNamespace();
123 if ( $ns == NS_MEDIA
) {
124 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
125 } elseif ( $ns < 0 ) {
126 throw new MWException( "Invalid or virtual namespace $ns given." );
131 $page = new WikiFilePage( $title );
134 $page = new WikiCategoryPage( $title );
137 $page = new WikiPage( $title );
144 * Constructor from a page id
146 * @param $id Int article ID to load
147 * @param $from string|int one of the following values:
148 * - "fromdb" or self::DATA_FROM_SLAVE to select from a slave database
149 * - "fromdbmaster" or self::DATA_FROM_MASTER to select from the master database
151 * @return WikiPage|null
153 public static function newFromID( $id, $from = 'fromdb' ) {
154 $from = self
::convertSelectType( $from );
155 $db = wfGetDB( $from === self
::DATA_FROM_MASTER ? DB_MASTER
: DB_SLAVE
);
156 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
160 return self
::newFromRow( $row, $from );
164 * Constructor from a database row
167 * @param $row object: database row containing at least fields returned
169 * @param $from string|int: source of $data:
170 * - "fromdb" or self::DATA_FROM_SLAVE: from a slave DB
171 * - "fromdbmaster" or self::DATA_FROM_MASTER: from the master DB
172 * - "forupdate" or self::DATA_FOR_UPDATE: from the master DB using SELECT FOR UPDATE
175 public static function newFromRow( $row, $from = 'fromdb' ) {
176 $page = self
::factory( Title
::newFromRow( $row ) );
177 $page->loadFromRow( $row, $from );
182 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to DATA_* constants.
184 * @param $type object|string|int
187 private static function convertSelectType( $type ) {
190 return self
::DATA_FROM_SLAVE
;
192 return self
::DATA_FROM_MASTER
;
194 return self
::DATA_FOR_UPDATE
;
196 // It may already be an integer or whatever else
202 * Returns overrides for action handlers.
203 * Classes listed here will be used instead of the default one when
204 * (and only when) $wgActions[$action] === true. This allows subclasses
205 * to override the default behavior.
207 * @todo: move this UI stuff somewhere else
211 public function getActionOverrides() {
216 * Get the title object of the article
217 * @return Title object of this page
219 public function getTitle() {
220 return $this->mTitle
;
226 public function clear() {
227 $this->mDataLoaded
= false;
228 $this->mDataLoadedFrom
= self
::DATA_NOT_LOADED
;
230 $this->mCounter
= null;
231 $this->mRedirectTarget
= null; # Title object if set
232 $this->mLastRevision
= null; # Latest revision
233 $this->mTouched
= '19700101000000';
234 $this->mTimestamp
= '';
235 $this->mIsRedirect
= false;
236 $this->mLatest
= false;
237 $this->mPreparedEdit
= false;
241 * Return the list of revision fields that should be selected to create
246 public static function selectFields() {
263 * Fetch a page record with the given conditions
264 * @param $dbr DatabaseBase object
265 * @param $conditions Array
266 * @param $options Array
267 * @return mixed Database result resource, or false on failure
269 protected function pageData( $dbr, $conditions, $options = array() ) {
270 $fields = self
::selectFields();
272 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
274 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
276 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
282 * Fetch a page record matching the Title object's namespace and title
283 * using a sanitized title string
285 * @param $dbr DatabaseBase object
286 * @param $title Title object
287 * @param $options Array
288 * @return mixed Database result resource, or false on failure
290 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
291 return $this->pageData( $dbr, array(
292 'page_namespace' => $title->getNamespace(),
293 'page_title' => $title->getDBkey() ), $options );
297 * Fetch a page record matching the requested ID
299 * @param $dbr DatabaseBase
301 * @param $options Array
302 * @return mixed Database result resource, or false on failure
304 public function pageDataFromId( $dbr, $id, $options = array() ) {
305 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
309 * Set the general counter, title etc data loaded from
312 * @param $from object|string|int One of the following:
313 * - A DB query result object
314 * - "fromdb" or self::DATA_FROM_SLAVE to get from a slave DB
315 * - "fromdbmaster" or self::DATA_FROM_MASTER to get from the master DB
316 * - "forupdate" or self::DATA_FOR_UPDATE to get from the master DB using SELECT FOR UPDATE
320 public function loadPageData( $from = 'fromdb' ) {
321 $from = self
::convertSelectType( $from );
322 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
323 // We already have the data from the correct location, no need to load it twice.
327 if ( $from === self
::DATA_FOR_UPDATE
) {
328 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
329 } elseif ( $from === self
::DATA_FROM_MASTER
) {
330 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
331 } elseif ( $from === self
::DATA_FROM_SLAVE
) {
332 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
333 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
334 # Note that DB also stores the master position in the session and checks it.
335 $touched = $this->getCachedLastEditTime();
336 if ( $touched ) { // key set
337 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
338 $from = self
::DATA_FROM_MASTER
;
339 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
343 // No idea from where the caller got this data, assume slave database.
345 $from = self
::DATA_FROM_SLAVE
;
348 $this->loadFromRow( $data, $from );
352 * Load the object from a database row
355 * @param $data object: database row containing at least fields returned
357 * @param $from string|int One of the following:
358 * - "fromdb" or self::DATA_FROM_SLAVE if the data comes from a slave DB
359 * - "fromdbmaster" or self::DATA_FROM_MASTER if the data comes from the master DB
360 * - "forupdate" or self::DATA_FOR_UPDATE if the data comes from from
361 * the master DB using SELECT FOR UPDATE
363 public function loadFromRow( $data, $from ) {
364 $lc = LinkCache
::singleton();
367 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
369 $this->mTitle
->loadFromRow( $data );
371 # Old-fashioned restrictions
372 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
374 $this->mCounter
= intval( $data->page_counter
);
375 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
376 $this->mIsRedirect
= intval( $data->page_is_redirect
);
377 $this->mLatest
= intval( $data->page_latest
);
379 $lc->addBadLinkObj( $this->mTitle
);
381 $this->mTitle
->loadFromRow( false );
384 $this->mDataLoaded
= true;
385 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
389 * @return int Page ID
391 public function getId() {
392 return $this->mTitle
->getArticleID();
396 * @return bool Whether or not the page exists in the database
398 public function exists() {
399 return $this->mTitle
->exists();
403 * Check if this page is something we're going to be showing
404 * some sort of sensible content for. If we return false, page
405 * views (plain action=view) will return an HTTP 404 response,
406 * so spiders and robots can know they're following a bad link.
410 public function hasViewableContent() {
411 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
415 * @return int The view count for the page
417 public function getCount() {
418 if ( !$this->mDataLoaded
) {
419 $this->loadPageData();
422 return $this->mCounter
;
426 * Tests if the article text represents a redirect
428 * @param $text mixed string containing article contents, or boolean
431 public function isRedirect( $text = false ) {
432 if ( $text === false ) {
433 if ( !$this->mDataLoaded
) {
434 $this->loadPageData();
437 return (bool)$this->mIsRedirect
;
439 return Title
::newFromRedirect( $text ) !== null;
444 * Loads page_touched and returns a value indicating if it should be used
445 * @return boolean true if not a redirect
447 public function checkTouched() {
448 if ( !$this->mDataLoaded
) {
449 $this->loadPageData();
451 return !$this->mIsRedirect
;
455 * Get the page_touched field
456 * @return string containing GMT timestamp
458 public function getTouched() {
459 if ( !$this->mDataLoaded
) {
460 $this->loadPageData();
462 return $this->mTouched
;
466 * Get the page_latest field
467 * @return integer rev_id of current revision
469 public function getLatest() {
470 if ( !$this->mDataLoaded
) {
471 $this->loadPageData();
473 return (int)$this->mLatest
;
477 * Loads everything except the text
478 * This isn't necessary for all uses, so it's only done if needed.
480 protected function loadLastEdit() {
481 if ( $this->mLastRevision
!== null ) {
482 return; // already loaded
485 $latest = $this->getLatest();
487 return; // page doesn't exist or is missing page_latest info
490 $revision = Revision
::newFromPageId( $this->getId(), $latest );
491 if ( $revision ) { // sanity
492 $this->setLastEdit( $revision );
497 * Set the latest revision
499 protected function setLastEdit( Revision
$revision ) {
500 $this->mLastRevision
= $revision;
501 $this->mTimestamp
= $revision->getTimestamp();
505 * Get the latest revision
506 * @return Revision|null
508 public function getRevision() {
509 $this->loadLastEdit();
510 if ( $this->mLastRevision
) {
511 return $this->mLastRevision
;
517 * Get the text of the current revision. No side-effects...
519 * @param $audience Integer: one of:
520 * Revision::FOR_PUBLIC to be displayed to all users
521 * Revision::FOR_THIS_USER to be displayed to $wgUser
522 * Revision::RAW get the text regardless of permissions
523 * @return String|bool The text of the current revision. False on failure
525 public function getText( $audience = Revision
::FOR_PUBLIC
) {
526 $this->loadLastEdit();
527 if ( $this->mLastRevision
) {
528 return $this->mLastRevision
->getText( $audience );
534 * Get the text of the current revision. No side-effects...
536 * @return String|bool The text of the current revision. False on failure
538 public function getRawText() {
539 $this->loadLastEdit();
540 if ( $this->mLastRevision
) {
541 return $this->mLastRevision
->getRawText();
547 * @return string MW timestamp of last article revision
549 public function getTimestamp() {
550 // Check if the field has been filled by WikiPage::setTimestamp()
551 if ( !$this->mTimestamp
) {
552 $this->loadLastEdit();
555 return wfTimestamp( TS_MW
, $this->mTimestamp
);
559 * Set the page timestamp (use only to avoid DB queries)
560 * @param $ts string MW timestamp of last article revision
563 public function setTimestamp( $ts ) {
564 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
568 * @param $audience Integer: one of:
569 * Revision::FOR_PUBLIC to be displayed to all users
570 * Revision::FOR_THIS_USER to be displayed to $wgUser
571 * Revision::RAW get the text regardless of permissions
572 * @return int user ID for the user that made the last article revision
574 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
575 $this->loadLastEdit();
576 if ( $this->mLastRevision
) {
577 return $this->mLastRevision
->getUser( $audience );
584 * @param $audience Integer: one of:
585 * Revision::FOR_PUBLIC to be displayed to all users
586 * Revision::FOR_THIS_USER to be displayed to $wgUser
587 * Revision::RAW get the text regardless of permissions
588 * @return string username of the user that made the last article revision
590 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
591 $this->loadLastEdit();
592 if ( $this->mLastRevision
) {
593 return $this->mLastRevision
->getUserText( $audience );
600 * @param $audience Integer: one of:
601 * Revision::FOR_PUBLIC to be displayed to all users
602 * Revision::FOR_THIS_USER to be displayed to $wgUser
603 * Revision::RAW get the text regardless of permissions
604 * @return string Comment stored for the last article revision
606 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
607 $this->loadLastEdit();
608 if ( $this->mLastRevision
) {
609 return $this->mLastRevision
->getComment( $audience );
616 * Returns true if last revision was marked as "minor edit"
618 * @return boolean Minor edit indicator for the last article revision.
620 public function getMinorEdit() {
621 $this->loadLastEdit();
622 if ( $this->mLastRevision
) {
623 return $this->mLastRevision
->isMinor();
630 * Get the cached timestamp for the last time the page changed.
631 * This is only used to help handle slave lag by comparing to page_touched.
632 * @return string MW timestamp
634 protected function getCachedLastEditTime() {
636 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
637 return $wgMemc->get( $key );
641 * Set the cached timestamp for the last time the page changed.
642 * This is only used to help handle slave lag by comparing to page_touched.
643 * @param $timestamp string
646 public function setCachedLastEditTime( $timestamp ) {
648 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
649 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
653 * Determine whether a page would be suitable for being counted as an
654 * article in the site_stats table based on the title & its content
656 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
657 * if false, the current database state will be used
660 public function isCountable( $editInfo = false ) {
661 global $wgArticleCountMethod;
663 if ( !$this->mTitle
->isContentPage() ) {
667 $text = $editInfo ?
$editInfo->pst
: false;
669 if ( $this->isRedirect( $text ) ) {
673 switch ( $wgArticleCountMethod ) {
677 if ( $text === false ) {
678 $text = $this->getRawText();
680 return strpos( $text, ',' ) !== false;
683 // ParserOutput::getLinks() is a 2D array of page links, so
684 // to be really correct we would need to recurse in the array
685 // but the main array should only have items in it if there are
687 return (bool)count( $editInfo->output
->getLinks() );
689 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
690 array( 'pl_from' => $this->getId() ), __METHOD__
);
696 * If this page is a redirect, get its target
698 * The target will be fetched from the redirect table if possible.
699 * If this page doesn't have an entry there, call insertRedirect()
700 * @return Title|mixed object, or null if this page is not a redirect
702 public function getRedirectTarget() {
703 if ( !$this->mTitle
->isRedirect() ) {
707 if ( $this->mRedirectTarget
!== null ) {
708 return $this->mRedirectTarget
;
711 # Query the redirect table
712 $dbr = wfGetDB( DB_SLAVE
);
713 $row = $dbr->selectRow( 'redirect',
714 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
715 array( 'rd_from' => $this->getId() ),
719 // rd_fragment and rd_interwiki were added later, populate them if empty
720 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
721 return $this->mRedirectTarget
= Title
::makeTitle(
722 $row->rd_namespace
, $row->rd_title
,
723 $row->rd_fragment
, $row->rd_interwiki
);
726 # This page doesn't have an entry in the redirect table
727 return $this->mRedirectTarget
= $this->insertRedirect();
731 * Insert an entry for this page into the redirect table.
733 * Don't call this function directly unless you know what you're doing.
734 * @return Title object or null if not a redirect
736 public function insertRedirect() {
737 // recurse through to only get the final target
738 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
742 $this->insertRedirectEntry( $retval );
747 * Insert or update the redirect table entry for this page to indicate
748 * it redirects to $rt .
749 * @param $rt Title redirect target
751 public function insertRedirectEntry( $rt ) {
752 $dbw = wfGetDB( DB_MASTER
);
753 $dbw->replace( 'redirect', array( 'rd_from' ),
755 'rd_from' => $this->getId(),
756 'rd_namespace' => $rt->getNamespace(),
757 'rd_title' => $rt->getDBkey(),
758 'rd_fragment' => $rt->getFragment(),
759 'rd_interwiki' => $rt->getInterwiki(),
766 * Get the Title object or URL this page redirects to
768 * @return mixed false, Title of in-wiki target, or string with URL
770 public function followRedirect() {
771 return $this->getRedirectURL( $this->getRedirectTarget() );
775 * Get the Title object or URL to use for a redirect. We use Title
776 * objects for same-wiki, non-special redirects and URLs for everything
778 * @param $rt Title Redirect target
779 * @return mixed false, Title object of local target, or string with URL
781 public function getRedirectURL( $rt ) {
786 if ( $rt->isExternal() ) {
787 if ( $rt->isLocal() ) {
788 // Offsite wikis need an HTTP redirect.
790 // This can be hard to reverse and may produce loops,
791 // so they may be disabled in the site configuration.
792 $source = $this->mTitle
->getFullURL( 'redirect=no' );
793 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
795 // External pages pages without "local" bit set are not valid
801 if ( $rt->isSpecialPage() ) {
802 // Gotta handle redirects to special pages differently:
803 // Fill the HTTP response "Location" header and ignore
804 // the rest of the page we're on.
806 // Some pages are not valid targets
807 if ( $rt->isValidRedirectTarget() ) {
808 return $rt->getFullURL();
818 * Get a list of users who have edited this article, not including the user who made
819 * the most recent revision, which you can get from $article->getUser() if you want it
820 * @return UserArrayFromResult
822 public function getContributors() {
823 # @todo FIXME: This is expensive; cache this info somewhere.
825 $dbr = wfGetDB( DB_SLAVE
);
827 if ( $dbr->implicitGroupby() ) {
828 $realNameField = 'user_real_name';
830 $realNameField = 'MIN(user_real_name) AS user_real_name';
833 $tables = array( 'revision', 'user' );
836 'rev_user as user_id',
837 'rev_user_text AS user_name',
839 'MAX(rev_timestamp) AS timestamp',
842 $conds = array( 'rev_page' => $this->getId() );
844 // The user who made the top revision gets credited as "this page was last edited by
845 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
846 $user = $this->getUser();
848 $conds[] = "rev_user != $user";
850 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
853 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
856 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
860 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
861 'ORDER BY' => 'timestamp DESC',
864 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
865 return new UserArrayFromResult( $res );
869 * Get the last N authors
870 * @param $num Integer: number of revisions to get
871 * @param $revLatest String: the latest rev_id, selected from the master (optional)
872 * @return array Array of authors, duplicates not removed
874 public function getLastNAuthors( $num, $revLatest = 0 ) {
875 wfProfileIn( __METHOD__
);
876 // First try the slave
877 // If that doesn't have the latest revision, try the master
879 $db = wfGetDB( DB_SLAVE
);
882 $res = $db->select( array( 'page', 'revision' ),
883 array( 'rev_id', 'rev_user_text' ),
885 'page_namespace' => $this->mTitle
->getNamespace(),
886 'page_title' => $this->mTitle
->getDBkey(),
890 'ORDER BY' => 'rev_timestamp DESC',
896 wfProfileOut( __METHOD__
);
900 $row = $db->fetchObject( $res );
902 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
903 $db = wfGetDB( DB_MASTER
);
908 } while ( $continue );
910 $authors = array( $row->rev_user_text
);
912 foreach ( $res as $row ) {
913 $authors[] = $row->rev_user_text
;
916 wfProfileOut( __METHOD__
);
921 * Should the parser cache be used?
923 * @param $parserOptions ParserOptions to check
927 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
928 global $wgEnableParserCache;
930 return $wgEnableParserCache
931 && $parserOptions->getStubThreshold() == 0
932 && $this->mTitle
->exists()
933 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
934 && $this->mTitle
->isWikitextPage();
938 * Get a ParserOutput for the given ParserOptions and revision ID.
939 * The parser cache will be used if possible.
942 * @param $parserOptions ParserOptions to use for the parse operation
943 * @param $oldid Revision ID to get the text from, passing null or 0 will
944 * get the current revision (default value)
945 * @return ParserOutput or false if the revision was not found
947 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
948 wfProfileIn( __METHOD__
);
950 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
951 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
952 if ( $parserOptions->getStubThreshold() ) {
953 wfIncrStats( 'pcache_miss_stub' );
956 if ( $useParserCache ) {
957 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
958 if ( $parserOutput !== false ) {
959 wfProfileOut( __METHOD__
);
960 return $parserOutput;
964 if ( $oldid === null ||
$oldid === 0 ) {
965 $oldid = $this->getLatest();
968 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
971 wfProfileOut( __METHOD__
);
973 return $pool->getParserOutput();
977 * Do standard deferred updates after page view
978 * @param $user User The relevant user
980 public function doViewUpdates( User
$user ) {
981 global $wgDisableCounters;
982 if ( wfReadOnly() ) {
986 # Don't update page view counters on views from bot users (bug 14044)
987 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
988 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
989 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
992 # Update newtalk / watchlist notification status
993 $user->clearNotification( $this->mTitle
);
997 * Perform the actions of a page purging
1000 public function doPurge() {
1003 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1007 // Invalidate the cache
1008 $this->mTitle
->invalidateCache();
1011 if ( $wgUseSquid ) {
1012 // Commit the transaction before the purge is sent
1013 $dbw = wfGetDB( DB_MASTER
);
1014 $dbw->commit( __METHOD__
);
1017 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1018 $update->doUpdate();
1021 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1022 if ( $this->mTitle
->exists() ) {
1023 $text = $this->getRawText();
1028 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1034 * Insert a new empty page record for this article.
1035 * This *must* be followed up by creating a revision
1036 * and running $this->updateRevisionOn( ... );
1037 * or else the record will be left in a funky state.
1038 * Best if all done inside a transaction.
1040 * @param $dbw DatabaseBase
1041 * @return int The newly created page_id key, or false if the title already existed
1043 public function insertOn( $dbw ) {
1044 wfProfileIn( __METHOD__
);
1046 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1047 $dbw->insert( 'page', array(
1048 'page_id' => $page_id,
1049 'page_namespace' => $this->mTitle
->getNamespace(),
1050 'page_title' => $this->mTitle
->getDBkey(),
1051 'page_counter' => 0,
1052 'page_restrictions' => '',
1053 'page_is_redirect' => 0, # Will set this shortly...
1055 'page_random' => wfRandom(),
1056 'page_touched' => $dbw->timestamp(),
1057 'page_latest' => 0, # Fill this in shortly...
1058 'page_len' => 0, # Fill this in shortly...
1059 ), __METHOD__
, 'IGNORE' );
1061 $affected = $dbw->affectedRows();
1064 $newid = $dbw->insertId();
1065 $this->mTitle
->resetArticleID( $newid );
1067 wfProfileOut( __METHOD__
);
1069 return $affected ?
$newid : false;
1073 * Update the page record to point to a newly saved revision.
1075 * @param $dbw DatabaseBase: object
1076 * @param $revision Revision: For ID number, and text used to set
1077 * length and redirect status fields
1078 * @param $lastRevision Integer: if given, will not overwrite the page field
1079 * when different from the currently set value.
1080 * Giving 0 indicates the new page flag should be set
1082 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1083 * removing rows in redirect table.
1084 * @return bool true on success, false on failure
1087 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1088 wfProfileIn( __METHOD__
);
1090 $text = $revision->getText();
1091 $len = strlen( $text );
1092 $rt = Title
::newFromRedirectRecurse( $text );
1094 $conditions = array( 'page_id' => $this->getId() );
1096 if ( !is_null( $lastRevision ) ) {
1097 # An extra check against threads stepping on each other
1098 $conditions['page_latest'] = $lastRevision;
1101 $now = wfTimestampNow();
1102 $dbw->update( 'page',
1104 'page_latest' => $revision->getId(),
1105 'page_touched' => $dbw->timestamp( $now ),
1106 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1107 'page_is_redirect' => $rt !== null ?
1 : 0,
1113 $result = $dbw->affectedRows() != 0;
1115 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1116 $this->setLastEdit( $revision );
1117 $this->setCachedLastEditTime( $now );
1118 $this->mLatest
= $revision->getId();
1119 $this->mIsRedirect
= (bool)$rt;
1120 # Update the LinkCache.
1121 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1124 wfProfileOut( __METHOD__
);
1129 * Add row to the redirect table if this is a redirect, remove otherwise.
1131 * @param $dbw DatabaseBase
1132 * @param $redirectTitle Title object pointing to the redirect target,
1133 * or NULL if this is not a redirect
1134 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1135 * removing rows in redirect table.
1136 * @return bool true on success, false on failure
1139 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1140 // Always update redirects (target link might have changed)
1141 // Update/Insert if we don't know if the last revision was a redirect or not
1142 // Delete if changing from redirect to non-redirect
1143 $isRedirect = !is_null( $redirectTitle );
1145 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1149 wfProfileIn( __METHOD__
);
1150 if ( $isRedirect ) {
1151 $this->insertRedirectEntry( $redirectTitle );
1153 // This is not a redirect, remove row from redirect table
1154 $where = array( 'rd_from' => $this->getId() );
1155 $dbw->delete( 'redirect', $where, __METHOD__
);
1158 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1159 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1161 wfProfileOut( __METHOD__
);
1163 return ( $dbw->affectedRows() != 0 );
1167 * If the given revision is newer than the currently set page_latest,
1168 * update the page record. Otherwise, do nothing.
1170 * @param $dbw DatabaseBase object
1171 * @param $revision Revision object
1174 public function updateIfNewerOn( $dbw, $revision ) {
1175 wfProfileIn( __METHOD__
);
1177 $row = $dbw->selectRow(
1178 array( 'revision', 'page' ),
1179 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1181 'page_id' => $this->getId(),
1182 'page_latest=rev_id' ),
1186 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1187 wfProfileOut( __METHOD__
);
1190 $prev = $row->rev_id
;
1191 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1193 # No or missing previous revision; mark the page as new
1195 $lastRevIsRedirect = null;
1198 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1200 wfProfileOut( __METHOD__
);
1205 * Get the text that needs to be saved in order to undo all revisions
1206 * between $undo and $undoafter. Revisions must belong to the same page,
1207 * must exist and must not be deleted
1208 * @param $undo Revision
1209 * @param $undoafter Revision Must be an earlier revision than $undo
1210 * @return mixed string on success, false on failure
1212 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1213 $cur_text = $this->getRawText();
1214 if ( $cur_text === false ) {
1215 return false; // no page
1217 $undo_text = $undo->getText();
1218 $undoafter_text = $undoafter->getText();
1220 if ( $cur_text == $undo_text ) {
1221 # No use doing a merge if it's just a straight revert.
1222 return $undoafter_text;
1227 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1231 return $undone_text;
1235 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1236 * @param $text String: new text of the section
1237 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1238 * @param $edittime String: revision timestamp or null to use the current revision
1239 * @return string Complete article text, or null if error
1241 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1242 wfProfileIn( __METHOD__
);
1244 if ( strval( $section ) == '' ) {
1245 // Whole-page edit; let the whole text through
1247 // Bug 30711: always use current version when adding a new section
1248 if ( is_null( $edittime ) ||
$section == 'new' ) {
1249 $oldtext = $this->getRawText();
1250 if ( $oldtext === false ) {
1251 wfDebug( __METHOD__
. ": no page text\n" );
1252 wfProfileOut( __METHOD__
);
1256 $dbw = wfGetDB( DB_MASTER
);
1257 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1260 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1261 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1262 wfProfileOut( __METHOD__
);
1266 $oldtext = $rev->getText();
1269 if ( $section == 'new' ) {
1270 # Inserting a new section
1271 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1272 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1273 $text = strlen( trim( $oldtext ) ) > 0
1274 ?
"{$oldtext}\n\n{$subject}{$text}"
1275 : "{$subject}{$text}";
1278 # Replacing an existing section; roll out the big guns
1281 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1285 wfProfileOut( __METHOD__
);
1290 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1292 * @return Int updated $flags
1294 function checkFlags( $flags ) {
1295 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1296 if ( $this->mTitle
->getArticleID() ) {
1297 $flags |
= EDIT_UPDATE
;
1307 * Change an existing article or create a new article. Updates RC and all necessary caches,
1308 * optionally via the deferred update array.
1310 * @param $text String: new text
1311 * @param $summary String: edit summary
1312 * @param $flags Integer bitfield:
1314 * Article is known or assumed to be non-existent, create a new one
1316 * Article is known or assumed to be pre-existing, update it
1318 * Mark this edit minor, if the user is allowed to do so
1320 * Do not log the change in recentchanges
1322 * Mark the edit a "bot" edit regardless of user rights
1323 * EDIT_DEFER_UPDATES
1324 * Defer some of the updates until the end of index.php
1326 * Fill in blank summaries with generated text where possible
1328 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1329 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1330 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1331 * edit-already-exists error will be returned. These two conditions are also possible with
1332 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1334 * @param $baseRevId int the revision ID this edit was based off, if any
1335 * @param $user User the user doing the edit
1337 * @return Status object. Possible errors:
1338 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1339 * edit-gone-missing: In update mode, but the article didn't exist
1340 * edit-conflict: In update mode, the article changed unexpectedly
1341 * edit-no-change: Warning that the text was the same as before
1342 * edit-already-exists: In creation mode, but the article already exists
1344 * Extensions may define additional errors.
1346 * $return->value will contain an associative array with members as follows:
1347 * new: Boolean indicating if the function attempted to create a new article
1348 * revision: The revision object for the inserted revision, or null
1350 * Compatibility note: this function previously returned a boolean value indicating success/failure
1352 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1353 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1355 # Low-level sanity check
1356 if ( $this->mTitle
->getText() === '' ) {
1357 throw new MWException( 'Something is trying to edit an article with an empty title' );
1360 wfProfileIn( __METHOD__
);
1362 $user = is_null( $user ) ?
$wgUser : $user;
1363 $status = Status
::newGood( array() );
1365 // Load the data from the master database if needed.
1366 // The caller may already loaded it from the master or even loaded it using
1367 // SELECT FOR UPDATE, so do not override that using clear().
1368 $this->loadPageData( 'fromdbmaster' );
1370 $flags = $this->checkFlags( $flags );
1372 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1373 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1375 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1377 if ( $status->isOK() ) {
1378 $status->fatal( 'edit-hook-aborted' );
1381 wfProfileOut( __METHOD__
);
1385 # Silently ignore EDIT_MINOR if not allowed
1386 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1387 $bot = $flags & EDIT_FORCE_BOT
;
1389 $oldtext = $this->getRawText(); // current revision
1390 $oldsize = strlen( $oldtext );
1391 $oldid = $this->getLatest();
1392 $oldIsRedirect = $this->isRedirect();
1393 $oldcountable = $this->isCountable();
1395 # Provide autosummaries if one is not provided and autosummaries are enabled.
1396 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1397 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1400 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1401 $text = $editInfo->pst
;
1402 $newsize = strlen( $text );
1404 $dbw = wfGetDB( DB_MASTER
);
1405 $now = wfTimestampNow();
1406 $this->mTimestamp
= $now;
1408 if ( $flags & EDIT_UPDATE
) {
1409 # Update article, but only if changed.
1410 $status->value
['new'] = false;
1413 # Article gone missing
1414 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1415 $status->fatal( 'edit-gone-missing' );
1417 wfProfileOut( __METHOD__
);
1421 # Make sure the revision is either completely inserted or not inserted at all
1422 if ( !$wgDBtransactions ) {
1423 $userAbort = ignore_user_abort( true );
1426 $revision = new Revision( array(
1427 'page' => $this->getId(),
1428 'comment' => $summary,
1429 'minor_edit' => $isminor,
1431 'parent_id' => $oldid,
1432 'user' => $user->getId(),
1433 'user_text' => $user->getName(),
1437 $changed = ( strcmp( $text, $oldtext ) != 0 );
1440 $dbw->begin( __METHOD__
);
1441 $revisionId = $revision->insertOn( $dbw );
1445 # Note that we use $this->mLatest instead of fetching a value from the master DB
1446 # during the course of this function. This makes sure that EditPage can detect
1447 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1448 # before this function is called. A previous function used a separate query, this
1449 # creates a window where concurrent edits can cause an ignored edit conflict.
1450 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1453 /* Belated edit conflict! Run away!! */
1454 $status->fatal( 'edit-conflict' );
1456 # Delete the invalid revision if the DB is not transactional
1457 if ( !$wgDBtransactions ) {
1458 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1462 $dbw->rollback( __METHOD__
);
1464 global $wgUseRCPatrol;
1465 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1466 # Update recentchanges
1467 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1468 # Mark as patrolled if the user can do so
1469 $patrolled = $wgUseRCPatrol && !count(
1470 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1471 # Add RC row to the DB
1472 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1473 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1474 $revisionId, $patrolled
1477 # Log auto-patrolled edits
1479 PatrolLog
::record( $rc, true, $user );
1482 $user->incEditCount();
1483 $dbw->commit( __METHOD__
);
1486 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1487 // related variables correctly
1488 $revision->setId( $this->getLatest() );
1491 if ( !$wgDBtransactions ) {
1492 ignore_user_abort( $userAbort );
1495 // Now that ignore_user_abort is restored, we can respond to fatal errors
1496 if ( !$status->isOK() ) {
1497 wfProfileOut( __METHOD__
);
1501 # Update links tables, site stats, etc.
1502 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1503 'oldcountable' => $oldcountable ) );
1506 $status->warning( 'edit-no-change' );
1508 // Update page_touched, this is usually implicit in the page update
1509 // Other cache updates are done in onArticleEdit()
1510 $this->mTitle
->invalidateCache();
1513 # Create new article
1514 $status->value
['new'] = true;
1516 $dbw->begin( __METHOD__
);
1518 # Add the page record; stake our claim on this title!
1519 # This will return false if the article already exists
1520 $newid = $this->insertOn( $dbw );
1522 if ( $newid === false ) {
1523 $dbw->rollback( __METHOD__
);
1524 $status->fatal( 'edit-already-exists' );
1526 wfProfileOut( __METHOD__
);
1530 # Save the revision text...
1531 $revision = new Revision( array(
1533 'comment' => $summary,
1534 'minor_edit' => $isminor,
1536 'user' => $user->getId(),
1537 'user_text' => $user->getName(),
1540 $revisionId = $revision->insertOn( $dbw );
1542 # Update the page record with revision data
1543 $this->updateRevisionOn( $dbw, $revision, 0 );
1545 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1547 # Update recentchanges
1548 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1549 global $wgUseRCPatrol, $wgUseNPPatrol;
1551 # Mark as patrolled if the user can do so
1552 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1553 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1554 # Add RC row to the DB
1555 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1556 '', strlen( $text ), $revisionId, $patrolled );
1558 # Log auto-patrolled edits
1560 PatrolLog
::record( $rc, true, $user );
1563 $user->incEditCount();
1564 $dbw->commit( __METHOD__
);
1566 # Update links, etc.
1567 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1569 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1570 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1573 # Do updates right now unless deferral was requested
1574 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1575 DeferredUpdates
::doUpdates();
1578 // Return the new revision (or null) to the caller
1579 $status->value
['revision'] = $revision;
1581 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1582 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1584 # Promote user to any groups they meet the criteria for
1585 $user->addAutopromoteOnceGroups( 'onEdit' );
1587 wfProfileOut( __METHOD__
);
1592 * Get parser options suitable for rendering the primary article wikitext
1593 * @param User|string $user User object or 'canonical'
1594 * @return ParserOptions
1596 public function makeParserOptions( $user ) {
1598 if ( $user instanceof User
) { // settings per user (even anons)
1599 $options = ParserOptions
::newFromUser( $user );
1600 } else { // canonical settings
1601 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1603 $options->enableLimitReport(); // show inclusion/loop reports
1604 $options->setTidy( true ); // fix bad HTML
1609 * Prepare text which is about to be saved.
1610 * Returns a stdclass with source, pst and output members
1611 * @return bool|object
1613 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1614 global $wgParser, $wgContLang, $wgUser;
1615 $user = is_null( $user ) ?
$wgUser : $user;
1616 // @TODO fixme: check $user->getId() here???
1617 if ( $this->mPreparedEdit
1618 && $this->mPreparedEdit
->newText
== $text
1619 && $this->mPreparedEdit
->revid
== $revid
1622 return $this->mPreparedEdit
;
1625 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1626 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1628 $edit = (object)array();
1629 $edit->revid
= $revid;
1630 $edit->newText
= $text;
1631 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1632 $edit->popts
= $this->makeParserOptions( 'canonical' );
1633 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1634 $edit->oldText
= $this->getRawText();
1636 $this->mPreparedEdit
= $edit;
1642 * Do standard deferred updates after page edit.
1643 * Update links tables, site stats, search index and message cache.
1644 * Purges pages that include this page if the text was changed here.
1645 * Every 100th edit, prune the recent changes table.
1648 * @param $revision Revision object
1649 * @param $user User object that did the revision
1650 * @param $options Array of options, following indexes are used:
1651 * - changed: boolean, whether the revision changed the content (default true)
1652 * - created: boolean, whether the revision created the page (default false)
1653 * - oldcountable: boolean or null (default null):
1654 * - boolean: whether the page was counted as an article before that
1655 * revision, only used in changed is true and created is false
1656 * - null: don't change the article count
1658 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1659 global $wgEnableParserCache;
1661 wfProfileIn( __METHOD__
);
1663 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1664 $text = $revision->getText();
1667 # Be careful not to double-PST: $text is usually already PST-ed once
1668 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1669 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1670 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1672 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1673 $editInfo = $this->mPreparedEdit
;
1676 # Save it to the parser cache
1677 if ( $wgEnableParserCache ) {
1678 $parserCache = ParserCache
::singleton();
1679 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1682 # Update the links tables
1683 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1686 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1688 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1689 if ( 0 == mt_rand( 0, 99 ) ) {
1690 // Flush old entries from the `recentchanges` table; we do this on
1691 // random requests so as to avoid an increase in writes for no good reason
1694 $dbw = wfGetDB( DB_MASTER
);
1695 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1698 array( "rc_timestamp < '$cutoff'" ),
1704 if ( !$this->mTitle
->exists() ) {
1705 wfProfileOut( __METHOD__
);
1709 $id = $this->getId();
1710 $title = $this->mTitle
->getPrefixedDBkey();
1711 $shortTitle = $this->mTitle
->getDBkey();
1713 if ( !$options['changed'] ) {
1716 } elseif ( $options['created'] ) {
1717 $good = (int)$this->isCountable( $editInfo );
1719 } elseif ( $options['oldcountable'] !== null ) {
1720 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1727 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1728 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1730 # If this is another user's talk page, update newtalk.
1731 # Don't do this if $options['changed'] = false (null-edits) nor if
1732 # it's a minor edit and the user doesn't want notifications for those.
1733 if ( $options['changed']
1734 && $this->mTitle
->getNamespace() == NS_USER_TALK
1735 && $shortTitle != $user->getTitleKey()
1736 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1738 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1739 $other = User
::newFromName( $shortTitle, false );
1741 wfDebug( __METHOD__
. ": invalid username\n" );
1742 } elseif ( User
::isIP( $shortTitle ) ) {
1743 // An anonymous user
1744 $other->setNewtalk( true );
1745 } elseif ( $other->isLoggedIn() ) {
1746 $other->setNewtalk( true );
1748 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1753 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1754 MessageCache
::singleton()->replace( $shortTitle, $text );
1757 if( $options['created'] ) {
1758 self
::onArticleCreate( $this->mTitle
);
1760 self
::onArticleEdit( $this->mTitle
);
1763 wfProfileOut( __METHOD__
);
1767 * Edit an article without doing all that other stuff
1768 * The article must already exist; link tables etc
1769 * are not updated, caches are not flushed.
1771 * @param $text String: text submitted
1772 * @param $user User The relevant user
1773 * @param $comment String: comment submitted
1774 * @param $minor Boolean: whereas it's a minor modification
1776 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1777 wfProfileIn( __METHOD__
);
1779 $dbw = wfGetDB( DB_MASTER
);
1780 $revision = new Revision( array(
1781 'page' => $this->getId(),
1783 'comment' => $comment,
1784 'minor_edit' => $minor ?
1 : 0,
1786 $revision->insertOn( $dbw );
1787 $this->updateRevisionOn( $dbw, $revision );
1789 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1791 wfProfileOut( __METHOD__
);
1795 * Update the article's restriction field, and leave a log entry.
1796 * This works for protection both existing and non-existing pages.
1798 * @param $limit Array: set of restriction keys
1799 * @param $reason String
1800 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1801 * @param $expiry Array: per restriction type expiration
1802 * @param $user User The user updating the restrictions
1805 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1808 if ( wfReadOnly() ) {
1809 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1812 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1814 $id = $this->mTitle
->getArticleID();
1820 // Take this opportunity to purge out expired restrictions
1821 Title
::purgeExpiredRestrictions();
1823 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1824 # we expect a single selection, but the schema allows otherwise.
1825 $isProtected = false;
1829 $dbw = wfGetDB( DB_MASTER
);
1831 foreach ( $restrictionTypes as $action ) {
1832 if ( !isset( $expiry[$action] ) ) {
1833 $expiry[$action] = $dbw->getInfinity();
1835 if ( !isset( $limit[$action] ) ) {
1836 $limit[$action] = '';
1837 } elseif ( $limit[$action] != '' ) {
1841 # Get current restrictions on $action
1842 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1843 if ( $current != '' ) {
1844 $isProtected = true;
1847 if ( $limit[$action] != $current ) {
1849 } elseif ( $limit[$action] != '' ) {
1850 # Only check expiry change if the action is actually being
1851 # protected, since expiry does nothing on an not-protected
1853 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1859 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1863 # If nothing's changed, do nothing
1865 return Status
::newGood();
1868 if ( !$protect ) { # No protection at all means unprotection
1869 $revCommentMsg = 'unprotectedarticle';
1870 $logAction = 'unprotect';
1871 } elseif ( $isProtected ) {
1872 $revCommentMsg = 'modifiedarticleprotection';
1873 $logAction = 'modify';
1875 $revCommentMsg = 'protectedarticle';
1876 $logAction = 'protect';
1879 $encodedExpiry = array();
1880 $protectDescription = '';
1881 foreach ( $limit as $action => $restrictions ) {
1882 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1883 if ( $restrictions != '' ) {
1884 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1885 if ( $encodedExpiry[$action] != 'infinity' ) {
1886 $protectDescription .= wfMsgForContent( 'protect-expiring',
1887 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1888 $wgContLang->date( $expiry[$action], false, false ) ,
1889 $wgContLang->time( $expiry[$action], false, false ) );
1891 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1894 $protectDescription .= ') ';
1897 $protectDescription = trim( $protectDescription );
1899 if ( $id ) { # Protection of existing page
1900 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1901 return Status
::newGood();
1904 # Only restrictions with the 'protect' right can cascade...
1905 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1906 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1908 # The schema allows multiple restrictions
1909 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1913 # Update restrictions table
1914 foreach ( $limit as $action => $restrictions ) {
1915 if ( $restrictions != '' ) {
1916 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1917 array( 'pr_page' => $id,
1918 'pr_type' => $action,
1919 'pr_level' => $restrictions,
1920 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1921 'pr_expiry' => $encodedExpiry[$action]
1926 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1927 'pr_type' => $action ), __METHOD__
);
1931 # Prepare a null revision to be added to the history
1932 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1934 $editComment .= ": $reason";
1936 if ( $protectDescription ) {
1937 $editComment .= " ($protectDescription)";
1940 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1943 # Insert a null revision
1944 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1945 $nullRevId = $nullRevision->insertOn( $dbw );
1947 $latest = $this->getLatest();
1948 # Update page record
1949 $dbw->update( 'page',
1951 'page_touched' => $dbw->timestamp(),
1952 'page_restrictions' => '',
1953 'page_latest' => $nullRevId
1954 ), array( /* WHERE */
1959 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1960 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1961 } else { # Protection of non-existing page (also known as "title protection")
1962 # Cascade protection is meaningless in this case
1965 if ( $limit['create'] != '' ) {
1966 $dbw->replace( 'protected_titles',
1967 array( array( 'pt_namespace', 'pt_title' ) ),
1969 'pt_namespace' => $this->mTitle
->getNamespace(),
1970 'pt_title' => $this->mTitle
->getDBkey(),
1971 'pt_create_perm' => $limit['create'],
1972 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1973 'pt_expiry' => $encodedExpiry['create'],
1974 'pt_user' => $user->getId(),
1975 'pt_reason' => $reason,
1979 $dbw->delete( 'protected_titles',
1981 'pt_namespace' => $this->mTitle
->getNamespace(),
1982 'pt_title' => $this->mTitle
->getDBkey()
1988 $this->mTitle
->flushRestrictions();
1990 if ( $logAction == 'unprotect' ) {
1991 $logParams = array();
1993 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1996 # Update the protection log
1997 $log = new LogPage( 'protect' );
1998 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2000 return Status
::newGood();
2004 * Take an array of page restrictions and flatten it to a string
2005 * suitable for insertion into the page_restrictions field.
2006 * @param $limit Array
2009 protected static function flattenRestrictions( $limit ) {
2010 if ( !is_array( $limit ) ) {
2011 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2017 foreach ( $limit as $action => $restrictions ) {
2018 if ( $restrictions != '' ) {
2019 $bits[] = "$action=$restrictions";
2023 return implode( ':', $bits );
2027 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2028 * Deletes the article with database consistency, writes logs, purges caches
2030 * @param $reason string delete reason for deletion log
2031 * @param $suppress int bitfield
2032 * Revision::DELETED_TEXT
2033 * Revision::DELETED_COMMENT
2034 * Revision::DELETED_USER
2035 * Revision::DELETED_RESTRICTED
2036 * @param $id int article ID
2037 * @param $commit boolean defaults to true, triggers transaction end
2038 * @param &$error Array of errors to append to
2039 * @param $user User The deleting user
2040 * @return boolean true if successful
2042 public function doDeleteArticle(
2043 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2045 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2046 == WikiPage
::DELETE_SUCCESS
;
2050 * Back-end article deletion
2051 * Deletes the article with database consistency, writes logs, purges caches
2053 * @param $reason string delete reason for deletion log
2054 * @param $suppress int bitfield
2055 * Revision::DELETED_TEXT
2056 * Revision::DELETED_COMMENT
2057 * Revision::DELETED_USER
2058 * Revision::DELETED_RESTRICTED
2059 * @param $id int article ID
2060 * @param $commit boolean defaults to true, triggers transaction end
2061 * @param &$error Array of errors to append to
2062 * @param $user User The deleting user
2063 * @return int: One of WikiPage::DELETE_* constants
2065 public function doDeleteArticleReal(
2066 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2070 wfDebug( __METHOD__
. "\n" );
2072 if ( $this->mTitle
->getDBkey() === '' ) {
2073 return WikiPage
::DELETE_NO_PAGE
;
2076 $user = is_null( $user ) ?
$wgUser : $user;
2077 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2078 return WikiPage
::DELETE_HOOK_ABORTED
;
2082 $this->loadPageData( 'forupdate' );
2083 $id = $this->getID();
2085 return WikiPage
::DELETE_NO_PAGE
;
2089 // Bitfields to further suppress the content
2092 // This should be 15...
2093 $bitfield |
= Revision
::DELETED_TEXT
;
2094 $bitfield |
= Revision
::DELETED_COMMENT
;
2095 $bitfield |
= Revision
::DELETED_USER
;
2096 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2098 $bitfield = 'rev_deleted';
2101 $dbw = wfGetDB( DB_MASTER
);
2102 $dbw->begin( __METHOD__
);
2103 // For now, shunt the revision data into the archive table.
2104 // Text is *not* removed from the text table; bulk storage
2105 // is left intact to avoid breaking block-compression or
2106 // immutable storage schemes.
2108 // For backwards compatibility, note that some older archive
2109 // table entries will have ar_text and ar_flags fields still.
2111 // In the future, we may keep revisions and mark them with
2112 // the rev_deleted field, which is reserved for this purpose.
2113 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2115 'ar_namespace' => 'page_namespace',
2116 'ar_title' => 'page_title',
2117 'ar_comment' => 'rev_comment',
2118 'ar_user' => 'rev_user',
2119 'ar_user_text' => 'rev_user_text',
2120 'ar_timestamp' => 'rev_timestamp',
2121 'ar_minor_edit' => 'rev_minor_edit',
2122 'ar_rev_id' => 'rev_id',
2123 'ar_parent_id' => 'rev_parent_id',
2124 'ar_text_id' => 'rev_text_id',
2125 'ar_text' => '\'\'', // Be explicit to appease
2126 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2127 'ar_len' => 'rev_len',
2128 'ar_page_id' => 'page_id',
2129 'ar_deleted' => $bitfield,
2130 'ar_sha1' => 'rev_sha1'
2133 'page_id = rev_page'
2137 # Now that it's safely backed up, delete it
2138 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2139 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2142 $dbw->rollback( __METHOD__
);
2143 return WikiPage
::DELETE_NO_REVISIONS
;
2146 $this->doDeleteUpdates( $id );
2148 # Log the deletion, if the page was suppressed, log it at Oversight instead
2149 $logtype = $suppress ?
'suppress' : 'delete';
2151 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2152 $logEntry->setPerformer( $user );
2153 $logEntry->setTarget( $this->mTitle
);
2154 $logEntry->setComment( $reason );
2155 $logid = $logEntry->insert();
2156 $logEntry->publish( $logid );
2159 $dbw->commit( __METHOD__
);
2162 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2163 return WikiPage
::DELETE_SUCCESS
;
2167 * Do some database updates after deletion
2169 * @param $id Int: page_id value of the page being deleted
2171 public function doDeleteUpdates( $id ) {
2172 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2174 $dbw = wfGetDB( DB_MASTER
);
2176 # Delete restrictions for it
2177 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2179 # Fix category table counts
2181 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2183 foreach ( $res as $row ) {
2184 $cats [] = $row->cl_to
;
2187 $this->updateCategoryCounts( array(), $cats );
2189 # If using cascading deletes, we can skip some explicit deletes
2190 if ( !$dbw->cascadingDeletes() ) {
2191 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2193 # Delete outgoing links
2194 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2195 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2196 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2197 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2198 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2199 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2200 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2201 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2202 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2205 # If using cleanup triggers, we can skip some manual deletes
2206 if ( !$dbw->cleanupTriggers() ) {
2207 # Clean up recentchanges entries...
2208 $dbw->delete( 'recentchanges',
2209 array( 'rc_type != ' . RC_LOG
,
2210 'rc_namespace' => $this->mTitle
->getNamespace(),
2211 'rc_title' => $this->mTitle
->getDBkey() ),
2213 $dbw->delete( 'recentchanges',
2214 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2219 self
::onArticleDelete( $this->mTitle
);
2224 # Clear the cached article id so the interface doesn't act like we exist
2225 $this->mTitle
->resetArticleID( 0 );
2229 * Roll back the most recent consecutive set of edits to a page
2230 * from the same user; fails if there are no eligible edits to
2231 * roll back to, e.g. user is the sole contributor. This function
2232 * performs permissions checks on $user, then calls commitRollback()
2233 * to do the dirty work
2235 * @todo: seperate the business/permission stuff out from backend code
2237 * @param $fromP String: Name of the user whose edits to rollback.
2238 * @param $summary String: Custom summary. Set to default summary if empty.
2239 * @param $token String: Rollback token.
2240 * @param $bot Boolean: If true, mark all reverted edits as bot.
2242 * @param $resultDetails Array: contains result-specific array of additional values
2243 * 'alreadyrolled' : 'current' (rev)
2244 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2246 * @param $user User The user performing the rollback
2247 * @return array of errors, each error formatted as
2248 * array(messagekey, param1, param2, ...).
2249 * On success, the array is empty. This array can also be passed to
2250 * OutputPage::showPermissionsErrorPage().
2252 public function doRollback(
2253 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2255 $resultDetails = null;
2258 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2259 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2260 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2262 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2263 $errors[] = array( 'sessionfailure' );
2266 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2267 $errors[] = array( 'actionthrottledtext' );
2270 # If there were errors, bail out now
2271 if ( !empty( $errors ) ) {
2275 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2279 * Backend implementation of doRollback(), please refer there for parameter
2280 * and return value documentation
2282 * NOTE: This function does NOT check ANY permissions, it just commits the
2283 * rollback to the DB. Therefore, you should only call this function direct-
2284 * ly if you want to use custom permissions checks. If you don't, use
2285 * doRollback() instead.
2286 * @param $fromP String: Name of the user whose edits to rollback.
2287 * @param $summary String: Custom summary. Set to default summary if empty.
2288 * @param $bot Boolean: If true, mark all reverted edits as bot.
2290 * @param $resultDetails Array: contains result-specific array of additional values
2291 * @param $guser User The user performing the rollback
2294 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2295 global $wgUseRCPatrol, $wgContLang;
2297 $dbw = wfGetDB( DB_MASTER
);
2299 if ( wfReadOnly() ) {
2300 return array( array( 'readonlytext' ) );
2303 # Get the last editor
2304 $current = $this->getRevision();
2305 if ( is_null( $current ) ) {
2306 # Something wrong... no page?
2307 return array( array( 'notanarticle' ) );
2310 $from = str_replace( '_', ' ', $fromP );
2311 # User name given should match up with the top revision.
2312 # If the user was deleted then $from should be empty.
2313 if ( $from != $current->getUserText() ) {
2314 $resultDetails = array( 'current' => $current );
2315 return array( array( 'alreadyrolled',
2316 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2317 htmlspecialchars( $fromP ),
2318 htmlspecialchars( $current->getUserText() )
2322 # Get the last edit not by this guy...
2323 # Note: these may not be public values
2324 $user = intval( $current->getRawUser() );
2325 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2326 $s = $dbw->selectRow( 'revision',
2327 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2328 array( 'rev_page' => $current->getPage(),
2329 "rev_user != {$user} OR rev_user_text != {$user_text}"
2331 array( 'USE INDEX' => 'page_timestamp',
2332 'ORDER BY' => 'rev_timestamp DESC' )
2334 if ( $s === false ) {
2335 # No one else ever edited this page
2336 return array( array( 'cantrollback' ) );
2337 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2338 # Only admins can see this text
2339 return array( array( 'notvisiblerev' ) );
2343 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2344 # Mark all reverted edits as bot
2348 if ( $wgUseRCPatrol ) {
2349 # Mark all reverted edits as patrolled
2350 $set['rc_patrolled'] = 1;
2353 if ( count( $set ) ) {
2354 $dbw->update( 'recentchanges', $set,
2356 'rc_cur_id' => $current->getPage(),
2357 'rc_user_text' => $current->getUserText(),
2358 "rc_timestamp > '{$s->rev_timestamp}'",
2363 # Generate the edit summary if necessary
2364 $target = Revision
::newFromId( $s->rev_id
);
2365 if ( empty( $summary ) ) {
2366 if ( $from == '' ) { // no public user name
2367 $summary = wfMsgForContent( 'revertpage-nouser' );
2369 $summary = wfMsgForContent( 'revertpage' );
2373 # Allow the custom summary to use the same args as the default message
2375 $target->getUserText(), $from, $s->rev_id
,
2376 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2377 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2379 $summary = wfMsgReplaceArgs( $summary, $args );
2382 $flags = EDIT_UPDATE
;
2384 if ( $guser->isAllowed( 'minoredit' ) ) {
2385 $flags |
= EDIT_MINOR
;
2388 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2389 $flags |
= EDIT_FORCE_BOT
;
2392 # Actually store the edit
2393 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2394 if ( !empty( $status->value
['revision'] ) ) {
2395 $revId = $status->value
['revision']->getId();
2400 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2402 $resultDetails = array(
2403 'summary' => $summary,
2404 'current' => $current,
2405 'target' => $target,
2413 * The onArticle*() functions are supposed to be a kind of hooks
2414 * which should be called whenever any of the specified actions
2417 * This is a good place to put code to clear caches, for instance.
2419 * This is called on page move and undelete, as well as edit
2421 * @param $title Title object
2423 public static function onArticleCreate( $title ) {
2424 # Update existence markers on article/talk tabs...
2425 if ( $title->isTalkPage() ) {
2426 $other = $title->getSubjectPage();
2428 $other = $title->getTalkPage();
2431 $other->invalidateCache();
2432 $other->purgeSquid();
2434 $title->touchLinks();
2435 $title->purgeSquid();
2436 $title->deleteTitleProtection();
2440 * Clears caches when article is deleted
2442 * @param $title Title
2444 public static function onArticleDelete( $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();
2459 HTMLFileCache
::clearFileCache( $title );
2462 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2463 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2467 if ( $title->getNamespace() == NS_FILE
) {
2468 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2469 $update->doUpdate();
2473 if ( $title->getNamespace() == NS_USER_TALK
) {
2474 $user = User
::newFromName( $title->getText(), false );
2476 $user->setNewtalk( false );
2481 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2485 * Purge caches on page update etc
2487 * @param $title Title object
2488 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2490 public static function onArticleEdit( $title ) {
2491 // Invalidate caches of articles which include this page
2492 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2495 // Invalidate the caches of all pages which redirect here
2496 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2498 # Purge squid for this page only
2499 $title->purgeSquid();
2501 # Clear file cache for this page only
2502 HTMLFileCache
::clearFileCache( $title );
2508 * Returns a list of hidden categories this page is a member of.
2509 * Uses the page_props and categorylinks tables.
2511 * @return Array of Title objects
2513 public function getHiddenCategories() {
2515 $id = $this->mTitle
->getArticleID();
2521 $dbr = wfGetDB( DB_SLAVE
);
2522 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2524 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2525 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2528 if ( $res !== false ) {
2529 foreach ( $res as $row ) {
2530 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2538 * Return an applicable autosummary if one exists for the given edit.
2539 * @param $oldtext String: the previous text of the page.
2540 * @param $newtext String: The submitted text of the page.
2541 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2542 * @return string An appropriate autosummary, or an empty string.
2544 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2547 # Decide what kind of autosummary is needed.
2549 # Redirect autosummaries
2550 $ot = Title
::newFromRedirect( $oldtext );
2551 $rt = Title
::newFromRedirect( $newtext );
2553 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2554 $truncatedtext = $wgContLang->truncate(
2555 str_replace( "\n", ' ', $newtext ),
2557 - strlen( wfMsgForContent( 'autoredircomment' ) )
2558 - strlen( $rt->getFullText() )
2560 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2563 # New page autosummaries
2564 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2565 # If they're making a new article, give its text, truncated, in the summary.
2567 $truncatedtext = $wgContLang->truncate(
2568 str_replace( "\n", ' ', $newtext ),
2569 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2571 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2574 # Blanking autosummaries
2575 if ( $oldtext != '' && $newtext == '' ) {
2576 return wfMsgForContent( 'autosumm-blank' );
2577 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2578 # Removing more than 90% of the article
2580 $truncatedtext = $wgContLang->truncate(
2582 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2584 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2587 # If we reach this point, there's no applicable autosummary for our case, so our
2588 # autosummary is empty.
2593 * Auto-generates a deletion reason
2595 * @param &$hasHistory Boolean: whether the page has a history
2596 * @return mixed String containing deletion reason or empty string, or boolean false
2597 * if no revision occurred
2599 public function getAutoDeleteReason( &$hasHistory ) {
2602 // Get the last revision
2603 $rev = $this->getRevision();
2605 if ( is_null( $rev ) ) {
2609 // Get the article's contents
2610 $contents = $rev->getText();
2613 // If the page is blank, use the text from the previous revision,
2614 // which can only be blank if there's a move/import/protect dummy revision involved
2615 if ( $contents == '' ) {
2616 $prev = $rev->getPrevious();
2619 $contents = $prev->getText();
2624 $dbw = wfGetDB( DB_MASTER
);
2626 // Find out if there was only one contributor
2627 // Only scan the last 20 revisions
2628 $res = $dbw->select( 'revision', 'rev_user_text',
2629 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2631 array( 'LIMIT' => 20 )
2634 if ( $res === false ) {
2635 // This page has no revisions, which is very weird
2639 $hasHistory = ( $res->numRows() > 1 );
2640 $row = $dbw->fetchObject( $res );
2642 if ( $row ) { // $row is false if the only contributor is hidden
2643 $onlyAuthor = $row->rev_user_text
;
2644 // Try to find a second contributor
2645 foreach ( $res as $row ) {
2646 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2647 $onlyAuthor = false;
2652 $onlyAuthor = false;
2655 // Generate the summary with a '$1' placeholder
2657 // The current revision is blank and the one before is also
2658 // blank. It's just not our lucky day
2659 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2661 if ( $onlyAuthor ) {
2662 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2664 $reason = wfMsgForContent( 'excontent', '$1' );
2668 if ( $reason == '-' ) {
2669 // Allow these UI messages to be blanked out cleanly
2673 // Replace newlines with spaces to prevent uglyness
2674 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2675 // Calculate the maximum amount of chars to get
2676 // Max content length = max comment length - length of the comment (excl. $1)
2677 $maxLength = 255 - ( strlen( $reason ) - 2 );
2678 $contents = $wgContLang->truncate( $contents, $maxLength );
2679 // Remove possible unfinished links
2680 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2681 // Now replace the '$1' placeholder
2682 $reason = str_replace( '$1', $contents, $reason );
2688 * Update all the appropriate counts in the category table, given that
2689 * we've added the categories $added and deleted the categories $deleted.
2691 * @param $added array The names of categories that were added
2692 * @param $deleted array The names of categories that were deleted
2694 public function updateCategoryCounts( $added, $deleted ) {
2695 $ns = $this->mTitle
->getNamespace();
2696 $dbw = wfGetDB( DB_MASTER
);
2698 # First make sure the rows exist. If one of the "deleted" ones didn't
2699 # exist, we might legitimately not create it, but it's simpler to just
2700 # create it and then give it a negative value, since the value is bogus
2703 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2704 $insertCats = array_merge( $added, $deleted );
2705 if ( !$insertCats ) {
2706 # Okay, nothing to do
2710 $insertRows = array();
2712 foreach ( $insertCats as $cat ) {
2713 $insertRows[] = array(
2714 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2718 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2720 $addFields = array( 'cat_pages = cat_pages + 1' );
2721 $removeFields = array( 'cat_pages = cat_pages - 1' );
2723 if ( $ns == NS_CATEGORY
) {
2724 $addFields[] = 'cat_subcats = cat_subcats + 1';
2725 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2726 } elseif ( $ns == NS_FILE
) {
2727 $addFields[] = 'cat_files = cat_files + 1';
2728 $removeFields[] = 'cat_files = cat_files - 1';
2735 array( 'cat_title' => $added ),
2744 array( 'cat_title' => $deleted ),
2751 * Updates cascading protections
2753 * @param $parserOutput ParserOutput object for the current version
2755 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2756 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2760 // templatelinks table may have become out of sync,
2761 // especially if using variable-based transclusions.
2762 // For paranoia, check if things have changed and if
2763 // so apply updates to the database. This will ensure
2764 // that cascaded protections apply as soon as the changes
2767 # Get templates from templatelinks
2768 $id = $this->mTitle
->getArticleID();
2770 $tlTemplates = array();
2772 $dbr = wfGetDB( DB_SLAVE
);
2773 $res = $dbr->select( array( 'templatelinks' ),
2774 array( 'tl_namespace', 'tl_title' ),
2775 array( 'tl_from' => $id ),
2779 foreach ( $res as $row ) {
2780 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2783 # Get templates from parser output.
2784 $poTemplates = array();
2785 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2786 foreach ( $templates as $dbk => $id ) {
2787 $poTemplates["$ns:$dbk"] = true;
2792 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2794 if ( count( $templates_diff ) > 0 ) {
2795 # Whee, link updates time.
2796 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2802 * Return a list of templates used by this article.
2803 * Uses the templatelinks table
2805 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2806 * @return Array of Title objects
2808 public function getUsedTemplates() {
2809 return $this->mTitle
->getTemplateLinksFrom();
2813 * Perform article updates on a special page creation.
2815 * @param $rev Revision object
2817 * @todo This is a shitty interface function. Kill it and replace the
2818 * other shitty functions like doEditUpdates and such so it's not needed
2820 * @deprecated since 1.18, use doEditUpdates()
2822 public function createUpdates( $rev ) {
2823 wfDeprecated( __METHOD__
, '1.18' );
2825 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2829 * This function is called right before saving the wikitext,
2830 * so we can do things like signatures and links-in-context.
2832 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2833 * @param $text String article contents
2834 * @param $user User object: user doing the edit
2835 * @param $popts ParserOptions object: parser options, default options for
2836 * the user loaded if null given
2837 * @return string article contents with altered wikitext markup (signatures
2838 * converted, {{subst:}}, templates, etc.)
2840 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2841 global $wgParser, $wgUser;
2843 wfDeprecated( __METHOD__
, '1.19' );
2845 $user = is_null( $user ) ?
$wgUser : $user;
2847 if ( $popts === null ) {
2848 $popts = ParserOptions
::newFromUser( $user );
2851 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2855 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2857 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2860 public function isBigDeletion() {
2861 wfDeprecated( __METHOD__
, '1.19' );
2862 return $this->mTitle
->isBigDeletion();
2866 * Get the approximate revision count of this page.
2868 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2871 public function estimateRevisionCount() {
2872 wfDeprecated( __METHOD__
, '1.19' );
2873 return $this->mTitle
->estimateRevisionCount();
2877 * Update the article's restriction field, and leave a log entry.
2879 * @deprecated since 1.19
2880 * @param $limit Array: set of restriction keys
2881 * @param $reason String
2882 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2883 * @param $expiry Array: per restriction type expiration
2884 * @param $user User The user updating the restrictions
2885 * @return bool true on success
2887 public function updateRestrictions(
2888 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2892 $user = is_null( $user ) ?
$wgUser : $user;
2894 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2898 * @deprecated since 1.18
2900 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2901 wfDeprecated( __METHOD__
, '1.18' );
2903 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2907 * @deprecated since 1.18
2909 public function viewUpdates() {
2910 wfDeprecated( __METHOD__
, '1.18' );
2912 return $this->doViewUpdates( $wgUser );
2916 * @deprecated since 1.18
2919 public function useParserCache( $oldid ) {
2920 wfDeprecated( __METHOD__
, '1.18' );
2922 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2926 class PoolWorkArticleView
extends PoolCounterWork
{
2944 * @var ParserOptions
2946 private $parserOptions;
2954 * @var ParserOutput|bool
2956 private $parserOutput = false;
2961 private $isDirty = false;
2966 private $error = false;
2972 * @param $revid Integer: ID of the revision being parsed
2973 * @param $useParserCache Boolean: whether to use the parser cache
2974 * @param $parserOptions parserOptions to use for the parse operation
2975 * @param $text String: text to parse or null to load it
2977 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2978 $this->page
= $page;
2979 $this->revid
= $revid;
2980 $this->cacheable
= $useParserCache;
2981 $this->parserOptions
= $parserOptions;
2982 $this->text
= $text;
2983 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2984 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2988 * Get the ParserOutput from this object, or false in case of failure
2990 * @return ParserOutput
2992 public function getParserOutput() {
2993 return $this->parserOutput
;
2997 * Get whether the ParserOutput is a dirty one (i.e. expired)
3001 public function getIsDirty() {
3002 return $this->isDirty
;
3006 * Get a Status object in case of error or false otherwise
3008 * @return Status|bool
3010 public function getError() {
3011 return $this->error
;
3018 global $wgParser, $wgUseFileCache;
3020 $isCurrent = $this->revid
=== $this->page
->getLatest();
3022 if ( $this->text
!== null ) {
3023 $text = $this->text
;
3024 } elseif ( $isCurrent ) {
3025 $text = $this->page
->getRawText();
3027 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3028 if ( $rev === null ) {
3031 $text = $rev->getText();
3034 $time = - microtime( true );
3035 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
3036 $this->parserOptions
, true, true, $this->revid
);
3037 $time +
= microtime( true );
3041 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3042 $this->page
->getTitle()->getPrefixedDBkey() ) );
3045 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3046 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3049 // Make sure file cache is not used on uncacheable content.
3050 // Output that has magic words in it can still use the parser cache
3051 // (if enabled), though it will generally expire sooner.
3052 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3053 $wgUseFileCache = false;
3057 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3066 function getCachedWork() {
3067 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3069 if ( $this->parserOutput
=== false ) {
3070 wfDebug( __METHOD__
. ": parser cache miss\n" );
3073 wfDebug( __METHOD__
. ": parser cache hit\n" );
3081 function fallback() {
3082 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3084 if ( $this->parserOutput
=== false ) {
3085 wfDebugLog( 'dirty', "dirty missing\n" );
3086 wfDebug( __METHOD__
. ": no dirty cache\n" );
3089 wfDebug( __METHOD__
. ": sending dirty output\n" );
3090 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3091 $this->isDirty
= true;
3097 * @param $status Status
3100 function error( $status ) {
3101 $this->error
= $status;