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 if ( !$old_content ) $old_content = null;
1379 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1382 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1383 $serialized = $editInfo->pst
;
1384 $content = $editInfo->pstContent
;
1385 $newsize = $content->getSize();
1387 $dbw = wfGetDB( DB_MASTER
);
1388 $now = wfTimestampNow();
1389 $this->mTimestamp
= $now;
1391 if ( $flags & EDIT_UPDATE
) {
1392 # Update article, but only if changed.
1393 $status->value
['new'] = false;
1396 # Article gone missing
1397 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1398 $status->fatal( 'edit-gone-missing' );
1400 wfProfileOut( __METHOD__
);
1404 # Make sure the revision is either completely inserted or not inserted at all
1405 if ( !$wgDBtransactions ) {
1406 $userAbort = ignore_user_abort( true );
1409 $revision = new Revision( array(
1410 'page' => $this->getId(),
1411 'comment' => $summary,
1412 'minor_edit' => $isminor,
1413 'text' => $serialized,
1415 'parent_id' => $oldid,
1416 'user' => $user->getId(),
1417 'user_text' => $user->getName(),
1418 'timestamp' => $now,
1419 'content_model' => $content->getModelName(),
1420 'content_format' => $serialisation_format,
1423 $changed = !$content->equals( $old_content );
1427 $revisionId = $revision->insertOn( $dbw );
1431 # Note that we use $this->mLatest instead of fetching a value from the master DB
1432 # during the course of this function. This makes sure that EditPage can detect
1433 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1434 # before this function is called. A previous function used a separate query, this
1435 # creates a window where concurrent edits can cause an ignored edit conflict.
1436 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1439 /* Belated edit conflict! Run away!! */
1440 $status->fatal( 'edit-conflict' );
1442 # Delete the invalid revision if the DB is not transactional
1443 if ( !$wgDBtransactions ) {
1444 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1450 global $wgUseRCPatrol;
1451 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1452 # Update recentchanges
1453 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1454 # Mark as patrolled if the user can do so
1455 $patrolled = $wgUseRCPatrol && !count(
1456 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1457 # Add RC row to the DB
1458 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1459 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1460 $revisionId, $patrolled
1463 # Log auto-patrolled edits
1465 PatrolLog
::record( $rc, true );
1468 $user->incEditCount();
1472 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1473 // related variables correctly
1474 $revision->setId( $this->getLatest() );
1477 if ( !$wgDBtransactions ) {
1478 ignore_user_abort( $userAbort );
1481 // Now that ignore_user_abort is restored, we can respond to fatal errors
1482 if ( !$status->isOK() ) {
1483 wfProfileOut( __METHOD__
);
1487 # Update links tables, site stats, etc.
1488 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1489 'oldcountable' => $oldcountable ) );
1492 $status->warning( 'edit-no-change' );
1494 // Update page_touched, this is usually implicit in the page update
1495 // Other cache updates are done in onArticleEdit()
1496 $this->mTitle
->invalidateCache();
1499 # Create new article
1500 $status->value
['new'] = true;
1504 # Add the page record; stake our claim on this title!
1505 # This will return false if the article already exists
1506 $newid = $this->insertOn( $dbw );
1508 if ( $newid === false ) {
1510 $status->fatal( 'edit-already-exists' );
1512 wfProfileOut( __METHOD__
);
1516 # Save the revision text...
1517 $revision = new Revision( array(
1519 'comment' => $summary,
1520 'minor_edit' => $isminor,
1521 'text' => $serialized,
1523 'user' => $user->getId(),
1524 'user_text' => $user->getName(),
1525 'timestamp' => $now,
1526 'content_model' => $content->getModelName(),
1527 'content_format' => $serialisation_format,
1529 $revisionId = $revision->insertOn( $dbw );
1531 # Update the page record with revision data
1532 $this->updateRevisionOn( $dbw, $revision, 0 );
1534 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1536 # Update recentchanges
1537 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1538 global $wgUseRCPatrol, $wgUseNPPatrol;
1540 # Mark as patrolled if the user can do so
1541 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1542 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1543 # Add RC row to the DB
1544 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1545 '', $content->getSize(), $revisionId, $patrolled );
1547 # Log auto-patrolled edits
1549 PatrolLog
::record( $rc, true );
1552 $user->incEditCount();
1555 # Update links, etc.
1556 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1558 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1559 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1561 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1562 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1565 # Do updates right now unless deferral was requested
1566 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1567 DeferredUpdates
::doUpdates();
1570 // Return the new revision (or null) to the caller
1571 $status->value
['revision'] = $revision;
1573 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1574 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1576 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1577 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1579 # Promote user to any groups they meet the criteria for
1580 $user->addAutopromoteOnceGroups( 'onEdit' );
1582 wfProfileOut( __METHOD__
);
1587 * Get parser options suitable for rendering the primary article wikitext
1588 * @param User|string $user User object or 'canonical'
1589 * @return ParserOptions
1591 public function makeParserOptions( $user ) {
1593 if ( $user instanceof User
) { // settings per user (even anons)
1594 $options = ParserOptions
::newFromUser( $user );
1595 } else { // canonical settings
1596 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1598 $options->enableLimitReport(); // show inclusion/loop reports
1599 $options->setTidy( true ); // fix bad HTML
1604 * Prepare text which is about to be saved.
1605 * Returns a stdclass with source, pst and output members
1606 * @deprecated in 1.20: use prepareContentForEdit instead.
1608 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) { #FIXME: use prepareContentForEdit() instead #XXX: who uses this?!
1609 #TODO: log use of deprecated function
1610 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1611 return $this->prepareContentForEdit( $content, $revid , $user );
1615 * Prepare content which is about to be saved.
1616 * Returns a stdclass with source, pst and output members
1618 * @param \Content $content
1619 * @param null $revid
1620 * @param null|\User $user
1621 * @param null $serialization_format
1622 * @return bool|object
1624 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) { #FIXME: use this #XXX: really public?!
1625 global $wgParser, $wgContLang, $wgUser;
1626 $user = is_null( $user ) ?
$wgUser : $user;
1627 // @TODO fixme: check $user->getId() here???
1629 if ( $this->mPreparedEdit
1630 && $this->mPreparedEdit
->newContent
1631 && $this->mPreparedEdit
->newContent
->equals( $content )
1632 && $this->mPreparedEdit
->revid
== $revid
1633 && $this->mPreparedEdit
->format
== $serialization_format
1634 #XXX: also check $user here?
1637 return $this->mPreparedEdit
;
1640 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1641 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1643 $edit = (object)array();
1644 $edit->revid
= $revid;
1646 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1647 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1648 $edit->format
= $serialization_format;
1650 $edit->popts
= $this->makeParserOptions( 'canonical' );
1651 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1653 $edit->newContent
= $content;
1654 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1656 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1657 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1659 $this->mPreparedEdit
= $edit;
1665 * Do standard deferred updates after page edit.
1666 * Update links tables, site stats, search index and message cache.
1667 * Purges pages that include this page if the text was changed here.
1668 * Every 100th edit, prune the recent changes table.
1671 * @param $revision Revision object
1672 * @param $user User object that did the revision
1673 * @param $options Array of options, following indexes are used:
1674 * - changed: boolean, whether the revision changed the content (default true)
1675 * - created: boolean, whether the revision created the page (default false)
1676 * - oldcountable: boolean or null (default null):
1677 * - boolean: whether the page was counted as an article before that
1678 * revision, only used in changed is true and created is false
1679 * - null: don't change the article count
1681 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1682 global $wgEnableParserCache;
1684 wfProfileIn( __METHOD__
);
1686 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1687 $content = $revision->getContent();
1690 # Be careful not to double-PST: $text is usually already PST-ed once
1691 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1692 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1693 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1695 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1696 $editInfo = $this->mPreparedEdit
;
1699 # Save it to the parser cache
1700 if ( $wgEnableParserCache ) {
1701 $parserCache = ParserCache
::singleton();
1702 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1705 # Update the links tables and other secondary data
1706 $updates = $editInfo->output
->getLinksUpdateAndOtherUpdates( $this->mTitle
);
1707 SecondaryDataUpdate
::runUpdates( $updates );
1709 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1711 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1712 if ( 0 == mt_rand( 0, 99 ) ) {
1713 // Flush old entries from the `recentchanges` table; we do this on
1714 // random requests so as to avoid an increase in writes for no good reason
1717 $dbw = wfGetDB( DB_MASTER
);
1718 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1721 array( "rc_timestamp < '$cutoff'" ),
1727 if ( !$this->mTitle
->exists() ) {
1728 wfProfileOut( __METHOD__
);
1732 $id = $this->getId();
1733 $title = $this->mTitle
->getPrefixedDBkey();
1734 $shortTitle = $this->mTitle
->getDBkey();
1736 if ( !$options['changed'] ) {
1739 } elseif ( $options['created'] ) {
1740 $good = (int)$this->isCountable( $editInfo );
1742 } elseif ( $options['oldcountable'] !== null ) {
1743 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1750 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1751 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
1753 # If this is another user's talk page, update newtalk.
1754 # Don't do this if $options['changed'] = false (null-edits) nor if
1755 # it's a minor edit and the user doesn't want notifications for those.
1756 if ( $options['changed']
1757 && $this->mTitle
->getNamespace() == NS_USER_TALK
1758 && $shortTitle != $user->getTitleKey()
1759 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1761 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1762 $other = User
::newFromName( $shortTitle, false );
1764 wfDebug( __METHOD__
. ": invalid username\n" );
1765 } elseif ( User
::isIP( $shortTitle ) ) {
1766 // An anonymous user
1767 $other->setNewtalk( true );
1768 } elseif ( $other->isLoggedIn() ) {
1769 $other->setNewtalk( true );
1771 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1776 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1777 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
1778 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
1780 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
1783 if( $options['created'] ) {
1784 self
::onArticleCreate( $this->mTitle
);
1786 self
::onArticleEdit( $this->mTitle
);
1789 wfProfileOut( __METHOD__
);
1793 * Edit an article without doing all that other stuff
1794 * The article must already exist; link tables etc
1795 * are not updated, caches are not flushed.
1797 * @param $text String: text submitted
1798 * @param $user User The relevant user
1799 * @param $comment String: comment submitted
1800 * @param $minor Boolean: whereas it's a minor modification
1802 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1803 #TODO: log use of deprecated function
1804 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1805 return $this->doQuickEdit( $content, $user, $comment , $minor );
1809 * Edit an article without doing all that other stuff
1810 * The article must already exist; link tables etc
1811 * are not updated, caches are not flushed.
1813 * @param $content Content: content submitted
1814 * @param $user User The relevant user
1815 * @param $comment String: comment submitted
1816 * @param $serialisation_format String: format for storing the content in the database
1817 * @param $minor Boolean: whereas it's a minor modification
1819 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
1820 wfProfileIn( __METHOD__
);
1822 $serialized = $content->serialize( $serialisation_format );
1824 $dbw = wfGetDB( DB_MASTER
);
1825 $revision = new Revision( array(
1826 'page' => $this->getId(),
1827 'text' => $serialized,
1828 'length' => $content->getSize(),
1829 'comment' => $comment,
1830 'minor_edit' => $minor ?
1 : 0,
1832 $revision->insertOn( $dbw );
1833 $this->updateRevisionOn( $dbw, $revision );
1835 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1837 wfProfileOut( __METHOD__
);
1841 * Update the article's restriction field, and leave a log entry.
1842 * This works for protection both existing and non-existing pages.
1844 * @param $limit Array: set of restriction keys
1845 * @param $reason String
1846 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1847 * @param $expiry Array: per restriction type expiration
1848 * @param $user User The user updating the restrictions
1849 * @return bool true on success
1851 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1854 if ( wfReadOnly() ) {
1855 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1858 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1860 $id = $this->mTitle
->getArticleID();
1866 // Take this opportunity to purge out expired restrictions
1867 Title
::purgeExpiredRestrictions();
1869 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1870 # we expect a single selection, but the schema allows otherwise.
1871 $isProtected = false;
1875 $dbw = wfGetDB( DB_MASTER
);
1877 foreach ( $restrictionTypes as $action ) {
1878 if ( !isset( $expiry[$action] ) ) {
1879 $expiry[$action] = $dbw->getInfinity();
1881 if ( !isset( $limit[$action] ) ) {
1882 $limit[$action] = '';
1883 } elseif ( $limit[$action] != '' ) {
1887 # Get current restrictions on $action
1888 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1889 if ( $current != '' ) {
1890 $isProtected = true;
1893 if ( $limit[$action] != $current ) {
1895 } elseif ( $limit[$action] != '' ) {
1896 # Only check expiry change if the action is actually being
1897 # protected, since expiry does nothing on an not-protected
1899 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1905 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1909 # If nothing's changed, do nothing
1911 return Status
::newGood();
1914 if ( !$protect ) { # No protection at all means unprotection
1915 $revCommentMsg = 'unprotectedarticle';
1916 $logAction = 'unprotect';
1917 } elseif ( $isProtected ) {
1918 $revCommentMsg = 'modifiedarticleprotection';
1919 $logAction = 'modify';
1921 $revCommentMsg = 'protectedarticle';
1922 $logAction = 'protect';
1925 $encodedExpiry = array();
1926 $protectDescription = '';
1927 foreach ( $limit as $action => $restrictions ) {
1928 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1929 if ( $restrictions != '' ) {
1930 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1931 if ( $encodedExpiry[$action] != 'infinity' ) {
1932 $protectDescription .= wfMsgForContent( 'protect-expiring',
1933 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1934 $wgContLang->date( $expiry[$action], false, false ) ,
1935 $wgContLang->time( $expiry[$action], false, false ) );
1937 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1940 $protectDescription .= ') ';
1943 $protectDescription = trim( $protectDescription );
1945 if ( $id ) { # Protection of existing page
1946 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1947 return Status
::newGood();
1950 # Only restrictions with the 'protect' right can cascade...
1951 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1952 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1954 # The schema allows multiple restrictions
1955 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1959 # Update restrictions table
1960 foreach ( $limit as $action => $restrictions ) {
1961 if ( $restrictions != '' ) {
1962 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1963 array( 'pr_page' => $id,
1964 'pr_type' => $action,
1965 'pr_level' => $restrictions,
1966 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1967 'pr_expiry' => $encodedExpiry[$action]
1972 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1973 'pr_type' => $action ), __METHOD__
);
1977 # Prepare a null revision to be added to the history
1978 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1980 $editComment .= ": $reason";
1982 if ( $protectDescription ) {
1983 $editComment .= " ($protectDescription)";
1986 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1989 # Insert a null revision
1990 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1991 $nullRevId = $nullRevision->insertOn( $dbw );
1993 $latest = $this->getLatest();
1994 # Update page record
1995 $dbw->update( 'page',
1997 'page_touched' => $dbw->timestamp(),
1998 'page_restrictions' => '',
1999 'page_latest' => $nullRevId
2000 ), array( /* WHERE */
2005 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2006 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2007 } else { # Protection of non-existing page (also known as "title protection")
2008 # Cascade protection is meaningless in this case
2011 if ( $limit['create'] != '' ) {
2012 $dbw->replace( 'protected_titles',
2013 array( array( 'pt_namespace', 'pt_title' ) ),
2015 'pt_namespace' => $this->mTitle
->getNamespace(),
2016 'pt_title' => $this->mTitle
->getDBkey(),
2017 'pt_create_perm' => $limit['create'],
2018 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2019 'pt_expiry' => $encodedExpiry['create'],
2020 'pt_user' => $user->getId(),
2021 'pt_reason' => $reason,
2025 $dbw->delete( 'protected_titles',
2027 'pt_namespace' => $this->mTitle
->getNamespace(),
2028 'pt_title' => $this->mTitle
->getDBkey()
2034 $this->mTitle
->flushRestrictions();
2036 if ( $logAction == 'unprotect' ) {
2037 $logParams = array();
2039 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2042 # Update the protection log
2043 $log = new LogPage( 'protect' );
2044 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2046 return Status
::newGood();
2050 * Take an array of page restrictions and flatten it to a string
2051 * suitable for insertion into the page_restrictions field.
2052 * @param $limit Array
2055 protected static function flattenRestrictions( $limit ) {
2056 if ( !is_array( $limit ) ) {
2057 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2063 foreach ( $limit as $action => $restrictions ) {
2064 if ( $restrictions != '' ) {
2065 $bits[] = "$action=$restrictions";
2069 return implode( ':', $bits );
2073 * Back-end article deletion
2074 * Deletes the article with database consistency, writes logs, purges caches
2076 * @param $reason string delete reason for deletion log
2077 * @param $suppress bitfield
2078 * Revision::DELETED_TEXT
2079 * Revision::DELETED_COMMENT
2080 * Revision::DELETED_USER
2081 * Revision::DELETED_RESTRICTED
2082 * @param $id int article ID
2083 * @param $commit boolean defaults to true, triggers transaction end
2084 * @param &$errors Array of errors to append to
2085 * @param $user User The relevant user
2086 * @return boolean true if successful
2088 public function doDeleteArticle(
2089 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2092 $user = is_null( $user ) ?
$wgUser : $user;
2094 wfDebug( __METHOD__
. "\n" );
2096 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2099 $dbw = wfGetDB( DB_MASTER
);
2100 $t = $this->mTitle
->getDBkey();
2101 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2103 if ( $t === '' ||
$id == 0 ) {
2107 // Bitfields to further suppress the content
2110 // This should be 15...
2111 $bitfield |
= Revision
::DELETED_TEXT
;
2112 $bitfield |
= Revision
::DELETED_COMMENT
;
2113 $bitfield |
= Revision
::DELETED_USER
;
2114 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2116 $bitfield = 'rev_deleted';
2120 // For now, shunt the revision data into the archive table.
2121 // Text is *not* removed from the text table; bulk storage
2122 // is left intact to avoid breaking block-compression or
2123 // immutable storage schemes.
2125 // For backwards compatibility, note that some older archive
2126 // table entries will have ar_text and ar_flags fields still.
2128 // In the future, we may keep revisions and mark them with
2129 // the rev_deleted field, which is reserved for this purpose.
2130 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2132 'ar_namespace' => 'page_namespace',
2133 'ar_title' => 'page_title',
2134 'ar_comment' => 'rev_comment',
2135 'ar_user' => 'rev_user',
2136 'ar_user_text' => 'rev_user_text',
2137 'ar_timestamp' => 'rev_timestamp',
2138 'ar_minor_edit' => 'rev_minor_edit',
2139 'ar_rev_id' => 'rev_id',
2140 'ar_parent_id' => 'rev_parent_id',
2141 'ar_text_id' => 'rev_text_id',
2142 'ar_text' => '\'\'', // Be explicit to appease
2143 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2144 'ar_len' => 'rev_len',
2145 'ar_page_id' => 'page_id',
2146 'ar_deleted' => $bitfield,
2147 'ar_sha1' => 'rev_content_model',
2148 'ar_content_format' => 'rev_content_format',
2149 'ar_content_format' => 'rev_sha1'
2152 'page_id = rev_page'
2156 # Now that it's safely backed up, delete it
2157 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2158 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2165 $this->doDeleteUpdates( $id );
2167 # Log the deletion, if the page was suppressed, log it at Oversight instead
2168 $logtype = $suppress ?
'suppress' : 'delete';
2170 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2171 $logEntry->setPerformer( $user );
2172 $logEntry->setTarget( $this->mTitle
);
2173 $logEntry->setComment( $reason );
2174 $logid = $logEntry->insert();
2175 $logEntry->publish( $logid );
2181 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2186 * Do some database updates after deletion
2188 * @param $id Int: page_id value of the page being deleted
2190 public function doDeleteUpdates( $id ) {
2191 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2193 $dbw = wfGetDB( DB_MASTER
);
2195 # Delete restrictions for it
2196 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2198 # Fix category table counts
2200 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2202 foreach ( $res as $row ) {
2203 $cats [] = $row->cl_to
;
2206 $this->updateCategoryCounts( array(), $cats );
2208 # If using cascading deletes, we can skip some explicit deletes
2209 if ( !$dbw->cascadingDeletes() ) {
2210 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2212 # Delete outgoing links
2213 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2214 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2215 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2216 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2217 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2218 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2219 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2220 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2221 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2224 # If using cleanup triggers, we can skip some manual deletes
2225 if ( !$dbw->cleanupTriggers() ) {
2226 # Clean up recentchanges entries...
2227 $dbw->delete( 'recentchanges',
2228 array( 'rc_type != ' . RC_LOG
,
2229 'rc_namespace' => $this->mTitle
->getNamespace(),
2230 'rc_title' => $this->mTitle
->getDBkey() ),
2232 $dbw->delete( 'recentchanges',
2233 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2238 self
::onArticleDelete( $this->mTitle
);
2240 # Clear the cached article id so the interface doesn't act like we exist
2241 $this->mTitle
->resetArticleID( 0 );
2245 * Roll back the most recent consecutive set of edits to a page
2246 * from the same user; fails if there are no eligible edits to
2247 * roll back to, e.g. user is the sole contributor. This function
2248 * performs permissions checks on $user, then calls commitRollback()
2249 * to do the dirty work
2251 * @todo: seperate the business/permission stuff out from backend code
2253 * @param $fromP String: Name of the user whose edits to rollback.
2254 * @param $summary String: Custom summary. Set to default summary if empty.
2255 * @param $token String: Rollback token.
2256 * @param $bot Boolean: If true, mark all reverted edits as bot.
2258 * @param $resultDetails Array: contains result-specific array of additional values
2259 * 'alreadyrolled' : 'current' (rev)
2260 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2262 * @param $user User The user performing the rollback
2263 * @return array of errors, each error formatted as
2264 * array(messagekey, param1, param2, ...).
2265 * On success, the array is empty. This array can also be passed to
2266 * OutputPage::showPermissionsErrorPage().
2268 public function doRollback(
2269 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2271 $resultDetails = null;
2274 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2275 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2276 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2278 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2279 $errors[] = array( 'sessionfailure' );
2282 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2283 $errors[] = array( 'actionthrottledtext' );
2286 # If there were errors, bail out now
2287 if ( !empty( $errors ) ) {
2291 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2295 * Backend implementation of doRollback(), please refer there for parameter
2296 * and return value documentation
2298 * NOTE: This function does NOT check ANY permissions, it just commits the
2299 * rollback to the DB. Therefore, you should only call this function direct-
2300 * ly if you want to use custom permissions checks. If you don't, use
2301 * doRollback() instead.
2302 * @param $fromP String: Name of the user whose edits to rollback.
2303 * @param $summary String: Custom summary. Set to default summary if empty.
2304 * @param $bot Boolean: If true, mark all reverted edits as bot.
2306 * @param $resultDetails Array: contains result-specific array of additional values
2307 * @param $guser User The user performing the rollback
2309 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2310 global $wgUseRCPatrol, $wgContLang;
2312 $dbw = wfGetDB( DB_MASTER
);
2314 if ( wfReadOnly() ) {
2315 return array( array( 'readonlytext' ) );
2318 # Get the last editor
2319 $current = Revision
::newFromTitle( $this->mTitle
);
2320 if ( is_null( $current ) ) {
2321 # Something wrong... no page?
2322 return array( array( 'notanarticle' ) );
2325 $from = str_replace( '_', ' ', $fromP );
2326 # User name given should match up with the top revision.
2327 # If the user was deleted then $from should be empty.
2328 if ( $from != $current->getUserText() ) {
2329 $resultDetails = array( 'current' => $current );
2330 return array( array( 'alreadyrolled',
2331 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2332 htmlspecialchars( $fromP ),
2333 htmlspecialchars( $current->getUserText() )
2337 # Get the last edit not by this guy...
2338 # Note: these may not be public values
2339 $user = intval( $current->getRawUser() );
2340 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2341 $s = $dbw->selectRow( 'revision',
2342 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2343 array( 'rev_page' => $current->getPage(),
2344 "rev_user != {$user} OR rev_user_text != {$user_text}"
2346 array( 'USE INDEX' => 'page_timestamp',
2347 'ORDER BY' => 'rev_timestamp DESC' )
2349 if ( $s === false ) {
2350 # No one else ever edited this page
2351 return array( array( 'cantrollback' ) );
2352 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2353 # Only admins can see this text
2354 return array( array( 'notvisiblerev' ) );
2358 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2359 # Mark all reverted edits as bot
2363 if ( $wgUseRCPatrol ) {
2364 # Mark all reverted edits as patrolled
2365 $set['rc_patrolled'] = 1;
2368 if ( count( $set ) ) {
2369 $dbw->update( 'recentchanges', $set,
2371 'rc_cur_id' => $current->getPage(),
2372 'rc_user_text' => $current->getUserText(),
2373 "rc_timestamp > '{$s->rev_timestamp}'",
2378 # Generate the edit summary if necessary
2379 $target = Revision
::newFromId( $s->rev_id
);
2380 if ( empty( $summary ) ) {
2381 if ( $from == '' ) { // no public user name
2382 $summary = wfMsgForContent( 'revertpage-nouser' );
2384 $summary = wfMsgForContent( 'revertpage' );
2388 # Allow the custom summary to use the same args as the default message
2390 $target->getUserText(), $from, $s->rev_id
,
2391 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2392 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2394 $summary = wfMsgReplaceArgs( $summary, $args );
2397 $flags = EDIT_UPDATE
;
2399 if ( $guser->isAllowed( 'minoredit' ) ) {
2400 $flags |
= EDIT_MINOR
;
2403 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2404 $flags |
= EDIT_FORCE_BOT
;
2407 # Actually store the edit
2408 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2409 if ( !empty( $status->value
['revision'] ) ) {
2410 $revId = $status->value
['revision']->getId();
2415 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2417 $resultDetails = array(
2418 'summary' => $summary,
2419 'current' => $current,
2420 'target' => $target,
2428 * The onArticle*() functions are supposed to be a kind of hooks
2429 * which should be called whenever any of the specified actions
2432 * This is a good place to put code to clear caches, for instance.
2434 * This is called on page move and undelete, as well as edit
2436 * @param $title Title object
2438 public static function onArticleCreate( $title ) {
2439 # Update existence markers on article/talk tabs...
2440 if ( $title->isTalkPage() ) {
2441 $other = $title->getSubjectPage();
2443 $other = $title->getTalkPage();
2446 $other->invalidateCache();
2447 $other->purgeSquid();
2449 $title->touchLinks();
2450 $title->purgeSquid();
2451 $title->deleteTitleProtection();
2455 * Clears caches when article is deleted
2457 * @param $title Title
2459 public static function onArticleDelete( $title ) {
2460 # Update existence markers on article/talk tabs...
2461 if ( $title->isTalkPage() ) {
2462 $other = $title->getSubjectPage();
2464 $other = $title->getTalkPage();
2467 $other->invalidateCache();
2468 $other->purgeSquid();
2470 $title->touchLinks();
2471 $title->purgeSquid();
2474 HTMLFileCache
::clearFileCache( $title );
2477 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2478 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2482 if ( $title->getNamespace() == NS_FILE
) {
2483 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2484 $update->doUpdate();
2488 if ( $title->getNamespace() == NS_USER_TALK
) {
2489 $user = User
::newFromName( $title->getText(), false );
2491 $user->setNewtalk( false );
2496 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2500 * Purge caches on page update etc
2502 * @param $title Title object
2503 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2505 public static function onArticleEdit( $title ) {
2506 // Invalidate caches of articles which include this page
2507 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2510 // Invalidate the caches of all pages which redirect here
2511 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2513 # Purge squid for this page only
2514 $title->purgeSquid();
2516 # Clear file cache for this page only
2517 HTMLFileCache
::clearFileCache( $title );
2523 * Returns a list of hidden categories this page is a member of.
2524 * Uses the page_props and categorylinks tables.
2526 * @return Array of Title objects
2528 public function getHiddenCategories() {
2530 $id = $this->mTitle
->getArticleID();
2536 $dbr = wfGetDB( DB_SLAVE
);
2537 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2539 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2540 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2543 if ( $res !== false ) {
2544 foreach ( $res as $row ) {
2545 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2553 * Return an applicable autosummary if one exists for the given edit.
2554 * @param $oldtext String: the previous text of the page.
2555 * @param $newtext String: The submitted text of the page.
2556 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2557 * @return string An appropriate autosummary, or an empty string.
2558 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
2560 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2561 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2563 $handler = ContentHandler
::getForModelName( CONTENT_MODEL_WIKITEXT
);
2564 $oldContent = $oldtext ?
$handler->unserialize( $oldtext ) : null;
2565 $newContent = $newtext ?
$handler->unserialize( $newtext ) : null;
2567 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2571 * Auto-generates a deletion reason
2573 * @param &$hasHistory Boolean: whether the page has a history
2574 * @return mixed String containing deletion reason or empty string, or boolean false
2575 * if no revision occurred
2576 * @deprecated since 1.20, use ContentHandler::getAutoDeleteReason() instead
2578 public function getAutoDeleteReason( &$hasHistory ) {
2579 #NOTE: stub for backwards-compatibility.
2581 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2582 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2586 * Update all the appropriate counts in the category table, given that
2587 * we've added the categories $added and deleted the categories $deleted.
2589 * @param $added array The names of categories that were added
2590 * @param $deleted array The names of categories that were deleted
2592 public function updateCategoryCounts( $added, $deleted ) {
2593 $ns = $this->mTitle
->getNamespace();
2594 $dbw = wfGetDB( DB_MASTER
);
2596 # First make sure the rows exist. If one of the "deleted" ones didn't
2597 # exist, we might legitimately not create it, but it's simpler to just
2598 # create it and then give it a negative value, since the value is bogus
2601 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2602 $insertCats = array_merge( $added, $deleted );
2603 if ( !$insertCats ) {
2604 # Okay, nothing to do
2608 $insertRows = array();
2610 foreach ( $insertCats as $cat ) {
2611 $insertRows[] = array(
2612 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2616 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2618 $addFields = array( 'cat_pages = cat_pages + 1' );
2619 $removeFields = array( 'cat_pages = cat_pages - 1' );
2621 if ( $ns == NS_CATEGORY
) {
2622 $addFields[] = 'cat_subcats = cat_subcats + 1';
2623 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2624 } elseif ( $ns == NS_FILE
) {
2625 $addFields[] = 'cat_files = cat_files + 1';
2626 $removeFields[] = 'cat_files = cat_files - 1';
2633 array( 'cat_title' => $added ),
2642 array( 'cat_title' => $deleted ),
2649 * Updates cascading protections
2651 * @param $parserOutput ParserOutput object for the current version
2653 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2654 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2658 // templatelinks table may have become out of sync,
2659 // especially if using variable-based transclusions.
2660 // For paranoia, check if things have changed and if
2661 // so apply updates to the database. This will ensure
2662 // that cascaded protections apply as soon as the changes
2665 # Get templates from templatelinks
2666 $id = $this->mTitle
->getArticleID();
2668 $tlTemplates = array();
2670 $dbr = wfGetDB( DB_SLAVE
);
2671 $res = $dbr->select( array( 'templatelinks' ),
2672 array( 'tl_namespace', 'tl_title' ),
2673 array( 'tl_from' => $id ),
2677 foreach ( $res as $row ) {
2678 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2681 # Get templates from parser output.
2682 $poTemplates = array();
2683 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2684 foreach ( $templates as $dbk => $id ) {
2685 $poTemplates["$ns:$dbk"] = true;
2690 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2692 if ( count( $templates_diff ) > 0 ) {
2693 # Whee, link updates time.
2694 # Note: we are only interested in links here. We don't need to get other SecondaryDataUpdate items from the parser output.
2695 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2701 * Return a list of templates used by this article.
2702 * Uses the templatelinks table
2704 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2705 * @return Array of Title objects
2707 public function getUsedTemplates() {
2708 return $this->mTitle
->getTemplateLinksFrom();
2712 * Perform article updates on a special page creation.
2714 * @param $rev Revision object
2716 * @todo This is a shitty interface function. Kill it and replace the
2717 * other shitty functions like doEditUpdates and such so it's not needed
2719 * @deprecated since 1.18, use doEditUpdates()
2721 public function createUpdates( $rev ) {
2722 wfDeprecated( __METHOD__
, '1.18' );
2724 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2728 * This function is called right before saving the wikitext,
2729 * so we can do things like signatures and links-in-context.
2731 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2732 * @param $text String article contents
2733 * @param $user User object: user doing the edit
2734 * @param $popts ParserOptions object: parser options, default options for
2735 * the user loaded if null given
2736 * @return string article contents with altered wikitext markup (signatures
2737 * converted, {{subst:}}, templates, etc.)
2739 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2740 global $wgParser, $wgUser;
2742 wfDeprecated( __METHOD__
, '1.19' );
2744 $user = is_null( $user ) ?
$wgUser : $user;
2746 if ( $popts === null ) {
2747 $popts = ParserOptions
::newFromUser( $user );
2750 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2754 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2756 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2759 public function isBigDeletion() {
2760 wfDeprecated( __METHOD__
, '1.19' );
2761 return $this->mTitle
->isBigDeletion();
2765 * Get the approximate revision count of this page.
2767 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2770 public function estimateRevisionCount() {
2771 wfDeprecated( __METHOD__
, '1.19' );
2772 return $this->mTitle
->estimateRevisionCount();
2776 * Update the article's restriction field, and leave a log entry.
2778 * @deprecated since 1.19
2779 * @param $limit Array: set of restriction keys
2780 * @param $reason String
2781 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2782 * @param $expiry Array: per restriction type expiration
2783 * @param $user User The user updating the restrictions
2784 * @return bool true on success
2786 public function updateRestrictions(
2787 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2791 $user = is_null( $user ) ?
$wgUser : $user;
2793 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2797 * @deprecated since 1.18
2799 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2800 wfDeprecated( __METHOD__
, '1.18' );
2802 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2806 * @deprecated since 1.18
2808 public function viewUpdates() {
2809 wfDeprecated( __METHOD__
, '1.18' );
2811 return $this->doViewUpdates( $wgUser );
2815 * @deprecated since 1.18
2817 public function useParserCache( $oldid ) {
2818 wfDeprecated( __METHOD__
, '1.18' );
2820 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2824 class PoolWorkArticleView
extends PoolCounterWork
{
2842 * @var ParserOptions
2844 private $parserOptions;
2852 * @var ParserOutput|false
2854 private $parserOutput = false;
2859 private $isDirty = false;
2864 private $error = false;
2870 * @param $revid Integer: ID of the revision being parsed
2871 * @param $useParserCache Boolean: whether to use the parser cache
2872 * @param $parserOptions parserOptions to use for the parse operation
2873 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
2875 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
2876 if ( is_string($content) ) { #BC: old style call
2877 $modelName = $page->getRevision()->getContentModelName();
2878 $format = $page->getRevision()->getContentFormat();
2879 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelName, $format );
2882 $this->page
= $page;
2883 $this->revid
= $revid;
2884 $this->cacheable
= $useParserCache;
2885 $this->parserOptions
= $parserOptions;
2886 $this->content
= $content;
2887 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2888 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2892 * Get the ParserOutput from this object, or false in case of failure
2894 * @return ParserOutput
2896 public function getParserOutput() {
2897 return $this->parserOutput
;
2901 * Get whether the ParserOutput is a dirty one (i.e. expired)
2905 public function getIsDirty() {
2906 return $this->isDirty
;
2910 * Get a Status object in case of error or false otherwise
2912 * @return Status|false
2914 public function getError() {
2915 return $this->error
;
2922 global $wgParser, $wgUseFileCache;
2924 $isCurrent = $this->revid
=== $this->page
->getLatest();
2926 if ( $this->content
!== null ) {
2927 $content = $this->content
;
2928 } elseif ( $isCurrent ) {
2929 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
2931 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2932 if ( $rev === null ) {
2935 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
2939 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
2944 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2945 $this->page
->getTitle()->getPrefixedDBkey() ) );
2948 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2949 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2952 // Make sure file cache is not used on uncacheable content.
2953 // Output that has magic words in it can still use the parser cache
2954 // (if enabled), though it will generally expire sooner.
2955 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2956 $wgUseFileCache = false;
2960 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2969 function getCachedWork() {
2970 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2972 if ( $this->parserOutput
=== false ) {
2973 wfDebug( __METHOD__
. ": parser cache miss\n" );
2976 wfDebug( __METHOD__
. ": parser cache hit\n" );
2984 function fallback() {
2985 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2987 if ( $this->parserOutput
=== false ) {
2988 wfDebugLog( 'dirty', "dirty missing\n" );
2989 wfDebug( __METHOD__
. ": no dirty cache\n" );
2992 wfDebug( __METHOD__
. ": sending dirty output\n" );
2993 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2994 $this->isDirty
= true;
3000 * @param $status Status
3002 function error( $status ) {
3003 $this->error
= $status;