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
155 public function getContentHandler() {
156 return ContentHandler
::getForModelName( $this->getContentModelName() );
160 * Get the title object of the article
161 * @return Title object of this page
163 public function getTitle() {
164 return $this->mTitle
;
170 public function clear() {
171 $this->mDataLoaded
= false;
173 $this->mCounter
= null;
174 $this->mRedirectTarget
= null; # Title object if set
175 $this->mLastRevision
= null; # Latest revision
176 $this->mTouched
= '19700101000000';
177 $this->mTimestamp
= '';
178 $this->mIsRedirect
= false;
179 $this->mLatest
= false;
180 $this->mPreparedEdit
= false;
184 * Return the list of revision fields that should be selected to create
189 public static function selectFields() {
202 'page_content_model',
207 * Fetch a page record with the given conditions
208 * @param $dbr DatabaseBase object
209 * @param $conditions Array
210 * @return mixed Database result resource, or false on failure
212 protected function pageData( $dbr, $conditions ) {
213 $fields = self
::selectFields();
215 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
217 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
219 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
225 * Fetch a page record matching the Title object's namespace and title
226 * using a sanitized title string
228 * @param $dbr DatabaseBase object
229 * @param $title Title object
230 * @return mixed Database result resource, or false on failure
232 public function pageDataFromTitle( $dbr, $title ) {
233 return $this->pageData( $dbr, array(
234 'page_namespace' => $title->getNamespace(),
235 'page_title' => $title->getDBkey() ) );
239 * Fetch a page record matching the requested ID
241 * @param $dbr DatabaseBase
243 * @return mixed Database result resource, or false on failure
245 public function pageDataFromId( $dbr, $id ) {
246 return $this->pageData( $dbr, array( 'page_id' => $id ) );
250 * Set the general counter, title etc data loaded from
253 * @param $data Object|String One of the following:
254 * A DB query result object or...
255 * "fromdb" to get from a slave DB or...
256 * "fromdbmaster" to get from the master DB
259 public function loadPageData( $data = 'fromdb' ) {
260 if ( $data === 'fromdbmaster' ) {
261 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
262 } elseif ( $data === 'fromdb' ) { // slave
263 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
264 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
265 # Note that DB also stores the master position in the session and checks it.
266 $touched = $this->getCachedLastEditTime();
267 if ( $touched ) { // key set
268 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
269 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
274 $lc = LinkCache
::singleton();
277 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
279 $this->mTitle
->loadFromRow( $data );
281 # Old-fashioned restrictions
282 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
284 $this->mCounter
= intval( $data->page_counter
);
285 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
286 $this->mIsRedirect
= intval( $data->page_is_redirect
);
287 $this->mLatest
= intval( $data->page_latest
);
289 $lc->addBadLinkObj( $this->mTitle
);
291 $this->mTitle
->loadFromRow( false );
294 $this->mDataLoaded
= true;
298 * @return int Page ID
300 public function getId() {
301 return $this->mTitle
->getArticleID();
305 * @return bool Whether or not the page exists in the database
307 public function exists() {
308 return $this->mTitle
->exists();
312 * Check if this page is something we're going to be showing
313 * some sort of sensible content for. If we return false, page
314 * views (plain action=view) will return an HTTP 404 response,
315 * so spiders and robots can know they're following a bad link.
319 public function hasViewableContent() {
320 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
324 * @return int The view count for the page
326 public function getCount() {
327 if ( !$this->mDataLoaded
) {
328 $this->loadPageData();
331 return $this->mCounter
;
335 * Tests if the article text represents a redirect
337 * @param $text mixed string containing article contents, or boolean
340 public function isRedirect( $text = false ) {
341 if ( $text === false ) $content = $this->getContent();
342 else $content = ContentHandler
::makeContent( $text, $this->mTitle
); # TODO: allow model and format to be provided; or better, expect a Content object
345 if ( empty( $content ) ) return false;
346 else return $content->isRedirect();
350 * Returns the page's content model name. Will use the revisions actual content model if the page exists,
351 * and the page's default if the page doesn't exist yet.
357 public function getContentModelName() {
358 if ( $this->exists() ) {
359 # look at the revision's actual content model
360 $rev = $this->getRevision();
361 return $rev->getContentModelName();
363 # use the default model for this page
364 return $this->mTitle
->getContentModelName();
369 * Loads page_touched and returns a value indicating if it should be used
370 * @return boolean true if not a redirect
372 public function checkTouched() {
373 if ( !$this->mDataLoaded
) {
374 $this->loadPageData();
376 return !$this->mIsRedirect
;
380 * Get the page_touched field
381 * @return string containing GMT timestamp
383 public function getTouched() {
384 if ( !$this->mDataLoaded
) {
385 $this->loadPageData();
387 return $this->mTouched
;
391 * Get the page_latest field
392 * @return integer rev_id of current revision
394 public function getLatest() {
395 if ( !$this->mDataLoaded
) {
396 $this->loadPageData();
398 return (int)$this->mLatest
;
402 * Loads everything except the text
403 * This isn't necessary for all uses, so it's only done if needed.
405 protected function loadLastEdit() {
406 if ( $this->mLastRevision
!== null ) {
407 return; // already loaded
410 $latest = $this->getLatest();
412 return; // page doesn't exist or is missing page_latest info
415 $revision = Revision
::newFromPageId( $this->getId(), $latest );
416 if ( $revision ) { // sanity
417 $this->setLastEdit( $revision );
422 * Set the latest revision
424 protected function setLastEdit( Revision
$revision ) {
425 $this->mLastRevision
= $revision;
426 $this->mTimestamp
= $revision->getTimestamp();
430 * Get the latest revision
431 * @return Revision|null
433 public function getRevision() {
434 $this->loadLastEdit();
435 if ( $this->mLastRevision
) {
436 return $this->mLastRevision
;
442 * Get the content of the current revision. No side-effects...
444 * @param $audience Integer: one of:
445 * Revision::FOR_PUBLIC to be displayed to all users
446 * Revision::FOR_THIS_USER to be displayed to $wgUser
447 * Revision::RAW get the text regardless of permissions
448 * @return Content|null The content of the current revision
452 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
453 $this->loadLastEdit();
454 if ( $this->mLastRevision
) {
455 return $this->mLastRevision
->getContent( $audience );
461 * Get the text of the current revision. No side-effects...
463 * @param $audience Integer: one of:
464 * Revision::FOR_PUBLIC to be displayed to all users
465 * Revision::FOR_THIS_USER to be displayed to $wgUser
466 * Revision::RAW get the text regardless of permissions
467 * @return String|false The text of the current revision
468 * @deprecated as of 1.WD, getContent() should be used instead.
470 public function getText( $audience = Revision
::FOR_PUBLIC
) { #@todo: deprecated, replace usage!
471 wfDeprecated( __METHOD__
, '1.WD' );
473 $this->loadLastEdit();
474 if ( $this->mLastRevision
) {
475 return $this->mLastRevision
->getText( $audience );
481 * Get the text of the current revision. No side-effects...
483 * @return String|bool The text of the current revision. False on failure
484 * @deprecated as of 1.WD, getContent() should be used instead.
486 public function getRawText() { #@todo: deprecated, replace usage!
487 wfDeprecated( __METHOD__
, '1.WD' );
489 return $this->getText( Revision
::RAW
);
493 * @return string MW timestamp of last article revision
495 public function getTimestamp() {
496 // Check if the field has been filled by WikiPage::setTimestamp()
497 if ( !$this->mTimestamp
) {
498 $this->loadLastEdit();
501 return wfTimestamp( TS_MW
, $this->mTimestamp
);
505 * Set the page timestamp (use only to avoid DB queries)
506 * @param $ts string MW timestamp of last article revision
509 public function setTimestamp( $ts ) {
510 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
514 * @param $audience Integer: one of:
515 * Revision::FOR_PUBLIC to be displayed to all users
516 * Revision::FOR_THIS_USER to be displayed to $wgUser
517 * Revision::RAW get the text regardless of permissions
518 * @return int user ID for the user that made the last article revision
520 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
521 $this->loadLastEdit();
522 if ( $this->mLastRevision
) {
523 return $this->mLastRevision
->getUser( $audience );
530 * @param $audience Integer: one of:
531 * Revision::FOR_PUBLIC to be displayed to all users
532 * Revision::FOR_THIS_USER to be displayed to $wgUser
533 * Revision::RAW get the text regardless of permissions
534 * @return string username of the user that made the last article revision
536 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
537 $this->loadLastEdit();
538 if ( $this->mLastRevision
) {
539 return $this->mLastRevision
->getUserText( $audience );
546 * @param $audience Integer: one of:
547 * Revision::FOR_PUBLIC to be displayed to all users
548 * Revision::FOR_THIS_USER to be displayed to $wgUser
549 * Revision::RAW get the text regardless of permissions
550 * @return string Comment stored for the last article revision
552 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
553 $this->loadLastEdit();
554 if ( $this->mLastRevision
) {
555 return $this->mLastRevision
->getComment( $audience );
562 * Returns true if last revision was marked as "minor edit"
564 * @return boolean Minor edit indicator for the last article revision.
566 public function getMinorEdit() {
567 $this->loadLastEdit();
568 if ( $this->mLastRevision
) {
569 return $this->mLastRevision
->isMinor();
576 * Get the cached timestamp for the last time the page changed.
577 * This is only used to help handle slave lag by comparing to page_touched.
578 * @return string MW timestamp
580 protected function getCachedLastEditTime() {
582 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
583 return $wgMemc->get( $key );
587 * Set the cached timestamp for the last time the page changed.
588 * This is only used to help handle slave lag by comparing to page_touched.
589 * @param $timestamp string
592 public function setCachedLastEditTime( $timestamp ) {
594 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
595 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
599 * Determine whether a page would be suitable for being counted as an
600 * article in the site_stats table based on the title & its content
602 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
603 * if false, the current database state will be used
606 public function isCountable( $editInfo = false ) {
607 global $wgArticleCountMethod;
609 if ( !$this->mTitle
->isContentPage() ) {
614 $content = $editInfo->pstContent
;
616 $content = $this->getContent();
619 if ( !$content ||
$content->isRedirect( ) ) {
625 if ( $wgArticleCountMethod === 'link' ) {
626 # nasty special case to avoid re-parsing to detect links
629 // ParserOutput::getLinks() is a 2D array of page links, so
630 // to be really correct we would need to recurse in the array
631 // but the main array should only have items in it if there are
633 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
635 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
636 array( 'pl_from' => $this->getId() ), __METHOD__
);
640 return $content->isCountable( $hasLinks );
644 * If this page is a redirect, get its target
646 * The target will be fetched from the redirect table if possible.
647 * If this page doesn't have an entry there, call insertRedirect()
648 * @return Title|mixed object, or null if this page is not a redirect
650 public function getRedirectTarget() {
651 if ( !$this->mTitle
->isRedirect() ) {
655 if ( $this->mRedirectTarget
!== null ) {
656 return $this->mRedirectTarget
;
659 # Query the redirect table
660 $dbr = wfGetDB( DB_SLAVE
);
661 $row = $dbr->selectRow( 'redirect',
662 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
663 array( 'rd_from' => $this->getId() ),
667 // rd_fragment and rd_interwiki were added later, populate them if empty
668 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
669 return $this->mRedirectTarget
= Title
::makeTitle(
670 $row->rd_namespace
, $row->rd_title
,
671 $row->rd_fragment
, $row->rd_interwiki
);
674 # This page doesn't have an entry in the redirect table
675 return $this->mRedirectTarget
= $this->insertRedirect();
679 * Insert an entry for this page into the redirect table.
681 * Don't call this function directly unless you know what you're doing.
682 * @return Title object or null if not a redirect
684 public function insertRedirect() {
685 // recurse through to only get the final target
686 $content = $this->getContent();
687 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
691 $this->insertRedirectEntry( $retval );
696 * Insert or update the redirect table entry for this page to indicate
697 * it redirects to $rt .
698 * @param $rt Title redirect target
700 public function insertRedirectEntry( $rt ) {
701 $dbw = wfGetDB( DB_MASTER
);
702 $dbw->replace( 'redirect', array( 'rd_from' ),
704 'rd_from' => $this->getId(),
705 'rd_namespace' => $rt->getNamespace(),
706 'rd_title' => $rt->getDBkey(),
707 'rd_fragment' => $rt->getFragment(),
708 'rd_interwiki' => $rt->getInterwiki(),
715 * Get the Title object or URL this page redirects to
717 * @return mixed false, Title of in-wiki target, or string with URL
719 public function followRedirect() {
720 return $this->getRedirectURL( $this->getRedirectTarget() );
724 * Get the Title object or URL to use for a redirect. We use Title
725 * objects for same-wiki, non-special redirects and URLs for everything
727 * @param $rt Title Redirect target
728 * @return mixed false, Title object of local target, or string with URL
730 public function getRedirectURL( $rt ) {
735 if ( $rt->isExternal() ) {
736 if ( $rt->isLocal() ) {
737 // Offsite wikis need an HTTP redirect.
739 // This can be hard to reverse and may produce loops,
740 // so they may be disabled in the site configuration.
741 $source = $this->mTitle
->getFullURL( 'redirect=no' );
742 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
744 // External pages pages without "local" bit set are not valid
750 if ( $rt->isSpecialPage() ) {
751 // Gotta handle redirects to special pages differently:
752 // Fill the HTTP response "Location" header and ignore
753 // the rest of the page we're on.
755 // Some pages are not valid targets
756 if ( $rt->isValidRedirectTarget() ) {
757 return $rt->getFullURL();
767 * Get a list of users who have edited this article, not including the user who made
768 * the most recent revision, which you can get from $article->getUser() if you want it
769 * @return UserArrayFromResult
771 public function getContributors() {
772 # @todo FIXME: This is expensive; cache this info somewhere.
774 $dbr = wfGetDB( DB_SLAVE
);
776 if ( $dbr->implicitGroupby() ) {
777 $realNameField = 'user_real_name';
779 $realNameField = 'MIN(user_real_name) AS user_real_name';
782 $tables = array( 'revision', 'user' );
785 'rev_user as user_id',
786 'rev_user_text AS user_name',
788 'MAX(rev_timestamp) AS timestamp',
791 $conds = array( 'rev_page' => $this->getId() );
793 // The user who made the top revision gets credited as "this page was last edited by
794 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
795 $user = $this->getUser();
797 $conds[] = "rev_user != $user";
799 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
802 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
805 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
809 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
810 'ORDER BY' => 'timestamp DESC',
813 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
814 return new UserArrayFromResult( $res );
818 * Get the last N authors
819 * @param $num Integer: number of revisions to get
820 * @param $revLatest String: the latest rev_id, selected from the master (optional)
821 * @return array Array of authors, duplicates not removed
823 public function getLastNAuthors( $num, $revLatest = 0 ) {
824 wfProfileIn( __METHOD__
);
825 // First try the slave
826 // If that doesn't have the latest revision, try the master
828 $db = wfGetDB( DB_SLAVE
);
831 $res = $db->select( array( 'page', 'revision' ),
832 array( 'rev_id', 'rev_user_text' ),
834 'page_namespace' => $this->mTitle
->getNamespace(),
835 'page_title' => $this->mTitle
->getDBkey(),
839 'ORDER BY' => 'rev_timestamp DESC',
845 wfProfileOut( __METHOD__
);
849 $row = $db->fetchObject( $res );
851 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
852 $db = wfGetDB( DB_MASTER
);
857 } while ( $continue );
859 $authors = array( $row->rev_user_text
);
861 foreach ( $res as $row ) {
862 $authors[] = $row->rev_user_text
;
865 wfProfileOut( __METHOD__
);
870 * Should the parser cache be used?
872 * @param $parserOptions ParserOptions to check
876 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
877 global $wgEnableParserCache;
879 return $wgEnableParserCache
880 && $parserOptions->getStubThreshold() == 0
881 && $this->mTitle
->exists()
882 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
883 && $this->getContentHandler()->isParserCacheSupported();
887 * Get a ParserOutput for the given ParserOptions and revision ID.
888 * The parser cache will be used if possible.
891 * @param $parserOptions ParserOptions to use for the parse operation
892 * @param $oldid Revision ID to get the text from, passing null or 0 will
893 * get the current revision (default value)
894 * @param $context IContextSource context for parsing
896 * @return ParserOutput or false if the revision was not found
898 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null, IContextSource
$context = null ) {
899 wfProfileIn( __METHOD__
);
901 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
902 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
903 if ( $parserOptions->getStubThreshold() ) {
904 wfIncrStats( 'pcache_miss_stub' );
907 if ( $useParserCache ) {
908 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
909 if ( $parserOutput !== false ) {
910 wfProfileOut( __METHOD__
);
911 return $parserOutput;
915 if ( $oldid === null ||
$oldid === 0 ) {
916 $oldid = $this->getLatest();
919 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache, null, $context );
922 wfProfileOut( __METHOD__
);
924 return $pool->getParserOutput();
928 * Do standard deferred updates after page view
929 * @param $user User The relevant user
931 public function doViewUpdates( User
$user ) {
932 global $wgDisableCounters;
933 if ( wfReadOnly() ) {
937 # Don't update page view counters on views from bot users (bug 14044)
938 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
939 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
940 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
943 # Update newtalk / watchlist notification status
944 $user->clearNotification( $this->mTitle
);
948 * Perform the actions of a page purging
951 public function doPurge() {
954 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
958 // Invalidate the cache
959 $this->mTitle
->invalidateCache();
963 // Commit the transaction before the purge is sent
964 $dbw = wfGetDB( DB_MASTER
);
965 $dbw->commit( __METHOD__
);
968 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
972 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
973 if ( $this->mTitle
->exists() ) {
974 $text = ContentHandler
::getContentText( $this->getNativeData() );
979 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
985 * Insert a new empty page record for this article.
986 * This *must* be followed up by creating a revision
987 * and running $this->updateRevisionOn( ... );
988 * or else the record will be left in a funky state.
989 * Best if all done inside a transaction.
991 * @param $dbw DatabaseBase
992 * @return int The newly created page_id key, or false if the title already existed
994 public function insertOn( $dbw ) {
995 wfProfileIn( __METHOD__
);
997 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
998 $dbw->insert( 'page', array(
999 'page_id' => $page_id,
1000 'page_namespace' => $this->mTitle
->getNamespace(),
1001 'page_title' => $this->mTitle
->getDBkey(),
1002 'page_counter' => 0,
1003 'page_restrictions' => '',
1004 'page_is_redirect' => 0, # Will set this shortly...
1006 'page_random' => wfRandom(),
1007 'page_touched' => $dbw->timestamp(),
1008 'page_latest' => 0, # Fill this in shortly...
1009 'page_len' => 0, # Fill this in shortly...
1010 ), __METHOD__
, 'IGNORE' );
1012 $affected = $dbw->affectedRows();
1015 $newid = $dbw->insertId();
1016 $this->mTitle
->resetArticleID( $newid );
1018 wfProfileOut( __METHOD__
);
1020 return $affected ?
$newid : false;
1024 * Update the page record to point to a newly saved revision.
1026 * @param $dbw DatabaseBase: object
1027 * @param $revision Revision: For ID number, and text used to set
1028 * length and redirect status fields
1029 * @param $lastRevision Integer: if given, will not overwrite the page field
1030 * when different from the currently set value.
1031 * Giving 0 indicates the new page flag should be set
1033 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1034 * removing rows in redirect table.
1035 * @return bool true on success, false on failure
1038 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1039 wfProfileIn( __METHOD__
);
1041 $content = $revision->getContent();
1042 $len = $content->getSize();
1043 $rt = $content->getUltimateRedirectTarget();
1045 $conditions = array( 'page_id' => $this->getId() );
1047 if ( !is_null( $lastRevision ) ) {
1048 # An extra check against threads stepping on each other
1049 $conditions['page_latest'] = $lastRevision;
1052 $now = wfTimestampNow();
1053 $dbw->update( 'page',
1055 'page_latest' => $revision->getId(),
1056 'page_touched' => $dbw->timestamp( $now ),
1057 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1058 'page_is_redirect' => $rt !== null ?
1 : 0,
1060 'page_content_model' => $revision->getContentModelName(),
1065 $result = $dbw->affectedRows() != 0;
1067 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1068 $this->setLastEdit( $revision );
1069 $this->setCachedLastEditTime( $now );
1070 $this->mLatest
= $revision->getId();
1071 $this->mIsRedirect
= (bool)$rt;
1072 # Update the LinkCache.
1073 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1076 wfProfileOut( __METHOD__
);
1081 * Add row to the redirect table if this is a redirect, remove otherwise.
1083 * @param $dbw DatabaseBase
1084 * @param $redirectTitle Title object pointing to the redirect target,
1085 * or NULL if this is not a redirect
1086 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1087 * removing rows in redirect table.
1088 * @return bool true on success, false on failure
1091 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1092 // Always update redirects (target link might have changed)
1093 // Update/Insert if we don't know if the last revision was a redirect or not
1094 // Delete if changing from redirect to non-redirect
1095 $isRedirect = !is_null( $redirectTitle );
1097 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1101 wfProfileIn( __METHOD__
);
1102 if ( $isRedirect ) {
1103 $this->insertRedirectEntry( $redirectTitle );
1105 // This is not a redirect, remove row from redirect table
1106 $where = array( 'rd_from' => $this->getId() );
1107 $dbw->delete( 'redirect', $where, __METHOD__
);
1110 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1111 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1113 wfProfileOut( __METHOD__
);
1115 return ( $dbw->affectedRows() != 0 );
1119 * If the given revision is newer than the currently set page_latest,
1120 * update the page record. Otherwise, do nothing.
1122 * @param $dbw DatabaseBase object
1123 * @param $revision Revision object
1126 public function updateIfNewerOn( $dbw, $revision ) {
1127 wfProfileIn( __METHOD__
);
1129 $row = $dbw->selectRow(
1130 array( 'revision', 'page' ),
1131 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1133 'page_id' => $this->getId(),
1134 'page_latest=rev_id' ),
1138 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1139 wfProfileOut( __METHOD__
);
1142 $prev = $row->rev_id
;
1143 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1145 # No or missing previous revision; mark the page as new
1147 $lastRevIsRedirect = null;
1150 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1152 wfProfileOut( __METHOD__
);
1157 * Get the text that needs to be saved in order to undo all revisions
1158 * between $undo and $undoafter. Revisions must belong to the same page,
1159 * must exist and must not be deleted
1160 * @param $undo Revision
1161 * @param $undoafter Revision Must be an earlier revision than $undo
1162 * @return mixed string on success, false on failure
1163 * @deprecated since 1.WD: use ContentHandler::getUndoContent() instead.
1165 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) { #FIXME: replace usages.
1166 wfDeprecated( __METHOD__
, '1.WD' );
1168 $this->loadLastEdit();
1170 if ( $this->mLastRevision
) {
1171 if ( is_null( $undoafter ) ) {
1172 $undoafter = $undo->getPrevious();
1175 $handler = $this->getContentHandler();
1176 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1181 return ContentHandler
::getContentText( $undone );
1189 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1190 * @param $text String: new text of the section
1191 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1192 * @param $edittime String: revision timestamp or null to use the current revision
1193 * @return String new complete article text, or null if error
1195 * @deprecated since 1.WD, use replaceSectionContent() instead
1197 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) { #FIXME: use replaceSectionContent() instead!
1198 wfDeprecated( __METHOD__
, '1.WD' );
1200 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1202 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1204 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1208 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1209 * @param $content Content: new content of the section
1210 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1211 * @param $edittime String: revision timestamp or null to use the current revision
1213 * @return Content new complete article content, or null if error
1217 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1218 wfProfileIn( __METHOD__
);
1220 if ( strval( $section ) == '' ) {
1221 // Whole-page edit; let the whole text through
1222 $newContent = $sectionContent;
1224 // Bug 30711: always use current version when adding a new section
1225 if ( is_null( $edittime ) ||
$section == 'new' ) {
1226 $oldContent = $this->getContent();
1227 if ( ! $oldContent ) {
1228 wfDebug( __METHOD__
. ": no page text\n" );
1229 wfProfileOut( __METHOD__
);
1233 $dbw = wfGetDB( DB_MASTER
);
1234 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1237 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1238 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1239 wfProfileOut( __METHOD__
);
1243 $oldContent = $rev->getContent();
1246 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1249 wfProfileOut( __METHOD__
);
1254 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1256 * @return Int updated $flags
1258 function checkFlags( $flags ) {
1259 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1260 if ( $this->mTitle
->getArticleID() ) {
1261 $flags |
= EDIT_UPDATE
;
1271 * Change an existing article or create a new article. Updates RC and all necessary caches,
1272 * optionally via the deferred update array.
1274 * @param $text String: new text
1275 * @param $summary String: edit summary
1276 * @param $flags Integer bitfield:
1278 * Article is known or assumed to be non-existent, create a new one
1280 * Article is known or assumed to be pre-existing, update it
1282 * Mark this edit minor, if the user is allowed to do so
1284 * Do not log the change in recentchanges
1286 * Mark the edit a "bot" edit regardless of user rights
1287 * EDIT_DEFER_UPDATES
1288 * Defer some of the updates until the end of index.php
1290 * Fill in blank summaries with generated text where possible
1292 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1293 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1294 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1295 * edit-already-exists error will be returned. These two conditions are also possible with
1296 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1298 * @param $baseRevId int the revision ID this edit was based off, if any
1299 * @param $user User the user doing the edit
1301 * @return Status object. Possible errors:
1302 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1303 * edit-gone-missing: In update mode, but the article didn't exist
1304 * edit-conflict: In update mode, the article changed unexpectedly
1305 * edit-no-change: Warning that the text was the same as before
1306 * edit-already-exists: In creation mode, but the article already exists
1308 * Extensions may define additional errors.
1310 * $return->value will contain an associative array with members as follows:
1311 * new: Boolean indicating if the function attempted to create a new article
1312 * revision: The revision object for the inserted revision, or null
1314 * Compatibility note: this function previously returned a boolean value indicating success/failure
1316 * @deprecated since 1.WD: use doEditContent() instead.
1318 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #FIXME: use doEditContent() instead
1319 wfDeprecated( __METHOD__
, '1.WD' );
1321 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1323 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1327 * Change an existing article or create a new article. Updates RC and all necessary caches,
1328 * optionally via the deferred update array.
1330 * @param $content Content: new content
1331 * @param $summary String: edit summary
1332 * @param $flags Integer bitfield:
1334 * Article is known or assumed to be non-existent, create a new one
1336 * Article is known or assumed to be pre-existing, update it
1338 * Mark this edit minor, if the user is allowed to do so
1340 * Do not log the change in recentchanges
1342 * Mark the edit a "bot" edit regardless of user rights
1343 * EDIT_DEFER_UPDATES
1344 * Defer some of the updates until the end of index.php
1346 * Fill in blank summaries with generated text where possible
1348 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1349 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1350 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1351 * edit-already-exists error will be returned. These two conditions are also possible with
1352 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1354 * @param $baseRevId the revision ID this edit was based off, if any
1355 * @param $user User the user doing the edit
1356 * @param $serialisation_format String: format for storing the content in the database
1358 * @return Status object. Possible errors:
1359 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1360 * edit-gone-missing: In update mode, but the article didn't exist
1361 * edit-conflict: In update mode, the article changed unexpectedly
1362 * edit-no-change: Warning that the text was the same as before
1363 * edit-already-exists: In creation mode, but the article already exists
1365 * Extensions may define additional errors.
1367 * $return->value will contain an associative array with members as follows:
1368 * new: Boolean indicating if the function attempted to create a new article
1369 * revision: The revision object for the inserted revision, or null
1373 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1374 User
$user = null, $serialisation_format = null ) { #FIXME: use this
1375 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1377 # Low-level sanity check
1378 if ( $this->mTitle
->getText() === '' ) {
1379 throw new MWException( 'Something is trying to edit an article with an empty title' );
1382 wfProfileIn( __METHOD__
);
1384 $user = is_null( $user ) ?
$wgUser : $user;
1385 $status = Status
::newGood( array() );
1387 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1388 $this->loadPageData( 'fromdbmaster' );
1390 $flags = $this->checkFlags( $flags );
1393 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary, #FIXME: document new hook!
1394 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1396 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { # avoid serialization overhead if the hook isn't present
1397 $content_text = $content->serialize();
1398 $txt = $content_text; # clone
1400 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary, #FIXME: deprecate legacy hook!
1401 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1403 if ( $txt !== $content_text ) {
1404 # if the text changed, unserialize the new version to create an updated Content object.
1405 $content = $content->getContentHandler()->unserializeContent( $txt );
1410 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1412 if ( $status->isOK() ) {
1413 $status->fatal( 'edit-hook-aborted' );
1416 wfProfileOut( __METHOD__
);
1420 # Silently ignore EDIT_MINOR if not allowed
1421 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1422 $bot = $flags & EDIT_FORCE_BOT
;
1424 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1426 $oldsize = $old_content ?
$old_content->getSize() : 0;
1427 $oldid = $this->getLatest();
1428 $oldIsRedirect = $this->isRedirect();
1429 $oldcountable = $this->isCountable();
1431 $handler = $content->getContentHandler();
1433 # Provide autosummaries if one is not provided and autosummaries are enabled.
1434 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1435 if ( !$old_content ) $old_content = null;
1436 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1439 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1440 $serialized = $editInfo->pst
;
1441 $content = $editInfo->pstContent
;
1442 $newsize = $content->getSize();
1444 $dbw = wfGetDB( DB_MASTER
);
1445 $now = wfTimestampNow();
1446 $this->mTimestamp
= $now;
1448 if ( $flags & EDIT_UPDATE
) {
1449 # Update article, but only if changed.
1450 $status->value
['new'] = false;
1453 # Article gone missing
1454 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1455 $status->fatal( 'edit-gone-missing' );
1457 wfProfileOut( __METHOD__
);
1461 # Make sure the revision is either completely inserted or not inserted at all
1462 if ( !$wgDBtransactions ) {
1463 $userAbort = ignore_user_abort( true );
1466 $revision = new Revision( array(
1467 'page' => $this->getId(),
1468 'comment' => $summary,
1469 'minor_edit' => $isminor,
1470 'text' => $serialized,
1472 'parent_id' => $oldid,
1473 'user' => $user->getId(),
1474 'user_text' => $user->getName(),
1475 'timestamp' => $now,
1476 'content_model' => $content->getModelName(),
1477 'content_format' => $serialisation_format,
1480 $changed = !$content->equals( $old_content );
1483 $dbw->begin( __METHOD__
);
1484 $revisionId = $revision->insertOn( $dbw );
1488 # Note that we use $this->mLatest instead of fetching a value from the master DB
1489 # during the course of this function. This makes sure that EditPage can detect
1490 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1491 # before this function is called. A previous function used a separate query, this
1492 # creates a window where concurrent edits can cause an ignored edit conflict.
1493 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1496 /* Belated edit conflict! Run away!! */
1497 $status->fatal( 'edit-conflict' );
1499 # Delete the invalid revision if the DB is not transactional
1500 if ( !$wgDBtransactions ) {
1501 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1505 $dbw->rollback( __METHOD__
);
1507 global $wgUseRCPatrol;
1508 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1509 # Update recentchanges
1510 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1511 # Mark as patrolled if the user can do so
1512 $patrolled = $wgUseRCPatrol && !count(
1513 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1514 # Add RC row to the DB
1515 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1516 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1517 $revisionId, $patrolled
1520 # Log auto-patrolled edits
1522 PatrolLog
::record( $rc, true, $user );
1525 $user->incEditCount();
1526 $dbw->commit( __METHOD__
);
1529 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1530 // related variables correctly
1531 $revision->setId( $this->getLatest() );
1534 if ( !$wgDBtransactions ) {
1535 ignore_user_abort( $userAbort );
1538 // Now that ignore_user_abort is restored, we can respond to fatal errors
1539 if ( !$status->isOK() ) {
1540 wfProfileOut( __METHOD__
);
1544 # Update links tables, site stats, etc.
1545 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1546 'oldcountable' => $oldcountable ) );
1549 $status->warning( 'edit-no-change' );
1551 // Update page_touched, this is usually implicit in the page update
1552 // Other cache updates are done in onArticleEdit()
1553 $this->mTitle
->invalidateCache();
1556 # Create new article
1557 $status->value
['new'] = true;
1559 $dbw->begin( __METHOD__
);
1561 # Add the page record; stake our claim on this title!
1562 # This will return false if the article already exists
1563 $newid = $this->insertOn( $dbw );
1565 if ( $newid === false ) {
1566 $dbw->rollback( __METHOD__
);
1567 $status->fatal( 'edit-already-exists' );
1569 wfProfileOut( __METHOD__
);
1573 # Save the revision text...
1574 $revision = new Revision( array(
1576 'comment' => $summary,
1577 'minor_edit' => $isminor,
1578 'text' => $serialized,
1580 'user' => $user->getId(),
1581 'user_text' => $user->getName(),
1582 'timestamp' => $now,
1583 'content_model' => $content->getModelName(),
1584 'content_format' => $serialisation_format,
1586 $revisionId = $revision->insertOn( $dbw );
1588 # Update the page record with revision data
1589 $this->updateRevisionOn( $dbw, $revision, 0 );
1591 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1593 # Update recentchanges
1594 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1595 global $wgUseRCPatrol, $wgUseNPPatrol;
1597 # Mark as patrolled if the user can do so
1598 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1599 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1600 # Add RC row to the DB
1601 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1602 '', $content->getSize(), $revisionId, $patrolled );
1604 # Log auto-patrolled edits
1606 PatrolLog
::record( $rc, true, $user );
1609 $user->incEditCount();
1610 $dbw->commit( __METHOD__
);
1612 # Update links, etc.
1613 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1615 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1616 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1618 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1619 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1622 # Do updates right now unless deferral was requested
1623 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1624 DeferredUpdates
::doUpdates();
1627 // Return the new revision (or null) to the caller
1628 $status->value
['revision'] = $revision;
1630 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1631 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1633 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1634 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1636 # Promote user to any groups they meet the criteria for
1637 $user->addAutopromoteOnceGroups( 'onEdit' );
1639 wfProfileOut( __METHOD__
);
1644 * Get parser options suitable for rendering the primary article wikitext
1645 * @param User|string $user User object or 'canonical'
1646 * @return ParserOptions
1648 public function makeParserOptions( $user ) {
1650 if ( $user instanceof User
) { // settings per user (even anons)
1651 $options = ParserOptions
::newFromUser( $user );
1652 } else { // canonical settings
1653 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1655 $options->enableLimitReport(); // show inclusion/loop reports
1656 $options->setTidy( true ); // fix bad HTML
1661 * Prepare text which is about to be saved.
1662 * Returns a stdclass with source, pst and output members
1664 * @deprecated in 1.WD: use prepareContentForEdit instead.
1666 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) { #FIXME: use prepareContentForEdit() instead #XXX: who uses this?!
1667 #TODO: log use of deprecated function
1668 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1669 return $this->prepareContentForEdit( $content, $revid , $user );
1673 * Prepare content which is about to be saved.
1674 * Returns a stdclass with source, pst and output members
1676 * @param \Content $content
1677 * @param null $revid
1678 * @param null|\User $user
1679 * @param null $serialization_format
1681 * @return bool|object
1685 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) { #FIXME: use this #XXX: really public?!
1686 global $wgParser, $wgContLang, $wgUser;
1687 $user = is_null( $user ) ?
$wgUser : $user;
1688 // @TODO fixme: check $user->getId() here???
1690 if ( $this->mPreparedEdit
1691 && $this->mPreparedEdit
->newContent
1692 && $this->mPreparedEdit
->newContent
->equals( $content )
1693 && $this->mPreparedEdit
->revid
== $revid
1694 && $this->mPreparedEdit
->format
== $serialization_format
1695 #XXX: also check $user here?
1698 return $this->mPreparedEdit
;
1701 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1702 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1704 $edit = (object)array();
1705 $edit->revid
= $revid;
1707 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1708 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1709 $edit->format
= $serialization_format;
1711 $edit->popts
= $this->makeParserOptions( 'canonical' );
1713 // TODO: is there no better way to obtain a context here?
1714 $context = RequestContext
::getMain();
1715 $context->setTitle( $this->mTitle
);
1716 $edit->output
= $edit->pstContent
->getParserOutput( $context, $revid, $edit->popts
);
1718 $edit->newContent
= $content;
1719 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1721 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1722 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1724 $this->mPreparedEdit
= $edit;
1730 * Do standard deferred updates after page edit.
1731 * Update links tables, site stats, search index and message cache.
1732 * Purges pages that include this page if the text was changed here.
1733 * Every 100th edit, prune the recent changes table.
1735 * @param $revision Revision object
1736 * @param $user User object that did the revision
1737 * @param $options Array of options, following indexes are used:
1738 * - changed: boolean, whether the revision changed the content (default true)
1739 * - created: boolean, whether the revision created the page (default false)
1740 * - oldcountable: boolean or null (default null):
1741 * - boolean: whether the page was counted as an article before that
1742 * revision, only used in changed is true and created is false
1743 * - null: don't change the article count
1745 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1746 global $wgEnableParserCache;
1748 wfProfileIn( __METHOD__
);
1750 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1751 $content = $revision->getContent();
1754 # Be careful not to double-PST: $text is usually already PST-ed once
1755 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1756 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1757 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1759 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1760 $editInfo = $this->mPreparedEdit
;
1763 # Save it to the parser cache
1764 if ( $wgEnableParserCache ) {
1765 $parserCache = ParserCache
::singleton();
1766 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1769 # Update the links tables and other secondary data
1770 $updates = $editInfo->output
->getSecondaryDataUpdates( $this->mTitle
);
1771 SecondaryDataUpdate
::runUpdates( $updates );
1773 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1775 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1776 if ( 0 == mt_rand( 0, 99 ) ) {
1777 // Flush old entries from the `recentchanges` table; we do this on
1778 // random requests so as to avoid an increase in writes for no good reason
1781 $dbw = wfGetDB( DB_MASTER
);
1782 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1785 array( "rc_timestamp < '$cutoff'" ),
1791 if ( !$this->mTitle
->exists() ) {
1792 wfProfileOut( __METHOD__
);
1796 $id = $this->getId();
1797 $title = $this->mTitle
->getPrefixedDBkey();
1798 $shortTitle = $this->mTitle
->getDBkey();
1800 if ( !$options['changed'] ) {
1803 } elseif ( $options['created'] ) {
1804 $good = (int)$this->isCountable( $editInfo );
1806 } elseif ( $options['oldcountable'] !== null ) {
1807 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1814 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1815 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
1817 # If this is another user's talk page, update newtalk.
1818 # Don't do this if $options['changed'] = false (null-edits) nor if
1819 # it's a minor edit and the user doesn't want notifications for those.
1820 if ( $options['changed']
1821 && $this->mTitle
->getNamespace() == NS_USER_TALK
1822 && $shortTitle != $user->getTitleKey()
1823 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1825 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1826 $other = User
::newFromName( $shortTitle, false );
1828 wfDebug( __METHOD__
. ": invalid username\n" );
1829 } elseif ( User
::isIP( $shortTitle ) ) {
1830 // An anonymous user
1831 $other->setNewtalk( true );
1832 } elseif ( $other->isLoggedIn() ) {
1833 $other->setNewtalk( true );
1835 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1840 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1841 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
1842 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
1844 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
1847 if( $options['created'] ) {
1848 self
::onArticleCreate( $this->mTitle
);
1850 self
::onArticleEdit( $this->mTitle
);
1853 wfProfileOut( __METHOD__
);
1857 * Edit an article without doing all that other stuff
1858 * The article must already exist; link tables etc
1859 * are not updated, caches are not flushed.
1861 * @param $text String: text submitted
1862 * @param $user User The relevant user
1863 * @param $comment String: comment submitted
1864 * @param $minor Boolean: whereas it's a minor modification
1866 * @deprecated since 1.WD, use doEditContent() instead.
1868 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1869 wfDeprecated( __METHOD__
, "1.WD" );
1871 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1872 return $this->doQuickEditContent( $content, $user, $comment , $minor );
1876 * Edit an article without doing all that other stuff
1877 * The article must already exist; link tables etc
1878 * are not updated, caches are not flushed.
1880 * @param $content Content: content submitted
1881 * @param $user User The relevant user
1882 * @param $comment String: comment submitted
1883 * @param $serialisation_format String: format for storing the content in the database
1884 * @param $minor Boolean: whereas it's a minor modification
1886 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
1887 wfProfileIn( __METHOD__
);
1889 $serialized = $content->serialize( $serialisation_format );
1891 $dbw = wfGetDB( DB_MASTER
);
1892 $revision = new Revision( array(
1893 'page' => $this->getId(),
1894 'text' => $serialized,
1895 'length' => $content->getSize(),
1896 'comment' => $comment,
1897 'minor_edit' => $minor ?
1 : 0,
1899 $revision->insertOn( $dbw );
1900 $this->updateRevisionOn( $dbw, $revision );
1902 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1904 wfProfileOut( __METHOD__
);
1908 * Update the article's restriction field, and leave a log entry.
1909 * This works for protection both existing and non-existing pages.
1911 * @param $limit Array: set of restriction keys
1912 * @param $reason String
1913 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1914 * @param $expiry Array: per restriction type expiration
1915 * @param $user User The user updating the restrictions
1916 * @return bool true on success
1918 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1921 if ( wfReadOnly() ) {
1922 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1925 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1927 $id = $this->mTitle
->getArticleID();
1933 // Take this opportunity to purge out expired restrictions
1934 Title
::purgeExpiredRestrictions();
1936 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1937 # we expect a single selection, but the schema allows otherwise.
1938 $isProtected = false;
1942 $dbw = wfGetDB( DB_MASTER
);
1944 foreach ( $restrictionTypes as $action ) {
1945 if ( !isset( $expiry[$action] ) ) {
1946 $expiry[$action] = $dbw->getInfinity();
1948 if ( !isset( $limit[$action] ) ) {
1949 $limit[$action] = '';
1950 } elseif ( $limit[$action] != '' ) {
1954 # Get current restrictions on $action
1955 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1956 if ( $current != '' ) {
1957 $isProtected = true;
1960 if ( $limit[$action] != $current ) {
1962 } elseif ( $limit[$action] != '' ) {
1963 # Only check expiry change if the action is actually being
1964 # protected, since expiry does nothing on an not-protected
1966 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1972 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1976 # If nothing's changed, do nothing
1978 return Status
::newGood();
1981 if ( !$protect ) { # No protection at all means unprotection
1982 $revCommentMsg = 'unprotectedarticle';
1983 $logAction = 'unprotect';
1984 } elseif ( $isProtected ) {
1985 $revCommentMsg = 'modifiedarticleprotection';
1986 $logAction = 'modify';
1988 $revCommentMsg = 'protectedarticle';
1989 $logAction = 'protect';
1992 $encodedExpiry = array();
1993 $protectDescription = '';
1994 foreach ( $limit as $action => $restrictions ) {
1995 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1996 if ( $restrictions != '' ) {
1997 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1998 if ( $encodedExpiry[$action] != 'infinity' ) {
1999 $protectDescription .= wfMsgForContent( 'protect-expiring',
2000 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2001 $wgContLang->date( $expiry[$action], false, false ) ,
2002 $wgContLang->time( $expiry[$action], false, false ) );
2004 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
2007 $protectDescription .= ') ';
2010 $protectDescription = trim( $protectDescription );
2012 if ( $id ) { # Protection of existing page
2013 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2014 return Status
::newGood();
2017 # Only restrictions with the 'protect' right can cascade...
2018 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2019 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2021 # The schema allows multiple restrictions
2022 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2026 # Update restrictions table
2027 foreach ( $limit as $action => $restrictions ) {
2028 if ( $restrictions != '' ) {
2029 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2030 array( 'pr_page' => $id,
2031 'pr_type' => $action,
2032 'pr_level' => $restrictions,
2033 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2034 'pr_expiry' => $encodedExpiry[$action]
2039 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2040 'pr_type' => $action ), __METHOD__
);
2044 # Prepare a null revision to be added to the history
2045 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2047 $editComment .= ": $reason";
2049 if ( $protectDescription ) {
2050 $editComment .= " ($protectDescription)";
2053 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2056 # Insert a null revision
2057 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2058 $nullRevId = $nullRevision->insertOn( $dbw );
2060 $latest = $this->getLatest();
2061 # Update page record
2062 $dbw->update( 'page',
2064 'page_touched' => $dbw->timestamp(),
2065 'page_restrictions' => '',
2066 'page_latest' => $nullRevId
2067 ), array( /* WHERE */
2072 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2073 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2074 } else { # Protection of non-existing page (also known as "title protection")
2075 # Cascade protection is meaningless in this case
2078 if ( $limit['create'] != '' ) {
2079 $dbw->replace( 'protected_titles',
2080 array( array( 'pt_namespace', 'pt_title' ) ),
2082 'pt_namespace' => $this->mTitle
->getNamespace(),
2083 'pt_title' => $this->mTitle
->getDBkey(),
2084 'pt_create_perm' => $limit['create'],
2085 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2086 'pt_expiry' => $encodedExpiry['create'],
2087 'pt_user' => $user->getId(),
2088 'pt_reason' => $reason,
2092 $dbw->delete( 'protected_titles',
2094 'pt_namespace' => $this->mTitle
->getNamespace(),
2095 'pt_title' => $this->mTitle
->getDBkey()
2101 $this->mTitle
->flushRestrictions();
2103 if ( $logAction == 'unprotect' ) {
2104 $logParams = array();
2106 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2109 # Update the protection log
2110 $log = new LogPage( 'protect' );
2111 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2113 return Status
::newGood();
2117 * Take an array of page restrictions and flatten it to a string
2118 * suitable for insertion into the page_restrictions field.
2119 * @param $limit Array
2122 protected static function flattenRestrictions( $limit ) {
2123 if ( !is_array( $limit ) ) {
2124 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2130 foreach ( $limit as $action => $restrictions ) {
2131 if ( $restrictions != '' ) {
2132 $bits[] = "$action=$restrictions";
2136 return implode( ':', $bits );
2140 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2141 * Deletes the article with database consistency, writes logs, purges caches
2143 * @param $reason string delete reason for deletion log
2144 * @param $suppress int bitfield
2145 * Revision::DELETED_TEXT
2146 * Revision::DELETED_COMMENT
2147 * Revision::DELETED_USER
2148 * Revision::DELETED_RESTRICTED
2149 * @param $id int article ID
2150 * @param $commit boolean defaults to true, triggers transaction end
2151 * @param &$error Array of errors to append to
2152 * @param $user User The deleting user
2153 * @return boolean true if successful
2155 public function doDeleteArticle(
2156 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2158 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2159 == WikiPage
::DELETE_SUCCESS
;
2163 * Back-end article deletion
2164 * Deletes the article with database consistency, writes logs, purges caches
2166 * @param $reason string delete reason for deletion log
2167 * @param $suppress int bitfield
2168 * Revision::DELETED_TEXT
2169 * Revision::DELETED_COMMENT
2170 * Revision::DELETED_USER
2171 * Revision::DELETED_RESTRICTED
2172 * @param $id int article ID
2173 * @param $commit boolean defaults to true, triggers transaction end
2174 * @param &$error Array of errors to append to
2175 * @param $user User The deleting user
2176 * @return int: One of WikiPage::DELETE_* constants
2178 public function doDeleteArticleReal(
2179 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2182 $user = is_null( $user ) ?
$wgUser : $user;
2184 wfDebug( __METHOD__
. "\n" );
2186 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2187 return WikiPage
::DELETE_HOOK_ABORTED
;
2189 $dbw = wfGetDB( DB_MASTER
);
2190 $t = $this->mTitle
->getDBkey();
2191 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2193 if ( $t === '' ||
$id == 0 ) {
2194 return WikiPage
::DELETE_NO_PAGE
;
2197 // Bitfields to further suppress the content
2200 // This should be 15...
2201 $bitfield |
= Revision
::DELETED_TEXT
;
2202 $bitfield |
= Revision
::DELETED_COMMENT
;
2203 $bitfield |
= Revision
::DELETED_USER
;
2204 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2206 $bitfield = 'rev_deleted';
2209 $dbw->begin( __METHOD__
);
2210 // For now, shunt the revision data into the archive table.
2211 // Text is *not* removed from the text table; bulk storage
2212 // is left intact to avoid breaking block-compression or
2213 // immutable storage schemes.
2215 // For backwards compatibility, note that some older archive
2216 // table entries will have ar_text and ar_flags fields still.
2218 // In the future, we may keep revisions and mark them with
2219 // the rev_deleted field, which is reserved for this purpose.
2220 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2222 'ar_namespace' => 'page_namespace',
2223 'ar_title' => 'page_title',
2224 'ar_comment' => 'rev_comment',
2225 'ar_user' => 'rev_user',
2226 'ar_user_text' => 'rev_user_text',
2227 'ar_timestamp' => 'rev_timestamp',
2228 'ar_minor_edit' => 'rev_minor_edit',
2229 'ar_rev_id' => 'rev_id',
2230 'ar_parent_id' => 'rev_parent_id',
2231 'ar_text_id' => 'rev_text_id',
2232 'ar_text' => '\'\'', // Be explicit to appease
2233 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2234 'ar_len' => 'rev_len',
2235 'ar_page_id' => 'page_id',
2236 'ar_deleted' => $bitfield,
2237 'ar_sha1' => 'rev_content_model',
2238 'ar_content_format' => 'rev_content_format',
2239 'ar_content_format' => 'rev_sha1'
2242 'page_id = rev_page'
2246 # Now that it's safely backed up, delete it
2247 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2248 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2251 $dbw->rollback( __METHOD__
);
2252 return WikiPage
::DELETE_NO_REVISIONS
;
2255 $this->doDeleteUpdates( $id );
2257 # Log the deletion, if the page was suppressed, log it at Oversight instead
2258 $logtype = $suppress ?
'suppress' : 'delete';
2260 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2261 $logEntry->setPerformer( $user );
2262 $logEntry->setTarget( $this->mTitle
);
2263 $logEntry->setComment( $reason );
2264 $logid = $logEntry->insert();
2265 $logEntry->publish( $logid );
2268 $dbw->commit( __METHOD__
);
2271 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2272 return WikiPage
::DELETE_SUCCESS
;
2276 * Do some database updates after deletion
2278 * @param $id Int: page_id value of the page being deleted
2280 public function doDeleteUpdates( $id ) {
2281 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2283 $dbw = wfGetDB( DB_MASTER
);
2285 # Delete restrictions for it
2286 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2288 # Fix category table counts
2290 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2292 foreach ( $res as $row ) {
2293 $cats [] = $row->cl_to
;
2296 $this->updateCategoryCounts( array(), $cats );
2298 #TODO: move this to an Update object!
2300 # If using cascading deletes, we can skip some explicit deletes
2301 if ( !$dbw->cascadingDeletes() ) {
2302 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2304 # Delete outgoing links
2305 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2306 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2307 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2308 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2309 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2310 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2311 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2312 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2313 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2316 # If using cleanup triggers, we can skip some manual deletes
2317 if ( !$dbw->cleanupTriggers() ) {
2318 # Clean up recentchanges entries...
2319 $dbw->delete( 'recentchanges',
2320 array( 'rc_type != ' . RC_LOG
,
2321 'rc_namespace' => $this->mTitle
->getNamespace(),
2322 'rc_title' => $this->mTitle
->getDBkey() ),
2324 $dbw->delete( 'recentchanges',
2325 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2330 self
::onArticleDelete( $this->mTitle
);
2335 # Clear the cached article id so the interface doesn't act like we exist
2336 $this->mTitle
->resetArticleID( 0 );
2340 * Roll back the most recent consecutive set of edits to a page
2341 * from the same user; fails if there are no eligible edits to
2342 * roll back to, e.g. user is the sole contributor. This function
2343 * performs permissions checks on $user, then calls commitRollback()
2344 * to do the dirty work
2346 * @todo: seperate the business/permission stuff out from backend code
2348 * @param $fromP String: Name of the user whose edits to rollback.
2349 * @param $summary String: Custom summary. Set to default summary if empty.
2350 * @param $token String: Rollback token.
2351 * @param $bot Boolean: If true, mark all reverted edits as bot.
2353 * @param $resultDetails Array: contains result-specific array of additional values
2354 * 'alreadyrolled' : 'current' (rev)
2355 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2357 * @param $user User The user performing the rollback
2358 * @return array of errors, each error formatted as
2359 * array(messagekey, param1, param2, ...).
2360 * On success, the array is empty. This array can also be passed to
2361 * OutputPage::showPermissionsErrorPage().
2363 public function doRollback(
2364 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2366 $resultDetails = null;
2369 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2370 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2371 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2373 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2374 $errors[] = array( 'sessionfailure' );
2377 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2378 $errors[] = array( 'actionthrottledtext' );
2381 # If there were errors, bail out now
2382 if ( !empty( $errors ) ) {
2386 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2390 * Backend implementation of doRollback(), please refer there for parameter
2391 * and return value documentation
2393 * NOTE: This function does NOT check ANY permissions, it just commits the
2394 * rollback to the DB. Therefore, you should only call this function direct-
2395 * ly if you want to use custom permissions checks. If you don't, use
2396 * doRollback() instead.
2397 * @param $fromP String: Name of the user whose edits to rollback.
2398 * @param $summary String: Custom summary. Set to default summary if empty.
2399 * @param $bot Boolean: If true, mark all reverted edits as bot.
2401 * @param $resultDetails Array: contains result-specific array of additional values
2402 * @param $guser User The user performing the rollback
2405 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2406 global $wgUseRCPatrol, $wgContLang;
2408 $dbw = wfGetDB( DB_MASTER
);
2410 if ( wfReadOnly() ) {
2411 return array( array( 'readonlytext' ) );
2414 # Get the last editor
2415 $current = $this->getRevision();
2416 if ( is_null( $current ) ) {
2417 # Something wrong... no page?
2418 return array( array( 'notanarticle' ) );
2421 $from = str_replace( '_', ' ', $fromP );
2422 # User name given should match up with the top revision.
2423 # If the user was deleted then $from should be empty.
2424 if ( $from != $current->getUserText() ) {
2425 $resultDetails = array( 'current' => $current );
2426 return array( array( 'alreadyrolled',
2427 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2428 htmlspecialchars( $fromP ),
2429 htmlspecialchars( $current->getUserText() )
2433 # Get the last edit not by this guy...
2434 # Note: these may not be public values
2435 $user = intval( $current->getRawUser() );
2436 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2437 $s = $dbw->selectRow( 'revision',
2438 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2439 array( 'rev_page' => $current->getPage(),
2440 "rev_user != {$user} OR rev_user_text != {$user_text}"
2442 array( 'USE INDEX' => 'page_timestamp',
2443 'ORDER BY' => 'rev_timestamp DESC' )
2445 if ( $s === false ) {
2446 # No one else ever edited this page
2447 return array( array( 'cantrollback' ) );
2448 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2449 # Only admins can see this text
2450 return array( array( 'notvisiblerev' ) );
2454 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2455 # Mark all reverted edits as bot
2459 if ( $wgUseRCPatrol ) {
2460 # Mark all reverted edits as patrolled
2461 $set['rc_patrolled'] = 1;
2464 if ( count( $set ) ) {
2465 $dbw->update( 'recentchanges', $set,
2467 'rc_cur_id' => $current->getPage(),
2468 'rc_user_text' => $current->getUserText(),
2469 "rc_timestamp > '{$s->rev_timestamp}'",
2474 # Generate the edit summary if necessary
2475 $target = Revision
::newFromId( $s->rev_id
);
2476 if ( empty( $summary ) ) {
2477 if ( $from == '' ) { // no public user name
2478 $summary = wfMsgForContent( 'revertpage-nouser' );
2480 $summary = wfMsgForContent( 'revertpage' );
2484 # Allow the custom summary to use the same args as the default message
2486 $target->getUserText(), $from, $s->rev_id
,
2487 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2488 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2490 $summary = wfMsgReplaceArgs( $summary, $args );
2493 $flags = EDIT_UPDATE
;
2495 if ( $guser->isAllowed( 'minoredit' ) ) {
2496 $flags |
= EDIT_MINOR
;
2499 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2500 $flags |
= EDIT_FORCE_BOT
;
2503 # Actually store the edit
2504 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2505 if ( !empty( $status->value
['revision'] ) ) {
2506 $revId = $status->value
['revision']->getId();
2511 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2513 $resultDetails = array(
2514 'summary' => $summary,
2515 'current' => $current,
2516 'target' => $target,
2524 * The onArticle*() functions are supposed to be a kind of hooks
2525 * which should be called whenever any of the specified actions
2528 * This is a good place to put code to clear caches, for instance.
2530 * This is called on page move and undelete, as well as edit
2532 * @param $title Title object
2534 public static function onArticleCreate( $title ) {
2535 # Update existence markers on article/talk tabs...
2536 if ( $title->isTalkPage() ) {
2537 $other = $title->getSubjectPage();
2539 $other = $title->getTalkPage();
2542 $other->invalidateCache();
2543 $other->purgeSquid();
2545 $title->touchLinks();
2546 $title->purgeSquid();
2547 $title->deleteTitleProtection();
2551 * Clears caches when article is deleted
2553 * @param $title Title
2555 public static function onArticleDelete( $title ) {
2556 # Update existence markers on article/talk tabs...
2557 if ( $title->isTalkPage() ) {
2558 $other = $title->getSubjectPage();
2560 $other = $title->getTalkPage();
2563 $other->invalidateCache();
2564 $other->purgeSquid();
2566 $title->touchLinks();
2567 $title->purgeSquid();
2570 HTMLFileCache
::clearFileCache( $title );
2573 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2574 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2578 if ( $title->getNamespace() == NS_FILE
) {
2579 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2580 $update->doUpdate();
2584 if ( $title->getNamespace() == NS_USER_TALK
) {
2585 $user = User
::newFromName( $title->getText(), false );
2587 $user->setNewtalk( false );
2592 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2596 * Purge caches on page update etc
2598 * @param $title Title object
2599 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2601 public static function onArticleEdit( $title ) {
2602 // Invalidate caches of articles which include this page
2603 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2606 // Invalidate the caches of all pages which redirect here
2607 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2609 # Purge squid for this page only
2610 $title->purgeSquid();
2612 # Clear file cache for this page only
2613 HTMLFileCache
::clearFileCache( $title );
2619 * Returns a list of hidden categories this page is a member of.
2620 * Uses the page_props and categorylinks tables.
2622 * @return Array of Title objects
2624 public function getHiddenCategories() {
2626 $id = $this->mTitle
->getArticleID();
2632 $dbr = wfGetDB( DB_SLAVE
);
2633 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2635 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2636 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2639 if ( $res !== false ) {
2640 foreach ( $res as $row ) {
2641 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2649 * Return an applicable autosummary if one exists for the given edit.
2650 * @param $oldtext String|null: the previous text of the page.
2651 * @param $newtext String|null: The submitted text of the page.
2652 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2653 * @return string An appropriate autosummary, or an empty string.
2654 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
2656 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2657 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2659 wfDeprecated( __METHOD__
, '1.WD' );
2661 $handler = ContentHandler
::getForModelName( CONTENT_MODEL_WIKITEXT
);
2662 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
2663 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
2665 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2669 * Auto-generates a deletion reason
2671 * @param &$hasHistory Boolean: whether the page has a history
2672 * @return mixed String containing deletion reason or empty string, or boolean false
2673 * if no revision occurred
2674 * @deprecated since 1.WD, use ContentHandler::getAutoDeleteReason() instead
2676 public function getAutoDeleteReason( &$hasHistory ) {
2677 #NOTE: stub for backwards-compatibility.
2679 wfDeprecated( __METHOD__
, '1.WD' );
2681 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2682 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2685 // Get the last revision
2686 $rev = $this->getRevision();
2688 if ( is_null( $rev ) ) {
2692 // Get the article's contents
2693 $contents = $rev->getText();
2696 // If the page is blank, use the text from the previous revision,
2697 // which can only be blank if there's a move/import/protect dummy revision involved
2698 if ( $contents == '' ) {
2699 $prev = $rev->getPrevious();
2702 $contents = $prev->getText();
2707 $dbw = wfGetDB( DB_MASTER
);
2709 // Find out if there was only one contributor
2710 // Only scan the last 20 revisions
2711 $res = $dbw->select( 'revision', 'rev_user_text',
2712 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2714 array( 'LIMIT' => 20 )
2717 if ( $res === false ) {
2718 // This page has no revisions, which is very weird
2722 $hasHistory = ( $res->numRows() > 1 );
2723 $row = $dbw->fetchObject( $res );
2725 if ( $row ) { // $row is false if the only contributor is hidden
2726 $onlyAuthor = $row->rev_user_text
;
2727 // Try to find a second contributor
2728 foreach ( $res as $row ) {
2729 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2730 $onlyAuthor = false;
2735 $onlyAuthor = false;
2738 // Generate the summary with a '$1' placeholder
2740 // The current revision is blank and the one before is also
2741 // blank. It's just not our lucky day
2742 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2744 if ( $onlyAuthor ) {
2745 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2747 $reason = wfMsgForContent( 'excontent', '$1' );
2751 if ( $reason == '-' ) {
2752 // Allow these UI messages to be blanked out cleanly
2756 // Replace newlines with spaces to prevent uglyness
2757 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2758 // Calculate the maximum amount of chars to get
2759 // Max content length = max comment length - length of the comment (excl. $1)
2760 $maxLength = 255 - ( strlen( $reason ) - 2 );
2761 $contents = $wgContLang->truncate( $contents, $maxLength );
2762 // Remove possible unfinished links
2763 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2764 // Now replace the '$1' placeholder
2765 $reason = str_replace( '$1', $contents, $reason );
2771 * Update all the appropriate counts in the category table, given that
2772 * we've added the categories $added and deleted the categories $deleted.
2774 * @param $added array The names of categories that were added
2775 * @param $deleted array The names of categories that were deleted
2777 public function updateCategoryCounts( $added, $deleted ) {
2778 $ns = $this->mTitle
->getNamespace();
2779 $dbw = wfGetDB( DB_MASTER
);
2781 # First make sure the rows exist. If one of the "deleted" ones didn't
2782 # exist, we might legitimately not create it, but it's simpler to just
2783 # create it and then give it a negative value, since the value is bogus
2786 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2787 $insertCats = array_merge( $added, $deleted );
2788 if ( !$insertCats ) {
2789 # Okay, nothing to do
2793 $insertRows = array();
2795 foreach ( $insertCats as $cat ) {
2796 $insertRows[] = array(
2797 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2801 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2803 $addFields = array( 'cat_pages = cat_pages + 1' );
2804 $removeFields = array( 'cat_pages = cat_pages - 1' );
2806 if ( $ns == NS_CATEGORY
) {
2807 $addFields[] = 'cat_subcats = cat_subcats + 1';
2808 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2809 } elseif ( $ns == NS_FILE
) {
2810 $addFields[] = 'cat_files = cat_files + 1';
2811 $removeFields[] = 'cat_files = cat_files - 1';
2818 array( 'cat_title' => $added ),
2827 array( 'cat_title' => $deleted ),
2834 * Updates cascading protections
2836 * @param $parserOutput ParserOutput object for the current version
2838 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2839 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2843 // templatelinks table may have become out of sync,
2844 // especially if using variable-based transclusions.
2845 // For paranoia, check if things have changed and if
2846 // so apply updates to the database. This will ensure
2847 // that cascaded protections apply as soon as the changes
2850 # Get templates from templatelinks
2851 $id = $this->mTitle
->getArticleID();
2853 $tlTemplates = array();
2855 $dbr = wfGetDB( DB_SLAVE
);
2856 $res = $dbr->select( array( 'templatelinks' ),
2857 array( 'tl_namespace', 'tl_title' ),
2858 array( 'tl_from' => $id ),
2862 foreach ( $res as $row ) {
2863 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2866 # Get templates from parser output.
2867 $poTemplates = array();
2868 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2869 foreach ( $templates as $dbk => $id ) {
2870 $poTemplates["$ns:$dbk"] = true;
2875 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2877 if ( count( $templates_diff ) > 0 ) {
2878 # Whee, link updates time.
2879 # Note: we are only interested in links here. We don't need to get other SecondaryDataUpdate items from the parser output.
2880 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2886 * Return a list of templates used by this article.
2887 * Uses the templatelinks table
2889 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2890 * @return Array of Title objects
2892 public function getUsedTemplates() {
2893 return $this->mTitle
->getTemplateLinksFrom();
2897 * Perform article updates on a special page creation.
2899 * @param $rev Revision object
2901 * @todo This is a shitty interface function. Kill it and replace the
2902 * other shitty functions like doEditUpdates and such so it's not needed
2904 * @deprecated since 1.18, use doEditUpdates()
2906 public function createUpdates( $rev ) {
2907 wfDeprecated( __METHOD__
, '1.18' );
2909 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2913 * This function is called right before saving the wikitext,
2914 * so we can do things like signatures and links-in-context.
2916 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2917 * @param $text String article contents
2918 * @param $user User object: user doing the edit
2919 * @param $popts ParserOptions object: parser options, default options for
2920 * the user loaded if null given
2921 * @return string article contents with altered wikitext markup (signatures
2922 * converted, {{subst:}}, templates, etc.)
2924 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2925 global $wgParser, $wgUser;
2927 wfDeprecated( __METHOD__
, '1.19' );
2929 $user = is_null( $user ) ?
$wgUser : $user;
2931 if ( $popts === null ) {
2932 $popts = ParserOptions
::newFromUser( $user );
2935 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2939 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2941 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2944 public function isBigDeletion() {
2945 wfDeprecated( __METHOD__
, '1.19' );
2946 return $this->mTitle
->isBigDeletion();
2950 * Get the approximate revision count of this page.
2952 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2955 public function estimateRevisionCount() {
2956 wfDeprecated( __METHOD__
, '1.19' );
2957 return $this->mTitle
->estimateRevisionCount();
2961 * Update the article's restriction field, and leave a log entry.
2963 * @deprecated since 1.19
2964 * @param $limit Array: set of restriction keys
2965 * @param $reason String
2966 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2967 * @param $expiry Array: per restriction type expiration
2968 * @param $user User The user updating the restrictions
2969 * @return bool true on success
2971 public function updateRestrictions(
2972 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2976 $user = is_null( $user ) ?
$wgUser : $user;
2978 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2982 * @deprecated since 1.18
2984 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2985 wfDeprecated( __METHOD__
, '1.18' );
2987 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2991 * @deprecated since 1.18
2993 public function viewUpdates() {
2994 wfDeprecated( __METHOD__
, '1.18' );
2996 return $this->doViewUpdates( $wgUser );
3000 * @deprecated since 1.18
3003 public function useParserCache( $oldid ) {
3004 wfDeprecated( __METHOD__
, '1.18' );
3006 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3010 class PoolWorkArticleView
extends PoolCounterWork
{
3028 * @var ParserOptions
3030 private $parserOptions;
3038 * @var ParserOutput|bool
3040 private $parserOutput = false;
3045 private $isDirty = false;
3050 private $error = false;
3056 * @param $revid Integer: ID of the revision being parsed
3057 * @param $useParserCache Boolean: whether to use the parser cache
3058 * @param $parserOptions parserOptions to use for the parse operation
3059 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3060 * @param $context IContextSource context for parsing
3062 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null, IContextSource
$context = null ) {
3063 if ( is_string($content) ) { #BC: old style call
3064 $modelName = $page->getRevision()->getContentModelName();
3065 $format = $page->getRevision()->getContentFormat();
3066 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelName, $format );
3069 if ( is_null( $context ) ) {
3070 $context = RequestContext
::getMain();
3071 #XXX: clone and then set title?
3074 $this->page
= $page;
3075 $this->revid
= $revid;
3076 $this->context
= $context;
3077 $this->cacheable
= $useParserCache;
3078 $this->parserOptions
= $parserOptions;
3079 $this->content
= $content;
3080 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3081 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3085 * Get the ParserOutput from this object, or false in case of failure
3087 * @return ParserOutput
3089 public function getParserOutput() {
3090 return $this->parserOutput
;
3094 * Get whether the ParserOutput is a dirty one (i.e. expired)
3098 public function getIsDirty() {
3099 return $this->isDirty
;
3103 * Get a Status object in case of error or false otherwise
3105 * @return Status|bool
3107 public function getError() {
3108 return $this->error
;
3115 global $wgUseFileCache;
3117 // @todo: several of the methods called on $this->page are not declared in Page, but present in WikiPage and delegated by Article.
3119 $isCurrent = $this->revid
=== $this->page
->getLatest();
3121 if ( $this->content
!== null ) {
3122 $content = $this->content
;
3123 } elseif ( $isCurrent ) {
3124 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
3126 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3127 if ( $rev === null ) {
3130 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
3133 $time = - microtime( true );
3134 // TODO: page might not have this method? Hard to tell what page is supposed to be here...
3135 $this->parserOutput
= $content->getParserOutput( $this->context
, $this->revid
, $this->parserOptions
);
3136 $time +
= microtime( true );
3140 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3141 $this->page
->getTitle()->getPrefixedDBkey() ) );
3144 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3145 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3148 // Make sure file cache is not used on uncacheable content.
3149 // Output that has magic words in it can still use the parser cache
3150 // (if enabled), though it will generally expire sooner.
3151 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3152 $wgUseFileCache = false;
3156 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3165 function getCachedWork() {
3166 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3168 if ( $this->parserOutput
=== false ) {
3169 wfDebug( __METHOD__
. ": parser cache miss\n" );
3172 wfDebug( __METHOD__
. ": parser cache hit\n" );
3180 function fallback() {
3181 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3183 if ( $this->parserOutput
=== false ) {
3184 wfDebugLog( 'dirty', "dirty missing\n" );
3185 wfDebug( __METHOD__
. ": no dirty cache\n" );
3188 wfDebug( __METHOD__
. ": sending dirty output\n" );
3189 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3190 $this->isDirty
= true;
3196 * @param $status Status
3199 function error( $status ) {
3200 $this->error
= $status;