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, $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(),
1403 $changed = !$content->equals( $old_content );
1407 $revisionId = $revision->insertOn( $dbw );
1411 # Note that we use $this->mLatest instead of fetching a value from the master DB
1412 # during the course of this function. This makes sure that EditPage can detect
1413 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1414 # before this function is called. A previous function used a separate query, this
1415 # creates a window where concurrent edits can cause an ignored edit conflict.
1416 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1419 /* Belated edit conflict! Run away!! */
1420 $status->fatal( 'edit-conflict' );
1422 # Delete the invalid revision if the DB is not transactional
1423 if ( !$wgDBtransactions ) {
1424 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1430 global $wgUseRCPatrol;
1431 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1432 # Update recentchanges
1433 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1434 # Mark as patrolled if the user can do so
1435 $patrolled = $wgUseRCPatrol && !count(
1436 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1437 # Add RC row to the DB
1438 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1439 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1440 $revisionId, $patrolled
1443 # Log auto-patrolled edits
1445 PatrolLog
::record( $rc, true );
1448 $user->incEditCount();
1452 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1453 // related variables correctly
1454 $revision->setId( $this->getLatest() );
1457 if ( !$wgDBtransactions ) {
1458 ignore_user_abort( $userAbort );
1461 // Now that ignore_user_abort is restored, we can respond to fatal errors
1462 if ( !$status->isOK() ) {
1463 wfProfileOut( __METHOD__
);
1467 # Update links tables, site stats, etc.
1468 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1469 'oldcountable' => $oldcountable ) );
1472 $status->warning( 'edit-no-change' );
1474 // Update page_touched, this is usually implicit in the page update
1475 // Other cache updates are done in onArticleEdit()
1476 $this->mTitle
->invalidateCache();
1479 # Create new article
1480 $status->value
['new'] = true;
1484 # Add the page record; stake our claim on this title!
1485 # This will return false if the article already exists
1486 $newid = $this->insertOn( $dbw );
1488 if ( $newid === false ) {
1490 $status->fatal( 'edit-already-exists' );
1492 wfProfileOut( __METHOD__
);
1496 # Save the revision text...
1497 $revision = new Revision( array(
1499 'comment' => $summary,
1500 'minor_edit' => $isminor,
1501 'text' => $serialized,
1503 'user' => $user->getId(),
1504 'user_text' => $user->getName(),
1507 $revisionId = $revision->insertOn( $dbw );
1509 # Update the page record with revision data
1510 $this->updateRevisionOn( $dbw, $revision, 0 );
1512 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1514 # Update recentchanges
1515 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1516 global $wgUseRCPatrol, $wgUseNPPatrol;
1518 # Mark as patrolled if the user can do so
1519 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1520 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1521 # Add RC row to the DB
1522 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1523 '', $content->getSize(), $revisionId, $patrolled );
1525 # Log auto-patrolled edits
1527 PatrolLog
::record( $rc, true );
1530 $user->incEditCount();
1533 # Update links, etc.
1534 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1536 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1537 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1539 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1540 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1543 # Do updates right now unless deferral was requested
1544 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1545 DeferredUpdates
::doUpdates();
1548 // Return the new revision (or null) to the caller
1549 $status->value
['revision'] = $revision;
1551 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1552 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1554 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1555 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1557 # Promote user to any groups they meet the criteria for
1558 $user->addAutopromoteOnceGroups( 'onEdit' );
1560 wfProfileOut( __METHOD__
);
1565 * Get parser options suitable for rendering the primary article wikitext
1566 * @param User|string $user User object or 'canonical'
1567 * @return ParserOptions
1569 public function makeParserOptions( $user ) {
1571 if ( $user instanceof User
) { // settings per user (even anons)
1572 $options = ParserOptions
::newFromUser( $user );
1573 } else { // canonical settings
1574 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1576 $options->enableLimitReport(); // show inclusion/loop reports
1577 $options->setTidy( true ); // fix bad HTML
1582 * Prepare text which is about to be saved.
1583 * Returns a stdclass with source, pst and output members
1584 * @deprecated in 1.20: use prepareContentForEdit instead.
1586 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) { #FIXME: use prepareContentForEdit() instead #XXX: who uses this?!
1587 #TODO: log use of deprecated function
1588 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1589 return $this->prepareContentForEdit( $content, $revid , $user );
1593 * Prepare content which is about to be saved.
1594 * Returns a stdclass with source, pst and output members
1596 * @param \Content $content
1597 * @param null $revid
1598 * @param null|\User $user
1599 * @param null $serialization_format
1600 * @return bool|object
1602 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) { #FIXME: use this #XXX: really public?!
1603 global $wgParser, $wgContLang, $wgUser;
1604 $user = is_null( $user ) ?
$wgUser : $user;
1605 // @TODO fixme: check $user->getId() here???
1607 if ( $this->mPreparedEdit
1608 && $this->mPreparedEdit
->newContent
1609 && $this->mPreparedEdit
->newContent
->equals( $content )
1610 && $this->mPreparedEdit
->revid
== $revid
1611 && $this->mPreparedEdit
->format
== $serialization_format
1612 #XXX: also check $user here?
1615 return $this->mPreparedEdit
;
1618 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1619 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1621 $edit = (object)array();
1622 $edit->revid
= $revid;
1624 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1625 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1626 $edit->format
= $serialization_format;
1628 $edit->popts
= $this->makeParserOptions( 'canonical' );
1629 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1631 $edit->newContent
= $content;
1632 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1634 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1635 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1637 $this->mPreparedEdit
= $edit;
1643 * Do standard deferred updates after page edit.
1644 * Update links tables, site stats, search index and message cache.
1645 * Purges pages that include this page if the text was changed here.
1646 * Every 100th edit, prune the recent changes table.
1649 * @param $revision Revision object
1650 * @param $user User object that did the revision
1651 * @param $options Array of options, following indexes are used:
1652 * - changed: boolean, whether the revision changed the content (default true)
1653 * - created: boolean, whether the revision created the page (default false)
1654 * - oldcountable: boolean or null (default null):
1655 * - boolean: whether the page was counted as an article before that
1656 * revision, only used in changed is true and created is false
1657 * - null: don't change the article count
1659 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1660 global $wgEnableParserCache;
1662 wfProfileIn( __METHOD__
);
1664 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1665 $content = $revision->getContent();
1668 # Be careful not to double-PST: $text is usually already PST-ed once
1669 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1670 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1671 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1673 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1674 $editInfo = $this->mPreparedEdit
;
1677 # Save it to the parser cache
1678 if ( $wgEnableParserCache ) {
1679 $parserCache = ParserCache
::singleton();
1680 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1683 # Update the links tables
1684 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1687 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1689 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1690 if ( 0 == mt_rand( 0, 99 ) ) {
1691 // Flush old entries from the `recentchanges` table; we do this on
1692 // random requests so as to avoid an increase in writes for no good reason
1695 $dbw = wfGetDB( DB_MASTER
);
1696 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1699 array( "rc_timestamp < '$cutoff'" ),
1705 if ( !$this->mTitle
->exists() ) {
1706 wfProfileOut( __METHOD__
);
1710 $id = $this->getId();
1711 $title = $this->mTitle
->getPrefixedDBkey();
1712 $shortTitle = $this->mTitle
->getDBkey();
1714 if ( !$options['changed'] ) {
1717 } elseif ( $options['created'] ) {
1718 $good = (int)$this->isCountable( $editInfo );
1720 } elseif ( $options['oldcountable'] !== null ) {
1721 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1728 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1729 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
1731 # If this is another user's talk page, update newtalk.
1732 # Don't do this if $options['changed'] = false (null-edits) nor if
1733 # it's a minor edit and the user doesn't want notifications for those.
1734 if ( $options['changed']
1735 && $this->mTitle
->getNamespace() == NS_USER_TALK
1736 && $shortTitle != $user->getTitleKey()
1737 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1739 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1740 $other = User
::newFromName( $shortTitle, false );
1742 wfDebug( __METHOD__
. ": invalid username\n" );
1743 } elseif ( User
::isIP( $shortTitle ) ) {
1744 // An anonymous user
1745 $other->setNewtalk( true );
1746 } elseif ( $other->isLoggedIn() ) {
1747 $other->setNewtalk( true );
1749 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1754 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1755 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
1756 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
1758 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
1761 if( $options['created'] ) {
1762 self
::onArticleCreate( $this->mTitle
);
1764 self
::onArticleEdit( $this->mTitle
);
1767 wfProfileOut( __METHOD__
);
1771 * Edit an article without doing all that other stuff
1772 * The article must already exist; link tables etc
1773 * are not updated, caches are not flushed.
1775 * @param $text String: text submitted
1776 * @param $user User The relevant user
1777 * @param $comment String: comment submitted
1778 * @param $minor Boolean: whereas it's a minor modification
1780 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1781 #TODO: log use of deprecated function
1782 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1783 return $this->doQuickEdit( $content, $user, $comment , $minor );
1787 * Edit an article without doing all that other stuff
1788 * The article must already exist; link tables etc
1789 * are not updated, caches are not flushed.
1791 * @param $content Content: content submitted
1792 * @param $user User The relevant user
1793 * @param $comment String: comment submitted
1794 * @param $serialisation_format String: format for storing the content in the database
1795 * @param $minor Boolean: whereas it's a minor modification
1797 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
1798 wfProfileIn( __METHOD__
);
1800 $serialized = $content->serialize( $serialisation_format );
1802 $dbw = wfGetDB( DB_MASTER
);
1803 $revision = new Revision( array(
1804 'page' => $this->getId(),
1805 'text' => $serialized,
1806 'length' => $content->getSize(),
1807 'comment' => $comment,
1808 'minor_edit' => $minor ?
1 : 0,
1810 $revision->insertOn( $dbw );
1811 $this->updateRevisionOn( $dbw, $revision );
1813 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1815 wfProfileOut( __METHOD__
);
1819 * Update the article's restriction field, and leave a log entry.
1820 * This works for protection both existing and non-existing pages.
1822 * @param $limit Array: set of restriction keys
1823 * @param $reason String
1824 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1825 * @param $expiry Array: per restriction type expiration
1826 * @param $user User The user updating the restrictions
1827 * @return bool true on success
1829 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1832 if ( wfReadOnly() ) {
1833 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1836 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1838 $id = $this->mTitle
->getArticleID();
1844 // Take this opportunity to purge out expired restrictions
1845 Title
::purgeExpiredRestrictions();
1847 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1848 # we expect a single selection, but the schema allows otherwise.
1849 $isProtected = false;
1853 $dbw = wfGetDB( DB_MASTER
);
1855 foreach ( $restrictionTypes as $action ) {
1856 if ( !isset( $expiry[$action] ) ) {
1857 $expiry[$action] = $dbw->getInfinity();
1859 if ( !isset( $limit[$action] ) ) {
1860 $limit[$action] = '';
1861 } elseif ( $limit[$action] != '' ) {
1865 # Get current restrictions on $action
1866 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1867 if ( $current != '' ) {
1868 $isProtected = true;
1871 if ( $limit[$action] != $current ) {
1873 } elseif ( $limit[$action] != '' ) {
1874 # Only check expiry change if the action is actually being
1875 # protected, since expiry does nothing on an not-protected
1877 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1883 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1887 # If nothing's changed, do nothing
1889 return Status
::newGood();
1892 if ( !$protect ) { # No protection at all means unprotection
1893 $revCommentMsg = 'unprotectedarticle';
1894 $logAction = 'unprotect';
1895 } elseif ( $isProtected ) {
1896 $revCommentMsg = 'modifiedarticleprotection';
1897 $logAction = 'modify';
1899 $revCommentMsg = 'protectedarticle';
1900 $logAction = 'protect';
1903 $encodedExpiry = array();
1904 $protectDescription = '';
1905 foreach ( $limit as $action => $restrictions ) {
1906 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1907 if ( $restrictions != '' ) {
1908 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1909 if ( $encodedExpiry[$action] != 'infinity' ) {
1910 $protectDescription .= wfMsgForContent( 'protect-expiring',
1911 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1912 $wgContLang->date( $expiry[$action], false, false ) ,
1913 $wgContLang->time( $expiry[$action], false, false ) );
1915 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1918 $protectDescription .= ') ';
1921 $protectDescription = trim( $protectDescription );
1923 if ( $id ) { # Protection of existing page
1924 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1925 return Status
::newGood();
1928 # Only restrictions with the 'protect' right can cascade...
1929 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1930 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1932 # The schema allows multiple restrictions
1933 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1937 # Update restrictions table
1938 foreach ( $limit as $action => $restrictions ) {
1939 if ( $restrictions != '' ) {
1940 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1941 array( 'pr_page' => $id,
1942 'pr_type' => $action,
1943 'pr_level' => $restrictions,
1944 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1945 'pr_expiry' => $encodedExpiry[$action]
1950 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1951 'pr_type' => $action ), __METHOD__
);
1955 # Prepare a null revision to be added to the history
1956 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1958 $editComment .= ": $reason";
1960 if ( $protectDescription ) {
1961 $editComment .= " ($protectDescription)";
1964 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1967 # Insert a null revision
1968 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1969 $nullRevId = $nullRevision->insertOn( $dbw );
1971 $latest = $this->getLatest();
1972 # Update page record
1973 $dbw->update( 'page',
1975 'page_touched' => $dbw->timestamp(),
1976 'page_restrictions' => '',
1977 'page_latest' => $nullRevId
1978 ), array( /* WHERE */
1983 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1984 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1985 } else { # Protection of non-existing page (also known as "title protection")
1986 # Cascade protection is meaningless in this case
1989 if ( $limit['create'] != '' ) {
1990 $dbw->replace( 'protected_titles',
1991 array( array( 'pt_namespace', 'pt_title' ) ),
1993 'pt_namespace' => $this->mTitle
->getNamespace(),
1994 'pt_title' => $this->mTitle
->getDBkey(),
1995 'pt_create_perm' => $limit['create'],
1996 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1997 'pt_expiry' => $encodedExpiry['create'],
1998 'pt_user' => $user->getId(),
1999 'pt_reason' => $reason,
2003 $dbw->delete( 'protected_titles',
2005 'pt_namespace' => $this->mTitle
->getNamespace(),
2006 'pt_title' => $this->mTitle
->getDBkey()
2012 $this->mTitle
->flushRestrictions();
2014 if ( $logAction == 'unprotect' ) {
2015 $logParams = array();
2017 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2020 # Update the protection log
2021 $log = new LogPage( 'protect' );
2022 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2024 return Status
::newGood();
2028 * Take an array of page restrictions and flatten it to a string
2029 * suitable for insertion into the page_restrictions field.
2030 * @param $limit Array
2033 protected static function flattenRestrictions( $limit ) {
2034 if ( !is_array( $limit ) ) {
2035 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2041 foreach ( $limit as $action => $restrictions ) {
2042 if ( $restrictions != '' ) {
2043 $bits[] = "$action=$restrictions";
2047 return implode( ':', $bits );
2051 * Back-end article deletion
2052 * Deletes the article with database consistency, writes logs, purges caches
2054 * @param $reason string delete reason for deletion log
2055 * @param $suppress bitfield
2056 * Revision::DELETED_TEXT
2057 * Revision::DELETED_COMMENT
2058 * Revision::DELETED_USER
2059 * Revision::DELETED_RESTRICTED
2060 * @param $id int article ID
2061 * @param $commit boolean defaults to true, triggers transaction end
2062 * @param &$errors Array of errors to append to
2063 * @param $user User The relevant user
2064 * @return boolean true if successful
2066 public function doDeleteArticle(
2067 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2070 $user = is_null( $user ) ?
$wgUser : $user;
2072 wfDebug( __METHOD__
. "\n" );
2074 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2077 $dbw = wfGetDB( DB_MASTER
);
2078 $t = $this->mTitle
->getDBkey();
2079 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2081 if ( $t === '' ||
$id == 0 ) {
2085 // Bitfields to further suppress the content
2088 // This should be 15...
2089 $bitfield |
= Revision
::DELETED_TEXT
;
2090 $bitfield |
= Revision
::DELETED_COMMENT
;
2091 $bitfield |
= Revision
::DELETED_USER
;
2092 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2094 $bitfield = 'rev_deleted';
2098 // For now, shunt the revision data into the archive table.
2099 // Text is *not* removed from the text table; bulk storage
2100 // is left intact to avoid breaking block-compression or
2101 // immutable storage schemes.
2103 // For backwards compatibility, note that some older archive
2104 // table entries will have ar_text and ar_flags fields still.
2106 // In the future, we may keep revisions and mark them with
2107 // the rev_deleted field, which is reserved for this purpose.
2108 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2110 'ar_namespace' => 'page_namespace',
2111 'ar_title' => 'page_title',
2112 'ar_comment' => 'rev_comment',
2113 'ar_user' => 'rev_user',
2114 'ar_user_text' => 'rev_user_text',
2115 'ar_timestamp' => 'rev_timestamp',
2116 'ar_minor_edit' => 'rev_minor_edit',
2117 'ar_rev_id' => 'rev_id',
2118 'ar_parent_id' => 'rev_parent_id',
2119 'ar_text_id' => 'rev_text_id',
2120 'ar_text' => '\'\'', // Be explicit to appease
2121 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2122 'ar_len' => 'rev_len',
2123 'ar_page_id' => 'page_id',
2124 'ar_deleted' => $bitfield,
2125 'ar_sha1' => 'rev_content_model',
2126 'ar_content_format' => 'rev_content_format',
2127 'ar_content_format' => 'rev_sha1'
2130 'page_id = rev_page'
2134 # Now that it's safely backed up, delete it
2135 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2136 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2143 $this->doDeleteUpdates( $id );
2145 # Log the deletion, if the page was suppressed, log it at Oversight instead
2146 $logtype = $suppress ?
'suppress' : 'delete';
2148 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2149 $logEntry->setPerformer( $user );
2150 $logEntry->setTarget( $this->mTitle
);
2151 $logEntry->setComment( $reason );
2152 $logid = $logEntry->insert();
2153 $logEntry->publish( $logid );
2159 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2164 * Do some database updates after deletion
2166 * @param $id Int: page_id value of the page being deleted
2168 public function doDeleteUpdates( $id ) {
2169 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2171 $dbw = wfGetDB( DB_MASTER
);
2173 # Delete restrictions for it
2174 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2176 # Fix category table counts
2178 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2180 foreach ( $res as $row ) {
2181 $cats [] = $row->cl_to
;
2184 $this->updateCategoryCounts( array(), $cats );
2186 # If using cascading deletes, we can skip some explicit deletes
2187 if ( !$dbw->cascadingDeletes() ) {
2188 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2190 # Delete outgoing links
2191 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2192 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2193 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2194 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2195 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2196 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2197 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2198 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2199 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2202 # If using cleanup triggers, we can skip some manual deletes
2203 if ( !$dbw->cleanupTriggers() ) {
2204 # Clean up recentchanges entries...
2205 $dbw->delete( 'recentchanges',
2206 array( 'rc_type != ' . RC_LOG
,
2207 'rc_namespace' => $this->mTitle
->getNamespace(),
2208 'rc_title' => $this->mTitle
->getDBkey() ),
2210 $dbw->delete( 'recentchanges',
2211 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2216 self
::onArticleDelete( $this->mTitle
);
2218 # Clear the cached article id so the interface doesn't act like we exist
2219 $this->mTitle
->resetArticleID( 0 );
2223 * Roll back the most recent consecutive set of edits to a page
2224 * from the same user; fails if there are no eligible edits to
2225 * roll back to, e.g. user is the sole contributor. This function
2226 * performs permissions checks on $user, then calls commitRollback()
2227 * to do the dirty work
2229 * @todo: seperate the business/permission stuff out from backend code
2231 * @param $fromP String: Name of the user whose edits to rollback.
2232 * @param $summary String: Custom summary. Set to default summary if empty.
2233 * @param $token String: Rollback token.
2234 * @param $bot Boolean: If true, mark all reverted edits as bot.
2236 * @param $resultDetails Array: contains result-specific array of additional values
2237 * 'alreadyrolled' : 'current' (rev)
2238 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2240 * @param $user User The user performing the rollback
2241 * @return array of errors, each error formatted as
2242 * array(messagekey, param1, param2, ...).
2243 * On success, the array is empty. This array can also be passed to
2244 * OutputPage::showPermissionsErrorPage().
2246 public function doRollback(
2247 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2249 $resultDetails = null;
2252 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2253 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2254 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2256 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2257 $errors[] = array( 'sessionfailure' );
2260 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2261 $errors[] = array( 'actionthrottledtext' );
2264 # If there were errors, bail out now
2265 if ( !empty( $errors ) ) {
2269 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2273 * Backend implementation of doRollback(), please refer there for parameter
2274 * and return value documentation
2276 * NOTE: This function does NOT check ANY permissions, it just commits the
2277 * rollback to the DB. Therefore, you should only call this function direct-
2278 * ly if you want to use custom permissions checks. If you don't, use
2279 * doRollback() instead.
2280 * @param $fromP String: Name of the user whose edits to rollback.
2281 * @param $summary String: Custom summary. Set to default summary if empty.
2282 * @param $bot Boolean: If true, mark all reverted edits as bot.
2284 * @param $resultDetails Array: contains result-specific array of additional values
2285 * @param $guser User The user performing the rollback
2287 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2288 global $wgUseRCPatrol, $wgContLang;
2290 $dbw = wfGetDB( DB_MASTER
);
2292 if ( wfReadOnly() ) {
2293 return array( array( 'readonlytext' ) );
2296 # Get the last editor
2297 $current = Revision
::newFromTitle( $this->mTitle
);
2298 if ( is_null( $current ) ) {
2299 # Something wrong... no page?
2300 return array( array( 'notanarticle' ) );
2303 $from = str_replace( '_', ' ', $fromP );
2304 # User name given should match up with the top revision.
2305 # If the user was deleted then $from should be empty.
2306 if ( $from != $current->getUserText() ) {
2307 $resultDetails = array( 'current' => $current );
2308 return array( array( 'alreadyrolled',
2309 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2310 htmlspecialchars( $fromP ),
2311 htmlspecialchars( $current->getUserText() )
2315 # Get the last edit not by this guy...
2316 # Note: these may not be public values
2317 $user = intval( $current->getRawUser() );
2318 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2319 $s = $dbw->selectRow( 'revision',
2320 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2321 array( 'rev_page' => $current->getPage(),
2322 "rev_user != {$user} OR rev_user_text != {$user_text}"
2324 array( 'USE INDEX' => 'page_timestamp',
2325 'ORDER BY' => 'rev_timestamp DESC' )
2327 if ( $s === false ) {
2328 # No one else ever edited this page
2329 return array( array( 'cantrollback' ) );
2330 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2331 # Only admins can see this text
2332 return array( array( 'notvisiblerev' ) );
2336 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2337 # Mark all reverted edits as bot
2341 if ( $wgUseRCPatrol ) {
2342 # Mark all reverted edits as patrolled
2343 $set['rc_patrolled'] = 1;
2346 if ( count( $set ) ) {
2347 $dbw->update( 'recentchanges', $set,
2349 'rc_cur_id' => $current->getPage(),
2350 'rc_user_text' => $current->getUserText(),
2351 "rc_timestamp > '{$s->rev_timestamp}'",
2356 # Generate the edit summary if necessary
2357 $target = Revision
::newFromId( $s->rev_id
);
2358 if ( empty( $summary ) ) {
2359 if ( $from == '' ) { // no public user name
2360 $summary = wfMsgForContent( 'revertpage-nouser' );
2362 $summary = wfMsgForContent( 'revertpage' );
2366 # Allow the custom summary to use the same args as the default message
2368 $target->getUserText(), $from, $s->rev_id
,
2369 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2370 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2372 $summary = wfMsgReplaceArgs( $summary, $args );
2375 $flags = EDIT_UPDATE
;
2377 if ( $guser->isAllowed( 'minoredit' ) ) {
2378 $flags |
= EDIT_MINOR
;
2381 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2382 $flags |
= EDIT_FORCE_BOT
;
2385 # Actually store the edit
2386 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2387 if ( !empty( $status->value
['revision'] ) ) {
2388 $revId = $status->value
['revision']->getId();
2393 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2395 $resultDetails = array(
2396 'summary' => $summary,
2397 'current' => $current,
2398 'target' => $target,
2406 * The onArticle*() functions are supposed to be a kind of hooks
2407 * which should be called whenever any of the specified actions
2410 * This is a good place to put code to clear caches, for instance.
2412 * This is called on page move and undelete, as well as edit
2414 * @param $title Title object
2416 public static function onArticleCreate( $title ) {
2417 # Update existence markers on article/talk tabs...
2418 if ( $title->isTalkPage() ) {
2419 $other = $title->getSubjectPage();
2421 $other = $title->getTalkPage();
2424 $other->invalidateCache();
2425 $other->purgeSquid();
2427 $title->touchLinks();
2428 $title->purgeSquid();
2429 $title->deleteTitleProtection();
2433 * Clears caches when article is deleted
2435 * @param $title Title
2437 public static function onArticleDelete( $title ) {
2438 # Update existence markers on article/talk tabs...
2439 if ( $title->isTalkPage() ) {
2440 $other = $title->getSubjectPage();
2442 $other = $title->getTalkPage();
2445 $other->invalidateCache();
2446 $other->purgeSquid();
2448 $title->touchLinks();
2449 $title->purgeSquid();
2452 HTMLFileCache
::clearFileCache( $title );
2455 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2456 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2460 if ( $title->getNamespace() == NS_FILE
) {
2461 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2462 $update->doUpdate();
2466 if ( $title->getNamespace() == NS_USER_TALK
) {
2467 $user = User
::newFromName( $title->getText(), false );
2469 $user->setNewtalk( false );
2474 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2478 * Purge caches on page update etc
2480 * @param $title Title object
2481 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2483 public static function onArticleEdit( $title ) {
2484 // Invalidate caches of articles which include this page
2485 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2488 // Invalidate the caches of all pages which redirect here
2489 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2491 # Purge squid for this page only
2492 $title->purgeSquid();
2494 # Clear file cache for this page only
2495 HTMLFileCache
::clearFileCache( $title );
2501 * Returns a list of hidden categories this page is a member of.
2502 * Uses the page_props and categorylinks tables.
2504 * @return Array of Title objects
2506 public function getHiddenCategories() {
2508 $id = $this->mTitle
->getArticleID();
2514 $dbr = wfGetDB( DB_SLAVE
);
2515 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2517 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2518 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2521 if ( $res !== false ) {
2522 foreach ( $res as $row ) {
2523 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2531 * Return an applicable autosummary if one exists for the given edit.
2532 * @param $oldtext String: the previous text of the page.
2533 * @param $newtext String: The submitted text of the page.
2534 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2535 * @return string An appropriate autosummary, or an empty string.
2536 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
2538 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2539 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2541 $handler = ContentHandler
::getForModelName( CONTENT_MODEL_WIKITEXT
);
2542 $oldContent = $handler->unserialize( $oldtext );
2543 $newContent = $handler->unserialize( $newtext );
2545 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2549 * Auto-generates a deletion reason
2551 * @param &$hasHistory Boolean: whether the page has a history
2552 * @return mixed String containing deletion reason or empty string, or boolean false
2553 * if no revision occurred
2554 * @deprecated since 1.20, use ContentHandler::getAutoDeleteReason() instead
2556 public function getAutoDeleteReason( &$hasHistory ) {
2557 #NOTE: stub for backwards-compatibility.
2559 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2560 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2564 * Update all the appropriate counts in the category table, given that
2565 * we've added the categories $added and deleted the categories $deleted.
2567 * @param $added array The names of categories that were added
2568 * @param $deleted array The names of categories that were deleted
2570 public function updateCategoryCounts( $added, $deleted ) {
2571 $ns = $this->mTitle
->getNamespace();
2572 $dbw = wfGetDB( DB_MASTER
);
2574 # First make sure the rows exist. If one of the "deleted" ones didn't
2575 # exist, we might legitimately not create it, but it's simpler to just
2576 # create it and then give it a negative value, since the value is bogus
2579 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2580 $insertCats = array_merge( $added, $deleted );
2581 if ( !$insertCats ) {
2582 # Okay, nothing to do
2586 $insertRows = array();
2588 foreach ( $insertCats as $cat ) {
2589 $insertRows[] = array(
2590 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2594 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2596 $addFields = array( 'cat_pages = cat_pages + 1' );
2597 $removeFields = array( 'cat_pages = cat_pages - 1' );
2599 if ( $ns == NS_CATEGORY
) {
2600 $addFields[] = 'cat_subcats = cat_subcats + 1';
2601 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2602 } elseif ( $ns == NS_FILE
) {
2603 $addFields[] = 'cat_files = cat_files + 1';
2604 $removeFields[] = 'cat_files = cat_files - 1';
2611 array( 'cat_title' => $added ),
2620 array( 'cat_title' => $deleted ),
2627 * Updates cascading protections
2629 * @param $parserOutput ParserOutput object for the current version
2631 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2632 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2636 // templatelinks table may have become out of sync,
2637 // especially if using variable-based transclusions.
2638 // For paranoia, check if things have changed and if
2639 // so apply updates to the database. This will ensure
2640 // that cascaded protections apply as soon as the changes
2643 # Get templates from templatelinks
2644 $id = $this->mTitle
->getArticleID();
2646 $tlTemplates = array();
2648 $dbr = wfGetDB( DB_SLAVE
);
2649 $res = $dbr->select( array( 'templatelinks' ),
2650 array( 'tl_namespace', 'tl_title' ),
2651 array( 'tl_from' => $id ),
2655 foreach ( $res as $row ) {
2656 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2659 # Get templates from parser output.
2660 $poTemplates = array();
2661 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2662 foreach ( $templates as $dbk => $id ) {
2663 $poTemplates["$ns:$dbk"] = true;
2668 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2670 if ( count( $templates_diff ) > 0 ) {
2671 # Whee, link updates time.
2672 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2678 * Return a list of templates used by this article.
2679 * Uses the templatelinks table
2681 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2682 * @return Array of Title objects
2684 public function getUsedTemplates() {
2685 return $this->mTitle
->getTemplateLinksFrom();
2689 * Perform article updates on a special page creation.
2691 * @param $rev Revision object
2693 * @todo This is a shitty interface function. Kill it and replace the
2694 * other shitty functions like doEditUpdates and such so it's not needed
2696 * @deprecated since 1.18, use doEditUpdates()
2698 public function createUpdates( $rev ) {
2699 wfDeprecated( __METHOD__
, '1.18' );
2701 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2705 * This function is called right before saving the wikitext,
2706 * so we can do things like signatures and links-in-context.
2708 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2709 * @param $text String article contents
2710 * @param $user User object: user doing the edit
2711 * @param $popts ParserOptions object: parser options, default options for
2712 * the user loaded if null given
2713 * @return string article contents with altered wikitext markup (signatures
2714 * converted, {{subst:}}, templates, etc.)
2716 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2717 global $wgParser, $wgUser;
2719 wfDeprecated( __METHOD__
, '1.19' );
2721 $user = is_null( $user ) ?
$wgUser : $user;
2723 if ( $popts === null ) {
2724 $popts = ParserOptions
::newFromUser( $user );
2727 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2731 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2733 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2736 public function isBigDeletion() {
2737 wfDeprecated( __METHOD__
, '1.19' );
2738 return $this->mTitle
->isBigDeletion();
2742 * Get the approximate revision count of this page.
2744 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2747 public function estimateRevisionCount() {
2748 wfDeprecated( __METHOD__
, '1.19' );
2749 return $this->mTitle
->estimateRevisionCount();
2753 * Update the article's restriction field, and leave a log entry.
2755 * @deprecated since 1.19
2756 * @param $limit Array: set of restriction keys
2757 * @param $reason String
2758 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2759 * @param $expiry Array: per restriction type expiration
2760 * @param $user User The user updating the restrictions
2761 * @return bool true on success
2763 public function updateRestrictions(
2764 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2768 $user = is_null( $user ) ?
$wgUser : $user;
2770 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2774 * @deprecated since 1.18
2776 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2777 wfDeprecated( __METHOD__
, '1.18' );
2779 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2783 * @deprecated since 1.18
2785 public function viewUpdates() {
2786 wfDeprecated( __METHOD__
, '1.18' );
2788 return $this->doViewUpdates( $wgUser );
2792 * @deprecated since 1.18
2794 public function useParserCache( $oldid ) {
2795 wfDeprecated( __METHOD__
, '1.18' );
2797 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2801 class PoolWorkArticleView
extends PoolCounterWork
{
2819 * @var ParserOptions
2821 private $parserOptions;
2829 * @var ParserOutput|false
2831 private $parserOutput = false;
2836 private $isDirty = false;
2841 private $error = false;
2847 * @param $revid Integer: ID of the revision being parsed
2848 * @param $useParserCache Boolean: whether to use the parser cache
2849 * @param $parserOptions parserOptions to use for the parse operation
2850 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
2852 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
2853 if ( is_string($content) ) { #BC: old style call
2854 $modelName = $page->getRevision()->getContentModelName();
2855 $format = $page->getRevision()->getContentFormat();
2856 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelName, $format );
2859 $this->page
= $page;
2860 $this->revid
= $revid;
2861 $this->cacheable
= $useParserCache;
2862 $this->parserOptions
= $parserOptions;
2863 $this->content
= $content;
2864 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2865 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2869 * Get the ParserOutput from this object, or false in case of failure
2871 * @return ParserOutput
2873 public function getParserOutput() {
2874 return $this->parserOutput
;
2878 * Get whether the ParserOutput is a dirty one (i.e. expired)
2882 public function getIsDirty() {
2883 return $this->isDirty
;
2887 * Get a Status object in case of error or false otherwise
2889 * @return Status|false
2891 public function getError() {
2892 return $this->error
;
2899 global $wgParser, $wgUseFileCache;
2901 $isCurrent = $this->revid
=== $this->page
->getLatest();
2903 if ( $this->content
!== null ) {
2904 $content = $this->content
;
2905 } elseif ( $isCurrent ) {
2906 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
2908 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2909 if ( $rev === null ) {
2912 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
2916 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
2921 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2922 $this->page
->getTitle()->getPrefixedDBkey() ) );
2925 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2926 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2929 // Make sure file cache is not used on uncacheable content.
2930 // Output that has magic words in it can still use the parser cache
2931 // (if enabled), though it will generally expire sooner.
2932 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2933 $wgUseFileCache = false;
2937 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2946 function getCachedWork() {
2947 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2949 if ( $this->parserOutput
=== false ) {
2950 wfDebug( __METHOD__
. ": parser cache miss\n" );
2953 wfDebug( __METHOD__
. ": parser cache hit\n" );
2961 function fallback() {
2962 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2964 if ( $this->parserOutput
=== false ) {
2965 wfDebugLog( 'dirty', "dirty missing\n" );
2966 wfDebug( __METHOD__
. ": no dirty cache\n" );
2969 wfDebug( __METHOD__
. ": sending dirty output\n" );
2970 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2971 $this->isDirty
= true;
2977 * @param $status Status
2979 function error( $status ) {
2980 $this->error
= $status;