3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
8 * Class representing a MediaWiki article and history.
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
13 * @internal documentation reviewed 15 Mar 2010
15 class WikiPage
extends Page
{
19 public $mTitle = null;
24 public $mDataLoaded = false; // !< Boolean
25 public $mIsRedirect = false; // !< Boolean
26 public $mLatest = false; // !< Integer (false means "not loaded")
27 public $mPreparedEdit = false; // !< Array
33 protected $mRedirectTarget = null;
38 protected $mLastRevision = null;
41 * @var string; timestamp of the current revision or empty string if not loaded
43 protected $mTimestamp = '';
48 protected $mTouched = '19700101000000';
53 protected $mCounter = null;
56 * Constructor and clear the article
57 * @param $title Title Reference to a Title object.
59 public function __construct( Title
$title ) {
60 $this->mTitle
= $title;
64 * Create a WikiPage object of the appropriate class for the given title.
67 * @return WikiPage object of the appropriate type
69 public static function factory( Title
$title ) {
70 $ns = $title->getNamespace();
72 if ( $ns == NS_MEDIA
) {
73 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
74 } elseif ( $ns < 0 ) {
75 throw new MWException( "Invalid or virtual namespace $ns given." );
80 $page = new WikiFilePage( $title );
83 $page = new WikiCategoryPage( $title );
86 $page = new WikiPage( $title );
93 * Constructor from a page id
95 * @param $id Int article ID to load
99 public static function newFromID( $id ) {
100 $t = Title
::newFromID( $id );
102 return self
::factory( $t );
108 * Returns overrides for action handlers.
109 * Classes listed here will be used instead of the default one when
110 * (and only when) $wgActions[$action] === true. This allows subclasses
111 * to override the default behavior.
113 * @todo: move this UI stuff somewhere else
117 public function getActionOverrides() {
122 * Get the title object of the article
123 * @return Title object of this page
125 public function getTitle() {
126 return $this->mTitle
;
132 public function clear() {
133 $this->mDataLoaded
= false;
135 $this->mCounter
= null;
136 $this->mRedirectTarget
= null; # Title object if set
137 $this->mLastRevision
= null; # Latest revision
138 $this->mTouched
= '19700101000000';
139 $this->mTimestamp
= '';
140 $this->mIsRedirect
= false;
141 $this->mLatest
= false;
142 $this->mPreparedEdit
= false;
146 * Return the list of revision fields that should be selected to create
151 public static function selectFields() {
164 'page_content_model',
169 * Fetch a page record with the given conditions
170 * @param $dbr DatabaseBase object
171 * @param $conditions Array
172 * @return mixed Database result resource, or false on failure
174 protected function pageData( $dbr, $conditions ) {
175 $fields = self
::selectFields();
177 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
179 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
181 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
187 * Fetch a page record matching the Title object's namespace and title
188 * using a sanitized title string
190 * @param $dbr DatabaseBase object
191 * @param $title Title object
192 * @return mixed Database result resource, or false on failure
194 public function pageDataFromTitle( $dbr, $title ) {
195 return $this->pageData( $dbr, array(
196 'page_namespace' => $title->getNamespace(),
197 'page_title' => $title->getDBkey() ) );
201 * Fetch a page record matching the requested ID
203 * @param $dbr DatabaseBase
205 * @return mixed Database result resource, or false on failure
207 public function pageDataFromId( $dbr, $id ) {
208 return $this->pageData( $dbr, array( 'page_id' => $id ) );
212 * Set the general counter, title etc data loaded from
215 * @param $data Object|String One of the following:
216 * A DB query result object or...
217 * "fromdb" to get from a slave DB or...
218 * "fromdbmaster" to get from the master DB
221 public function loadPageData( $data = 'fromdb' ) {
222 if ( $data === 'fromdbmaster' ) {
223 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
224 } elseif ( $data === 'fromdb' ) { // slave
225 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
226 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
227 # Note that DB also stores the master position in the session and checks it.
228 $touched = $this->getCachedLastEditTime();
229 if ( $touched ) { // key set
230 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
231 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
236 $lc = LinkCache
::singleton();
239 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
241 $this->mTitle
->loadFromRow( $data );
243 # Old-fashioned restrictions
244 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
246 $this->mCounter
= intval( $data->page_counter
);
247 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
248 $this->mIsRedirect
= intval( $data->page_is_redirect
);
249 $this->mLatest
= intval( $data->page_latest
);
251 $lc->addBadLinkObj( $this->mTitle
);
253 $this->mTitle
->loadFromRow( false );
256 $this->mDataLoaded
= true;
260 * @return int Page ID
262 public function getId() {
263 return $this->mTitle
->getArticleID();
267 * @return bool Whether or not the page exists in the database
269 public function exists() {
270 return $this->mTitle
->exists();
274 * Check if this page is something we're going to be showing
275 * some sort of sensible content for. If we return false, page
276 * views (plain action=view) will return an HTTP 404 response,
277 * so spiders and robots can know they're following a bad link.
281 public function hasViewableContent() {
282 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
286 * @return int The view count for the page
288 public function getCount() {
289 if ( !$this->mDataLoaded
) {
290 $this->loadPageData();
293 return $this->mCounter
;
297 * Tests if the article text represents a redirect
299 * @param $text mixed string containing article contents, or boolean
302 public function isRedirect( $text = false ) {
303 if ( $text === false ) {
304 if ( !$this->mDataLoaded
) {
305 $this->loadPageData();
308 return (bool)$this->mIsRedirect
;
310 return Title
::newFromRedirect( $text ) !== null;
315 * Loads page_touched and returns a value indicating if it should be used
316 * @return boolean true if not a redirect
318 public function checkTouched() {
319 if ( !$this->mDataLoaded
) {
320 $this->loadPageData();
322 return !$this->mIsRedirect
;
326 * Get the page_touched field
327 * @return string containing GMT timestamp
329 public function getTouched() {
330 if ( !$this->mDataLoaded
) {
331 $this->loadPageData();
333 return $this->mTouched
;
337 * Get the page_latest field
338 * @return integer rev_id of current revision
340 public function getLatest() {
341 if ( !$this->mDataLoaded
) {
342 $this->loadPageData();
344 return (int)$this->mLatest
;
348 * Loads everything except the text
349 * This isn't necessary for all uses, so it's only done if needed.
351 protected function loadLastEdit() {
352 if ( $this->mLastRevision
!== null ) {
353 return; // already loaded
356 $latest = $this->getLatest();
358 return; // page doesn't exist or is missing page_latest info
361 $revision = Revision
::newFromPageId( $this->getId(), $latest );
362 if ( $revision ) { // sanity
363 $this->setLastEdit( $revision );
368 * Set the latest revision
370 protected function setLastEdit( Revision
$revision ) {
371 $this->mLastRevision
= $revision;
372 $this->mTimestamp
= $revision->getTimestamp();
376 * Get the latest revision
377 * @return Revision|null
379 public function getRevision() {
380 $this->loadLastEdit();
381 if ( $this->mLastRevision
) {
382 return $this->mLastRevision
;
388 * Get the content of the current revision. No side-effects...
390 * @param $audience Integer: one of:
391 * Revision::FOR_PUBLIC to be displayed to all users
392 * Revision::FOR_THIS_USER to be displayed to $wgUser
393 * Revision::RAW get the text regardless of permissions
394 * @return String|null The content of the current revision
396 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
397 $this->loadLastEdit();
398 if ( $this->mLastRevision
) {
399 return $this->mLastRevision
->getContent( $audience );
405 * Get the text of the current revision. No side-effects...
407 * @param $audience Integer: one of:
408 * Revision::FOR_PUBLIC to be displayed to all users
409 * Revision::FOR_THIS_USER to be displayed to $wgUser
410 * Revision::RAW get the text regardless of permissions
411 * @return String|false The text of the current revision
412 * @deprecated as of 1.20, getContent() should be used instead.
414 public function getText( $audience = Revision
::FOR_PUBLIC
) { #FIXME: deprecated, replace usage!
415 wfDeprecated( __METHOD__
, '1.20' );
416 $this->loadLastEdit();
417 if ( $this->mLastRevision
) {
418 return $this->mLastRevision
->getText( $audience );
424 * Get the text of the current revision. No side-effects...
426 * @return String|false The text of the current revision
428 public function getRawText() { #FIXME: deprecated, replace usage!
429 return $this->getText( Revision
::RAW
);
432 protected function getNativeData() {
433 $content = $this->getContent( Revision
::RAW
);
434 if ( !$content ) return null;
436 return $content->getNativeData();
440 * @return string MW timestamp of last article revision
442 public function getTimestamp() {
443 // Check if the field has been filled by WikiPage::setTimestamp()
444 if ( !$this->mTimestamp
) {
445 $this->loadLastEdit();
447 return wfTimestamp( TS_MW
, $this->mTimestamp
);
451 * Set the page timestamp (use only to avoid DB queries)
452 * @param $ts string MW timestamp of last article revision
455 public function setTimestamp( $ts ) {
456 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
460 * @param $audience Integer: one of:
461 * Revision::FOR_PUBLIC to be displayed to all users
462 * Revision::FOR_THIS_USER to be displayed to $wgUser
463 * Revision::RAW get the text regardless of permissions
464 * @return int user ID for the user that made the last article revision
466 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
467 $this->loadLastEdit();
468 if ( $this->mLastRevision
) {
469 return $this->mLastRevision
->getUser( $audience );
476 * @param $audience Integer: one of:
477 * Revision::FOR_PUBLIC to be displayed to all users
478 * Revision::FOR_THIS_USER to be displayed to $wgUser
479 * Revision::RAW get the text regardless of permissions
480 * @return string username of the user that made the last article revision
482 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
483 $this->loadLastEdit();
484 if ( $this->mLastRevision
) {
485 return $this->mLastRevision
->getUserText( $audience );
492 * @param $audience Integer: one of:
493 * Revision::FOR_PUBLIC to be displayed to all users
494 * Revision::FOR_THIS_USER to be displayed to $wgUser
495 * Revision::RAW get the text regardless of permissions
496 * @return string Comment stored for the last article revision
498 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
499 $this->loadLastEdit();
500 if ( $this->mLastRevision
) {
501 return $this->mLastRevision
->getComment( $audience );
508 * Returns true if last revision was marked as "minor edit"
510 * @return boolean Minor edit indicator for the last article revision.
512 public function getMinorEdit() {
513 $this->loadLastEdit();
514 if ( $this->mLastRevision
) {
515 return $this->mLastRevision
->isMinor();
522 * Get the cached timestamp for the last time the page changed.
523 * This is only used to help handle slave lag by comparing to page_touched.
524 * @return string MW timestamp
526 protected function getCachedLastEditTime() {
528 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
529 return $wgMemc->get( $key );
533 * Set the cached timestamp for the last time the page changed.
534 * This is only used to help handle slave lag by comparing to page_touched.
535 * @param $timestamp string
538 public function setCachedLastEditTime( $timestamp ) {
540 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
541 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
545 * Determine whether a page would be suitable for being counted as an
546 * article in the site_stats table based on the title & its content
548 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
549 * if false, the current database state will be used
552 public function isCountable( $editInfo = false ) { #FIXME: move this to Content object
553 global $wgArticleCountMethod;
555 if ( !$this->mTitle
->isContentPage() ) {
559 $text = $editInfo ?
$editInfo->pst
: false;
561 if ( $this->isRedirect( $text ) ) {
565 switch ( $wgArticleCountMethod ) {
569 if ( $text === false ) {
570 $text = $this->getRawText();
572 return strpos( $text, ',' ) !== false;
575 // ParserOutput::getLinks() is a 2D array of page links, so
576 // to be really correct we would need to recurse in the array
577 // but the main array should only have items in it if there are
579 return (bool)count( $editInfo->output
->getLinks() );
581 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
582 array( 'pl_from' => $this->getId() ), __METHOD__
);
588 * If this page is a redirect, get its target
590 * The target will be fetched from the redirect table if possible.
591 * If this page doesn't have an entry there, call insertRedirect()
592 * @return Title|mixed object, or null if this page is not a redirect
594 public function getRedirectTarget() {
595 if ( !$this->mTitle
->isRedirect() ) {
599 if ( $this->mRedirectTarget
!== null ) {
600 return $this->mRedirectTarget
;
603 # Query the redirect table
604 $dbr = wfGetDB( DB_SLAVE
);
605 $row = $dbr->selectRow( 'redirect',
606 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
607 array( 'rd_from' => $this->getId() ),
611 // rd_fragment and rd_interwiki were added later, populate them if empty
612 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
613 return $this->mRedirectTarget
= Title
::makeTitle(
614 $row->rd_namespace
, $row->rd_title
,
615 $row->rd_fragment
, $row->rd_interwiki
);
618 # This page doesn't have an entry in the redirect table
619 return $this->mRedirectTarget
= $this->insertRedirect();
623 * Insert an entry for this page into the redirect table.
625 * Don't call this function directly unless you know what you're doing.
626 * @return Title object or null if not a redirect
628 public function insertRedirect() {
629 // recurse through to only get the final target
630 $retval = Title
::newFromRedirectRecurse( $this->getRawText() ); #FIXME: move this to Content object
634 $this->insertRedirectEntry( $retval );
639 * Insert or update the redirect table entry for this page to indicate
640 * it redirects to $rt .
641 * @param $rt Title redirect target
643 public function insertRedirectEntry( $rt ) {
644 $dbw = wfGetDB( DB_MASTER
);
645 $dbw->replace( 'redirect', array( 'rd_from' ),
647 'rd_from' => $this->getId(),
648 'rd_namespace' => $rt->getNamespace(),
649 'rd_title' => $rt->getDBkey(),
650 'rd_fragment' => $rt->getFragment(),
651 'rd_interwiki' => $rt->getInterwiki(),
658 * Get the Title object or URL this page redirects to
660 * @return mixed false, Title of in-wiki target, or string with URL
662 public function followRedirect() {
663 return $this->getRedirectURL( $this->getRedirectTarget() );
667 * Get the Title object or URL to use for a redirect. We use Title
668 * objects for same-wiki, non-special redirects and URLs for everything
670 * @param $rt Title Redirect target
671 * @return mixed false, Title object of local target, or string with URL
673 public function getRedirectURL( $rt ) {
678 if ( $rt->isExternal() ) {
679 if ( $rt->isLocal() ) {
680 // Offsite wikis need an HTTP redirect.
682 // This can be hard to reverse and may produce loops,
683 // so they may be disabled in the site configuration.
684 $source = $this->mTitle
->getFullURL( 'redirect=no' );
685 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
687 // External pages pages without "local" bit set are not valid
693 if ( $rt->isSpecialPage() ) {
694 // Gotta handle redirects to special pages differently:
695 // Fill the HTTP response "Location" header and ignore
696 // the rest of the page we're on.
698 // Some pages are not valid targets
699 if ( $rt->isValidRedirectTarget() ) {
700 return $rt->getFullURL();
710 * Get a list of users who have edited this article, not including the user who made
711 * the most recent revision, which you can get from $article->getUser() if you want it
712 * @return UserArrayFromResult
714 public function getContributors() {
715 # @todo FIXME: This is expensive; cache this info somewhere.
717 $dbr = wfGetDB( DB_SLAVE
);
719 if ( $dbr->implicitGroupby() ) {
720 $realNameField = 'user_real_name';
722 $realNameField = 'MIN(user_real_name) AS user_real_name';
725 $tables = array( 'revision', 'user' );
728 'rev_user as user_id',
729 'rev_user_text AS user_name',
731 'MAX(rev_timestamp) AS timestamp',
734 $conds = array( 'rev_page' => $this->getId() );
736 // The user who made the top revision gets credited as "this page was last edited by
737 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
738 $user = $this->getUser();
740 $conds[] = "rev_user != $user";
742 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
745 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
748 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
752 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
753 'ORDER BY' => 'timestamp DESC',
756 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
757 return new UserArrayFromResult( $res );
761 * Get the last N authors
762 * @param $num Integer: number of revisions to get
763 * @param $revLatest String: the latest rev_id, selected from the master (optional)
764 * @return array Array of authors, duplicates not removed
766 public function getLastNAuthors( $num, $revLatest = 0 ) {
767 wfProfileIn( __METHOD__
);
768 // First try the slave
769 // If that doesn't have the latest revision, try the master
771 $db = wfGetDB( DB_SLAVE
);
774 $res = $db->select( array( 'page', 'revision' ),
775 array( 'rev_id', 'rev_user_text' ),
777 'page_namespace' => $this->mTitle
->getNamespace(),
778 'page_title' => $this->mTitle
->getDBkey(),
782 'ORDER BY' => 'rev_timestamp DESC',
788 wfProfileOut( __METHOD__
);
792 $row = $db->fetchObject( $res );
794 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
795 $db = wfGetDB( DB_MASTER
);
800 } while ( $continue );
802 $authors = array( $row->rev_user_text
);
804 foreach ( $res as $row ) {
805 $authors[] = $row->rev_user_text
;
808 wfProfileOut( __METHOD__
);
813 * Should the parser cache be used?
815 * @param $parserOptions ParserOptions to check
819 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
820 global $wgEnableParserCache;
822 return $wgEnableParserCache
823 && $parserOptions->getStubThreshold() == 0
824 && $this->mTitle
->exists()
825 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
826 && $this->mTitle
->isWikitextPage(); #FIXME: ask ContentHandler if cachable!
830 * Get a ParserOutput for the given ParserOptions and revision ID.
831 * The parser cache will be used if possible.
834 * @param $parserOptions ParserOptions to use for the parse operation
835 * @param $oldid Revision ID to get the text from, passing null or 0 will
836 * get the current revision (default value)
837 * @return ParserOutput or false if the revision was not found
839 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
840 wfProfileIn( __METHOD__
);
842 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
843 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
844 if ( $parserOptions->getStubThreshold() ) {
845 wfIncrStats( 'pcache_miss_stub' );
848 if ( $useParserCache ) {
849 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
850 if ( $parserOutput !== false ) {
851 wfProfileOut( __METHOD__
);
852 return $parserOutput;
856 if ( $oldid === null ||
$oldid === 0 ) {
857 $oldid = $this->getLatest();
860 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
863 wfProfileOut( __METHOD__
);
865 return $pool->getParserOutput();
869 * Do standard deferred updates after page view
870 * @param $user User The relevant user
872 public function doViewUpdates( User
$user ) {
873 global $wgDisableCounters;
874 if ( wfReadOnly() ) {
878 # Don't update page view counters on views from bot users (bug 14044)
879 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
880 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
881 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
884 # Update newtalk / watchlist notification status
885 $user->clearNotification( $this->mTitle
);
889 * Perform the actions of a page purging
891 public function doPurge() {
894 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
898 // Invalidate the cache
899 $this->mTitle
->invalidateCache();
903 // Commit the transaction before the purge is sent
904 $dbw = wfGetDB( DB_MASTER
);
908 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
912 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
913 if ( $this->mTitle
->exists() ) {
914 $text = $this->getNativeData();
919 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
925 * Insert a new empty page record for this article.
926 * This *must* be followed up by creating a revision
927 * and running $this->updateRevisionOn( ... );
928 * or else the record will be left in a funky state.
929 * Best if all done inside a transaction.
931 * @param $dbw DatabaseBase
932 * @return int The newly created page_id key, or false if the title already existed
934 public function insertOn( $dbw ) {
935 wfProfileIn( __METHOD__
);
937 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
938 $dbw->insert( 'page', array(
939 'page_id' => $page_id,
940 'page_namespace' => $this->mTitle
->getNamespace(),
941 'page_title' => $this->mTitle
->getDBkey(),
943 'page_restrictions' => '',
944 'page_is_redirect' => 0, # Will set this shortly...
946 'page_random' => wfRandom(),
947 'page_touched' => $dbw->timestamp(),
948 'page_latest' => 0, # Fill this in shortly...
949 'page_len' => 0, # Fill this in shortly...
950 ), __METHOD__
, 'IGNORE' );
952 $affected = $dbw->affectedRows();
955 $newid = $dbw->insertId();
956 $this->mTitle
->resetArticleID( $newid );
958 wfProfileOut( __METHOD__
);
960 return $affected ?
$newid : false;
964 * Update the page record to point to a newly saved revision.
966 * @param $dbw DatabaseBase: object
967 * @param $revision Revision: For ID number, and text used to set
968 * length and redirect status fields
969 * @param $lastRevision Integer: if given, will not overwrite the page field
970 * when different from the currently set value.
971 * Giving 0 indicates the new page flag should be set
973 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
974 * removing rows in redirect table.
975 * @return bool true on success, false on failure
978 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
979 wfProfileIn( __METHOD__
);
981 $text = $revision->getText();
982 $len = strlen( $text );
983 $rt = Title
::newFromRedirectRecurse( $text );
985 $conditions = array( 'page_id' => $this->getId() );
987 if ( !is_null( $lastRevision ) ) {
988 # An extra check against threads stepping on each other
989 $conditions['page_latest'] = $lastRevision;
992 $now = wfTimestampNow();
993 $dbw->update( 'page',
995 'page_latest' => $revision->getId(),
996 'page_touched' => $dbw->timestamp( $now ),
997 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
998 'page_is_redirect' => $rt !== null ?
1 : 0,
1004 $result = $dbw->affectedRows() != 0;
1006 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1007 $this->setLastEdit( $revision );
1008 $this->setCachedLastEditTime( $now );
1009 $this->mLatest
= $revision->getId();
1010 $this->mIsRedirect
= (bool)$rt;
1011 # Update the LinkCache.
1012 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1015 wfProfileOut( __METHOD__
);
1020 * Add row to the redirect table if this is a redirect, remove otherwise.
1022 * @param $dbw DatabaseBase
1023 * @param $redirectTitle Title object pointing to the redirect target,
1024 * or NULL if this is not a redirect
1025 * @param $lastRevIsRedirect If given, will optimize adding and
1026 * removing rows in redirect table.
1027 * @return bool true on success, false on failure
1030 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1031 // Always update redirects (target link might have changed)
1032 // Update/Insert if we don't know if the last revision was a redirect or not
1033 // Delete if changing from redirect to non-redirect
1034 $isRedirect = !is_null( $redirectTitle );
1036 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1040 wfProfileIn( __METHOD__
);
1041 if ( $isRedirect ) {
1042 $this->insertRedirectEntry( $redirectTitle );
1044 // This is not a redirect, remove row from redirect table
1045 $where = array( 'rd_from' => $this->getId() );
1046 $dbw->delete( 'redirect', $where, __METHOD__
);
1049 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1050 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1052 wfProfileOut( __METHOD__
);
1054 return ( $dbw->affectedRows() != 0 );
1058 * If the given revision is newer than the currently set page_latest,
1059 * update the page record. Otherwise, do nothing.
1061 * @param $dbw Database object
1062 * @param $revision Revision object
1065 public function updateIfNewerOn( $dbw, $revision ) {
1066 wfProfileIn( __METHOD__
);
1068 $row = $dbw->selectRow(
1069 array( 'revision', 'page' ),
1070 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1072 'page_id' => $this->getId(),
1073 'page_latest=rev_id' ),
1077 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1078 wfProfileOut( __METHOD__
);
1081 $prev = $row->rev_id
;
1082 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1084 # No or missing previous revision; mark the page as new
1086 $lastRevIsRedirect = null;
1089 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1091 wfProfileOut( __METHOD__
);
1096 * Get the text that needs to be saved in order to undo all revisions
1097 * between $undo and $undoafter. Revisions must belong to the same page,
1098 * must exist and must not be deleted
1099 * @param $undo Revision
1100 * @param $undoafter Revision Must be an earlier revision than $undo
1101 * @return mixed string on success, false on failure
1103 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) { #FIXME: move undo logic to ContentHandler
1104 $cur_text = $this->getRawText();
1105 if ( $cur_text === false ) {
1106 return false; // no page
1108 $undo_text = $undo->getText();
1109 $undoafter_text = $undoafter->getText();
1111 if ( $cur_text == $undo_text ) {
1112 # No use doing a merge if it's just a straight revert.
1113 return $undoafter_text;
1118 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1122 return $undone_text;
1126 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1127 * @param $text String: new text of the section
1128 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1129 * @param $edittime String: revision timestamp or null to use the current revision
1130 * @return Content new complete article content, or null if error
1132 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1133 wfProfileIn( __METHOD__
);
1135 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1137 if ( strval( $section ) == '' ) {
1138 // Whole-page edit; let the whole text through
1139 $newContent = $sectionContent;
1141 // Bug 30711: always use current version when adding a new section
1142 if ( is_null( $edittime ) ||
$section == 'new' ) {
1143 $oldContent = $this->getContent();
1144 if ( ! $oldContent ) {
1145 wfDebug( __METHOD__
. ": no page text\n" );
1146 wfProfileOut( __METHOD__
);
1150 $dbw = wfGetDB( DB_MASTER
);
1151 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1154 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1155 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1156 wfProfileOut( __METHOD__
);
1160 $oldContent = $rev->getContent();
1163 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1166 wfProfileOut( __METHOD__
);
1171 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1173 * @return Int updated $flags
1175 function checkFlags( $flags ) {
1176 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1177 if ( $this->mTitle
->getArticleID() ) {
1178 $flags |
= EDIT_UPDATE
;
1188 * Change an existing article or create a new article. Updates RC and all necessary caches,
1189 * optionally via the deferred update array.
1191 * @param $text String: new text
1192 * @param $summary String: edit summary
1193 * @param $flags Integer bitfield:
1195 * Article is known or assumed to be non-existent, create a new one
1197 * Article is known or assumed to be pre-existing, update it
1199 * Mark this edit minor, if the user is allowed to do so
1201 * Do not log the change in recentchanges
1203 * Mark the edit a "bot" edit regardless of user rights
1204 * EDIT_DEFER_UPDATES
1205 * Defer some of the updates until the end of index.php
1207 * Fill in blank summaries with generated text where possible
1209 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1210 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1211 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1212 * edit-already-exists error will be returned. These two conditions are also possible with
1213 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1215 * @param $baseRevId the revision ID this edit was based off, if any
1216 * @param $user User the user doing the edit
1218 * @return Status object. Possible errors:
1219 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1220 * edit-gone-missing: In update mode, but the article didn't exist
1221 * edit-conflict: In update mode, the article changed unexpectedly
1222 * edit-no-change: Warning that the text was the same as before
1223 * edit-already-exists: In creation mode, but the article already exists
1225 * Extensions may define additional errors.
1227 * $return->value will contain an associative array with members as follows:
1228 * new: Boolean indicating if the function attempted to create a new article
1229 * revision: The revision object for the inserted revision, or null
1231 * Compatibility note: this function previously returned a boolean value indicating success/failure
1233 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #FIXME: change $text to $content
1234 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1236 # Low-level sanity check
1237 if ( $this->mTitle
->getText() === '' ) {
1238 throw new MWException( 'Something is trying to edit an article with an empty title' );
1241 wfProfileIn( __METHOD__
);
1243 $user = is_null( $user ) ?
$wgUser : $user;
1244 $status = Status
::newGood( array() );
1246 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1247 $this->loadPageData( 'fromdbmaster' );
1249 $flags = $this->checkFlags( $flags );
1251 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1252 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1254 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1256 if ( $status->isOK() ) {
1257 $status->fatal( 'edit-hook-aborted' );
1260 wfProfileOut( __METHOD__
);
1264 # Silently ignore EDIT_MINOR if not allowed
1265 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1266 $bot = $flags & EDIT_FORCE_BOT
;
1268 $oldtext = $this->getNativeData(); // current revision
1269 $oldsize = strlen( $oldtext );
1270 $oldid = $this->getLatest();
1271 $oldIsRedirect = $this->isRedirect();
1272 $oldcountable = $this->isCountable();
1274 # Provide autosummaries if one is not provided and autosummaries are enabled.
1275 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1276 $summary = self
::getAutosummary( $oldtext, $text, $flags ); #FIXME: auto-summary from ContentHandler
1279 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1280 $text = $editInfo->pst
;
1281 $newsize = strlen( $text );
1283 $dbw = wfGetDB( DB_MASTER
);
1284 $now = wfTimestampNow();
1285 $this->mTimestamp
= $now;
1287 if ( $flags & EDIT_UPDATE
) {
1288 # Update article, but only if changed.
1289 $status->value
['new'] = false;
1292 # Article gone missing
1293 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1294 $status->fatal( 'edit-gone-missing' );
1296 wfProfileOut( __METHOD__
);
1300 # Make sure the revision is either completely inserted or not inserted at all
1301 if ( !$wgDBtransactions ) {
1302 $userAbort = ignore_user_abort( true );
1305 $revision = new Revision( array(
1306 'page' => $this->getId(),
1307 'comment' => $summary,
1308 'minor_edit' => $isminor,
1309 'text' => $text, #FIXME: set content instead, leave serialization to revision?!
1310 'parent_id' => $oldid,
1311 'user' => $user->getId(),
1312 'user_text' => $user->getName(),
1316 $changed = ( strcmp( $text, $oldtext ) != 0 );
1320 $revisionId = $revision->insertOn( $dbw );
1324 # Note that we use $this->mLatest instead of fetching a value from the master DB
1325 # during the course of this function. This makes sure that EditPage can detect
1326 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1327 # before this function is called. A previous function used a separate query, this
1328 # creates a window where concurrent edits can cause an ignored edit conflict.
1329 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1332 /* Belated edit conflict! Run away!! */
1333 $status->fatal( 'edit-conflict' );
1335 # Delete the invalid revision if the DB is not transactional
1336 if ( !$wgDBtransactions ) {
1337 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1343 global $wgUseRCPatrol;
1344 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1345 # Update recentchanges
1346 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1347 # Mark as patrolled if the user can do so
1348 $patrolled = $wgUseRCPatrol && !count(
1349 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1350 # Add RC row to the DB
1351 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1352 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1353 $revisionId, $patrolled
1356 # Log auto-patrolled edits
1358 PatrolLog
::record( $rc, true );
1361 $user->incEditCount();
1365 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1366 // related variables correctly
1367 $revision->setId( $this->getLatest() );
1370 if ( !$wgDBtransactions ) {
1371 ignore_user_abort( $userAbort );
1374 // Now that ignore_user_abort is restored, we can respond to fatal errors
1375 if ( !$status->isOK() ) {
1376 wfProfileOut( __METHOD__
);
1380 # Update links tables, site stats, etc.
1381 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1382 'oldcountable' => $oldcountable ) );
1385 $status->warning( 'edit-no-change' );
1387 // Update page_touched, this is usually implicit in the page update
1388 // Other cache updates are done in onArticleEdit()
1389 $this->mTitle
->invalidateCache();
1392 # Create new article
1393 $status->value
['new'] = true;
1397 # Add the page record; stake our claim on this title!
1398 # This will return false if the article already exists
1399 $newid = $this->insertOn( $dbw );
1401 if ( $newid === false ) {
1403 $status->fatal( 'edit-already-exists' );
1405 wfProfileOut( __METHOD__
);
1409 # Save the revision text...
1410 $revision = new Revision( array(
1412 'comment' => $summary,
1413 'minor_edit' => $isminor,
1415 'user' => $user->getId(),
1416 'user_text' => $user->getName(),
1419 $revisionId = $revision->insertOn( $dbw );
1421 # Update the page record with revision data
1422 $this->updateRevisionOn( $dbw, $revision, 0 );
1424 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1426 # Update recentchanges
1427 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1428 global $wgUseRCPatrol, $wgUseNPPatrol;
1430 # Mark as patrolled if the user can do so
1431 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1432 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1433 # Add RC row to the DB
1434 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1435 '', strlen( $text ), $revisionId, $patrolled );
1437 # Log auto-patrolled edits
1439 PatrolLog
::record( $rc, true );
1442 $user->incEditCount();
1445 # Update links, etc.
1446 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1448 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1449 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1452 # Do updates right now unless deferral was requested
1453 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1454 DeferredUpdates
::doUpdates();
1457 // Return the new revision (or null) to the caller
1458 $status->value
['revision'] = $revision;
1460 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1461 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1463 # Promote user to any groups they meet the criteria for
1464 $user->addAutopromoteOnceGroups( 'onEdit' );
1466 wfProfileOut( __METHOD__
);
1471 * Get parser options suitable for rendering the primary article wikitext
1472 * @param User|string $user User object or 'canonical'
1473 * @return ParserOptions
1475 public function makeParserOptions( $user ) {
1477 if ( $user instanceof User
) { // settings per user (even anons)
1478 $options = ParserOptions
::newFromUser( $user );
1479 } else { // canonical settings
1480 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1482 $options->enableLimitReport(); // show inclusion/loop reports
1483 $options->setTidy( true ); // fix bad HTML
1488 * Prepare text which is about to be saved.
1489 * Returns a stdclass with source, pst and output members
1491 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1492 global $wgParser, $wgContLang, $wgUser;
1493 $user = is_null( $user ) ?
$wgUser : $user;
1494 // @TODO fixme: check $user->getId() here???
1495 if ( $this->mPreparedEdit
1496 && $this->mPreparedEdit
->newText
== $text
1497 && $this->mPreparedEdit
->revid
== $revid
1500 return $this->mPreparedEdit
;
1503 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1504 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1506 $edit = (object)array();
1507 $edit->revid
= $revid;
1508 $edit->newText
= $text;
1509 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1510 $edit->popts
= $this->makeParserOptions( 'canonical' );
1511 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1512 $edit->oldText
= $this->getRawText(); #FIXME: $oldcontent instead?!
1514 $this->mPreparedEdit
= $edit;
1520 * Do standard deferred updates after page edit.
1521 * Update links tables, site stats, search index and message cache.
1522 * Purges pages that include this page if the text was changed here.
1523 * Every 100th edit, prune the recent changes table.
1526 * @param $revision Revision object
1527 * @param $user User object that did the revision
1528 * @param $options Array of options, following indexes are used:
1529 * - changed: boolean, whether the revision changed the content (default true)
1530 * - created: boolean, whether the revision created the page (default false)
1531 * - oldcountable: boolean or null (default null):
1532 * - boolean: whether the page was counted as an article before that
1533 * revision, only used in changed is true and created is false
1534 * - null: don't change the article count
1536 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1537 global $wgEnableParserCache;
1539 wfProfileIn( __METHOD__
);
1541 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1542 $text = $revision->getText();
1545 # Be careful not to double-PST: $text is usually already PST-ed once
1546 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1547 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1548 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1550 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1551 $editInfo = $this->mPreparedEdit
;
1554 # Save it to the parser cache
1555 if ( $wgEnableParserCache ) {
1556 $parserCache = ParserCache
::singleton();
1557 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1560 # Update the links tables
1561 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1564 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1566 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1567 if ( 0 == mt_rand( 0, 99 ) ) {
1568 // Flush old entries from the `recentchanges` table; we do this on
1569 // random requests so as to avoid an increase in writes for no good reason
1572 $dbw = wfGetDB( DB_MASTER
);
1573 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1576 array( "rc_timestamp < '$cutoff'" ),
1582 if ( !$this->mTitle
->exists() ) {
1583 wfProfileOut( __METHOD__
);
1587 $id = $this->getId();
1588 $title = $this->mTitle
->getPrefixedDBkey();
1589 $shortTitle = $this->mTitle
->getDBkey();
1591 if ( !$options['changed'] ) {
1594 } elseif ( $options['created'] ) {
1595 $good = (int)$this->isCountable( $editInfo );
1597 } elseif ( $options['oldcountable'] !== null ) {
1598 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1605 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1606 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1608 # If this is another user's talk page, update newtalk.
1609 # Don't do this if $options['changed'] = false (null-edits) nor if
1610 # it's a minor edit and the user doesn't want notifications for those.
1611 if ( $options['changed']
1612 && $this->mTitle
->getNamespace() == NS_USER_TALK
1613 && $shortTitle != $user->getTitleKey()
1614 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1616 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1617 $other = User
::newFromName( $shortTitle, false );
1619 wfDebug( __METHOD__
. ": invalid username\n" );
1620 } elseif ( User
::isIP( $shortTitle ) ) {
1621 // An anonymous user
1622 $other->setNewtalk( true );
1623 } elseif ( $other->isLoggedIn() ) {
1624 $other->setNewtalk( true );
1626 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1631 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1632 MessageCache
::singleton()->replace( $shortTitle, $text );
1635 if( $options['created'] ) {
1636 self
::onArticleCreate( $this->mTitle
);
1638 self
::onArticleEdit( $this->mTitle
);
1641 wfProfileOut( __METHOD__
);
1645 * Edit an article without doing all that other stuff
1646 * The article must already exist; link tables etc
1647 * are not updated, caches are not flushed.
1649 * @param $text String: text submitted
1650 * @param $user User The relevant user
1651 * @param $comment String: comment submitted
1652 * @param $minor Boolean: whereas it's a minor modification
1654 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1655 wfProfileIn( __METHOD__
);
1657 $dbw = wfGetDB( DB_MASTER
);
1658 $revision = new Revision( array(
1659 'page' => $this->getId(),
1661 'comment' => $comment,
1662 'minor_edit' => $minor ?
1 : 0,
1664 $revision->insertOn( $dbw );
1665 $this->updateRevisionOn( $dbw, $revision );
1667 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1669 wfProfileOut( __METHOD__
);
1673 * Update the article's restriction field, and leave a log entry.
1674 * This works for protection both existing and non-existing pages.
1676 * @param $limit Array: set of restriction keys
1677 * @param $reason String
1678 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1679 * @param $expiry Array: per restriction type expiration
1680 * @param $user User The user updating the restrictions
1681 * @return bool true on success
1683 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1686 if ( wfReadOnly() ) {
1687 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1690 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1692 $id = $this->mTitle
->getArticleID();
1698 // Take this opportunity to purge out expired restrictions
1699 Title
::purgeExpiredRestrictions();
1701 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1702 # we expect a single selection, but the schema allows otherwise.
1703 $isProtected = false;
1707 $dbw = wfGetDB( DB_MASTER
);
1709 foreach ( $restrictionTypes as $action ) {
1710 if ( !isset( $expiry[$action] ) ) {
1711 $expiry[$action] = $dbw->getInfinity();
1713 if ( !isset( $limit[$action] ) ) {
1714 $limit[$action] = '';
1715 } elseif ( $limit[$action] != '' ) {
1719 # Get current restrictions on $action
1720 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1721 if ( $current != '' ) {
1722 $isProtected = true;
1725 if ( $limit[$action] != $current ) {
1727 } elseif ( $limit[$action] != '' ) {
1728 # Only check expiry change if the action is actually being
1729 # protected, since expiry does nothing on an not-protected
1731 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1737 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1741 # If nothing's changed, do nothing
1743 return Status
::newGood();
1746 if ( !$protect ) { # No protection at all means unprotection
1747 $revCommentMsg = 'unprotectedarticle';
1748 $logAction = 'unprotect';
1749 } elseif ( $isProtected ) {
1750 $revCommentMsg = 'modifiedarticleprotection';
1751 $logAction = 'modify';
1753 $revCommentMsg = 'protectedarticle';
1754 $logAction = 'protect';
1757 $encodedExpiry = array();
1758 $protectDescription = '';
1759 foreach ( $limit as $action => $restrictions ) {
1760 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1761 if ( $restrictions != '' ) {
1762 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1763 if ( $encodedExpiry[$action] != 'infinity' ) {
1764 $protectDescription .= wfMsgForContent( 'protect-expiring',
1765 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1766 $wgContLang->date( $expiry[$action], false, false ) ,
1767 $wgContLang->time( $expiry[$action], false, false ) );
1769 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1772 $protectDescription .= ') ';
1775 $protectDescription = trim( $protectDescription );
1777 if ( $id ) { # Protection of existing page
1778 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1779 return Status
::newGood();
1782 # Only restrictions with the 'protect' right can cascade...
1783 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1784 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1786 # The schema allows multiple restrictions
1787 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1791 # Update restrictions table
1792 foreach ( $limit as $action => $restrictions ) {
1793 if ( $restrictions != '' ) {
1794 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1795 array( 'pr_page' => $id,
1796 'pr_type' => $action,
1797 'pr_level' => $restrictions,
1798 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1799 'pr_expiry' => $encodedExpiry[$action]
1804 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1805 'pr_type' => $action ), __METHOD__
);
1809 # Prepare a null revision to be added to the history
1810 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1812 $editComment .= ": $reason";
1814 if ( $protectDescription ) {
1815 $editComment .= " ($protectDescription)";
1818 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1821 # Insert a null revision
1822 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1823 $nullRevId = $nullRevision->insertOn( $dbw );
1825 $latest = $this->getLatest();
1826 # Update page record
1827 $dbw->update( 'page',
1829 'page_touched' => $dbw->timestamp(),
1830 'page_restrictions' => '',
1831 'page_latest' => $nullRevId
1832 ), array( /* WHERE */
1837 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1838 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1839 } else { # Protection of non-existing page (also known as "title protection")
1840 # Cascade protection is meaningless in this case
1843 if ( $limit['create'] != '' ) {
1844 $dbw->replace( 'protected_titles',
1845 array( array( 'pt_namespace', 'pt_title' ) ),
1847 'pt_namespace' => $this->mTitle
->getNamespace(),
1848 'pt_title' => $this->mTitle
->getDBkey(),
1849 'pt_create_perm' => $limit['create'],
1850 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1851 'pt_expiry' => $encodedExpiry['create'],
1852 'pt_user' => $user->getId(),
1853 'pt_reason' => $reason,
1857 $dbw->delete( 'protected_titles',
1859 'pt_namespace' => $this->mTitle
->getNamespace(),
1860 'pt_title' => $this->mTitle
->getDBkey()
1866 $this->mTitle
->flushRestrictions();
1868 if ( $logAction == 'unprotect' ) {
1869 $logParams = array();
1871 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1874 # Update the protection log
1875 $log = new LogPage( 'protect' );
1876 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1878 return Status
::newGood();
1882 * Take an array of page restrictions and flatten it to a string
1883 * suitable for insertion into the page_restrictions field.
1884 * @param $limit Array
1887 protected static function flattenRestrictions( $limit ) {
1888 if ( !is_array( $limit ) ) {
1889 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1895 foreach ( $limit as $action => $restrictions ) {
1896 if ( $restrictions != '' ) {
1897 $bits[] = "$action=$restrictions";
1901 return implode( ':', $bits );
1905 * Back-end article deletion
1906 * Deletes the article with database consistency, writes logs, purges caches
1908 * @param $reason string delete reason for deletion log
1909 * @param $suppress bitfield
1910 * Revision::DELETED_TEXT
1911 * Revision::DELETED_COMMENT
1912 * Revision::DELETED_USER
1913 * Revision::DELETED_RESTRICTED
1914 * @param $id int article ID
1915 * @param $commit boolean defaults to true, triggers transaction end
1916 * @param &$errors Array of errors to append to
1917 * @param $user User The relevant user
1918 * @return boolean true if successful
1920 public function doDeleteArticle(
1921 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1924 $user = is_null( $user ) ?
$wgUser : $user;
1926 wfDebug( __METHOD__
. "\n" );
1928 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1931 $dbw = wfGetDB( DB_MASTER
);
1932 $t = $this->mTitle
->getDBkey();
1933 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1935 if ( $t === '' ||
$id == 0 ) {
1939 // Bitfields to further suppress the content
1942 // This should be 15...
1943 $bitfield |
= Revision
::DELETED_TEXT
;
1944 $bitfield |
= Revision
::DELETED_COMMENT
;
1945 $bitfield |
= Revision
::DELETED_USER
;
1946 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1948 $bitfield = 'rev_deleted';
1952 // For now, shunt the revision data into the archive table.
1953 // Text is *not* removed from the text table; bulk storage
1954 // is left intact to avoid breaking block-compression or
1955 // immutable storage schemes.
1957 // For backwards compatibility, note that some older archive
1958 // table entries will have ar_text and ar_flags fields still.
1960 // In the future, we may keep revisions and mark them with
1961 // the rev_deleted field, which is reserved for this purpose.
1962 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1964 'ar_namespace' => 'page_namespace',
1965 'ar_title' => 'page_title',
1966 'ar_comment' => 'rev_comment',
1967 'ar_user' => 'rev_user',
1968 'ar_user_text' => 'rev_user_text',
1969 'ar_timestamp' => 'rev_timestamp',
1970 'ar_minor_edit' => 'rev_minor_edit',
1971 'ar_rev_id' => 'rev_id',
1972 'ar_parent_id' => 'rev_parent_id',
1973 'ar_text_id' => 'rev_text_id',
1974 'ar_text' => '\'\'', // Be explicit to appease
1975 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1976 'ar_len' => 'rev_len',
1977 'ar_page_id' => 'page_id',
1978 'ar_deleted' => $bitfield,
1979 'ar_sha1' => 'rev_content_model',
1980 'ar_content_format' => 'rev_content_format',
1981 'ar_content_format' => 'rev_sha1'
1984 'page_id = rev_page'
1988 # Now that it's safely backed up, delete it
1989 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1990 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1997 $this->doDeleteUpdates( $id );
1999 # Log the deletion, if the page was suppressed, log it at Oversight instead
2000 $logtype = $suppress ?
'suppress' : 'delete';
2002 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2003 $logEntry->setPerformer( $user );
2004 $logEntry->setTarget( $this->mTitle
);
2005 $logEntry->setComment( $reason );
2006 $logid = $logEntry->insert();
2007 $logEntry->publish( $logid );
2013 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2018 * Do some database updates after deletion
2020 * @param $id Int: page_id value of the page being deleted
2022 public function doDeleteUpdates( $id ) {
2023 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2025 $dbw = wfGetDB( DB_MASTER
);
2027 # Delete restrictions for it
2028 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2030 # Fix category table counts
2032 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2034 foreach ( $res as $row ) {
2035 $cats [] = $row->cl_to
;
2038 $this->updateCategoryCounts( array(), $cats );
2040 # If using cascading deletes, we can skip some explicit deletes
2041 if ( !$dbw->cascadingDeletes() ) {
2042 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2044 # Delete outgoing links
2045 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2046 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2047 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2048 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2049 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2050 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2051 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2052 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2053 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2056 # If using cleanup triggers, we can skip some manual deletes
2057 if ( !$dbw->cleanupTriggers() ) {
2058 # Clean up recentchanges entries...
2059 $dbw->delete( 'recentchanges',
2060 array( 'rc_type != ' . RC_LOG
,
2061 'rc_namespace' => $this->mTitle
->getNamespace(),
2062 'rc_title' => $this->mTitle
->getDBkey() ),
2064 $dbw->delete( 'recentchanges',
2065 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2070 self
::onArticleDelete( $this->mTitle
);
2072 # Clear the cached article id so the interface doesn't act like we exist
2073 $this->mTitle
->resetArticleID( 0 );
2077 * Roll back the most recent consecutive set of edits to a page
2078 * from the same user; fails if there are no eligible edits to
2079 * roll back to, e.g. user is the sole contributor. This function
2080 * performs permissions checks on $user, then calls commitRollback()
2081 * to do the dirty work
2083 * @todo: seperate the business/permission stuff out from backend code
2085 * @param $fromP String: Name of the user whose edits to rollback.
2086 * @param $summary String: Custom summary. Set to default summary if empty.
2087 * @param $token String: Rollback token.
2088 * @param $bot Boolean: If true, mark all reverted edits as bot.
2090 * @param $resultDetails Array: contains result-specific array of additional values
2091 * 'alreadyrolled' : 'current' (rev)
2092 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2094 * @param $user User The user performing the rollback
2095 * @return array of errors, each error formatted as
2096 * array(messagekey, param1, param2, ...).
2097 * On success, the array is empty. This array can also be passed to
2098 * OutputPage::showPermissionsErrorPage().
2100 public function doRollback(
2101 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2103 $resultDetails = null;
2106 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2107 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2108 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2110 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2111 $errors[] = array( 'sessionfailure' );
2114 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2115 $errors[] = array( 'actionthrottledtext' );
2118 # If there were errors, bail out now
2119 if ( !empty( $errors ) ) {
2123 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2127 * Backend implementation of doRollback(), please refer there for parameter
2128 * and return value documentation
2130 * NOTE: This function does NOT check ANY permissions, it just commits the
2131 * rollback to the DB. Therefore, you should only call this function direct-
2132 * ly if you want to use custom permissions checks. If you don't, use
2133 * doRollback() instead.
2134 * @param $fromP String: Name of the user whose edits to rollback.
2135 * @param $summary String: Custom summary. Set to default summary if empty.
2136 * @param $bot Boolean: If true, mark all reverted edits as bot.
2138 * @param $resultDetails Array: contains result-specific array of additional values
2139 * @param $guser User The user performing the rollback
2141 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2142 global $wgUseRCPatrol, $wgContLang;
2144 $dbw = wfGetDB( DB_MASTER
);
2146 if ( wfReadOnly() ) {
2147 return array( array( 'readonlytext' ) );
2150 # Get the last editor
2151 $current = Revision
::newFromTitle( $this->mTitle
);
2152 if ( is_null( $current ) ) {
2153 # Something wrong... no page?
2154 return array( array( 'notanarticle' ) );
2157 $from = str_replace( '_', ' ', $fromP );
2158 # User name given should match up with the top revision.
2159 # If the user was deleted then $from should be empty.
2160 if ( $from != $current->getUserText() ) {
2161 $resultDetails = array( 'current' => $current );
2162 return array( array( 'alreadyrolled',
2163 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2164 htmlspecialchars( $fromP ),
2165 htmlspecialchars( $current->getUserText() )
2169 # Get the last edit not by this guy...
2170 # Note: these may not be public values
2171 $user = intval( $current->getRawUser() );
2172 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2173 $s = $dbw->selectRow( 'revision',
2174 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2175 array( 'rev_page' => $current->getPage(),
2176 "rev_user != {$user} OR rev_user_text != {$user_text}"
2178 array( 'USE INDEX' => 'page_timestamp',
2179 'ORDER BY' => 'rev_timestamp DESC' )
2181 if ( $s === false ) {
2182 # No one else ever edited this page
2183 return array( array( 'cantrollback' ) );
2184 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2185 # Only admins can see this text
2186 return array( array( 'notvisiblerev' ) );
2190 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2191 # Mark all reverted edits as bot
2195 if ( $wgUseRCPatrol ) {
2196 # Mark all reverted edits as patrolled
2197 $set['rc_patrolled'] = 1;
2200 if ( count( $set ) ) {
2201 $dbw->update( 'recentchanges', $set,
2203 'rc_cur_id' => $current->getPage(),
2204 'rc_user_text' => $current->getUserText(),
2205 "rc_timestamp > '{$s->rev_timestamp}'",
2210 # Generate the edit summary if necessary
2211 $target = Revision
::newFromId( $s->rev_id
);
2212 if ( empty( $summary ) ) {
2213 if ( $from == '' ) { // no public user name
2214 $summary = wfMsgForContent( 'revertpage-nouser' );
2216 $summary = wfMsgForContent( 'revertpage' );
2220 # Allow the custom summary to use the same args as the default message
2222 $target->getUserText(), $from, $s->rev_id
,
2223 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2224 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2226 $summary = wfMsgReplaceArgs( $summary, $args );
2229 $flags = EDIT_UPDATE
;
2231 if ( $guser->isAllowed( 'minoredit' ) ) {
2232 $flags |
= EDIT_MINOR
;
2235 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2236 $flags |
= EDIT_FORCE_BOT
;
2239 # Actually store the edit
2240 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2241 if ( !empty( $status->value
['revision'] ) ) {
2242 $revId = $status->value
['revision']->getId();
2247 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2249 $resultDetails = array(
2250 'summary' => $summary,
2251 'current' => $current,
2252 'target' => $target,
2260 * The onArticle*() functions are supposed to be a kind of hooks
2261 * which should be called whenever any of the specified actions
2264 * This is a good place to put code to clear caches, for instance.
2266 * This is called on page move and undelete, as well as edit
2268 * @param $title Title object
2270 public static function onArticleCreate( $title ) {
2271 # Update existence markers on article/talk tabs...
2272 if ( $title->isTalkPage() ) {
2273 $other = $title->getSubjectPage();
2275 $other = $title->getTalkPage();
2278 $other->invalidateCache();
2279 $other->purgeSquid();
2281 $title->touchLinks();
2282 $title->purgeSquid();
2283 $title->deleteTitleProtection();
2287 * Clears caches when article is deleted
2289 * @param $title Title
2291 public static function onArticleDelete( $title ) {
2292 # Update existence markers on article/talk tabs...
2293 if ( $title->isTalkPage() ) {
2294 $other = $title->getSubjectPage();
2296 $other = $title->getTalkPage();
2299 $other->invalidateCache();
2300 $other->purgeSquid();
2302 $title->touchLinks();
2303 $title->purgeSquid();
2306 HTMLFileCache
::clearFileCache( $title );
2309 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2310 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2314 if ( $title->getNamespace() == NS_FILE
) {
2315 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2316 $update->doUpdate();
2320 if ( $title->getNamespace() == NS_USER_TALK
) {
2321 $user = User
::newFromName( $title->getText(), false );
2323 $user->setNewtalk( false );
2328 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2332 * Purge caches on page update etc
2334 * @param $title Title object
2335 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2337 public static function onArticleEdit( $title ) {
2338 // Invalidate caches of articles which include this page
2339 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2342 // Invalidate the caches of all pages which redirect here
2343 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2345 # Purge squid for this page only
2346 $title->purgeSquid();
2348 # Clear file cache for this page only
2349 HTMLFileCache
::clearFileCache( $title );
2355 * Returns a list of hidden categories this page is a member of.
2356 * Uses the page_props and categorylinks tables.
2358 * @return Array of Title objects
2360 public function getHiddenCategories() {
2362 $id = $this->mTitle
->getArticleID();
2368 $dbr = wfGetDB( DB_SLAVE
);
2369 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2371 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2372 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2375 if ( $res !== false ) {
2376 foreach ( $res as $row ) {
2377 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2385 * Return an applicable autosummary if one exists for the given edit.
2386 * @param $oldtext String: the previous text of the page.
2387 * @param $newtext String: The submitted text of the page.
2388 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2389 * @return string An appropriate autosummary, or an empty string.
2391 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2394 # Decide what kind of autosummary is needed.
2396 # Redirect autosummaries
2397 $ot = Title
::newFromRedirect( $oldtext );
2398 $rt = Title
::newFromRedirect( $newtext );
2400 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2401 $truncatedtext = $wgContLang->truncate(
2402 str_replace( "\n", ' ', $newtext ),
2404 - strlen( wfMsgForContent( 'autoredircomment' ) )
2405 - strlen( $rt->getFullText() )
2407 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2410 # New page autosummaries
2411 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2412 # If they're making a new article, give its text, truncated, in the summary.
2414 $truncatedtext = $wgContLang->truncate(
2415 str_replace( "\n", ' ', $newtext ),
2416 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2418 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2421 # Blanking autosummaries
2422 if ( $oldtext != '' && $newtext == '' ) {
2423 return wfMsgForContent( 'autosumm-blank' );
2424 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2425 # Removing more than 90% of the article
2427 $truncatedtext = $wgContLang->truncate(
2429 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2431 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2434 # If we reach this point, there's no applicable autosummary for our case, so our
2435 # autosummary is empty.
2440 * Auto-generates a deletion reason
2442 * @param &$hasHistory Boolean: whether the page has a history
2443 * @return mixed String containing deletion reason or empty string, or boolean false
2444 * if no revision occurred
2446 public function getAutoDeleteReason( &$hasHistory ) {
2449 $dbw = wfGetDB( DB_MASTER
);
2450 // Get the last revision
2451 $rev = Revision
::newFromTitle( $this->getTitle() );
2453 if ( is_null( $rev ) ) {
2457 // Get the article's contents
2458 $contents = $rev->getText();
2461 // If the page is blank, use the text from the previous revision,
2462 // which can only be blank if there's a move/import/protect dummy revision involved
2463 if ( $contents == '' ) {
2464 $prev = $rev->getPrevious();
2467 $contents = $prev->getText();
2472 // Find out if there was only one contributor
2473 // Only scan the last 20 revisions
2474 $res = $dbw->select( 'revision', 'rev_user_text',
2475 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2477 array( 'LIMIT' => 20 )
2480 if ( $res === false ) {
2481 // This page has no revisions, which is very weird
2485 $hasHistory = ( $res->numRows() > 1 );
2486 $row = $dbw->fetchObject( $res );
2488 if ( $row ) { // $row is false if the only contributor is hidden
2489 $onlyAuthor = $row->rev_user_text
;
2490 // Try to find a second contributor
2491 foreach ( $res as $row ) {
2492 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2493 $onlyAuthor = false;
2498 $onlyAuthor = false;
2501 // Generate the summary with a '$1' placeholder
2503 // The current revision is blank and the one before is also
2504 // blank. It's just not our lucky day
2505 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2507 if ( $onlyAuthor ) {
2508 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2510 $reason = wfMsgForContent( 'excontent', '$1' );
2514 if ( $reason == '-' ) {
2515 // Allow these UI messages to be blanked out cleanly
2519 // Replace newlines with spaces to prevent uglyness
2520 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2521 // Calculate the maximum amount of chars to get
2522 // Max content length = max comment length - length of the comment (excl. $1)
2523 $maxLength = 255 - ( strlen( $reason ) - 2 );
2524 $contents = $wgContLang->truncate( $contents, $maxLength );
2525 // Remove possible unfinished links
2526 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2527 // Now replace the '$1' placeholder
2528 $reason = str_replace( '$1', $contents, $reason );
2534 * Update all the appropriate counts in the category table, given that
2535 * we've added the categories $added and deleted the categories $deleted.
2537 * @param $added array The names of categories that were added
2538 * @param $deleted array The names of categories that were deleted
2540 public function updateCategoryCounts( $added, $deleted ) {
2541 $ns = $this->mTitle
->getNamespace();
2542 $dbw = wfGetDB( DB_MASTER
);
2544 # First make sure the rows exist. If one of the "deleted" ones didn't
2545 # exist, we might legitimately not create it, but it's simpler to just
2546 # create it and then give it a negative value, since the value is bogus
2549 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2550 $insertCats = array_merge( $added, $deleted );
2551 if ( !$insertCats ) {
2552 # Okay, nothing to do
2556 $insertRows = array();
2558 foreach ( $insertCats as $cat ) {
2559 $insertRows[] = array(
2560 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2564 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2566 $addFields = array( 'cat_pages = cat_pages + 1' );
2567 $removeFields = array( 'cat_pages = cat_pages - 1' );
2569 if ( $ns == NS_CATEGORY
) {
2570 $addFields[] = 'cat_subcats = cat_subcats + 1';
2571 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2572 } elseif ( $ns == NS_FILE
) {
2573 $addFields[] = 'cat_files = cat_files + 1';
2574 $removeFields[] = 'cat_files = cat_files - 1';
2581 array( 'cat_title' => $added ),
2590 array( 'cat_title' => $deleted ),
2597 * Updates cascading protections
2599 * @param $parserOutput ParserOutput object for the current version
2601 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2602 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2606 // templatelinks table may have become out of sync,
2607 // especially if using variable-based transclusions.
2608 // For paranoia, check if things have changed and if
2609 // so apply updates to the database. This will ensure
2610 // that cascaded protections apply as soon as the changes
2613 # Get templates from templatelinks
2614 $id = $this->mTitle
->getArticleID();
2616 $tlTemplates = array();
2618 $dbr = wfGetDB( DB_SLAVE
);
2619 $res = $dbr->select( array( 'templatelinks' ),
2620 array( 'tl_namespace', 'tl_title' ),
2621 array( 'tl_from' => $id ),
2625 foreach ( $res as $row ) {
2626 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2629 # Get templates from parser output.
2630 $poTemplates = array();
2631 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2632 foreach ( $templates as $dbk => $id ) {
2633 $poTemplates["$ns:$dbk"] = true;
2638 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2640 if ( count( $templates_diff ) > 0 ) {
2641 # Whee, link updates time.
2642 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2648 * Return a list of templates used by this article.
2649 * Uses the templatelinks table
2651 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2652 * @return Array of Title objects
2654 public function getUsedTemplates() {
2655 return $this->mTitle
->getTemplateLinksFrom();
2659 * Perform article updates on a special page creation.
2661 * @param $rev Revision object
2663 * @todo This is a shitty interface function. Kill it and replace the
2664 * other shitty functions like doEditUpdates and such so it's not needed
2666 * @deprecated since 1.18, use doEditUpdates()
2668 public function createUpdates( $rev ) {
2669 wfDeprecated( __METHOD__
, '1.18' );
2671 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2675 * This function is called right before saving the wikitext,
2676 * so we can do things like signatures and links-in-context.
2678 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2679 * @param $text String article contents
2680 * @param $user User object: user doing the edit
2681 * @param $popts ParserOptions object: parser options, default options for
2682 * the user loaded if null given
2683 * @return string article contents with altered wikitext markup (signatures
2684 * converted, {{subst:}}, templates, etc.)
2686 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2687 global $wgParser, $wgUser;
2689 wfDeprecated( __METHOD__
, '1.19' );
2691 $user = is_null( $user ) ?
$wgUser : $user;
2693 if ( $popts === null ) {
2694 $popts = ParserOptions
::newFromUser( $user );
2697 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2701 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2703 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2706 public function isBigDeletion() {
2707 wfDeprecated( __METHOD__
, '1.19' );
2708 return $this->mTitle
->isBigDeletion();
2712 * Get the approximate revision count of this page.
2714 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2717 public function estimateRevisionCount() {
2718 wfDeprecated( __METHOD__
, '1.19' );
2719 return $this->mTitle
->estimateRevisionCount();
2723 * Update the article's restriction field, and leave a log entry.
2725 * @deprecated since 1.19
2726 * @param $limit Array: set of restriction keys
2727 * @param $reason String
2728 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2729 * @param $expiry Array: per restriction type expiration
2730 * @param $user User The user updating the restrictions
2731 * @return bool true on success
2733 public function updateRestrictions(
2734 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2738 $user = is_null( $user ) ?
$wgUser : $user;
2740 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2744 * @deprecated since 1.18
2746 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2747 wfDeprecated( __METHOD__
, '1.18' );
2749 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2753 * @deprecated since 1.18
2755 public function viewUpdates() {
2756 wfDeprecated( __METHOD__
, '1.18' );
2758 return $this->doViewUpdates( $wgUser );
2762 * @deprecated since 1.18
2764 public function useParserCache( $oldid ) {
2765 wfDeprecated( __METHOD__
, '1.18' );
2767 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2771 class PoolWorkArticleView
extends PoolCounterWork
{
2789 * @var ParserOptions
2791 private $parserOptions;
2799 * @var ParserOutput|false
2801 private $parserOutput = false;
2806 private $isDirty = false;
2811 private $error = false;
2817 * @param $revid Integer: ID of the revision being parsed
2818 * @param $useParserCache Boolean: whether to use the parser cache
2819 * @param $parserOptions parserOptions to use for the parse operation
2820 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
2822 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
2823 if ( is_string($content) ) { #BC: old style call
2824 $modelName = $page->getRevision()->getContentModelName();
2825 $format = $page->getRevision()->getContentFormat();
2826 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelName, $format );
2829 $this->page
= $page;
2830 $this->revid
= $revid;
2831 $this->cacheable
= $useParserCache;
2832 $this->parserOptions
= $parserOptions;
2833 $this->content
= $content;
2834 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2835 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2839 * Get the ParserOutput from this object, or false in case of failure
2841 * @return ParserOutput
2843 public function getParserOutput() {
2844 return $this->parserOutput
;
2848 * Get whether the ParserOutput is a dirty one (i.e. expired)
2852 public function getIsDirty() {
2853 return $this->isDirty
;
2857 * Get a Status object in case of error or false otherwise
2859 * @return Status|false
2861 public function getError() {
2862 return $this->error
;
2869 global $wgParser, $wgUseFileCache;
2871 $isCurrent = $this->revid
=== $this->page
->getLatest();
2873 if ( $this->content
!== null ) {
2874 $content = $this->content
;
2875 } elseif ( $isCurrent ) {
2876 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
2878 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2879 if ( $rev === null ) {
2882 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
2886 $this->parserOutput
= $content->getParserOutput( $this->parserOptions
);
2891 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2892 $this->page
->getTitle()->getPrefixedDBkey() ) );
2895 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2896 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2899 // Make sure file cache is not used on uncacheable content.
2900 // Output that has magic words in it can still use the parser cache
2901 // (if enabled), though it will generally expire sooner.
2902 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2903 $wgUseFileCache = false;
2907 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2916 function getCachedWork() {
2917 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2919 if ( $this->parserOutput
=== false ) {
2920 wfDebug( __METHOD__
. ": parser cache miss\n" );
2923 wfDebug( __METHOD__
. ": parser cache hit\n" );
2931 function fallback() {
2932 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2934 if ( $this->parserOutput
=== false ) {
2935 wfDebugLog( 'dirty', "dirty missing\n" );
2936 wfDebug( __METHOD__
. ": no dirty cache\n" );
2939 wfDebug( __METHOD__
. ": sending dirty output\n" );
2940 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2941 $this->isDirty
= true;
2947 * @param $status Status
2949 function error( $status ) {
2950 $this->error
= $status;