3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
8 * Class representing a MediaWiki article and history.
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
13 * @internal documentation reviewed 15 Mar 2010
15 class WikiPage
extends Page
{
19 public $mTitle = null;
24 public $mDataLoaded = false; // !< Boolean
25 public $mIsRedirect = false; // !< Boolean
26 public $mLatest = false; // !< Integer (false means "not loaded")
27 public $mPreparedEdit = false; // !< Array
33 protected $mRedirectTarget = null;
38 protected $mLastRevision = null;
41 * @var string; timestamp of the current revision or empty string if not loaded
43 protected $mTimestamp = '';
48 protected $mTouched = '19700101000000';
53 protected $mCounter = null;
56 * Constructor and clear the article
57 * @param $title Title Reference to a Title object.
59 public function __construct( Title
$title ) {
60 $this->mTitle
= $title;
64 * Create a WikiPage object of the appropriate class for the given title.
67 * @return WikiPage object of the appropriate type
69 public static function factory( Title
$title ) {
70 $ns = $title->getNamespace();
72 if ( $ns == NS_MEDIA
) {
73 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
74 } elseif ( $ns < 0 ) {
75 throw new MWException( "Invalid or virtual namespace $ns given." );
80 $page = new WikiFilePage( $title );
83 $page = new WikiCategoryPage( $title );
86 $page = new WikiPage( $title );
93 * Constructor from a page id
95 * @param $id Int article ID to load
99 public static function newFromID( $id ) {
100 $t = Title
::newFromID( $id );
102 return self
::factory( $t );
108 * Returns overrides for action handlers.
109 * Classes listed here will be used instead of the default one when
110 * (and only when) $wgActions[$action] === true. This allows subclasses
111 * to override the default behavior.
113 * @todo: move this UI stuff somewhere else
117 public function getActionOverrides() {
122 * Get the title object of the article
123 * @return Title object of this page
125 public function getTitle() {
126 return $this->mTitle
;
132 public function clear() {
133 $this->mDataLoaded
= false;
135 $this->mCounter
= null;
136 $this->mRedirectTarget
= null; # Title object if set
137 $this->mLastRevision
= null; # Latest revision
138 $this->mTouched
= '19700101000000';
139 $this->mTimestamp
= '';
140 $this->mIsRedirect
= false;
141 $this->mLatest
= false;
142 $this->mPreparedEdit
= false;
146 * Return the list of revision fields that should be selected to create
151 public static function selectFields() {
168 * Fetch a page record with the given conditions
169 * @param $dbr DatabaseBase object
170 * @param $conditions Array
171 * @return mixed Database result resource, or false on failure
173 protected function pageData( $dbr, $conditions ) {
174 $fields = self
::selectFields();
176 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
178 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
180 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
186 * Fetch a page record matching the Title object's namespace and title
187 * using a sanitized title string
189 * @param $dbr DatabaseBase object
190 * @param $title Title object
191 * @return mixed Database result resource, or false on failure
193 public function pageDataFromTitle( $dbr, $title ) {
194 return $this->pageData( $dbr, array(
195 'page_namespace' => $title->getNamespace(),
196 'page_title' => $title->getDBkey() ) );
200 * Fetch a page record matching the requested ID
202 * @param $dbr DatabaseBase
204 * @return mixed Database result resource, or false on failure
206 public function pageDataFromId( $dbr, $id ) {
207 return $this->pageData( $dbr, array( 'page_id' => $id ) );
211 * Set the general counter, title etc data loaded from
214 * @param $data Object|String One of the following:
215 * A DB query result object or...
216 * "fromdb" to get from a slave DB or...
217 * "fromdbmaster" to get from the master DB
220 public function loadPageData( $data = 'fromdb' ) {
221 if ( $data === 'fromdbmaster' ) {
222 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
223 } elseif ( $data === 'fromdb' ) { // slave
224 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
225 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
226 # Note that DB also stores the master position in the session and checks it.
227 $touched = $this->getCachedLastEditTime();
228 if ( $touched ) { // key set
229 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
230 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
235 $lc = LinkCache
::singleton();
238 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
240 $this->mTitle
->loadFromRow( $data );
242 # Old-fashioned restrictions
243 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
245 $this->mCounter
= intval( $data->page_counter
);
246 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
247 $this->mIsRedirect
= intval( $data->page_is_redirect
);
248 $this->mLatest
= intval( $data->page_latest
);
250 $lc->addBadLinkObj( $this->mTitle
);
252 $this->mTitle
->loadFromRow( false );
255 $this->mDataLoaded
= true;
259 * @return int Page ID
261 public function getId() {
262 return $this->mTitle
->getArticleID();
266 * @return bool Whether or not the page exists in the database
268 public function exists() {
269 return $this->mTitle
->exists();
273 * Check if this page is something we're going to be showing
274 * some sort of sensible content for. If we return false, page
275 * views (plain action=view) will return an HTTP 404 response,
276 * so spiders and robots can know they're following a bad link.
280 public function hasViewableContent() {
281 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
285 * @return int The view count for the page
287 public function getCount() {
288 if ( !$this->mDataLoaded
) {
289 $this->loadPageData();
292 return $this->mCounter
;
296 * Tests if the article text represents a redirect
298 * @param $text mixed string containing article contents, or boolean
301 public function isRedirect( $text = false ) {
302 if ( $text === false ) {
303 if ( !$this->mDataLoaded
) {
304 $this->loadPageData();
307 return (bool)$this->mIsRedirect
;
309 return Title
::newFromRedirect( $text ) !== null;
314 * Loads page_touched and returns a value indicating if it should be used
315 * @return boolean true if not a redirect
317 public function checkTouched() {
318 if ( !$this->mDataLoaded
) {
319 $this->loadPageData();
321 return !$this->mIsRedirect
;
325 * Get the page_touched field
326 * @return string containing GMT timestamp
328 public function getTouched() {
329 if ( !$this->mDataLoaded
) {
330 $this->loadPageData();
332 return $this->mTouched
;
336 * Get the page_latest field
337 * @return integer rev_id of current revision
339 public function getLatest() {
340 if ( !$this->mDataLoaded
) {
341 $this->loadPageData();
343 return (int)$this->mLatest
;
347 * Loads everything except the text
348 * This isn't necessary for all uses, so it's only done if needed.
350 protected function loadLastEdit() {
351 if ( $this->mLastRevision
!== null ) {
352 return; // already loaded
355 $latest = $this->getLatest();
357 return; // page doesn't exist or is missing page_latest info
360 $revision = Revision
::newFromPageId( $this->getId(), $latest );
361 if ( $revision ) { // sanity
362 $this->setLastEdit( $revision );
367 * Set the latest revision
369 protected function setLastEdit( Revision
$revision ) {
370 $this->mLastRevision
= $revision;
371 $this->mTimestamp
= $revision->getTimestamp();
375 * Get the latest revision
376 * @return Revision|null
378 public function getRevision() {
379 $this->loadLastEdit();
380 if ( $this->mLastRevision
) {
381 return $this->mLastRevision
;
387 * Get the text of the current revision. No side-effects...
389 * @param $audience Integer: one of:
390 * Revision::FOR_PUBLIC to be displayed to all users
391 * Revision::FOR_THIS_USER to be displayed to $wgUser
392 * Revision::RAW get the text regardless of permissions
393 * @return String|false The text of the current revision
395 public function getText( $audience = Revision
::FOR_PUBLIC
) {
396 $this->loadLastEdit();
397 if ( $this->mLastRevision
) {
398 return $this->mLastRevision
->getText( $audience );
404 * Get the text of the current revision. No side-effects...
406 * @return String|false The text of the current revision
408 public function getRawText() {
409 $this->loadLastEdit();
410 if ( $this->mLastRevision
) {
411 return $this->mLastRevision
->getRawText();
417 * @return string MW timestamp of last article revision
419 public function getTimestamp() {
420 // Check if the field has been filled by WikiPage::setTimestamp()
421 if ( !$this->mTimestamp
) {
422 $this->loadLastEdit();
424 return wfTimestamp( TS_MW
, $this->mTimestamp
);
428 * Set the page timestamp (use only to avoid DB queries)
429 * @param $ts string MW timestamp of last article revision
432 public function setTimestamp( $ts ) {
433 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
437 * @param $audience Integer: one of:
438 * Revision::FOR_PUBLIC to be displayed to all users
439 * Revision::FOR_THIS_USER to be displayed to $wgUser
440 * Revision::RAW get the text regardless of permissions
441 * @return int user ID for the user that made the last article revision
443 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
444 $this->loadLastEdit();
445 if ( $this->mLastRevision
) {
446 return $this->mLastRevision
->getUser( $audience );
453 * @param $audience Integer: one of:
454 * Revision::FOR_PUBLIC to be displayed to all users
455 * Revision::FOR_THIS_USER to be displayed to $wgUser
456 * Revision::RAW get the text regardless of permissions
457 * @return string username of the user that made the last article revision
459 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
460 $this->loadLastEdit();
461 if ( $this->mLastRevision
) {
462 return $this->mLastRevision
->getUserText( $audience );
469 * @param $audience Integer: one of:
470 * Revision::FOR_PUBLIC to be displayed to all users
471 * Revision::FOR_THIS_USER to be displayed to $wgUser
472 * Revision::RAW get the text regardless of permissions
473 * @return string Comment stored for the last article revision
475 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
476 $this->loadLastEdit();
477 if ( $this->mLastRevision
) {
478 return $this->mLastRevision
->getComment( $audience );
485 * Returns true if last revision was marked as "minor edit"
487 * @return boolean Minor edit indicator for the last article revision.
489 public function getMinorEdit() {
490 $this->loadLastEdit();
491 if ( $this->mLastRevision
) {
492 return $this->mLastRevision
->isMinor();
499 * Get the cached timestamp for the last time the page changed.
500 * This is only used to help handle slave lag by comparing to page_touched.
501 * @return string MW timestamp
503 protected function getCachedLastEditTime() {
505 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
506 return $wgMemc->get( $key );
510 * Set the cached timestamp for the last time the page changed.
511 * This is only used to help handle slave lag by comparing to page_touched.
512 * @param $timestamp string
515 public function setCachedLastEditTime( $timestamp ) {
517 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
518 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
522 * Determine whether a page would be suitable for being counted as an
523 * article in the site_stats table based on the title & its content
525 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
526 * if false, the current database state will be used
529 public function isCountable( $editInfo = false ) {
530 global $wgArticleCountMethod;
532 if ( !$this->mTitle
->isContentPage() ) {
536 $text = $editInfo ?
$editInfo->pst
: false;
538 if ( $this->isRedirect( $text ) ) {
542 switch ( $wgArticleCountMethod ) {
546 if ( $text === false ) {
547 $text = $this->getRawText();
549 return strpos( $text, ',' ) !== false;
552 // ParserOutput::getLinks() is a 2D array of page links, so
553 // to be really correct we would need to recurse in the array
554 // but the main array should only have items in it if there are
556 return (bool)count( $editInfo->output
->getLinks() );
558 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
559 array( 'pl_from' => $this->getId() ), __METHOD__
);
565 * If this page is a redirect, get its target
567 * The target will be fetched from the redirect table if possible.
568 * If this page doesn't have an entry there, call insertRedirect()
569 * @return Title|mixed object, or null if this page is not a redirect
571 public function getRedirectTarget() {
572 if ( !$this->mTitle
->isRedirect() ) {
576 if ( $this->mRedirectTarget
!== null ) {
577 return $this->mRedirectTarget
;
580 # Query the redirect table
581 $dbr = wfGetDB( DB_SLAVE
);
582 $row = $dbr->selectRow( 'redirect',
583 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
584 array( 'rd_from' => $this->getId() ),
588 // rd_fragment and rd_interwiki were added later, populate them if empty
589 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
590 return $this->mRedirectTarget
= Title
::makeTitle(
591 $row->rd_namespace
, $row->rd_title
,
592 $row->rd_fragment
, $row->rd_interwiki
);
595 # This page doesn't have an entry in the redirect table
596 return $this->mRedirectTarget
= $this->insertRedirect();
600 * Insert an entry for this page into the redirect table.
602 * Don't call this function directly unless you know what you're doing.
603 * @return Title object or null if not a redirect
605 public function insertRedirect() {
606 // recurse through to only get the final target
607 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
611 $this->insertRedirectEntry( $retval );
616 * Insert or update the redirect table entry for this page to indicate
617 * it redirects to $rt .
618 * @param $rt Title redirect target
620 public function insertRedirectEntry( $rt ) {
621 $dbw = wfGetDB( DB_MASTER
);
622 $dbw->replace( 'redirect', array( 'rd_from' ),
624 'rd_from' => $this->getId(),
625 'rd_namespace' => $rt->getNamespace(),
626 'rd_title' => $rt->getDBkey(),
627 'rd_fragment' => $rt->getFragment(),
628 'rd_interwiki' => $rt->getInterwiki(),
635 * Get the Title object or URL this page redirects to
637 * @return mixed false, Title of in-wiki target, or string with URL
639 public function followRedirect() {
640 return $this->getRedirectURL( $this->getRedirectTarget() );
644 * Get the Title object or URL to use for a redirect. We use Title
645 * objects for same-wiki, non-special redirects and URLs for everything
647 * @param $rt Title Redirect target
648 * @return mixed false, Title object of local target, or string with URL
650 public function getRedirectURL( $rt ) {
655 if ( $rt->isExternal() ) {
656 if ( $rt->isLocal() ) {
657 // Offsite wikis need an HTTP redirect.
659 // This can be hard to reverse and may produce loops,
660 // so they may be disabled in the site configuration.
661 $source = $this->mTitle
->getFullURL( 'redirect=no' );
662 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
664 // External pages pages without "local" bit set are not valid
670 if ( $rt->isSpecialPage() ) {
671 // Gotta handle redirects to special pages differently:
672 // Fill the HTTP response "Location" header and ignore
673 // the rest of the page we're on.
675 // Some pages are not valid targets
676 if ( $rt->isValidRedirectTarget() ) {
677 return $rt->getFullURL();
687 * Get a list of users who have edited this article, not including the user who made
688 * the most recent revision, which you can get from $article->getUser() if you want it
689 * @return UserArrayFromResult
691 public function getContributors() {
692 # @todo FIXME: This is expensive; cache this info somewhere.
694 $dbr = wfGetDB( DB_SLAVE
);
696 if ( $dbr->implicitGroupby() ) {
697 $realNameField = 'user_real_name';
699 $realNameField = 'MIN(user_real_name) AS user_real_name';
702 $tables = array( 'revision', 'user' );
705 'rev_user as user_id',
706 'rev_user_text AS user_name',
708 'MAX(rev_timestamp) AS timestamp',
711 $conds = array( 'rev_page' => $this->getId() );
713 // The user who made the top revision gets credited as "this page was last edited by
714 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
715 $user = $this->getUser();
717 $conds[] = "rev_user != $user";
719 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
722 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
725 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
729 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
730 'ORDER BY' => 'timestamp DESC',
733 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
734 return new UserArrayFromResult( $res );
738 * Get the last N authors
739 * @param $num Integer: number of revisions to get
740 * @param $revLatest String: the latest rev_id, selected from the master (optional)
741 * @return array Array of authors, duplicates not removed
743 public function getLastNAuthors( $num, $revLatest = 0 ) {
744 wfProfileIn( __METHOD__
);
745 // First try the slave
746 // If that doesn't have the latest revision, try the master
748 $db = wfGetDB( DB_SLAVE
);
751 $res = $db->select( array( 'page', 'revision' ),
752 array( 'rev_id', 'rev_user_text' ),
754 'page_namespace' => $this->mTitle
->getNamespace(),
755 'page_title' => $this->mTitle
->getDBkey(),
759 'ORDER BY' => 'rev_timestamp DESC',
765 wfProfileOut( __METHOD__
);
769 $row = $db->fetchObject( $res );
771 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
772 $db = wfGetDB( DB_MASTER
);
777 } while ( $continue );
779 $authors = array( $row->rev_user_text
);
781 foreach ( $res as $row ) {
782 $authors[] = $row->rev_user_text
;
785 wfProfileOut( __METHOD__
);
790 * Should the parser cache be used?
792 * @param $parserOptions ParserOptions to check
796 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
797 global $wgEnableParserCache;
799 return $wgEnableParserCache
800 && $parserOptions->getStubThreshold() == 0
801 && $this->mTitle
->exists()
802 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
803 && $this->mTitle
->isWikitextPage();
807 * Get a ParserOutput for the given ParserOptions and revision ID.
808 * The parser cache will be used if possible.
811 * @param $parserOptions ParserOptions to use for the parse operation
812 * @param $oldid Revision ID to get the text from, passing null or 0 will
813 * get the current revision (default value)
814 * @return ParserOutput or false if the revision was not found
816 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
817 wfProfileIn( __METHOD__
);
819 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
820 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
821 if ( $parserOptions->getStubThreshold() ) {
822 wfIncrStats( 'pcache_miss_stub' );
825 if ( $useParserCache ) {
826 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
827 if ( $parserOutput !== false ) {
828 wfProfileOut( __METHOD__
);
829 return $parserOutput;
833 if ( $oldid === null ||
$oldid === 0 ) {
834 $oldid = $this->getLatest();
837 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
840 wfProfileOut( __METHOD__
);
842 return $pool->getParserOutput();
846 * Do standard deferred updates after page view
847 * @param $user User The relevant user
849 public function doViewUpdates( User
$user ) {
850 global $wgDisableCounters;
851 if ( wfReadOnly() ) {
855 # Don't update page view counters on views from bot users (bug 14044)
856 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
857 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
858 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
861 # Update newtalk / watchlist notification status
862 $user->clearNotification( $this->mTitle
);
866 * Perform the actions of a page purging
868 public function doPurge() {
871 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
875 // Invalidate the cache
876 $this->mTitle
->invalidateCache();
880 // Commit the transaction before the purge is sent
881 $dbw = wfGetDB( DB_MASTER
);
885 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
889 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
890 if ( $this->mTitle
->exists() ) {
891 $text = $this->getRawText();
896 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
902 * Insert a new empty page record for this article.
903 * This *must* be followed up by creating a revision
904 * and running $this->updateRevisionOn( ... );
905 * or else the record will be left in a funky state.
906 * Best if all done inside a transaction.
908 * @param $dbw DatabaseBase
909 * @return int The newly created page_id key, or false if the title already existed
911 public function insertOn( $dbw ) {
912 wfProfileIn( __METHOD__
);
914 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
915 $dbw->insert( 'page', array(
916 'page_id' => $page_id,
917 'page_namespace' => $this->mTitle
->getNamespace(),
918 'page_title' => $this->mTitle
->getDBkey(),
920 'page_restrictions' => '',
921 'page_is_redirect' => 0, # Will set this shortly...
923 'page_random' => wfRandom(),
924 'page_touched' => $dbw->timestamp(),
925 'page_latest' => 0, # Fill this in shortly...
926 'page_len' => 0, # Fill this in shortly...
927 ), __METHOD__
, 'IGNORE' );
929 $affected = $dbw->affectedRows();
932 $newid = $dbw->insertId();
933 $this->mTitle
->resetArticleID( $newid );
935 wfProfileOut( __METHOD__
);
937 return $affected ?
$newid : false;
941 * Update the page record to point to a newly saved revision.
943 * @param $dbw DatabaseBase: object
944 * @param $revision Revision: For ID number, and text used to set
945 * length and redirect status fields
946 * @param $lastRevision Integer: if given, will not overwrite the page field
947 * when different from the currently set value.
948 * Giving 0 indicates the new page flag should be set
950 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
951 * removing rows in redirect table.
952 * @return bool true on success, false on failure
955 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
956 wfProfileIn( __METHOD__
);
958 $text = $revision->getText();
959 $len = strlen( $text );
960 $rt = Title
::newFromRedirectRecurse( $text );
962 $conditions = array( 'page_id' => $this->getId() );
964 if ( !is_null( $lastRevision ) ) {
965 # An extra check against threads stepping on each other
966 $conditions['page_latest'] = $lastRevision;
969 $now = wfTimestampNow();
970 $dbw->update( 'page',
972 'page_latest' => $revision->getId(),
973 'page_touched' => $dbw->timestamp( $now ),
974 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
975 'page_is_redirect' => $rt !== null ?
1 : 0,
981 $result = $dbw->affectedRows() != 0;
983 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
984 $this->setLastEdit( $revision );
985 $this->setCachedLastEditTime( $now );
986 $this->mLatest
= $revision->getId();
987 $this->mIsRedirect
= (bool)$rt;
988 # Update the LinkCache.
989 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
992 wfProfileOut( __METHOD__
);
997 * Add row to the redirect table if this is a redirect, remove otherwise.
999 * @param $dbw DatabaseBase
1000 * @param $redirectTitle Title object pointing to the redirect target,
1001 * or NULL if this is not a redirect
1002 * @param $lastRevIsRedirect If given, will optimize adding and
1003 * removing rows in redirect table.
1004 * @return bool true on success, false on failure
1007 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1008 // Always update redirects (target link might have changed)
1009 // Update/Insert if we don't know if the last revision was a redirect or not
1010 // Delete if changing from redirect to non-redirect
1011 $isRedirect = !is_null( $redirectTitle );
1013 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1017 wfProfileIn( __METHOD__
);
1018 if ( $isRedirect ) {
1019 $this->insertRedirectEntry( $redirectTitle );
1021 // This is not a redirect, remove row from redirect table
1022 $where = array( 'rd_from' => $this->getId() );
1023 $dbw->delete( 'redirect', $where, __METHOD__
);
1026 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1027 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1029 wfProfileOut( __METHOD__
);
1031 return ( $dbw->affectedRows() != 0 );
1035 * If the given revision is newer than the currently set page_latest,
1036 * update the page record. Otherwise, do nothing.
1038 * @param $dbw Database object
1039 * @param $revision Revision object
1042 public function updateIfNewerOn( $dbw, $revision ) {
1043 wfProfileIn( __METHOD__
);
1045 $row = $dbw->selectRow(
1046 array( 'revision', 'page' ),
1047 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1049 'page_id' => $this->getId(),
1050 'page_latest=rev_id' ),
1054 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1055 wfProfileOut( __METHOD__
);
1058 $prev = $row->rev_id
;
1059 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1061 # No or missing previous revision; mark the page as new
1063 $lastRevIsRedirect = null;
1066 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1068 wfProfileOut( __METHOD__
);
1073 * Get the text that needs to be saved in order to undo all revisions
1074 * between $undo and $undoafter. Revisions must belong to the same page,
1075 * must exist and must not be deleted
1076 * @param $undo Revision
1077 * @param $undoafter Revision Must be an earlier revision than $undo
1078 * @return mixed string on success, false on failure
1080 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1081 $cur_text = $this->getRawText();
1082 if ( $cur_text === false ) {
1083 return false; // no page
1085 $undo_text = $undo->getText();
1086 $undoafter_text = $undoafter->getText();
1088 if ( $cur_text == $undo_text ) {
1089 # No use doing a merge if it's just a straight revert.
1090 return $undoafter_text;
1095 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1099 return $undone_text;
1103 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1104 * @param $text String: new text of the section
1105 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1106 * @param $edittime String: revision timestamp or null to use the current revision
1107 * @return string Complete article text, or null if error
1109 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1110 wfProfileIn( __METHOD__
);
1112 if ( strval( $section ) == '' ) {
1113 // Whole-page edit; let the whole text through
1115 // Bug 30711: always use current version when adding a new section
1116 if ( is_null( $edittime ) ||
$section == 'new' ) {
1117 $oldtext = $this->getRawText();
1118 if ( $oldtext === false ) {
1119 wfDebug( __METHOD__
. ": no page text\n" );
1120 wfProfileOut( __METHOD__
);
1124 $dbw = wfGetDB( DB_MASTER
);
1125 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1128 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1129 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1130 wfProfileOut( __METHOD__
);
1134 $oldtext = $rev->getText();
1137 if ( $section == 'new' ) {
1138 # Inserting a new section
1139 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1140 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1141 $text = strlen( trim( $oldtext ) ) > 0
1142 ?
"{$oldtext}\n\n{$subject}{$text}"
1143 : "{$subject}{$text}";
1146 # Replacing an existing section; roll out the big guns
1149 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1153 wfProfileOut( __METHOD__
);
1158 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1160 * @return Int updated $flags
1162 function checkFlags( $flags ) {
1163 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1164 if ( $this->mTitle
->getArticleID() ) {
1165 $flags |
= EDIT_UPDATE
;
1175 * Change an existing article or create a new article. Updates RC and all necessary caches,
1176 * optionally via the deferred update array.
1178 * @param $text String: new text
1179 * @param $summary String: edit summary
1180 * @param $flags Integer bitfield:
1182 * Article is known or assumed to be non-existent, create a new one
1184 * Article is known or assumed to be pre-existing, update it
1186 * Mark this edit minor, if the user is allowed to do so
1188 * Do not log the change in recentchanges
1190 * Mark the edit a "bot" edit regardless of user rights
1191 * EDIT_DEFER_UPDATES
1192 * Defer some of the updates until the end of index.php
1194 * Fill in blank summaries with generated text where possible
1196 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1197 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1198 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1199 * edit-already-exists error will be returned. These two conditions are also possible with
1200 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1202 * @param $baseRevId the revision ID this edit was based off, if any
1203 * @param $user User the user doing the edit
1205 * @return Status object. Possible errors:
1206 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1207 * edit-gone-missing: In update mode, but the article didn't exist
1208 * edit-conflict: In update mode, the article changed unexpectedly
1209 * edit-no-change: Warning that the text was the same as before
1210 * edit-already-exists: In creation mode, but the article already exists
1212 * Extensions may define additional errors.
1214 * $return->value will contain an associative array with members as follows:
1215 * new: Boolean indicating if the function attempted to create a new article
1216 * revision: The revision object for the inserted revision, or null
1218 * Compatibility note: this function previously returned a boolean value indicating success/failure
1220 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1221 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1223 # Low-level sanity check
1224 if ( $this->mTitle
->getText() === '' ) {
1225 throw new MWException( 'Something is trying to edit an article with an empty title' );
1228 wfProfileIn( __METHOD__
);
1230 $user = is_null( $user ) ?
$wgUser : $user;
1231 $status = Status
::newGood( array() );
1233 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1234 $this->loadPageData( 'fromdbmaster' );
1236 $flags = $this->checkFlags( $flags );
1238 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1239 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1241 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1243 if ( $status->isOK() ) {
1244 $status->fatal( 'edit-hook-aborted' );
1247 wfProfileOut( __METHOD__
);
1251 # Silently ignore EDIT_MINOR if not allowed
1252 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1253 $bot = $flags & EDIT_FORCE_BOT
;
1255 $oldtext = $this->getRawText(); // current revision
1256 $oldsize = strlen( $oldtext );
1257 $oldid = $this->getLatest();
1258 $oldIsRedirect = $this->isRedirect();
1259 $oldcountable = $this->isCountable();
1261 # Provide autosummaries if one is not provided and autosummaries are enabled.
1262 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1263 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1266 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1267 $text = $editInfo->pst
;
1268 $newsize = strlen( $text );
1270 $dbw = wfGetDB( DB_MASTER
);
1271 $now = wfTimestampNow();
1272 $this->mTimestamp
= $now;
1274 if ( $flags & EDIT_UPDATE
) {
1275 # Update article, but only if changed.
1276 $status->value
['new'] = false;
1279 # Article gone missing
1280 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1281 $status->fatal( 'edit-gone-missing' );
1283 wfProfileOut( __METHOD__
);
1287 # Make sure the revision is either completely inserted or not inserted at all
1288 if ( !$wgDBtransactions ) {
1289 $userAbort = ignore_user_abort( true );
1292 $revision = new Revision( array(
1293 'page' => $this->getId(),
1294 'comment' => $summary,
1295 'minor_edit' => $isminor,
1297 'parent_id' => $oldid,
1298 'user' => $user->getId(),
1299 'user_text' => $user->getName(),
1303 $changed = ( strcmp( $text, $oldtext ) != 0 );
1307 $revisionId = $revision->insertOn( $dbw );
1311 # Note that we use $this->mLatest instead of fetching a value from the master DB
1312 # during the course of this function. This makes sure that EditPage can detect
1313 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1314 # before this function is called. A previous function used a separate query, this
1315 # creates a window where concurrent edits can cause an ignored edit conflict.
1316 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1319 /* Belated edit conflict! Run away!! */
1320 $status->fatal( 'edit-conflict' );
1322 # Delete the invalid revision if the DB is not transactional
1323 if ( !$wgDBtransactions ) {
1324 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1330 global $wgUseRCPatrol;
1331 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1332 # Update recentchanges
1333 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1334 # Mark as patrolled if the user can do so
1335 $patrolled = $wgUseRCPatrol && !count(
1336 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1337 # Add RC row to the DB
1338 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1339 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1340 $revisionId, $patrolled
1343 # Log auto-patrolled edits
1345 PatrolLog
::record( $rc, true );
1348 $user->incEditCount();
1352 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1353 // related variables correctly
1354 $revision->setId( $this->getLatest() );
1357 if ( !$wgDBtransactions ) {
1358 ignore_user_abort( $userAbort );
1361 // Now that ignore_user_abort is restored, we can respond to fatal errors
1362 if ( !$status->isOK() ) {
1363 wfProfileOut( __METHOD__
);
1367 # Update links tables, site stats, etc.
1368 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1369 'oldcountable' => $oldcountable ) );
1372 $status->warning( 'edit-no-change' );
1374 // Update page_touched, this is usually implicit in the page update
1375 // Other cache updates are done in onArticleEdit()
1376 $this->mTitle
->invalidateCache();
1379 # Create new article
1380 $status->value
['new'] = true;
1384 # Add the page record; stake our claim on this title!
1385 # This will return false if the article already exists
1386 $newid = $this->insertOn( $dbw );
1388 if ( $newid === false ) {
1390 $status->fatal( 'edit-already-exists' );
1392 wfProfileOut( __METHOD__
);
1396 # Save the revision text...
1397 $revision = new Revision( array(
1399 'comment' => $summary,
1400 'minor_edit' => $isminor,
1402 'user' => $user->getId(),
1403 'user_text' => $user->getName(),
1406 $revisionId = $revision->insertOn( $dbw );
1408 # Update the page record with revision data
1409 $this->updateRevisionOn( $dbw, $revision, 0 );
1411 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1413 # Update recentchanges
1414 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1415 global $wgUseRCPatrol, $wgUseNPPatrol;
1417 # Mark as patrolled if the user can do so
1418 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1419 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1420 # Add RC row to the DB
1421 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1422 '', strlen( $text ), $revisionId, $patrolled );
1424 # Log auto-patrolled edits
1426 PatrolLog
::record( $rc, true );
1429 $user->incEditCount();
1432 # Update links, etc.
1433 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1435 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1436 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1439 # Do updates right now unless deferral was requested
1440 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1441 DeferredUpdates
::doUpdates();
1444 // Return the new revision (or null) to the caller
1445 $status->value
['revision'] = $revision;
1447 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1448 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1450 # Promote user to any groups they meet the criteria for
1451 $user->addAutopromoteOnceGroups( 'onEdit' );
1453 wfProfileOut( __METHOD__
);
1458 * Get parser options suitable for rendering the primary article wikitext
1459 * @param User|string $user User object or 'canonical'
1460 * @return ParserOptions
1462 public function makeParserOptions( $user ) {
1464 if ( $user instanceof User
) { // settings per user (even anons)
1465 $options = ParserOptions
::newFromUser( $user );
1466 } else { // canonical settings
1467 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1469 $options->enableLimitReport(); // show inclusion/loop reports
1470 $options->setTidy( true ); // fix bad HTML
1475 * Prepare text which is about to be saved.
1476 * Returns a stdclass with source, pst and output members
1478 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1479 global $wgParser, $wgContLang, $wgUser;
1480 $user = is_null( $user ) ?
$wgUser : $user;
1481 // @TODO fixme: check $user->getId() here???
1482 if ( $this->mPreparedEdit
1483 && $this->mPreparedEdit
->newText
== $text
1484 && $this->mPreparedEdit
->revid
== $revid
1487 return $this->mPreparedEdit
;
1490 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1491 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1493 $edit = (object)array();
1494 $edit->revid
= $revid;
1495 $edit->newText
= $text;
1496 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1497 $edit->popts
= $this->makeParserOptions( 'canonical' );
1498 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1499 $edit->oldText
= $this->getRawText();
1501 $this->mPreparedEdit
= $edit;
1507 * Do standard deferred updates after page edit.
1508 * Update links tables, site stats, search index and message cache.
1509 * Purges pages that include this page if the text was changed here.
1510 * Every 100th edit, prune the recent changes table.
1513 * @param $revision Revision object
1514 * @param $user User object that did the revision
1515 * @param $options Array of options, following indexes are used:
1516 * - changed: boolean, whether the revision changed the content (default true)
1517 * - created: boolean, whether the revision created the page (default false)
1518 * - oldcountable: boolean or null (default null):
1519 * - boolean: whether the page was counted as an article before that
1520 * revision, only used in changed is true and created is false
1521 * - null: don't change the article count
1523 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1524 global $wgEnableParserCache;
1526 wfProfileIn( __METHOD__
);
1528 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1529 $text = $revision->getText();
1532 # Be careful not to double-PST: $text is usually already PST-ed once
1533 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1534 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1535 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1537 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1538 $editInfo = $this->mPreparedEdit
;
1541 # Save it to the parser cache
1542 if ( $wgEnableParserCache ) {
1543 $parserCache = ParserCache
::singleton();
1544 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1547 # Update the links tables
1548 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1551 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1553 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1554 if ( 0 == mt_rand( 0, 99 ) ) {
1555 // Flush old entries from the `recentchanges` table; we do this on
1556 // random requests so as to avoid an increase in writes for no good reason
1559 $dbw = wfGetDB( DB_MASTER
);
1560 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1563 array( "rc_timestamp < '$cutoff'" ),
1569 if ( !$this->mTitle
->exists() ) {
1570 wfProfileOut( __METHOD__
);
1574 $id = $this->getId();
1575 $title = $this->mTitle
->getPrefixedDBkey();
1576 $shortTitle = $this->mTitle
->getDBkey();
1578 if ( !$options['changed'] ) {
1581 } elseif ( $options['created'] ) {
1582 $good = (int)$this->isCountable( $editInfo );
1584 } elseif ( $options['oldcountable'] !== null ) {
1585 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1592 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1593 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1595 # If this is another user's talk page, update newtalk.
1596 # Don't do this if $options['changed'] = false (null-edits) nor if
1597 # it's a minor edit and the user doesn't want notifications for those.
1598 if ( $options['changed']
1599 && $this->mTitle
->getNamespace() == NS_USER_TALK
1600 && $shortTitle != $user->getTitleKey()
1601 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1603 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1604 $other = User
::newFromName( $shortTitle, false );
1606 wfDebug( __METHOD__
. ": invalid username\n" );
1607 } elseif ( User
::isIP( $shortTitle ) ) {
1608 // An anonymous user
1609 $other->setNewtalk( true );
1610 } elseif ( $other->isLoggedIn() ) {
1611 $other->setNewtalk( true );
1613 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1618 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1619 MessageCache
::singleton()->replace( $shortTitle, $text );
1622 if( $options['created'] ) {
1623 self
::onArticleCreate( $this->mTitle
);
1625 self
::onArticleEdit( $this->mTitle
);
1628 wfProfileOut( __METHOD__
);
1632 * Edit an article without doing all that other stuff
1633 * The article must already exist; link tables etc
1634 * are not updated, caches are not flushed.
1636 * @param $text String: text submitted
1637 * @param $user User The relevant user
1638 * @param $comment String: comment submitted
1639 * @param $minor Boolean: whereas it's a minor modification
1641 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1642 wfProfileIn( __METHOD__
);
1644 $dbw = wfGetDB( DB_MASTER
);
1645 $revision = new Revision( array(
1646 'page' => $this->getId(),
1648 'comment' => $comment,
1649 'minor_edit' => $minor ?
1 : 0,
1651 $revision->insertOn( $dbw );
1652 $this->updateRevisionOn( $dbw, $revision );
1654 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1656 wfProfileOut( __METHOD__
);
1660 * Update the article's restriction field, and leave a log entry.
1661 * This works for protection both existing and non-existing pages.
1663 * @param $limit Array: set of restriction keys
1664 * @param $reason String
1665 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1666 * @param $expiry Array: per restriction type expiration
1667 * @param $user User The user updating the restrictions
1668 * @return bool true on success
1670 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1673 if ( wfReadOnly() ) {
1674 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1677 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1679 $id = $this->mTitle
->getArticleID();
1685 // Take this opportunity to purge out expired restrictions
1686 Title
::purgeExpiredRestrictions();
1688 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1689 # we expect a single selection, but the schema allows otherwise.
1690 $isProtected = false;
1694 $dbw = wfGetDB( DB_MASTER
);
1696 foreach ( $restrictionTypes as $action ) {
1697 if ( !isset( $expiry[$action] ) ) {
1698 $expiry[$action] = $dbw->getInfinity();
1700 if ( !isset( $limit[$action] ) ) {
1701 $limit[$action] = '';
1702 } elseif ( $limit[$action] != '' ) {
1706 # Get current restrictions on $action
1707 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1708 if ( $current != '' ) {
1709 $isProtected = true;
1712 if ( $limit[$action] != $current ) {
1714 } elseif ( $limit[$action] != '' ) {
1715 # Only check expiry change if the action is actually being
1716 # protected, since expiry does nothing on an not-protected
1718 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1724 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1728 # If nothing's changed, do nothing
1730 return Status
::newGood();
1733 if ( !$protect ) { # No protection at all means unprotection
1734 $revCommentMsg = 'unprotectedarticle';
1735 $logAction = 'unprotect';
1736 } elseif ( $isProtected ) {
1737 $revCommentMsg = 'modifiedarticleprotection';
1738 $logAction = 'modify';
1740 $revCommentMsg = 'protectedarticle';
1741 $logAction = 'protect';
1744 $encodedExpiry = array();
1745 $protectDescription = '';
1746 foreach ( $limit as $action => $restrictions ) {
1747 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1748 if ( $restrictions != '' ) {
1749 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1750 if ( $encodedExpiry[$action] != 'infinity' ) {
1751 $protectDescription .= wfMsgForContent( 'protect-expiring',
1752 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1753 $wgContLang->date( $expiry[$action], false, false ) ,
1754 $wgContLang->time( $expiry[$action], false, false ) );
1756 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1759 $protectDescription .= ') ';
1762 $protectDescription = trim( $protectDescription );
1764 if ( $id ) { # Protection of existing page
1765 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1766 return Status
::newGood();
1769 # Only restrictions with the 'protect' right can cascade...
1770 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1771 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1773 # The schema allows multiple restrictions
1774 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1778 # Update restrictions table
1779 foreach ( $limit as $action => $restrictions ) {
1780 if ( $restrictions != '' ) {
1781 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1782 array( 'pr_page' => $id,
1783 'pr_type' => $action,
1784 'pr_level' => $restrictions,
1785 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1786 'pr_expiry' => $encodedExpiry[$action]
1791 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1792 'pr_type' => $action ), __METHOD__
);
1796 # Prepare a null revision to be added to the history
1797 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1799 $editComment .= ": $reason";
1801 if ( $protectDescription ) {
1802 $editComment .= " ($protectDescription)";
1805 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1808 # Insert a null revision
1809 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1810 $nullRevId = $nullRevision->insertOn( $dbw );
1812 $latest = $this->getLatest();
1813 # Update page record
1814 $dbw->update( 'page',
1816 'page_touched' => $dbw->timestamp(),
1817 'page_restrictions' => '',
1818 'page_latest' => $nullRevId
1819 ), array( /* WHERE */
1824 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1825 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1826 } else { # Protection of non-existing page (also known as "title protection")
1827 # Cascade protection is meaningless in this case
1830 if ( $limit['create'] != '' ) {
1831 $dbw->replace( 'protected_titles',
1832 array( array( 'pt_namespace', 'pt_title' ) ),
1834 'pt_namespace' => $this->mTitle
->getNamespace(),
1835 'pt_title' => $this->mTitle
->getDBkey(),
1836 'pt_create_perm' => $limit['create'],
1837 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1838 'pt_expiry' => $encodedExpiry['create'],
1839 'pt_user' => $user->getId(),
1840 'pt_reason' => $reason,
1844 $dbw->delete( 'protected_titles',
1846 'pt_namespace' => $this->mTitle
->getNamespace(),
1847 'pt_title' => $this->mTitle
->getDBkey()
1853 $this->mTitle
->flushRestrictions();
1855 if ( $logAction == 'unprotect' ) {
1856 $logParams = array();
1858 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1861 # Update the protection log
1862 $log = new LogPage( 'protect' );
1863 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1865 return Status
::newGood();
1869 * Take an array of page restrictions and flatten it to a string
1870 * suitable for insertion into the page_restrictions field.
1871 * @param $limit Array
1874 protected static function flattenRestrictions( $limit ) {
1875 if ( !is_array( $limit ) ) {
1876 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1882 foreach ( $limit as $action => $restrictions ) {
1883 if ( $restrictions != '' ) {
1884 $bits[] = "$action=$restrictions";
1888 return implode( ':', $bits );
1892 * Back-end article deletion
1893 * Deletes the article with database consistency, writes logs, purges caches
1895 * @param $reason string delete reason for deletion log
1896 * @param $suppress bitfield
1897 * Revision::DELETED_TEXT
1898 * Revision::DELETED_COMMENT
1899 * Revision::DELETED_USER
1900 * Revision::DELETED_RESTRICTED
1901 * @param $id int article ID
1902 * @param $commit boolean defaults to true, triggers transaction end
1903 * @param &$error Array of errors to append to
1904 * @param $user User The relevant user
1905 * @return boolean true if successful
1907 public function doDeleteArticle(
1908 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1911 $user = is_null( $user ) ?
$wgUser : $user;
1913 wfDebug( __METHOD__
. "\n" );
1915 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1918 $dbw = wfGetDB( DB_MASTER
);
1919 $t = $this->mTitle
->getDBkey();
1920 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1922 if ( $t === '' ||
$id == 0 ) {
1926 // Bitfields to further suppress the content
1929 // This should be 15...
1930 $bitfield |
= Revision
::DELETED_TEXT
;
1931 $bitfield |
= Revision
::DELETED_COMMENT
;
1932 $bitfield |
= Revision
::DELETED_USER
;
1933 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1935 $bitfield = 'rev_deleted';
1939 // For now, shunt the revision data into the archive table.
1940 // Text is *not* removed from the text table; bulk storage
1941 // is left intact to avoid breaking block-compression or
1942 // immutable storage schemes.
1944 // For backwards compatibility, note that some older archive
1945 // table entries will have ar_text and ar_flags fields still.
1947 // In the future, we may keep revisions and mark them with
1948 // the rev_deleted field, which is reserved for this purpose.
1949 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1951 'ar_namespace' => 'page_namespace',
1952 'ar_title' => 'page_title',
1953 'ar_comment' => 'rev_comment',
1954 'ar_user' => 'rev_user',
1955 'ar_user_text' => 'rev_user_text',
1956 'ar_timestamp' => 'rev_timestamp',
1957 'ar_minor_edit' => 'rev_minor_edit',
1958 'ar_rev_id' => 'rev_id',
1959 'ar_parent_id' => 'rev_parent_id',
1960 'ar_text_id' => 'rev_text_id',
1961 'ar_text' => '\'\'', // Be explicit to appease
1962 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1963 'ar_len' => 'rev_len',
1964 'ar_page_id' => 'page_id',
1965 'ar_deleted' => $bitfield,
1966 'ar_sha1' => 'rev_sha1'
1969 'page_id = rev_page'
1973 # Now that it's safely backed up, delete it
1974 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1975 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1982 $this->doDeleteUpdates( $id );
1984 # Log the deletion, if the page was suppressed, log it at Oversight instead
1985 $logtype = $suppress ?
'suppress' : 'delete';
1987 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1988 $logEntry->setPerformer( $user );
1989 $logEntry->setTarget( $this->mTitle
);
1990 $logEntry->setComment( $reason );
1991 $logid = $logEntry->insert();
1992 $logEntry->publish( $logid );
1998 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2003 * Do some database updates after deletion
2005 * @param $id Int: page_id value of the page being deleted
2007 public function doDeleteUpdates( $id ) {
2008 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2010 $dbw = wfGetDB( DB_MASTER
);
2012 # Delete restrictions for it
2013 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2015 # Fix category table counts
2017 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2019 foreach ( $res as $row ) {
2020 $cats [] = $row->cl_to
;
2023 $this->updateCategoryCounts( array(), $cats );
2025 # If using cascading deletes, we can skip some explicit deletes
2026 if ( !$dbw->cascadingDeletes() ) {
2027 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2029 # Delete outgoing links
2030 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2031 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2032 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2033 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2034 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2035 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2036 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2037 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2038 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2041 # If using cleanup triggers, we can skip some manual deletes
2042 if ( !$dbw->cleanupTriggers() ) {
2043 # Clean up recentchanges entries...
2044 $dbw->delete( 'recentchanges',
2045 array( 'rc_type != ' . RC_LOG
,
2046 'rc_namespace' => $this->mTitle
->getNamespace(),
2047 'rc_title' => $this->mTitle
->getDBkey() ),
2049 $dbw->delete( 'recentchanges',
2050 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2055 self
::onArticleDelete( $this->mTitle
);
2057 # Clear the cached article id so the interface doesn't act like we exist
2058 $this->mTitle
->resetArticleID( 0 );
2062 * Roll back the most recent consecutive set of edits to a page
2063 * from the same user; fails if there are no eligible edits to
2064 * roll back to, e.g. user is the sole contributor. This function
2065 * performs permissions checks on $user, then calls commitRollback()
2066 * to do the dirty work
2068 * @todo: seperate the business/permission stuff out from backend code
2070 * @param $fromP String: Name of the user whose edits to rollback.
2071 * @param $summary String: Custom summary. Set to default summary if empty.
2072 * @param $token String: Rollback token.
2073 * @param $bot Boolean: If true, mark all reverted edits as bot.
2075 * @param $resultDetails Array: contains result-specific array of additional values
2076 * 'alreadyrolled' : 'current' (rev)
2077 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2079 * @param $user User The user performing the rollback
2080 * @return array of errors, each error formatted as
2081 * array(messagekey, param1, param2, ...).
2082 * On success, the array is empty. This array can also be passed to
2083 * OutputPage::showPermissionsErrorPage().
2085 public function doRollback(
2086 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2088 $resultDetails = null;
2091 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2092 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2093 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2095 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2096 $errors[] = array( 'sessionfailure' );
2099 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2100 $errors[] = array( 'actionthrottledtext' );
2103 # If there were errors, bail out now
2104 if ( !empty( $errors ) ) {
2108 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2112 * Backend implementation of doRollback(), please refer there for parameter
2113 * and return value documentation
2115 * NOTE: This function does NOT check ANY permissions, it just commits the
2116 * rollback to the DB. Therefore, you should only call this function direct-
2117 * ly if you want to use custom permissions checks. If you don't, use
2118 * doRollback() instead.
2119 * @param $fromP String: Name of the user whose edits to rollback.
2120 * @param $summary String: Custom summary. Set to default summary if empty.
2121 * @param $bot Boolean: If true, mark all reverted edits as bot.
2123 * @param $resultDetails Array: contains result-specific array of additional values
2124 * @param $guser User The user performing the rollback
2126 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2127 global $wgUseRCPatrol, $wgContLang;
2129 $dbw = wfGetDB( DB_MASTER
);
2131 if ( wfReadOnly() ) {
2132 return array( array( 'readonlytext' ) );
2135 # Get the last editor
2136 $current = Revision
::newFromTitle( $this->mTitle
);
2137 if ( is_null( $current ) ) {
2138 # Something wrong... no page?
2139 return array( array( 'notanarticle' ) );
2142 $from = str_replace( '_', ' ', $fromP );
2143 # User name given should match up with the top revision.
2144 # If the user was deleted then $from should be empty.
2145 if ( $from != $current->getUserText() ) {
2146 $resultDetails = array( 'current' => $current );
2147 return array( array( 'alreadyrolled',
2148 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2149 htmlspecialchars( $fromP ),
2150 htmlspecialchars( $current->getUserText() )
2154 # Get the last edit not by this guy...
2155 # Note: these may not be public values
2156 $user = intval( $current->getRawUser() );
2157 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2158 $s = $dbw->selectRow( 'revision',
2159 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2160 array( 'rev_page' => $current->getPage(),
2161 "rev_user != {$user} OR rev_user_text != {$user_text}"
2163 array( 'USE INDEX' => 'page_timestamp',
2164 'ORDER BY' => 'rev_timestamp DESC' )
2166 if ( $s === false ) {
2167 # No one else ever edited this page
2168 return array( array( 'cantrollback' ) );
2169 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2170 # Only admins can see this text
2171 return array( array( 'notvisiblerev' ) );
2175 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2176 # Mark all reverted edits as bot
2180 if ( $wgUseRCPatrol ) {
2181 # Mark all reverted edits as patrolled
2182 $set['rc_patrolled'] = 1;
2185 if ( count( $set ) ) {
2186 $dbw->update( 'recentchanges', $set,
2188 'rc_cur_id' => $current->getPage(),
2189 'rc_user_text' => $current->getUserText(),
2190 "rc_timestamp > '{$s->rev_timestamp}'",
2195 # Generate the edit summary if necessary
2196 $target = Revision
::newFromId( $s->rev_id
);
2197 if ( empty( $summary ) ) {
2198 if ( $from == '' ) { // no public user name
2199 $summary = wfMsgForContent( 'revertpage-nouser' );
2201 $summary = wfMsgForContent( 'revertpage' );
2205 # Allow the custom summary to use the same args as the default message
2207 $target->getUserText(), $from, $s->rev_id
,
2208 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2209 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2211 $summary = wfMsgReplaceArgs( $summary, $args );
2214 $flags = EDIT_UPDATE
;
2216 if ( $guser->isAllowed( 'minoredit' ) ) {
2217 $flags |
= EDIT_MINOR
;
2220 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2221 $flags |
= EDIT_FORCE_BOT
;
2224 # Actually store the edit
2225 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2226 if ( !empty( $status->value
['revision'] ) ) {
2227 $revId = $status->value
['revision']->getId();
2232 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2234 $resultDetails = array(
2235 'summary' => $summary,
2236 'current' => $current,
2237 'target' => $target,
2245 * The onArticle*() functions are supposed to be a kind of hooks
2246 * which should be called whenever any of the specified actions
2249 * This is a good place to put code to clear caches, for instance.
2251 * This is called on page move and undelete, as well as edit
2253 * @param $title Title object
2255 public static function onArticleCreate( $title ) {
2256 # Update existence markers on article/talk tabs...
2257 if ( $title->isTalkPage() ) {
2258 $other = $title->getSubjectPage();
2260 $other = $title->getTalkPage();
2263 $other->invalidateCache();
2264 $other->purgeSquid();
2266 $title->touchLinks();
2267 $title->purgeSquid();
2268 $title->deleteTitleProtection();
2272 * Clears caches when article is deleted
2274 * @param $title Title
2276 public static function onArticleDelete( $title ) {
2277 # Update existence markers on article/talk tabs...
2278 if ( $title->isTalkPage() ) {
2279 $other = $title->getSubjectPage();
2281 $other = $title->getTalkPage();
2284 $other->invalidateCache();
2285 $other->purgeSquid();
2287 $title->touchLinks();
2288 $title->purgeSquid();
2291 HTMLFileCache
::clearFileCache( $title );
2294 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2295 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2299 if ( $title->getNamespace() == NS_FILE
) {
2300 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2301 $update->doUpdate();
2305 if ( $title->getNamespace() == NS_USER_TALK
) {
2306 $user = User
::newFromName( $title->getText(), false );
2308 $user->setNewtalk( false );
2313 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2317 * Purge caches on page update etc
2319 * @param $title Title object
2320 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2322 public static function onArticleEdit( $title ) {
2323 // Invalidate caches of articles which include this page
2324 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2327 // Invalidate the caches of all pages which redirect here
2328 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2330 # Purge squid for this page only
2331 $title->purgeSquid();
2333 # Clear file cache for this page only
2334 HTMLFileCache
::clearFileCache( $title );
2340 * Returns a list of hidden categories this page is a member of.
2341 * Uses the page_props and categorylinks tables.
2343 * @return Array of Title objects
2345 public function getHiddenCategories() {
2347 $id = $this->mTitle
->getArticleID();
2353 $dbr = wfGetDB( DB_SLAVE
);
2354 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2356 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2357 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2360 if ( $res !== false ) {
2361 foreach ( $res as $row ) {
2362 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2370 * Return an applicable autosummary if one exists for the given edit.
2371 * @param $oldtext String: the previous text of the page.
2372 * @param $newtext String: The submitted text of the page.
2373 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2374 * @return string An appropriate autosummary, or an empty string.
2376 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2379 # Decide what kind of autosummary is needed.
2381 # Redirect autosummaries
2382 $ot = Title
::newFromRedirect( $oldtext );
2383 $rt = Title
::newFromRedirect( $newtext );
2385 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2386 $truncatedtext = $wgContLang->truncate(
2387 str_replace( "\n", ' ', $newtext ),
2389 - strlen( wfMsgForContent( 'autoredircomment' ) )
2390 - strlen( $rt->getFullText() )
2392 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2395 # New page autosummaries
2396 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2397 # If they're making a new article, give its text, truncated, in the summary.
2399 $truncatedtext = $wgContLang->truncate(
2400 str_replace( "\n", ' ', $newtext ),
2401 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2403 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2406 # Blanking autosummaries
2407 if ( $oldtext != '' && $newtext == '' ) {
2408 return wfMsgForContent( 'autosumm-blank' );
2409 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2410 # Removing more than 90% of the article
2412 $truncatedtext = $wgContLang->truncate(
2414 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2416 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2419 # If we reach this point, there's no applicable autosummary for our case, so our
2420 # autosummary is empty.
2425 * Auto-generates a deletion reason
2427 * @param &$hasHistory Boolean: whether the page has a history
2428 * @return mixed String containing deletion reason or empty string, or boolean false
2429 * if no revision occurred
2431 public function getAutoDeleteReason( &$hasHistory ) {
2434 $dbw = wfGetDB( DB_MASTER
);
2435 // Get the last revision
2436 $rev = Revision
::newFromTitle( $this->getTitle() );
2438 if ( is_null( $rev ) ) {
2442 // Get the article's contents
2443 $contents = $rev->getText();
2446 // If the page is blank, use the text from the previous revision,
2447 // which can only be blank if there's a move/import/protect dummy revision involved
2448 if ( $contents == '' ) {
2449 $prev = $rev->getPrevious();
2452 $contents = $prev->getText();
2457 // Find out if there was only one contributor
2458 // Only scan the last 20 revisions
2459 $res = $dbw->select( 'revision', 'rev_user_text',
2460 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2462 array( 'LIMIT' => 20 )
2465 if ( $res === false ) {
2466 // This page has no revisions, which is very weird
2470 $hasHistory = ( $res->numRows() > 1 );
2471 $row = $dbw->fetchObject( $res );
2473 if ( $row ) { // $row is false if the only contributor is hidden
2474 $onlyAuthor = $row->rev_user_text
;
2475 // Try to find a second contributor
2476 foreach ( $res as $row ) {
2477 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2478 $onlyAuthor = false;
2483 $onlyAuthor = false;
2486 // Generate the summary with a '$1' placeholder
2488 // The current revision is blank and the one before is also
2489 // blank. It's just not our lucky day
2490 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2492 if ( $onlyAuthor ) {
2493 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2495 $reason = wfMsgForContent( 'excontent', '$1' );
2499 if ( $reason == '-' ) {
2500 // Allow these UI messages to be blanked out cleanly
2504 // Replace newlines with spaces to prevent uglyness
2505 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2506 // Calculate the maximum amount of chars to get
2507 // Max content length = max comment length - length of the comment (excl. $1)
2508 $maxLength = 255 - ( strlen( $reason ) - 2 );
2509 $contents = $wgContLang->truncate( $contents, $maxLength );
2510 // Remove possible unfinished links
2511 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2512 // Now replace the '$1' placeholder
2513 $reason = str_replace( '$1', $contents, $reason );
2519 * Update all the appropriate counts in the category table, given that
2520 * we've added the categories $added and deleted the categories $deleted.
2522 * @param $added array The names of categories that were added
2523 * @param $deleted array The names of categories that were deleted
2525 public function updateCategoryCounts( $added, $deleted ) {
2526 $ns = $this->mTitle
->getNamespace();
2527 $dbw = wfGetDB( DB_MASTER
);
2529 # First make sure the rows exist. If one of the "deleted" ones didn't
2530 # exist, we might legitimately not create it, but it's simpler to just
2531 # create it and then give it a negative value, since the value is bogus
2534 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2535 $insertCats = array_merge( $added, $deleted );
2536 if ( !$insertCats ) {
2537 # Okay, nothing to do
2541 $insertRows = array();
2543 foreach ( $insertCats as $cat ) {
2544 $insertRows[] = array(
2545 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2549 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2551 $addFields = array( 'cat_pages = cat_pages + 1' );
2552 $removeFields = array( 'cat_pages = cat_pages - 1' );
2554 if ( $ns == NS_CATEGORY
) {
2555 $addFields[] = 'cat_subcats = cat_subcats + 1';
2556 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2557 } elseif ( $ns == NS_FILE
) {
2558 $addFields[] = 'cat_files = cat_files + 1';
2559 $removeFields[] = 'cat_files = cat_files - 1';
2566 array( 'cat_title' => $added ),
2575 array( 'cat_title' => $deleted ),
2582 * Updates cascading protections
2584 * @param $parserOutput ParserOutput object for the current version
2586 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2587 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2591 // templatelinks table may have become out of sync,
2592 // especially if using variable-based transclusions.
2593 // For paranoia, check if things have changed and if
2594 // so apply updates to the database. This will ensure
2595 // that cascaded protections apply as soon as the changes
2598 # Get templates from templatelinks
2599 $id = $this->mTitle
->getArticleID();
2601 $tlTemplates = array();
2603 $dbr = wfGetDB( DB_SLAVE
);
2604 $res = $dbr->select( array( 'templatelinks' ),
2605 array( 'tl_namespace', 'tl_title' ),
2606 array( 'tl_from' => $id ),
2610 foreach ( $res as $row ) {
2611 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2614 # Get templates from parser output.
2615 $poTemplates = array();
2616 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2617 foreach ( $templates as $dbk => $id ) {
2618 $poTemplates["$ns:$dbk"] = true;
2623 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2625 if ( count( $templates_diff ) > 0 ) {
2626 # Whee, link updates time.
2627 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2633 * Return a list of templates used by this article.
2634 * Uses the templatelinks table
2636 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2637 * @return Array of Title objects
2639 public function getUsedTemplates() {
2640 return $this->mTitle
->getTemplateLinksFrom();
2644 * Perform article updates on a special page creation.
2646 * @param $rev Revision object
2648 * @todo This is a shitty interface function. Kill it and replace the
2649 * other shitty functions like doEditUpdates and such so it's not needed
2651 * @deprecated since 1.18, use doEditUpdates()
2653 public function createUpdates( $rev ) {
2654 wfDeprecated( __METHOD__
, '1.18' );
2656 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2660 * This function is called right before saving the wikitext,
2661 * so we can do things like signatures and links-in-context.
2663 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2664 * @param $text String article contents
2665 * @param $user User object: user doing the edit
2666 * @param $popts ParserOptions object: parser options, default options for
2667 * the user loaded if null given
2668 * @return string article contents with altered wikitext markup (signatures
2669 * converted, {{subst:}}, templates, etc.)
2671 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2672 global $wgParser, $wgUser;
2674 wfDeprecated( __METHOD__
, '1.19' );
2676 $user = is_null( $user ) ?
$wgUser : $user;
2678 if ( $popts === null ) {
2679 $popts = ParserOptions
::newFromUser( $user );
2682 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2686 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2688 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2691 public function isBigDeletion() {
2692 wfDeprecated( __METHOD__
, '1.19' );
2693 return $this->mTitle
->isBigDeletion();
2697 * Get the approximate revision count of this page.
2699 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2702 public function estimateRevisionCount() {
2703 wfDeprecated( __METHOD__
, '1.19' );
2704 return $this->mTitle
->estimateRevisionCount();
2708 * Update the article's restriction field, and leave a log entry.
2710 * @deprecated since 1.19
2711 * @param $limit Array: set of restriction keys
2712 * @param $reason String
2713 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2714 * @param $expiry Array: per restriction type expiration
2715 * @param $user User The user updating the restrictions
2716 * @return bool true on success
2718 public function updateRestrictions(
2719 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2723 $user = is_null( $user ) ?
$wgUser : $user;
2725 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2729 * @deprecated since 1.18
2731 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2732 wfDeprecated( __METHOD__
, '1.18' );
2734 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2738 * @deprecated since 1.18
2740 public function viewUpdates() {
2741 wfDeprecated( __METHOD__
, '1.18' );
2743 return $this->doViewUpdates( $wgUser );
2747 * @deprecated since 1.18
2749 public function useParserCache( $oldid ) {
2750 wfDeprecated( __METHOD__
, '1.18' );
2752 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2756 class PoolWorkArticleView
extends PoolCounterWork
{
2774 * @var ParserOptions
2776 private $parserOptions;
2784 * @var ParserOutput|false
2786 private $parserOutput = false;
2791 private $isDirty = false;
2796 private $error = false;
2802 * @param $revid Integer: ID of the revision being parsed
2803 * @param $useParserCache Boolean: whether to use the parser cache
2804 * @param $parserOptions parserOptions to use for the parse operation
2805 * @param $text String: text to parse or null to load it
2807 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2808 $this->page
= $page;
2809 $this->revid
= $revid;
2810 $this->cacheable
= $useParserCache;
2811 $this->parserOptions
= $parserOptions;
2812 $this->text
= $text;
2813 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2814 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2818 * Get the ParserOutput from this object, or false in case of failure
2820 * @return ParserOutput
2822 public function getParserOutput() {
2823 return $this->parserOutput
;
2827 * Get whether the ParserOutput is a dirty one (i.e. expired)
2831 public function getIsDirty() {
2832 return $this->isDirty
;
2836 * Get a Status object in case of error or false otherwise
2838 * @return Status|false
2840 public function getError() {
2841 return $this->error
;
2848 global $wgParser, $wgUseFileCache;
2850 $isCurrent = $this->revid
=== $this->page
->getLatest();
2852 if ( $this->text
!== null ) {
2853 $text = $this->text
;
2854 } elseif ( $isCurrent ) {
2855 $text = $this->page
->getRawText();
2857 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2858 if ( $rev === null ) {
2861 $text = $rev->getText();
2865 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2866 $this->parserOptions
, true, true, $this->revid
);
2871 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2872 $this->page
->getTitle()->getPrefixedDBkey() ) );
2875 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2876 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2879 // Make sure file cache is not used on uncacheable content.
2880 // Output that has magic words in it can still use the parser cache
2881 // (if enabled), though it will generally expire sooner.
2882 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2883 $wgUseFileCache = false;
2887 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2896 function getCachedWork() {
2897 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2899 if ( $this->parserOutput
=== false ) {
2900 wfDebug( __METHOD__
. ": parser cache miss\n" );
2903 wfDebug( __METHOD__
. ": parser cache hit\n" );
2911 function fallback() {
2912 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2914 if ( $this->parserOutput
=== false ) {
2915 wfDebugLog( 'dirty', "dirty missing\n" );
2916 wfDebug( __METHOD__
. ": no dirty cache\n" );
2919 wfDebug( __METHOD__
. ": sending dirty output\n" );
2920 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2921 $this->isDirty
= true;
2927 * @param $status Status
2929 function error( $status ) {
2930 $this->error
= $status;