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
{
19 public $mTitle = null;
24 public $mDataLoaded = false; // !< Boolean
25 public $mIsRedirect = false; // !< Boolean
26 public $mLatest = false; // !< Integer (false means "not loaded")
27 public $mPreparedEdit = false; // !< Array
33 protected $mRedirectTarget = null;
38 protected $mLastRevision = null;
41 * @var string; timestamp of the current revision or empty string if not loaded
43 protected $mTimestamp = '';
48 protected $mTouched = '19700101000000';
53 protected $mCounter = null;
56 * Constructor and clear the article
57 * @param $title Title Reference to a Title object.
59 public function __construct( Title
$title ) {
60 $this->mTitle
= $title;
64 * Create a WikiPage object of the appropriate class for the given title.
67 * @return WikiPage object of the appropriate type
69 public static function factory( Title
$title ) {
70 $ns = $title->getNamespace();
72 if ( $ns == NS_MEDIA
) {
73 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
74 } elseif ( $ns < 0 ) {
75 throw new MWException( "Invalid or virtual namespace $ns given." );
80 $page = new WikiFilePage( $title );
83 $page = new WikiCategoryPage( $title );
86 $page = new WikiPage( $title );
93 * Constructor from a page id
95 * @param $id Int article ID to load
99 public static function newFromID( $id ) {
100 $t = Title
::newFromID( $id );
102 return self
::factory( $t );
108 * Returns overrides for action handlers.
109 * Classes listed here will be used instead of the default one when
110 * (and only when) $wgActions[$action] === true. This allows subclasses
111 * to override the default behavior.
113 * @todo: move this UI stuff somewhere else
117 public function getActionOverrides() {
122 * Get the title object of the article
123 * @return Title object of this page
125 public function getTitle() {
126 return $this->mTitle
;
132 public function clear() {
133 $this->mDataLoaded
= false;
135 $this->mCounter
= null;
136 $this->mRedirectTarget
= null; # Title object if set
137 $this->mLastRevision
= null; # Latest revision
138 $this->mTouched
= '19700101000000';
139 $this->mTimestamp
= '';
140 $this->mIsRedirect
= false;
141 $this->mLatest
= false;
142 $this->mPreparedEdit
= false;
146 * Return the list of revision fields that should be selected to create
151 public static function selectFields() {
164 'page_content_model',
169 * Fetch a page record with the given conditions
170 * @param $dbr DatabaseBase object
171 * @param $conditions Array
172 * @return mixed Database result resource, or false on failure
174 protected function pageData( $dbr, $conditions ) {
175 $fields = self
::selectFields();
177 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
179 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
181 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
187 * Fetch a page record matching the Title object's namespace and title
188 * using a sanitized title string
190 * @param $dbr DatabaseBase object
191 * @param $title Title object
192 * @return mixed Database result resource, or false on failure
194 public function pageDataFromTitle( $dbr, $title ) {
195 return $this->pageData( $dbr, array(
196 'page_namespace' => $title->getNamespace(),
197 'page_title' => $title->getDBkey() ) );
201 * Fetch a page record matching the requested ID
203 * @param $dbr DatabaseBase
205 * @return mixed Database result resource, or false on failure
207 public function pageDataFromId( $dbr, $id ) {
208 return $this->pageData( $dbr, array( 'page_id' => $id ) );
212 * Set the general counter, title etc data loaded from
215 * @param $data Object|String One of the following:
216 * A DB query result object or...
217 * "fromdb" to get from a slave DB or...
218 * "fromdbmaster" to get from the master DB
221 public function loadPageData( $data = 'fromdb' ) {
222 if ( $data === 'fromdbmaster' ) {
223 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
224 } elseif ( $data === 'fromdb' ) { // slave
225 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
226 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
227 # Note that DB also stores the master position in the session and checks it.
228 $touched = $this->getCachedLastEditTime();
229 if ( $touched ) { // key set
230 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
231 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
236 $lc = LinkCache
::singleton();
239 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
241 $this->mTitle
->loadFromRow( $data );
243 # Old-fashioned restrictions
244 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
246 $this->mCounter
= intval( $data->page_counter
);
247 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
248 $this->mIsRedirect
= intval( $data->page_is_redirect
);
249 $this->mLatest
= intval( $data->page_latest
);
251 $lc->addBadLinkObj( $this->mTitle
);
253 $this->mTitle
->loadFromRow( false );
256 $this->mDataLoaded
= true;
260 * @return int Page ID
262 public function getId() {
263 return $this->mTitle
->getArticleID();
267 * @return bool Whether or not the page exists in the database
269 public function exists() {
270 return $this->mTitle
->exists();
274 * Check if this page is something we're going to be showing
275 * some sort of sensible content for. If we return false, page
276 * views (plain action=view) will return an HTTP 404 response,
277 * so spiders and robots can know they're following a bad link.
281 public function hasViewableContent() {
282 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
286 * @return int The view count for the page
288 public function getCount() {
289 if ( !$this->mDataLoaded
) {
290 $this->loadPageData();
293 return $this->mCounter
;
297 * Tests if the article text represents a redirect
299 * @param $text mixed string containing article contents, or boolean
302 public function isRedirect( $text = false ) {
303 if ( $text === false ) $content = $this->getContent();
304 else $content = ContentHandler
::makeContent( $text, $this->mTitle
); # TODO: allow model and format to be provided; or better, expect a Content object
307 if ( empty( $content ) ) return false;
308 else return $content->isRedirect();
312 * Returns the page's content model name. Will use the revisions actual content model if the page exists,
313 * and the page's default if the page doesn't exist yet.
317 public function getContentModelName() {
318 if ( $this->exists() ) {
319 # look at the revision's actual content model
320 $content = $this->getContent();
321 return $content->getModelName();
323 # use the default model for this page
324 return $this->mTitle
->getContentModelName();
329 * Loads page_touched and returns a value indicating if it should be used
330 * @return boolean true if not a redirect
332 public function checkTouched() {
333 if ( !$this->mDataLoaded
) {
334 $this->loadPageData();
336 return !$this->mIsRedirect
;
340 * Get the page_touched field
341 * @return string containing GMT timestamp
343 public function getTouched() {
344 if ( !$this->mDataLoaded
) {
345 $this->loadPageData();
347 return $this->mTouched
;
351 * Get the page_latest field
352 * @return integer rev_id of current revision
354 public function getLatest() {
355 if ( !$this->mDataLoaded
) {
356 $this->loadPageData();
358 return (int)$this->mLatest
;
362 * Loads everything except the text
363 * This isn't necessary for all uses, so it's only done if needed.
365 protected function loadLastEdit() {
366 if ( $this->mLastRevision
!== null ) {
367 return; // already loaded
370 $latest = $this->getLatest();
372 return; // page doesn't exist or is missing page_latest info
375 $revision = Revision
::newFromPageId( $this->getId(), $latest );
376 if ( $revision ) { // sanity
377 $this->setLastEdit( $revision );
382 * Set the latest revision
384 protected function setLastEdit( Revision
$revision ) {
385 $this->mLastRevision
= $revision;
386 $this->mTimestamp
= $revision->getTimestamp();
390 * Get the latest revision
391 * @return Revision|null
393 public function getRevision() {
394 $this->loadLastEdit();
395 if ( $this->mLastRevision
) {
396 return $this->mLastRevision
;
402 * Get the content of the current revision. No side-effects...
404 * @param $audience Integer: one of:
405 * Revision::FOR_PUBLIC to be displayed to all users
406 * Revision::FOR_THIS_USER to be displayed to $wgUser
407 * Revision::RAW get the text regardless of permissions
408 * @return Content|null The content of the current revision
410 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
411 $this->loadLastEdit();
412 if ( $this->mLastRevision
) {
413 return $this->mLastRevision
->getContent( $audience );
419 * Get the text of the current revision. No side-effects...
421 * @param $audience Integer: one of:
422 * Revision::FOR_PUBLIC to be displayed to all users
423 * Revision::FOR_THIS_USER to be displayed to $wgUser
424 * Revision::RAW get the text regardless of permissions
425 * @return String|false The text of the current revision
426 * @deprecated as of 1.20, getContent() should be used instead.
428 public function getText( $audience = Revision
::FOR_PUBLIC
) { #FIXME: deprecated, replace usage!
429 wfDeprecated( __METHOD__
, '1.20' );
430 $this->loadLastEdit();
431 if ( $this->mLastRevision
) {
432 return $this->mLastRevision
->getText( $audience );
438 * Get the text of the current revision. No side-effects...
440 * @return String|false The text of the current revision
442 public function getRawText() { #FIXME: deprecated, replace usage!
443 return $this->getText( Revision
::RAW
);
447 * Get the content of the current revision. No side-effects...
449 * @return Contet|false The text of the current revision
451 protected function getNativeData() { #FIXME: examine all uses carefully! caller must be aware of content model!
452 $content = $this->getContent( Revision
::RAW
);
453 if ( !$content ) return null;
455 return $content->getNativeData();
459 * @return string MW timestamp of last article revision
461 public function getTimestamp() {
462 // Check if the field has been filled by WikiPage::setTimestamp()
463 if ( !$this->mTimestamp
) {
464 $this->loadLastEdit();
466 return wfTimestamp( TS_MW
, $this->mTimestamp
);
470 * Set the page timestamp (use only to avoid DB queries)
471 * @param $ts string MW timestamp of last article revision
474 public function setTimestamp( $ts ) {
475 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
479 * @param $audience Integer: one of:
480 * Revision::FOR_PUBLIC to be displayed to all users
481 * Revision::FOR_THIS_USER to be displayed to $wgUser
482 * Revision::RAW get the text regardless of permissions
483 * @return int user ID for the user that made the last article revision
485 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
486 $this->loadLastEdit();
487 if ( $this->mLastRevision
) {
488 return $this->mLastRevision
->getUser( $audience );
495 * @param $audience Integer: one of:
496 * Revision::FOR_PUBLIC to be displayed to all users
497 * Revision::FOR_THIS_USER to be displayed to $wgUser
498 * Revision::RAW get the text regardless of permissions
499 * @return string username of the user that made the last article revision
501 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
502 $this->loadLastEdit();
503 if ( $this->mLastRevision
) {
504 return $this->mLastRevision
->getUserText( $audience );
511 * @param $audience Integer: one of:
512 * Revision::FOR_PUBLIC to be displayed to all users
513 * Revision::FOR_THIS_USER to be displayed to $wgUser
514 * Revision::RAW get the text regardless of permissions
515 * @return string Comment stored for the last article revision
517 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
518 $this->loadLastEdit();
519 if ( $this->mLastRevision
) {
520 return $this->mLastRevision
->getComment( $audience );
527 * Returns true if last revision was marked as "minor edit"
529 * @return boolean Minor edit indicator for the last article revision.
531 public function getMinorEdit() {
532 $this->loadLastEdit();
533 if ( $this->mLastRevision
) {
534 return $this->mLastRevision
->isMinor();
541 * Get the cached timestamp for the last time the page changed.
542 * This is only used to help handle slave lag by comparing to page_touched.
543 * @return string MW timestamp
545 protected function getCachedLastEditTime() {
547 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
548 return $wgMemc->get( $key );
552 * Set the cached timestamp for the last time the page changed.
553 * This is only used to help handle slave lag by comparing to page_touched.
554 * @param $timestamp string
557 public function setCachedLastEditTime( $timestamp ) {
559 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
560 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
564 * Determine whether a page would be suitable for being counted as an
565 * article in the site_stats table based on the title & its content
567 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
568 * if false, the current database state will be used
571 public function isCountable( $editInfo = false ) {
572 global $wgArticleCountMethod;
574 if ( !$this->mTitle
->isContentPage() ) {
579 $content = ContentHandler
::makeContent( $editInfo->pst
, $this->mTitle
);
580 # TODO: take model and format from edit info!
582 $content = $this->getContent();
585 if ( !$content ||
$content->isRedirect( ) ) {
591 if ( $wgArticleCountMethod === 'link' ) {
592 # nasty special case to avoid re-parsing to detect links
595 // ParserOutput::getLinks() is a 2D array of page links, so
596 // to be really correct we would need to recurse in the array
597 // but the main array should only have items in it if there are
599 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
601 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
602 array( 'pl_from' => $this->getId() ), __METHOD__
);
606 return $content->isCountable( $hasLinks );
610 * If this page is a redirect, get its target
612 * The target will be fetched from the redirect table if possible.
613 * If this page doesn't have an entry there, call insertRedirect()
614 * @return Title|mixed object, or null if this page is not a redirect
616 public function getRedirectTarget() {
617 if ( !$this->mTitle
->isRedirect() ) {
621 if ( $this->mRedirectTarget
!== null ) {
622 return $this->mRedirectTarget
;
625 # Query the redirect table
626 $dbr = wfGetDB( DB_SLAVE
);
627 $row = $dbr->selectRow( 'redirect',
628 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
629 array( 'rd_from' => $this->getId() ),
633 // rd_fragment and rd_interwiki were added later, populate them if empty
634 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
635 return $this->mRedirectTarget
= Title
::makeTitle(
636 $row->rd_namespace
, $row->rd_title
,
637 $row->rd_fragment
, $row->rd_interwiki
);
640 # This page doesn't have an entry in the redirect table
641 return $this->mRedirectTarget
= $this->insertRedirect();
645 * Insert an entry for this page into the redirect table.
647 * Don't call this function directly unless you know what you're doing.
648 * @return Title object or null if not a redirect
650 public function insertRedirect() {
651 // recurse through to only get the final target
652 $content = $this->getContent();
653 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
657 $this->insertRedirectEntry( $retval );
662 * Insert or update the redirect table entry for this page to indicate
663 * it redirects to $rt .
664 * @param $rt Title redirect target
666 public function insertRedirectEntry( $rt ) {
667 $dbw = wfGetDB( DB_MASTER
);
668 $dbw->replace( 'redirect', array( 'rd_from' ),
670 'rd_from' => $this->getId(),
671 'rd_namespace' => $rt->getNamespace(),
672 'rd_title' => $rt->getDBkey(),
673 'rd_fragment' => $rt->getFragment(),
674 'rd_interwiki' => $rt->getInterwiki(),
681 * Get the Title object or URL this page redirects to
683 * @return mixed false, Title of in-wiki target, or string with URL
685 public function followRedirect() {
686 return $this->getRedirectURL( $this->getRedirectTarget() );
690 * Get the Title object or URL to use for a redirect. We use Title
691 * objects for same-wiki, non-special redirects and URLs for everything
693 * @param $rt Title Redirect target
694 * @return mixed false, Title object of local target, or string with URL
696 public function getRedirectURL( $rt ) {
701 if ( $rt->isExternal() ) {
702 if ( $rt->isLocal() ) {
703 // Offsite wikis need an HTTP redirect.
705 // This can be hard to reverse and may produce loops,
706 // so they may be disabled in the site configuration.
707 $source = $this->mTitle
->getFullURL( 'redirect=no' );
708 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
710 // External pages pages without "local" bit set are not valid
716 if ( $rt->isSpecialPage() ) {
717 // Gotta handle redirects to special pages differently:
718 // Fill the HTTP response "Location" header and ignore
719 // the rest of the page we're on.
721 // Some pages are not valid targets
722 if ( $rt->isValidRedirectTarget() ) {
723 return $rt->getFullURL();
733 * Get a list of users who have edited this article, not including the user who made
734 * the most recent revision, which you can get from $article->getUser() if you want it
735 * @return UserArrayFromResult
737 public function getContributors() {
738 # @todo FIXME: This is expensive; cache this info somewhere.
740 $dbr = wfGetDB( DB_SLAVE
);
742 if ( $dbr->implicitGroupby() ) {
743 $realNameField = 'user_real_name';
745 $realNameField = 'MIN(user_real_name) AS user_real_name';
748 $tables = array( 'revision', 'user' );
751 'rev_user as user_id',
752 'rev_user_text AS user_name',
754 'MAX(rev_timestamp) AS timestamp',
757 $conds = array( 'rev_page' => $this->getId() );
759 // The user who made the top revision gets credited as "this page was last edited by
760 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
761 $user = $this->getUser();
763 $conds[] = "rev_user != $user";
765 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
768 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
771 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
775 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
776 'ORDER BY' => 'timestamp DESC',
779 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
780 return new UserArrayFromResult( $res );
784 * Get the last N authors
785 * @param $num Integer: number of revisions to get
786 * @param $revLatest String: the latest rev_id, selected from the master (optional)
787 * @return array Array of authors, duplicates not removed
789 public function getLastNAuthors( $num, $revLatest = 0 ) {
790 wfProfileIn( __METHOD__
);
791 // First try the slave
792 // If that doesn't have the latest revision, try the master
794 $db = wfGetDB( DB_SLAVE
);
797 $res = $db->select( array( 'page', 'revision' ),
798 array( 'rev_id', 'rev_user_text' ),
800 'page_namespace' => $this->mTitle
->getNamespace(),
801 'page_title' => $this->mTitle
->getDBkey(),
805 'ORDER BY' => 'rev_timestamp DESC',
811 wfProfileOut( __METHOD__
);
815 $row = $db->fetchObject( $res );
817 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
818 $db = wfGetDB( DB_MASTER
);
823 } while ( $continue );
825 $authors = array( $row->rev_user_text
);
827 foreach ( $res as $row ) {
828 $authors[] = $row->rev_user_text
;
831 wfProfileOut( __METHOD__
);
836 * Should the parser cache be used?
838 * @param $parserOptions ParserOptions to check
842 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
843 global $wgEnableParserCache;
845 return $wgEnableParserCache
846 && $parserOptions->getStubThreshold() == 0
847 && $this->mTitle
->exists()
848 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
849 && $this->mTitle
->isWikitextPage(); #FIXME: ask ContentHandler if cachable!
853 * Get a ParserOutput for the given ParserOptions and revision ID.
854 * The parser cache will be used if possible.
857 * @param $parserOptions ParserOptions to use for the parse operation
858 * @param $oldid Revision ID to get the text from, passing null or 0 will
859 * get the current revision (default value)
860 * @return ParserOutput or false if the revision was not found
862 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
863 wfProfileIn( __METHOD__
);
865 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
866 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
867 if ( $parserOptions->getStubThreshold() ) {
868 wfIncrStats( 'pcache_miss_stub' );
871 if ( $useParserCache ) {
872 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
873 if ( $parserOutput !== false ) {
874 wfProfileOut( __METHOD__
);
875 return $parserOutput;
879 if ( $oldid === null ||
$oldid === 0 ) {
880 $oldid = $this->getLatest();
883 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
886 wfProfileOut( __METHOD__
);
888 return $pool->getParserOutput();
892 * Do standard deferred updates after page view
893 * @param $user User The relevant user
895 public function doViewUpdates( User
$user ) {
896 global $wgDisableCounters;
897 if ( wfReadOnly() ) {
901 # Don't update page view counters on views from bot users (bug 14044)
902 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
903 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
904 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
907 # Update newtalk / watchlist notification status
908 $user->clearNotification( $this->mTitle
);
912 * Perform the actions of a page purging
914 public function doPurge() {
917 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
921 // Invalidate the cache
922 $this->mTitle
->invalidateCache();
926 // Commit the transaction before the purge is sent
927 $dbw = wfGetDB( DB_MASTER
);
931 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
935 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
936 if ( $this->mTitle
->exists() ) {
937 $text = $this->getNativeData(); #FIXME: may not be a string. check Content model!
942 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
948 * Insert a new empty page record for this article.
949 * This *must* be followed up by creating a revision
950 * and running $this->updateRevisionOn( ... );
951 * or else the record will be left in a funky state.
952 * Best if all done inside a transaction.
954 * @param $dbw DatabaseBase
955 * @return int The newly created page_id key, or false if the title already existed
957 public function insertOn( $dbw ) {
958 wfProfileIn( __METHOD__
);
960 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
961 $dbw->insert( 'page', array(
962 'page_id' => $page_id,
963 'page_namespace' => $this->mTitle
->getNamespace(),
964 'page_title' => $this->mTitle
->getDBkey(),
966 'page_restrictions' => '',
967 'page_is_redirect' => 0, # Will set this shortly...
969 'page_random' => wfRandom(),
970 'page_touched' => $dbw->timestamp(),
971 'page_latest' => 0, # Fill this in shortly...
972 'page_len' => 0, # Fill this in shortly...
973 ), __METHOD__
, 'IGNORE' );
975 $affected = $dbw->affectedRows();
978 $newid = $dbw->insertId();
979 $this->mTitle
->resetArticleID( $newid );
981 wfProfileOut( __METHOD__
);
983 return $affected ?
$newid : false;
987 * Update the page record to point to a newly saved revision.
989 * @param $dbw DatabaseBase: object
990 * @param $revision Revision: For ID number, and text used to set
991 * length and redirect status fields
992 * @param $lastRevision Integer: if given, will not overwrite the page field
993 * when different from the currently set value.
994 * Giving 0 indicates the new page flag should be set
996 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
997 * removing rows in redirect table.
998 * @return bool true on success, false on failure
1001 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1002 wfProfileIn( __METHOD__
);
1004 $content = $revision->getContent();
1005 $len = $content->getSize();
1006 $rt = $content->getUltimateRedirectTarget();
1008 $conditions = array( 'page_id' => $this->getId() );
1010 if ( !is_null( $lastRevision ) ) {
1011 # An extra check against threads stepping on each other
1012 $conditions['page_latest'] = $lastRevision;
1015 $now = wfTimestampNow();
1016 $dbw->update( 'page',
1018 'page_latest' => $revision->getId(),
1019 'page_touched' => $dbw->timestamp( $now ),
1020 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1021 'page_is_redirect' => $rt !== null ?
1 : 0,
1027 $result = $dbw->affectedRows() != 0;
1029 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1030 $this->setLastEdit( $revision );
1031 $this->setCachedLastEditTime( $now );
1032 $this->mLatest
= $revision->getId();
1033 $this->mIsRedirect
= (bool)$rt;
1034 # Update the LinkCache.
1035 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1038 wfProfileOut( __METHOD__
);
1043 * Add row to the redirect table if this is a redirect, remove otherwise.
1045 * @param $dbw DatabaseBase
1046 * @param $redirectTitle Title object pointing to the redirect target,
1047 * or NULL if this is not a redirect
1048 * @param $lastRevIsRedirect If given, will optimize adding and
1049 * removing rows in redirect table.
1050 * @return bool true on success, false on failure
1053 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1054 // Always update redirects (target link might have changed)
1055 // Update/Insert if we don't know if the last revision was a redirect or not
1056 // Delete if changing from redirect to non-redirect
1057 $isRedirect = !is_null( $redirectTitle );
1059 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1063 wfProfileIn( __METHOD__
);
1064 if ( $isRedirect ) {
1065 $this->insertRedirectEntry( $redirectTitle );
1067 // This is not a redirect, remove row from redirect table
1068 $where = array( 'rd_from' => $this->getId() );
1069 $dbw->delete( 'redirect', $where, __METHOD__
);
1072 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1073 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1075 wfProfileOut( __METHOD__
);
1077 return ( $dbw->affectedRows() != 0 );
1081 * If the given revision is newer than the currently set page_latest,
1082 * update the page record. Otherwise, do nothing.
1084 * @param $dbw Database object
1085 * @param $revision Revision object
1088 public function updateIfNewerOn( $dbw, $revision ) {
1089 wfProfileIn( __METHOD__
);
1091 $row = $dbw->selectRow(
1092 array( 'revision', 'page' ),
1093 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1095 'page_id' => $this->getId(),
1096 'page_latest=rev_id' ),
1100 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1101 wfProfileOut( __METHOD__
);
1104 $prev = $row->rev_id
;
1105 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1107 # No or missing previous revision; mark the page as new
1109 $lastRevIsRedirect = null;
1112 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1114 wfProfileOut( __METHOD__
);
1119 * Get the text that needs to be saved in order to undo all revisions
1120 * between $undo and $undoafter. Revisions must belong to the same page,
1121 * must exist and must not be deleted
1122 * @param $undo Revision
1123 * @param $undoafter Revision Must be an earlier revision than $undo
1124 * @return mixed string on success, false on failure
1125 * @deprecated since 1.20: use ContentHandler::getUndoContent() instead.
1127 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) { #FIXME: replace usages.
1128 $this->loadLastEdit();
1130 if ( $this->mLastRevision
) {
1131 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1132 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1137 return ContentHandler
::getContentText( $undone );
1145 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1146 * @param $text String: new text of the section
1147 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1148 * @param $edittime String: revision timestamp or null to use the current revision
1149 * @return Content new complete article content, or null if error
1150 * @deprected since 1.20, use replaceSectionContent() instead
1152 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) { #FIXME: use replaceSectionContent() instead!
1153 wfDeprecated( __METHOD__
, '1.20' );
1155 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1157 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1159 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1162 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1163 wfProfileIn( __METHOD__
);
1165 if ( strval( $section ) == '' ) {
1166 // Whole-page edit; let the whole text through
1167 $newContent = $sectionContent;
1169 // Bug 30711: always use current version when adding a new section
1170 if ( is_null( $edittime ) ||
$section == 'new' ) {
1171 $oldContent = $this->getContent();
1172 if ( ! $oldContent ) {
1173 wfDebug( __METHOD__
. ": no page text\n" );
1174 wfProfileOut( __METHOD__
);
1178 $dbw = wfGetDB( DB_MASTER
);
1179 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1182 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1183 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1184 wfProfileOut( __METHOD__
);
1188 $oldContent = $rev->getContent();
1191 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1194 wfProfileOut( __METHOD__
);
1199 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1201 * @return Int updated $flags
1203 function checkFlags( $flags ) {
1204 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1205 if ( $this->mTitle
->getArticleID() ) {
1206 $flags |
= EDIT_UPDATE
;
1216 * Change an existing article or create a new article. Updates RC and all necessary caches,
1217 * optionally via the deferred update array.
1219 * @param $text String: new text
1220 * @param $summary String: edit summary
1221 * @param $flags Integer bitfield:
1223 * Article is known or assumed to be non-existent, create a new one
1225 * Article is known or assumed to be pre-existing, update it
1227 * Mark this edit minor, if the user is allowed to do so
1229 * Do not log the change in recentchanges
1231 * Mark the edit a "bot" edit regardless of user rights
1232 * EDIT_DEFER_UPDATES
1233 * Defer some of the updates until the end of index.php
1235 * Fill in blank summaries with generated text where possible
1237 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1238 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1239 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1240 * edit-already-exists error will be returned. These two conditions are also possible with
1241 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1243 * @param $baseRevId the revision ID this edit was based off, if any
1244 * @param $user User the user doing the edit
1246 * @return Status object. Possible errors:
1247 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1248 * edit-gone-missing: In update mode, but the article didn't exist
1249 * edit-conflict: In update mode, the article changed unexpectedly
1250 * edit-no-change: Warning that the text was the same as before
1251 * edit-already-exists: In creation mode, but the article already exists
1253 * Extensions may define additional errors.
1255 * $return->value will contain an associative array with members as follows:
1256 * new: Boolean indicating if the function attempted to create a new article
1257 * revision: The revision object for the inserted revision, or null
1259 * Compatibility note: this function previously returned a boolean value indicating success/failure
1260 * @deprecated since 1.20: use doEditContent() instead.
1262 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #FIXME: use doEditContent() instead
1263 #TODO: log use of deprecated function
1264 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1266 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1270 * Change an existing article or create a new article. Updates RC and all necessary caches,
1271 * optionally via the deferred update array.
1273 * @param $content Content: new content
1274 * @param $summary String: edit summary
1275 * @param $flags Integer bitfield:
1277 * Article is known or assumed to be non-existent, create a new one
1279 * Article is known or assumed to be pre-existing, update it
1281 * Mark this edit minor, if the user is allowed to do so
1283 * Do not log the change in recentchanges
1285 * Mark the edit a "bot" edit regardless of user rights
1286 * EDIT_DEFER_UPDATES
1287 * Defer some of the updates until the end of index.php
1289 * Fill in blank summaries with generated text where possible
1291 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1292 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1293 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1294 * edit-already-exists error will be returned. These two conditions are also possible with
1295 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1297 * @param $baseRevId the revision ID this edit was based off, if any
1298 * @param $user User the user doing the edit
1299 * @param $serialisation_format String: format for storing the content in the database
1301 * @return Status object. Possible errors:
1302 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1303 * edit-gone-missing: In update mode, but the article didn't exist
1304 * edit-conflict: In update mode, the article changed unexpectedly
1305 * edit-no-change: Warning that the text was the same as before
1306 * edit-already-exists: In creation mode, but the article already exists
1308 * Extensions may define additional errors.
1310 * $return->value will contain an associative array with members as follows:
1311 * new: Boolean indicating if the function attempted to create a new article
1312 * revision: The revision object for the inserted revision, or null
1314 * Compatibility note: this function previously returned a boolean value indicating success/failure
1316 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1317 User
$user = null, $serialisation_format = null ) { #FIXME: use this
1318 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1320 # Low-level sanity check
1321 if ( $this->mTitle
->getText() === '' ) {
1322 throw new MWException( 'Something is trying to edit an article with an empty title' );
1325 wfProfileIn( __METHOD__
);
1327 $user = is_null( $user ) ?
$wgUser : $user;
1328 $status = Status
::newGood( array() );
1330 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1331 $this->loadPageData( 'fromdbmaster' );
1333 $flags = $this->checkFlags( $flags );
1336 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary, #FIXME: document new hook!
1337 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1339 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { # avoid serialization overhead if the hook isn't present
1340 $content_text = $content->serialize();
1341 $txt = $content_text; # clone
1343 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary, #FIXME: deprecate legacy hook!
1344 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1346 if ( $txt !== $content_text ) {
1347 # if the text changed, unserialize the new version to create an updated Content object.
1348 $content = $content->getContentHandler()->unserialize( $txt );
1353 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1355 if ( $status->isOK() ) {
1356 $status->fatal( 'edit-hook-aborted' );
1359 wfProfileOut( __METHOD__
);
1363 # Silently ignore EDIT_MINOR if not allowed
1364 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1365 $bot = $flags & EDIT_FORCE_BOT
;
1367 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1369 $oldsize = $old_content ?
$old_content->getSize() : 0;
1370 $oldid = $this->getLatest();
1371 $oldIsRedirect = $this->isRedirect();
1372 $oldcountable = $this->isCountable();
1374 $handler = $content->getContentHandler();
1376 # Provide autosummaries if one is not provided and autosummaries are enabled.
1377 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1378 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1381 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1382 $serialized = $editInfo->pst
;
1383 $content = $editInfo->pstContent
;
1384 $newsize = $content->getSize();
1386 $dbw = wfGetDB( DB_MASTER
);
1387 $now = wfTimestampNow();
1388 $this->mTimestamp
= $now;
1390 if ( $flags & EDIT_UPDATE
) {
1391 # Update article, but only if changed.
1392 $status->value
['new'] = false;
1395 # Article gone missing
1396 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1397 $status->fatal( 'edit-gone-missing' );
1399 wfProfileOut( __METHOD__
);
1403 # Make sure the revision is either completely inserted or not inserted at all
1404 if ( !$wgDBtransactions ) {
1405 $userAbort = ignore_user_abort( true );
1408 $revision = new Revision( array(
1409 'page' => $this->getId(),
1410 'comment' => $summary,
1411 'minor_edit' => $isminor,
1412 'text' => $serialized,
1414 'parent_id' => $oldid,
1415 'user' => $user->getId(),
1416 'user_text' => $user->getName(),
1417 'timestamp' => $now,
1418 'content_model' => $content->getModelName(),
1419 'content_format' => $serialisation_format,
1422 $changed = !$content->equals( $old_content );
1426 $revisionId = $revision->insertOn( $dbw );
1430 # Note that we use $this->mLatest instead of fetching a value from the master DB
1431 # during the course of this function. This makes sure that EditPage can detect
1432 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1433 # before this function is called. A previous function used a separate query, this
1434 # creates a window where concurrent edits can cause an ignored edit conflict.
1435 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1438 /* Belated edit conflict! Run away!! */
1439 $status->fatal( 'edit-conflict' );
1441 # Delete the invalid revision if the DB is not transactional
1442 if ( !$wgDBtransactions ) {
1443 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1449 global $wgUseRCPatrol;
1450 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1451 # Update recentchanges
1452 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1453 # Mark as patrolled if the user can do so
1454 $patrolled = $wgUseRCPatrol && !count(
1455 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1456 # Add RC row to the DB
1457 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1458 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1459 $revisionId, $patrolled
1462 # Log auto-patrolled edits
1464 PatrolLog
::record( $rc, true );
1467 $user->incEditCount();
1471 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1472 // related variables correctly
1473 $revision->setId( $this->getLatest() );
1476 if ( !$wgDBtransactions ) {
1477 ignore_user_abort( $userAbort );
1480 // Now that ignore_user_abort is restored, we can respond to fatal errors
1481 if ( !$status->isOK() ) {
1482 wfProfileOut( __METHOD__
);
1486 # Update links tables, site stats, etc.
1487 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1488 'oldcountable' => $oldcountable ) );
1491 $status->warning( 'edit-no-change' );
1493 // Update page_touched, this is usually implicit in the page update
1494 // Other cache updates are done in onArticleEdit()
1495 $this->mTitle
->invalidateCache();
1498 # Create new article
1499 $status->value
['new'] = true;
1503 # Add the page record; stake our claim on this title!
1504 # This will return false if the article already exists
1505 $newid = $this->insertOn( $dbw );
1507 if ( $newid === false ) {
1509 $status->fatal( 'edit-already-exists' );
1511 wfProfileOut( __METHOD__
);
1515 # Save the revision text...
1516 $revision = new Revision( array(
1518 'comment' => $summary,
1519 'minor_edit' => $isminor,
1520 'text' => $serialized,
1522 'user' => $user->getId(),
1523 'user_text' => $user->getName(),
1524 'timestamp' => $now,
1525 'content_model' => $content->getModelName(),
1526 'content_format' => $serialisation_format,
1528 $revisionId = $revision->insertOn( $dbw );
1530 # Update the page record with revision data
1531 $this->updateRevisionOn( $dbw, $revision, 0 );
1533 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1535 # Update recentchanges
1536 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1537 global $wgUseRCPatrol, $wgUseNPPatrol;
1539 # Mark as patrolled if the user can do so
1540 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1541 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1542 # Add RC row to the DB
1543 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1544 '', $content->getSize(), $revisionId, $patrolled );
1546 # Log auto-patrolled edits
1548 PatrolLog
::record( $rc, true );
1551 $user->incEditCount();
1554 # Update links, etc.
1555 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1557 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1558 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1560 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1561 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1564 # Do updates right now unless deferral was requested
1565 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1566 DeferredUpdates
::doUpdates();
1569 // Return the new revision (or null) to the caller
1570 $status->value
['revision'] = $revision;
1572 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1573 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1575 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1576 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1578 # Promote user to any groups they meet the criteria for
1579 $user->addAutopromoteOnceGroups( 'onEdit' );
1581 wfProfileOut( __METHOD__
);
1586 * Get parser options suitable for rendering the primary article wikitext
1587 * @param User|string $user User object or 'canonical'
1588 * @return ParserOptions
1590 public function makeParserOptions( $user ) {
1592 if ( $user instanceof User
) { // settings per user (even anons)
1593 $options = ParserOptions
::newFromUser( $user );
1594 } else { // canonical settings
1595 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1597 $options->enableLimitReport(); // show inclusion/loop reports
1598 $options->setTidy( true ); // fix bad HTML
1603 * Prepare text which is about to be saved.
1604 * Returns a stdclass with source, pst and output members
1605 * @deprecated in 1.20: use prepareContentForEdit instead.
1607 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) { #FIXME: use prepareContentForEdit() instead #XXX: who uses this?!
1608 #TODO: log use of deprecated function
1609 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1610 return $this->prepareContentForEdit( $content, $revid , $user );
1614 * Prepare content which is about to be saved.
1615 * Returns a stdclass with source, pst and output members
1617 * @param \Content $content
1618 * @param null $revid
1619 * @param null|\User $user
1620 * @param null $serialization_format
1621 * @return bool|object
1623 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) { #FIXME: use this #XXX: really public?!
1624 global $wgParser, $wgContLang, $wgUser;
1625 $user = is_null( $user ) ?
$wgUser : $user;
1626 // @TODO fixme: check $user->getId() here???
1628 if ( $this->mPreparedEdit
1629 && $this->mPreparedEdit
->newContent
1630 && $this->mPreparedEdit
->newContent
->equals( $content )
1631 && $this->mPreparedEdit
->revid
== $revid
1632 && $this->mPreparedEdit
->format
== $serialization_format
1633 #XXX: also check $user here?
1636 return $this->mPreparedEdit
;
1639 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1640 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1642 $edit = (object)array();
1643 $edit->revid
= $revid;
1645 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1646 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1647 $edit->format
= $serialization_format;
1649 $edit->popts
= $this->makeParserOptions( 'canonical' );
1650 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1652 $edit->newContent
= $content;
1653 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1655 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1656 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1658 $this->mPreparedEdit
= $edit;
1664 * Do standard deferred updates after page edit.
1665 * Update links tables, site stats, search index and message cache.
1666 * Purges pages that include this page if the text was changed here.
1667 * Every 100th edit, prune the recent changes table.
1670 * @param $revision Revision object
1671 * @param $user User object that did the revision
1672 * @param $options Array of options, following indexes are used:
1673 * - changed: boolean, whether the revision changed the content (default true)
1674 * - created: boolean, whether the revision created the page (default false)
1675 * - oldcountable: boolean or null (default null):
1676 * - boolean: whether the page was counted as an article before that
1677 * revision, only used in changed is true and created is false
1678 * - null: don't change the article count
1680 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1681 global $wgEnableParserCache;
1683 wfProfileIn( __METHOD__
);
1685 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1686 $content = $revision->getContent();
1689 # Be careful not to double-PST: $text is usually already PST-ed once
1690 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1691 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1692 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1694 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1695 $editInfo = $this->mPreparedEdit
;
1698 # Save it to the parser cache
1699 if ( $wgEnableParserCache ) {
1700 $parserCache = ParserCache
::singleton();
1701 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1704 # Update the links tables
1705 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1708 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1710 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1711 if ( 0 == mt_rand( 0, 99 ) ) {
1712 // Flush old entries from the `recentchanges` table; we do this on
1713 // random requests so as to avoid an increase in writes for no good reason
1716 $dbw = wfGetDB( DB_MASTER
);
1717 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1720 array( "rc_timestamp < '$cutoff'" ),
1726 if ( !$this->mTitle
->exists() ) {
1727 wfProfileOut( __METHOD__
);
1731 $id = $this->getId();
1732 $title = $this->mTitle
->getPrefixedDBkey();
1733 $shortTitle = $this->mTitle
->getDBkey();
1735 if ( !$options['changed'] ) {
1738 } elseif ( $options['created'] ) {
1739 $good = (int)$this->isCountable( $editInfo );
1741 } elseif ( $options['oldcountable'] !== null ) {
1742 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1749 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1750 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
1752 # If this is another user's talk page, update newtalk.
1753 # Don't do this if $options['changed'] = false (null-edits) nor if
1754 # it's a minor edit and the user doesn't want notifications for those.
1755 if ( $options['changed']
1756 && $this->mTitle
->getNamespace() == NS_USER_TALK
1757 && $shortTitle != $user->getTitleKey()
1758 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1760 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1761 $other = User
::newFromName( $shortTitle, false );
1763 wfDebug( __METHOD__
. ": invalid username\n" );
1764 } elseif ( User
::isIP( $shortTitle ) ) {
1765 // An anonymous user
1766 $other->setNewtalk( true );
1767 } elseif ( $other->isLoggedIn() ) {
1768 $other->setNewtalk( true );
1770 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1775 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1776 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
1777 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
1779 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
1782 if( $options['created'] ) {
1783 self
::onArticleCreate( $this->mTitle
);
1785 self
::onArticleEdit( $this->mTitle
);
1788 wfProfileOut( __METHOD__
);
1792 * Edit an article without doing all that other stuff
1793 * The article must already exist; link tables etc
1794 * are not updated, caches are not flushed.
1796 * @param $text String: text submitted
1797 * @param $user User The relevant user
1798 * @param $comment String: comment submitted
1799 * @param $minor Boolean: whereas it's a minor modification
1801 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1802 #TODO: log use of deprecated function
1803 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1804 return $this->doQuickEdit( $content, $user, $comment , $minor );
1808 * Edit an article without doing all that other stuff
1809 * The article must already exist; link tables etc
1810 * are not updated, caches are not flushed.
1812 * @param $content Content: content submitted
1813 * @param $user User The relevant user
1814 * @param $comment String: comment submitted
1815 * @param $serialisation_format String: format for storing the content in the database
1816 * @param $minor Boolean: whereas it's a minor modification
1818 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
1819 wfProfileIn( __METHOD__
);
1821 $serialized = $content->serialize( $serialisation_format );
1823 $dbw = wfGetDB( DB_MASTER
);
1824 $revision = new Revision( array(
1825 'page' => $this->getId(),
1826 'text' => $serialized,
1827 'length' => $content->getSize(),
1828 'comment' => $comment,
1829 'minor_edit' => $minor ?
1 : 0,
1831 $revision->insertOn( $dbw );
1832 $this->updateRevisionOn( $dbw, $revision );
1834 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1836 wfProfileOut( __METHOD__
);
1840 * Update the article's restriction field, and leave a log entry.
1841 * This works for protection both existing and non-existing pages.
1843 * @param $limit Array: set of restriction keys
1844 * @param $reason String
1845 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1846 * @param $expiry Array: per restriction type expiration
1847 * @param $user User The user updating the restrictions
1848 * @return bool true on success
1850 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1853 if ( wfReadOnly() ) {
1854 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1857 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1859 $id = $this->mTitle
->getArticleID();
1865 // Take this opportunity to purge out expired restrictions
1866 Title
::purgeExpiredRestrictions();
1868 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1869 # we expect a single selection, but the schema allows otherwise.
1870 $isProtected = false;
1874 $dbw = wfGetDB( DB_MASTER
);
1876 foreach ( $restrictionTypes as $action ) {
1877 if ( !isset( $expiry[$action] ) ) {
1878 $expiry[$action] = $dbw->getInfinity();
1880 if ( !isset( $limit[$action] ) ) {
1881 $limit[$action] = '';
1882 } elseif ( $limit[$action] != '' ) {
1886 # Get current restrictions on $action
1887 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1888 if ( $current != '' ) {
1889 $isProtected = true;
1892 if ( $limit[$action] != $current ) {
1894 } elseif ( $limit[$action] != '' ) {
1895 # Only check expiry change if the action is actually being
1896 # protected, since expiry does nothing on an not-protected
1898 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1904 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1908 # If nothing's changed, do nothing
1910 return Status
::newGood();
1913 if ( !$protect ) { # No protection at all means unprotection
1914 $revCommentMsg = 'unprotectedarticle';
1915 $logAction = 'unprotect';
1916 } elseif ( $isProtected ) {
1917 $revCommentMsg = 'modifiedarticleprotection';
1918 $logAction = 'modify';
1920 $revCommentMsg = 'protectedarticle';
1921 $logAction = 'protect';
1924 $encodedExpiry = array();
1925 $protectDescription = '';
1926 foreach ( $limit as $action => $restrictions ) {
1927 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1928 if ( $restrictions != '' ) {
1929 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1930 if ( $encodedExpiry[$action] != 'infinity' ) {
1931 $protectDescription .= wfMsgForContent( 'protect-expiring',
1932 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1933 $wgContLang->date( $expiry[$action], false, false ) ,
1934 $wgContLang->time( $expiry[$action], false, false ) );
1936 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1939 $protectDescription .= ') ';
1942 $protectDescription = trim( $protectDescription );
1944 if ( $id ) { # Protection of existing page
1945 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1946 return Status
::newGood();
1949 # Only restrictions with the 'protect' right can cascade...
1950 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1951 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1953 # The schema allows multiple restrictions
1954 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1958 # Update restrictions table
1959 foreach ( $limit as $action => $restrictions ) {
1960 if ( $restrictions != '' ) {
1961 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1962 array( 'pr_page' => $id,
1963 'pr_type' => $action,
1964 'pr_level' => $restrictions,
1965 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1966 'pr_expiry' => $encodedExpiry[$action]
1971 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1972 'pr_type' => $action ), __METHOD__
);
1976 # Prepare a null revision to be added to the history
1977 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1979 $editComment .= ": $reason";
1981 if ( $protectDescription ) {
1982 $editComment .= " ($protectDescription)";
1985 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1988 # Insert a null revision
1989 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1990 $nullRevId = $nullRevision->insertOn( $dbw );
1992 $latest = $this->getLatest();
1993 # Update page record
1994 $dbw->update( 'page',
1996 'page_touched' => $dbw->timestamp(),
1997 'page_restrictions' => '',
1998 'page_latest' => $nullRevId
1999 ), array( /* WHERE */
2004 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2005 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2006 } else { # Protection of non-existing page (also known as "title protection")
2007 # Cascade protection is meaningless in this case
2010 if ( $limit['create'] != '' ) {
2011 $dbw->replace( 'protected_titles',
2012 array( array( 'pt_namespace', 'pt_title' ) ),
2014 'pt_namespace' => $this->mTitle
->getNamespace(),
2015 'pt_title' => $this->mTitle
->getDBkey(),
2016 'pt_create_perm' => $limit['create'],
2017 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2018 'pt_expiry' => $encodedExpiry['create'],
2019 'pt_user' => $user->getId(),
2020 'pt_reason' => $reason,
2024 $dbw->delete( 'protected_titles',
2026 'pt_namespace' => $this->mTitle
->getNamespace(),
2027 'pt_title' => $this->mTitle
->getDBkey()
2033 $this->mTitle
->flushRestrictions();
2035 if ( $logAction == 'unprotect' ) {
2036 $logParams = array();
2038 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2041 # Update the protection log
2042 $log = new LogPage( 'protect' );
2043 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2045 return Status
::newGood();
2049 * Take an array of page restrictions and flatten it to a string
2050 * suitable for insertion into the page_restrictions field.
2051 * @param $limit Array
2054 protected static function flattenRestrictions( $limit ) {
2055 if ( !is_array( $limit ) ) {
2056 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2062 foreach ( $limit as $action => $restrictions ) {
2063 if ( $restrictions != '' ) {
2064 $bits[] = "$action=$restrictions";
2068 return implode( ':', $bits );
2072 * Back-end article deletion
2073 * Deletes the article with database consistency, writes logs, purges caches
2075 * @param $reason string delete reason for deletion log
2076 * @param $suppress bitfield
2077 * Revision::DELETED_TEXT
2078 * Revision::DELETED_COMMENT
2079 * Revision::DELETED_USER
2080 * Revision::DELETED_RESTRICTED
2081 * @param $id int article ID
2082 * @param $commit boolean defaults to true, triggers transaction end
2083 * @param &$errors Array of errors to append to
2084 * @param $user User The relevant user
2085 * @return boolean true if successful
2087 public function doDeleteArticle(
2088 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2091 $user = is_null( $user ) ?
$wgUser : $user;
2093 wfDebug( __METHOD__
. "\n" );
2095 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2098 $dbw = wfGetDB( DB_MASTER
);
2099 $t = $this->mTitle
->getDBkey();
2100 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2102 if ( $t === '' ||
$id == 0 ) {
2106 // Bitfields to further suppress the content
2109 // This should be 15...
2110 $bitfield |
= Revision
::DELETED_TEXT
;
2111 $bitfield |
= Revision
::DELETED_COMMENT
;
2112 $bitfield |
= Revision
::DELETED_USER
;
2113 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2115 $bitfield = 'rev_deleted';
2119 // For now, shunt the revision data into the archive table.
2120 // Text is *not* removed from the text table; bulk storage
2121 // is left intact to avoid breaking block-compression or
2122 // immutable storage schemes.
2124 // For backwards compatibility, note that some older archive
2125 // table entries will have ar_text and ar_flags fields still.
2127 // In the future, we may keep revisions and mark them with
2128 // the rev_deleted field, which is reserved for this purpose.
2129 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2131 'ar_namespace' => 'page_namespace',
2132 'ar_title' => 'page_title',
2133 'ar_comment' => 'rev_comment',
2134 'ar_user' => 'rev_user',
2135 'ar_user_text' => 'rev_user_text',
2136 'ar_timestamp' => 'rev_timestamp',
2137 'ar_minor_edit' => 'rev_minor_edit',
2138 'ar_rev_id' => 'rev_id',
2139 'ar_parent_id' => 'rev_parent_id',
2140 'ar_text_id' => 'rev_text_id',
2141 'ar_text' => '\'\'', // Be explicit to appease
2142 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2143 'ar_len' => 'rev_len',
2144 'ar_page_id' => 'page_id',
2145 'ar_deleted' => $bitfield,
2146 'ar_sha1' => 'rev_content_model',
2147 'ar_content_format' => 'rev_content_format',
2148 'ar_content_format' => 'rev_sha1'
2151 'page_id = rev_page'
2155 # Now that it's safely backed up, delete it
2156 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2157 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2164 $this->doDeleteUpdates( $id );
2166 # Log the deletion, if the page was suppressed, log it at Oversight instead
2167 $logtype = $suppress ?
'suppress' : 'delete';
2169 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2170 $logEntry->setPerformer( $user );
2171 $logEntry->setTarget( $this->mTitle
);
2172 $logEntry->setComment( $reason );
2173 $logid = $logEntry->insert();
2174 $logEntry->publish( $logid );
2180 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2185 * Do some database updates after deletion
2187 * @param $id Int: page_id value of the page being deleted
2189 public function doDeleteUpdates( $id ) {
2190 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2192 $dbw = wfGetDB( DB_MASTER
);
2194 # Delete restrictions for it
2195 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2197 # Fix category table counts
2199 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2201 foreach ( $res as $row ) {
2202 $cats [] = $row->cl_to
;
2205 $this->updateCategoryCounts( array(), $cats );
2207 # If using cascading deletes, we can skip some explicit deletes
2208 if ( !$dbw->cascadingDeletes() ) {
2209 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2211 # Delete outgoing links
2212 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2213 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2214 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2215 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2216 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2217 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2218 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2219 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2220 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2223 # If using cleanup triggers, we can skip some manual deletes
2224 if ( !$dbw->cleanupTriggers() ) {
2225 # Clean up recentchanges entries...
2226 $dbw->delete( 'recentchanges',
2227 array( 'rc_type != ' . RC_LOG
,
2228 'rc_namespace' => $this->mTitle
->getNamespace(),
2229 'rc_title' => $this->mTitle
->getDBkey() ),
2231 $dbw->delete( 'recentchanges',
2232 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2237 self
::onArticleDelete( $this->mTitle
);
2239 # Clear the cached article id so the interface doesn't act like we exist
2240 $this->mTitle
->resetArticleID( 0 );
2244 * Roll back the most recent consecutive set of edits to a page
2245 * from the same user; fails if there are no eligible edits to
2246 * roll back to, e.g. user is the sole contributor. This function
2247 * performs permissions checks on $user, then calls commitRollback()
2248 * to do the dirty work
2250 * @todo: seperate the business/permission stuff out from backend code
2252 * @param $fromP String: Name of the user whose edits to rollback.
2253 * @param $summary String: Custom summary. Set to default summary if empty.
2254 * @param $token String: Rollback token.
2255 * @param $bot Boolean: If true, mark all reverted edits as bot.
2257 * @param $resultDetails Array: contains result-specific array of additional values
2258 * 'alreadyrolled' : 'current' (rev)
2259 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2261 * @param $user User The user performing the rollback
2262 * @return array of errors, each error formatted as
2263 * array(messagekey, param1, param2, ...).
2264 * On success, the array is empty. This array can also be passed to
2265 * OutputPage::showPermissionsErrorPage().
2267 public function doRollback(
2268 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2270 $resultDetails = null;
2273 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2274 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2275 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2277 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2278 $errors[] = array( 'sessionfailure' );
2281 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2282 $errors[] = array( 'actionthrottledtext' );
2285 # If there were errors, bail out now
2286 if ( !empty( $errors ) ) {
2290 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2294 * Backend implementation of doRollback(), please refer there for parameter
2295 * and return value documentation
2297 * NOTE: This function does NOT check ANY permissions, it just commits the
2298 * rollback to the DB. Therefore, you should only call this function direct-
2299 * ly if you want to use custom permissions checks. If you don't, use
2300 * doRollback() instead.
2301 * @param $fromP String: Name of the user whose edits to rollback.
2302 * @param $summary String: Custom summary. Set to default summary if empty.
2303 * @param $bot Boolean: If true, mark all reverted edits as bot.
2305 * @param $resultDetails Array: contains result-specific array of additional values
2306 * @param $guser User The user performing the rollback
2308 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2309 global $wgUseRCPatrol, $wgContLang;
2311 $dbw = wfGetDB( DB_MASTER
);
2313 if ( wfReadOnly() ) {
2314 return array( array( 'readonlytext' ) );
2317 # Get the last editor
2318 $current = Revision
::newFromTitle( $this->mTitle
);
2319 if ( is_null( $current ) ) {
2320 # Something wrong... no page?
2321 return array( array( 'notanarticle' ) );
2324 $from = str_replace( '_', ' ', $fromP );
2325 # User name given should match up with the top revision.
2326 # If the user was deleted then $from should be empty.
2327 if ( $from != $current->getUserText() ) {
2328 $resultDetails = array( 'current' => $current );
2329 return array( array( 'alreadyrolled',
2330 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2331 htmlspecialchars( $fromP ),
2332 htmlspecialchars( $current->getUserText() )
2336 # Get the last edit not by this guy...
2337 # Note: these may not be public values
2338 $user = intval( $current->getRawUser() );
2339 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2340 $s = $dbw->selectRow( 'revision',
2341 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2342 array( 'rev_page' => $current->getPage(),
2343 "rev_user != {$user} OR rev_user_text != {$user_text}"
2345 array( 'USE INDEX' => 'page_timestamp',
2346 'ORDER BY' => 'rev_timestamp DESC' )
2348 if ( $s === false ) {
2349 # No one else ever edited this page
2350 return array( array( 'cantrollback' ) );
2351 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2352 # Only admins can see this text
2353 return array( array( 'notvisiblerev' ) );
2357 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2358 # Mark all reverted edits as bot
2362 if ( $wgUseRCPatrol ) {
2363 # Mark all reverted edits as patrolled
2364 $set['rc_patrolled'] = 1;
2367 if ( count( $set ) ) {
2368 $dbw->update( 'recentchanges', $set,
2370 'rc_cur_id' => $current->getPage(),
2371 'rc_user_text' => $current->getUserText(),
2372 "rc_timestamp > '{$s->rev_timestamp}'",
2377 # Generate the edit summary if necessary
2378 $target = Revision
::newFromId( $s->rev_id
);
2379 if ( empty( $summary ) ) {
2380 if ( $from == '' ) { // no public user name
2381 $summary = wfMsgForContent( 'revertpage-nouser' );
2383 $summary = wfMsgForContent( 'revertpage' );
2387 # Allow the custom summary to use the same args as the default message
2389 $target->getUserText(), $from, $s->rev_id
,
2390 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2391 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2393 $summary = wfMsgReplaceArgs( $summary, $args );
2396 $flags = EDIT_UPDATE
;
2398 if ( $guser->isAllowed( 'minoredit' ) ) {
2399 $flags |
= EDIT_MINOR
;
2402 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2403 $flags |
= EDIT_FORCE_BOT
;
2406 # Actually store the edit
2407 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2408 if ( !empty( $status->value
['revision'] ) ) {
2409 $revId = $status->value
['revision']->getId();
2414 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2416 $resultDetails = array(
2417 'summary' => $summary,
2418 'current' => $current,
2419 'target' => $target,
2427 * The onArticle*() functions are supposed to be a kind of hooks
2428 * which should be called whenever any of the specified actions
2431 * This is a good place to put code to clear caches, for instance.
2433 * This is called on page move and undelete, as well as edit
2435 * @param $title Title object
2437 public static function onArticleCreate( $title ) {
2438 # Update existence markers on article/talk tabs...
2439 if ( $title->isTalkPage() ) {
2440 $other = $title->getSubjectPage();
2442 $other = $title->getTalkPage();
2445 $other->invalidateCache();
2446 $other->purgeSquid();
2448 $title->touchLinks();
2449 $title->purgeSquid();
2450 $title->deleteTitleProtection();
2454 * Clears caches when article is deleted
2456 * @param $title Title
2458 public static function onArticleDelete( $title ) {
2459 # Update existence markers on article/talk tabs...
2460 if ( $title->isTalkPage() ) {
2461 $other = $title->getSubjectPage();
2463 $other = $title->getTalkPage();
2466 $other->invalidateCache();
2467 $other->purgeSquid();
2469 $title->touchLinks();
2470 $title->purgeSquid();
2473 HTMLFileCache
::clearFileCache( $title );
2476 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2477 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2481 if ( $title->getNamespace() == NS_FILE
) {
2482 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2483 $update->doUpdate();
2487 if ( $title->getNamespace() == NS_USER_TALK
) {
2488 $user = User
::newFromName( $title->getText(), false );
2490 $user->setNewtalk( false );
2495 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2499 * Purge caches on page update etc
2501 * @param $title Title object
2502 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2504 public static function onArticleEdit( $title ) {
2505 // Invalidate caches of articles which include this page
2506 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2509 // Invalidate the caches of all pages which redirect here
2510 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2512 # Purge squid for this page only
2513 $title->purgeSquid();
2515 # Clear file cache for this page only
2516 HTMLFileCache
::clearFileCache( $title );
2522 * Returns a list of hidden categories this page is a member of.
2523 * Uses the page_props and categorylinks tables.
2525 * @return Array of Title objects
2527 public function getHiddenCategories() {
2529 $id = $this->mTitle
->getArticleID();
2535 $dbr = wfGetDB( DB_SLAVE
);
2536 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2538 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2539 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2542 if ( $res !== false ) {
2543 foreach ( $res as $row ) {
2544 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2552 * Return an applicable autosummary if one exists for the given edit.
2553 * @param $oldtext String: the previous text of the page.
2554 * @param $newtext String: The submitted text of the page.
2555 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2556 * @return string An appropriate autosummary, or an empty string.
2557 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
2559 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2560 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2562 $handler = ContentHandler
::getForModelName( CONTENT_MODEL_WIKITEXT
);
2563 $oldContent = $handler->unserialize( $oldtext );
2564 $newContent = $handler->unserialize( $newtext );
2566 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2570 * Auto-generates a deletion reason
2572 * @param &$hasHistory Boolean: whether the page has a history
2573 * @return mixed String containing deletion reason or empty string, or boolean false
2574 * if no revision occurred
2575 * @deprecated since 1.20, use ContentHandler::getAutoDeleteReason() instead
2577 public function getAutoDeleteReason( &$hasHistory ) {
2578 #NOTE: stub for backwards-compatibility.
2580 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2581 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2585 * Update all the appropriate counts in the category table, given that
2586 * we've added the categories $added and deleted the categories $deleted.
2588 * @param $added array The names of categories that were added
2589 * @param $deleted array The names of categories that were deleted
2591 public function updateCategoryCounts( $added, $deleted ) {
2592 $ns = $this->mTitle
->getNamespace();
2593 $dbw = wfGetDB( DB_MASTER
);
2595 # First make sure the rows exist. If one of the "deleted" ones didn't
2596 # exist, we might legitimately not create it, but it's simpler to just
2597 # create it and then give it a negative value, since the value is bogus
2600 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2601 $insertCats = array_merge( $added, $deleted );
2602 if ( !$insertCats ) {
2603 # Okay, nothing to do
2607 $insertRows = array();
2609 foreach ( $insertCats as $cat ) {
2610 $insertRows[] = array(
2611 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2615 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2617 $addFields = array( 'cat_pages = cat_pages + 1' );
2618 $removeFields = array( 'cat_pages = cat_pages - 1' );
2620 if ( $ns == NS_CATEGORY
) {
2621 $addFields[] = 'cat_subcats = cat_subcats + 1';
2622 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2623 } elseif ( $ns == NS_FILE
) {
2624 $addFields[] = 'cat_files = cat_files + 1';
2625 $removeFields[] = 'cat_files = cat_files - 1';
2632 array( 'cat_title' => $added ),
2641 array( 'cat_title' => $deleted ),
2648 * Updates cascading protections
2650 * @param $parserOutput ParserOutput object for the current version
2652 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2653 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2657 // templatelinks table may have become out of sync,
2658 // especially if using variable-based transclusions.
2659 // For paranoia, check if things have changed and if
2660 // so apply updates to the database. This will ensure
2661 // that cascaded protections apply as soon as the changes
2664 # Get templates from templatelinks
2665 $id = $this->mTitle
->getArticleID();
2667 $tlTemplates = array();
2669 $dbr = wfGetDB( DB_SLAVE
);
2670 $res = $dbr->select( array( 'templatelinks' ),
2671 array( 'tl_namespace', 'tl_title' ),
2672 array( 'tl_from' => $id ),
2676 foreach ( $res as $row ) {
2677 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2680 # Get templates from parser output.
2681 $poTemplates = array();
2682 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2683 foreach ( $templates as $dbk => $id ) {
2684 $poTemplates["$ns:$dbk"] = true;
2689 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2691 if ( count( $templates_diff ) > 0 ) {
2692 # Whee, link updates time.
2693 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2699 * Return a list of templates used by this article.
2700 * Uses the templatelinks table
2702 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2703 * @return Array of Title objects
2705 public function getUsedTemplates() {
2706 return $this->mTitle
->getTemplateLinksFrom();
2710 * Perform article updates on a special page creation.
2712 * @param $rev Revision object
2714 * @todo This is a shitty interface function. Kill it and replace the
2715 * other shitty functions like doEditUpdates and such so it's not needed
2717 * @deprecated since 1.18, use doEditUpdates()
2719 public function createUpdates( $rev ) {
2720 wfDeprecated( __METHOD__
, '1.18' );
2722 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2726 * This function is called right before saving the wikitext,
2727 * so we can do things like signatures and links-in-context.
2729 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2730 * @param $text String article contents
2731 * @param $user User object: user doing the edit
2732 * @param $popts ParserOptions object: parser options, default options for
2733 * the user loaded if null given
2734 * @return string article contents with altered wikitext markup (signatures
2735 * converted, {{subst:}}, templates, etc.)
2737 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2738 global $wgParser, $wgUser;
2740 wfDeprecated( __METHOD__
, '1.19' );
2742 $user = is_null( $user ) ?
$wgUser : $user;
2744 if ( $popts === null ) {
2745 $popts = ParserOptions
::newFromUser( $user );
2748 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2752 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2754 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2757 public function isBigDeletion() {
2758 wfDeprecated( __METHOD__
, '1.19' );
2759 return $this->mTitle
->isBigDeletion();
2763 * Get the approximate revision count of this page.
2765 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2768 public function estimateRevisionCount() {
2769 wfDeprecated( __METHOD__
, '1.19' );
2770 return $this->mTitle
->estimateRevisionCount();
2774 * Update the article's restriction field, and leave a log entry.
2776 * @deprecated since 1.19
2777 * @param $limit Array: set of restriction keys
2778 * @param $reason String
2779 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2780 * @param $expiry Array: per restriction type expiration
2781 * @param $user User The user updating the restrictions
2782 * @return bool true on success
2784 public function updateRestrictions(
2785 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2789 $user = is_null( $user ) ?
$wgUser : $user;
2791 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2795 * @deprecated since 1.18
2797 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2798 wfDeprecated( __METHOD__
, '1.18' );
2800 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2804 * @deprecated since 1.18
2806 public function viewUpdates() {
2807 wfDeprecated( __METHOD__
, '1.18' );
2809 return $this->doViewUpdates( $wgUser );
2813 * @deprecated since 1.18
2815 public function useParserCache( $oldid ) {
2816 wfDeprecated( __METHOD__
, '1.18' );
2818 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2822 class PoolWorkArticleView
extends PoolCounterWork
{
2840 * @var ParserOptions
2842 private $parserOptions;
2850 * @var ParserOutput|false
2852 private $parserOutput = false;
2857 private $isDirty = false;
2862 private $error = false;
2868 * @param $revid Integer: ID of the revision being parsed
2869 * @param $useParserCache Boolean: whether to use the parser cache
2870 * @param $parserOptions parserOptions to use for the parse operation
2871 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
2873 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
2874 if ( is_string($content) ) { #BC: old style call
2875 $modelName = $page->getRevision()->getContentModelName();
2876 $format = $page->getRevision()->getContentFormat();
2877 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelName, $format );
2880 $this->page
= $page;
2881 $this->revid
= $revid;
2882 $this->cacheable
= $useParserCache;
2883 $this->parserOptions
= $parserOptions;
2884 $this->content
= $content;
2885 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2886 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2890 * Get the ParserOutput from this object, or false in case of failure
2892 * @return ParserOutput
2894 public function getParserOutput() {
2895 return $this->parserOutput
;
2899 * Get whether the ParserOutput is a dirty one (i.e. expired)
2903 public function getIsDirty() {
2904 return $this->isDirty
;
2908 * Get a Status object in case of error or false otherwise
2910 * @return Status|false
2912 public function getError() {
2913 return $this->error
;
2920 global $wgParser, $wgUseFileCache;
2922 $isCurrent = $this->revid
=== $this->page
->getLatest();
2924 if ( $this->content
!== null ) {
2925 $content = $this->content
;
2926 } elseif ( $isCurrent ) {
2927 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
2929 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2930 if ( $rev === null ) {
2933 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
2937 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
2942 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2943 $this->page
->getTitle()->getPrefixedDBkey() ) );
2946 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2947 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2950 // Make sure file cache is not used on uncacheable content.
2951 // Output that has magic words in it can still use the parser cache
2952 // (if enabled), though it will generally expire sooner.
2953 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2954 $wgUseFileCache = false;
2958 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2967 function getCachedWork() {
2968 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2970 if ( $this->parserOutput
=== false ) {
2971 wfDebug( __METHOD__
. ": parser cache miss\n" );
2974 wfDebug( __METHOD__
. ": parser cache hit\n" );
2982 function fallback() {
2983 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2985 if ( $this->parserOutput
=== false ) {
2986 wfDebugLog( 'dirty', "dirty missing\n" );
2987 wfDebug( __METHOD__
. ": no dirty cache\n" );
2990 wfDebug( __METHOD__
. ": sending dirty output\n" );
2991 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2992 $this->isDirty
= true;
2998 * @param $status Status
3000 function error( $status ) {
3001 $this->error
= $status;