Move to EP untill slush ends
[mediawiki.git] / includes / WikiPage.php
blob53330b8982115bbb579ad0369f3038a3630e9166
1 <?php
2 /**
3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
4 */
5 abstract class Page {}
7 /**
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
18 // not being deleted
20 /**
21 * Delete operation aborted by hook
23 const DELETE_HOOK_ABORTED = -1;
25 /**
26 * Deletion successful
28 const DELETE_SUCCESS = 0;
30 /**
31 * Page not found
33 const DELETE_NO_PAGE = 1;
35 /**
36 * No revisions found to delete
38 const DELETE_NO_REVISIONS = 2;
40 /**
41 * @var Title
43 public $mTitle = null;
45 /**@{{
46 * @protected
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
51 public $mPreparedEdit = false; // !< Array
52 /**@}}*/
54 /**
55 * @var Title
57 protected $mRedirectTarget = null;
59 /**
60 * @var Revision
62 protected $mLastRevision = null;
64 /**
65 * @var string; timestamp of the current revision or empty string if not loaded
67 protected $mTimestamp = '';
69 /**
70 * @var string
72 protected $mTouched = '19700101000000';
74 /**
75 * @var int|null
77 protected $mCounter = null;
79 /**
80 * Constructor and clear the article
81 * @param $title Title Reference to a Title object.
83 public function __construct( Title $title ) {
84 $this->mTitle = $title;
87 /**
88 * Create a WikiPage object of the appropriate class for the given title.
90 * @param $title Title
91 * @return WikiPage object of the appropriate type
93 public static function factory( Title $title ) {
94 $ns = $title->getNamespace();
96 if ( $ns == NS_MEDIA ) {
97 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
98 } elseif ( $ns < 0 ) {
99 throw new MWException( "Invalid or virtual namespace $ns given." );
102 switch ( $ns ) {
103 case NS_FILE:
104 $page = new WikiFilePage( $title );
105 break;
106 case NS_CATEGORY:
107 $page = new WikiCategoryPage( $title );
108 break;
109 default:
110 $page = new WikiPage( $title );
113 return $page;
117 * Constructor from a page id
119 * @param $id Int article ID to load
121 * @return WikiPage
123 public static function newFromID( $id ) {
124 $t = Title::newFromID( $id );
125 if ( $t ) {
126 return self::factory( $t );
128 return null;
132 * Returns overrides for action handlers.
133 * Classes listed here will be used instead of the default one when
134 * (and only when) $wgActions[$action] === true. This allows subclasses
135 * to override the default behavior.
137 * @todo: move this UI stuff somewhere else
139 * @return Array
141 public function getActionOverrides() {
142 return array();
146 * Get the title object of the article
147 * @return Title object of this page
149 public function getTitle() {
150 return $this->mTitle;
154 * Clear the object
156 public function clear() {
157 $this->mDataLoaded = false;
159 $this->mCounter = null;
160 $this->mRedirectTarget = null; # Title object if set
161 $this->mLastRevision = null; # Latest revision
162 $this->mTouched = '19700101000000';
163 $this->mTimestamp = '';
164 $this->mIsRedirect = false;
165 $this->mLatest = false;
166 $this->mPreparedEdit = false;
170 * Return the list of revision fields that should be selected to create
171 * a new page.
173 * @return array
175 public static function selectFields() {
176 return array(
177 'page_id',
178 'page_namespace',
179 'page_title',
180 'page_restrictions',
181 'page_counter',
182 'page_is_redirect',
183 'page_is_new',
184 'page_random',
185 'page_touched',
186 'page_latest',
187 'page_len',
192 * Fetch a page record with the given conditions
193 * @param $dbr DatabaseBase object
194 * @param $conditions Array
195 * @return mixed Database result resource, or false on failure
197 protected function pageData( $dbr, $conditions ) {
198 $fields = self::selectFields();
200 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
202 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__ );
204 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
206 return $row;
210 * Fetch a page record matching the Title object's namespace and title
211 * using a sanitized title string
213 * @param $dbr DatabaseBase object
214 * @param $title Title object
215 * @return mixed Database result resource, or false on failure
217 public function pageDataFromTitle( $dbr, $title ) {
218 return $this->pageData( $dbr, array(
219 'page_namespace' => $title->getNamespace(),
220 'page_title' => $title->getDBkey() ) );
224 * Fetch a page record matching the requested ID
226 * @param $dbr DatabaseBase
227 * @param $id Integer
228 * @return mixed Database result resource, or false on failure
230 public function pageDataFromId( $dbr, $id ) {
231 return $this->pageData( $dbr, array( 'page_id' => $id ) );
235 * Set the general counter, title etc data loaded from
236 * some source.
238 * @param $data Object|String One of the following:
239 * A DB query result object or...
240 * "fromdb" to get from a slave DB or...
241 * "fromdbmaster" to get from the master DB
242 * @return void
244 public function loadPageData( $data = 'fromdb' ) {
245 if ( $data === 'fromdbmaster' ) {
246 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
247 } elseif ( $data === 'fromdb' ) { // slave
248 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE ), $this->mTitle );
249 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
250 # Note that DB also stores the master position in the session and checks it.
251 $touched = $this->getCachedLastEditTime();
252 if ( $touched ) { // key set
253 if ( !$data || $touched > wfTimestamp( TS_MW, $data->page_touched ) ) {
254 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
259 $lc = LinkCache::singleton();
261 if ( $data ) {
262 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
264 $this->mTitle->loadFromRow( $data );
266 # Old-fashioned restrictions
267 $this->mTitle->loadRestrictions( $data->page_restrictions );
269 $this->mCounter = intval( $data->page_counter );
270 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
271 $this->mIsRedirect = intval( $data->page_is_redirect );
272 $this->mLatest = intval( $data->page_latest );
273 } else {
274 $lc->addBadLinkObj( $this->mTitle );
276 $this->mTitle->loadFromRow( false );
279 $this->mDataLoaded = true;
283 * @return int Page ID
285 public function getId() {
286 return $this->mTitle->getArticleID();
290 * @return bool Whether or not the page exists in the database
292 public function exists() {
293 return $this->mTitle->exists();
297 * Check if this page is something we're going to be showing
298 * some sort of sensible content for. If we return false, page
299 * views (plain action=view) will return an HTTP 404 response,
300 * so spiders and robots can know they're following a bad link.
302 * @return bool
304 public function hasViewableContent() {
305 return $this->mTitle->exists() || $this->mTitle->isAlwaysKnown();
309 * @return int The view count for the page
311 public function getCount() {
312 if ( !$this->mDataLoaded ) {
313 $this->loadPageData();
316 return $this->mCounter;
320 * Tests if the article text represents a redirect
322 * @param $text mixed string containing article contents, or boolean
323 * @return bool
325 public function isRedirect( $text = false ) {
326 if ( $text === false ) {
327 if ( !$this->mDataLoaded ) {
328 $this->loadPageData();
331 return (bool)$this->mIsRedirect;
332 } else {
333 return Title::newFromRedirect( $text ) !== null;
338 * Loads page_touched and returns a value indicating if it should be used
339 * @return boolean true if not a redirect
341 public function checkTouched() {
342 if ( !$this->mDataLoaded ) {
343 $this->loadPageData();
345 return !$this->mIsRedirect;
349 * Get the page_touched field
350 * @return string containing GMT timestamp
352 public function getTouched() {
353 if ( !$this->mDataLoaded ) {
354 $this->loadPageData();
356 return $this->mTouched;
360 * Get the page_latest field
361 * @return integer rev_id of current revision
363 public function getLatest() {
364 if ( !$this->mDataLoaded ) {
365 $this->loadPageData();
367 return (int)$this->mLatest;
371 * Loads everything except the text
372 * This isn't necessary for all uses, so it's only done if needed.
374 protected function loadLastEdit() {
375 if ( $this->mLastRevision !== null ) {
376 return; // already loaded
379 $latest = $this->getLatest();
380 if ( !$latest ) {
381 return; // page doesn't exist or is missing page_latest info
384 $revision = Revision::newFromPageId( $this->getId(), $latest );
385 if ( $revision ) { // sanity
386 $this->setLastEdit( $revision );
391 * Set the latest revision
393 protected function setLastEdit( Revision $revision ) {
394 $this->mLastRevision = $revision;
395 $this->mTimestamp = $revision->getTimestamp();
399 * Get the latest revision
400 * @return Revision|null
402 public function getRevision() {
403 $this->loadLastEdit();
404 if ( $this->mLastRevision ) {
405 return $this->mLastRevision;
407 return null;
411 * Get the text of the current revision. No side-effects...
413 * @param $audience Integer: one of:
414 * Revision::FOR_PUBLIC to be displayed to all users
415 * Revision::FOR_THIS_USER to be displayed to $wgUser
416 * Revision::RAW get the text regardless of permissions
417 * @return String|bool The text of the current revision. False on failure
419 public function getText( $audience = Revision::FOR_PUBLIC ) {
420 $this->loadLastEdit();
421 if ( $this->mLastRevision ) {
422 return $this->mLastRevision->getText( $audience );
424 return false;
428 * Get the text of the current revision. No side-effects...
430 * @return String|bool The text of the current revision. False on failure
432 public function getRawText() {
433 $this->loadLastEdit();
434 if ( $this->mLastRevision ) {
435 return $this->mLastRevision->getRawText();
437 return false;
441 * @return string MW timestamp of last article revision
443 public function getTimestamp() {
444 // Check if the field has been filled by WikiPage::setTimestamp()
445 if ( !$this->mTimestamp ) {
446 $this->loadLastEdit();
449 return wfTimestamp( TS_MW, $this->mTimestamp );
453 * Set the page timestamp (use only to avoid DB queries)
454 * @param $ts string MW timestamp of last article revision
455 * @return void
457 public function setTimestamp( $ts ) {
458 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
462 * @param $audience Integer: one of:
463 * Revision::FOR_PUBLIC to be displayed to all users
464 * Revision::FOR_THIS_USER to be displayed to $wgUser
465 * Revision::RAW get the text regardless of permissions
466 * @return int user ID for the user that made the last article revision
468 public function getUser( $audience = Revision::FOR_PUBLIC ) {
469 $this->loadLastEdit();
470 if ( $this->mLastRevision ) {
471 return $this->mLastRevision->getUser( $audience );
472 } else {
473 return -1;
478 * @param $audience Integer: one of:
479 * Revision::FOR_PUBLIC to be displayed to all users
480 * Revision::FOR_THIS_USER to be displayed to $wgUser
481 * Revision::RAW get the text regardless of permissions
482 * @return string username of the user that made the last article revision
484 public function getUserText( $audience = Revision::FOR_PUBLIC ) {
485 $this->loadLastEdit();
486 if ( $this->mLastRevision ) {
487 return $this->mLastRevision->getUserText( $audience );
488 } else {
489 return '';
494 * @param $audience Integer: one of:
495 * Revision::FOR_PUBLIC to be displayed to all users
496 * Revision::FOR_THIS_USER to be displayed to $wgUser
497 * Revision::RAW get the text regardless of permissions
498 * @return string Comment stored for the last article revision
500 public function getComment( $audience = Revision::FOR_PUBLIC ) {
501 $this->loadLastEdit();
502 if ( $this->mLastRevision ) {
503 return $this->mLastRevision->getComment( $audience );
504 } else {
505 return '';
510 * Returns true if last revision was marked as "minor edit"
512 * @return boolean Minor edit indicator for the last article revision.
514 public function getMinorEdit() {
515 $this->loadLastEdit();
516 if ( $this->mLastRevision ) {
517 return $this->mLastRevision->isMinor();
518 } else {
519 return false;
524 * Get the cached timestamp for the last time the page changed.
525 * This is only used to help handle slave lag by comparing to page_touched.
526 * @return string MW timestamp
528 protected function getCachedLastEditTime() {
529 global $wgMemc;
530 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
531 return $wgMemc->get( $key );
535 * Set the cached timestamp for the last time the page changed.
536 * This is only used to help handle slave lag by comparing to page_touched.
537 * @param $timestamp string
538 * @return void
540 public function setCachedLastEditTime( $timestamp ) {
541 global $wgMemc;
542 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
543 $wgMemc->set( $key, wfTimestamp( TS_MW, $timestamp ), 60*15 );
547 * Determine whether a page would be suitable for being counted as an
548 * article in the site_stats table based on the title & its content
550 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
551 * if false, the current database state will be used
552 * @return Boolean
554 public function isCountable( $editInfo = false ) {
555 global $wgArticleCountMethod;
557 if ( !$this->mTitle->isContentPage() ) {
558 return false;
561 $text = $editInfo ? $editInfo->pst : false;
563 if ( $this->isRedirect( $text ) ) {
564 return false;
567 switch ( $wgArticleCountMethod ) {
568 case 'any':
569 return true;
570 case 'comma':
571 if ( $text === false ) {
572 $text = $this->getRawText();
574 return strpos( $text, ',' ) !== false;
575 case 'link':
576 if ( $editInfo ) {
577 // ParserOutput::getLinks() is a 2D array of page links, so
578 // to be really correct we would need to recurse in the array
579 // but the main array should only have items in it if there are
580 // links.
581 return (bool)count( $editInfo->output->getLinks() );
582 } else {
583 return (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
584 array( 'pl_from' => $this->getId() ), __METHOD__ );
590 * If this page is a redirect, get its target
592 * The target will be fetched from the redirect table if possible.
593 * If this page doesn't have an entry there, call insertRedirect()
594 * @return Title|mixed object, or null if this page is not a redirect
596 public function getRedirectTarget() {
597 if ( !$this->mTitle->isRedirect() ) {
598 return null;
601 if ( $this->mRedirectTarget !== null ) {
602 return $this->mRedirectTarget;
605 # Query the redirect table
606 $dbr = wfGetDB( DB_SLAVE );
607 $row = $dbr->selectRow( 'redirect',
608 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
609 array( 'rd_from' => $this->getId() ),
610 __METHOD__
613 // rd_fragment and rd_interwiki were added later, populate them if empty
614 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
615 return $this->mRedirectTarget = Title::makeTitle(
616 $row->rd_namespace, $row->rd_title,
617 $row->rd_fragment, $row->rd_interwiki );
620 # This page doesn't have an entry in the redirect table
621 return $this->mRedirectTarget = $this->insertRedirect();
625 * Insert an entry for this page into the redirect table.
627 * Don't call this function directly unless you know what you're doing.
628 * @return Title object or null if not a redirect
630 public function insertRedirect() {
631 // recurse through to only get the final target
632 $retval = Title::newFromRedirectRecurse( $this->getRawText() );
633 if ( !$retval ) {
634 return null;
636 $this->insertRedirectEntry( $retval );
637 return $retval;
641 * Insert or update the redirect table entry for this page to indicate
642 * it redirects to $rt .
643 * @param $rt Title redirect target
645 public function insertRedirectEntry( $rt ) {
646 $dbw = wfGetDB( DB_MASTER );
647 $dbw->replace( 'redirect', array( 'rd_from' ),
648 array(
649 'rd_from' => $this->getId(),
650 'rd_namespace' => $rt->getNamespace(),
651 'rd_title' => $rt->getDBkey(),
652 'rd_fragment' => $rt->getFragment(),
653 'rd_interwiki' => $rt->getInterwiki(),
655 __METHOD__
660 * Get the Title object or URL this page redirects to
662 * @return mixed false, Title of in-wiki target, or string with URL
664 public function followRedirect() {
665 return $this->getRedirectURL( $this->getRedirectTarget() );
669 * Get the Title object or URL to use for a redirect. We use Title
670 * objects for same-wiki, non-special redirects and URLs for everything
671 * else.
672 * @param $rt Title Redirect target
673 * @return mixed false, Title object of local target, or string with URL
675 public function getRedirectURL( $rt ) {
676 if ( !$rt ) {
677 return false;
680 if ( $rt->isExternal() ) {
681 if ( $rt->isLocal() ) {
682 // Offsite wikis need an HTTP redirect.
684 // This can be hard to reverse and may produce loops,
685 // so they may be disabled in the site configuration.
686 $source = $this->mTitle->getFullURL( 'redirect=no' );
687 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
688 } else {
689 // External pages pages without "local" bit set are not valid
690 // redirect targets
691 return false;
695 if ( $rt->isSpecialPage() ) {
696 // Gotta handle redirects to special pages differently:
697 // Fill the HTTP response "Location" header and ignore
698 // the rest of the page we're on.
700 // Some pages are not valid targets
701 if ( $rt->isValidRedirectTarget() ) {
702 return $rt->getFullURL();
703 } else {
704 return false;
708 return $rt;
712 * Get a list of users who have edited this article, not including the user who made
713 * the most recent revision, which you can get from $article->getUser() if you want it
714 * @return UserArrayFromResult
716 public function getContributors() {
717 # @todo FIXME: This is expensive; cache this info somewhere.
719 $dbr = wfGetDB( DB_SLAVE );
721 if ( $dbr->implicitGroupby() ) {
722 $realNameField = 'user_real_name';
723 } else {
724 $realNameField = 'MIN(user_real_name) AS user_real_name';
727 $tables = array( 'revision', 'user' );
729 $fields = array(
730 'rev_user as user_id',
731 'rev_user_text AS user_name',
732 $realNameField,
733 'MAX(rev_timestamp) AS timestamp',
736 $conds = array( 'rev_page' => $this->getId() );
738 // The user who made the top revision gets credited as "this page was last edited by
739 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
740 $user = $this->getUser();
741 if ( $user ) {
742 $conds[] = "rev_user != $user";
743 } else {
744 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
747 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
749 $jconds = array(
750 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
753 $options = array(
754 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
755 'ORDER BY' => 'timestamp DESC',
758 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
759 return new UserArrayFromResult( $res );
763 * Get the last N authors
764 * @param $num Integer: number of revisions to get
765 * @param $revLatest String: the latest rev_id, selected from the master (optional)
766 * @return array Array of authors, duplicates not removed
768 public function getLastNAuthors( $num, $revLatest = 0 ) {
769 wfProfileIn( __METHOD__ );
770 // First try the slave
771 // If that doesn't have the latest revision, try the master
772 $continue = 2;
773 $db = wfGetDB( DB_SLAVE );
775 do {
776 $res = $db->select( array( 'page', 'revision' ),
777 array( 'rev_id', 'rev_user_text' ),
778 array(
779 'page_namespace' => $this->mTitle->getNamespace(),
780 'page_title' => $this->mTitle->getDBkey(),
781 'rev_page = page_id'
782 ), __METHOD__,
783 array(
784 'ORDER BY' => 'rev_timestamp DESC',
785 'LIMIT' => $num
789 if ( !$res ) {
790 wfProfileOut( __METHOD__ );
791 return array();
794 $row = $db->fetchObject( $res );
796 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
797 $db = wfGetDB( DB_MASTER );
798 $continue--;
799 } else {
800 $continue = 0;
802 } while ( $continue );
804 $authors = array( $row->rev_user_text );
806 foreach ( $res as $row ) {
807 $authors[] = $row->rev_user_text;
810 wfProfileOut( __METHOD__ );
811 return $authors;
815 * Should the parser cache be used?
817 * @param $parserOptions ParserOptions to check
818 * @param $oldid int
819 * @return boolean
821 public function isParserCacheUsed( ParserOptions $parserOptions, $oldid ) {
822 global $wgEnableParserCache;
824 return $wgEnableParserCache
825 && $parserOptions->getStubThreshold() == 0
826 && $this->mTitle->exists()
827 && ( $oldid === null || $oldid === 0 || $oldid === $this->getLatest() )
828 && $this->mTitle->isWikitextPage();
832 * Get a ParserOutput for the given ParserOptions and revision ID.
833 * The parser cache will be used if possible.
835 * @since 1.19
836 * @param $parserOptions ParserOptions to use for the parse operation
837 * @param $oldid Revision ID to get the text from, passing null or 0 will
838 * get the current revision (default value)
839 * @return ParserOutput or false if the revision was not found
841 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
842 wfProfileIn( __METHOD__ );
844 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
845 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
846 if ( $parserOptions->getStubThreshold() ) {
847 wfIncrStats( 'pcache_miss_stub' );
850 if ( $useParserCache ) {
851 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
852 if ( $parserOutput !== false ) {
853 wfProfileOut( __METHOD__ );
854 return $parserOutput;
858 if ( $oldid === null || $oldid === 0 ) {
859 $oldid = $this->getLatest();
862 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
863 $pool->execute();
865 wfProfileOut( __METHOD__ );
867 return $pool->getParserOutput();
871 * Do standard deferred updates after page view
872 * @param $user User The relevant user
874 public function doViewUpdates( User $user ) {
875 global $wgDisableCounters;
876 if ( wfReadOnly() ) {
877 return;
880 # Don't update page view counters on views from bot users (bug 14044)
881 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle->exists() ) {
882 DeferredUpdates::addUpdate( new ViewCountUpdate( $this->getId() ) );
883 DeferredUpdates::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
886 # Update newtalk / watchlist notification status
887 $user->clearNotification( $this->mTitle );
891 * Perform the actions of a page purging
892 * @return bool
894 public function doPurge() {
895 global $wgUseSquid;
897 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
898 return false;
901 // Invalidate the cache
902 $this->mTitle->invalidateCache();
903 $this->clear();
905 if ( $wgUseSquid ) {
906 // Commit the transaction before the purge is sent
907 $dbw = wfGetDB( DB_MASTER );
908 $dbw->commit();
910 // Send purge
911 $update = SquidUpdate::newSimplePurge( $this->mTitle );
912 $update->doUpdate();
915 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
916 if ( $this->mTitle->exists() ) {
917 $text = $this->getRawText();
918 } else {
919 $text = false;
922 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
924 return true;
928 * Insert a new empty page record for this article.
929 * This *must* be followed up by creating a revision
930 * and running $this->updateRevisionOn( ... );
931 * or else the record will be left in a funky state.
932 * Best if all done inside a transaction.
934 * @param $dbw DatabaseBase
935 * @return int The newly created page_id key, or false if the title already existed
937 public function insertOn( $dbw ) {
938 wfProfileIn( __METHOD__ );
940 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
941 $dbw->insert( 'page', array(
942 'page_id' => $page_id,
943 'page_namespace' => $this->mTitle->getNamespace(),
944 'page_title' => $this->mTitle->getDBkey(),
945 'page_counter' => 0,
946 'page_restrictions' => '',
947 'page_is_redirect' => 0, # Will set this shortly...
948 'page_is_new' => 1,
949 'page_random' => wfRandom(),
950 'page_touched' => $dbw->timestamp(),
951 'page_latest' => 0, # Fill this in shortly...
952 'page_len' => 0, # Fill this in shortly...
953 ), __METHOD__, 'IGNORE' );
955 $affected = $dbw->affectedRows();
957 if ( $affected ) {
958 $newid = $dbw->insertId();
959 $this->mTitle->resetArticleID( $newid );
961 wfProfileOut( __METHOD__ );
963 return $affected ? $newid : false;
967 * Update the page record to point to a newly saved revision.
969 * @param $dbw DatabaseBase: object
970 * @param $revision Revision: For ID number, and text used to set
971 * length and redirect status fields
972 * @param $lastRevision Integer: if given, will not overwrite the page field
973 * when different from the currently set value.
974 * Giving 0 indicates the new page flag should be set
975 * on.
976 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
977 * removing rows in redirect table.
978 * @return bool true on success, false on failure
979 * @private
981 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
982 wfProfileIn( __METHOD__ );
984 $text = $revision->getText();
985 $len = strlen( $text );
986 $rt = Title::newFromRedirectRecurse( $text );
988 $conditions = array( 'page_id' => $this->getId() );
990 if ( !is_null( $lastRevision ) ) {
991 # An extra check against threads stepping on each other
992 $conditions['page_latest'] = $lastRevision;
995 $now = wfTimestampNow();
996 $dbw->update( 'page',
997 array( /* SET */
998 'page_latest' => $revision->getId(),
999 'page_touched' => $dbw->timestamp( $now ),
1000 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1001 'page_is_redirect' => $rt !== null ? 1 : 0,
1002 'page_len' => $len,
1004 $conditions,
1005 __METHOD__ );
1007 $result = $dbw->affectedRows() != 0;
1008 if ( $result ) {
1009 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1010 $this->setLastEdit( $revision );
1011 $this->setCachedLastEditTime( $now );
1012 $this->mLatest = $revision->getId();
1013 $this->mIsRedirect = (bool)$rt;
1014 # Update the LinkCache.
1015 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect, $this->mLatest );
1018 wfProfileOut( __METHOD__ );
1019 return $result;
1023 * Add row to the redirect table if this is a redirect, remove otherwise.
1025 * @param $dbw DatabaseBase
1026 * @param $redirectTitle Title object pointing to the redirect target,
1027 * or NULL if this is not a redirect
1028 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1029 * removing rows in redirect table.
1030 * @return bool true on success, false on failure
1031 * @private
1033 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1034 // Always update redirects (target link might have changed)
1035 // Update/Insert if we don't know if the last revision was a redirect or not
1036 // Delete if changing from redirect to non-redirect
1037 $isRedirect = !is_null( $redirectTitle );
1039 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1040 return true;
1043 wfProfileIn( __METHOD__ );
1044 if ( $isRedirect ) {
1045 $this->insertRedirectEntry( $redirectTitle );
1046 } else {
1047 // This is not a redirect, remove row from redirect table
1048 $where = array( 'rd_from' => $this->getId() );
1049 $dbw->delete( 'redirect', $where, __METHOD__ );
1052 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1053 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1055 wfProfileOut( __METHOD__ );
1057 return ( $dbw->affectedRows() != 0 );
1061 * If the given revision is newer than the currently set page_latest,
1062 * update the page record. Otherwise, do nothing.
1064 * @param $dbw DatabaseBase object
1065 * @param $revision Revision object
1066 * @return mixed
1068 public function updateIfNewerOn( $dbw, $revision ) {
1069 wfProfileIn( __METHOD__ );
1071 $row = $dbw->selectRow(
1072 array( 'revision', 'page' ),
1073 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1074 array(
1075 'page_id' => $this->getId(),
1076 'page_latest=rev_id' ),
1077 __METHOD__ );
1079 if ( $row ) {
1080 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1081 wfProfileOut( __METHOD__ );
1082 return false;
1084 $prev = $row->rev_id;
1085 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1086 } else {
1087 # No or missing previous revision; mark the page as new
1088 $prev = 0;
1089 $lastRevIsRedirect = null;
1092 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1094 wfProfileOut( __METHOD__ );
1095 return $ret;
1099 * Get the text that needs to be saved in order to undo all revisions
1100 * between $undo and $undoafter. Revisions must belong to the same page,
1101 * must exist and must not be deleted
1102 * @param $undo Revision
1103 * @param $undoafter Revision Must be an earlier revision than $undo
1104 * @return mixed string on success, false on failure
1106 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1107 $cur_text = $this->getRawText();
1108 if ( $cur_text === false ) {
1109 return false; // no page
1111 $undo_text = $undo->getText();
1112 $undoafter_text = $undoafter->getText();
1114 if ( $cur_text == $undo_text ) {
1115 # No use doing a merge if it's just a straight revert.
1116 return $undoafter_text;
1119 $undone_text = '';
1121 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1122 return false;
1125 return $undone_text;
1129 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1130 * @param $text String: new text of the section
1131 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1132 * @param $edittime String: revision timestamp or null to use the current revision
1133 * @return string Complete article text, or null if error
1135 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1136 wfProfileIn( __METHOD__ );
1138 if ( strval( $section ) == '' ) {
1139 // Whole-page edit; let the whole text through
1140 } else {
1141 // Bug 30711: always use current version when adding a new section
1142 if ( is_null( $edittime ) || $section == 'new' ) {
1143 $oldtext = $this->getRawText();
1144 if ( $oldtext === false ) {
1145 wfDebug( __METHOD__ . ": no page text\n" );
1146 wfProfileOut( __METHOD__ );
1147 return null;
1149 } else {
1150 $dbw = wfGetDB( DB_MASTER );
1151 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1153 if ( !$rev ) {
1154 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1155 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1156 wfProfileOut( __METHOD__ );
1157 return null;
1160 $oldtext = $rev->getText();
1163 if ( $section == 'new' ) {
1164 # Inserting a new section
1165 $subject = $sectionTitle ? wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1166 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1167 $text = strlen( trim( $oldtext ) ) > 0
1168 ? "{$oldtext}\n\n{$subject}{$text}"
1169 : "{$subject}{$text}";
1171 } else {
1172 # Replacing an existing section; roll out the big guns
1173 global $wgParser;
1175 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1179 wfProfileOut( __METHOD__ );
1180 return $text;
1184 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1185 * @param $flags Int
1186 * @return Int updated $flags
1188 function checkFlags( $flags ) {
1189 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1190 if ( $this->mTitle->getArticleID() ) {
1191 $flags |= EDIT_UPDATE;
1192 } else {
1193 $flags |= EDIT_NEW;
1197 return $flags;
1201 * Change an existing article or create a new article. Updates RC and all necessary caches,
1202 * optionally via the deferred update array.
1204 * @param $text String: new text
1205 * @param $summary String: edit summary
1206 * @param $flags Integer bitfield:
1207 * EDIT_NEW
1208 * Article is known or assumed to be non-existent, create a new one
1209 * EDIT_UPDATE
1210 * Article is known or assumed to be pre-existing, update it
1211 * EDIT_MINOR
1212 * Mark this edit minor, if the user is allowed to do so
1213 * EDIT_SUPPRESS_RC
1214 * Do not log the change in recentchanges
1215 * EDIT_FORCE_BOT
1216 * Mark the edit a "bot" edit regardless of user rights
1217 * EDIT_DEFER_UPDATES
1218 * Defer some of the updates until the end of index.php
1219 * EDIT_AUTOSUMMARY
1220 * Fill in blank summaries with generated text where possible
1222 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1223 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1224 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1225 * edit-already-exists error will be returned. These two conditions are also possible with
1226 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1228 * @param $baseRevId int the revision ID this edit was based off, if any
1229 * @param $user User the user doing the edit
1231 * @return Status object. Possible errors:
1232 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1233 * edit-gone-missing: In update mode, but the article didn't exist
1234 * edit-conflict: In update mode, the article changed unexpectedly
1235 * edit-no-change: Warning that the text was the same as before
1236 * edit-already-exists: In creation mode, but the article already exists
1238 * Extensions may define additional errors.
1240 * $return->value will contain an associative array with members as follows:
1241 * new: Boolean indicating if the function attempted to create a new article
1242 * revision: The revision object for the inserted revision, or null
1244 * Compatibility note: this function previously returned a boolean value indicating success/failure
1246 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1247 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1249 # Low-level sanity check
1250 if ( $this->mTitle->getText() === '' ) {
1251 throw new MWException( 'Something is trying to edit an article with an empty title' );
1254 wfProfileIn( __METHOD__ );
1256 $user = is_null( $user ) ? $wgUser : $user;
1257 $status = Status::newGood( array() );
1259 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1260 $this->loadPageData( 'fromdbmaster' );
1262 $flags = $this->checkFlags( $flags );
1264 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1265 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1267 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1269 if ( $status->isOK() ) {
1270 $status->fatal( 'edit-hook-aborted' );
1273 wfProfileOut( __METHOD__ );
1274 return $status;
1277 # Silently ignore EDIT_MINOR if not allowed
1278 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1279 $bot = $flags & EDIT_FORCE_BOT;
1281 $oldtext = $this->getRawText(); // current revision
1282 $oldsize = strlen( $oldtext );
1283 $oldid = $this->getLatest();
1284 $oldIsRedirect = $this->isRedirect();
1285 $oldcountable = $this->isCountable();
1287 # Provide autosummaries if one is not provided and autosummaries are enabled.
1288 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1289 $summary = self::getAutosummary( $oldtext, $text, $flags );
1292 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1293 $text = $editInfo->pst;
1294 $newsize = strlen( $text );
1296 $dbw = wfGetDB( DB_MASTER );
1297 $now = wfTimestampNow();
1298 $this->mTimestamp = $now;
1300 if ( $flags & EDIT_UPDATE ) {
1301 # Update article, but only if changed.
1302 $status->value['new'] = false;
1304 if ( !$oldid ) {
1305 # Article gone missing
1306 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1307 $status->fatal( 'edit-gone-missing' );
1309 wfProfileOut( __METHOD__ );
1310 return $status;
1313 # Make sure the revision is either completely inserted or not inserted at all
1314 if ( !$wgDBtransactions ) {
1315 $userAbort = ignore_user_abort( true );
1318 $revision = new Revision( array(
1319 'page' => $this->getId(),
1320 'comment' => $summary,
1321 'minor_edit' => $isminor,
1322 'text' => $text,
1323 'parent_id' => $oldid,
1324 'user' => $user->getId(),
1325 'user_text' => $user->getName(),
1326 'timestamp' => $now
1327 ) );
1329 $changed = ( strcmp( $text, $oldtext ) != 0 );
1331 if ( $changed ) {
1332 $dbw->begin();
1333 $revisionId = $revision->insertOn( $dbw );
1335 # Update page
1337 # Note that we use $this->mLatest instead of fetching a value from the master DB
1338 # during the course of this function. This makes sure that EditPage can detect
1339 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1340 # before this function is called. A previous function used a separate query, this
1341 # creates a window where concurrent edits can cause an ignored edit conflict.
1342 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1344 if ( !$ok ) {
1345 /* Belated edit conflict! Run away!! */
1346 $status->fatal( 'edit-conflict' );
1348 # Delete the invalid revision if the DB is not transactional
1349 if ( !$wgDBtransactions ) {
1350 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1353 $revisionId = 0;
1354 $dbw->rollback();
1355 } else {
1356 global $wgUseRCPatrol;
1357 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1358 # Update recentchanges
1359 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1360 # Mark as patrolled if the user can do so
1361 $patrolled = $wgUseRCPatrol && !count(
1362 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1363 # Add RC row to the DB
1364 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1365 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1366 $revisionId, $patrolled
1369 # Log auto-patrolled edits
1370 if ( $patrolled ) {
1371 PatrolLog::record( $rc, true );
1374 $user->incEditCount();
1375 $dbw->commit();
1377 } else {
1378 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1379 // related variables correctly
1380 $revision->setId( $this->getLatest() );
1383 if ( !$wgDBtransactions ) {
1384 ignore_user_abort( $userAbort );
1387 // Now that ignore_user_abort is restored, we can respond to fatal errors
1388 if ( !$status->isOK() ) {
1389 wfProfileOut( __METHOD__ );
1390 return $status;
1393 # Update links tables, site stats, etc.
1394 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1395 'oldcountable' => $oldcountable ) );
1397 if ( !$changed ) {
1398 $status->warning( 'edit-no-change' );
1399 $revision = null;
1400 // Update page_touched, this is usually implicit in the page update
1401 // Other cache updates are done in onArticleEdit()
1402 $this->mTitle->invalidateCache();
1404 } else {
1405 # Create new article
1406 $status->value['new'] = true;
1408 $dbw->begin();
1410 # Add the page record; stake our claim on this title!
1411 # This will return false if the article already exists
1412 $newid = $this->insertOn( $dbw );
1414 if ( $newid === false ) {
1415 $dbw->rollback();
1416 $status->fatal( 'edit-already-exists' );
1418 wfProfileOut( __METHOD__ );
1419 return $status;
1422 # Save the revision text...
1423 $revision = new Revision( array(
1424 'page' => $newid,
1425 'comment' => $summary,
1426 'minor_edit' => $isminor,
1427 'text' => $text,
1428 'user' => $user->getId(),
1429 'user_text' => $user->getName(),
1430 'timestamp' => $now
1431 ) );
1432 $revisionId = $revision->insertOn( $dbw );
1434 # Update the page record with revision data
1435 $this->updateRevisionOn( $dbw, $revision, 0 );
1437 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1439 # Update recentchanges
1440 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1441 global $wgUseRCPatrol, $wgUseNPPatrol;
1443 # Mark as patrolled if the user can do so
1444 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1445 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1446 # Add RC row to the DB
1447 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1448 '', strlen( $text ), $revisionId, $patrolled );
1450 # Log auto-patrolled edits
1451 if ( $patrolled ) {
1452 PatrolLog::record( $rc, true );
1455 $user->incEditCount();
1456 $dbw->commit();
1458 # Update links, etc.
1459 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1461 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1462 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1465 # Do updates right now unless deferral was requested
1466 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1467 DeferredUpdates::doUpdates();
1470 // Return the new revision (or null) to the caller
1471 $status->value['revision'] = $revision;
1473 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1474 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1476 # Promote user to any groups they meet the criteria for
1477 $user->addAutopromoteOnceGroups( 'onEdit' );
1479 wfProfileOut( __METHOD__ );
1480 return $status;
1484 * Get parser options suitable for rendering the primary article wikitext
1485 * @param User|string $user User object or 'canonical'
1486 * @return ParserOptions
1488 public function makeParserOptions( $user ) {
1489 global $wgContLang;
1490 if ( $user instanceof User ) { // settings per user (even anons)
1491 $options = ParserOptions::newFromUser( $user );
1492 } else { // canonical settings
1493 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
1495 $options->enableLimitReport(); // show inclusion/loop reports
1496 $options->setTidy( true ); // fix bad HTML
1497 return $options;
1501 * Prepare text which is about to be saved.
1502 * Returns a stdclass with source, pst and output members
1503 * @return bool|object
1505 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1506 global $wgParser, $wgContLang, $wgUser;
1507 $user = is_null( $user ) ? $wgUser : $user;
1508 // @TODO fixme: check $user->getId() here???
1509 if ( $this->mPreparedEdit
1510 && $this->mPreparedEdit->newText == $text
1511 && $this->mPreparedEdit->revid == $revid
1513 // Already prepared
1514 return $this->mPreparedEdit;
1517 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
1518 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1520 $edit = (object)array();
1521 $edit->revid = $revid;
1522 $edit->newText = $text;
1523 $edit->pst = $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
1524 $edit->popts = $this->makeParserOptions( 'canonical' );
1525 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
1526 $edit->oldText = $this->getRawText();
1528 $this->mPreparedEdit = $edit;
1530 return $edit;
1534 * Do standard deferred updates after page edit.
1535 * Update links tables, site stats, search index and message cache.
1536 * Purges pages that include this page if the text was changed here.
1537 * Every 100th edit, prune the recent changes table.
1539 * @private
1540 * @param $revision Revision object
1541 * @param $user User object that did the revision
1542 * @param $options Array of options, following indexes are used:
1543 * - changed: boolean, whether the revision changed the content (default true)
1544 * - created: boolean, whether the revision created the page (default false)
1545 * - oldcountable: boolean or null (default null):
1546 * - boolean: whether the page was counted as an article before that
1547 * revision, only used in changed is true and created is false
1548 * - null: don't change the article count
1550 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
1551 global $wgEnableParserCache;
1553 wfProfileIn( __METHOD__ );
1555 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1556 $text = $revision->getText();
1558 # Parse the text
1559 # Be careful not to double-PST: $text is usually already PST-ed once
1560 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
1561 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
1562 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1563 } else {
1564 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
1565 $editInfo = $this->mPreparedEdit;
1568 # Save it to the parser cache
1569 if ( $wgEnableParserCache ) {
1570 $parserCache = ParserCache::singleton();
1571 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
1574 # Update the links tables
1575 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
1576 $u->doUpdate();
1578 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1580 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1581 if ( 0 == mt_rand( 0, 99 ) ) {
1582 // Flush old entries from the `recentchanges` table; we do this on
1583 // random requests so as to avoid an increase in writes for no good reason
1584 global $wgRCMaxAge;
1586 $dbw = wfGetDB( DB_MASTER );
1587 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1588 $dbw->delete(
1589 'recentchanges',
1590 array( "rc_timestamp < '$cutoff'" ),
1591 __METHOD__
1596 if ( !$this->mTitle->exists() ) {
1597 wfProfileOut( __METHOD__ );
1598 return;
1601 $id = $this->getId();
1602 $title = $this->mTitle->getPrefixedDBkey();
1603 $shortTitle = $this->mTitle->getDBkey();
1605 if ( !$options['changed'] ) {
1606 $good = 0;
1607 $total = 0;
1608 } elseif ( $options['created'] ) {
1609 $good = (int)$this->isCountable( $editInfo );
1610 $total = 1;
1611 } elseif ( $options['oldcountable'] !== null ) {
1612 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1613 $total = 0;
1614 } else {
1615 $good = 0;
1616 $total = 0;
1619 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1620 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $text ) );
1622 # If this is another user's talk page, update newtalk.
1623 # Don't do this if $options['changed'] = false (null-edits) nor if
1624 # it's a minor edit and the user doesn't want notifications for those.
1625 if ( $options['changed']
1626 && $this->mTitle->getNamespace() == NS_USER_TALK
1627 && $shortTitle != $user->getTitleKey()
1628 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1630 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1631 $other = User::newFromName( $shortTitle, false );
1632 if ( !$other ) {
1633 wfDebug( __METHOD__ . ": invalid username\n" );
1634 } elseif ( User::isIP( $shortTitle ) ) {
1635 // An anonymous user
1636 $other->setNewtalk( true );
1637 } elseif ( $other->isLoggedIn() ) {
1638 $other->setNewtalk( true );
1639 } else {
1640 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
1645 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1646 MessageCache::singleton()->replace( $shortTitle, $text );
1649 if( $options['created'] ) {
1650 self::onArticleCreate( $this->mTitle );
1651 } else {
1652 self::onArticleEdit( $this->mTitle );
1655 wfProfileOut( __METHOD__ );
1659 * Edit an article without doing all that other stuff
1660 * The article must already exist; link tables etc
1661 * are not updated, caches are not flushed.
1663 * @param $text String: text submitted
1664 * @param $user User The relevant user
1665 * @param $comment String: comment submitted
1666 * @param $minor Boolean: whereas it's a minor modification
1668 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
1669 wfProfileIn( __METHOD__ );
1671 $dbw = wfGetDB( DB_MASTER );
1672 $revision = new Revision( array(
1673 'page' => $this->getId(),
1674 'text' => $text,
1675 'comment' => $comment,
1676 'minor_edit' => $minor ? 1 : 0,
1677 ) );
1678 $revision->insertOn( $dbw );
1679 $this->updateRevisionOn( $dbw, $revision );
1681 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1683 wfProfileOut( __METHOD__ );
1687 * Update the article's restriction field, and leave a log entry.
1688 * This works for protection both existing and non-existing pages.
1690 * @param $limit Array: set of restriction keys
1691 * @param $reason String
1692 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1693 * @param $expiry Array: per restriction type expiration
1694 * @param $user User The user updating the restrictions
1695 * @return bool true on success
1697 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
1698 global $wgContLang;
1700 if ( wfReadOnly() ) {
1701 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
1704 $restrictionTypes = $this->mTitle->getRestrictionTypes();
1706 $id = $this->mTitle->getArticleID();
1708 if ( !$cascade ) {
1709 $cascade = false;
1712 // Take this opportunity to purge out expired restrictions
1713 Title::purgeExpiredRestrictions();
1715 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1716 # we expect a single selection, but the schema allows otherwise.
1717 $isProtected = false;
1718 $protect = false;
1719 $changed = false;
1721 $dbw = wfGetDB( DB_MASTER );
1723 foreach ( $restrictionTypes as $action ) {
1724 if ( !isset( $expiry[$action] ) ) {
1725 $expiry[$action] = $dbw->getInfinity();
1727 if ( !isset( $limit[$action] ) ) {
1728 $limit[$action] = '';
1729 } elseif ( $limit[$action] != '' ) {
1730 $protect = true;
1733 # Get current restrictions on $action
1734 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
1735 if ( $current != '' ) {
1736 $isProtected = true;
1739 if ( $limit[$action] != $current ) {
1740 $changed = true;
1741 } elseif ( $limit[$action] != '' ) {
1742 # Only check expiry change if the action is actually being
1743 # protected, since expiry does nothing on an not-protected
1744 # action.
1745 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1746 $changed = true;
1751 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
1752 $changed = true;
1755 # If nothing's changed, do nothing
1756 if ( !$changed ) {
1757 return Status::newGood();
1760 if ( !$protect ) { # No protection at all means unprotection
1761 $revCommentMsg = 'unprotectedarticle';
1762 $logAction = 'unprotect';
1763 } elseif ( $isProtected ) {
1764 $revCommentMsg = 'modifiedarticleprotection';
1765 $logAction = 'modify';
1766 } else {
1767 $revCommentMsg = 'protectedarticle';
1768 $logAction = 'protect';
1771 $encodedExpiry = array();
1772 $protectDescription = '';
1773 foreach ( $limit as $action => $restrictions ) {
1774 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1775 if ( $restrictions != '' ) {
1776 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1777 if ( $encodedExpiry[$action] != 'infinity' ) {
1778 $protectDescription .= wfMsgForContent( 'protect-expiring',
1779 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1780 $wgContLang->date( $expiry[$action], false, false ) ,
1781 $wgContLang->time( $expiry[$action], false, false ) );
1782 } else {
1783 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1786 $protectDescription .= ') ';
1789 $protectDescription = trim( $protectDescription );
1791 if ( $id ) { # Protection of existing page
1792 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1793 return Status::newGood();
1796 # Only restrictions with the 'protect' right can cascade...
1797 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1798 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1800 # The schema allows multiple restrictions
1801 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1802 $cascade = false;
1805 # Update restrictions table
1806 foreach ( $limit as $action => $restrictions ) {
1807 if ( $restrictions != '' ) {
1808 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1809 array( 'pr_page' => $id,
1810 'pr_type' => $action,
1811 'pr_level' => $restrictions,
1812 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
1813 'pr_expiry' => $encodedExpiry[$action]
1815 __METHOD__
1817 } else {
1818 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1819 'pr_type' => $action ), __METHOD__ );
1823 # Prepare a null revision to be added to the history
1824 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle->getPrefixedText() ) );
1825 if ( $reason ) {
1826 $editComment .= ": $reason";
1828 if ( $protectDescription ) {
1829 $editComment .= " ($protectDescription)";
1831 if ( $cascade ) {
1832 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1835 # Insert a null revision
1836 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1837 $nullRevId = $nullRevision->insertOn( $dbw );
1839 $latest = $this->getLatest();
1840 # Update page record
1841 $dbw->update( 'page',
1842 array( /* SET */
1843 'page_touched' => $dbw->timestamp(),
1844 'page_restrictions' => '',
1845 'page_latest' => $nullRevId
1846 ), array( /* WHERE */
1847 'page_id' => $id
1848 ), __METHOD__
1851 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1852 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1853 } else { # Protection of non-existing page (also known as "title protection")
1854 # Cascade protection is meaningless in this case
1855 $cascade = false;
1857 if ( $limit['create'] != '' ) {
1858 $dbw->replace( 'protected_titles',
1859 array( array( 'pt_namespace', 'pt_title' ) ),
1860 array(
1861 'pt_namespace' => $this->mTitle->getNamespace(),
1862 'pt_title' => $this->mTitle->getDBkey(),
1863 'pt_create_perm' => $limit['create'],
1864 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1865 'pt_expiry' => $encodedExpiry['create'],
1866 'pt_user' => $user->getId(),
1867 'pt_reason' => $reason,
1868 ), __METHOD__
1870 } else {
1871 $dbw->delete( 'protected_titles',
1872 array(
1873 'pt_namespace' => $this->mTitle->getNamespace(),
1874 'pt_title' => $this->mTitle->getDBkey()
1875 ), __METHOD__
1880 $this->mTitle->flushRestrictions();
1882 if ( $logAction == 'unprotect' ) {
1883 $logParams = array();
1884 } else {
1885 $logParams = array( $protectDescription, $cascade ? 'cascade' : '' );
1888 # Update the protection log
1889 $log = new LogPage( 'protect' );
1890 $log->addEntry( $logAction, $this->mTitle, trim( $reason ), $logParams, $user );
1892 return Status::newGood();
1896 * Take an array of page restrictions and flatten it to a string
1897 * suitable for insertion into the page_restrictions field.
1898 * @param $limit Array
1899 * @return String
1901 protected static function flattenRestrictions( $limit ) {
1902 if ( !is_array( $limit ) ) {
1903 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1906 $bits = array();
1907 ksort( $limit );
1909 foreach ( $limit as $action => $restrictions ) {
1910 if ( $restrictions != '' ) {
1911 $bits[] = "$action=$restrictions";
1915 return implode( ':', $bits );
1919 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
1920 * Deletes the article with database consistency, writes logs, purges caches
1922 * @param $reason string delete reason for deletion log
1923 * @param $suppress int bitfield
1924 * Revision::DELETED_TEXT
1925 * Revision::DELETED_COMMENT
1926 * Revision::DELETED_USER
1927 * Revision::DELETED_RESTRICTED
1928 * @param $id int article ID
1929 * @param $commit boolean defaults to true, triggers transaction end
1930 * @param &$error Array of errors to append to
1931 * @param $user User The deleting user
1932 * @return boolean true if successful
1934 public function doDeleteArticle(
1935 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
1937 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
1938 == WikiPage::DELETE_SUCCESS;
1942 * Back-end article deletion
1943 * Deletes the article with database consistency, writes logs, purges caches
1945 * @param $reason string delete reason for deletion log
1946 * @param $suppress int bitfield
1947 * Revision::DELETED_TEXT
1948 * Revision::DELETED_COMMENT
1949 * Revision::DELETED_USER
1950 * Revision::DELETED_RESTRICTED
1951 * @param $id int article ID
1952 * @param $commit boolean defaults to true, triggers transaction end
1953 * @param &$error Array of errors to append to
1954 * @param $user User The deleting user
1955 * @return int: One of WikiPage::DELETE_* constants
1957 public function doDeleteArticleReal(
1958 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
1960 global $wgUser;
1961 $user = is_null( $user ) ? $wgUser : $user;
1963 wfDebug( __METHOD__ . "\n" );
1965 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1966 return WikiPage::DELETE_HOOK_ABORTED;
1968 $dbw = wfGetDB( DB_MASTER );
1969 $t = $this->mTitle->getDBkey();
1970 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
1972 if ( $t === '' || $id == 0 ) {
1973 return WikiPage::DELETE_NO_PAGE;
1976 // Bitfields to further suppress the content
1977 if ( $suppress ) {
1978 $bitfield = 0;
1979 // This should be 15...
1980 $bitfield |= Revision::DELETED_TEXT;
1981 $bitfield |= Revision::DELETED_COMMENT;
1982 $bitfield |= Revision::DELETED_USER;
1983 $bitfield |= Revision::DELETED_RESTRICTED;
1984 } else {
1985 $bitfield = 'rev_deleted';
1988 $dbw->begin();
1989 // For now, shunt the revision data into the archive table.
1990 // Text is *not* removed from the text table; bulk storage
1991 // is left intact to avoid breaking block-compression or
1992 // immutable storage schemes.
1994 // For backwards compatibility, note that some older archive
1995 // table entries will have ar_text and ar_flags fields still.
1997 // In the future, we may keep revisions and mark them with
1998 // the rev_deleted field, which is reserved for this purpose.
1999 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2000 array(
2001 'ar_namespace' => 'page_namespace',
2002 'ar_title' => 'page_title',
2003 'ar_comment' => 'rev_comment',
2004 'ar_user' => 'rev_user',
2005 'ar_user_text' => 'rev_user_text',
2006 'ar_timestamp' => 'rev_timestamp',
2007 'ar_minor_edit' => 'rev_minor_edit',
2008 'ar_rev_id' => 'rev_id',
2009 'ar_parent_id' => 'rev_parent_id',
2010 'ar_text_id' => 'rev_text_id',
2011 'ar_text' => '\'\'', // Be explicit to appease
2012 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2013 'ar_len' => 'rev_len',
2014 'ar_page_id' => 'page_id',
2015 'ar_deleted' => $bitfield,
2016 'ar_sha1' => 'rev_sha1'
2017 ), array(
2018 'page_id' => $id,
2019 'page_id = rev_page'
2020 ), __METHOD__
2023 # Now that it's safely backed up, delete it
2024 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2025 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2027 if ( !$ok ) {
2028 $dbw->rollback();
2029 return WikiPage::DELETE_NO_REVISIONS;
2032 $this->doDeleteUpdates( $id );
2034 # Log the deletion, if the page was suppressed, log it at Oversight instead
2035 $logtype = $suppress ? 'suppress' : 'delete';
2037 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2038 $logEntry->setPerformer( $user );
2039 $logEntry->setTarget( $this->mTitle );
2040 $logEntry->setComment( $reason );
2041 $logid = $logEntry->insert();
2042 $logEntry->publish( $logid );
2044 if ( $commit ) {
2045 $dbw->commit();
2048 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2049 return WikiPage::DELETE_SUCCESS;
2053 * Do some database updates after deletion
2055 * @param $id Int: page_id value of the page being deleted
2057 public function doDeleteUpdates( $id ) {
2058 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2060 $dbw = wfGetDB( DB_MASTER );
2062 # Delete restrictions for it
2063 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2065 # Fix category table counts
2066 $cats = array();
2067 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2069 foreach ( $res as $row ) {
2070 $cats [] = $row->cl_to;
2073 $this->updateCategoryCounts( array(), $cats );
2075 # If using cascading deletes, we can skip some explicit deletes
2076 if ( !$dbw->cascadingDeletes() ) {
2077 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2079 # Delete outgoing links
2080 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__ );
2081 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__ );
2082 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__ );
2083 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__ );
2084 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__ );
2085 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__ );
2086 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__ );
2087 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__ );
2088 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__ );
2091 # If using cleanup triggers, we can skip some manual deletes
2092 if ( !$dbw->cleanupTriggers() ) {
2093 # Clean up recentchanges entries...
2094 $dbw->delete( 'recentchanges',
2095 array( 'rc_type != ' . RC_LOG,
2096 'rc_namespace' => $this->mTitle->getNamespace(),
2097 'rc_title' => $this->mTitle->getDBkey() ),
2098 __METHOD__ );
2099 $dbw->delete( 'recentchanges',
2100 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
2101 __METHOD__ );
2104 # Clear caches
2105 self::onArticleDelete( $this->mTitle );
2107 # Reset this object
2108 $this->clear();
2110 # Clear the cached article id so the interface doesn't act like we exist
2111 $this->mTitle->resetArticleID( 0 );
2115 * Roll back the most recent consecutive set of edits to a page
2116 * from the same user; fails if there are no eligible edits to
2117 * roll back to, e.g. user is the sole contributor. This function
2118 * performs permissions checks on $user, then calls commitRollback()
2119 * to do the dirty work
2121 * @todo: seperate the business/permission stuff out from backend code
2123 * @param $fromP String: Name of the user whose edits to rollback.
2124 * @param $summary String: Custom summary. Set to default summary if empty.
2125 * @param $token String: Rollback token.
2126 * @param $bot Boolean: If true, mark all reverted edits as bot.
2128 * @param $resultDetails Array: contains result-specific array of additional values
2129 * 'alreadyrolled' : 'current' (rev)
2130 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2132 * @param $user User The user performing the rollback
2133 * @return array of errors, each error formatted as
2134 * array(messagekey, param1, param2, ...).
2135 * On success, the array is empty. This array can also be passed to
2136 * OutputPage::showPermissionsErrorPage().
2138 public function doRollback(
2139 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2141 $resultDetails = null;
2143 # Check permissions
2144 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2145 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2146 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2148 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2149 $errors[] = array( 'sessionfailure' );
2152 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2153 $errors[] = array( 'actionthrottledtext' );
2156 # If there were errors, bail out now
2157 if ( !empty( $errors ) ) {
2158 return $errors;
2161 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2165 * Backend implementation of doRollback(), please refer there for parameter
2166 * and return value documentation
2168 * NOTE: This function does NOT check ANY permissions, it just commits the
2169 * rollback to the DB. Therefore, you should only call this function direct-
2170 * ly if you want to use custom permissions checks. If you don't, use
2171 * doRollback() instead.
2172 * @param $fromP String: Name of the user whose edits to rollback.
2173 * @param $summary String: Custom summary. Set to default summary if empty.
2174 * @param $bot Boolean: If true, mark all reverted edits as bot.
2176 * @param $resultDetails Array: contains result-specific array of additional values
2177 * @param $guser User The user performing the rollback
2178 * @return array
2180 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2181 global $wgUseRCPatrol, $wgContLang;
2183 $dbw = wfGetDB( DB_MASTER );
2185 if ( wfReadOnly() ) {
2186 return array( array( 'readonlytext' ) );
2189 # Get the last editor
2190 $current = $this->getRevision();
2191 if ( is_null( $current ) ) {
2192 # Something wrong... no page?
2193 return array( array( 'notanarticle' ) );
2196 $from = str_replace( '_', ' ', $fromP );
2197 # User name given should match up with the top revision.
2198 # If the user was deleted then $from should be empty.
2199 if ( $from != $current->getUserText() ) {
2200 $resultDetails = array( 'current' => $current );
2201 return array( array( 'alreadyrolled',
2202 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2203 htmlspecialchars( $fromP ),
2204 htmlspecialchars( $current->getUserText() )
2205 ) );
2208 # Get the last edit not by this guy...
2209 # Note: these may not be public values
2210 $user = intval( $current->getRawUser() );
2211 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2212 $s = $dbw->selectRow( 'revision',
2213 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2214 array( 'rev_page' => $current->getPage(),
2215 "rev_user != {$user} OR rev_user_text != {$user_text}"
2216 ), __METHOD__,
2217 array( 'USE INDEX' => 'page_timestamp',
2218 'ORDER BY' => 'rev_timestamp DESC' )
2220 if ( $s === false ) {
2221 # No one else ever edited this page
2222 return array( array( 'cantrollback' ) );
2223 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
2224 # Only admins can see this text
2225 return array( array( 'notvisiblerev' ) );
2228 $set = array();
2229 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2230 # Mark all reverted edits as bot
2231 $set['rc_bot'] = 1;
2234 if ( $wgUseRCPatrol ) {
2235 # Mark all reverted edits as patrolled
2236 $set['rc_patrolled'] = 1;
2239 if ( count( $set ) ) {
2240 $dbw->update( 'recentchanges', $set,
2241 array( /* WHERE */
2242 'rc_cur_id' => $current->getPage(),
2243 'rc_user_text' => $current->getUserText(),
2244 "rc_timestamp > '{$s->rev_timestamp}'",
2245 ), __METHOD__
2249 # Generate the edit summary if necessary
2250 $target = Revision::newFromId( $s->rev_id );
2251 if ( empty( $summary ) ) {
2252 if ( $from == '' ) { // no public user name
2253 $summary = wfMsgForContent( 'revertpage-nouser' );
2254 } else {
2255 $summary = wfMsgForContent( 'revertpage' );
2259 # Allow the custom summary to use the same args as the default message
2260 $args = array(
2261 $target->getUserText(), $from, $s->rev_id,
2262 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
2263 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2265 $summary = wfMsgReplaceArgs( $summary, $args );
2267 # Save
2268 $flags = EDIT_UPDATE;
2270 if ( $guser->isAllowed( 'minoredit' ) ) {
2271 $flags |= EDIT_MINOR;
2274 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2275 $flags |= EDIT_FORCE_BOT;
2278 # Actually store the edit
2279 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2280 if ( !empty( $status->value['revision'] ) ) {
2281 $revId = $status->value['revision']->getId();
2282 } else {
2283 $revId = false;
2286 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2288 $resultDetails = array(
2289 'summary' => $summary,
2290 'current' => $current,
2291 'target' => $target,
2292 'newid' => $revId
2295 return array();
2299 * The onArticle*() functions are supposed to be a kind of hooks
2300 * which should be called whenever any of the specified actions
2301 * are done.
2303 * This is a good place to put code to clear caches, for instance.
2305 * This is called on page move and undelete, as well as edit
2307 * @param $title Title object
2309 public static function onArticleCreate( $title ) {
2310 # Update existence markers on article/talk tabs...
2311 if ( $title->isTalkPage() ) {
2312 $other = $title->getSubjectPage();
2313 } else {
2314 $other = $title->getTalkPage();
2317 $other->invalidateCache();
2318 $other->purgeSquid();
2320 $title->touchLinks();
2321 $title->purgeSquid();
2322 $title->deleteTitleProtection();
2326 * Clears caches when article is deleted
2328 * @param $title Title
2330 public static function onArticleDelete( $title ) {
2331 # Update existence markers on article/talk tabs...
2332 if ( $title->isTalkPage() ) {
2333 $other = $title->getSubjectPage();
2334 } else {
2335 $other = $title->getTalkPage();
2338 $other->invalidateCache();
2339 $other->purgeSquid();
2341 $title->touchLinks();
2342 $title->purgeSquid();
2344 # File cache
2345 HTMLFileCache::clearFileCache( $title );
2347 # Messages
2348 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2349 MessageCache::singleton()->replace( $title->getDBkey(), false );
2352 # Images
2353 if ( $title->getNamespace() == NS_FILE ) {
2354 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2355 $update->doUpdate();
2358 # User talk pages
2359 if ( $title->getNamespace() == NS_USER_TALK ) {
2360 $user = User::newFromName( $title->getText(), false );
2361 if ( $user ) {
2362 $user->setNewtalk( false );
2366 # Image redirects
2367 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2371 * Purge caches on page update etc
2373 * @param $title Title object
2374 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2376 public static function onArticleEdit( $title ) {
2377 // Invalidate caches of articles which include this page
2378 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
2381 // Invalidate the caches of all pages which redirect here
2382 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
2384 # Purge squid for this page only
2385 $title->purgeSquid();
2387 # Clear file cache for this page only
2388 HTMLFileCache::clearFileCache( $title );
2391 /**#@-*/
2394 * Returns a list of hidden categories this page is a member of.
2395 * Uses the page_props and categorylinks tables.
2397 * @return Array of Title objects
2399 public function getHiddenCategories() {
2400 $result = array();
2401 $id = $this->mTitle->getArticleID();
2403 if ( $id == 0 ) {
2404 return array();
2407 $dbr = wfGetDB( DB_SLAVE );
2408 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2409 array( 'cl_to' ),
2410 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2411 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2412 __METHOD__ );
2414 if ( $res !== false ) {
2415 foreach ( $res as $row ) {
2416 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2420 return $result;
2424 * Return an applicable autosummary if one exists for the given edit.
2425 * @param $oldtext String: the previous text of the page.
2426 * @param $newtext String: The submitted text of the page.
2427 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2428 * @return string An appropriate autosummary, or an empty string.
2430 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2431 global $wgContLang;
2433 # Decide what kind of autosummary is needed.
2435 # Redirect autosummaries
2436 $ot = Title::newFromRedirect( $oldtext );
2437 $rt = Title::newFromRedirect( $newtext );
2439 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
2440 $truncatedtext = $wgContLang->truncate(
2441 str_replace( "\n", ' ', $newtext ),
2442 max( 0, 250
2443 - strlen( wfMsgForContent( 'autoredircomment' ) )
2444 - strlen( $rt->getFullText() )
2445 ) );
2446 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2449 # New page autosummaries
2450 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
2451 # If they're making a new article, give its text, truncated, in the summary.
2453 $truncatedtext = $wgContLang->truncate(
2454 str_replace( "\n", ' ', $newtext ),
2455 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2457 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2460 # Blanking autosummaries
2461 if ( $oldtext != '' && $newtext == '' ) {
2462 return wfMsgForContent( 'autosumm-blank' );
2463 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2464 # Removing more than 90% of the article
2466 $truncatedtext = $wgContLang->truncate(
2467 $newtext,
2468 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2470 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2473 # If we reach this point, there's no applicable autosummary for our case, so our
2474 # autosummary is empty.
2475 return '';
2479 * Auto-generates a deletion reason
2481 * @param &$hasHistory Boolean: whether the page has a history
2482 * @return mixed String containing deletion reason or empty string, or boolean false
2483 * if no revision occurred
2485 public function getAutoDeleteReason( &$hasHistory ) {
2486 global $wgContLang;
2488 // Get the last revision
2489 $rev = $this->getRevision();
2491 if ( is_null( $rev ) ) {
2492 return false;
2495 // Get the article's contents
2496 $contents = $rev->getText();
2497 $blank = false;
2499 // If the page is blank, use the text from the previous revision,
2500 // which can only be blank if there's a move/import/protect dummy revision involved
2501 if ( $contents == '' ) {
2502 $prev = $rev->getPrevious();
2504 if ( $prev ) {
2505 $contents = $prev->getText();
2506 $blank = true;
2510 $dbw = wfGetDB( DB_MASTER );
2512 // Find out if there was only one contributor
2513 // Only scan the last 20 revisions
2514 $res = $dbw->select( 'revision', 'rev_user_text',
2515 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2516 __METHOD__,
2517 array( 'LIMIT' => 20 )
2520 if ( $res === false ) {
2521 // This page has no revisions, which is very weird
2522 return false;
2525 $hasHistory = ( $res->numRows() > 1 );
2526 $row = $dbw->fetchObject( $res );
2528 if ( $row ) { // $row is false if the only contributor is hidden
2529 $onlyAuthor = $row->rev_user_text;
2530 // Try to find a second contributor
2531 foreach ( $res as $row ) {
2532 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2533 $onlyAuthor = false;
2534 break;
2537 } else {
2538 $onlyAuthor = false;
2541 // Generate the summary with a '$1' placeholder
2542 if ( $blank ) {
2543 // The current revision is blank and the one before is also
2544 // blank. It's just not our lucky day
2545 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2546 } else {
2547 if ( $onlyAuthor ) {
2548 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2549 } else {
2550 $reason = wfMsgForContent( 'excontent', '$1' );
2554 if ( $reason == '-' ) {
2555 // Allow these UI messages to be blanked out cleanly
2556 return '';
2559 // Replace newlines with spaces to prevent uglyness
2560 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2561 // Calculate the maximum amount of chars to get
2562 // Max content length = max comment length - length of the comment (excl. $1)
2563 $maxLength = 255 - ( strlen( $reason ) - 2 );
2564 $contents = $wgContLang->truncate( $contents, $maxLength );
2565 // Remove possible unfinished links
2566 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2567 // Now replace the '$1' placeholder
2568 $reason = str_replace( '$1', $contents, $reason );
2570 return $reason;
2574 * Update all the appropriate counts in the category table, given that
2575 * we've added the categories $added and deleted the categories $deleted.
2577 * @param $added array The names of categories that were added
2578 * @param $deleted array The names of categories that were deleted
2580 public function updateCategoryCounts( $added, $deleted ) {
2581 $ns = $this->mTitle->getNamespace();
2582 $dbw = wfGetDB( DB_MASTER );
2584 # First make sure the rows exist. If one of the "deleted" ones didn't
2585 # exist, we might legitimately not create it, but it's simpler to just
2586 # create it and then give it a negative value, since the value is bogus
2587 # anyway.
2589 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2590 $insertCats = array_merge( $added, $deleted );
2591 if ( !$insertCats ) {
2592 # Okay, nothing to do
2593 return;
2596 $insertRows = array();
2598 foreach ( $insertCats as $cat ) {
2599 $insertRows[] = array(
2600 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2601 'cat_title' => $cat
2604 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2606 $addFields = array( 'cat_pages = cat_pages + 1' );
2607 $removeFields = array( 'cat_pages = cat_pages - 1' );
2609 if ( $ns == NS_CATEGORY ) {
2610 $addFields[] = 'cat_subcats = cat_subcats + 1';
2611 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2612 } elseif ( $ns == NS_FILE ) {
2613 $addFields[] = 'cat_files = cat_files + 1';
2614 $removeFields[] = 'cat_files = cat_files - 1';
2617 if ( $added ) {
2618 $dbw->update(
2619 'category',
2620 $addFields,
2621 array( 'cat_title' => $added ),
2622 __METHOD__
2626 if ( $deleted ) {
2627 $dbw->update(
2628 'category',
2629 $removeFields,
2630 array( 'cat_title' => $deleted ),
2631 __METHOD__
2637 * Updates cascading protections
2639 * @param $parserOutput ParserOutput object for the current version
2641 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
2642 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
2643 return;
2646 // templatelinks table may have become out of sync,
2647 // especially if using variable-based transclusions.
2648 // For paranoia, check if things have changed and if
2649 // so apply updates to the database. This will ensure
2650 // that cascaded protections apply as soon as the changes
2651 // are visible.
2653 # Get templates from templatelinks
2654 $id = $this->mTitle->getArticleID();
2656 $tlTemplates = array();
2658 $dbr = wfGetDB( DB_SLAVE );
2659 $res = $dbr->select( array( 'templatelinks' ),
2660 array( 'tl_namespace', 'tl_title' ),
2661 array( 'tl_from' => $id ),
2662 __METHOD__
2665 foreach ( $res as $row ) {
2666 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2669 # Get templates from parser output.
2670 $poTemplates = array();
2671 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2672 foreach ( $templates as $dbk => $id ) {
2673 $poTemplates["$ns:$dbk"] = true;
2677 # Get the diff
2678 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2680 if ( count( $templates_diff ) > 0 ) {
2681 # Whee, link updates time.
2682 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
2683 $u->doUpdate();
2688 * Return a list of templates used by this article.
2689 * Uses the templatelinks table
2691 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2692 * @return Array of Title objects
2694 public function getUsedTemplates() {
2695 return $this->mTitle->getTemplateLinksFrom();
2699 * Perform article updates on a special page creation.
2701 * @param $rev Revision object
2703 * @todo This is a shitty interface function. Kill it and replace the
2704 * other shitty functions like doEditUpdates and such so it's not needed
2705 * anymore.
2706 * @deprecated since 1.18, use doEditUpdates()
2708 public function createUpdates( $rev ) {
2709 wfDeprecated( __METHOD__, '1.18' );
2710 global $wgUser;
2711 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2715 * This function is called right before saving the wikitext,
2716 * so we can do things like signatures and links-in-context.
2718 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2719 * @param $text String article contents
2720 * @param $user User object: user doing the edit
2721 * @param $popts ParserOptions object: parser options, default options for
2722 * the user loaded if null given
2723 * @return string article contents with altered wikitext markup (signatures
2724 * converted, {{subst:}}, templates, etc.)
2726 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
2727 global $wgParser, $wgUser;
2729 wfDeprecated( __METHOD__, '1.19' );
2731 $user = is_null( $user ) ? $wgUser : $user;
2733 if ( $popts === null ) {
2734 $popts = ParserOptions::newFromUser( $user );
2737 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
2741 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2743 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2744 * @return bool
2746 public function isBigDeletion() {
2747 wfDeprecated( __METHOD__, '1.19' );
2748 return $this->mTitle->isBigDeletion();
2752 * Get the approximate revision count of this page.
2754 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2755 * @return int
2757 public function estimateRevisionCount() {
2758 wfDeprecated( __METHOD__, '1.19' );
2759 return $this->mTitle->estimateRevisionCount();
2763 * Update the article's restriction field, and leave a log entry.
2765 * @deprecated since 1.19
2766 * @param $limit Array: set of restriction keys
2767 * @param $reason String
2768 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2769 * @param $expiry Array: per restriction type expiration
2770 * @param $user User The user updating the restrictions
2771 * @return bool true on success
2773 public function updateRestrictions(
2774 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
2776 global $wgUser;
2778 $user = is_null( $user ) ? $wgUser : $user;
2780 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2784 * @deprecated since 1.18
2786 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2787 wfDeprecated( __METHOD__, '1.18' );
2788 global $wgUser;
2789 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2793 * @deprecated since 1.18
2795 public function viewUpdates() {
2796 wfDeprecated( __METHOD__, '1.18' );
2797 global $wgUser;
2798 return $this->doViewUpdates( $wgUser );
2802 * @deprecated since 1.18
2803 * @return bool
2805 public function useParserCache( $oldid ) {
2806 wfDeprecated( __METHOD__, '1.18' );
2807 global $wgUser;
2808 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
2812 class PoolWorkArticleView extends PoolCounterWork {
2815 * @var Page
2817 private $page;
2820 * @var string
2822 private $cacheKey;
2825 * @var integer
2827 private $revid;
2830 * @var ParserOptions
2832 private $parserOptions;
2835 * @var string|null
2837 private $text;
2840 * @var ParserOutput|bool
2842 private $parserOutput = false;
2845 * @var bool
2847 private $isDirty = false;
2850 * @var Status|bool
2852 private $error = false;
2855 * Constructor
2857 * @param $page Page
2858 * @param $revid Integer: ID of the revision being parsed
2859 * @param $useParserCache Boolean: whether to use the parser cache
2860 * @param $parserOptions parserOptions to use for the parse operation
2861 * @param $text String: text to parse or null to load it
2863 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $text = null ) {
2864 $this->page = $page;
2865 $this->revid = $revid;
2866 $this->cacheable = $useParserCache;
2867 $this->parserOptions = $parserOptions;
2868 $this->text = $text;
2869 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
2870 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
2874 * Get the ParserOutput from this object, or false in case of failure
2876 * @return ParserOutput
2878 public function getParserOutput() {
2879 return $this->parserOutput;
2883 * Get whether the ParserOutput is a dirty one (i.e. expired)
2885 * @return bool
2887 public function getIsDirty() {
2888 return $this->isDirty;
2892 * Get a Status object in case of error or false otherwise
2894 * @return Status|bool
2896 public function getError() {
2897 return $this->error;
2901 * @return bool
2903 function doWork() {
2904 global $wgParser, $wgUseFileCache;
2906 $isCurrent = $this->revid === $this->page->getLatest();
2908 if ( $this->text !== null ) {
2909 $text = $this->text;
2910 } elseif ( $isCurrent ) {
2911 $text = $this->page->getRawText();
2912 } else {
2913 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
2914 if ( $rev === null ) {
2915 return false;
2917 $text = $rev->getText();
2920 $time = - microtime( true );
2921 $this->parserOutput = $wgParser->parse( $text, $this->page->getTitle(),
2922 $this->parserOptions, true, true, $this->revid );
2923 $time += microtime( true );
2925 # Timing hack
2926 if ( $time > 3 ) {
2927 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2928 $this->page->getTitle()->getPrefixedDBkey() ) );
2931 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
2932 ParserCache::singleton()->save( $this->parserOutput, $this->page, $this->parserOptions );
2935 // Make sure file cache is not used on uncacheable content.
2936 // Output that has magic words in it can still use the parser cache
2937 // (if enabled), though it will generally expire sooner.
2938 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
2939 $wgUseFileCache = false;
2942 if ( $isCurrent ) {
2943 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
2946 return true;
2950 * @return bool
2952 function getCachedWork() {
2953 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
2955 if ( $this->parserOutput === false ) {
2956 wfDebug( __METHOD__ . ": parser cache miss\n" );
2957 return false;
2958 } else {
2959 wfDebug( __METHOD__ . ": parser cache hit\n" );
2960 return true;
2965 * @return bool
2967 function fallback() {
2968 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
2970 if ( $this->parserOutput === false ) {
2971 wfDebugLog( 'dirty', "dirty missing\n" );
2972 wfDebug( __METHOD__ . ": no dirty cache\n" );
2973 return false;
2974 } else {
2975 wfDebug( __METHOD__ . ": sending dirty output\n" );
2976 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2977 $this->isDirty = true;
2978 return true;
2983 * @param $status Status
2984 * @return bool
2986 function error( $status ) {
2987 $this->error = $status;
2988 return false;