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
{
16 // doDeleteArticleReal() return values. Values less than zero indicate fatal errors,
17 // values greater than zero indicate that there were problems not resulting in page
21 * Delete operation aborted by hook
23 const DELETE_HOOK_ABORTED
= -1;
28 const DELETE_SUCCESS
= 0;
33 const DELETE_NO_PAGE
= 1;
36 * No revisions found to delete
38 const DELETE_NO_REVISIONS
= 2;
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
51 public $mPreparedEdit = false; // !< Array
57 protected $mRedirectTarget = null;
62 protected $mLastRevision = null;
65 * @var string; timestamp of the current revision or empty string if not loaded
67 protected $mTimestamp = '';
72 protected $mTouched = '19700101000000';
77 protected $mCounter = null;
80 * Constructor and clear the article
81 * @param $title Title Reference to a Title object.
83 public function __construct( Title
$title ) {
84 $this->mTitle
= $title;
88 * Create a WikiPage object of the appropriate class for the given title.
91 * @return WikiPage object of the appropriate type
93 public static function factory( Title
$title ) {
94 $ns = $title->getNamespace();
96 if ( $ns == NS_MEDIA
) {
97 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
98 } elseif ( $ns < 0 ) {
99 throw new MWException( "Invalid or virtual namespace $ns given." );
104 $page = new WikiFilePage( $title );
107 $page = new WikiCategoryPage( $title );
110 $page = new WikiPage( $title );
117 * Constructor from a page id
119 * @param $id Int article ID to load
121 * @return WikiPage|null
123 public static function newFromID( $id ) {
124 $dbr = wfGetDB( DB_SLAVE
);
125 $row = $dbr->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
129 return self
::newFromRow( $row );
133 * Constructor from a database row
136 * @param $row object: database row containing at least fields returned
140 public static function newFromRow( $row ) {
141 $page = self
::factory( Title
::newFromRow( $row ) );
142 $page->loadFromRow( $row );
147 * Returns overrides for action handlers.
148 * Classes listed here will be used instead of the default one when
149 * (and only when) $wgActions[$action] === true. This allows subclasses
150 * to override the default behavior.
152 * @todo: move this UI stuff somewhere else
156 public function getActionOverrides() {
157 $content_handler = $this->getContentHandler();
158 return $content_handler->getActionOverrides();
162 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
164 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
166 * @return ContentHandler
170 public function getContentHandler() {
171 return ContentHandler
::getForModelID( $this->getContentModel() );
175 * Get the title object of the article
176 * @return Title object of this page
178 public function getTitle() {
179 return $this->mTitle
;
185 public function clear() {
186 $this->mDataLoaded
= false;
188 $this->mCounter
= null;
189 $this->mRedirectTarget
= null; # Title object if set
190 $this->mLastRevision
= null; # Latest revision
191 $this->mTouched
= '19700101000000';
192 $this->mTimestamp
= '';
193 $this->mIsRedirect
= false;
194 $this->mLatest
= false;
195 $this->mPreparedEdit
= false;
199 * Return the list of revision fields that should be selected to create
204 public static function selectFields() {
205 global $wgContentHandlerUseDB;
221 if ( $wgContentHandlerUseDB ) {
222 $fields[] = 'page_content_model';
229 * Fetch a page record with the given conditions
230 * @param $dbr DatabaseBase object
231 * @param $conditions Array
232 * @return mixed Database result resource, or false on failure
234 protected function pageData( $dbr, $conditions ) {
235 $fields = self
::selectFields();
237 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
239 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
241 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
247 * Fetch a page record matching the Title object's namespace and title
248 * using a sanitized title string
250 * @param $dbr DatabaseBase object
251 * @param $title Title object
252 * @return mixed Database result resource, or false on failure
254 public function pageDataFromTitle( $dbr, $title ) {
255 return $this->pageData( $dbr, array(
256 'page_namespace' => $title->getNamespace(),
257 'page_title' => $title->getDBkey() ) );
261 * Fetch a page record matching the requested ID
263 * @param $dbr DatabaseBase
265 * @return mixed Database result resource, or false on failure
267 public function pageDataFromId( $dbr, $id ) {
268 return $this->pageData( $dbr, array( 'page_id' => $id ) );
272 * Set the general counter, title etc data loaded from
275 * @param $data Object|String One of the following:
276 * A DB query result object or...
277 * "fromdb" to get from a slave DB or...
278 * "fromdbmaster" to get from the master DB
281 public function loadPageData( $data = 'fromdb' ) {
282 if ( $data === 'fromdbmaster' ) {
283 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
284 } elseif ( $data === 'fromdb' ) { // slave
285 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
286 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
287 # Note that DB also stores the master position in the session and checks it.
288 $touched = $this->getCachedLastEditTime();
289 if ( $touched ) { // key set
290 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
291 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
296 $this->loadFromRow( $data );
300 * Load the object from a database row
303 * @param $data object: database row containing at least fields returned
306 public function loadFromRow( $data ) {
307 $lc = LinkCache
::singleton();
310 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
312 $this->mTitle
->loadFromRow( $data );
314 # Old-fashioned restrictions
315 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
317 $this->mCounter
= intval( $data->page_counter
);
318 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
319 $this->mIsRedirect
= intval( $data->page_is_redirect
);
320 $this->mLatest
= intval( $data->page_latest
);
322 $lc->addBadLinkObj( $this->mTitle
);
324 $this->mTitle
->loadFromRow( false );
327 $this->mDataLoaded
= true;
331 * @return int Page ID
333 public function getId() {
334 return $this->mTitle
->getArticleID();
338 * @return bool Whether or not the page exists in the database
340 public function exists() {
341 return $this->mTitle
->exists();
345 * Check if this page is something we're going to be showing
346 * some sort of sensible content for. If we return false, page
347 * views (plain action=view) will return an HTTP 404 response,
348 * so spiders and robots can know they're following a bad link.
352 public function hasViewableContent() {
353 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
357 * @return int The view count for the page
359 public function getCount() {
360 if ( !$this->mDataLoaded
) {
361 $this->loadPageData();
364 return $this->mCounter
;
368 * Tests if the article text represents a redirect
370 * @param $text mixed string containing article contents, or boolean
373 public function isRedirect( $text = false ) {
374 if ( $text === false ) $content = $this->getContent();
375 else $content = ContentHandler
::makeContent( $text, $this->mTitle
); # TODO: allow model and format to be provided; or better, expect a Content object
378 if ( empty( $content ) ) return false;
379 else return $content->isRedirect();
383 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
385 * Will use the revisions actual content model if the page exists,
386 * and the page's default if the page doesn't exist yet.
392 public function getContentModel() {
393 if ( $this->exists() ) {
394 # look at the revision's actual content model
395 $rev = $this->getRevision();
397 if ( $rev !== null ) {
398 return $rev->getContentModel();
400 wfWarn( "Page exists but has no revision!" );
404 # use the default model for this page
405 return $this->mTitle
->getContentModel();
409 * Loads page_touched and returns a value indicating if it should be used
410 * @return boolean true if not a redirect
412 public function checkTouched() {
413 if ( !$this->mDataLoaded
) {
414 $this->loadPageData();
416 return !$this->mIsRedirect
;
420 * Get the page_touched field
421 * @return string containing GMT timestamp
423 public function getTouched() {
424 if ( !$this->mDataLoaded
) {
425 $this->loadPageData();
427 return $this->mTouched
;
431 * Get the page_latest field
432 * @return integer rev_id of current revision
434 public function getLatest() {
435 if ( !$this->mDataLoaded
) {
436 $this->loadPageData();
438 return (int)$this->mLatest
;
442 * Loads everything except the text
443 * This isn't necessary for all uses, so it's only done if needed.
445 protected function loadLastEdit() {
446 if ( $this->mLastRevision
!== null ) {
447 return; // already loaded
450 $latest = $this->getLatest();
452 return; // page doesn't exist or is missing page_latest info
455 $revision = Revision
::newFromPageId( $this->getId(), $latest );
456 if ( $revision ) { // sanity
457 $this->setLastEdit( $revision );
462 * Set the latest revision
464 protected function setLastEdit( Revision
$revision ) {
465 $this->mLastRevision
= $revision;
466 $this->mTimestamp
= $revision->getTimestamp();
470 * Get the latest revision
471 * @return Revision|null
473 public function getRevision() {
474 $this->loadLastEdit();
475 if ( $this->mLastRevision
) {
476 return $this->mLastRevision
;
482 * Get the content of the current revision. No side-effects...
484 * @param $audience Integer: one of:
485 * Revision::FOR_PUBLIC to be displayed to all users
486 * Revision::FOR_THIS_USER to be displayed to $wgUser
487 * Revision::RAW get the text regardless of permissions
488 * @return Content|null The content of the current revision
492 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
493 $this->loadLastEdit();
494 if ( $this->mLastRevision
) {
495 return $this->mLastRevision
->getContent( $audience );
501 * Get the text of the current revision. No side-effects...
503 * @param $audience Integer: one of:
504 * Revision::FOR_PUBLIC to be displayed to all users
505 * Revision::FOR_THIS_USER to be displayed to $wgUser
506 * Revision::RAW get the text regardless of permissions
507 * @return String|false The text of the current revision
508 * @deprecated as of 1.WD, getContent() should be used instead.
510 public function getText( $audience = Revision
::FOR_PUBLIC
) { #@todo: deprecated, replace usage!
511 wfDeprecated( __METHOD__
, '1.WD' );
513 $this->loadLastEdit();
514 if ( $this->mLastRevision
) {
515 return $this->mLastRevision
->getText( $audience );
521 * Get the text of the current revision. No side-effects...
523 * @return String|bool The text of the current revision. False on failure
524 * @deprecated as of 1.WD, getContent() should be used instead.
526 public function getRawText() { #@todo: deprecated, replace usage!
527 wfDeprecated( __METHOD__
, '1.WD' );
529 return $this->getText( Revision
::RAW
);
533 * @return string MW timestamp of last article revision
535 public function getTimestamp() {
536 // Check if the field has been filled by WikiPage::setTimestamp()
537 if ( !$this->mTimestamp
) {
538 $this->loadLastEdit();
541 return wfTimestamp( TS_MW
, $this->mTimestamp
);
545 * Set the page timestamp (use only to avoid DB queries)
546 * @param $ts string MW timestamp of last article revision
549 public function setTimestamp( $ts ) {
550 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
554 * @param $audience Integer: one of:
555 * Revision::FOR_PUBLIC to be displayed to all users
556 * Revision::FOR_THIS_USER to be displayed to $wgUser
557 * Revision::RAW get the text regardless of permissions
558 * @return int user ID for the user that made the last article revision
560 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
561 $this->loadLastEdit();
562 if ( $this->mLastRevision
) {
563 return $this->mLastRevision
->getUser( $audience );
570 * @param $audience Integer: one of:
571 * Revision::FOR_PUBLIC to be displayed to all users
572 * Revision::FOR_THIS_USER to be displayed to $wgUser
573 * Revision::RAW get the text regardless of permissions
574 * @return string username of the user that made the last article revision
576 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
577 $this->loadLastEdit();
578 if ( $this->mLastRevision
) {
579 return $this->mLastRevision
->getUserText( $audience );
586 * @param $audience Integer: one of:
587 * Revision::FOR_PUBLIC to be displayed to all users
588 * Revision::FOR_THIS_USER to be displayed to $wgUser
589 * Revision::RAW get the text regardless of permissions
590 * @return string Comment stored for the last article revision
592 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
593 $this->loadLastEdit();
594 if ( $this->mLastRevision
) {
595 return $this->mLastRevision
->getComment( $audience );
602 * Returns true if last revision was marked as "minor edit"
604 * @return boolean Minor edit indicator for the last article revision.
606 public function getMinorEdit() {
607 $this->loadLastEdit();
608 if ( $this->mLastRevision
) {
609 return $this->mLastRevision
->isMinor();
616 * Get the cached timestamp for the last time the page changed.
617 * This is only used to help handle slave lag by comparing to page_touched.
618 * @return string MW timestamp
620 protected function getCachedLastEditTime() {
622 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
623 return $wgMemc->get( $key );
627 * Set the cached timestamp for the last time the page changed.
628 * This is only used to help handle slave lag by comparing to page_touched.
629 * @param $timestamp string
632 public function setCachedLastEditTime( $timestamp ) {
634 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
635 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
639 * Determine whether a page would be suitable for being counted as an
640 * article in the site_stats table based on the title & its content
642 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
643 * if false, the current database state will be used
646 public function isCountable( $editInfo = false ) {
647 global $wgArticleCountMethod;
649 if ( !$this->mTitle
->isContentPage() ) {
654 $content = $editInfo->pstContent
;
656 $content = $this->getContent();
659 if ( !$content ||
$content->isRedirect( ) ) {
665 if ( $wgArticleCountMethod === 'link' ) {
666 # nasty special case to avoid re-parsing to detect links
669 // ParserOutput::getLinks() is a 2D array of page links, so
670 // to be really correct we would need to recurse in the array
671 // but the main array should only have items in it if there are
673 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
675 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
676 array( 'pl_from' => $this->getId() ), __METHOD__
);
680 return $content->isCountable( $hasLinks );
684 * If this page is a redirect, get its target
686 * The target will be fetched from the redirect table if possible.
687 * If this page doesn't have an entry there, call insertRedirect()
688 * @return Title|mixed object, or null if this page is not a redirect
690 public function getRedirectTarget() {
691 if ( !$this->mTitle
->isRedirect() ) {
695 if ( $this->mRedirectTarget
!== null ) {
696 return $this->mRedirectTarget
;
699 # Query the redirect table
700 $dbr = wfGetDB( DB_SLAVE
);
701 $row = $dbr->selectRow( 'redirect',
702 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
703 array( 'rd_from' => $this->getId() ),
707 // rd_fragment and rd_interwiki were added later, populate them if empty
708 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
709 return $this->mRedirectTarget
= Title
::makeTitle(
710 $row->rd_namespace
, $row->rd_title
,
711 $row->rd_fragment
, $row->rd_interwiki
);
714 # This page doesn't have an entry in the redirect table
715 return $this->mRedirectTarget
= $this->insertRedirect();
719 * Insert an entry for this page into the redirect table.
721 * Don't call this function directly unless you know what you're doing.
722 * @return Title object or null if not a redirect
724 public function insertRedirect() {
725 // recurse through to only get the final target
726 $content = $this->getContent();
727 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
731 $this->insertRedirectEntry( $retval );
736 * Insert or update the redirect table entry for this page to indicate
737 * it redirects to $rt .
738 * @param $rt Title redirect target
740 public function insertRedirectEntry( $rt ) {
741 $dbw = wfGetDB( DB_MASTER
);
742 $dbw->replace( 'redirect', array( 'rd_from' ),
744 'rd_from' => $this->getId(),
745 'rd_namespace' => $rt->getNamespace(),
746 'rd_title' => $rt->getDBkey(),
747 'rd_fragment' => $rt->getFragment(),
748 'rd_interwiki' => $rt->getInterwiki(),
755 * Get the Title object or URL this page redirects to
757 * @return mixed false, Title of in-wiki target, or string with URL
759 public function followRedirect() {
760 return $this->getRedirectURL( $this->getRedirectTarget() );
764 * Get the Title object or URL to use for a redirect. We use Title
765 * objects for same-wiki, non-special redirects and URLs for everything
767 * @param $rt Title Redirect target
768 * @return mixed false, Title object of local target, or string with URL
770 public function getRedirectURL( $rt ) {
775 if ( $rt->isExternal() ) {
776 if ( $rt->isLocal() ) {
777 // Offsite wikis need an HTTP redirect.
779 // This can be hard to reverse and may produce loops,
780 // so they may be disabled in the site configuration.
781 $source = $this->mTitle
->getFullURL( 'redirect=no' );
782 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
784 // External pages pages without "local" bit set are not valid
790 if ( $rt->isSpecialPage() ) {
791 // Gotta handle redirects to special pages differently:
792 // Fill the HTTP response "Location" header and ignore
793 // the rest of the page we're on.
795 // Some pages are not valid targets
796 if ( $rt->isValidRedirectTarget() ) {
797 return $rt->getFullURL();
807 * Get a list of users who have edited this article, not including the user who made
808 * the most recent revision, which you can get from $article->getUser() if you want it
809 * @return UserArrayFromResult
811 public function getContributors() {
812 # @todo FIXME: This is expensive; cache this info somewhere.
814 $dbr = wfGetDB( DB_SLAVE
);
816 if ( $dbr->implicitGroupby() ) {
817 $realNameField = 'user_real_name';
819 $realNameField = 'MIN(user_real_name) AS user_real_name';
822 $tables = array( 'revision', 'user' );
825 'rev_user as user_id',
826 'rev_user_text AS user_name',
828 'MAX(rev_timestamp) AS timestamp',
831 $conds = array( 'rev_page' => $this->getId() );
833 // The user who made the top revision gets credited as "this page was last edited by
834 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
835 $user = $this->getUser();
837 $conds[] = "rev_user != $user";
839 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
842 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
845 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
849 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
850 'ORDER BY' => 'timestamp DESC',
853 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
854 return new UserArrayFromResult( $res );
858 * Get the last N authors
859 * @param $num Integer: number of revisions to get
860 * @param $revLatest String: the latest rev_id, selected from the master (optional)
861 * @return array Array of authors, duplicates not removed
863 public function getLastNAuthors( $num, $revLatest = 0 ) {
864 wfProfileIn( __METHOD__
);
865 // First try the slave
866 // If that doesn't have the latest revision, try the master
868 $db = wfGetDB( DB_SLAVE
);
871 $res = $db->select( array( 'page', 'revision' ),
872 array( 'rev_id', 'rev_user_text' ),
874 'page_namespace' => $this->mTitle
->getNamespace(),
875 'page_title' => $this->mTitle
->getDBkey(),
879 'ORDER BY' => 'rev_timestamp DESC',
885 wfProfileOut( __METHOD__
);
889 $row = $db->fetchObject( $res );
891 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
892 $db = wfGetDB( DB_MASTER
);
897 } while ( $continue );
899 $authors = array( $row->rev_user_text
);
901 foreach ( $res as $row ) {
902 $authors[] = $row->rev_user_text
;
905 wfProfileOut( __METHOD__
);
910 * Should the parser cache be used?
912 * @param $parserOptions ParserOptions to check
916 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
917 global $wgEnableParserCache;
919 return $wgEnableParserCache
920 && $parserOptions->getStubThreshold() == 0
921 && $this->mTitle
->exists()
922 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
923 && $this->getContentHandler()->isParserCacheSupported();
927 * Get a ParserOutput for the given ParserOptions and revision ID.
928 * The parser cache will be used if possible.
931 * @param $parserOptions ParserOptions to use for the parse operation
932 * @param $oldid Revision ID to get the text from, passing null or 0 will
933 * get the current revision (default value)
934 * @param $context IContextSource context for parsing
936 * @return ParserOutput or false if the revision was not found
938 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null, IContextSource
$context = null ) {
939 wfProfileIn( __METHOD__
);
941 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
942 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
943 if ( $parserOptions->getStubThreshold() ) {
944 wfIncrStats( 'pcache_miss_stub' );
947 if ( $useParserCache ) {
948 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
949 if ( $parserOutput !== false ) {
950 wfProfileOut( __METHOD__
);
951 return $parserOutput;
955 if ( $oldid === null ||
$oldid === 0 ) {
956 $oldid = $this->getLatest();
959 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache, null, $context );
962 wfProfileOut( __METHOD__
);
964 return $pool->getParserOutput();
968 * Do standard deferred updates after page view
969 * @param $user User The relevant user
971 public function doViewUpdates( User
$user ) {
972 global $wgDisableCounters;
973 if ( wfReadOnly() ) {
977 # Don't update page view counters on views from bot users (bug 14044)
978 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
979 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
980 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
983 # Update newtalk / watchlist notification status
984 $user->clearNotification( $this->mTitle
);
988 * Perform the actions of a page purging
991 public function doPurge() {
994 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
998 // Invalidate the cache
999 $this->mTitle
->invalidateCache();
1002 if ( $wgUseSquid ) {
1003 // Commit the transaction before the purge is sent
1004 $dbw = wfGetDB( DB_MASTER
);
1005 $dbw->commit( __METHOD__
);
1008 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1009 $update->doUpdate();
1012 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1013 if ( $this->mTitle
->exists() ) {
1014 $text = ContentHandler
::getContentText( $this->getContent() );
1019 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1025 * Insert a new empty page record for this article.
1026 * This *must* be followed up by creating a revision
1027 * and running $this->updateRevisionOn( ... );
1028 * or else the record will be left in a funky state.
1029 * Best if all done inside a transaction.
1031 * @param $dbw DatabaseBase
1032 * @return int The newly created page_id key, or false if the title already existed
1034 public function insertOn( $dbw ) {
1035 wfProfileIn( __METHOD__
);
1037 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1038 $dbw->insert( 'page', array(
1039 'page_id' => $page_id,
1040 'page_namespace' => $this->mTitle
->getNamespace(),
1041 'page_title' => $this->mTitle
->getDBkey(),
1042 'page_counter' => 0,
1043 'page_restrictions' => '',
1044 'page_is_redirect' => 0, # Will set this shortly...
1046 'page_random' => wfRandom(),
1047 'page_touched' => $dbw->timestamp(),
1048 'page_latest' => 0, # Fill this in shortly...
1049 'page_len' => 0, # Fill this in shortly...
1050 ), __METHOD__
, 'IGNORE' );
1052 $affected = $dbw->affectedRows();
1055 $newid = $dbw->insertId();
1056 $this->mTitle
->resetArticleID( $newid );
1058 wfProfileOut( __METHOD__
);
1060 return $affected ?
$newid : false;
1064 * Update the page record to point to a newly saved revision.
1066 * @param $dbw DatabaseBase: object
1067 * @param $revision Revision: For ID number, and text used to set
1068 * length and redirect status fields
1069 * @param $lastRevision Integer: if given, will not overwrite the page field
1070 * when different from the currently set value.
1071 * Giving 0 indicates the new page flag should be set
1073 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1074 * removing rows in redirect table.
1075 * @return bool true on success, false on failure
1078 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1079 global $wgContentHandlerUseDB;
1081 wfProfileIn( __METHOD__
);
1083 $content = $revision->getContent();
1084 $len = $content->getSize();
1085 $rt = $content->getUltimateRedirectTarget();
1087 $conditions = array( 'page_id' => $this->getId() );
1089 if ( !is_null( $lastRevision ) ) {
1090 # An extra check against threads stepping on each other
1091 $conditions['page_latest'] = $lastRevision;
1094 $now = wfTimestampNow();
1095 $row = array( /* SET */
1096 'page_latest' => $revision->getId(),
1097 'page_touched' => $dbw->timestamp( $now ),
1098 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1099 'page_is_redirect' => $rt !== null ?
1 : 0,
1103 if ( $wgContentHandlerUseDB ) {
1104 $row[ 'page_content_model' ] = $revision->getContentModel();
1107 $dbw->update( 'page',
1112 $result = $dbw->affectedRows() != 0;
1114 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1115 $this->setLastEdit( $revision );
1116 $this->setCachedLastEditTime( $now );
1117 $this->mLatest
= $revision->getId();
1118 $this->mIsRedirect
= (bool)$rt;
1119 # Update the LinkCache.
1120 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1123 wfProfileOut( __METHOD__
);
1128 * Add row to the redirect table if this is a redirect, remove otherwise.
1130 * @param $dbw DatabaseBase
1131 * @param $redirectTitle Title object pointing to the redirect target,
1132 * or NULL if this is not a redirect
1133 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1134 * removing rows in redirect table.
1135 * @return bool true on success, false on failure
1138 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1139 // Always update redirects (target link might have changed)
1140 // Update/Insert if we don't know if the last revision was a redirect or not
1141 // Delete if changing from redirect to non-redirect
1142 $isRedirect = !is_null( $redirectTitle );
1144 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1148 wfProfileIn( __METHOD__
);
1149 if ( $isRedirect ) {
1150 $this->insertRedirectEntry( $redirectTitle );
1152 // This is not a redirect, remove row from redirect table
1153 $where = array( 'rd_from' => $this->getId() );
1154 $dbw->delete( 'redirect', $where, __METHOD__
);
1157 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1158 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1160 wfProfileOut( __METHOD__
);
1162 return ( $dbw->affectedRows() != 0 );
1166 * If the given revision is newer than the currently set page_latest,
1167 * update the page record. Otherwise, do nothing.
1169 * @param $dbw DatabaseBase object
1170 * @param $revision Revision object
1173 public function updateIfNewerOn( $dbw, $revision ) {
1174 wfProfileIn( __METHOD__
);
1176 $row = $dbw->selectRow(
1177 array( 'revision', 'page' ),
1178 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1180 'page_id' => $this->getId(),
1181 'page_latest=rev_id' ),
1185 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1186 wfProfileOut( __METHOD__
);
1189 $prev = $row->rev_id
;
1190 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1192 # No or missing previous revision; mark the page as new
1194 $lastRevIsRedirect = null;
1197 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1199 wfProfileOut( __METHOD__
);
1204 * Get the text that needs to be saved in order to undo all revisions
1205 * between $undo and $undoafter. Revisions must belong to the same page,
1206 * must exist and must not be deleted
1207 * @param $undo Revision
1208 * @param $undoafter Revision Must be an earlier revision than $undo
1209 * @return mixed string on success, false on failure
1210 * @deprecated since 1.WD: use ContentHandler::getUndoContent() instead.
1212 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1213 wfDeprecated( __METHOD__
, '1.WD' );
1215 $this->loadLastEdit();
1217 if ( $this->mLastRevision
) {
1218 if ( is_null( $undoafter ) ) {
1219 $undoafter = $undo->getPrevious();
1222 $handler = $this->getContentHandler();
1223 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1228 return ContentHandler
::getContentText( $undone );
1236 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1237 * @param $text String: new text of the section
1238 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1239 * @param $edittime String: revision timestamp or null to use the current revision
1240 * @return String new complete article text, or null if error
1242 * @deprecated since 1.WD, use replaceSectionContent() instead
1244 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1245 wfDeprecated( __METHOD__
, '1.WD' );
1247 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1249 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1251 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1255 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1256 * @param $content Content: new content of the section
1257 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1258 * @param $edittime String: revision timestamp or null to use the current revision
1260 * @return Content new complete article content, or null if error
1264 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1265 wfProfileIn( __METHOD__
);
1267 if ( strval( $section ) == '' ) {
1268 // Whole-page edit; let the whole text through
1269 $newContent = $sectionContent;
1271 // Bug 30711: always use current version when adding a new section
1272 if ( is_null( $edittime ) ||
$section == 'new' ) {
1273 $oldContent = $this->getContent();
1274 if ( ! $oldContent ) {
1275 wfDebug( __METHOD__
. ": no page text\n" );
1276 wfProfileOut( __METHOD__
);
1280 $dbw = wfGetDB( DB_MASTER
);
1281 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1284 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1285 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1286 wfProfileOut( __METHOD__
);
1290 $oldContent = $rev->getContent();
1293 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1296 wfProfileOut( __METHOD__
);
1301 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1303 * @return Int updated $flags
1305 function checkFlags( $flags ) {
1306 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1307 if ( $this->mTitle
->getArticleID() ) {
1308 $flags |
= EDIT_UPDATE
;
1318 * Change an existing article or create a new article. Updates RC and all necessary caches,
1319 * optionally via the deferred update array.
1321 * @param $text String: new text
1322 * @param $summary String: edit summary
1323 * @param $flags Integer bitfield:
1325 * Article is known or assumed to be non-existent, create a new one
1327 * Article is known or assumed to be pre-existing, update it
1329 * Mark this edit minor, if the user is allowed to do so
1331 * Do not log the change in recentchanges
1333 * Mark the edit a "bot" edit regardless of user rights
1334 * EDIT_DEFER_UPDATES
1335 * Defer some of the updates until the end of index.php
1337 * Fill in blank summaries with generated text where possible
1339 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1340 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1341 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1342 * edit-already-exists error will be returned. These two conditions are also possible with
1343 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1345 * @param $baseRevId int the revision ID this edit was based off, if any
1346 * @param $user User the user doing the edit
1348 * @return Status object. Possible errors:
1349 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1350 * edit-gone-missing: In update mode, but the article didn't exist
1351 * edit-conflict: In update mode, the article changed unexpectedly
1352 * edit-no-change: Warning that the text was the same as before
1353 * edit-already-exists: In creation mode, but the article already exists
1355 * Extensions may define additional errors.
1357 * $return->value will contain an associative array with members as follows:
1358 * new: Boolean indicating if the function attempted to create a new article
1359 * revision: The revision object for the inserted revision, or null
1361 * Compatibility note: this function previously returned a boolean value indicating success/failure
1363 * @deprecated since 1.WD: use doEditContent() instead.
1365 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #@todo: use doEditContent() instead
1366 wfDeprecated( __METHOD__
, '1.WD' );
1368 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1370 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1374 * Change an existing article or create a new article. Updates RC and all necessary caches,
1375 * optionally via the deferred update array.
1377 * @param $content Content: new content
1378 * @param $summary String: edit summary
1379 * @param $flags Integer bitfield:
1381 * Article is known or assumed to be non-existent, create a new one
1383 * Article is known or assumed to be pre-existing, update it
1385 * Mark this edit minor, if the user is allowed to do so
1387 * Do not log the change in recentchanges
1389 * Mark the edit a "bot" edit regardless of user rights
1390 * EDIT_DEFER_UPDATES
1391 * Defer some of the updates until the end of index.php
1393 * Fill in blank summaries with generated text where possible
1395 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1396 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1397 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1398 * edit-already-exists error will be returned. These two conditions are also possible with
1399 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1401 * @param $baseRevId the revision ID this edit was based off, if any
1402 * @param $user User the user doing the edit
1403 * @param $serialisation_format String: format for storing the content in the database
1405 * @return Status object. Possible errors:
1406 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1407 * edit-gone-missing: In update mode, but the article didn't exist
1408 * edit-conflict: In update mode, the article changed unexpectedly
1409 * edit-no-change: Warning that the text was the same as before
1410 * edit-already-exists: In creation mode, but the article already exists
1412 * Extensions may define additional errors.
1414 * $return->value will contain an associative array with members as follows:
1415 * new: Boolean indicating if the function attempted to create a new article
1416 * revision: The revision object for the inserted revision, or null
1420 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1421 User
$user = null, $serialisation_format = null ) {
1422 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1424 # Low-level sanity check
1425 if ( $this->mTitle
->getText() === '' ) {
1426 throw new MWException( 'Something is trying to edit an article with an empty title' );
1429 wfProfileIn( __METHOD__
);
1431 $user = is_null( $user ) ?
$wgUser : $user;
1432 $status = Status
::newGood( array() );
1434 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1435 $this->loadPageData( 'fromdbmaster' );
1437 $flags = $this->checkFlags( $flags );
1440 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary,
1441 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1443 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { # avoid serialization overhead if the hook isn't present
1444 $content_text = $content->serialize();
1445 $txt = $content_text; # clone
1447 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary,
1448 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1450 if ( $txt !== $content_text ) {
1451 # if the text changed, unserialize the new version to create an updated Content object.
1452 $content = $content->getContentHandler()->unserializeContent( $txt );
1457 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1459 if ( $status->isOK() ) {
1460 $status->fatal( 'edit-hook-aborted' );
1463 wfProfileOut( __METHOD__
);
1467 # Silently ignore EDIT_MINOR if not allowed
1468 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1469 $bot = $flags & EDIT_FORCE_BOT
;
1471 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1473 $oldsize = $old_content ?
$old_content->getSize() : 0;
1474 $oldid = $this->getLatest();
1475 $oldIsRedirect = $this->isRedirect();
1476 $oldcountable = $this->isCountable();
1478 $handler = $content->getContentHandler();
1480 # Provide autosummaries if one is not provided and autosummaries are enabled.
1481 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1482 if ( !$old_content ) $old_content = null;
1483 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1486 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1487 $serialized = $editInfo->pst
;
1488 $content = $editInfo->pstContent
;
1489 $newsize = $content->getSize();
1491 $dbw = wfGetDB( DB_MASTER
);
1492 $now = wfTimestampNow();
1493 $this->mTimestamp
= $now;
1495 if ( $flags & EDIT_UPDATE
) {
1496 # Update article, but only if changed.
1497 $status->value
['new'] = false;
1500 # Article gone missing
1501 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1502 $status->fatal( 'edit-gone-missing' );
1504 wfProfileOut( __METHOD__
);
1508 # Make sure the revision is either completely inserted or not inserted at all
1509 if ( !$wgDBtransactions ) {
1510 $userAbort = ignore_user_abort( true );
1513 $revision = new Revision( array(
1514 'page' => $this->getId(),
1515 'comment' => $summary,
1516 'minor_edit' => $isminor,
1517 'text' => $serialized,
1519 'parent_id' => $oldid,
1520 'user' => $user->getId(),
1521 'user_text' => $user->getName(),
1522 'timestamp' => $now,
1523 'content_model' => $content->getModel(),
1524 'content_format' => $serialisation_format,
1527 $changed = !$content->equals( $old_content );
1530 $dbw->begin( __METHOD__
);
1531 $revisionId = $revision->insertOn( $dbw );
1535 # Note that we use $this->mLatest instead of fetching a value from the master DB
1536 # during the course of this function. This makes sure that EditPage can detect
1537 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1538 # before this function is called. A previous function used a separate query, this
1539 # creates a window where concurrent edits can cause an ignored edit conflict.
1540 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1543 /* Belated edit conflict! Run away!! */
1544 $status->fatal( 'edit-conflict' );
1546 # Delete the invalid revision if the DB is not transactional
1547 if ( !$wgDBtransactions ) {
1548 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1552 $dbw->rollback( __METHOD__
);
1554 global $wgUseRCPatrol;
1555 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1556 # Update recentchanges
1557 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1558 # Mark as patrolled if the user can do so
1559 $patrolled = $wgUseRCPatrol && !count(
1560 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1561 # Add RC row to the DB
1562 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1563 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1564 $revisionId, $patrolled
1567 # Log auto-patrolled edits
1569 PatrolLog
::record( $rc, true, $user );
1572 $user->incEditCount();
1573 $dbw->commit( __METHOD__
);
1576 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1577 // related variables correctly
1578 $revision->setId( $this->getLatest() );
1581 if ( !$wgDBtransactions ) {
1582 ignore_user_abort( $userAbort );
1585 // Now that ignore_user_abort is restored, we can respond to fatal errors
1586 if ( !$status->isOK() ) {
1587 wfProfileOut( __METHOD__
);
1591 # Update links tables, site stats, etc.
1592 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1593 'oldcountable' => $oldcountable ) );
1596 $status->warning( 'edit-no-change' );
1598 // Update page_touched, this is usually implicit in the page update
1599 // Other cache updates are done in onArticleEdit()
1600 $this->mTitle
->invalidateCache();
1603 # Create new article
1604 $status->value
['new'] = true;
1606 $dbw->begin( __METHOD__
);
1608 # Add the page record; stake our claim on this title!
1609 # This will return false if the article already exists
1610 $newid = $this->insertOn( $dbw );
1612 if ( $newid === false ) {
1613 $dbw->rollback( __METHOD__
);
1614 $status->fatal( 'edit-already-exists' );
1616 wfProfileOut( __METHOD__
);
1620 # Save the revision text...
1621 $revision = new Revision( array(
1623 'comment' => $summary,
1624 'minor_edit' => $isminor,
1625 'text' => $serialized,
1627 'user' => $user->getId(),
1628 'user_text' => $user->getName(),
1629 'timestamp' => $now,
1630 'content_model' => $content->getModel(),
1631 'content_format' => $serialisation_format,
1633 $revisionId = $revision->insertOn( $dbw );
1635 # Update the page record with revision data
1636 $this->updateRevisionOn( $dbw, $revision, 0 );
1638 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1640 # Update recentchanges
1641 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1642 global $wgUseRCPatrol, $wgUseNPPatrol;
1644 # Mark as patrolled if the user can do so
1645 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1646 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1647 # Add RC row to the DB
1648 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1649 '', $content->getSize(), $revisionId, $patrolled );
1651 # Log auto-patrolled edits
1653 PatrolLog
::record( $rc, true, $user );
1656 $user->incEditCount();
1657 $dbw->commit( __METHOD__
);
1659 # Update links, etc.
1660 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1662 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary,
1663 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1665 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary,
1666 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1669 # Do updates right now unless deferral was requested
1670 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1671 DeferredUpdates
::doUpdates();
1674 // Return the new revision (or null) to the caller
1675 $status->value
['revision'] = $revision;
1677 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary,
1678 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1680 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary,
1681 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1683 # Promote user to any groups they meet the criteria for
1684 $user->addAutopromoteOnceGroups( 'onEdit' );
1686 wfProfileOut( __METHOD__
);
1691 * Get parser options suitable for rendering the primary article wikitext
1692 * @param User|string $user User object or 'canonical'
1693 * @return ParserOptions
1695 public function makeParserOptions( $user ) {
1697 if ( $user instanceof User
) { // settings per user (even anons)
1698 $options = ParserOptions
::newFromUser( $user );
1699 } else { // canonical settings
1700 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1702 $options->enableLimitReport(); // show inclusion/loop reports
1703 $options->setTidy( true ); // fix bad HTML
1708 * Prepare text which is about to be saved.
1709 * Returns a stdclass with source, pst and output members
1711 * @deprecated in 1.WD: use prepareContentForEdit instead.
1713 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1714 wfDeprecated( __METHOD__
, '1.WD' );
1715 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1716 return $this->prepareContentForEdit( $content, $revid , $user );
1720 * Prepare content which is about to be saved.
1721 * Returns a stdclass with source, pst and output members
1723 * @param \Content $content
1724 * @param null $revid
1725 * @param null|\User $user
1726 * @param null $serialization_format
1728 * @return bool|object
1732 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) {
1733 global $wgParser, $wgContLang, $wgUser;
1734 $user = is_null( $user ) ?
$wgUser : $user;
1735 // @TODO fixme: check $user->getId() here???
1737 if ( $this->mPreparedEdit
1738 && $this->mPreparedEdit
->newContent
1739 && $this->mPreparedEdit
->newContent
->equals( $content )
1740 && $this->mPreparedEdit
->revid
== $revid
1741 && $this->mPreparedEdit
->format
== $serialization_format
1742 #XXX: also check $user here?
1745 return $this->mPreparedEdit
;
1748 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1749 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1751 $edit = (object)array();
1752 $edit->revid
= $revid;
1754 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1755 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1756 $edit->format
= $serialization_format;
1758 $edit->popts
= $this->makeParserOptions( 'canonical' );
1760 // TODO: is there no better way to obtain a context here?
1761 $context = RequestContext
::getMain();
1762 $context->setTitle( $this->mTitle
);
1763 $edit->output
= $edit->pstContent
->getParserOutput( $context, $revid, $edit->popts
);
1765 $edit->newContent
= $content;
1766 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1768 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1769 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1771 $this->mPreparedEdit
= $edit;
1777 * Do standard deferred updates after page edit.
1778 * Update links tables, site stats, search index and message cache.
1779 * Purges pages that include this page if the text was changed here.
1780 * Every 100th edit, prune the recent changes table.
1782 * @param $revision Revision object
1783 * @param $user User object that did the revision
1784 * @param $options Array of options, following indexes are used:
1785 * - changed: boolean, whether the revision changed the content (default true)
1786 * - created: boolean, whether the revision created the page (default false)
1787 * - oldcountable: boolean or null (default null):
1788 * - boolean: whether the page was counted as an article before that
1789 * revision, only used in changed is true and created is false
1790 * - null: don't change the article count
1792 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1793 global $wgEnableParserCache;
1795 wfProfileIn( __METHOD__
);
1797 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1798 $content = $revision->getContent();
1801 # Be careful not to double-PST: $text is usually already PST-ed once
1802 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1803 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1804 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1806 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1807 $editInfo = $this->mPreparedEdit
;
1810 # Save it to the parser cache
1811 if ( $wgEnableParserCache ) {
1812 $parserCache = ParserCache
::singleton();
1813 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1816 # Update the links tables and other secondary data
1817 $updates = $editInfo->output
->getSecondaryDataUpdates( $this->mTitle
);
1818 SecondaryDataUpdate
::runUpdates( $updates );
1820 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1822 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1823 if ( 0 == mt_rand( 0, 99 ) ) {
1824 // Flush old entries from the `recentchanges` table; we do this on
1825 // random requests so as to avoid an increase in writes for no good reason
1828 $dbw = wfGetDB( DB_MASTER
);
1829 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1832 array( "rc_timestamp < '$cutoff'" ),
1838 if ( !$this->mTitle
->exists() ) {
1839 wfProfileOut( __METHOD__
);
1843 $id = $this->getId();
1844 $title = $this->mTitle
->getPrefixedDBkey();
1845 $shortTitle = $this->mTitle
->getDBkey();
1847 if ( !$options['changed'] ) {
1850 } elseif ( $options['created'] ) {
1851 $good = (int)$this->isCountable( $editInfo );
1853 } elseif ( $options['oldcountable'] !== null ) {
1854 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1861 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1862 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
1864 # If this is another user's talk page, update newtalk.
1865 # Don't do this if $options['changed'] = false (null-edits) nor if
1866 # it's a minor edit and the user doesn't want notifications for those.
1867 if ( $options['changed']
1868 && $this->mTitle
->getNamespace() == NS_USER_TALK
1869 && $shortTitle != $user->getTitleKey()
1870 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1872 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1873 $other = User
::newFromName( $shortTitle, false );
1875 wfDebug( __METHOD__
. ": invalid username\n" );
1876 } elseif ( User
::isIP( $shortTitle ) ) {
1877 // An anonymous user
1878 $other->setNewtalk( true );
1879 } elseif ( $other->isLoggedIn() ) {
1880 $other->setNewtalk( true );
1882 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1887 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1888 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
1889 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
1891 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
1894 if( $options['created'] ) {
1895 self
::onArticleCreate( $this->mTitle
);
1897 self
::onArticleEdit( $this->mTitle
);
1900 wfProfileOut( __METHOD__
);
1904 * Edit an article without doing all that other stuff
1905 * The article must already exist; link tables etc
1906 * are not updated, caches are not flushed.
1908 * @param $text String: text submitted
1909 * @param $user User The relevant user
1910 * @param $comment String: comment submitted
1911 * @param $minor Boolean: whereas it's a minor modification
1913 * @deprecated since 1.WD, use doEditContent() instead.
1915 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1916 wfDeprecated( __METHOD__
, "1.WD" );
1918 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1919 return $this->doQuickEditContent( $content, $user, $comment , $minor );
1923 * Edit an article without doing all that other stuff
1924 * The article must already exist; link tables etc
1925 * are not updated, caches are not flushed.
1927 * @param $content Content: content submitted
1928 * @param $user User The relevant user
1929 * @param $comment String: comment submitted
1930 * @param $serialisation_format String: format for storing the content in the database
1931 * @param $minor Boolean: whereas it's a minor modification
1933 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
1934 wfProfileIn( __METHOD__
);
1936 $serialized = $content->serialize( $serialisation_format );
1938 $dbw = wfGetDB( DB_MASTER
);
1939 $revision = new Revision( array(
1940 'page' => $this->getId(),
1941 'text' => $serialized,
1942 'length' => $content->getSize(),
1943 'comment' => $comment,
1944 'minor_edit' => $minor ?
1 : 0,
1946 $revision->insertOn( $dbw );
1947 $this->updateRevisionOn( $dbw, $revision );
1949 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1951 wfProfileOut( __METHOD__
);
1955 * Update the article's restriction field, and leave a log entry.
1956 * This works for protection both existing and non-existing pages.
1958 * @param $limit Array: set of restriction keys
1959 * @param $reason String
1960 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1961 * @param $expiry Array: per restriction type expiration
1962 * @param $user User The user updating the restrictions
1963 * @return bool true on success
1965 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1968 if ( wfReadOnly() ) {
1969 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1972 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1974 $id = $this->mTitle
->getArticleID();
1980 // Take this opportunity to purge out expired restrictions
1981 Title
::purgeExpiredRestrictions();
1983 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1984 # we expect a single selection, but the schema allows otherwise.
1985 $isProtected = false;
1989 $dbw = wfGetDB( DB_MASTER
);
1991 foreach ( $restrictionTypes as $action ) {
1992 if ( !isset( $expiry[$action] ) ) {
1993 $expiry[$action] = $dbw->getInfinity();
1995 if ( !isset( $limit[$action] ) ) {
1996 $limit[$action] = '';
1997 } elseif ( $limit[$action] != '' ) {
2001 # Get current restrictions on $action
2002 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2003 if ( $current != '' ) {
2004 $isProtected = true;
2007 if ( $limit[$action] != $current ) {
2009 } elseif ( $limit[$action] != '' ) {
2010 # Only check expiry change if the action is actually being
2011 # protected, since expiry does nothing on an not-protected
2013 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2019 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2023 # If nothing's changed, do nothing
2025 return Status
::newGood();
2028 if ( !$protect ) { # No protection at all means unprotection
2029 $revCommentMsg = 'unprotectedarticle';
2030 $logAction = 'unprotect';
2031 } elseif ( $isProtected ) {
2032 $revCommentMsg = 'modifiedarticleprotection';
2033 $logAction = 'modify';
2035 $revCommentMsg = 'protectedarticle';
2036 $logAction = 'protect';
2039 $encodedExpiry = array();
2040 $protectDescription = '';
2041 foreach ( $limit as $action => $restrictions ) {
2042 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2043 if ( $restrictions != '' ) {
2044 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2045 if ( $encodedExpiry[$action] != 'infinity' ) {
2046 $protectDescription .= wfMsgForContent( 'protect-expiring',
2047 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2048 $wgContLang->date( $expiry[$action], false, false ) ,
2049 $wgContLang->time( $expiry[$action], false, false ) );
2051 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
2054 $protectDescription .= ') ';
2057 $protectDescription = trim( $protectDescription );
2059 if ( $id ) { # Protection of existing page
2060 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2061 return Status
::newGood();
2064 # Only restrictions with the 'protect' right can cascade...
2065 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2066 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2068 # The schema allows multiple restrictions
2069 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2073 # Update restrictions table
2074 foreach ( $limit as $action => $restrictions ) {
2075 if ( $restrictions != '' ) {
2076 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2077 array( 'pr_page' => $id,
2078 'pr_type' => $action,
2079 'pr_level' => $restrictions,
2080 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2081 'pr_expiry' => $encodedExpiry[$action]
2086 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2087 'pr_type' => $action ), __METHOD__
);
2091 # Prepare a null revision to be added to the history
2092 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2094 $editComment .= ": $reason";
2096 if ( $protectDescription ) {
2097 $editComment .= " ($protectDescription)";
2100 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2103 # Insert a null revision
2104 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2105 $nullRevId = $nullRevision->insertOn( $dbw );
2107 $latest = $this->getLatest();
2108 # Update page record
2109 $dbw->update( 'page',
2111 'page_touched' => $dbw->timestamp(),
2112 'page_restrictions' => '',
2113 'page_latest' => $nullRevId
2114 ), array( /* WHERE */
2119 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2120 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2121 } else { # Protection of non-existing page (also known as "title protection")
2122 # Cascade protection is meaningless in this case
2125 if ( $limit['create'] != '' ) {
2126 $dbw->replace( 'protected_titles',
2127 array( array( 'pt_namespace', 'pt_title' ) ),
2129 'pt_namespace' => $this->mTitle
->getNamespace(),
2130 'pt_title' => $this->mTitle
->getDBkey(),
2131 'pt_create_perm' => $limit['create'],
2132 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2133 'pt_expiry' => $encodedExpiry['create'],
2134 'pt_user' => $user->getId(),
2135 'pt_reason' => $reason,
2139 $dbw->delete( 'protected_titles',
2141 'pt_namespace' => $this->mTitle
->getNamespace(),
2142 'pt_title' => $this->mTitle
->getDBkey()
2148 $this->mTitle
->flushRestrictions();
2150 if ( $logAction == 'unprotect' ) {
2151 $logParams = array();
2153 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2156 # Update the protection log
2157 $log = new LogPage( 'protect' );
2158 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2160 return Status
::newGood();
2164 * Take an array of page restrictions and flatten it to a string
2165 * suitable for insertion into the page_restrictions field.
2166 * @param $limit Array
2169 protected static function flattenRestrictions( $limit ) {
2170 if ( !is_array( $limit ) ) {
2171 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2177 foreach ( $limit as $action => $restrictions ) {
2178 if ( $restrictions != '' ) {
2179 $bits[] = "$action=$restrictions";
2183 return implode( ':', $bits );
2187 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2188 * Deletes the article with database consistency, writes logs, purges caches
2190 * @param $reason string delete reason for deletion log
2191 * @param $suppress int bitfield
2192 * Revision::DELETED_TEXT
2193 * Revision::DELETED_COMMENT
2194 * Revision::DELETED_USER
2195 * Revision::DELETED_RESTRICTED
2196 * @param $id int article ID
2197 * @param $commit boolean defaults to true, triggers transaction end
2198 * @param &$error Array of errors to append to
2199 * @param $user User The deleting user
2200 * @return boolean true if successful
2202 public function doDeleteArticle(
2203 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2205 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2206 == WikiPage
::DELETE_SUCCESS
;
2210 * Back-end article deletion
2211 * Deletes the article with database consistency, writes logs, purges caches
2213 * @param $reason string delete reason for deletion log
2214 * @param $suppress int bitfield
2215 * Revision::DELETED_TEXT
2216 * Revision::DELETED_COMMENT
2217 * Revision::DELETED_USER
2218 * Revision::DELETED_RESTRICTED
2219 * @param $id int article ID
2220 * @param $commit boolean defaults to true, triggers transaction end
2221 * @param &$error Array of errors to append to
2222 * @param $user User The deleting user
2223 * @return int: One of WikiPage::DELETE_* constants
2225 public function doDeleteArticleReal(
2226 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2228 global $wgUser, $wgContentHandlerUseDB;
2229 $user = is_null( $user ) ?
$wgUser : $user;
2231 wfDebug( __METHOD__
. "\n" );
2233 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2234 return WikiPage
::DELETE_HOOK_ABORTED
;
2236 $dbw = wfGetDB( DB_MASTER
);
2237 $t = $this->mTitle
->getDBkey();
2238 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2240 if ( $t === '' ||
$id == 0 ) {
2241 return WikiPage
::DELETE_NO_PAGE
;
2244 // Bitfields to further suppress the content
2247 // This should be 15...
2248 $bitfield |
= Revision
::DELETED_TEXT
;
2249 $bitfield |
= Revision
::DELETED_COMMENT
;
2250 $bitfield |
= Revision
::DELETED_USER
;
2251 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2253 $bitfield = 'rev_deleted';
2256 $dbw->begin( __METHOD__
);
2257 // For now, shunt the revision data into the archive table.
2258 // Text is *not* removed from the text table; bulk storage
2259 // is left intact to avoid breaking block-compression or
2260 // immutable storage schemes.
2262 // For backwards compatibility, note that some older archive
2263 // table entries will have ar_text and ar_flags fields still.
2265 // In the future, we may keep revisions and mark them with
2266 // the rev_deleted field, which is reserved for this purpose.
2269 'ar_namespace' => 'page_namespace',
2270 'ar_title' => 'page_title',
2271 'ar_comment' => 'rev_comment',
2272 'ar_user' => 'rev_user',
2273 'ar_user_text' => 'rev_user_text',
2274 'ar_timestamp' => 'rev_timestamp',
2275 'ar_minor_edit' => 'rev_minor_edit',
2276 'ar_rev_id' => 'rev_id',
2277 'ar_parent_id' => 'rev_parent_id',
2278 'ar_text_id' => 'rev_text_id',
2279 'ar_text' => '\'\'', // Be explicit to appease
2280 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2281 'ar_len' => 'rev_len',
2282 'ar_page_id' => 'page_id',
2283 'ar_deleted' => $bitfield,
2284 'ar_sha1' => 'rev_sha1',
2287 if ( $wgContentHandlerUseDB ) {
2288 $row[ 'ar_content_model' ] = 'rev_content_model';
2289 $row[ 'ar_content_format' ] = 'rev_content_format';
2292 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2296 'page_id = rev_page'
2300 # Now that it's safely backed up, delete it
2301 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2302 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2305 $dbw->rollback( __METHOD__
);
2306 return WikiPage
::DELETE_NO_REVISIONS
;
2309 # update site status
2310 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2312 # remove secondary indexes, etc
2313 $handler = $this->getContentHandler();
2314 $updates = $handler->getDeletionUpdates( $this );
2315 SecondaryDataUpdate
::runUpdates( $updates );
2318 WikiPage
::onArticleDelete( $this->mTitle
);
2323 # Clear the cached article id so the interface doesn't act like we exist
2324 $this->mTitle
->resetArticleID( 0 );
2326 # Log the deletion, if the page was suppressed, log it at Oversight instead
2327 $logtype = $suppress ?
'suppress' : 'delete';
2329 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2330 $logEntry->setPerformer( $user );
2331 $logEntry->setTarget( $this->mTitle
);
2332 $logEntry->setComment( $reason );
2333 $logid = $logEntry->insert();
2334 $logEntry->publish( $logid );
2337 $dbw->commit( __METHOD__
);
2340 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2341 return WikiPage
::DELETE_SUCCESS
;
2345 * Roll back the most recent consecutive set of edits to a page
2346 * from the same user; fails if there are no eligible edits to
2347 * roll back to, e.g. user is the sole contributor. This function
2348 * performs permissions checks on $user, then calls commitRollback()
2349 * to do the dirty work
2351 * @todo: seperate the business/permission stuff out from backend code
2353 * @param $fromP String: Name of the user whose edits to rollback.
2354 * @param $summary String: Custom summary. Set to default summary if empty.
2355 * @param $token String: Rollback token.
2356 * @param $bot Boolean: If true, mark all reverted edits as bot.
2358 * @param $resultDetails Array: contains result-specific array of additional values
2359 * 'alreadyrolled' : 'current' (rev)
2360 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2362 * @param $user User The user performing the rollback
2363 * @return array of errors, each error formatted as
2364 * array(messagekey, param1, param2, ...).
2365 * On success, the array is empty. This array can also be passed to
2366 * OutputPage::showPermissionsErrorPage().
2368 public function doRollback(
2369 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2371 $resultDetails = null;
2374 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2375 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2376 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2378 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2379 $errors[] = array( 'sessionfailure' );
2382 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2383 $errors[] = array( 'actionthrottledtext' );
2386 # If there were errors, bail out now
2387 if ( !empty( $errors ) ) {
2391 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2395 * Backend implementation of doRollback(), please refer there for parameter
2396 * and return value documentation
2398 * NOTE: This function does NOT check ANY permissions, it just commits the
2399 * rollback to the DB. Therefore, you should only call this function direct-
2400 * ly if you want to use custom permissions checks. If you don't, use
2401 * doRollback() instead.
2402 * @param $fromP String: Name of the user whose edits to rollback.
2403 * @param $summary String: Custom summary. Set to default summary if empty.
2404 * @param $bot Boolean: If true, mark all reverted edits as bot.
2406 * @param $resultDetails Array: contains result-specific array of additional values
2407 * @param $guser User The user performing the rollback
2410 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2411 global $wgUseRCPatrol, $wgContLang;
2413 $dbw = wfGetDB( DB_MASTER
);
2415 if ( wfReadOnly() ) {
2416 return array( array( 'readonlytext' ) );
2419 # Get the last editor
2420 $current = $this->getRevision();
2421 if ( is_null( $current ) ) {
2422 # Something wrong... no page?
2423 return array( array( 'notanarticle' ) );
2426 $from = str_replace( '_', ' ', $fromP );
2427 # User name given should match up with the top revision.
2428 # If the user was deleted then $from should be empty.
2429 if ( $from != $current->getUserText() ) {
2430 $resultDetails = array( 'current' => $current );
2431 return array( array( 'alreadyrolled',
2432 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2433 htmlspecialchars( $fromP ),
2434 htmlspecialchars( $current->getUserText() )
2438 # Get the last edit not by this guy...
2439 # Note: these may not be public values
2440 $user = intval( $current->getRawUser() );
2441 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2442 $s = $dbw->selectRow( 'revision',
2443 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2444 array( 'rev_page' => $current->getPage(),
2445 "rev_user != {$user} OR rev_user_text != {$user_text}"
2447 array( 'USE INDEX' => 'page_timestamp',
2448 'ORDER BY' => 'rev_timestamp DESC' )
2450 if ( $s === false ) {
2451 # No one else ever edited this page
2452 return array( array( 'cantrollback' ) );
2453 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2454 # Only admins can see this text
2455 return array( array( 'notvisiblerev' ) );
2459 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2460 # Mark all reverted edits as bot
2464 if ( $wgUseRCPatrol ) {
2465 # Mark all reverted edits as patrolled
2466 $set['rc_patrolled'] = 1;
2469 if ( count( $set ) ) {
2470 $dbw->update( 'recentchanges', $set,
2472 'rc_cur_id' => $current->getPage(),
2473 'rc_user_text' => $current->getUserText(),
2474 "rc_timestamp > '{$s->rev_timestamp}'",
2479 # Generate the edit summary if necessary
2480 $target = Revision
::newFromId( $s->rev_id
);
2481 if ( empty( $summary ) ) {
2482 if ( $from == '' ) { // no public user name
2483 $summary = wfMsgForContent( 'revertpage-nouser' );
2485 $summary = wfMsgForContent( 'revertpage' );
2489 # Allow the custom summary to use the same args as the default message
2491 $target->getUserText(), $from, $s->rev_id
,
2492 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2493 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2495 $summary = wfMsgReplaceArgs( $summary, $args );
2498 $flags = EDIT_UPDATE
;
2500 if ( $guser->isAllowed( 'minoredit' ) ) {
2501 $flags |
= EDIT_MINOR
;
2504 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2505 $flags |
= EDIT_FORCE_BOT
;
2508 # Actually store the edit
2509 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2510 if ( !empty( $status->value
['revision'] ) ) {
2511 $revId = $status->value
['revision']->getId();
2516 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2518 $resultDetails = array(
2519 'summary' => $summary,
2520 'current' => $current,
2521 'target' => $target,
2529 * The onArticle*() functions are supposed to be a kind of hooks
2530 * which should be called whenever any of the specified actions
2533 * This is a good place to put code to clear caches, for instance.
2535 * This is called on page move and undelete, as well as edit
2537 * @param $title Title object
2539 public static function onArticleCreate( $title ) {
2540 # Update existence markers on article/talk tabs...
2541 if ( $title->isTalkPage() ) {
2542 $other = $title->getSubjectPage();
2544 $other = $title->getTalkPage();
2547 $other->invalidateCache();
2548 $other->purgeSquid();
2550 $title->touchLinks();
2551 $title->purgeSquid();
2552 $title->deleteTitleProtection();
2556 * Clears caches when article is deleted
2558 * @param $title Title
2560 public static function onArticleDelete( $title ) {
2561 # Update existence markers on article/talk tabs...
2562 if ( $title->isTalkPage() ) {
2563 $other = $title->getSubjectPage();
2565 $other = $title->getTalkPage();
2568 $other->invalidateCache();
2569 $other->purgeSquid();
2571 $title->touchLinks();
2572 $title->purgeSquid();
2575 HTMLFileCache
::clearFileCache( $title );
2578 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2579 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2583 if ( $title->getNamespace() == NS_FILE
) {
2584 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2585 $update->doUpdate();
2589 if ( $title->getNamespace() == NS_USER_TALK
) {
2590 $user = User
::newFromName( $title->getText(), false );
2592 $user->setNewtalk( false );
2597 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2601 * Purge caches on page update etc
2603 * @param $title Title object
2604 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2606 public static function onArticleEdit( $title ) {
2607 // Invalidate caches of articles which include this page
2608 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2611 // Invalidate the caches of all pages which redirect here
2612 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2614 # Purge squid for this page only
2615 $title->purgeSquid();
2617 # Clear file cache for this page only
2618 HTMLFileCache
::clearFileCache( $title );
2624 * Returns a list of hidden categories this page is a member of.
2625 * Uses the page_props and categorylinks tables.
2627 * @return Array of Title objects
2629 public function getHiddenCategories() {
2631 $id = $this->mTitle
->getArticleID();
2637 $dbr = wfGetDB( DB_SLAVE
);
2638 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2640 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2641 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2644 if ( $res !== false ) {
2645 foreach ( $res as $row ) {
2646 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2654 * Return an applicable autosummary if one exists for the given edit.
2655 * @param $oldtext String|null: the previous text of the page.
2656 * @param $newtext String|null: The submitted text of the page.
2657 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2658 * @return string An appropriate autosummary, or an empty string.
2659 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
2661 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2662 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2664 wfDeprecated( __METHOD__
, '1.WD' );
2666 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
2667 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
2668 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
2670 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2674 * Auto-generates a deletion reason
2676 * @param &$hasHistory Boolean: whether the page has a history
2677 * @return mixed String containing deletion reason or empty string, or boolean false
2678 * if no revision occurred
2679 * @deprecated since 1.WD, use ContentHandler::getAutoDeleteReason() instead
2681 public function getAutoDeleteReason( &$hasHistory ) {
2682 #NOTE: stub for backwards-compatibility.
2684 wfDeprecated( __METHOD__
, '1.WD' );
2686 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2687 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2690 // Get the last revision
2691 $rev = $this->getRevision();
2693 if ( is_null( $rev ) ) {
2697 // Get the article's contents
2698 $contents = $rev->getText();
2701 // If the page is blank, use the text from the previous revision,
2702 // which can only be blank if there's a move/import/protect dummy revision involved
2703 if ( $contents == '' ) {
2704 $prev = $rev->getPrevious();
2707 $contents = $prev->getText();
2712 $dbw = wfGetDB( DB_MASTER
);
2714 // Find out if there was only one contributor
2715 // Only scan the last 20 revisions
2716 $res = $dbw->select( 'revision', 'rev_user_text',
2717 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2719 array( 'LIMIT' => 20 )
2722 if ( $res === false ) {
2723 // This page has no revisions, which is very weird
2727 $hasHistory = ( $res->numRows() > 1 );
2728 $row = $dbw->fetchObject( $res );
2730 if ( $row ) { // $row is false if the only contributor is hidden
2731 $onlyAuthor = $row->rev_user_text
;
2732 // Try to find a second contributor
2733 foreach ( $res as $row ) {
2734 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2735 $onlyAuthor = false;
2740 $onlyAuthor = false;
2743 // Generate the summary with a '$1' placeholder
2745 // The current revision is blank and the one before is also
2746 // blank. It's just not our lucky day
2747 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2749 if ( $onlyAuthor ) {
2750 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2752 $reason = wfMsgForContent( 'excontent', '$1' );
2756 if ( $reason == '-' ) {
2757 // Allow these UI messages to be blanked out cleanly
2761 // Replace newlines with spaces to prevent uglyness
2762 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2763 // Calculate the maximum amount of chars to get
2764 // Max content length = max comment length - length of the comment (excl. $1)
2765 $maxLength = 255 - ( strlen( $reason ) - 2 );
2766 $contents = $wgContLang->truncate( $contents, $maxLength );
2767 // Remove possible unfinished links
2768 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2769 // Now replace the '$1' placeholder
2770 $reason = str_replace( '$1', $contents, $reason );
2776 * Update all the appropriate counts in the category table, given that
2777 * we've added the categories $added and deleted the categories $deleted.
2779 * @param $added array The names of categories that were added
2780 * @param $deleted array The names of categories that were deleted
2782 public function updateCategoryCounts( $added, $deleted ) {
2783 $ns = $this->mTitle
->getNamespace();
2784 $dbw = wfGetDB( DB_MASTER
);
2786 # First make sure the rows exist. If one of the "deleted" ones didn't
2787 # exist, we might legitimately not create it, but it's simpler to just
2788 # create it and then give it a negative value, since the value is bogus
2791 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2792 $insertCats = array_merge( $added, $deleted );
2793 if ( !$insertCats ) {
2794 # Okay, nothing to do
2798 $insertRows = array();
2800 foreach ( $insertCats as $cat ) {
2801 $insertRows[] = array(
2802 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2806 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2808 $addFields = array( 'cat_pages = cat_pages + 1' );
2809 $removeFields = array( 'cat_pages = cat_pages - 1' );
2811 if ( $ns == NS_CATEGORY
) {
2812 $addFields[] = 'cat_subcats = cat_subcats + 1';
2813 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2814 } elseif ( $ns == NS_FILE
) {
2815 $addFields[] = 'cat_files = cat_files + 1';
2816 $removeFields[] = 'cat_files = cat_files - 1';
2823 array( 'cat_title' => $added ),
2832 array( 'cat_title' => $deleted ),
2839 * Updates cascading protections
2841 * @param $parserOutput ParserOutput object for the current version
2843 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2844 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2848 // templatelinks table may have become out of sync,
2849 // especially if using variable-based transclusions.
2850 // For paranoia, check if things have changed and if
2851 // so apply updates to the database. This will ensure
2852 // that cascaded protections apply as soon as the changes
2855 # Get templates from templatelinks
2856 $id = $this->mTitle
->getArticleID();
2858 $tlTemplates = array();
2860 $dbr = wfGetDB( DB_SLAVE
);
2861 $res = $dbr->select( array( 'templatelinks' ),
2862 array( 'tl_namespace', 'tl_title' ),
2863 array( 'tl_from' => $id ),
2867 foreach ( $res as $row ) {
2868 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2871 # Get templates from parser output.
2872 $poTemplates = array();
2873 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2874 foreach ( $templates as $dbk => $id ) {
2875 $poTemplates["$ns:$dbk"] = true;
2880 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2882 if ( count( $templates_diff ) > 0 ) {
2883 # Whee, link updates time.
2884 # Note: we are only interested in links here. We don't need to get other SecondaryDataUpdate items from the parser output.
2885 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2891 * Return a list of templates used by this article.
2892 * Uses the templatelinks table
2894 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2895 * @return Array of Title objects
2897 public function getUsedTemplates() {
2898 return $this->mTitle
->getTemplateLinksFrom();
2902 * Perform article updates on a special page creation.
2904 * @param $rev Revision object
2906 * @todo This is a shitty interface function. Kill it and replace the
2907 * other shitty functions like doEditUpdates and such so it's not needed
2909 * @deprecated since 1.18, use doEditUpdates()
2911 public function createUpdates( $rev ) {
2912 wfDeprecated( __METHOD__
, '1.18' );
2914 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2918 * This function is called right before saving the wikitext,
2919 * so we can do things like signatures and links-in-context.
2921 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2922 * @param $text String article contents
2923 * @param $user User object: user doing the edit
2924 * @param $popts ParserOptions object: parser options, default options for
2925 * the user loaded if null given
2926 * @return string article contents with altered wikitext markup (signatures
2927 * converted, {{subst:}}, templates, etc.)
2929 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2930 global $wgParser, $wgUser;
2932 wfDeprecated( __METHOD__
, '1.19' );
2934 $user = is_null( $user ) ?
$wgUser : $user;
2936 if ( $popts === null ) {
2937 $popts = ParserOptions
::newFromUser( $user );
2940 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2944 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2946 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2949 public function isBigDeletion() {
2950 wfDeprecated( __METHOD__
, '1.19' );
2951 return $this->mTitle
->isBigDeletion();
2955 * Get the approximate revision count of this page.
2957 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2960 public function estimateRevisionCount() {
2961 wfDeprecated( __METHOD__
, '1.19' );
2962 return $this->mTitle
->estimateRevisionCount();
2966 * Update the article's restriction field, and leave a log entry.
2968 * @deprecated since 1.19
2969 * @param $limit Array: set of restriction keys
2970 * @param $reason String
2971 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2972 * @param $expiry Array: per restriction type expiration
2973 * @param $user User The user updating the restrictions
2974 * @return bool true on success
2976 public function updateRestrictions(
2977 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2981 $user = is_null( $user ) ?
$wgUser : $user;
2983 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2987 * @deprecated since 1.18
2989 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2990 wfDeprecated( __METHOD__
, '1.18' );
2992 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2996 * @deprecated since 1.18
2998 public function viewUpdates() {
2999 wfDeprecated( __METHOD__
, '1.18' );
3001 return $this->doViewUpdates( $wgUser );
3005 * @deprecated since 1.18
3008 public function useParserCache( $oldid ) {
3009 wfDeprecated( __METHOD__
, '1.18' );
3011 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3015 class PoolWorkArticleView
extends PoolCounterWork
{
3033 * @var ParserOptions
3035 private $parserOptions;
3043 * @var ParserOutput|bool
3045 private $parserOutput = false;
3050 private $isDirty = false;
3055 private $error = false;
3061 * @param $revid Integer: ID of the revision being parsed
3062 * @param $useParserCache Boolean: whether to use the parser cache
3063 * @param $parserOptions parserOptions to use for the parse operation
3064 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3065 * @param $context IContextSource context for parsing
3067 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null, IContextSource
$context = null ) {
3068 if ( is_string($content) ) { #BC: old style call
3069 $modelId = $page->getRevision()->getContentModel();
3070 $format = $page->getRevision()->getContentFormat();
3071 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3074 if ( is_null( $context ) ) {
3075 $context = RequestContext
::getMain();
3076 #XXX: clone and then set title?
3079 $this->page
= $page;
3080 $this->revid
= $revid;
3081 $this->context
= $context;
3082 $this->cacheable
= $useParserCache;
3083 $this->parserOptions
= $parserOptions;
3084 $this->content
= $content;
3085 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3086 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3090 * Get the ParserOutput from this object, or false in case of failure
3092 * @return ParserOutput
3094 public function getParserOutput() {
3095 return $this->parserOutput
;
3099 * Get whether the ParserOutput is a dirty one (i.e. expired)
3103 public function getIsDirty() {
3104 return $this->isDirty
;
3108 * Get a Status object in case of error or false otherwise
3110 * @return Status|bool
3112 public function getError() {
3113 return $this->error
;
3120 global $wgUseFileCache;
3122 // @todo: several of the methods called on $this->page are not declared in Page, but present in WikiPage and delegated by Article.
3124 $isCurrent = $this->revid
=== $this->page
->getLatest();
3126 if ( $this->content
!== null ) {
3127 $content = $this->content
;
3128 } elseif ( $isCurrent ) {
3129 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
3131 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3132 if ( $rev === null ) {
3135 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
3138 $time = - microtime( true );
3139 // TODO: page might not have this method? Hard to tell what page is supposed to be here...
3140 $this->parserOutput
= $content->getParserOutput( $this->context
, $this->revid
, $this->parserOptions
);
3141 $time +
= microtime( true );
3145 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3146 $this->page
->getTitle()->getPrefixedDBkey() ) );
3149 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3150 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3153 // Make sure file cache is not used on uncacheable content.
3154 // Output that has magic words in it can still use the parser cache
3155 // (if enabled), though it will generally expire sooner.
3156 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3157 $wgUseFileCache = false;
3161 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3170 function getCachedWork() {
3171 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3173 if ( $this->parserOutput
=== false ) {
3174 wfDebug( __METHOD__
. ": parser cache miss\n" );
3177 wfDebug( __METHOD__
. ": parser cache hit\n" );
3185 function fallback() {
3186 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3188 if ( $this->parserOutput
=== false ) {
3189 wfDebugLog( 'dirty', "dirty missing\n" );
3190 wfDebug( __METHOD__
. ": no dirty cache\n" );
3193 wfDebug( __METHOD__
. ": sending dirty output\n" );
3194 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3195 $this->isDirty
= true;
3201 * @param $status Status
3204 function error( $status ) {
3205 $this->error
= $status;