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 * Loads page_touched and returns a value indicating if it should be used
313 * @return boolean true if not a redirect
315 public function checkTouched() {
316 if ( !$this->mDataLoaded
) {
317 $this->loadPageData();
319 return !$this->mIsRedirect
;
323 * Get the page_touched field
324 * @return string containing GMT timestamp
326 public function getTouched() {
327 if ( !$this->mDataLoaded
) {
328 $this->loadPageData();
330 return $this->mTouched
;
334 * Get the page_latest field
335 * @return integer rev_id of current revision
337 public function getLatest() {
338 if ( !$this->mDataLoaded
) {
339 $this->loadPageData();
341 return (int)$this->mLatest
;
345 * Loads everything except the text
346 * This isn't necessary for all uses, so it's only done if needed.
348 protected function loadLastEdit() {
349 if ( $this->mLastRevision
!== null ) {
350 return; // already loaded
353 $latest = $this->getLatest();
355 return; // page doesn't exist or is missing page_latest info
358 $revision = Revision
::newFromPageId( $this->getId(), $latest );
359 if ( $revision ) { // sanity
360 $this->setLastEdit( $revision );
365 * Set the latest revision
367 protected function setLastEdit( Revision
$revision ) {
368 $this->mLastRevision
= $revision;
369 $this->mTimestamp
= $revision->getTimestamp();
373 * Get the latest revision
374 * @return Revision|null
376 public function getRevision() {
377 $this->loadLastEdit();
378 if ( $this->mLastRevision
) {
379 return $this->mLastRevision
;
385 * Get the content of the current revision. No side-effects...
387 * @param $audience Integer: one of:
388 * Revision::FOR_PUBLIC to be displayed to all users
389 * Revision::FOR_THIS_USER to be displayed to $wgUser
390 * Revision::RAW get the text regardless of permissions
391 * @return Content|null The content of the current revision
393 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
394 $this->loadLastEdit();
395 if ( $this->mLastRevision
) {
396 return $this->mLastRevision
->getContent( $audience );
402 * Get the text 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 String|false The text of the current revision
409 * @deprecated as of 1.20, getContent() should be used instead.
411 public function getText( $audience = Revision
::FOR_PUBLIC
) { #FIXME: deprecated, replace usage!
412 wfDeprecated( __METHOD__
, '1.20' );
413 $this->loadLastEdit();
414 if ( $this->mLastRevision
) {
415 return $this->mLastRevision
->getText( $audience );
421 * Get the text of the current revision. No side-effects...
423 * @return String|false The text of the current revision
425 public function getRawText() { #FIXME: deprecated, replace usage!
426 return $this->getText( Revision
::RAW
);
430 * Get the content of the current revision. No side-effects...
432 * @return Contet|false The text of the current revision
434 protected function getNativeData() { #FIXME: examine all uses carefully! caller must be aware of content model!
435 $content = $this->getContent( Revision
::RAW
);
436 if ( !$content ) return null;
438 return $content->getNativeData();
442 * @return string MW timestamp of last article revision
444 public function getTimestamp() {
445 // Check if the field has been filled by WikiPage::setTimestamp()
446 if ( !$this->mTimestamp
) {
447 $this->loadLastEdit();
449 return wfTimestamp( TS_MW
, $this->mTimestamp
);
453 * Set the page timestamp (use only to avoid DB queries)
454 * @param $ts string MW timestamp of last article revision
457 public function setTimestamp( $ts ) {
458 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
462 * @param $audience Integer: one of:
463 * Revision::FOR_PUBLIC to be displayed to all users
464 * Revision::FOR_THIS_USER to be displayed to $wgUser
465 * Revision::RAW get the text regardless of permissions
466 * @return int user ID for the user that made the last article revision
468 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
469 $this->loadLastEdit();
470 if ( $this->mLastRevision
) {
471 return $this->mLastRevision
->getUser( $audience );
478 * @param $audience Integer: one of:
479 * Revision::FOR_PUBLIC to be displayed to all users
480 * Revision::FOR_THIS_USER to be displayed to $wgUser
481 * Revision::RAW get the text regardless of permissions
482 * @return string username of the user that made the last article revision
484 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
485 $this->loadLastEdit();
486 if ( $this->mLastRevision
) {
487 return $this->mLastRevision
->getUserText( $audience );
494 * @param $audience Integer: one of:
495 * Revision::FOR_PUBLIC to be displayed to all users
496 * Revision::FOR_THIS_USER to be displayed to $wgUser
497 * Revision::RAW get the text regardless of permissions
498 * @return string Comment stored for the last article revision
500 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
501 $this->loadLastEdit();
502 if ( $this->mLastRevision
) {
503 return $this->mLastRevision
->getComment( $audience );
510 * Returns true if last revision was marked as "minor edit"
512 * @return boolean Minor edit indicator for the last article revision.
514 public function getMinorEdit() {
515 $this->loadLastEdit();
516 if ( $this->mLastRevision
) {
517 return $this->mLastRevision
->isMinor();
524 * Get the cached timestamp for the last time the page changed.
525 * This is only used to help handle slave lag by comparing to page_touched.
526 * @return string MW timestamp
528 protected function getCachedLastEditTime() {
530 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
531 return $wgMemc->get( $key );
535 * Set the cached timestamp for the last time the page changed.
536 * This is only used to help handle slave lag by comparing to page_touched.
537 * @param $timestamp string
540 public function setCachedLastEditTime( $timestamp ) {
542 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
543 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
547 * Determine whether a page would be suitable for being counted as an
548 * article in the site_stats table based on the title & its content
550 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
551 * if false, the current database state will be used
554 public function isCountable( $editInfo = false ) {
555 global $wgArticleCountMethod;
557 if ( !$this->mTitle
->isContentPage() ) {
562 $content = ContentHandler
::makeContent( $editInfo->pst
, $this->mTitle
);
563 # TODO: take model and format from edit info!
565 $content = $this->getContent();
568 if ( !$content ||
$content->isRedirect( ) ) {
574 if ( $wgArticleCountMethod === 'link' ) {
575 # nasty special case to avoid re-parsing to detect links
578 // ParserOutput::getLinks() is a 2D array of page links, so
579 // to be really correct we would need to recurse in the array
580 // but the main array should only have items in it if there are
582 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
584 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
585 array( 'pl_from' => $this->getId() ), __METHOD__
);
589 return $content->isCountable( $hasLinks );
593 * If this page is a redirect, get its target
595 * The target will be fetched from the redirect table if possible.
596 * If this page doesn't have an entry there, call insertRedirect()
597 * @return Title|mixed object, or null if this page is not a redirect
599 public function getRedirectTarget() {
600 if ( !$this->mTitle
->isRedirect() ) {
604 if ( $this->mRedirectTarget
!== null ) {
605 return $this->mRedirectTarget
;
608 # Query the redirect table
609 $dbr = wfGetDB( DB_SLAVE
);
610 $row = $dbr->selectRow( 'redirect',
611 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
612 array( 'rd_from' => $this->getId() ),
616 // rd_fragment and rd_interwiki were added later, populate them if empty
617 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
618 return $this->mRedirectTarget
= Title
::makeTitle(
619 $row->rd_namespace
, $row->rd_title
,
620 $row->rd_fragment
, $row->rd_interwiki
);
623 # This page doesn't have an entry in the redirect table
624 return $this->mRedirectTarget
= $this->insertRedirect();
628 * Insert an entry for this page into the redirect table.
630 * Don't call this function directly unless you know what you're doing.
631 * @return Title object or null if not a redirect
633 public function insertRedirect() {
634 // recurse through to only get the final target
635 $content = $this->getContent();
636 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
640 $this->insertRedirectEntry( $retval );
645 * Insert or update the redirect table entry for this page to indicate
646 * it redirects to $rt .
647 * @param $rt Title redirect target
649 public function insertRedirectEntry( $rt ) {
650 $dbw = wfGetDB( DB_MASTER
);
651 $dbw->replace( 'redirect', array( 'rd_from' ),
653 'rd_from' => $this->getId(),
654 'rd_namespace' => $rt->getNamespace(),
655 'rd_title' => $rt->getDBkey(),
656 'rd_fragment' => $rt->getFragment(),
657 'rd_interwiki' => $rt->getInterwiki(),
664 * Get the Title object or URL this page redirects to
666 * @return mixed false, Title of in-wiki target, or string with URL
668 public function followRedirect() {
669 return $this->getRedirectURL( $this->getRedirectTarget() );
673 * Get the Title object or URL to use for a redirect. We use Title
674 * objects for same-wiki, non-special redirects and URLs for everything
676 * @param $rt Title Redirect target
677 * @return mixed false, Title object of local target, or string with URL
679 public function getRedirectURL( $rt ) {
684 if ( $rt->isExternal() ) {
685 if ( $rt->isLocal() ) {
686 // Offsite wikis need an HTTP redirect.
688 // This can be hard to reverse and may produce loops,
689 // so they may be disabled in the site configuration.
690 $source = $this->mTitle
->getFullURL( 'redirect=no' );
691 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
693 // External pages pages without "local" bit set are not valid
699 if ( $rt->isSpecialPage() ) {
700 // Gotta handle redirects to special pages differently:
701 // Fill the HTTP response "Location" header and ignore
702 // the rest of the page we're on.
704 // Some pages are not valid targets
705 if ( $rt->isValidRedirectTarget() ) {
706 return $rt->getFullURL();
716 * Get a list of users who have edited this article, not including the user who made
717 * the most recent revision, which you can get from $article->getUser() if you want it
718 * @return UserArrayFromResult
720 public function getContributors() {
721 # @todo FIXME: This is expensive; cache this info somewhere.
723 $dbr = wfGetDB( DB_SLAVE
);
725 if ( $dbr->implicitGroupby() ) {
726 $realNameField = 'user_real_name';
728 $realNameField = 'MIN(user_real_name) AS user_real_name';
731 $tables = array( 'revision', 'user' );
734 'rev_user as user_id',
735 'rev_user_text AS user_name',
737 'MAX(rev_timestamp) AS timestamp',
740 $conds = array( 'rev_page' => $this->getId() );
742 // The user who made the top revision gets credited as "this page was last edited by
743 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
744 $user = $this->getUser();
746 $conds[] = "rev_user != $user";
748 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
751 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
754 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
758 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
759 'ORDER BY' => 'timestamp DESC',
762 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
763 return new UserArrayFromResult( $res );
767 * Get the last N authors
768 * @param $num Integer: number of revisions to get
769 * @param $revLatest String: the latest rev_id, selected from the master (optional)
770 * @return array Array of authors, duplicates not removed
772 public function getLastNAuthors( $num, $revLatest = 0 ) {
773 wfProfileIn( __METHOD__
);
774 // First try the slave
775 // If that doesn't have the latest revision, try the master
777 $db = wfGetDB( DB_SLAVE
);
780 $res = $db->select( array( 'page', 'revision' ),
781 array( 'rev_id', 'rev_user_text' ),
783 'page_namespace' => $this->mTitle
->getNamespace(),
784 'page_title' => $this->mTitle
->getDBkey(),
788 'ORDER BY' => 'rev_timestamp DESC',
794 wfProfileOut( __METHOD__
);
798 $row = $db->fetchObject( $res );
800 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
801 $db = wfGetDB( DB_MASTER
);
806 } while ( $continue );
808 $authors = array( $row->rev_user_text
);
810 foreach ( $res as $row ) {
811 $authors[] = $row->rev_user_text
;
814 wfProfileOut( __METHOD__
);
819 * Should the parser cache be used?
821 * @param $parserOptions ParserOptions to check
825 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
826 global $wgEnableParserCache;
828 return $wgEnableParserCache
829 && $parserOptions->getStubThreshold() == 0
830 && $this->mTitle
->exists()
831 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
832 && $this->mTitle
->isWikitextPage(); #FIXME: ask ContentHandler if cachable!
836 * Get a ParserOutput for the given ParserOptions and revision ID.
837 * The parser cache will be used if possible.
840 * @param $parserOptions ParserOptions to use for the parse operation
841 * @param $oldid Revision ID to get the text from, passing null or 0 will
842 * get the current revision (default value)
843 * @return ParserOutput or false if the revision was not found
845 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
846 wfProfileIn( __METHOD__
);
848 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
849 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
850 if ( $parserOptions->getStubThreshold() ) {
851 wfIncrStats( 'pcache_miss_stub' );
854 if ( $useParserCache ) {
855 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
856 if ( $parserOutput !== false ) {
857 wfProfileOut( __METHOD__
);
858 return $parserOutput;
862 if ( $oldid === null ||
$oldid === 0 ) {
863 $oldid = $this->getLatest();
866 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
869 wfProfileOut( __METHOD__
);
871 return $pool->getParserOutput();
875 * Do standard deferred updates after page view
876 * @param $user User The relevant user
878 public function doViewUpdates( User
$user ) {
879 global $wgDisableCounters;
880 if ( wfReadOnly() ) {
884 # Don't update page view counters on views from bot users (bug 14044)
885 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
886 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
887 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
890 # Update newtalk / watchlist notification status
891 $user->clearNotification( $this->mTitle
);
895 * Perform the actions of a page purging
897 public function doPurge() {
900 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
904 // Invalidate the cache
905 $this->mTitle
->invalidateCache();
909 // Commit the transaction before the purge is sent
910 $dbw = wfGetDB( DB_MASTER
);
914 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
918 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
919 if ( $this->mTitle
->exists() ) {
920 $text = $this->getNativeData(); #FIXME: may not be a string. check Content model!
925 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
931 * Insert a new empty page record for this article.
932 * This *must* be followed up by creating a revision
933 * and running $this->updateRevisionOn( ... );
934 * or else the record will be left in a funky state.
935 * Best if all done inside a transaction.
937 * @param $dbw DatabaseBase
938 * @return int The newly created page_id key, or false if the title already existed
940 public function insertOn( $dbw ) {
941 wfProfileIn( __METHOD__
);
943 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
944 $dbw->insert( 'page', array(
945 'page_id' => $page_id,
946 'page_namespace' => $this->mTitle
->getNamespace(),
947 'page_title' => $this->mTitle
->getDBkey(),
949 'page_restrictions' => '',
950 'page_is_redirect' => 0, # Will set this shortly...
952 'page_random' => wfRandom(),
953 'page_touched' => $dbw->timestamp(),
954 'page_latest' => 0, # Fill this in shortly...
955 'page_len' => 0, # Fill this in shortly...
956 ), __METHOD__
, 'IGNORE' );
958 $affected = $dbw->affectedRows();
961 $newid = $dbw->insertId();
962 $this->mTitle
->resetArticleID( $newid );
964 wfProfileOut( __METHOD__
);
966 return $affected ?
$newid : false;
970 * Update the page record to point to a newly saved revision.
972 * @param $dbw DatabaseBase: object
973 * @param $revision Revision: For ID number, and text used to set
974 * length and redirect status fields
975 * @param $lastRevision Integer: if given, will not overwrite the page field
976 * when different from the currently set value.
977 * Giving 0 indicates the new page flag should be set
979 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
980 * removing rows in redirect table.
981 * @return bool true on success, false on failure
984 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
985 wfProfileIn( __METHOD__
);
987 $content = $revision->getContent();
988 $len = $content->getSize();
989 $rt = $content->getUltimateRedirectTarget();
991 $conditions = array( 'page_id' => $this->getId() );
993 if ( !is_null( $lastRevision ) ) {
994 # An extra check against threads stepping on each other
995 $conditions['page_latest'] = $lastRevision;
998 $now = wfTimestampNow();
999 $dbw->update( 'page',
1001 'page_latest' => $revision->getId(),
1002 'page_touched' => $dbw->timestamp( $now ),
1003 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1004 'page_is_redirect' => $rt !== null ?
1 : 0,
1010 $result = $dbw->affectedRows() != 0;
1012 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1013 $this->setLastEdit( $revision );
1014 $this->setCachedLastEditTime( $now );
1015 $this->mLatest
= $revision->getId();
1016 $this->mIsRedirect
= (bool)$rt;
1017 # Update the LinkCache.
1018 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1021 wfProfileOut( __METHOD__
);
1026 * Add row to the redirect table if this is a redirect, remove otherwise.
1028 * @param $dbw DatabaseBase
1029 * @param $redirectTitle Title object pointing to the redirect target,
1030 * or NULL if this is not a redirect
1031 * @param $lastRevIsRedirect If given, will optimize adding and
1032 * removing rows in redirect table.
1033 * @return bool true on success, false on failure
1036 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1037 // Always update redirects (target link might have changed)
1038 // Update/Insert if we don't know if the last revision was a redirect or not
1039 // Delete if changing from redirect to non-redirect
1040 $isRedirect = !is_null( $redirectTitle );
1042 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1046 wfProfileIn( __METHOD__
);
1047 if ( $isRedirect ) {
1048 $this->insertRedirectEntry( $redirectTitle );
1050 // This is not a redirect, remove row from redirect table
1051 $where = array( 'rd_from' => $this->getId() );
1052 $dbw->delete( 'redirect', $where, __METHOD__
);
1055 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1056 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1058 wfProfileOut( __METHOD__
);
1060 return ( $dbw->affectedRows() != 0 );
1064 * If the given revision is newer than the currently set page_latest,
1065 * update the page record. Otherwise, do nothing.
1067 * @param $dbw Database object
1068 * @param $revision Revision object
1071 public function updateIfNewerOn( $dbw, $revision ) {
1072 wfProfileIn( __METHOD__
);
1074 $row = $dbw->selectRow(
1075 array( 'revision', 'page' ),
1076 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1078 'page_id' => $this->getId(),
1079 'page_latest=rev_id' ),
1083 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1084 wfProfileOut( __METHOD__
);
1087 $prev = $row->rev_id
;
1088 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1090 # No or missing previous revision; mark the page as new
1092 $lastRevIsRedirect = null;
1095 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1097 wfProfileOut( __METHOD__
);
1102 * Get the text that needs to be saved in order to undo all revisions
1103 * between $undo and $undoafter. Revisions must belong to the same page,
1104 * must exist and must not be deleted
1105 * @param $undo Revision
1106 * @param $undoafter Revision Must be an earlier revision than $undo
1107 * @return mixed string on success, false on failure
1108 * @deprecated since 1.20: use ContentHandler::getUndoContent() instead.
1110 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) { #FIXME: replace usages.
1111 $this->loadLastEdit();
1113 if ( $this->mLastRevision
) {
1114 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1115 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1120 return ContentHandler
::getContentText( $undone );
1128 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1129 * @param $text String: new text of the section
1130 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1131 * @param $edittime String: revision timestamp or null to use the current revision
1132 * @return Content new complete article content, or null if error
1133 * @deprected since 1.20, use replaceSectionContent() instead
1135 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) { #FIXME: use replaceSectionContent() instead!
1136 wfDeprecated( __METHOD__
, '1.20' );
1138 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1140 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1142 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1145 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1146 wfProfileIn( __METHOD__
);
1148 if ( strval( $section ) == '' ) {
1149 // Whole-page edit; let the whole text through
1150 $newContent = $sectionContent;
1152 // Bug 30711: always use current version when adding a new section
1153 if ( is_null( $edittime ) ||
$section == 'new' ) {
1154 $oldContent = $this->getContent();
1155 if ( ! $oldContent ) {
1156 wfDebug( __METHOD__
. ": no page text\n" );
1157 wfProfileOut( __METHOD__
);
1161 $dbw = wfGetDB( DB_MASTER
);
1162 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1165 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1166 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1167 wfProfileOut( __METHOD__
);
1171 $oldContent = $rev->getContent();
1174 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1177 wfProfileOut( __METHOD__
);
1182 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1184 * @return Int updated $flags
1186 function checkFlags( $flags ) {
1187 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1188 if ( $this->mTitle
->getArticleID() ) {
1189 $flags |
= EDIT_UPDATE
;
1199 * Change an existing article or create a new article. Updates RC and all necessary caches,
1200 * optionally via the deferred update array.
1202 * @param $text String: new text
1203 * @param $summary String: edit summary
1204 * @param $flags Integer bitfield:
1206 * Article is known or assumed to be non-existent, create a new one
1208 * Article is known or assumed to be pre-existing, update it
1210 * Mark this edit minor, if the user is allowed to do so
1212 * Do not log the change in recentchanges
1214 * Mark the edit a "bot" edit regardless of user rights
1215 * EDIT_DEFER_UPDATES
1216 * Defer some of the updates until the end of index.php
1218 * Fill in blank summaries with generated text where possible
1220 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1221 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1222 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1223 * edit-already-exists error will be returned. These two conditions are also possible with
1224 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1226 * @param $baseRevId the revision ID this edit was based off, if any
1227 * @param $user User the user doing the edit
1229 * @return Status object. Possible errors:
1230 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1231 * edit-gone-missing: In update mode, but the article didn't exist
1232 * edit-conflict: In update mode, the article changed unexpectedly
1233 * edit-no-change: Warning that the text was the same as before
1234 * edit-already-exists: In creation mode, but the article already exists
1236 * Extensions may define additional errors.
1238 * $return->value will contain an associative array with members as follows:
1239 * new: Boolean indicating if the function attempted to create a new article
1240 * revision: The revision object for the inserted revision, or null
1242 * Compatibility note: this function previously returned a boolean value indicating success/failure
1243 * @deprecated since 1.20: use doEditContent() instead.
1245 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #FIXME: use doEditContent() instead
1246 #TODO: log use of deprecated function
1247 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1249 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1253 * Change an existing article or create a new article. Updates RC and all necessary caches,
1254 * optionally via the deferred update array.
1256 * @param $content Content: new content
1257 * @param $summary String: edit summary
1258 * @param $flags Integer bitfield:
1260 * Article is known or assumed to be non-existent, create a new one
1262 * Article is known or assumed to be pre-existing, update it
1264 * Mark this edit minor, if the user is allowed to do so
1266 * Do not log the change in recentchanges
1268 * Mark the edit a "bot" edit regardless of user rights
1269 * EDIT_DEFER_UPDATES
1270 * Defer some of the updates until the end of index.php
1272 * Fill in blank summaries with generated text where possible
1274 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1275 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1276 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1277 * edit-already-exists error will be returned. These two conditions are also possible with
1278 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1280 * @param $baseRevId the revision ID this edit was based off, if any
1281 * @param $user User the user doing the edit
1282 * @param $serialisation_format String: format for storing the content in the database
1284 * @return Status object. Possible errors:
1285 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1286 * edit-gone-missing: In update mode, but the article didn't exist
1287 * edit-conflict: In update mode, the article changed unexpectedly
1288 * edit-no-change: Warning that the text was the same as before
1289 * edit-already-exists: In creation mode, but the article already exists
1291 * Extensions may define additional errors.
1293 * $return->value will contain an associative array with members as follows:
1294 * new: Boolean indicating if the function attempted to create a new article
1295 * revision: The revision object for the inserted revision, or null
1297 * Compatibility note: this function previously returned a boolean value indicating success/failure
1299 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1300 User
$user = null, $serialisation_format = null ) { #FIXME: use this
1301 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1303 # Low-level sanity check
1304 if ( $this->mTitle
->getText() === '' ) {
1305 throw new MWException( 'Something is trying to edit an article with an empty title' );
1308 wfProfileIn( __METHOD__
);
1310 $user = is_null( $user ) ?
$wgUser : $user;
1311 $status = Status
::newGood( array() );
1313 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1314 $this->loadPageData( 'fromdbmaster' );
1316 $flags = $this->checkFlags( $flags );
1319 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary, #FIXME: document new hook!
1320 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1322 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { # avoid serialization overhead if the hook isn't present
1323 $content_text = $content->serialize();
1324 $txt = $content_text; # clone
1326 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary, #FIXME: deprecate legacy hook!
1327 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1329 if ( $txt !== $content_text ) {
1330 # if the text changed, unserialize the new version to create an updated Content object.
1331 $content = $content->getContentHandler()->unserialize( $txt );
1336 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1338 if ( $status->isOK() ) {
1339 $status->fatal( 'edit-hook-aborted' );
1342 wfProfileOut( __METHOD__
);
1346 # Silently ignore EDIT_MINOR if not allowed
1347 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1348 $bot = $flags & EDIT_FORCE_BOT
;
1350 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1352 $oldsize = $old_content ?
$old_content->getSize() : 0;
1353 $oldid = $this->getLatest();
1354 $oldIsRedirect = $this->isRedirect();
1355 $oldcountable = $this->isCountable();
1357 $handler = $content->getContentHandler();
1359 # Provide autosummaries if one is not provided and autosummaries are enabled.
1360 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1361 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1364 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1365 $serialized = $editInfo->pst
;
1366 $content = $editInfo->pstContent
;
1367 $newsize = $content->getSize();
1369 $dbw = wfGetDB( DB_MASTER
);
1370 $now = wfTimestampNow();
1371 $this->mTimestamp
= $now;
1373 if ( $flags & EDIT_UPDATE
) {
1374 # Update article, but only if changed.
1375 $status->value
['new'] = false;
1378 # Article gone missing
1379 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1380 $status->fatal( 'edit-gone-missing' );
1382 wfProfileOut( __METHOD__
);
1386 # Make sure the revision is either completely inserted or not inserted at all
1387 if ( !$wgDBtransactions ) {
1388 $userAbort = ignore_user_abort( true );
1391 $revision = new Revision( array(
1392 'page' => $this->getId(),
1393 'comment' => $summary,
1394 'minor_edit' => $isminor,
1395 'text' => $serialized,
1397 'parent_id' => $oldid,
1398 'user' => $user->getId(),
1399 'user_text' => $user->getName(),
1400 'timestamp' => $now,
1401 'content_model' => $content->getModelName(),
1402 'content_format' => $serialisation_format,
1405 $changed = !$content->equals( $old_content );
1409 $revisionId = $revision->insertOn( $dbw );
1413 # Note that we use $this->mLatest instead of fetching a value from the master DB
1414 # during the course of this function. This makes sure that EditPage can detect
1415 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1416 # before this function is called. A previous function used a separate query, this
1417 # creates a window where concurrent edits can cause an ignored edit conflict.
1418 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1421 /* Belated edit conflict! Run away!! */
1422 $status->fatal( 'edit-conflict' );
1424 # Delete the invalid revision if the DB is not transactional
1425 if ( !$wgDBtransactions ) {
1426 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1432 global $wgUseRCPatrol;
1433 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1434 # Update recentchanges
1435 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1436 # Mark as patrolled if the user can do so
1437 $patrolled = $wgUseRCPatrol && !count(
1438 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1439 # Add RC row to the DB
1440 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1441 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1442 $revisionId, $patrolled
1445 # Log auto-patrolled edits
1447 PatrolLog
::record( $rc, true );
1450 $user->incEditCount();
1454 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1455 // related variables correctly
1456 $revision->setId( $this->getLatest() );
1459 if ( !$wgDBtransactions ) {
1460 ignore_user_abort( $userAbort );
1463 // Now that ignore_user_abort is restored, we can respond to fatal errors
1464 if ( !$status->isOK() ) {
1465 wfProfileOut( __METHOD__
);
1469 # Update links tables, site stats, etc.
1470 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1471 'oldcountable' => $oldcountable ) );
1474 $status->warning( 'edit-no-change' );
1476 // Update page_touched, this is usually implicit in the page update
1477 // Other cache updates are done in onArticleEdit()
1478 $this->mTitle
->invalidateCache();
1481 # Create new article
1482 $status->value
['new'] = true;
1486 # Add the page record; stake our claim on this title!
1487 # This will return false if the article already exists
1488 $newid = $this->insertOn( $dbw );
1490 if ( $newid === false ) {
1492 $status->fatal( 'edit-already-exists' );
1494 wfProfileOut( __METHOD__
);
1498 # Save the revision text...
1499 $revision = new Revision( array(
1501 'comment' => $summary,
1502 'minor_edit' => $isminor,
1503 'text' => $serialized,
1505 'user' => $user->getId(),
1506 'user_text' => $user->getName(),
1507 'timestamp' => $now,
1508 'content_model' => $content->getModelName(),
1509 'content_format' => $serialisation_format,
1511 $revisionId = $revision->insertOn( $dbw );
1513 # Update the page record with revision data
1514 $this->updateRevisionOn( $dbw, $revision, 0 );
1516 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1518 # Update recentchanges
1519 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1520 global $wgUseRCPatrol, $wgUseNPPatrol;
1522 # Mark as patrolled if the user can do so
1523 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1524 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1525 # Add RC row to the DB
1526 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1527 '', $content->getSize(), $revisionId, $patrolled );
1529 # Log auto-patrolled edits
1531 PatrolLog
::record( $rc, true );
1534 $user->incEditCount();
1537 # Update links, etc.
1538 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1540 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1541 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1543 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1544 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1547 # Do updates right now unless deferral was requested
1548 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1549 DeferredUpdates
::doUpdates();
1552 // Return the new revision (or null) to the caller
1553 $status->value
['revision'] = $revision;
1555 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1556 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1558 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1559 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1561 # Promote user to any groups they meet the criteria for
1562 $user->addAutopromoteOnceGroups( 'onEdit' );
1564 wfProfileOut( __METHOD__
);
1569 * Get parser options suitable for rendering the primary article wikitext
1570 * @param User|string $user User object or 'canonical'
1571 * @return ParserOptions
1573 public function makeParserOptions( $user ) {
1575 if ( $user instanceof User
) { // settings per user (even anons)
1576 $options = ParserOptions
::newFromUser( $user );
1577 } else { // canonical settings
1578 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1580 $options->enableLimitReport(); // show inclusion/loop reports
1581 $options->setTidy( true ); // fix bad HTML
1586 * Prepare text which is about to be saved.
1587 * Returns a stdclass with source, pst and output members
1588 * @deprecated in 1.20: use prepareContentForEdit instead.
1590 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) { #FIXME: use prepareContentForEdit() instead #XXX: who uses this?!
1591 #TODO: log use of deprecated function
1592 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1593 return $this->prepareContentForEdit( $content, $revid , $user );
1597 * Prepare content which is about to be saved.
1598 * Returns a stdclass with source, pst and output members
1600 * @param \Content $content
1601 * @param null $revid
1602 * @param null|\User $user
1603 * @param null $serialization_format
1604 * @return bool|object
1606 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) { #FIXME: use this #XXX: really public?!
1607 global $wgParser, $wgContLang, $wgUser;
1608 $user = is_null( $user ) ?
$wgUser : $user;
1609 // @TODO fixme: check $user->getId() here???
1611 if ( $this->mPreparedEdit
1612 && $this->mPreparedEdit
->newContent
1613 && $this->mPreparedEdit
->newContent
->equals( $content )
1614 && $this->mPreparedEdit
->revid
== $revid
1615 && $this->mPreparedEdit
->format
== $serialization_format
1616 #XXX: also check $user here?
1619 return $this->mPreparedEdit
;
1622 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1623 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1625 $edit = (object)array();
1626 $edit->revid
= $revid;
1628 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1629 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1630 $edit->format
= $serialization_format;
1632 $edit->popts
= $this->makeParserOptions( 'canonical' );
1633 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1635 $edit->newContent
= $content;
1636 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1638 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1639 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1641 $this->mPreparedEdit
= $edit;
1647 * Do standard deferred updates after page edit.
1648 * Update links tables, site stats, search index and message cache.
1649 * Purges pages that include this page if the text was changed here.
1650 * Every 100th edit, prune the recent changes table.
1653 * @param $revision Revision object
1654 * @param $user User object that did the revision
1655 * @param $options Array of options, following indexes are used:
1656 * - changed: boolean, whether the revision changed the content (default true)
1657 * - created: boolean, whether the revision created the page (default false)
1658 * - oldcountable: boolean or null (default null):
1659 * - boolean: whether the page was counted as an article before that
1660 * revision, only used in changed is true and created is false
1661 * - null: don't change the article count
1663 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1664 global $wgEnableParserCache;
1666 wfProfileIn( __METHOD__
);
1668 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1669 $content = $revision->getContent();
1672 # Be careful not to double-PST: $text is usually already PST-ed once
1673 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1674 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1675 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1677 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1678 $editInfo = $this->mPreparedEdit
;
1681 # Save it to the parser cache
1682 if ( $wgEnableParserCache ) {
1683 $parserCache = ParserCache
::singleton();
1684 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1687 # Update the links tables
1688 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1691 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1693 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1694 if ( 0 == mt_rand( 0, 99 ) ) {
1695 // Flush old entries from the `recentchanges` table; we do this on
1696 // random requests so as to avoid an increase in writes for no good reason
1699 $dbw = wfGetDB( DB_MASTER
);
1700 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1703 array( "rc_timestamp < '$cutoff'" ),
1709 if ( !$this->mTitle
->exists() ) {
1710 wfProfileOut( __METHOD__
);
1714 $id = $this->getId();
1715 $title = $this->mTitle
->getPrefixedDBkey();
1716 $shortTitle = $this->mTitle
->getDBkey();
1718 if ( !$options['changed'] ) {
1721 } elseif ( $options['created'] ) {
1722 $good = (int)$this->isCountable( $editInfo );
1724 } elseif ( $options['oldcountable'] !== null ) {
1725 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1732 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1733 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
1735 # If this is another user's talk page, update newtalk.
1736 # Don't do this if $options['changed'] = false (null-edits) nor if
1737 # it's a minor edit and the user doesn't want notifications for those.
1738 if ( $options['changed']
1739 && $this->mTitle
->getNamespace() == NS_USER_TALK
1740 && $shortTitle != $user->getTitleKey()
1741 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1743 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1744 $other = User
::newFromName( $shortTitle, false );
1746 wfDebug( __METHOD__
. ": invalid username\n" );
1747 } elseif ( User
::isIP( $shortTitle ) ) {
1748 // An anonymous user
1749 $other->setNewtalk( true );
1750 } elseif ( $other->isLoggedIn() ) {
1751 $other->setNewtalk( true );
1753 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1758 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1759 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
1760 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
1762 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
1765 if( $options['created'] ) {
1766 self
::onArticleCreate( $this->mTitle
);
1768 self
::onArticleEdit( $this->mTitle
);
1771 wfProfileOut( __METHOD__
);
1775 * Edit an article without doing all that other stuff
1776 * The article must already exist; link tables etc
1777 * are not updated, caches are not flushed.
1779 * @param $text String: text submitted
1780 * @param $user User The relevant user
1781 * @param $comment String: comment submitted
1782 * @param $minor Boolean: whereas it's a minor modification
1784 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1785 #TODO: log use of deprecated function
1786 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1787 return $this->doQuickEdit( $content, $user, $comment , $minor );
1791 * Edit an article without doing all that other stuff
1792 * The article must already exist; link tables etc
1793 * are not updated, caches are not flushed.
1795 * @param $content Content: content submitted
1796 * @param $user User The relevant user
1797 * @param $comment String: comment submitted
1798 * @param $serialisation_format String: format for storing the content in the database
1799 * @param $minor Boolean: whereas it's a minor modification
1801 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
1802 wfProfileIn( __METHOD__
);
1804 $serialized = $content->serialize( $serialisation_format );
1806 $dbw = wfGetDB( DB_MASTER
);
1807 $revision = new Revision( array(
1808 'page' => $this->getId(),
1809 'text' => $serialized,
1810 'length' => $content->getSize(),
1811 'comment' => $comment,
1812 'minor_edit' => $minor ?
1 : 0,
1814 $revision->insertOn( $dbw );
1815 $this->updateRevisionOn( $dbw, $revision );
1817 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1819 wfProfileOut( __METHOD__
);
1823 * Update the article's restriction field, and leave a log entry.
1824 * This works for protection both existing and non-existing pages.
1826 * @param $limit Array: set of restriction keys
1827 * @param $reason String
1828 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1829 * @param $expiry Array: per restriction type expiration
1830 * @param $user User The user updating the restrictions
1831 * @return bool true on success
1833 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1836 if ( wfReadOnly() ) {
1837 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1840 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1842 $id = $this->mTitle
->getArticleID();
1848 // Take this opportunity to purge out expired restrictions
1849 Title
::purgeExpiredRestrictions();
1851 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1852 # we expect a single selection, but the schema allows otherwise.
1853 $isProtected = false;
1857 $dbw = wfGetDB( DB_MASTER
);
1859 foreach ( $restrictionTypes as $action ) {
1860 if ( !isset( $expiry[$action] ) ) {
1861 $expiry[$action] = $dbw->getInfinity();
1863 if ( !isset( $limit[$action] ) ) {
1864 $limit[$action] = '';
1865 } elseif ( $limit[$action] != '' ) {
1869 # Get current restrictions on $action
1870 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1871 if ( $current != '' ) {
1872 $isProtected = true;
1875 if ( $limit[$action] != $current ) {
1877 } elseif ( $limit[$action] != '' ) {
1878 # Only check expiry change if the action is actually being
1879 # protected, since expiry does nothing on an not-protected
1881 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1887 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1891 # If nothing's changed, do nothing
1893 return Status
::newGood();
1896 if ( !$protect ) { # No protection at all means unprotection
1897 $revCommentMsg = 'unprotectedarticle';
1898 $logAction = 'unprotect';
1899 } elseif ( $isProtected ) {
1900 $revCommentMsg = 'modifiedarticleprotection';
1901 $logAction = 'modify';
1903 $revCommentMsg = 'protectedarticle';
1904 $logAction = 'protect';
1907 $encodedExpiry = array();
1908 $protectDescription = '';
1909 foreach ( $limit as $action => $restrictions ) {
1910 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1911 if ( $restrictions != '' ) {
1912 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1913 if ( $encodedExpiry[$action] != 'infinity' ) {
1914 $protectDescription .= wfMsgForContent( 'protect-expiring',
1915 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1916 $wgContLang->date( $expiry[$action], false, false ) ,
1917 $wgContLang->time( $expiry[$action], false, false ) );
1919 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1922 $protectDescription .= ') ';
1925 $protectDescription = trim( $protectDescription );
1927 if ( $id ) { # Protection of existing page
1928 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1929 return Status
::newGood();
1932 # Only restrictions with the 'protect' right can cascade...
1933 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1934 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1936 # The schema allows multiple restrictions
1937 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1941 # Update restrictions table
1942 foreach ( $limit as $action => $restrictions ) {
1943 if ( $restrictions != '' ) {
1944 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1945 array( 'pr_page' => $id,
1946 'pr_type' => $action,
1947 'pr_level' => $restrictions,
1948 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1949 'pr_expiry' => $encodedExpiry[$action]
1954 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1955 'pr_type' => $action ), __METHOD__
);
1959 # Prepare a null revision to be added to the history
1960 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1962 $editComment .= ": $reason";
1964 if ( $protectDescription ) {
1965 $editComment .= " ($protectDescription)";
1968 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1971 # Insert a null revision
1972 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1973 $nullRevId = $nullRevision->insertOn( $dbw );
1975 $latest = $this->getLatest();
1976 # Update page record
1977 $dbw->update( 'page',
1979 'page_touched' => $dbw->timestamp(),
1980 'page_restrictions' => '',
1981 'page_latest' => $nullRevId
1982 ), array( /* WHERE */
1987 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1988 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1989 } else { # Protection of non-existing page (also known as "title protection")
1990 # Cascade protection is meaningless in this case
1993 if ( $limit['create'] != '' ) {
1994 $dbw->replace( 'protected_titles',
1995 array( array( 'pt_namespace', 'pt_title' ) ),
1997 'pt_namespace' => $this->mTitle
->getNamespace(),
1998 'pt_title' => $this->mTitle
->getDBkey(),
1999 'pt_create_perm' => $limit['create'],
2000 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2001 'pt_expiry' => $encodedExpiry['create'],
2002 'pt_user' => $user->getId(),
2003 'pt_reason' => $reason,
2007 $dbw->delete( 'protected_titles',
2009 'pt_namespace' => $this->mTitle
->getNamespace(),
2010 'pt_title' => $this->mTitle
->getDBkey()
2016 $this->mTitle
->flushRestrictions();
2018 if ( $logAction == 'unprotect' ) {
2019 $logParams = array();
2021 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2024 # Update the protection log
2025 $log = new LogPage( 'protect' );
2026 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2028 return Status
::newGood();
2032 * Take an array of page restrictions and flatten it to a string
2033 * suitable for insertion into the page_restrictions field.
2034 * @param $limit Array
2037 protected static function flattenRestrictions( $limit ) {
2038 if ( !is_array( $limit ) ) {
2039 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2045 foreach ( $limit as $action => $restrictions ) {
2046 if ( $restrictions != '' ) {
2047 $bits[] = "$action=$restrictions";
2051 return implode( ':', $bits );
2055 * Back-end article deletion
2056 * Deletes the article with database consistency, writes logs, purges caches
2058 * @param $reason string delete reason for deletion log
2059 * @param $suppress bitfield
2060 * Revision::DELETED_TEXT
2061 * Revision::DELETED_COMMENT
2062 * Revision::DELETED_USER
2063 * Revision::DELETED_RESTRICTED
2064 * @param $id int article ID
2065 * @param $commit boolean defaults to true, triggers transaction end
2066 * @param &$errors Array of errors to append to
2067 * @param $user User The relevant user
2068 * @return boolean true if successful
2070 public function doDeleteArticle(
2071 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2074 $user = is_null( $user ) ?
$wgUser : $user;
2076 wfDebug( __METHOD__
. "\n" );
2078 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2081 $dbw = wfGetDB( DB_MASTER
);
2082 $t = $this->mTitle
->getDBkey();
2083 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2085 if ( $t === '' ||
$id == 0 ) {
2089 // Bitfields to further suppress the content
2092 // This should be 15...
2093 $bitfield |
= Revision
::DELETED_TEXT
;
2094 $bitfield |
= Revision
::DELETED_COMMENT
;
2095 $bitfield |
= Revision
::DELETED_USER
;
2096 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2098 $bitfield = 'rev_deleted';
2102 // For now, shunt the revision data into the archive table.
2103 // Text is *not* removed from the text table; bulk storage
2104 // is left intact to avoid breaking block-compression or
2105 // immutable storage schemes.
2107 // For backwards compatibility, note that some older archive
2108 // table entries will have ar_text and ar_flags fields still.
2110 // In the future, we may keep revisions and mark them with
2111 // the rev_deleted field, which is reserved for this purpose.
2112 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2114 'ar_namespace' => 'page_namespace',
2115 'ar_title' => 'page_title',
2116 'ar_comment' => 'rev_comment',
2117 'ar_user' => 'rev_user',
2118 'ar_user_text' => 'rev_user_text',
2119 'ar_timestamp' => 'rev_timestamp',
2120 'ar_minor_edit' => 'rev_minor_edit',
2121 'ar_rev_id' => 'rev_id',
2122 'ar_parent_id' => 'rev_parent_id',
2123 'ar_text_id' => 'rev_text_id',
2124 'ar_text' => '\'\'', // Be explicit to appease
2125 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2126 'ar_len' => 'rev_len',
2127 'ar_page_id' => 'page_id',
2128 'ar_deleted' => $bitfield,
2129 'ar_sha1' => 'rev_content_model',
2130 'ar_content_format' => 'rev_content_format',
2131 'ar_content_format' => 'rev_sha1'
2134 'page_id = rev_page'
2138 # Now that it's safely backed up, delete it
2139 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2140 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2147 $this->doDeleteUpdates( $id );
2149 # Log the deletion, if the page was suppressed, log it at Oversight instead
2150 $logtype = $suppress ?
'suppress' : 'delete';
2152 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2153 $logEntry->setPerformer( $user );
2154 $logEntry->setTarget( $this->mTitle
);
2155 $logEntry->setComment( $reason );
2156 $logid = $logEntry->insert();
2157 $logEntry->publish( $logid );
2163 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2168 * Do some database updates after deletion
2170 * @param $id Int: page_id value of the page being deleted
2172 public function doDeleteUpdates( $id ) {
2173 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2175 $dbw = wfGetDB( DB_MASTER
);
2177 # Delete restrictions for it
2178 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2180 # Fix category table counts
2182 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2184 foreach ( $res as $row ) {
2185 $cats [] = $row->cl_to
;
2188 $this->updateCategoryCounts( array(), $cats );
2190 # If using cascading deletes, we can skip some explicit deletes
2191 if ( !$dbw->cascadingDeletes() ) {
2192 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2194 # Delete outgoing links
2195 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2196 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2197 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2198 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2199 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2200 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2201 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2202 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2203 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2206 # If using cleanup triggers, we can skip some manual deletes
2207 if ( !$dbw->cleanupTriggers() ) {
2208 # Clean up recentchanges entries...
2209 $dbw->delete( 'recentchanges',
2210 array( 'rc_type != ' . RC_LOG
,
2211 'rc_namespace' => $this->mTitle
->getNamespace(),
2212 'rc_title' => $this->mTitle
->getDBkey() ),
2214 $dbw->delete( 'recentchanges',
2215 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2220 self
::onArticleDelete( $this->mTitle
);
2222 # Clear the cached article id so the interface doesn't act like we exist
2223 $this->mTitle
->resetArticleID( 0 );
2227 * Roll back the most recent consecutive set of edits to a page
2228 * from the same user; fails if there are no eligible edits to
2229 * roll back to, e.g. user is the sole contributor. This function
2230 * performs permissions checks on $user, then calls commitRollback()
2231 * to do the dirty work
2233 * @todo: seperate the business/permission stuff out from backend code
2235 * @param $fromP String: Name of the user whose edits to rollback.
2236 * @param $summary String: Custom summary. Set to default summary if empty.
2237 * @param $token String: Rollback token.
2238 * @param $bot Boolean: If true, mark all reverted edits as bot.
2240 * @param $resultDetails Array: contains result-specific array of additional values
2241 * 'alreadyrolled' : 'current' (rev)
2242 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2244 * @param $user User The user performing the rollback
2245 * @return array of errors, each error formatted as
2246 * array(messagekey, param1, param2, ...).
2247 * On success, the array is empty. This array can also be passed to
2248 * OutputPage::showPermissionsErrorPage().
2250 public function doRollback(
2251 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2253 $resultDetails = null;
2256 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2257 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2258 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2260 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2261 $errors[] = array( 'sessionfailure' );
2264 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2265 $errors[] = array( 'actionthrottledtext' );
2268 # If there were errors, bail out now
2269 if ( !empty( $errors ) ) {
2273 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2277 * Backend implementation of doRollback(), please refer there for parameter
2278 * and return value documentation
2280 * NOTE: This function does NOT check ANY permissions, it just commits the
2281 * rollback to the DB. Therefore, you should only call this function direct-
2282 * ly if you want to use custom permissions checks. If you don't, use
2283 * doRollback() instead.
2284 * @param $fromP String: Name of the user whose edits to rollback.
2285 * @param $summary String: Custom summary. Set to default summary if empty.
2286 * @param $bot Boolean: If true, mark all reverted edits as bot.
2288 * @param $resultDetails Array: contains result-specific array of additional values
2289 * @param $guser User The user performing the rollback
2291 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2292 global $wgUseRCPatrol, $wgContLang;
2294 $dbw = wfGetDB( DB_MASTER
);
2296 if ( wfReadOnly() ) {
2297 return array( array( 'readonlytext' ) );
2300 # Get the last editor
2301 $current = Revision
::newFromTitle( $this->mTitle
);
2302 if ( is_null( $current ) ) {
2303 # Something wrong... no page?
2304 return array( array( 'notanarticle' ) );
2307 $from = str_replace( '_', ' ', $fromP );
2308 # User name given should match up with the top revision.
2309 # If the user was deleted then $from should be empty.
2310 if ( $from != $current->getUserText() ) {
2311 $resultDetails = array( 'current' => $current );
2312 return array( array( 'alreadyrolled',
2313 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2314 htmlspecialchars( $fromP ),
2315 htmlspecialchars( $current->getUserText() )
2319 # Get the last edit not by this guy...
2320 # Note: these may not be public values
2321 $user = intval( $current->getRawUser() );
2322 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2323 $s = $dbw->selectRow( 'revision',
2324 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2325 array( 'rev_page' => $current->getPage(),
2326 "rev_user != {$user} OR rev_user_text != {$user_text}"
2328 array( 'USE INDEX' => 'page_timestamp',
2329 'ORDER BY' => 'rev_timestamp DESC' )
2331 if ( $s === false ) {
2332 # No one else ever edited this page
2333 return array( array( 'cantrollback' ) );
2334 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2335 # Only admins can see this text
2336 return array( array( 'notvisiblerev' ) );
2340 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2341 # Mark all reverted edits as bot
2345 if ( $wgUseRCPatrol ) {
2346 # Mark all reverted edits as patrolled
2347 $set['rc_patrolled'] = 1;
2350 if ( count( $set ) ) {
2351 $dbw->update( 'recentchanges', $set,
2353 'rc_cur_id' => $current->getPage(),
2354 'rc_user_text' => $current->getUserText(),
2355 "rc_timestamp > '{$s->rev_timestamp}'",
2360 # Generate the edit summary if necessary
2361 $target = Revision
::newFromId( $s->rev_id
);
2362 if ( empty( $summary ) ) {
2363 if ( $from == '' ) { // no public user name
2364 $summary = wfMsgForContent( 'revertpage-nouser' );
2366 $summary = wfMsgForContent( 'revertpage' );
2370 # Allow the custom summary to use the same args as the default message
2372 $target->getUserText(), $from, $s->rev_id
,
2373 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2374 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2376 $summary = wfMsgReplaceArgs( $summary, $args );
2379 $flags = EDIT_UPDATE
;
2381 if ( $guser->isAllowed( 'minoredit' ) ) {
2382 $flags |
= EDIT_MINOR
;
2385 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2386 $flags |
= EDIT_FORCE_BOT
;
2389 # Actually store the edit
2390 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2391 if ( !empty( $status->value
['revision'] ) ) {
2392 $revId = $status->value
['revision']->getId();
2397 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2399 $resultDetails = array(
2400 'summary' => $summary,
2401 'current' => $current,
2402 'target' => $target,
2410 * The onArticle*() functions are supposed to be a kind of hooks
2411 * which should be called whenever any of the specified actions
2414 * This is a good place to put code to clear caches, for instance.
2416 * This is called on page move and undelete, as well as edit
2418 * @param $title Title object
2420 public static function onArticleCreate( $title ) {
2421 # Update existence markers on article/talk tabs...
2422 if ( $title->isTalkPage() ) {
2423 $other = $title->getSubjectPage();
2425 $other = $title->getTalkPage();
2428 $other->invalidateCache();
2429 $other->purgeSquid();
2431 $title->touchLinks();
2432 $title->purgeSquid();
2433 $title->deleteTitleProtection();
2437 * Clears caches when article is deleted
2439 * @param $title Title
2441 public static function onArticleDelete( $title ) {
2442 # Update existence markers on article/talk tabs...
2443 if ( $title->isTalkPage() ) {
2444 $other = $title->getSubjectPage();
2446 $other = $title->getTalkPage();
2449 $other->invalidateCache();
2450 $other->purgeSquid();
2452 $title->touchLinks();
2453 $title->purgeSquid();
2456 HTMLFileCache
::clearFileCache( $title );
2459 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2460 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2464 if ( $title->getNamespace() == NS_FILE
) {
2465 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2466 $update->doUpdate();
2470 if ( $title->getNamespace() == NS_USER_TALK
) {
2471 $user = User
::newFromName( $title->getText(), false );
2473 $user->setNewtalk( false );
2478 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2482 * Purge caches on page update etc
2484 * @param $title Title object
2485 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2487 public static function onArticleEdit( $title ) {
2488 // Invalidate caches of articles which include this page
2489 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2492 // Invalidate the caches of all pages which redirect here
2493 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2495 # Purge squid for this page only
2496 $title->purgeSquid();
2498 # Clear file cache for this page only
2499 HTMLFileCache
::clearFileCache( $title );
2505 * Returns a list of hidden categories this page is a member of.
2506 * Uses the page_props and categorylinks tables.
2508 * @return Array of Title objects
2510 public function getHiddenCategories() {
2512 $id = $this->mTitle
->getArticleID();
2518 $dbr = wfGetDB( DB_SLAVE
);
2519 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2521 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2522 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2525 if ( $res !== false ) {
2526 foreach ( $res as $row ) {
2527 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2535 * Return an applicable autosummary if one exists for the given edit.
2536 * @param $oldtext String: the previous text of the page.
2537 * @param $newtext String: The submitted text of the page.
2538 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2539 * @return string An appropriate autosummary, or an empty string.
2540 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
2542 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2543 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2545 $handler = ContentHandler
::getForModelName( CONTENT_MODEL_WIKITEXT
);
2546 $oldContent = $handler->unserialize( $oldtext );
2547 $newContent = $handler->unserialize( $newtext );
2549 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2553 * Auto-generates a deletion reason
2555 * @param &$hasHistory Boolean: whether the page has a history
2556 * @return mixed String containing deletion reason or empty string, or boolean false
2557 * if no revision occurred
2558 * @deprecated since 1.20, use ContentHandler::getAutoDeleteReason() instead
2560 public function getAutoDeleteReason( &$hasHistory ) {
2561 #NOTE: stub for backwards-compatibility.
2563 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2564 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2568 * Update all the appropriate counts in the category table, given that
2569 * we've added the categories $added and deleted the categories $deleted.
2571 * @param $added array The names of categories that were added
2572 * @param $deleted array The names of categories that were deleted
2574 public function updateCategoryCounts( $added, $deleted ) {
2575 $ns = $this->mTitle
->getNamespace();
2576 $dbw = wfGetDB( DB_MASTER
);
2578 # First make sure the rows exist. If one of the "deleted" ones didn't
2579 # exist, we might legitimately not create it, but it's simpler to just
2580 # create it and then give it a negative value, since the value is bogus
2583 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2584 $insertCats = array_merge( $added, $deleted );
2585 if ( !$insertCats ) {
2586 # Okay, nothing to do
2590 $insertRows = array();
2592 foreach ( $insertCats as $cat ) {
2593 $insertRows[] = array(
2594 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2598 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2600 $addFields = array( 'cat_pages = cat_pages + 1' );
2601 $removeFields = array( 'cat_pages = cat_pages - 1' );
2603 if ( $ns == NS_CATEGORY
) {
2604 $addFields[] = 'cat_subcats = cat_subcats + 1';
2605 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2606 } elseif ( $ns == NS_FILE
) {
2607 $addFields[] = 'cat_files = cat_files + 1';
2608 $removeFields[] = 'cat_files = cat_files - 1';
2615 array( 'cat_title' => $added ),
2624 array( 'cat_title' => $deleted ),
2631 * Updates cascading protections
2633 * @param $parserOutput ParserOutput object for the current version
2635 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2636 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2640 // templatelinks table may have become out of sync,
2641 // especially if using variable-based transclusions.
2642 // For paranoia, check if things have changed and if
2643 // so apply updates to the database. This will ensure
2644 // that cascaded protections apply as soon as the changes
2647 # Get templates from templatelinks
2648 $id = $this->mTitle
->getArticleID();
2650 $tlTemplates = array();
2652 $dbr = wfGetDB( DB_SLAVE
);
2653 $res = $dbr->select( array( 'templatelinks' ),
2654 array( 'tl_namespace', 'tl_title' ),
2655 array( 'tl_from' => $id ),
2659 foreach ( $res as $row ) {
2660 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2663 # Get templates from parser output.
2664 $poTemplates = array();
2665 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2666 foreach ( $templates as $dbk => $id ) {
2667 $poTemplates["$ns:$dbk"] = true;
2672 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2674 if ( count( $templates_diff ) > 0 ) {
2675 # Whee, link updates time.
2676 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2682 * Return a list of templates used by this article.
2683 * Uses the templatelinks table
2685 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2686 * @return Array of Title objects
2688 public function getUsedTemplates() {
2689 return $this->mTitle
->getTemplateLinksFrom();
2693 * Perform article updates on a special page creation.
2695 * @param $rev Revision object
2697 * @todo This is a shitty interface function. Kill it and replace the
2698 * other shitty functions like doEditUpdates and such so it's not needed
2700 * @deprecated since 1.18, use doEditUpdates()
2702 public function createUpdates( $rev ) {
2703 wfDeprecated( __METHOD__
, '1.18' );
2705 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2709 * This function is called right before saving the wikitext,
2710 * so we can do things like signatures and links-in-context.
2712 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2713 * @param $text String article contents
2714 * @param $user User object: user doing the edit
2715 * @param $popts ParserOptions object: parser options, default options for
2716 * the user loaded if null given
2717 * @return string article contents with altered wikitext markup (signatures
2718 * converted, {{subst:}}, templates, etc.)
2720 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2721 global $wgParser, $wgUser;
2723 wfDeprecated( __METHOD__
, '1.19' );
2725 $user = is_null( $user ) ?
$wgUser : $user;
2727 if ( $popts === null ) {
2728 $popts = ParserOptions
::newFromUser( $user );
2731 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2735 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2737 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2740 public function isBigDeletion() {
2741 wfDeprecated( __METHOD__
, '1.19' );
2742 return $this->mTitle
->isBigDeletion();
2746 * Get the approximate revision count of this page.
2748 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2751 public function estimateRevisionCount() {
2752 wfDeprecated( __METHOD__
, '1.19' );
2753 return $this->mTitle
->estimateRevisionCount();
2757 * Update the article's restriction field, and leave a log entry.
2759 * @deprecated since 1.19
2760 * @param $limit Array: set of restriction keys
2761 * @param $reason String
2762 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2763 * @param $expiry Array: per restriction type expiration
2764 * @param $user User The user updating the restrictions
2765 * @return bool true on success
2767 public function updateRestrictions(
2768 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2772 $user = is_null( $user ) ?
$wgUser : $user;
2774 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2778 * @deprecated since 1.18
2780 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2781 wfDeprecated( __METHOD__
, '1.18' );
2783 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2787 * @deprecated since 1.18
2789 public function viewUpdates() {
2790 wfDeprecated( __METHOD__
, '1.18' );
2792 return $this->doViewUpdates( $wgUser );
2796 * @deprecated since 1.18
2798 public function useParserCache( $oldid ) {
2799 wfDeprecated( __METHOD__
, '1.18' );
2801 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2805 class PoolWorkArticleView
extends PoolCounterWork
{
2823 * @var ParserOptions
2825 private $parserOptions;
2833 * @var ParserOutput|false
2835 private $parserOutput = false;
2840 private $isDirty = false;
2845 private $error = false;
2851 * @param $revid Integer: ID of the revision being parsed
2852 * @param $useParserCache Boolean: whether to use the parser cache
2853 * @param $parserOptions parserOptions to use for the parse operation
2854 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
2856 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
2857 if ( is_string($content) ) { #BC: old style call
2858 $modelName = $page->getRevision()->getContentModelName();
2859 $format = $page->getRevision()->getContentFormat();
2860 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelName, $format );
2863 $this->page
= $page;
2864 $this->revid
= $revid;
2865 $this->cacheable
= $useParserCache;
2866 $this->parserOptions
= $parserOptions;
2867 $this->content
= $content;
2868 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2869 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2873 * Get the ParserOutput from this object, or false in case of failure
2875 * @return ParserOutput
2877 public function getParserOutput() {
2878 return $this->parserOutput
;
2882 * Get whether the ParserOutput is a dirty one (i.e. expired)
2886 public function getIsDirty() {
2887 return $this->isDirty
;
2891 * Get a Status object in case of error or false otherwise
2893 * @return Status|false
2895 public function getError() {
2896 return $this->error
;
2903 global $wgParser, $wgUseFileCache;
2905 $isCurrent = $this->revid
=== $this->page
->getLatest();
2907 if ( $this->content
!== null ) {
2908 $content = $this->content
;
2909 } elseif ( $isCurrent ) {
2910 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
2912 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2913 if ( $rev === null ) {
2916 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
2920 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
2925 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2926 $this->page
->getTitle()->getPrefixedDBkey() ) );
2929 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2930 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2933 // Make sure file cache is not used on uncacheable content.
2934 // Output that has magic words in it can still use the parser cache
2935 // (if enabled), though it will generally expire sooner.
2936 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2937 $wgUseFileCache = false;
2941 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2950 function getCachedWork() {
2951 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2953 if ( $this->parserOutput
=== false ) {
2954 wfDebug( __METHOD__
. ": parser cache miss\n" );
2957 wfDebug( __METHOD__
. ": parser cache hit\n" );
2965 function fallback() {
2966 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2968 if ( $this->parserOutput
=== false ) {
2969 wfDebugLog( 'dirty', "dirty missing\n" );
2970 wfDebug( __METHOD__
. ": no dirty cache\n" );
2973 wfDebug( __METHOD__
. ": sending dirty output\n" );
2974 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2975 $this->isDirty
= true;
2981 * @param $status Status
2983 function error( $status ) {
2984 $this->error
= $status;