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 $t = Title
::newFromID( $id );
126 return self
::factory( $t );
132 * Returns overrides for action handlers.
133 * Classes listed here will be used instead of the default one when
134 * (and only when) $wgActions[$action] === true. This allows subclasses
135 * to override the default behavior.
137 * @todo: move this UI stuff somewhere else
141 public function getActionOverrides() {
142 $content_handler = $this->getContentHandler();
143 return $content_handler->getActionOverrides();
147 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
149 * Shorthand for ContentHandler::getForModelName( $this->getContentModelName() );
151 * @return ContentHandler
153 public function getContentHandler() {
154 return ContentHandler
::getForModelName( $this->getContentModelName() );
158 * Get the title object of the article
159 * @return Title object of this page
161 public function getTitle() {
162 return $this->mTitle
;
168 public function clear() {
169 $this->mDataLoaded
= false;
171 $this->mCounter
= null;
172 $this->mRedirectTarget
= null; # Title object if set
173 $this->mLastRevision
= null; # Latest revision
174 $this->mTouched
= '19700101000000';
175 $this->mTimestamp
= '';
176 $this->mIsRedirect
= false;
177 $this->mLatest
= false;
178 $this->mPreparedEdit
= false;
182 * Return the list of revision fields that should be selected to create
187 public static function selectFields() {
200 'page_content_model',
205 * Fetch a page record with the given conditions
206 * @param $dbr DatabaseBase object
207 * @param $conditions Array
208 * @return mixed Database result resource, or false on failure
210 protected function pageData( $dbr, $conditions ) {
211 $fields = self
::selectFields();
213 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
215 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
217 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
223 * Fetch a page record matching the Title object's namespace and title
224 * using a sanitized title string
226 * @param $dbr DatabaseBase object
227 * @param $title Title object
228 * @return mixed Database result resource, or false on failure
230 public function pageDataFromTitle( $dbr, $title ) {
231 return $this->pageData( $dbr, array(
232 'page_namespace' => $title->getNamespace(),
233 'page_title' => $title->getDBkey() ) );
237 * Fetch a page record matching the requested ID
239 * @param $dbr DatabaseBase
241 * @return mixed Database result resource, or false on failure
243 public function pageDataFromId( $dbr, $id ) {
244 return $this->pageData( $dbr, array( 'page_id' => $id ) );
248 * Set the general counter, title etc data loaded from
251 * @param $data Object|String One of the following:
252 * A DB query result object or...
253 * "fromdb" to get from a slave DB or...
254 * "fromdbmaster" to get from the master DB
257 public function loadPageData( $data = 'fromdb' ) {
258 if ( $data === 'fromdbmaster' ) {
259 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
260 } elseif ( $data === 'fromdb' ) { // slave
261 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
262 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
263 # Note that DB also stores the master position in the session and checks it.
264 $touched = $this->getCachedLastEditTime();
265 if ( $touched ) { // key set
266 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
267 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
272 $lc = LinkCache
::singleton();
275 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
277 $this->mTitle
->loadFromRow( $data );
279 # Old-fashioned restrictions
280 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
282 $this->mCounter
= intval( $data->page_counter
);
283 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
284 $this->mIsRedirect
= intval( $data->page_is_redirect
);
285 $this->mLatest
= intval( $data->page_latest
);
287 $lc->addBadLinkObj( $this->mTitle
);
289 $this->mTitle
->loadFromRow( false );
292 $this->mDataLoaded
= true;
296 * @return int Page ID
298 public function getId() {
299 return $this->mTitle
->getArticleID();
303 * @return bool Whether or not the page exists in the database
305 public function exists() {
306 return $this->mTitle
->exists();
310 * Check if this page is something we're going to be showing
311 * some sort of sensible content for. If we return false, page
312 * views (plain action=view) will return an HTTP 404 response,
313 * so spiders and robots can know they're following a bad link.
317 public function hasViewableContent() {
318 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
322 * @return int The view count for the page
324 public function getCount() {
325 if ( !$this->mDataLoaded
) {
326 $this->loadPageData();
329 return $this->mCounter
;
333 * Tests if the article text represents a redirect
335 * @param $text mixed string containing article contents, or boolean
338 public function isRedirect( $text = false ) {
339 if ( $text === false ) $content = $this->getContent();
340 else $content = ContentHandler
::makeContent( $text, $this->mTitle
); # TODO: allow model and format to be provided; or better, expect a Content object
343 if ( empty( $content ) ) return false;
344 else return $content->isRedirect();
348 * Returns the page's content model name. Will use the revisions actual content model if the page exists,
349 * and the page's default if the page doesn't exist yet.
353 public function getContentModelName() {
354 if ( $this->exists() ) {
355 # look at the revision's actual content model
356 $rev = $this->getRevision();
357 return $rev->getContentModelName();
359 # use the default model for this page
360 return $this->mTitle
->getContentModelName();
365 * Loads page_touched and returns a value indicating if it should be used
366 * @return boolean true if not a redirect
368 public function checkTouched() {
369 if ( !$this->mDataLoaded
) {
370 $this->loadPageData();
372 return !$this->mIsRedirect
;
376 * Get the page_touched field
377 * @return string containing GMT timestamp
379 public function getTouched() {
380 if ( !$this->mDataLoaded
) {
381 $this->loadPageData();
383 return $this->mTouched
;
387 * Get the page_latest field
388 * @return integer rev_id of current revision
390 public function getLatest() {
391 if ( !$this->mDataLoaded
) {
392 $this->loadPageData();
394 return (int)$this->mLatest
;
398 * Loads everything except the text
399 * This isn't necessary for all uses, so it's only done if needed.
401 protected function loadLastEdit() {
402 if ( $this->mLastRevision
!== null ) {
403 return; // already loaded
406 $latest = $this->getLatest();
408 return; // page doesn't exist or is missing page_latest info
411 $revision = Revision
::newFromPageId( $this->getId(), $latest );
412 if ( $revision ) { // sanity
413 $this->setLastEdit( $revision );
418 * Set the latest revision
420 protected function setLastEdit( Revision
$revision ) {
421 $this->mLastRevision
= $revision;
422 $this->mTimestamp
= $revision->getTimestamp();
426 * Get the latest revision
427 * @return Revision|null
429 public function getRevision() {
430 $this->loadLastEdit();
431 if ( $this->mLastRevision
) {
432 return $this->mLastRevision
;
438 * Get the content of the current revision. No side-effects...
440 * @param $audience Integer: one of:
441 * Revision::FOR_PUBLIC to be displayed to all users
442 * Revision::FOR_THIS_USER to be displayed to $wgUser
443 * Revision::RAW get the text regardless of permissions
444 * @return Content|null The content of the current revision
446 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
447 $this->loadLastEdit();
448 if ( $this->mLastRevision
) {
449 return $this->mLastRevision
->getContent( $audience );
455 * Get the text of the current revision. No side-effects...
457 * @param $audience Integer: one of:
458 * Revision::FOR_PUBLIC to be displayed to all users
459 * Revision::FOR_THIS_USER to be displayed to $wgUser
460 * Revision::RAW get the text regardless of permissions
461 * @return String|false The text of the current revision
462 * @deprecated as of 1.20, getContent() should be used instead.
464 public function getText( $audience = Revision
::FOR_PUBLIC
) { #@todo: deprecated, replace usage!
465 wfDeprecated( __METHOD__
, '1.20' );
467 $this->loadLastEdit();
468 if ( $this->mLastRevision
) {
469 return $this->mLastRevision
->getText( $audience );
475 * Get the text of the current revision. No side-effects...
477 * @return String|bool The text of the current revision. False on failure
478 * @deprecated as of 1.20, getContent() should be used instead.
480 public function getRawText() { #@todo: deprecated, replace usage!
481 wfDeprecated( __METHOD__
, '1.20' );
483 return $this->getText( Revision
::RAW
);
487 * Get the content of the current revision. No side-effects...
489 * @return Contet|false The text of the current revision
491 protected function getNativeData() { #FIXME: examine all uses carefully! caller must be aware of content model!
492 $content = $this->getContent( Revision
::RAW
);
493 if ( !$content ) return null;
495 return $content->getNativeData();
499 * @return string MW timestamp of last article revision
501 public function getTimestamp() {
502 // Check if the field has been filled by WikiPage::setTimestamp()
503 if ( !$this->mTimestamp
) {
504 $this->loadLastEdit();
507 return wfTimestamp( TS_MW
, $this->mTimestamp
);
511 * Set the page timestamp (use only to avoid DB queries)
512 * @param $ts string MW timestamp of last article revision
515 public function setTimestamp( $ts ) {
516 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
520 * @param $audience Integer: one of:
521 * Revision::FOR_PUBLIC to be displayed to all users
522 * Revision::FOR_THIS_USER to be displayed to $wgUser
523 * Revision::RAW get the text regardless of permissions
524 * @return int user ID for the user that made the last article revision
526 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
527 $this->loadLastEdit();
528 if ( $this->mLastRevision
) {
529 return $this->mLastRevision
->getUser( $audience );
536 * @param $audience Integer: one of:
537 * Revision::FOR_PUBLIC to be displayed to all users
538 * Revision::FOR_THIS_USER to be displayed to $wgUser
539 * Revision::RAW get the text regardless of permissions
540 * @return string username of the user that made the last article revision
542 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
543 $this->loadLastEdit();
544 if ( $this->mLastRevision
) {
545 return $this->mLastRevision
->getUserText( $audience );
552 * @param $audience Integer: one of:
553 * Revision::FOR_PUBLIC to be displayed to all users
554 * Revision::FOR_THIS_USER to be displayed to $wgUser
555 * Revision::RAW get the text regardless of permissions
556 * @return string Comment stored for the last article revision
558 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
559 $this->loadLastEdit();
560 if ( $this->mLastRevision
) {
561 return $this->mLastRevision
->getComment( $audience );
568 * Returns true if last revision was marked as "minor edit"
570 * @return boolean Minor edit indicator for the last article revision.
572 public function getMinorEdit() {
573 $this->loadLastEdit();
574 if ( $this->mLastRevision
) {
575 return $this->mLastRevision
->isMinor();
582 * Get the cached timestamp for the last time the page changed.
583 * This is only used to help handle slave lag by comparing to page_touched.
584 * @return string MW timestamp
586 protected function getCachedLastEditTime() {
588 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
589 return $wgMemc->get( $key );
593 * Set the cached timestamp for the last time the page changed.
594 * This is only used to help handle slave lag by comparing to page_touched.
595 * @param $timestamp string
598 public function setCachedLastEditTime( $timestamp ) {
600 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
601 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
605 * Determine whether a page would be suitable for being counted as an
606 * article in the site_stats table based on the title & its content
608 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
609 * if false, the current database state will be used
612 public function isCountable( $editInfo = false ) {
613 global $wgArticleCountMethod;
615 if ( !$this->mTitle
->isContentPage() ) {
620 $content = $editInfo->pstContent
;
622 $content = $this->getContent();
625 if ( !$content ||
$content->isRedirect( ) ) {
631 if ( $wgArticleCountMethod === 'link' ) {
632 # nasty special case to avoid re-parsing to detect links
635 // ParserOutput::getLinks() is a 2D array of page links, so
636 // to be really correct we would need to recurse in the array
637 // but the main array should only have items in it if there are
639 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
641 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
642 array( 'pl_from' => $this->getId() ), __METHOD__
);
646 return $content->isCountable( $hasLinks );
650 * If this page is a redirect, get its target
652 * The target will be fetched from the redirect table if possible.
653 * If this page doesn't have an entry there, call insertRedirect()
654 * @return Title|mixed object, or null if this page is not a redirect
656 public function getRedirectTarget() {
657 if ( !$this->mTitle
->isRedirect() ) {
661 if ( $this->mRedirectTarget
!== null ) {
662 return $this->mRedirectTarget
;
665 # Query the redirect table
666 $dbr = wfGetDB( DB_SLAVE
);
667 $row = $dbr->selectRow( 'redirect',
668 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
669 array( 'rd_from' => $this->getId() ),
673 // rd_fragment and rd_interwiki were added later, populate them if empty
674 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
675 return $this->mRedirectTarget
= Title
::makeTitle(
676 $row->rd_namespace
, $row->rd_title
,
677 $row->rd_fragment
, $row->rd_interwiki
);
680 # This page doesn't have an entry in the redirect table
681 return $this->mRedirectTarget
= $this->insertRedirect();
685 * Insert an entry for this page into the redirect table.
687 * Don't call this function directly unless you know what you're doing.
688 * @return Title object or null if not a redirect
690 public function insertRedirect() {
691 // recurse through to only get the final target
692 $content = $this->getContent();
693 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
697 $this->insertRedirectEntry( $retval );
702 * Insert or update the redirect table entry for this page to indicate
703 * it redirects to $rt .
704 * @param $rt Title redirect target
706 public function insertRedirectEntry( $rt ) {
707 $dbw = wfGetDB( DB_MASTER
);
708 $dbw->replace( 'redirect', array( 'rd_from' ),
710 'rd_from' => $this->getId(),
711 'rd_namespace' => $rt->getNamespace(),
712 'rd_title' => $rt->getDBkey(),
713 'rd_fragment' => $rt->getFragment(),
714 'rd_interwiki' => $rt->getInterwiki(),
721 * Get the Title object or URL this page redirects to
723 * @return mixed false, Title of in-wiki target, or string with URL
725 public function followRedirect() {
726 return $this->getRedirectURL( $this->getRedirectTarget() );
730 * Get the Title object or URL to use for a redirect. We use Title
731 * objects for same-wiki, non-special redirects and URLs for everything
733 * @param $rt Title Redirect target
734 * @return mixed false, Title object of local target, or string with URL
736 public function getRedirectURL( $rt ) {
741 if ( $rt->isExternal() ) {
742 if ( $rt->isLocal() ) {
743 // Offsite wikis need an HTTP redirect.
745 // This can be hard to reverse and may produce loops,
746 // so they may be disabled in the site configuration.
747 $source = $this->mTitle
->getFullURL( 'redirect=no' );
748 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
750 // External pages pages without "local" bit set are not valid
756 if ( $rt->isSpecialPage() ) {
757 // Gotta handle redirects to special pages differently:
758 // Fill the HTTP response "Location" header and ignore
759 // the rest of the page we're on.
761 // Some pages are not valid targets
762 if ( $rt->isValidRedirectTarget() ) {
763 return $rt->getFullURL();
773 * Get a list of users who have edited this article, not including the user who made
774 * the most recent revision, which you can get from $article->getUser() if you want it
775 * @return UserArrayFromResult
777 public function getContributors() {
778 # @todo FIXME: This is expensive; cache this info somewhere.
780 $dbr = wfGetDB( DB_SLAVE
);
782 if ( $dbr->implicitGroupby() ) {
783 $realNameField = 'user_real_name';
785 $realNameField = 'MIN(user_real_name) AS user_real_name';
788 $tables = array( 'revision', 'user' );
791 'rev_user as user_id',
792 'rev_user_text AS user_name',
794 'MAX(rev_timestamp) AS timestamp',
797 $conds = array( 'rev_page' => $this->getId() );
799 // The user who made the top revision gets credited as "this page was last edited by
800 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
801 $user = $this->getUser();
803 $conds[] = "rev_user != $user";
805 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
808 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
811 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
815 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
816 'ORDER BY' => 'timestamp DESC',
819 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
820 return new UserArrayFromResult( $res );
824 * Get the last N authors
825 * @param $num Integer: number of revisions to get
826 * @param $revLatest String: the latest rev_id, selected from the master (optional)
827 * @return array Array of authors, duplicates not removed
829 public function getLastNAuthors( $num, $revLatest = 0 ) {
830 wfProfileIn( __METHOD__
);
831 // First try the slave
832 // If that doesn't have the latest revision, try the master
834 $db = wfGetDB( DB_SLAVE
);
837 $res = $db->select( array( 'page', 'revision' ),
838 array( 'rev_id', 'rev_user_text' ),
840 'page_namespace' => $this->mTitle
->getNamespace(),
841 'page_title' => $this->mTitle
->getDBkey(),
845 'ORDER BY' => 'rev_timestamp DESC',
851 wfProfileOut( __METHOD__
);
855 $row = $db->fetchObject( $res );
857 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
858 $db = wfGetDB( DB_MASTER
);
863 } while ( $continue );
865 $authors = array( $row->rev_user_text
);
867 foreach ( $res as $row ) {
868 $authors[] = $row->rev_user_text
;
871 wfProfileOut( __METHOD__
);
876 * Should the parser cache be used?
878 * @param $parserOptions ParserOptions to check
882 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
883 global $wgEnableParserCache;
885 return $wgEnableParserCache
886 && $parserOptions->getStubThreshold() == 0
887 && $this->mTitle
->exists()
888 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
889 && $this->getContentHandler()->isParserCacheSupported();
893 * Get a ParserOutput for the given ParserOptions and revision ID.
894 * The parser cache will be used if possible.
897 * @param $parserOptions ParserOptions to use for the parse operation
898 * @param $oldid Revision ID to get the text from, passing null or 0 will
899 * get the current revision (default value)
900 * @param $context IContextSource context for parsing
902 * @return ParserOutput or false if the revision was not found
904 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null, IContextSource
$context = null ) {
905 wfProfileIn( __METHOD__
);
907 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
908 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
909 if ( $parserOptions->getStubThreshold() ) {
910 wfIncrStats( 'pcache_miss_stub' );
913 if ( $useParserCache ) {
914 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
915 if ( $parserOutput !== false ) {
916 wfProfileOut( __METHOD__
);
917 return $parserOutput;
921 if ( $oldid === null ||
$oldid === 0 ) {
922 $oldid = $this->getLatest();
925 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache, null, $context );
928 wfProfileOut( __METHOD__
);
930 return $pool->getParserOutput();
934 * Do standard deferred updates after page view
935 * @param $user User The relevant user
937 public function doViewUpdates( User
$user ) {
938 global $wgDisableCounters;
939 if ( wfReadOnly() ) {
943 # Don't update page view counters on views from bot users (bug 14044)
944 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
945 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
946 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
949 # Update newtalk / watchlist notification status
950 $user->clearNotification( $this->mTitle
);
954 * Perform the actions of a page purging
957 public function doPurge() {
960 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
964 // Invalidate the cache
965 $this->mTitle
->invalidateCache();
969 // Commit the transaction before the purge is sent
970 $dbw = wfGetDB( DB_MASTER
);
971 $dbw->commit( __METHOD__
);
974 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
978 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
979 if ( $this->mTitle
->exists() ) {
980 $text = $this->getNativeData(); #FIXME: may not be a string. check Content model!
985 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
991 * Insert a new empty page record for this article.
992 * This *must* be followed up by creating a revision
993 * and running $this->updateRevisionOn( ... );
994 * or else the record will be left in a funky state.
995 * Best if all done inside a transaction.
997 * @param $dbw DatabaseBase
998 * @return int The newly created page_id key, or false if the title already existed
1000 public function insertOn( $dbw ) {
1001 wfProfileIn( __METHOD__
);
1003 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1004 $dbw->insert( 'page', array(
1005 'page_id' => $page_id,
1006 'page_namespace' => $this->mTitle
->getNamespace(),
1007 'page_title' => $this->mTitle
->getDBkey(),
1008 'page_counter' => 0,
1009 'page_restrictions' => '',
1010 'page_is_redirect' => 0, # Will set this shortly...
1012 'page_random' => wfRandom(),
1013 'page_touched' => $dbw->timestamp(),
1014 'page_latest' => 0, # Fill this in shortly...
1015 'page_len' => 0, # Fill this in shortly...
1016 ), __METHOD__
, 'IGNORE' );
1018 $affected = $dbw->affectedRows();
1021 $newid = $dbw->insertId();
1022 $this->mTitle
->resetArticleID( $newid );
1024 wfProfileOut( __METHOD__
);
1026 return $affected ?
$newid : false;
1030 * Update the page record to point to a newly saved revision.
1032 * @param $dbw DatabaseBase: object
1033 * @param $revision Revision: For ID number, and text used to set
1034 * length and redirect status fields
1035 * @param $lastRevision Integer: if given, will not overwrite the page field
1036 * when different from the currently set value.
1037 * Giving 0 indicates the new page flag should be set
1039 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1040 * removing rows in redirect table.
1041 * @return bool true on success, false on failure
1044 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1045 wfProfileIn( __METHOD__
);
1047 $content = $revision->getContent();
1048 $len = $content->getSize();
1049 $rt = $content->getUltimateRedirectTarget();
1051 $conditions = array( 'page_id' => $this->getId() );
1053 if ( !is_null( $lastRevision ) ) {
1054 # An extra check against threads stepping on each other
1055 $conditions['page_latest'] = $lastRevision;
1058 $now = wfTimestampNow();
1059 $dbw->update( 'page',
1061 'page_latest' => $revision->getId(),
1062 'page_touched' => $dbw->timestamp( $now ),
1063 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1064 'page_is_redirect' => $rt !== null ?
1 : 0,
1066 'page_content_model' => $revision->getContentModelName(),
1071 $result = $dbw->affectedRows() != 0;
1073 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1074 $this->setLastEdit( $revision );
1075 $this->setCachedLastEditTime( $now );
1076 $this->mLatest
= $revision->getId();
1077 $this->mIsRedirect
= (bool)$rt;
1078 # Update the LinkCache.
1079 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1082 wfProfileOut( __METHOD__
);
1087 * Add row to the redirect table if this is a redirect, remove otherwise.
1089 * @param $dbw DatabaseBase
1090 * @param $redirectTitle Title object pointing to the redirect target,
1091 * or NULL if this is not a redirect
1092 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1093 * removing rows in redirect table.
1094 * @return bool true on success, false on failure
1097 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1098 // Always update redirects (target link might have changed)
1099 // Update/Insert if we don't know if the last revision was a redirect or not
1100 // Delete if changing from redirect to non-redirect
1101 $isRedirect = !is_null( $redirectTitle );
1103 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1107 wfProfileIn( __METHOD__
);
1108 if ( $isRedirect ) {
1109 $this->insertRedirectEntry( $redirectTitle );
1111 // This is not a redirect, remove row from redirect table
1112 $where = array( 'rd_from' => $this->getId() );
1113 $dbw->delete( 'redirect', $where, __METHOD__
);
1116 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1117 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1119 wfProfileOut( __METHOD__
);
1121 return ( $dbw->affectedRows() != 0 );
1125 * If the given revision is newer than the currently set page_latest,
1126 * update the page record. Otherwise, do nothing.
1128 * @param $dbw DatabaseBase object
1129 * @param $revision Revision object
1132 public function updateIfNewerOn( $dbw, $revision ) {
1133 wfProfileIn( __METHOD__
);
1135 $row = $dbw->selectRow(
1136 array( 'revision', 'page' ),
1137 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1139 'page_id' => $this->getId(),
1140 'page_latest=rev_id' ),
1144 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1145 wfProfileOut( __METHOD__
);
1148 $prev = $row->rev_id
;
1149 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1151 # No or missing previous revision; mark the page as new
1153 $lastRevIsRedirect = null;
1156 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1158 wfProfileOut( __METHOD__
);
1163 * Get the text that needs to be saved in order to undo all revisions
1164 * between $undo and $undoafter. Revisions must belong to the same page,
1165 * must exist and must not be deleted
1166 * @param $undo Revision
1167 * @param $undoafter Revision Must be an earlier revision than $undo
1168 * @return mixed string on success, false on failure
1169 * @deprecated since 1.20: use ContentHandler::getUndoContent() instead.
1171 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) { #FIXME: replace usages.
1172 wfDeprecated( __METHOD__
, '1.20' );
1174 $this->loadLastEdit();
1176 if ( $this->mLastRevision
) {
1177 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1178 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1183 return ContentHandler
::getContentText( $undone );
1191 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1192 * @param $text String: new text of the section
1193 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1194 * @param $edittime String: revision timestamp or null to use the current revision
1195 * @return Content new complete article content, or null if error
1196 * @deprecated since 1.20, use replaceSectionContent() instead
1198 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) { #FIXME: use replaceSectionContent() instead!
1199 wfDeprecated( __METHOD__
, '1.20' );
1201 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1203 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1205 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1208 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1209 wfProfileIn( __METHOD__
);
1211 if ( strval( $section ) == '' ) {
1212 // Whole-page edit; let the whole text through
1213 $newContent = $sectionContent;
1215 // Bug 30711: always use current version when adding a new section
1216 if ( is_null( $edittime ) ||
$section == 'new' ) {
1217 $oldContent = $this->getContent();
1218 if ( ! $oldContent ) {
1219 wfDebug( __METHOD__
. ": no page text\n" );
1220 wfProfileOut( __METHOD__
);
1224 $dbw = wfGetDB( DB_MASTER
);
1225 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1228 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1229 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1230 wfProfileOut( __METHOD__
);
1234 $oldContent = $rev->getContent();
1237 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1240 wfProfileOut( __METHOD__
);
1245 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1247 * @return Int updated $flags
1249 function checkFlags( $flags ) {
1250 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1251 if ( $this->mTitle
->getArticleID() ) {
1252 $flags |
= EDIT_UPDATE
;
1262 * Change an existing article or create a new article. Updates RC and all necessary caches,
1263 * optionally via the deferred update array.
1265 * @param $text String: new text
1266 * @param $summary String: edit summary
1267 * @param $flags Integer bitfield:
1269 * Article is known or assumed to be non-existent, create a new one
1271 * Article is known or assumed to be pre-existing, update it
1273 * Mark this edit minor, if the user is allowed to do so
1275 * Do not log the change in recentchanges
1277 * Mark the edit a "bot" edit regardless of user rights
1278 * EDIT_DEFER_UPDATES
1279 * Defer some of the updates until the end of index.php
1281 * Fill in blank summaries with generated text where possible
1283 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1284 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1285 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1286 * edit-already-exists error will be returned. These two conditions are also possible with
1287 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1289 * @param $baseRevId int the revision ID this edit was based off, if any
1290 * @param $user User the user doing the edit
1292 * @return Status object. Possible errors:
1293 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1294 * edit-gone-missing: In update mode, but the article didn't exist
1295 * edit-conflict: In update mode, the article changed unexpectedly
1296 * edit-no-change: Warning that the text was the same as before
1297 * edit-already-exists: In creation mode, but the article already exists
1299 * Extensions may define additional errors.
1301 * $return->value will contain an associative array with members as follows:
1302 * new: Boolean indicating if the function attempted to create a new article
1303 * revision: The revision object for the inserted revision, or null
1305 * Compatibility note: this function previously returned a boolean value indicating success/failure
1306 * @deprecated since 1.20: use doEditContent() instead.
1308 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #FIXME: use doEditContent() instead
1309 #TODO: log use of deprecated function
1310 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1312 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1316 * Change an existing article or create a new article. Updates RC and all necessary caches,
1317 * optionally via the deferred update array.
1319 * @param $content Content: new content
1320 * @param $summary String: edit summary
1321 * @param $flags Integer bitfield:
1323 * Article is known or assumed to be non-existent, create a new one
1325 * Article is known or assumed to be pre-existing, update it
1327 * Mark this edit minor, if the user is allowed to do so
1329 * Do not log the change in recentchanges
1331 * Mark the edit a "bot" edit regardless of user rights
1332 * EDIT_DEFER_UPDATES
1333 * Defer some of the updates until the end of index.php
1335 * Fill in blank summaries with generated text where possible
1337 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1338 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1339 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1340 * edit-already-exists error will be returned. These two conditions are also possible with
1341 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1343 * @param $baseRevId the revision ID this edit was based off, if any
1344 * @param $user User the user doing the edit
1345 * @param $serialisation_format String: format for storing the content in the database
1347 * @return Status object. Possible errors:
1348 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1349 * edit-gone-missing: In update mode, but the article didn't exist
1350 * edit-conflict: In update mode, the article changed unexpectedly
1351 * edit-no-change: Warning that the text was the same as before
1352 * edit-already-exists: In creation mode, but the article already exists
1354 * Extensions may define additional errors.
1356 * $return->value will contain an associative array with members as follows:
1357 * new: Boolean indicating if the function attempted to create a new article
1358 * revision: The revision object for the inserted revision, or null
1360 * Compatibility note: this function previously returned a boolean value indicating success/failure
1362 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1363 User
$user = null, $serialisation_format = null ) { #FIXME: use this
1364 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1366 # Low-level sanity check
1367 if ( $this->mTitle
->getText() === '' ) {
1368 throw new MWException( 'Something is trying to edit an article with an empty title' );
1371 wfProfileIn( __METHOD__
);
1373 $user = is_null( $user ) ?
$wgUser : $user;
1374 $status = Status
::newGood( array() );
1376 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1377 $this->loadPageData( 'fromdbmaster' );
1379 $flags = $this->checkFlags( $flags );
1382 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary, #FIXME: document new hook!
1383 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1385 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { # avoid serialization overhead if the hook isn't present
1386 $content_text = $content->serialize();
1387 $txt = $content_text; # clone
1389 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary, #FIXME: deprecate legacy hook!
1390 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1392 if ( $txt !== $content_text ) {
1393 # if the text changed, unserialize the new version to create an updated Content object.
1394 $content = $content->getContentHandler()->unserializeContent( $txt );
1399 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1401 if ( $status->isOK() ) {
1402 $status->fatal( 'edit-hook-aborted' );
1405 wfProfileOut( __METHOD__
);
1409 # Silently ignore EDIT_MINOR if not allowed
1410 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1411 $bot = $flags & EDIT_FORCE_BOT
;
1413 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1415 $oldsize = $old_content ?
$old_content->getSize() : 0;
1416 $oldid = $this->getLatest();
1417 $oldIsRedirect = $this->isRedirect();
1418 $oldcountable = $this->isCountable();
1420 $handler = $content->getContentHandler();
1422 # Provide autosummaries if one is not provided and autosummaries are enabled.
1423 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1424 if ( !$old_content ) $old_content = null;
1425 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1428 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1429 $serialized = $editInfo->pst
;
1430 $content = $editInfo->pstContent
;
1431 $newsize = $content->getSize();
1433 $dbw = wfGetDB( DB_MASTER
);
1434 $now = wfTimestampNow();
1435 $this->mTimestamp
= $now;
1437 if ( $flags & EDIT_UPDATE
) {
1438 # Update article, but only if changed.
1439 $status->value
['new'] = false;
1442 # Article gone missing
1443 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1444 $status->fatal( 'edit-gone-missing' );
1446 wfProfileOut( __METHOD__
);
1450 # Make sure the revision is either completely inserted or not inserted at all
1451 if ( !$wgDBtransactions ) {
1452 $userAbort = ignore_user_abort( true );
1455 $revision = new Revision( array(
1456 'page' => $this->getId(),
1457 'comment' => $summary,
1458 'minor_edit' => $isminor,
1459 'text' => $serialized,
1461 'parent_id' => $oldid,
1462 'user' => $user->getId(),
1463 'user_text' => $user->getName(),
1464 'timestamp' => $now,
1465 'content_model' => $content->getModelName(),
1466 'content_format' => $serialisation_format,
1469 $changed = !$content->equals( $old_content );
1472 $dbw->begin( __METHOD__
);
1473 $revisionId = $revision->insertOn( $dbw );
1477 # Note that we use $this->mLatest instead of fetching a value from the master DB
1478 # during the course of this function. This makes sure that EditPage can detect
1479 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1480 # before this function is called. A previous function used a separate query, this
1481 # creates a window where concurrent edits can cause an ignored edit conflict.
1482 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1485 /* Belated edit conflict! Run away!! */
1486 $status->fatal( 'edit-conflict' );
1488 # Delete the invalid revision if the DB is not transactional
1489 if ( !$wgDBtransactions ) {
1490 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1494 $dbw->rollback( __METHOD__
);
1496 global $wgUseRCPatrol;
1497 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1498 # Update recentchanges
1499 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1500 # Mark as patrolled if the user can do so
1501 $patrolled = $wgUseRCPatrol && !count(
1502 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1503 # Add RC row to the DB
1504 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1505 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1506 $revisionId, $patrolled
1509 # Log auto-patrolled edits
1511 PatrolLog
::record( $rc, true, $user );
1514 $user->incEditCount();
1515 $dbw->commit( __METHOD__
);
1518 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1519 // related variables correctly
1520 $revision->setId( $this->getLatest() );
1523 if ( !$wgDBtransactions ) {
1524 ignore_user_abort( $userAbort );
1527 // Now that ignore_user_abort is restored, we can respond to fatal errors
1528 if ( !$status->isOK() ) {
1529 wfProfileOut( __METHOD__
);
1533 # Update links tables, site stats, etc.
1534 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1535 'oldcountable' => $oldcountable ) );
1538 $status->warning( 'edit-no-change' );
1540 // Update page_touched, this is usually implicit in the page update
1541 // Other cache updates are done in onArticleEdit()
1542 $this->mTitle
->invalidateCache();
1545 # Create new article
1546 $status->value
['new'] = true;
1548 $dbw->begin( __METHOD__
);
1550 # Add the page record; stake our claim on this title!
1551 # This will return false if the article already exists
1552 $newid = $this->insertOn( $dbw );
1554 if ( $newid === false ) {
1555 $dbw->rollback( __METHOD__
);
1556 $status->fatal( 'edit-already-exists' );
1558 wfProfileOut( __METHOD__
);
1562 # Save the revision text...
1563 $revision = new Revision( array(
1565 'comment' => $summary,
1566 'minor_edit' => $isminor,
1567 'text' => $serialized,
1569 'user' => $user->getId(),
1570 'user_text' => $user->getName(),
1571 'timestamp' => $now,
1572 'content_model' => $content->getModelName(),
1573 'content_format' => $serialisation_format,
1575 $revisionId = $revision->insertOn( $dbw );
1577 # Update the page record with revision data
1578 $this->updateRevisionOn( $dbw, $revision, 0 );
1580 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1582 # Update recentchanges
1583 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1584 global $wgUseRCPatrol, $wgUseNPPatrol;
1586 # Mark as patrolled if the user can do so
1587 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1588 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1589 # Add RC row to the DB
1590 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1591 '', $content->getSize(), $revisionId, $patrolled );
1593 # Log auto-patrolled edits
1595 PatrolLog
::record( $rc, true, $user );
1598 $user->incEditCount();
1599 $dbw->commit( __METHOD__
);
1601 # Update links, etc.
1602 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1604 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1605 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1607 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1608 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1611 # Do updates right now unless deferral was requested
1612 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1613 DeferredUpdates
::doUpdates();
1616 // Return the new revision (or null) to the caller
1617 $status->value
['revision'] = $revision;
1619 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1620 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1622 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1623 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1625 # Promote user to any groups they meet the criteria for
1626 $user->addAutopromoteOnceGroups( 'onEdit' );
1628 wfProfileOut( __METHOD__
);
1633 * Get parser options suitable for rendering the primary article wikitext
1634 * @param User|string $user User object or 'canonical'
1635 * @return ParserOptions
1637 public function makeParserOptions( $user ) {
1639 if ( $user instanceof User
) { // settings per user (even anons)
1640 $options = ParserOptions
::newFromUser( $user );
1641 } else { // canonical settings
1642 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1644 $options->enableLimitReport(); // show inclusion/loop reports
1645 $options->setTidy( true ); // fix bad HTML
1650 * Prepare text which is about to be saved.
1651 * Returns a stdclass with source, pst and output members
1652 * @deprecated in 1.20: use prepareContentForEdit instead.
1654 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) { #FIXME: use prepareContentForEdit() instead #XXX: who uses this?!
1655 #TODO: log use of deprecated function
1656 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1657 return $this->prepareContentForEdit( $content, $revid , $user );
1661 * Prepare content which is about to be saved.
1662 * Returns a stdclass with source, pst and output members
1664 * @param \Content $content
1665 * @param null $revid
1666 * @param null|\User $user
1667 * @param null $serialization_format
1668 * @return bool|object
1670 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) { #FIXME: use this #XXX: really public?!
1671 global $wgParser, $wgContLang, $wgUser;
1672 $user = is_null( $user ) ?
$wgUser : $user;
1673 // @TODO fixme: check $user->getId() here???
1675 if ( $this->mPreparedEdit
1676 && $this->mPreparedEdit
->newContent
1677 && $this->mPreparedEdit
->newContent
->equals( $content )
1678 && $this->mPreparedEdit
->revid
== $revid
1679 && $this->mPreparedEdit
->format
== $serialization_format
1680 #XXX: also check $user here?
1683 return $this->mPreparedEdit
;
1686 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1687 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1689 $edit = (object)array();
1690 $edit->revid
= $revid;
1692 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1693 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1694 $edit->format
= $serialization_format;
1696 $edit->popts
= $this->makeParserOptions( 'canonical' );
1698 // TODO: is there no better way to obtain a context here?
1699 $context = RequestContext
::getMain();
1700 $context->setTitle( $this->mTitle
);
1701 $edit->output
= $edit->pstContent
->getParserOutput( $context, $revid, $edit->popts
);
1703 $edit->newContent
= $content;
1704 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1706 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1707 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1709 $this->mPreparedEdit
= $edit;
1715 * Do standard deferred updates after page edit.
1716 * Update links tables, site stats, search index and message cache.
1717 * Purges pages that include this page if the text was changed here.
1718 * Every 100th edit, prune the recent changes table.
1721 * @param $revision Revision object
1722 * @param $user User object that did the revision
1723 * @param $options Array of options, following indexes are used:
1724 * - changed: boolean, whether the revision changed the content (default true)
1725 * - created: boolean, whether the revision created the page (default false)
1726 * - oldcountable: boolean or null (default null):
1727 * - boolean: whether the page was counted as an article before that
1728 * revision, only used in changed is true and created is false
1729 * - null: don't change the article count
1731 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1732 global $wgEnableParserCache;
1734 wfProfileIn( __METHOD__
);
1736 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1737 $content = $revision->getContent();
1740 # Be careful not to double-PST: $text is usually already PST-ed once
1741 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1742 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1743 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1745 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1746 $editInfo = $this->mPreparedEdit
;
1749 # Save it to the parser cache
1750 if ( $wgEnableParserCache ) {
1751 $parserCache = ParserCache
::singleton();
1752 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1755 # Update the links tables and other secondary data
1756 $updates = $editInfo->output
->getSecondaryDataUpdates( $this->mTitle
);
1757 SecondaryDataUpdate
::runUpdates( $updates );
1759 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1761 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1762 if ( 0 == mt_rand( 0, 99 ) ) {
1763 // Flush old entries from the `recentchanges` table; we do this on
1764 // random requests so as to avoid an increase in writes for no good reason
1767 $dbw = wfGetDB( DB_MASTER
);
1768 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1771 array( "rc_timestamp < '$cutoff'" ),
1777 if ( !$this->mTitle
->exists() ) {
1778 wfProfileOut( __METHOD__
);
1782 $id = $this->getId();
1783 $title = $this->mTitle
->getPrefixedDBkey();
1784 $shortTitle = $this->mTitle
->getDBkey();
1786 if ( !$options['changed'] ) {
1789 } elseif ( $options['created'] ) {
1790 $good = (int)$this->isCountable( $editInfo );
1792 } elseif ( $options['oldcountable'] !== null ) {
1793 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1800 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1801 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
1803 # If this is another user's talk page, update newtalk.
1804 # Don't do this if $options['changed'] = false (null-edits) nor if
1805 # it's a minor edit and the user doesn't want notifications for those.
1806 if ( $options['changed']
1807 && $this->mTitle
->getNamespace() == NS_USER_TALK
1808 && $shortTitle != $user->getTitleKey()
1809 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1811 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1812 $other = User
::newFromName( $shortTitle, false );
1814 wfDebug( __METHOD__
. ": invalid username\n" );
1815 } elseif ( User
::isIP( $shortTitle ) ) {
1816 // An anonymous user
1817 $other->setNewtalk( true );
1818 } elseif ( $other->isLoggedIn() ) {
1819 $other->setNewtalk( true );
1821 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1826 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1827 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
1828 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
1830 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
1833 if( $options['created'] ) {
1834 self
::onArticleCreate( $this->mTitle
);
1836 self
::onArticleEdit( $this->mTitle
);
1839 wfProfileOut( __METHOD__
);
1843 * Edit an article without doing all that other stuff
1844 * The article must already exist; link tables etc
1845 * are not updated, caches are not flushed.
1847 * @param $text String: text submitted
1848 * @param $user User The relevant user
1849 * @param $comment String: comment submitted
1850 * @param $minor Boolean: whereas it's a minor modification
1852 * @deprecated since 1.20, use doEditContent() instead.
1854 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1855 wfDeprecated( __METHOD__
, "1.20" );
1857 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1858 return $this->doQuickEditContent( $content, $user, $comment , $minor );
1862 * Edit an article without doing all that other stuff
1863 * The article must already exist; link tables etc
1864 * are not updated, caches are not flushed.
1866 * @param $content Content: content submitted
1867 * @param $user User The relevant user
1868 * @param $comment String: comment submitted
1869 * @param $serialisation_format String: format for storing the content in the database
1870 * @param $minor Boolean: whereas it's a minor modification
1872 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
1873 wfProfileIn( __METHOD__
);
1875 $serialized = $content->serialize( $serialisation_format );
1877 $dbw = wfGetDB( DB_MASTER
);
1878 $revision = new Revision( array(
1879 'page' => $this->getId(),
1880 'text' => $serialized,
1881 'length' => $content->getSize(),
1882 'comment' => $comment,
1883 'minor_edit' => $minor ?
1 : 0,
1885 $revision->insertOn( $dbw );
1886 $this->updateRevisionOn( $dbw, $revision );
1888 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1890 wfProfileOut( __METHOD__
);
1894 * Update the article's restriction field, and leave a log entry.
1895 * This works for protection both existing and non-existing pages.
1897 * @param $limit Array: set of restriction keys
1898 * @param $reason String
1899 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1900 * @param $expiry Array: per restriction type expiration
1901 * @param $user User The user updating the restrictions
1902 * @return bool true on success
1904 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1907 if ( wfReadOnly() ) {
1908 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1911 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1913 $id = $this->mTitle
->getArticleID();
1919 // Take this opportunity to purge out expired restrictions
1920 Title
::purgeExpiredRestrictions();
1922 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1923 # we expect a single selection, but the schema allows otherwise.
1924 $isProtected = false;
1928 $dbw = wfGetDB( DB_MASTER
);
1930 foreach ( $restrictionTypes as $action ) {
1931 if ( !isset( $expiry[$action] ) ) {
1932 $expiry[$action] = $dbw->getInfinity();
1934 if ( !isset( $limit[$action] ) ) {
1935 $limit[$action] = '';
1936 } elseif ( $limit[$action] != '' ) {
1940 # Get current restrictions on $action
1941 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1942 if ( $current != '' ) {
1943 $isProtected = true;
1946 if ( $limit[$action] != $current ) {
1948 } elseif ( $limit[$action] != '' ) {
1949 # Only check expiry change if the action is actually being
1950 # protected, since expiry does nothing on an not-protected
1952 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1958 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1962 # If nothing's changed, do nothing
1964 return Status
::newGood();
1967 if ( !$protect ) { # No protection at all means unprotection
1968 $revCommentMsg = 'unprotectedarticle';
1969 $logAction = 'unprotect';
1970 } elseif ( $isProtected ) {
1971 $revCommentMsg = 'modifiedarticleprotection';
1972 $logAction = 'modify';
1974 $revCommentMsg = 'protectedarticle';
1975 $logAction = 'protect';
1978 $encodedExpiry = array();
1979 $protectDescription = '';
1980 foreach ( $limit as $action => $restrictions ) {
1981 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1982 if ( $restrictions != '' ) {
1983 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1984 if ( $encodedExpiry[$action] != 'infinity' ) {
1985 $protectDescription .= wfMsgForContent( 'protect-expiring',
1986 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1987 $wgContLang->date( $expiry[$action], false, false ) ,
1988 $wgContLang->time( $expiry[$action], false, false ) );
1990 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1993 $protectDescription .= ') ';
1996 $protectDescription = trim( $protectDescription );
1998 if ( $id ) { # Protection of existing page
1999 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2000 return Status
::newGood();
2003 # Only restrictions with the 'protect' right can cascade...
2004 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2005 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2007 # The schema allows multiple restrictions
2008 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2012 # Update restrictions table
2013 foreach ( $limit as $action => $restrictions ) {
2014 if ( $restrictions != '' ) {
2015 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2016 array( 'pr_page' => $id,
2017 'pr_type' => $action,
2018 'pr_level' => $restrictions,
2019 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2020 'pr_expiry' => $encodedExpiry[$action]
2025 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2026 'pr_type' => $action ), __METHOD__
);
2030 # Prepare a null revision to be added to the history
2031 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2033 $editComment .= ": $reason";
2035 if ( $protectDescription ) {
2036 $editComment .= " ($protectDescription)";
2039 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2042 # Insert a null revision
2043 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2044 $nullRevId = $nullRevision->insertOn( $dbw );
2046 $latest = $this->getLatest();
2047 # Update page record
2048 $dbw->update( 'page',
2050 'page_touched' => $dbw->timestamp(),
2051 'page_restrictions' => '',
2052 'page_latest' => $nullRevId
2053 ), array( /* WHERE */
2058 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2059 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2060 } else { # Protection of non-existing page (also known as "title protection")
2061 # Cascade protection is meaningless in this case
2064 if ( $limit['create'] != '' ) {
2065 $dbw->replace( 'protected_titles',
2066 array( array( 'pt_namespace', 'pt_title' ) ),
2068 'pt_namespace' => $this->mTitle
->getNamespace(),
2069 'pt_title' => $this->mTitle
->getDBkey(),
2070 'pt_create_perm' => $limit['create'],
2071 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2072 'pt_expiry' => $encodedExpiry['create'],
2073 'pt_user' => $user->getId(),
2074 'pt_reason' => $reason,
2078 $dbw->delete( 'protected_titles',
2080 'pt_namespace' => $this->mTitle
->getNamespace(),
2081 'pt_title' => $this->mTitle
->getDBkey()
2087 $this->mTitle
->flushRestrictions();
2089 if ( $logAction == 'unprotect' ) {
2090 $logParams = array();
2092 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2095 # Update the protection log
2096 $log = new LogPage( 'protect' );
2097 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2099 return Status
::newGood();
2103 * Take an array of page restrictions and flatten it to a string
2104 * suitable for insertion into the page_restrictions field.
2105 * @param $limit Array
2108 protected static function flattenRestrictions( $limit ) {
2109 if ( !is_array( $limit ) ) {
2110 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2116 foreach ( $limit as $action => $restrictions ) {
2117 if ( $restrictions != '' ) {
2118 $bits[] = "$action=$restrictions";
2122 return implode( ':', $bits );
2126 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2127 * Deletes the article with database consistency, writes logs, purges caches
2129 * @param $reason string delete reason for deletion log
2130 * @param $suppress int bitfield
2131 * Revision::DELETED_TEXT
2132 * Revision::DELETED_COMMENT
2133 * Revision::DELETED_USER
2134 * Revision::DELETED_RESTRICTED
2135 * @param $id int article ID
2136 * @param $commit boolean defaults to true, triggers transaction end
2137 * @param &$error Array of errors to append to
2138 * @param $user User The deleting user
2139 * @return boolean true if successful
2141 public function doDeleteArticle(
2142 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2144 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2145 == WikiPage
::DELETE_SUCCESS
;
2149 * Back-end article deletion
2150 * Deletes the article with database consistency, writes logs, purges caches
2152 * @param $reason string delete reason for deletion log
2153 * @param $suppress int bitfield
2154 * Revision::DELETED_TEXT
2155 * Revision::DELETED_COMMENT
2156 * Revision::DELETED_USER
2157 * Revision::DELETED_RESTRICTED
2158 * @param $id int article ID
2159 * @param $commit boolean defaults to true, triggers transaction end
2160 * @param &$error Array of errors to append to
2161 * @param $user User The deleting user
2162 * @return int: One of WikiPage::DELETE_* constants
2164 public function doDeleteArticleReal(
2165 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2168 $user = is_null( $user ) ?
$wgUser : $user;
2170 wfDebug( __METHOD__
. "\n" );
2172 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2173 return WikiPage
::DELETE_HOOK_ABORTED
;
2175 $dbw = wfGetDB( DB_MASTER
);
2176 $t = $this->mTitle
->getDBkey();
2177 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2179 if ( $t === '' ||
$id == 0 ) {
2180 return WikiPage
::DELETE_NO_PAGE
;
2183 // Bitfields to further suppress the content
2186 // This should be 15...
2187 $bitfield |
= Revision
::DELETED_TEXT
;
2188 $bitfield |
= Revision
::DELETED_COMMENT
;
2189 $bitfield |
= Revision
::DELETED_USER
;
2190 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2192 $bitfield = 'rev_deleted';
2195 $dbw->begin( __METHOD__
);
2196 // For now, shunt the revision data into the archive table.
2197 // Text is *not* removed from the text table; bulk storage
2198 // is left intact to avoid breaking block-compression or
2199 // immutable storage schemes.
2201 // For backwards compatibility, note that some older archive
2202 // table entries will have ar_text and ar_flags fields still.
2204 // In the future, we may keep revisions and mark them with
2205 // the rev_deleted field, which is reserved for this purpose.
2206 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2208 'ar_namespace' => 'page_namespace',
2209 'ar_title' => 'page_title',
2210 'ar_comment' => 'rev_comment',
2211 'ar_user' => 'rev_user',
2212 'ar_user_text' => 'rev_user_text',
2213 'ar_timestamp' => 'rev_timestamp',
2214 'ar_minor_edit' => 'rev_minor_edit',
2215 'ar_rev_id' => 'rev_id',
2216 'ar_parent_id' => 'rev_parent_id',
2217 'ar_text_id' => 'rev_text_id',
2218 'ar_text' => '\'\'', // Be explicit to appease
2219 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2220 'ar_len' => 'rev_len',
2221 'ar_page_id' => 'page_id',
2222 'ar_deleted' => $bitfield,
2223 'ar_sha1' => 'rev_content_model',
2224 'ar_content_format' => 'rev_content_format',
2225 'ar_content_format' => 'rev_sha1'
2228 'page_id = rev_page'
2232 # Now that it's safely backed up, delete it
2233 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2234 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2237 $dbw->rollback( __METHOD__
);
2238 return WikiPage
::DELETE_NO_REVISIONS
;
2241 $this->doDeleteUpdates( $id );
2243 # Log the deletion, if the page was suppressed, log it at Oversight instead
2244 $logtype = $suppress ?
'suppress' : 'delete';
2246 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2247 $logEntry->setPerformer( $user );
2248 $logEntry->setTarget( $this->mTitle
);
2249 $logEntry->setComment( $reason );
2250 $logid = $logEntry->insert();
2251 $logEntry->publish( $logid );
2254 $dbw->commit( __METHOD__
);
2257 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2258 return WikiPage
::DELETE_SUCCESS
;
2262 * Do some database updates after deletion
2264 * @param $id Int: page_id value of the page being deleted
2266 public function doDeleteUpdates( $id ) {
2267 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2269 $dbw = wfGetDB( DB_MASTER
);
2271 # Delete restrictions for it
2272 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2274 # Fix category table counts
2276 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2278 foreach ( $res as $row ) {
2279 $cats [] = $row->cl_to
;
2282 $this->updateCategoryCounts( array(), $cats );
2284 #TODO: move this to an Update object!
2286 # If using cascading deletes, we can skip some explicit deletes
2287 if ( !$dbw->cascadingDeletes() ) {
2288 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2290 # Delete outgoing links
2291 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2292 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2293 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2294 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2295 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2296 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2297 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2298 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2299 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2302 # If using cleanup triggers, we can skip some manual deletes
2303 if ( !$dbw->cleanupTriggers() ) {
2304 # Clean up recentchanges entries...
2305 $dbw->delete( 'recentchanges',
2306 array( 'rc_type != ' . RC_LOG
,
2307 'rc_namespace' => $this->mTitle
->getNamespace(),
2308 'rc_title' => $this->mTitle
->getDBkey() ),
2310 $dbw->delete( 'recentchanges',
2311 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2316 self
::onArticleDelete( $this->mTitle
);
2321 # Clear the cached article id so the interface doesn't act like we exist
2322 $this->mTitle
->resetArticleID( 0 );
2326 * Roll back the most recent consecutive set of edits to a page
2327 * from the same user; fails if there are no eligible edits to
2328 * roll back to, e.g. user is the sole contributor. This function
2329 * performs permissions checks on $user, then calls commitRollback()
2330 * to do the dirty work
2332 * @todo: seperate the business/permission stuff out from backend code
2334 * @param $fromP String: Name of the user whose edits to rollback.
2335 * @param $summary String: Custom summary. Set to default summary if empty.
2336 * @param $token String: Rollback token.
2337 * @param $bot Boolean: If true, mark all reverted edits as bot.
2339 * @param $resultDetails Array: contains result-specific array of additional values
2340 * 'alreadyrolled' : 'current' (rev)
2341 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2343 * @param $user User The user performing the rollback
2344 * @return array of errors, each error formatted as
2345 * array(messagekey, param1, param2, ...).
2346 * On success, the array is empty. This array can also be passed to
2347 * OutputPage::showPermissionsErrorPage().
2349 public function doRollback(
2350 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2352 $resultDetails = null;
2355 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2356 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2357 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2359 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2360 $errors[] = array( 'sessionfailure' );
2363 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2364 $errors[] = array( 'actionthrottledtext' );
2367 # If there were errors, bail out now
2368 if ( !empty( $errors ) ) {
2372 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2376 * Backend implementation of doRollback(), please refer there for parameter
2377 * and return value documentation
2379 * NOTE: This function does NOT check ANY permissions, it just commits the
2380 * rollback to the DB. Therefore, you should only call this function direct-
2381 * ly if you want to use custom permissions checks. If you don't, use
2382 * doRollback() instead.
2383 * @param $fromP String: Name of the user whose edits to rollback.
2384 * @param $summary String: Custom summary. Set to default summary if empty.
2385 * @param $bot Boolean: If true, mark all reverted edits as bot.
2387 * @param $resultDetails Array: contains result-specific array of additional values
2388 * @param $guser User The user performing the rollback
2391 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2392 global $wgUseRCPatrol, $wgContLang;
2394 $dbw = wfGetDB( DB_MASTER
);
2396 if ( wfReadOnly() ) {
2397 return array( array( 'readonlytext' ) );
2400 # Get the last editor
2401 $current = $this->getRevision();
2402 if ( is_null( $current ) ) {
2403 # Something wrong... no page?
2404 return array( array( 'notanarticle' ) );
2407 $from = str_replace( '_', ' ', $fromP );
2408 # User name given should match up with the top revision.
2409 # If the user was deleted then $from should be empty.
2410 if ( $from != $current->getUserText() ) {
2411 $resultDetails = array( 'current' => $current );
2412 return array( array( 'alreadyrolled',
2413 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2414 htmlspecialchars( $fromP ),
2415 htmlspecialchars( $current->getUserText() )
2419 # Get the last edit not by this guy...
2420 # Note: these may not be public values
2421 $user = intval( $current->getRawUser() );
2422 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2423 $s = $dbw->selectRow( 'revision',
2424 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2425 array( 'rev_page' => $current->getPage(),
2426 "rev_user != {$user} OR rev_user_text != {$user_text}"
2428 array( 'USE INDEX' => 'page_timestamp',
2429 'ORDER BY' => 'rev_timestamp DESC' )
2431 if ( $s === false ) {
2432 # No one else ever edited this page
2433 return array( array( 'cantrollback' ) );
2434 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2435 # Only admins can see this text
2436 return array( array( 'notvisiblerev' ) );
2440 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2441 # Mark all reverted edits as bot
2445 if ( $wgUseRCPatrol ) {
2446 # Mark all reverted edits as patrolled
2447 $set['rc_patrolled'] = 1;
2450 if ( count( $set ) ) {
2451 $dbw->update( 'recentchanges', $set,
2453 'rc_cur_id' => $current->getPage(),
2454 'rc_user_text' => $current->getUserText(),
2455 "rc_timestamp > '{$s->rev_timestamp}'",
2460 # Generate the edit summary if necessary
2461 $target = Revision
::newFromId( $s->rev_id
);
2462 if ( empty( $summary ) ) {
2463 if ( $from == '' ) { // no public user name
2464 $summary = wfMsgForContent( 'revertpage-nouser' );
2466 $summary = wfMsgForContent( 'revertpage' );
2470 # Allow the custom summary to use the same args as the default message
2472 $target->getUserText(), $from, $s->rev_id
,
2473 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2474 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2476 $summary = wfMsgReplaceArgs( $summary, $args );
2479 $flags = EDIT_UPDATE
;
2481 if ( $guser->isAllowed( 'minoredit' ) ) {
2482 $flags |
= EDIT_MINOR
;
2485 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2486 $flags |
= EDIT_FORCE_BOT
;
2489 # Actually store the edit
2490 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2491 if ( !empty( $status->value
['revision'] ) ) {
2492 $revId = $status->value
['revision']->getId();
2497 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2499 $resultDetails = array(
2500 'summary' => $summary,
2501 'current' => $current,
2502 'target' => $target,
2510 * The onArticle*() functions are supposed to be a kind of hooks
2511 * which should be called whenever any of the specified actions
2514 * This is a good place to put code to clear caches, for instance.
2516 * This is called on page move and undelete, as well as edit
2518 * @param $title Title object
2520 public static function onArticleCreate( $title ) {
2521 # Update existence markers on article/talk tabs...
2522 if ( $title->isTalkPage() ) {
2523 $other = $title->getSubjectPage();
2525 $other = $title->getTalkPage();
2528 $other->invalidateCache();
2529 $other->purgeSquid();
2531 $title->touchLinks();
2532 $title->purgeSquid();
2533 $title->deleteTitleProtection();
2537 * Clears caches when article is deleted
2539 * @param $title Title
2541 public static function onArticleDelete( $title ) {
2542 # Update existence markers on article/talk tabs...
2543 if ( $title->isTalkPage() ) {
2544 $other = $title->getSubjectPage();
2546 $other = $title->getTalkPage();
2549 $other->invalidateCache();
2550 $other->purgeSquid();
2552 $title->touchLinks();
2553 $title->purgeSquid();
2556 HTMLFileCache
::clearFileCache( $title );
2559 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2560 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2564 if ( $title->getNamespace() == NS_FILE
) {
2565 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2566 $update->doUpdate();
2570 if ( $title->getNamespace() == NS_USER_TALK
) {
2571 $user = User
::newFromName( $title->getText(), false );
2573 $user->setNewtalk( false );
2578 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2582 * Purge caches on page update etc
2584 * @param $title Title object
2585 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2587 public static function onArticleEdit( $title ) {
2588 // Invalidate caches of articles which include this page
2589 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2592 // Invalidate the caches of all pages which redirect here
2593 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2595 # Purge squid for this page only
2596 $title->purgeSquid();
2598 # Clear file cache for this page only
2599 HTMLFileCache
::clearFileCache( $title );
2605 * Returns a list of hidden categories this page is a member of.
2606 * Uses the page_props and categorylinks tables.
2608 * @return Array of Title objects
2610 public function getHiddenCategories() {
2612 $id = $this->mTitle
->getArticleID();
2618 $dbr = wfGetDB( DB_SLAVE
);
2619 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2621 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2622 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2625 if ( $res !== false ) {
2626 foreach ( $res as $row ) {
2627 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2635 * Return an applicable autosummary if one exists for the given edit.
2636 * @param $oldtext String: the previous text of the page.
2637 * @param $newtext String: The submitted text of the page.
2638 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2639 * @return string An appropriate autosummary, or an empty string.
2640 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
2642 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2643 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2645 $handler = ContentHandler
::getForModelName( CONTENT_MODEL_WIKITEXT
);
2646 $oldContent = $oldtext ?
$handler->unserializeContent( $oldtext ) : null;
2647 $newContent = $newtext ?
$handler->unserializeContent( $newtext ) : null;
2649 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2653 * Auto-generates a deletion reason
2655 * @param &$hasHistory Boolean: whether the page has a history
2656 * @return mixed String containing deletion reason or empty string, or boolean false
2657 * if no revision occurred
2658 * @deprecated since 1.20, use ContentHandler::getAutoDeleteReason() instead
2660 public function getAutoDeleteReason( &$hasHistory ) {
2661 #NOTE: stub for backwards-compatibility.
2663 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2664 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2667 // Get the last revision
2668 $rev = $this->getRevision();
2670 if ( is_null( $rev ) ) {
2674 // Get the article's contents
2675 $contents = $rev->getText();
2678 // If the page is blank, use the text from the previous revision,
2679 // which can only be blank if there's a move/import/protect dummy revision involved
2680 if ( $contents == '' ) {
2681 $prev = $rev->getPrevious();
2684 $contents = $prev->getText();
2689 $dbw = wfGetDB( DB_MASTER
);
2691 // Find out if there was only one contributor
2692 // Only scan the last 20 revisions
2693 $res = $dbw->select( 'revision', 'rev_user_text',
2694 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2696 array( 'LIMIT' => 20 )
2699 if ( $res === false ) {
2700 // This page has no revisions, which is very weird
2704 $hasHistory = ( $res->numRows() > 1 );
2705 $row = $dbw->fetchObject( $res );
2707 if ( $row ) { // $row is false if the only contributor is hidden
2708 $onlyAuthor = $row->rev_user_text
;
2709 // Try to find a second contributor
2710 foreach ( $res as $row ) {
2711 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2712 $onlyAuthor = false;
2717 $onlyAuthor = false;
2720 // Generate the summary with a '$1' placeholder
2722 // The current revision is blank and the one before is also
2723 // blank. It's just not our lucky day
2724 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2726 if ( $onlyAuthor ) {
2727 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2729 $reason = wfMsgForContent( 'excontent', '$1' );
2733 if ( $reason == '-' ) {
2734 // Allow these UI messages to be blanked out cleanly
2738 // Replace newlines with spaces to prevent uglyness
2739 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2740 // Calculate the maximum amount of chars to get
2741 // Max content length = max comment length - length of the comment (excl. $1)
2742 $maxLength = 255 - ( strlen( $reason ) - 2 );
2743 $contents = $wgContLang->truncate( $contents, $maxLength );
2744 // Remove possible unfinished links
2745 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2746 // Now replace the '$1' placeholder
2747 $reason = str_replace( '$1', $contents, $reason );
2753 * Update all the appropriate counts in the category table, given that
2754 * we've added the categories $added and deleted the categories $deleted.
2756 * @param $added array The names of categories that were added
2757 * @param $deleted array The names of categories that were deleted
2759 public function updateCategoryCounts( $added, $deleted ) {
2760 $ns = $this->mTitle
->getNamespace();
2761 $dbw = wfGetDB( DB_MASTER
);
2763 # First make sure the rows exist. If one of the "deleted" ones didn't
2764 # exist, we might legitimately not create it, but it's simpler to just
2765 # create it and then give it a negative value, since the value is bogus
2768 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2769 $insertCats = array_merge( $added, $deleted );
2770 if ( !$insertCats ) {
2771 # Okay, nothing to do
2775 $insertRows = array();
2777 foreach ( $insertCats as $cat ) {
2778 $insertRows[] = array(
2779 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2783 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2785 $addFields = array( 'cat_pages = cat_pages + 1' );
2786 $removeFields = array( 'cat_pages = cat_pages - 1' );
2788 if ( $ns == NS_CATEGORY
) {
2789 $addFields[] = 'cat_subcats = cat_subcats + 1';
2790 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2791 } elseif ( $ns == NS_FILE
) {
2792 $addFields[] = 'cat_files = cat_files + 1';
2793 $removeFields[] = 'cat_files = cat_files - 1';
2800 array( 'cat_title' => $added ),
2809 array( 'cat_title' => $deleted ),
2816 * Updates cascading protections
2818 * @param $parserOutput ParserOutput object for the current version
2820 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2821 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2825 // templatelinks table may have become out of sync,
2826 // especially if using variable-based transclusions.
2827 // For paranoia, check if things have changed and if
2828 // so apply updates to the database. This will ensure
2829 // that cascaded protections apply as soon as the changes
2832 # Get templates from templatelinks
2833 $id = $this->mTitle
->getArticleID();
2835 $tlTemplates = array();
2837 $dbr = wfGetDB( DB_SLAVE
);
2838 $res = $dbr->select( array( 'templatelinks' ),
2839 array( 'tl_namespace', 'tl_title' ),
2840 array( 'tl_from' => $id ),
2844 foreach ( $res as $row ) {
2845 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2848 # Get templates from parser output.
2849 $poTemplates = array();
2850 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2851 foreach ( $templates as $dbk => $id ) {
2852 $poTemplates["$ns:$dbk"] = true;
2857 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2859 if ( count( $templates_diff ) > 0 ) {
2860 # Whee, link updates time.
2861 # Note: we are only interested in links here. We don't need to get other SecondaryDataUpdate items from the parser output.
2862 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2868 * Return a list of templates used by this article.
2869 * Uses the templatelinks table
2871 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2872 * @return Array of Title objects
2874 public function getUsedTemplates() {
2875 return $this->mTitle
->getTemplateLinksFrom();
2879 * Perform article updates on a special page creation.
2881 * @param $rev Revision object
2883 * @todo This is a shitty interface function. Kill it and replace the
2884 * other shitty functions like doEditUpdates and such so it's not needed
2886 * @deprecated since 1.18, use doEditUpdates()
2888 public function createUpdates( $rev ) {
2889 wfDeprecated( __METHOD__
, '1.18' );
2891 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2895 * This function is called right before saving the wikitext,
2896 * so we can do things like signatures and links-in-context.
2898 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2899 * @param $text String article contents
2900 * @param $user User object: user doing the edit
2901 * @param $popts ParserOptions object: parser options, default options for
2902 * the user loaded if null given
2903 * @return string article contents with altered wikitext markup (signatures
2904 * converted, {{subst:}}, templates, etc.)
2906 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2907 global $wgParser, $wgUser;
2909 wfDeprecated( __METHOD__
, '1.19' );
2911 $user = is_null( $user ) ?
$wgUser : $user;
2913 if ( $popts === null ) {
2914 $popts = ParserOptions
::newFromUser( $user );
2917 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2921 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2923 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2926 public function isBigDeletion() {
2927 wfDeprecated( __METHOD__
, '1.19' );
2928 return $this->mTitle
->isBigDeletion();
2932 * Get the approximate revision count of this page.
2934 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2937 public function estimateRevisionCount() {
2938 wfDeprecated( __METHOD__
, '1.19' );
2939 return $this->mTitle
->estimateRevisionCount();
2943 * Update the article's restriction field, and leave a log entry.
2945 * @deprecated since 1.19
2946 * @param $limit Array: set of restriction keys
2947 * @param $reason String
2948 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2949 * @param $expiry Array: per restriction type expiration
2950 * @param $user User The user updating the restrictions
2951 * @return bool true on success
2953 public function updateRestrictions(
2954 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2958 $user = is_null( $user ) ?
$wgUser : $user;
2960 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2964 * @deprecated since 1.18
2966 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2967 wfDeprecated( __METHOD__
, '1.18' );
2969 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2973 * @deprecated since 1.18
2975 public function viewUpdates() {
2976 wfDeprecated( __METHOD__
, '1.18' );
2978 return $this->doViewUpdates( $wgUser );
2982 * @deprecated since 1.18
2985 public function useParserCache( $oldid ) {
2986 wfDeprecated( __METHOD__
, '1.18' );
2988 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2992 class PoolWorkArticleView
extends PoolCounterWork
{
3010 * @var ParserOptions
3012 private $parserOptions;
3020 * @var ParserOutput|bool
3022 private $parserOutput = false;
3027 private $isDirty = false;
3032 private $error = false;
3038 * @param $revid Integer: ID of the revision being parsed
3039 * @param $useParserCache Boolean: whether to use the parser cache
3040 * @param $parserOptions parserOptions to use for the parse operation
3041 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3042 * @param $context IContextSource context for parsing
3044 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null, IContextSource
$context = null ) {
3045 if ( is_string($content) ) { #BC: old style call
3046 $modelName = $page->getRevision()->getContentModelName();
3047 $format = $page->getRevision()->getContentFormat();
3048 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelName, $format );
3051 if ( is_null( $context ) ) {
3052 $context = RequestContext
::getMain();
3053 #XXX: clone and then set title?
3056 $this->page
= $page;
3057 $this->revid
= $revid;
3058 $this->context
= $context;
3059 $this->cacheable
= $useParserCache;
3060 $this->parserOptions
= $parserOptions;
3061 $this->content
= $content;
3062 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3063 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3067 * Get the ParserOutput from this object, or false in case of failure
3069 * @return ParserOutput
3071 public function getParserOutput() {
3072 return $this->parserOutput
;
3076 * Get whether the ParserOutput is a dirty one (i.e. expired)
3080 public function getIsDirty() {
3081 return $this->isDirty
;
3085 * Get a Status object in case of error or false otherwise
3087 * @return Status|bool
3089 public function getError() {
3090 return $this->error
;
3097 global $wgUseFileCache;
3099 // @todo: several of the methods called on $this->page are not declared in Page, but present in WikiPage and delegated by Article.
3101 $isCurrent = $this->revid
=== $this->page
->getLatest();
3103 if ( $this->content
!== null ) {
3104 $content = $this->content
;
3105 } elseif ( $isCurrent ) {
3106 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
3108 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3109 if ( $rev === null ) {
3112 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
3115 $time = - microtime( true );
3116 // TODO: page might not have this method? Hard to tell what page is supposed to be here...
3117 $this->parserOutput
= $content->getParserOutput( $this->context
, $this->revid
, $this->parserOptions
);
3118 $time +
= microtime( true );
3122 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3123 $this->page
->getTitle()->getPrefixedDBkey() ) );
3126 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3127 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3130 // Make sure file cache is not used on uncacheable content.
3131 // Output that has magic words in it can still use the parser cache
3132 // (if enabled), though it will generally expire sooner.
3133 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3134 $wgUseFileCache = false;
3138 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3147 function getCachedWork() {
3148 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3150 if ( $this->parserOutput
=== false ) {
3151 wfDebug( __METHOD__
. ": parser cache miss\n" );
3154 wfDebug( __METHOD__
. ": parser cache hit\n" );
3162 function fallback() {
3163 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3165 if ( $this->parserOutput
=== false ) {
3166 wfDebugLog( 'dirty', "dirty missing\n" );
3167 wfDebug( __METHOD__
. ": no dirty cache\n" );
3170 wfDebug( __METHOD__
. ": sending dirty output\n" );
3171 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3172 $this->isDirty
= true;
3178 * @param $status Status
3181 function error( $status ) {
3182 $this->error
= $status;