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 $retval = Title
::newFromRedirectRecurse( $this->getRawText() ); #FIXME: move this to Content object
639 $this->insertRedirectEntry( $retval );
644 * Insert or update the redirect table entry for this page to indicate
645 * it redirects to $rt .
646 * @param $rt Title redirect target
648 public function insertRedirectEntry( $rt ) {
649 $dbw = wfGetDB( DB_MASTER
);
650 $dbw->replace( 'redirect', array( 'rd_from' ),
652 'rd_from' => $this->getId(),
653 'rd_namespace' => $rt->getNamespace(),
654 'rd_title' => $rt->getDBkey(),
655 'rd_fragment' => $rt->getFragment(),
656 'rd_interwiki' => $rt->getInterwiki(),
663 * Get the Title object or URL this page redirects to
665 * @return mixed false, Title of in-wiki target, or string with URL
667 public function followRedirect() {
668 return $this->getRedirectURL( $this->getRedirectTarget() );
672 * Get the Title object or URL to use for a redirect. We use Title
673 * objects for same-wiki, non-special redirects and URLs for everything
675 * @param $rt Title Redirect target
676 * @return mixed false, Title object of local target, or string with URL
678 public function getRedirectURL( $rt ) {
683 if ( $rt->isExternal() ) {
684 if ( $rt->isLocal() ) {
685 // Offsite wikis need an HTTP redirect.
687 // This can be hard to reverse and may produce loops,
688 // so they may be disabled in the site configuration.
689 $source = $this->mTitle
->getFullURL( 'redirect=no' );
690 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
692 // External pages pages without "local" bit set are not valid
698 if ( $rt->isSpecialPage() ) {
699 // Gotta handle redirects to special pages differently:
700 // Fill the HTTP response "Location" header and ignore
701 // the rest of the page we're on.
703 // Some pages are not valid targets
704 if ( $rt->isValidRedirectTarget() ) {
705 return $rt->getFullURL();
715 * Get a list of users who have edited this article, not including the user who made
716 * the most recent revision, which you can get from $article->getUser() if you want it
717 * @return UserArrayFromResult
719 public function getContributors() {
720 # @todo FIXME: This is expensive; cache this info somewhere.
722 $dbr = wfGetDB( DB_SLAVE
);
724 if ( $dbr->implicitGroupby() ) {
725 $realNameField = 'user_real_name';
727 $realNameField = 'MIN(user_real_name) AS user_real_name';
730 $tables = array( 'revision', 'user' );
733 'rev_user as user_id',
734 'rev_user_text AS user_name',
736 'MAX(rev_timestamp) AS timestamp',
739 $conds = array( 'rev_page' => $this->getId() );
741 // The user who made the top revision gets credited as "this page was last edited by
742 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
743 $user = $this->getUser();
745 $conds[] = "rev_user != $user";
747 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
750 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
753 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
757 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
758 'ORDER BY' => 'timestamp DESC',
761 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
762 return new UserArrayFromResult( $res );
766 * Get the last N authors
767 * @param $num Integer: number of revisions to get
768 * @param $revLatest String: the latest rev_id, selected from the master (optional)
769 * @return array Array of authors, duplicates not removed
771 public function getLastNAuthors( $num, $revLatest = 0 ) {
772 wfProfileIn( __METHOD__
);
773 // First try the slave
774 // If that doesn't have the latest revision, try the master
776 $db = wfGetDB( DB_SLAVE
);
779 $res = $db->select( array( 'page', 'revision' ),
780 array( 'rev_id', 'rev_user_text' ),
782 'page_namespace' => $this->mTitle
->getNamespace(),
783 'page_title' => $this->mTitle
->getDBkey(),
787 'ORDER BY' => 'rev_timestamp DESC',
793 wfProfileOut( __METHOD__
);
797 $row = $db->fetchObject( $res );
799 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
800 $db = wfGetDB( DB_MASTER
);
805 } while ( $continue );
807 $authors = array( $row->rev_user_text
);
809 foreach ( $res as $row ) {
810 $authors[] = $row->rev_user_text
;
813 wfProfileOut( __METHOD__
);
818 * Should the parser cache be used?
820 * @param $parserOptions ParserOptions to check
824 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
825 global $wgEnableParserCache;
827 return $wgEnableParserCache
828 && $parserOptions->getStubThreshold() == 0
829 && $this->mTitle
->exists()
830 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
831 && $this->mTitle
->isWikitextPage(); #FIXME: ask ContentHandler if cachable!
835 * Get a ParserOutput for the given ParserOptions and revision ID.
836 * The parser cache will be used if possible.
839 * @param $parserOptions ParserOptions to use for the parse operation
840 * @param $oldid Revision ID to get the text from, passing null or 0 will
841 * get the current revision (default value)
842 * @return ParserOutput or false if the revision was not found
844 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
845 wfProfileIn( __METHOD__
);
847 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
848 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
849 if ( $parserOptions->getStubThreshold() ) {
850 wfIncrStats( 'pcache_miss_stub' );
853 if ( $useParserCache ) {
854 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
855 if ( $parserOutput !== false ) {
856 wfProfileOut( __METHOD__
);
857 return $parserOutput;
861 if ( $oldid === null ||
$oldid === 0 ) {
862 $oldid = $this->getLatest();
865 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
868 wfProfileOut( __METHOD__
);
870 return $pool->getParserOutput();
874 * Do standard deferred updates after page view
875 * @param $user User The relevant user
877 public function doViewUpdates( User
$user ) {
878 global $wgDisableCounters;
879 if ( wfReadOnly() ) {
883 # Don't update page view counters on views from bot users (bug 14044)
884 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
885 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
886 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
889 # Update newtalk / watchlist notification status
890 $user->clearNotification( $this->mTitle
);
894 * Perform the actions of a page purging
896 public function doPurge() {
899 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
903 // Invalidate the cache
904 $this->mTitle
->invalidateCache();
908 // Commit the transaction before the purge is sent
909 $dbw = wfGetDB( DB_MASTER
);
913 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
917 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
918 if ( $this->mTitle
->exists() ) {
919 $text = $this->getNativeData(); #FIXME: may not be a string. check Content model!
924 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
930 * Insert a new empty page record for this article.
931 * This *must* be followed up by creating a revision
932 * and running $this->updateRevisionOn( ... );
933 * or else the record will be left in a funky state.
934 * Best if all done inside a transaction.
936 * @param $dbw DatabaseBase
937 * @return int The newly created page_id key, or false if the title already existed
939 public function insertOn( $dbw ) {
940 wfProfileIn( __METHOD__
);
942 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
943 $dbw->insert( 'page', array(
944 'page_id' => $page_id,
945 'page_namespace' => $this->mTitle
->getNamespace(),
946 'page_title' => $this->mTitle
->getDBkey(),
948 'page_restrictions' => '',
949 'page_is_redirect' => 0, # Will set this shortly...
951 'page_random' => wfRandom(),
952 'page_touched' => $dbw->timestamp(),
953 'page_latest' => 0, # Fill this in shortly...
954 'page_len' => 0, # Fill this in shortly...
955 ), __METHOD__
, 'IGNORE' );
957 $affected = $dbw->affectedRows();
960 $newid = $dbw->insertId();
961 $this->mTitle
->resetArticleID( $newid );
963 wfProfileOut( __METHOD__
);
965 return $affected ?
$newid : false;
969 * Update the page record to point to a newly saved revision.
971 * @param $dbw DatabaseBase: object
972 * @param $revision Revision: For ID number, and text used to set
973 * length and redirect status fields
974 * @param $lastRevision Integer: if given, will not overwrite the page field
975 * when different from the currently set value.
976 * Giving 0 indicates the new page flag should be set
978 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
979 * removing rows in redirect table.
980 * @return bool true on success, false on failure
983 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
984 wfProfileIn( __METHOD__
);
986 $text = $revision->getText();
987 $len = strlen( $text );
988 $rt = Title
::newFromRedirectRecurse( $text );
990 $conditions = array( 'page_id' => $this->getId() );
992 if ( !is_null( $lastRevision ) ) {
993 # An extra check against threads stepping on each other
994 $conditions['page_latest'] = $lastRevision;
997 $now = wfTimestampNow();
998 $dbw->update( 'page',
1000 'page_latest' => $revision->getId(),
1001 'page_touched' => $dbw->timestamp( $now ),
1002 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1003 'page_is_redirect' => $rt !== null ?
1 : 0,
1009 $result = $dbw->affectedRows() != 0;
1011 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1012 $this->setLastEdit( $revision );
1013 $this->setCachedLastEditTime( $now );
1014 $this->mLatest
= $revision->getId();
1015 $this->mIsRedirect
= (bool)$rt;
1016 # Update the LinkCache.
1017 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1020 wfProfileOut( __METHOD__
);
1025 * Add row to the redirect table if this is a redirect, remove otherwise.
1027 * @param $dbw DatabaseBase
1028 * @param $redirectTitle Title object pointing to the redirect target,
1029 * or NULL if this is not a redirect
1030 * @param $lastRevIsRedirect If given, will optimize adding and
1031 * removing rows in redirect table.
1032 * @return bool true on success, false on failure
1035 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1036 // Always update redirects (target link might have changed)
1037 // Update/Insert if we don't know if the last revision was a redirect or not
1038 // Delete if changing from redirect to non-redirect
1039 $isRedirect = !is_null( $redirectTitle );
1041 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1045 wfProfileIn( __METHOD__
);
1046 if ( $isRedirect ) {
1047 $this->insertRedirectEntry( $redirectTitle );
1049 // This is not a redirect, remove row from redirect table
1050 $where = array( 'rd_from' => $this->getId() );
1051 $dbw->delete( 'redirect', $where, __METHOD__
);
1054 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1055 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1057 wfProfileOut( __METHOD__
);
1059 return ( $dbw->affectedRows() != 0 );
1063 * If the given revision is newer than the currently set page_latest,
1064 * update the page record. Otherwise, do nothing.
1066 * @param $dbw Database object
1067 * @param $revision Revision object
1070 public function updateIfNewerOn( $dbw, $revision ) {
1071 wfProfileIn( __METHOD__
);
1073 $row = $dbw->selectRow(
1074 array( 'revision', 'page' ),
1075 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1077 'page_id' => $this->getId(),
1078 'page_latest=rev_id' ),
1082 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1083 wfProfileOut( __METHOD__
);
1086 $prev = $row->rev_id
;
1087 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1089 # No or missing previous revision; mark the page as new
1091 $lastRevIsRedirect = null;
1094 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1096 wfProfileOut( __METHOD__
);
1101 * Get the text that needs to be saved in order to undo all revisions
1102 * between $undo and $undoafter. Revisions must belong to the same page,
1103 * must exist and must not be deleted
1104 * @param $undo Revision
1105 * @param $undoafter Revision Must be an earlier revision than $undo
1106 * @return mixed string on success, false on failure
1107 * @deprecated since 1.20: use ContentHandler::getUndoContent() instead.
1109 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) { #FIXME: replace usages.
1110 $this->loadLastEdit();
1112 if ( $this->mLastRevision
) {
1113 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1114 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1119 return ContentHandler
::getContentText( $undone );
1127 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1128 * @param $text String: new text of the section
1129 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1130 * @param $edittime String: revision timestamp or null to use the current revision
1131 * @return Content new complete article content, or null if error
1132 * @deprecated since 1.20: use Content::replaceSection () instead.
1134 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) { #FIXME: create a Content-based version (take and return Content object)
1135 wfProfileIn( __METHOD__
);
1137 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1139 if ( strval( $section ) == '' ) {
1140 // Whole-page edit; let the whole text through
1141 $newContent = $sectionContent;
1143 // Bug 30711: always use current version when adding a new section
1144 if ( is_null( $edittime ) ||
$section == 'new' ) {
1145 $oldContent = $this->getContent();
1146 if ( ! $oldContent ) {
1147 wfDebug( __METHOD__
. ": no page text\n" );
1148 wfProfileOut( __METHOD__
);
1152 $dbw = wfGetDB( DB_MASTER
);
1153 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1156 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1157 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1158 wfProfileOut( __METHOD__
);
1162 $oldContent = $rev->getContent();
1165 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1168 wfProfileOut( __METHOD__
);
1169 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1173 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1175 * @return Int updated $flags
1177 function checkFlags( $flags ) {
1178 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1179 if ( $this->mTitle
->getArticleID() ) {
1180 $flags |
= EDIT_UPDATE
;
1190 * Change an existing article or create a new article. Updates RC and all necessary caches,
1191 * optionally via the deferred update array.
1193 * @param $text String: new text
1194 * @param $summary String: edit summary
1195 * @param $flags Integer bitfield:
1197 * Article is known or assumed to be non-existent, create a new one
1199 * Article is known or assumed to be pre-existing, update it
1201 * Mark this edit minor, if the user is allowed to do so
1203 * Do not log the change in recentchanges
1205 * Mark the edit a "bot" edit regardless of user rights
1206 * EDIT_DEFER_UPDATES
1207 * Defer some of the updates until the end of index.php
1209 * Fill in blank summaries with generated text where possible
1211 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1212 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1213 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1214 * edit-already-exists error will be returned. These two conditions are also possible with
1215 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1217 * @param $baseRevId the revision ID this edit was based off, if any
1218 * @param $user User the user doing the edit
1220 * @return Status object. Possible errors:
1221 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1222 * edit-gone-missing: In update mode, but the article didn't exist
1223 * edit-conflict: In update mode, the article changed unexpectedly
1224 * edit-no-change: Warning that the text was the same as before
1225 * edit-already-exists: In creation mode, but the article already exists
1227 * Extensions may define additional errors.
1229 * $return->value will contain an associative array with members as follows:
1230 * new: Boolean indicating if the function attempted to create a new article
1231 * revision: The revision object for the inserted revision, or null
1233 * Compatibility note: this function previously returned a boolean value indicating success/failure
1234 * @deprecated since 1.20: use doEditContent() instead.
1236 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #FIXME: use doEditContent() instead
1237 #TODO: log use of deprecated function
1238 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1240 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1244 * Change an existing article or create a new article. Updates RC and all necessary caches,
1245 * optionally via the deferred update array.
1247 * @param $content Content: new content
1248 * @param $summary String: edit summary
1249 * @param $flags Integer bitfield:
1251 * Article is known or assumed to be non-existent, create a new one
1253 * Article is known or assumed to be pre-existing, update it
1255 * Mark this edit minor, if the user is allowed to do so
1257 * Do not log the change in recentchanges
1259 * Mark the edit a "bot" edit regardless of user rights
1260 * EDIT_DEFER_UPDATES
1261 * Defer some of the updates until the end of index.php
1263 * Fill in blank summaries with generated text where possible
1265 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1266 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1267 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1268 * edit-already-exists error will be returned. These two conditions are also possible with
1269 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1271 * @param $baseRevId the revision ID this edit was based off, if any
1272 * @param $user User the user doing the edit
1273 * @param $serialisation_format String: format for storing the content in the database
1275 * @return Status object. Possible errors:
1276 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1277 * edit-gone-missing: In update mode, but the article didn't exist
1278 * edit-conflict: In update mode, the article changed unexpectedly
1279 * edit-no-change: Warning that the text was the same as before
1280 * edit-already-exists: In creation mode, but the article already exists
1282 * Extensions may define additional errors.
1284 * $return->value will contain an associative array with members as follows:
1285 * new: Boolean indicating if the function attempted to create a new article
1286 * revision: The revision object for the inserted revision, or null
1288 * Compatibility note: this function previously returned a boolean value indicating success/failure
1290 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1291 User
$user = null, $serialisation_format = null ) { #FIXME: use this
1292 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1294 # Low-level sanity check
1295 if ( $this->mTitle
->getText() === '' ) {
1296 throw new MWException( 'Something is trying to edit an article with an empty title' );
1299 wfProfileIn( __METHOD__
);
1301 $user = is_null( $user ) ?
$wgUser : $user;
1302 $status = Status
::newGood( array() );
1304 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1305 $this->loadPageData( 'fromdbmaster' );
1307 $flags = $this->checkFlags( $flags );
1310 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary, #FIXME: document new hook!
1311 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1313 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { # avoid serialization overhead if the hook isn't present
1314 $content_text = $content->serialize();
1315 $txt = $content_text; # clone
1317 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary, #FIXME: deprecate legacy hook!
1318 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1320 if ( $txt !== $content_text ) {
1321 # if the text changed, unserialize the new version to create an updated Content object.
1322 $content = $content->getContentHandler()->unserialize( $txt );
1327 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1329 if ( $status->isOK() ) {
1330 $status->fatal( 'edit-hook-aborted' );
1333 wfProfileOut( __METHOD__
);
1337 # Silently ignore EDIT_MINOR if not allowed
1338 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1339 $bot = $flags & EDIT_FORCE_BOT
;
1341 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1343 $oldsize = $old_content ?
$old_content->getSize() : 0;
1344 $oldid = $this->getLatest();
1345 $oldIsRedirect = $this->isRedirect();
1346 $oldcountable = $this->isCountable();
1348 $handler = $content->getContentHandler();
1350 # Provide autosummaries if one is not provided and autosummaries are enabled.
1351 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1352 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1355 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1356 $serialized = $editInfo->pst
;
1357 $content = $editInfo->pstContent
;
1358 $newsize = $content->getSize();
1360 $dbw = wfGetDB( DB_MASTER
);
1361 $now = wfTimestampNow();
1362 $this->mTimestamp
= $now;
1364 if ( $flags & EDIT_UPDATE
) {
1365 # Update article, but only if changed.
1366 $status->value
['new'] = false;
1369 # Article gone missing
1370 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1371 $status->fatal( 'edit-gone-missing' );
1373 wfProfileOut( __METHOD__
);
1377 # Make sure the revision is either completely inserted or not inserted at all
1378 if ( !$wgDBtransactions ) {
1379 $userAbort = ignore_user_abort( true );
1382 $revision = new Revision( array(
1383 'page' => $this->getId(),
1384 'comment' => $summary,
1385 'minor_edit' => $isminor,
1386 'text' => $serialized,
1388 'parent_id' => $oldid,
1389 'user' => $user->getId(),
1390 'user_text' => $user->getName(),
1394 $changed = !$content->equals( $old_content );
1398 $revisionId = $revision->insertOn( $dbw );
1402 # Note that we use $this->mLatest instead of fetching a value from the master DB
1403 # during the course of this function. This makes sure that EditPage can detect
1404 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1405 # before this function is called. A previous function used a separate query, this
1406 # creates a window where concurrent edits can cause an ignored edit conflict.
1407 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1410 /* Belated edit conflict! Run away!! */
1411 $status->fatal( 'edit-conflict' );
1413 # Delete the invalid revision if the DB is not transactional
1414 if ( !$wgDBtransactions ) {
1415 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1421 global $wgUseRCPatrol;
1422 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1423 # Update recentchanges
1424 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1425 # Mark as patrolled if the user can do so
1426 $patrolled = $wgUseRCPatrol && !count(
1427 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1428 # Add RC row to the DB
1429 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1430 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1431 $revisionId, $patrolled
1434 # Log auto-patrolled edits
1436 PatrolLog
::record( $rc, true );
1439 $user->incEditCount();
1443 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1444 // related variables correctly
1445 $revision->setId( $this->getLatest() );
1448 if ( !$wgDBtransactions ) {
1449 ignore_user_abort( $userAbort );
1452 // Now that ignore_user_abort is restored, we can respond to fatal errors
1453 if ( !$status->isOK() ) {
1454 wfProfileOut( __METHOD__
);
1458 # Update links tables, site stats, etc.
1459 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1460 'oldcountable' => $oldcountable ) );
1463 $status->warning( 'edit-no-change' );
1465 // Update page_touched, this is usually implicit in the page update
1466 // Other cache updates are done in onArticleEdit()
1467 $this->mTitle
->invalidateCache();
1470 # Create new article
1471 $status->value
['new'] = true;
1475 # Add the page record; stake our claim on this title!
1476 # This will return false if the article already exists
1477 $newid = $this->insertOn( $dbw );
1479 if ( $newid === false ) {
1481 $status->fatal( 'edit-already-exists' );
1483 wfProfileOut( __METHOD__
);
1487 # Save the revision text...
1488 $revision = new Revision( array(
1490 'comment' => $summary,
1491 'minor_edit' => $isminor,
1492 'text' => $serialized,
1494 'user' => $user->getId(),
1495 'user_text' => $user->getName(),
1498 $revisionId = $revision->insertOn( $dbw );
1500 # Update the page record with revision data
1501 $this->updateRevisionOn( $dbw, $revision, 0 );
1503 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1505 # Update recentchanges
1506 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1507 global $wgUseRCPatrol, $wgUseNPPatrol;
1509 # Mark as patrolled if the user can do so
1510 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1511 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1512 # Add RC row to the DB
1513 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1514 '', $content->getSize(), $revisionId, $patrolled );
1516 # Log auto-patrolled edits
1518 PatrolLog
::record( $rc, true );
1521 $user->incEditCount();
1524 # Update links, etc.
1525 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1527 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1528 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1530 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1531 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1534 # Do updates right now unless deferral was requested
1535 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1536 DeferredUpdates
::doUpdates();
1539 // Return the new revision (or null) to the caller
1540 $status->value
['revision'] = $revision;
1542 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1543 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1545 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1546 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1548 # Promote user to any groups they meet the criteria for
1549 $user->addAutopromoteOnceGroups( 'onEdit' );
1551 wfProfileOut( __METHOD__
);
1556 * Get parser options suitable for rendering the primary article wikitext
1557 * @param User|string $user User object or 'canonical'
1558 * @return ParserOptions
1560 public function makeParserOptions( $user ) {
1562 if ( $user instanceof User
) { // settings per user (even anons)
1563 $options = ParserOptions
::newFromUser( $user );
1564 } else { // canonical settings
1565 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1567 $options->enableLimitReport(); // show inclusion/loop reports
1568 $options->setTidy( true ); // fix bad HTML
1573 * Prepare text which is about to be saved.
1574 * Returns a stdclass with source, pst and output members
1575 * @deprecated in 1.20: use prepareContentForEdit instead.
1577 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) { #FIXME: use prepareContentForEdit() instead #XXX: who uses this?!
1578 #TODO: log use of deprecated function
1579 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1580 return $this->prepareContentForEdit( $content, $revid , $user );
1584 * Prepare content which is about to be saved.
1585 * Returns a stdclass with source, pst and output members
1587 * @param \Content $content
1588 * @param null $revid
1589 * @param null|\User $user
1590 * @param null $serialization_format
1591 * @return bool|object
1593 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) { #FIXME: use this #XXX: really public?!
1594 global $wgParser, $wgContLang, $wgUser;
1595 $user = is_null( $user ) ?
$wgUser : $user;
1596 // @TODO fixme: check $user->getId() here???
1598 if ( $this->mPreparedEdit
1599 && $this->mPreparedEdit
->newContent
1600 && $this->mPreparedEdit
->newContent
->equals( $content )
1601 && $this->mPreparedEdit
->revid
== $revid
1602 && $this->mPreparedEdit
->format
== $serialization_format
1603 #XXX: also check $user here?
1606 return $this->mPreparedEdit
;
1609 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1610 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1612 $edit = (object)array();
1613 $edit->revid
= $revid;
1615 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1616 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1617 $edit->format
= $serialization_format;
1619 $edit->popts
= $this->makeParserOptions( 'canonical' );
1620 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1622 $edit->newContent
= $content;
1623 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1625 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1626 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1628 $this->mPreparedEdit
= $edit;
1634 * Do standard deferred updates after page edit.
1635 * Update links tables, site stats, search index and message cache.
1636 * Purges pages that include this page if the text was changed here.
1637 * Every 100th edit, prune the recent changes table.
1640 * @param $revision Revision object
1641 * @param $user User object that did the revision
1642 * @param $options Array of options, following indexes are used:
1643 * - changed: boolean, whether the revision changed the content (default true)
1644 * - created: boolean, whether the revision created the page (default false)
1645 * - oldcountable: boolean or null (default null):
1646 * - boolean: whether the page was counted as an article before that
1647 * revision, only used in changed is true and created is false
1648 * - null: don't change the article count
1650 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1651 global $wgEnableParserCache;
1653 wfProfileIn( __METHOD__
);
1655 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1656 $text = $revision->getText();
1659 # Be careful not to double-PST: $text is usually already PST-ed once
1660 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1661 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1662 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1664 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1665 $editInfo = $this->mPreparedEdit
;
1668 # Save it to the parser cache
1669 if ( $wgEnableParserCache ) {
1670 $parserCache = ParserCache
::singleton();
1671 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1674 # Update the links tables
1675 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1678 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1680 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1681 if ( 0 == mt_rand( 0, 99 ) ) {
1682 // Flush old entries from the `recentchanges` table; we do this on
1683 // random requests so as to avoid an increase in writes for no good reason
1686 $dbw = wfGetDB( DB_MASTER
);
1687 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1690 array( "rc_timestamp < '$cutoff'" ),
1696 if ( !$this->mTitle
->exists() ) {
1697 wfProfileOut( __METHOD__
);
1701 $id = $this->getId();
1702 $title = $this->mTitle
->getPrefixedDBkey();
1703 $shortTitle = $this->mTitle
->getDBkey();
1705 if ( !$options['changed'] ) {
1708 } elseif ( $options['created'] ) {
1709 $good = (int)$this->isCountable( $editInfo );
1711 } elseif ( $options['oldcountable'] !== null ) {
1712 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1719 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1720 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1722 # If this is another user's talk page, update newtalk.
1723 # Don't do this if $options['changed'] = false (null-edits) nor if
1724 # it's a minor edit and the user doesn't want notifications for those.
1725 if ( $options['changed']
1726 && $this->mTitle
->getNamespace() == NS_USER_TALK
1727 && $shortTitle != $user->getTitleKey()
1728 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1730 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1731 $other = User
::newFromName( $shortTitle, false );
1733 wfDebug( __METHOD__
. ": invalid username\n" );
1734 } elseif ( User
::isIP( $shortTitle ) ) {
1735 // An anonymous user
1736 $other->setNewtalk( true );
1737 } elseif ( $other->isLoggedIn() ) {
1738 $other->setNewtalk( true );
1740 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1745 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1746 MessageCache
::singleton()->replace( $shortTitle, $text );
1749 if( $options['created'] ) {
1750 self
::onArticleCreate( $this->mTitle
);
1752 self
::onArticleEdit( $this->mTitle
);
1755 wfProfileOut( __METHOD__
);
1759 * Edit an article without doing all that other stuff
1760 * The article must already exist; link tables etc
1761 * are not updated, caches are not flushed.
1763 * @param $text String: text submitted
1764 * @param $user User The relevant user
1765 * @param $comment String: comment submitted
1766 * @param $minor Boolean: whereas it's a minor modification
1768 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1769 #TODO: log use of deprecated function
1770 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1771 return $this->doQuickEdit( $content, $user, $comment , $minor );
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 $content Content: content submitted
1780 * @param $user User The relevant user
1781 * @param $comment String: comment submitted
1782 * @param $serialisation_format String: format for storing the content in the database
1783 * @param $minor Boolean: whereas it's a minor modification
1785 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
1786 wfProfileIn( __METHOD__
);
1788 $serialized = $content->serialize( $serialisation_format );
1790 $dbw = wfGetDB( DB_MASTER
);
1791 $revision = new Revision( array(
1792 'page' => $this->getId(),
1793 'text' => $serialized,
1794 'length' => $content->getSize(),
1795 'comment' => $comment,
1796 'minor_edit' => $minor ?
1 : 0,
1798 $revision->insertOn( $dbw );
1799 $this->updateRevisionOn( $dbw, $revision );
1801 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1803 wfProfileOut( __METHOD__
);
1807 * Update the article's restriction field, and leave a log entry.
1808 * This works for protection both existing and non-existing pages.
1810 * @param $limit Array: set of restriction keys
1811 * @param $reason String
1812 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1813 * @param $expiry Array: per restriction type expiration
1814 * @param $user User The user updating the restrictions
1815 * @return bool true on success
1817 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1820 if ( wfReadOnly() ) {
1821 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1824 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1826 $id = $this->mTitle
->getArticleID();
1832 // Take this opportunity to purge out expired restrictions
1833 Title
::purgeExpiredRestrictions();
1835 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1836 # we expect a single selection, but the schema allows otherwise.
1837 $isProtected = false;
1841 $dbw = wfGetDB( DB_MASTER
);
1843 foreach ( $restrictionTypes as $action ) {
1844 if ( !isset( $expiry[$action] ) ) {
1845 $expiry[$action] = $dbw->getInfinity();
1847 if ( !isset( $limit[$action] ) ) {
1848 $limit[$action] = '';
1849 } elseif ( $limit[$action] != '' ) {
1853 # Get current restrictions on $action
1854 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1855 if ( $current != '' ) {
1856 $isProtected = true;
1859 if ( $limit[$action] != $current ) {
1861 } elseif ( $limit[$action] != '' ) {
1862 # Only check expiry change if the action is actually being
1863 # protected, since expiry does nothing on an not-protected
1865 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1871 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1875 # If nothing's changed, do nothing
1877 return Status
::newGood();
1880 if ( !$protect ) { # No protection at all means unprotection
1881 $revCommentMsg = 'unprotectedarticle';
1882 $logAction = 'unprotect';
1883 } elseif ( $isProtected ) {
1884 $revCommentMsg = 'modifiedarticleprotection';
1885 $logAction = 'modify';
1887 $revCommentMsg = 'protectedarticle';
1888 $logAction = 'protect';
1891 $encodedExpiry = array();
1892 $protectDescription = '';
1893 foreach ( $limit as $action => $restrictions ) {
1894 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1895 if ( $restrictions != '' ) {
1896 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1897 if ( $encodedExpiry[$action] != 'infinity' ) {
1898 $protectDescription .= wfMsgForContent( 'protect-expiring',
1899 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1900 $wgContLang->date( $expiry[$action], false, false ) ,
1901 $wgContLang->time( $expiry[$action], false, false ) );
1903 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1906 $protectDescription .= ') ';
1909 $protectDescription = trim( $protectDescription );
1911 if ( $id ) { # Protection of existing page
1912 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1913 return Status
::newGood();
1916 # Only restrictions with the 'protect' right can cascade...
1917 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1918 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1920 # The schema allows multiple restrictions
1921 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1925 # Update restrictions table
1926 foreach ( $limit as $action => $restrictions ) {
1927 if ( $restrictions != '' ) {
1928 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1929 array( 'pr_page' => $id,
1930 'pr_type' => $action,
1931 'pr_level' => $restrictions,
1932 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1933 'pr_expiry' => $encodedExpiry[$action]
1938 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1939 'pr_type' => $action ), __METHOD__
);
1943 # Prepare a null revision to be added to the history
1944 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1946 $editComment .= ": $reason";
1948 if ( $protectDescription ) {
1949 $editComment .= " ($protectDescription)";
1952 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1955 # Insert a null revision
1956 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1957 $nullRevId = $nullRevision->insertOn( $dbw );
1959 $latest = $this->getLatest();
1960 # Update page record
1961 $dbw->update( 'page',
1963 'page_touched' => $dbw->timestamp(),
1964 'page_restrictions' => '',
1965 'page_latest' => $nullRevId
1966 ), array( /* WHERE */
1971 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1972 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1973 } else { # Protection of non-existing page (also known as "title protection")
1974 # Cascade protection is meaningless in this case
1977 if ( $limit['create'] != '' ) {
1978 $dbw->replace( 'protected_titles',
1979 array( array( 'pt_namespace', 'pt_title' ) ),
1981 'pt_namespace' => $this->mTitle
->getNamespace(),
1982 'pt_title' => $this->mTitle
->getDBkey(),
1983 'pt_create_perm' => $limit['create'],
1984 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1985 'pt_expiry' => $encodedExpiry['create'],
1986 'pt_user' => $user->getId(),
1987 'pt_reason' => $reason,
1991 $dbw->delete( 'protected_titles',
1993 'pt_namespace' => $this->mTitle
->getNamespace(),
1994 'pt_title' => $this->mTitle
->getDBkey()
2000 $this->mTitle
->flushRestrictions();
2002 if ( $logAction == 'unprotect' ) {
2003 $logParams = array();
2005 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2008 # Update the protection log
2009 $log = new LogPage( 'protect' );
2010 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2012 return Status
::newGood();
2016 * Take an array of page restrictions and flatten it to a string
2017 * suitable for insertion into the page_restrictions field.
2018 * @param $limit Array
2021 protected static function flattenRestrictions( $limit ) {
2022 if ( !is_array( $limit ) ) {
2023 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2029 foreach ( $limit as $action => $restrictions ) {
2030 if ( $restrictions != '' ) {
2031 $bits[] = "$action=$restrictions";
2035 return implode( ':', $bits );
2039 * Back-end article deletion
2040 * Deletes the article with database consistency, writes logs, purges caches
2042 * @param $reason string delete reason for deletion log
2043 * @param $suppress bitfield
2044 * Revision::DELETED_TEXT
2045 * Revision::DELETED_COMMENT
2046 * Revision::DELETED_USER
2047 * Revision::DELETED_RESTRICTED
2048 * @param $id int article ID
2049 * @param $commit boolean defaults to true, triggers transaction end
2050 * @param &$errors Array of errors to append to
2051 * @param $user User The relevant user
2052 * @return boolean true if successful
2054 public function doDeleteArticle(
2055 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2058 $user = is_null( $user ) ?
$wgUser : $user;
2060 wfDebug( __METHOD__
. "\n" );
2062 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2065 $dbw = wfGetDB( DB_MASTER
);
2066 $t = $this->mTitle
->getDBkey();
2067 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2069 if ( $t === '' ||
$id == 0 ) {
2073 // Bitfields to further suppress the content
2076 // This should be 15...
2077 $bitfield |
= Revision
::DELETED_TEXT
;
2078 $bitfield |
= Revision
::DELETED_COMMENT
;
2079 $bitfield |
= Revision
::DELETED_USER
;
2080 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2082 $bitfield = 'rev_deleted';
2086 // For now, shunt the revision data into the archive table.
2087 // Text is *not* removed from the text table; bulk storage
2088 // is left intact to avoid breaking block-compression or
2089 // immutable storage schemes.
2091 // For backwards compatibility, note that some older archive
2092 // table entries will have ar_text and ar_flags fields still.
2094 // In the future, we may keep revisions and mark them with
2095 // the rev_deleted field, which is reserved for this purpose.
2096 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2098 'ar_namespace' => 'page_namespace',
2099 'ar_title' => 'page_title',
2100 'ar_comment' => 'rev_comment',
2101 'ar_user' => 'rev_user',
2102 'ar_user_text' => 'rev_user_text',
2103 'ar_timestamp' => 'rev_timestamp',
2104 'ar_minor_edit' => 'rev_minor_edit',
2105 'ar_rev_id' => 'rev_id',
2106 'ar_parent_id' => 'rev_parent_id',
2107 'ar_text_id' => 'rev_text_id',
2108 'ar_text' => '\'\'', // Be explicit to appease
2109 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2110 'ar_len' => 'rev_len',
2111 'ar_page_id' => 'page_id',
2112 'ar_deleted' => $bitfield,
2113 'ar_sha1' => 'rev_content_model',
2114 'ar_content_format' => 'rev_content_format',
2115 'ar_content_format' => 'rev_sha1'
2118 'page_id = rev_page'
2122 # Now that it's safely backed up, delete it
2123 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2124 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2131 $this->doDeleteUpdates( $id );
2133 # Log the deletion, if the page was suppressed, log it at Oversight instead
2134 $logtype = $suppress ?
'suppress' : 'delete';
2136 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2137 $logEntry->setPerformer( $user );
2138 $logEntry->setTarget( $this->mTitle
);
2139 $logEntry->setComment( $reason );
2140 $logid = $logEntry->insert();
2141 $logEntry->publish( $logid );
2147 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2152 * Do some database updates after deletion
2154 * @param $id Int: page_id value of the page being deleted
2156 public function doDeleteUpdates( $id ) {
2157 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2159 $dbw = wfGetDB( DB_MASTER
);
2161 # Delete restrictions for it
2162 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2164 # Fix category table counts
2166 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2168 foreach ( $res as $row ) {
2169 $cats [] = $row->cl_to
;
2172 $this->updateCategoryCounts( array(), $cats );
2174 # If using cascading deletes, we can skip some explicit deletes
2175 if ( !$dbw->cascadingDeletes() ) {
2176 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2178 # Delete outgoing links
2179 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2180 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2181 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2182 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2183 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2184 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2185 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2186 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2187 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2190 # If using cleanup triggers, we can skip some manual deletes
2191 if ( !$dbw->cleanupTriggers() ) {
2192 # Clean up recentchanges entries...
2193 $dbw->delete( 'recentchanges',
2194 array( 'rc_type != ' . RC_LOG
,
2195 'rc_namespace' => $this->mTitle
->getNamespace(),
2196 'rc_title' => $this->mTitle
->getDBkey() ),
2198 $dbw->delete( 'recentchanges',
2199 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2204 self
::onArticleDelete( $this->mTitle
);
2206 # Clear the cached article id so the interface doesn't act like we exist
2207 $this->mTitle
->resetArticleID( 0 );
2211 * Roll back the most recent consecutive set of edits to a page
2212 * from the same user; fails if there are no eligible edits to
2213 * roll back to, e.g. user is the sole contributor. This function
2214 * performs permissions checks on $user, then calls commitRollback()
2215 * to do the dirty work
2217 * @todo: seperate the business/permission stuff out from backend code
2219 * @param $fromP String: Name of the user whose edits to rollback.
2220 * @param $summary String: Custom summary. Set to default summary if empty.
2221 * @param $token String: Rollback token.
2222 * @param $bot Boolean: If true, mark all reverted edits as bot.
2224 * @param $resultDetails Array: contains result-specific array of additional values
2225 * 'alreadyrolled' : 'current' (rev)
2226 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2228 * @param $user User The user performing the rollback
2229 * @return array of errors, each error formatted as
2230 * array(messagekey, param1, param2, ...).
2231 * On success, the array is empty. This array can also be passed to
2232 * OutputPage::showPermissionsErrorPage().
2234 public function doRollback(
2235 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2237 $resultDetails = null;
2240 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2241 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2242 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2244 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2245 $errors[] = array( 'sessionfailure' );
2248 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2249 $errors[] = array( 'actionthrottledtext' );
2252 # If there were errors, bail out now
2253 if ( !empty( $errors ) ) {
2257 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2261 * Backend implementation of doRollback(), please refer there for parameter
2262 * and return value documentation
2264 * NOTE: This function does NOT check ANY permissions, it just commits the
2265 * rollback to the DB. Therefore, you should only call this function direct-
2266 * ly if you want to use custom permissions checks. If you don't, use
2267 * doRollback() instead.
2268 * @param $fromP String: Name of the user whose edits to rollback.
2269 * @param $summary String: Custom summary. Set to default summary if empty.
2270 * @param $bot Boolean: If true, mark all reverted edits as bot.
2272 * @param $resultDetails Array: contains result-specific array of additional values
2273 * @param $guser User The user performing the rollback
2275 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2276 global $wgUseRCPatrol, $wgContLang;
2278 $dbw = wfGetDB( DB_MASTER
);
2280 if ( wfReadOnly() ) {
2281 return array( array( 'readonlytext' ) );
2284 # Get the last editor
2285 $current = Revision
::newFromTitle( $this->mTitle
);
2286 if ( is_null( $current ) ) {
2287 # Something wrong... no page?
2288 return array( array( 'notanarticle' ) );
2291 $from = str_replace( '_', ' ', $fromP );
2292 # User name given should match up with the top revision.
2293 # If the user was deleted then $from should be empty.
2294 if ( $from != $current->getUserText() ) {
2295 $resultDetails = array( 'current' => $current );
2296 return array( array( 'alreadyrolled',
2297 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2298 htmlspecialchars( $fromP ),
2299 htmlspecialchars( $current->getUserText() )
2303 # Get the last edit not by this guy...
2304 # Note: these may not be public values
2305 $user = intval( $current->getRawUser() );
2306 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2307 $s = $dbw->selectRow( 'revision',
2308 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2309 array( 'rev_page' => $current->getPage(),
2310 "rev_user != {$user} OR rev_user_text != {$user_text}"
2312 array( 'USE INDEX' => 'page_timestamp',
2313 'ORDER BY' => 'rev_timestamp DESC' )
2315 if ( $s === false ) {
2316 # No one else ever edited this page
2317 return array( array( 'cantrollback' ) );
2318 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2319 # Only admins can see this text
2320 return array( array( 'notvisiblerev' ) );
2324 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2325 # Mark all reverted edits as bot
2329 if ( $wgUseRCPatrol ) {
2330 # Mark all reverted edits as patrolled
2331 $set['rc_patrolled'] = 1;
2334 if ( count( $set ) ) {
2335 $dbw->update( 'recentchanges', $set,
2337 'rc_cur_id' => $current->getPage(),
2338 'rc_user_text' => $current->getUserText(),
2339 "rc_timestamp > '{$s->rev_timestamp}'",
2344 # Generate the edit summary if necessary
2345 $target = Revision
::newFromId( $s->rev_id
);
2346 if ( empty( $summary ) ) {
2347 if ( $from == '' ) { // no public user name
2348 $summary = wfMsgForContent( 'revertpage-nouser' );
2350 $summary = wfMsgForContent( 'revertpage' );
2354 # Allow the custom summary to use the same args as the default message
2356 $target->getUserText(), $from, $s->rev_id
,
2357 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2358 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2360 $summary = wfMsgReplaceArgs( $summary, $args );
2363 $flags = EDIT_UPDATE
;
2365 if ( $guser->isAllowed( 'minoredit' ) ) {
2366 $flags |
= EDIT_MINOR
;
2369 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2370 $flags |
= EDIT_FORCE_BOT
;
2373 # Actually store the edit
2374 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2375 if ( !empty( $status->value
['revision'] ) ) {
2376 $revId = $status->value
['revision']->getId();
2381 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2383 $resultDetails = array(
2384 'summary' => $summary,
2385 'current' => $current,
2386 'target' => $target,
2394 * The onArticle*() functions are supposed to be a kind of hooks
2395 * which should be called whenever any of the specified actions
2398 * This is a good place to put code to clear caches, for instance.
2400 * This is called on page move and undelete, as well as edit
2402 * @param $title Title object
2404 public static function onArticleCreate( $title ) {
2405 # Update existence markers on article/talk tabs...
2406 if ( $title->isTalkPage() ) {
2407 $other = $title->getSubjectPage();
2409 $other = $title->getTalkPage();
2412 $other->invalidateCache();
2413 $other->purgeSquid();
2415 $title->touchLinks();
2416 $title->purgeSquid();
2417 $title->deleteTitleProtection();
2421 * Clears caches when article is deleted
2423 * @param $title Title
2425 public static function onArticleDelete( $title ) {
2426 # Update existence markers on article/talk tabs...
2427 if ( $title->isTalkPage() ) {
2428 $other = $title->getSubjectPage();
2430 $other = $title->getTalkPage();
2433 $other->invalidateCache();
2434 $other->purgeSquid();
2436 $title->touchLinks();
2437 $title->purgeSquid();
2440 HTMLFileCache
::clearFileCache( $title );
2443 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2444 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2448 if ( $title->getNamespace() == NS_FILE
) {
2449 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2450 $update->doUpdate();
2454 if ( $title->getNamespace() == NS_USER_TALK
) {
2455 $user = User
::newFromName( $title->getText(), false );
2457 $user->setNewtalk( false );
2462 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2466 * Purge caches on page update etc
2468 * @param $title Title object
2469 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2471 public static function onArticleEdit( $title ) {
2472 // Invalidate caches of articles which include this page
2473 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2476 // Invalidate the caches of all pages which redirect here
2477 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2479 # Purge squid for this page only
2480 $title->purgeSquid();
2482 # Clear file cache for this page only
2483 HTMLFileCache
::clearFileCache( $title );
2489 * Returns a list of hidden categories this page is a member of.
2490 * Uses the page_props and categorylinks tables.
2492 * @return Array of Title objects
2494 public function getHiddenCategories() {
2496 $id = $this->mTitle
->getArticleID();
2502 $dbr = wfGetDB( DB_SLAVE
);
2503 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2505 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2506 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2509 if ( $res !== false ) {
2510 foreach ( $res as $row ) {
2511 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2519 * Return an applicable autosummary if one exists for the given edit.
2520 * @param $oldtext String: the previous text of the page.
2521 * @param $newtext String: The submitted text of the page.
2522 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2523 * @return string An appropriate autosummary, or an empty string.
2524 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
2526 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2527 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2529 $handler = ContentHandler
::getForModelName( CONTENT_MODEL_WIKITEXT
);
2530 $oldContent = $handler->unserialize( $oldtext );
2531 $newContent = $handler->unserialize( $newtext );
2533 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2537 * Auto-generates a deletion reason
2539 * @param &$hasHistory Boolean: whether the page has a history
2540 * @return mixed String containing deletion reason or empty string, or boolean false
2541 * if no revision occurred
2542 * @deprecated since 1.20, use ContentHandler::getAutoDeleteReason() instead
2544 public function getAutoDeleteReason( &$hasHistory ) {
2545 #NOTE: stub for backwards-compatibility.
2547 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2548 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2552 * Update all the appropriate counts in the category table, given that
2553 * we've added the categories $added and deleted the categories $deleted.
2555 * @param $added array The names of categories that were added
2556 * @param $deleted array The names of categories that were deleted
2558 public function updateCategoryCounts( $added, $deleted ) {
2559 $ns = $this->mTitle
->getNamespace();
2560 $dbw = wfGetDB( DB_MASTER
);
2562 # First make sure the rows exist. If one of the "deleted" ones didn't
2563 # exist, we might legitimately not create it, but it's simpler to just
2564 # create it and then give it a negative value, since the value is bogus
2567 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2568 $insertCats = array_merge( $added, $deleted );
2569 if ( !$insertCats ) {
2570 # Okay, nothing to do
2574 $insertRows = array();
2576 foreach ( $insertCats as $cat ) {
2577 $insertRows[] = array(
2578 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2582 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2584 $addFields = array( 'cat_pages = cat_pages + 1' );
2585 $removeFields = array( 'cat_pages = cat_pages - 1' );
2587 if ( $ns == NS_CATEGORY
) {
2588 $addFields[] = 'cat_subcats = cat_subcats + 1';
2589 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2590 } elseif ( $ns == NS_FILE
) {
2591 $addFields[] = 'cat_files = cat_files + 1';
2592 $removeFields[] = 'cat_files = cat_files - 1';
2599 array( 'cat_title' => $added ),
2608 array( 'cat_title' => $deleted ),
2615 * Updates cascading protections
2617 * @param $parserOutput ParserOutput object for the current version
2619 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2620 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2624 // templatelinks table may have become out of sync,
2625 // especially if using variable-based transclusions.
2626 // For paranoia, check if things have changed and if
2627 // so apply updates to the database. This will ensure
2628 // that cascaded protections apply as soon as the changes
2631 # Get templates from templatelinks
2632 $id = $this->mTitle
->getArticleID();
2634 $tlTemplates = array();
2636 $dbr = wfGetDB( DB_SLAVE
);
2637 $res = $dbr->select( array( 'templatelinks' ),
2638 array( 'tl_namespace', 'tl_title' ),
2639 array( 'tl_from' => $id ),
2643 foreach ( $res as $row ) {
2644 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2647 # Get templates from parser output.
2648 $poTemplates = array();
2649 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2650 foreach ( $templates as $dbk => $id ) {
2651 $poTemplates["$ns:$dbk"] = true;
2656 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2658 if ( count( $templates_diff ) > 0 ) {
2659 # Whee, link updates time.
2660 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2666 * Return a list of templates used by this article.
2667 * Uses the templatelinks table
2669 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2670 * @return Array of Title objects
2672 public function getUsedTemplates() {
2673 return $this->mTitle
->getTemplateLinksFrom();
2677 * Perform article updates on a special page creation.
2679 * @param $rev Revision object
2681 * @todo This is a shitty interface function. Kill it and replace the
2682 * other shitty functions like doEditUpdates and such so it's not needed
2684 * @deprecated since 1.18, use doEditUpdates()
2686 public function createUpdates( $rev ) {
2687 wfDeprecated( __METHOD__
, '1.18' );
2689 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2693 * This function is called right before saving the wikitext,
2694 * so we can do things like signatures and links-in-context.
2696 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2697 * @param $text String article contents
2698 * @param $user User object: user doing the edit
2699 * @param $popts ParserOptions object: parser options, default options for
2700 * the user loaded if null given
2701 * @return string article contents with altered wikitext markup (signatures
2702 * converted, {{subst:}}, templates, etc.)
2704 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2705 global $wgParser, $wgUser;
2707 wfDeprecated( __METHOD__
, '1.19' );
2709 $user = is_null( $user ) ?
$wgUser : $user;
2711 if ( $popts === null ) {
2712 $popts = ParserOptions
::newFromUser( $user );
2715 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2719 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2721 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2724 public function isBigDeletion() {
2725 wfDeprecated( __METHOD__
, '1.19' );
2726 return $this->mTitle
->isBigDeletion();
2730 * Get the approximate revision count of this page.
2732 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2735 public function estimateRevisionCount() {
2736 wfDeprecated( __METHOD__
, '1.19' );
2737 return $this->mTitle
->estimateRevisionCount();
2741 * Update the article's restriction field, and leave a log entry.
2743 * @deprecated since 1.19
2744 * @param $limit Array: set of restriction keys
2745 * @param $reason String
2746 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2747 * @param $expiry Array: per restriction type expiration
2748 * @param $user User The user updating the restrictions
2749 * @return bool true on success
2751 public function updateRestrictions(
2752 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2756 $user = is_null( $user ) ?
$wgUser : $user;
2758 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2762 * @deprecated since 1.18
2764 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2765 wfDeprecated( __METHOD__
, '1.18' );
2767 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2771 * @deprecated since 1.18
2773 public function viewUpdates() {
2774 wfDeprecated( __METHOD__
, '1.18' );
2776 return $this->doViewUpdates( $wgUser );
2780 * @deprecated since 1.18
2782 public function useParserCache( $oldid ) {
2783 wfDeprecated( __METHOD__
, '1.18' );
2785 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2789 class PoolWorkArticleView
extends PoolCounterWork
{
2807 * @var ParserOptions
2809 private $parserOptions;
2817 * @var ParserOutput|false
2819 private $parserOutput = false;
2824 private $isDirty = false;
2829 private $error = false;
2835 * @param $revid Integer: ID of the revision being parsed
2836 * @param $useParserCache Boolean: whether to use the parser cache
2837 * @param $parserOptions parserOptions to use for the parse operation
2838 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
2840 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
2841 if ( is_string($content) ) { #BC: old style call
2842 $modelName = $page->getRevision()->getContentModelName();
2843 $format = $page->getRevision()->getContentFormat();
2844 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelName, $format );
2847 $this->page
= $page;
2848 $this->revid
= $revid;
2849 $this->cacheable
= $useParserCache;
2850 $this->parserOptions
= $parserOptions;
2851 $this->content
= $content;
2852 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2853 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2857 * Get the ParserOutput from this object, or false in case of failure
2859 * @return ParserOutput
2861 public function getParserOutput() {
2862 return $this->parserOutput
;
2866 * Get whether the ParserOutput is a dirty one (i.e. expired)
2870 public function getIsDirty() {
2871 return $this->isDirty
;
2875 * Get a Status object in case of error or false otherwise
2877 * @return Status|false
2879 public function getError() {
2880 return $this->error
;
2887 global $wgParser, $wgUseFileCache;
2889 $isCurrent = $this->revid
=== $this->page
->getLatest();
2891 if ( $this->content
!== null ) {
2892 $content = $this->content
;
2893 } elseif ( $isCurrent ) {
2894 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
2896 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2897 if ( $rev === null ) {
2900 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
2904 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
2909 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2910 $this->page
->getTitle()->getPrefixedDBkey() ) );
2913 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2914 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2917 // Make sure file cache is not used on uncacheable content.
2918 // Output that has magic words in it can still use the parser cache
2919 // (if enabled), though it will generally expire sooner.
2920 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2921 $wgUseFileCache = false;
2925 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2934 function getCachedWork() {
2935 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2937 if ( $this->parserOutput
=== false ) {
2938 wfDebug( __METHOD__
. ": parser cache miss\n" );
2941 wfDebug( __METHOD__
. ": parser cache hit\n" );
2949 function fallback() {
2950 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2952 if ( $this->parserOutput
=== false ) {
2953 wfDebugLog( 'dirty', "dirty missing\n" );
2954 wfDebug( __METHOD__
. ": no dirty cache\n" );
2957 wfDebug( __METHOD__
. ": sending dirty output\n" );
2958 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2959 $this->isDirty
= true;
2965 * @param $status Status
2967 function error( $status ) {
2968 $this->error
= $status;