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
);
433 * @return string MW timestamp of last article revision
435 public function getTimestamp() {
436 // Check if the field has been filled by WikiPage::setTimestamp()
437 if ( !$this->mTimestamp
) {
438 $this->loadLastEdit();
440 return wfTimestamp( TS_MW
, $this->mTimestamp
);
444 * Set the page timestamp (use only to avoid DB queries)
445 * @param $ts string MW timestamp of last article revision
448 public function setTimestamp( $ts ) {
449 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
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 int user ID for the user that made the last article revision
459 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
460 $this->loadLastEdit();
461 if ( $this->mLastRevision
) {
462 return $this->mLastRevision
->getUser( $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 username of the user that made the last article revision
475 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
476 $this->loadLastEdit();
477 if ( $this->mLastRevision
) {
478 return $this->mLastRevision
->getUserText( $audience );
485 * @param $audience Integer: one of:
486 * Revision::FOR_PUBLIC to be displayed to all users
487 * Revision::FOR_THIS_USER to be displayed to $wgUser
488 * Revision::RAW get the text regardless of permissions
489 * @return string Comment stored for the last article revision
491 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
492 $this->loadLastEdit();
493 if ( $this->mLastRevision
) {
494 return $this->mLastRevision
->getComment( $audience );
501 * Returns true if last revision was marked as "minor edit"
503 * @return boolean Minor edit indicator for the last article revision.
505 public function getMinorEdit() {
506 $this->loadLastEdit();
507 if ( $this->mLastRevision
) {
508 return $this->mLastRevision
->isMinor();
515 * Get the cached timestamp for the last time the page changed.
516 * This is only used to help handle slave lag by comparing to page_touched.
517 * @return string MW timestamp
519 protected function getCachedLastEditTime() {
521 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
522 return $wgMemc->get( $key );
526 * Set the cached timestamp for the last time the page changed.
527 * This is only used to help handle slave lag by comparing to page_touched.
528 * @param $timestamp string
531 public function setCachedLastEditTime( $timestamp ) {
533 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
534 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
538 * Determine whether a page would be suitable for being counted as an
539 * article in the site_stats table based on the title & its content
541 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
542 * if false, the current database state will be used
545 public function isCountable( $editInfo = false ) {
546 global $wgArticleCountMethod;
548 if ( !$this->mTitle
->isContentPage() ) {
552 $text = $editInfo ?
$editInfo->pst
: false;
554 if ( $this->isRedirect( $text ) ) {
558 switch ( $wgArticleCountMethod ) {
562 if ( $text === false ) {
563 $text = $this->getRawText();
565 return strpos( $text, ',' ) !== false;
568 // ParserOutput::getLinks() is a 2D array of page links, so
569 // to be really correct we would need to recurse in the array
570 // but the main array should only have items in it if there are
572 return (bool)count( $editInfo->output
->getLinks() );
574 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
575 array( 'pl_from' => $this->getId() ), __METHOD__
);
581 * If this page is a redirect, get its target
583 * The target will be fetched from the redirect table if possible.
584 * If this page doesn't have an entry there, call insertRedirect()
585 * @return Title|mixed object, or null if this page is not a redirect
587 public function getRedirectTarget() {
588 if ( !$this->mTitle
->isRedirect() ) {
592 if ( $this->mRedirectTarget
!== null ) {
593 return $this->mRedirectTarget
;
596 # Query the redirect table
597 $dbr = wfGetDB( DB_SLAVE
);
598 $row = $dbr->selectRow( 'redirect',
599 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
600 array( 'rd_from' => $this->getId() ),
604 // rd_fragment and rd_interwiki were added later, populate them if empty
605 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
606 return $this->mRedirectTarget
= Title
::makeTitle(
607 $row->rd_namespace
, $row->rd_title
,
608 $row->rd_fragment
, $row->rd_interwiki
);
611 # This page doesn't have an entry in the redirect table
612 return $this->mRedirectTarget
= $this->insertRedirect();
616 * Insert an entry for this page into the redirect table.
618 * Don't call this function directly unless you know what you're doing.
619 * @return Title object or null if not a redirect
621 public function insertRedirect() {
622 // recurse through to only get the final target
623 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
627 $this->insertRedirectEntry( $retval );
632 * Insert or update the redirect table entry for this page to indicate
633 * it redirects to $rt .
634 * @param $rt Title redirect target
636 public function insertRedirectEntry( $rt ) {
637 $dbw = wfGetDB( DB_MASTER
);
638 $dbw->replace( 'redirect', array( 'rd_from' ),
640 'rd_from' => $this->getId(),
641 'rd_namespace' => $rt->getNamespace(),
642 'rd_title' => $rt->getDBkey(),
643 'rd_fragment' => $rt->getFragment(),
644 'rd_interwiki' => $rt->getInterwiki(),
651 * Get the Title object or URL this page redirects to
653 * @return mixed false, Title of in-wiki target, or string with URL
655 public function followRedirect() {
656 return $this->getRedirectURL( $this->getRedirectTarget() );
660 * Get the Title object or URL to use for a redirect. We use Title
661 * objects for same-wiki, non-special redirects and URLs for everything
663 * @param $rt Title Redirect target
664 * @return mixed false, Title object of local target, or string with URL
666 public function getRedirectURL( $rt ) {
671 if ( $rt->isExternal() ) {
672 if ( $rt->isLocal() ) {
673 // Offsite wikis need an HTTP redirect.
675 // This can be hard to reverse and may produce loops,
676 // so they may be disabled in the site configuration.
677 $source = $this->mTitle
->getFullURL( 'redirect=no' );
678 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
680 // External pages pages without "local" bit set are not valid
686 if ( $rt->isSpecialPage() ) {
687 // Gotta handle redirects to special pages differently:
688 // Fill the HTTP response "Location" header and ignore
689 // the rest of the page we're on.
691 // Some pages are not valid targets
692 if ( $rt->isValidRedirectTarget() ) {
693 return $rt->getFullURL();
703 * Get a list of users who have edited this article, not including the user who made
704 * the most recent revision, which you can get from $article->getUser() if you want it
705 * @return UserArrayFromResult
707 public function getContributors() {
708 # @todo FIXME: This is expensive; cache this info somewhere.
710 $dbr = wfGetDB( DB_SLAVE
);
712 if ( $dbr->implicitGroupby() ) {
713 $realNameField = 'user_real_name';
715 $realNameField = 'MIN(user_real_name) AS user_real_name';
718 $tables = array( 'revision', 'user' );
721 'rev_user as user_id',
722 'rev_user_text AS user_name',
724 'MAX(rev_timestamp) AS timestamp',
727 $conds = array( 'rev_page' => $this->getId() );
729 // The user who made the top revision gets credited as "this page was last edited by
730 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
731 $user = $this->getUser();
733 $conds[] = "rev_user != $user";
735 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
738 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
741 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
745 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
746 'ORDER BY' => 'timestamp DESC',
749 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
750 return new UserArrayFromResult( $res );
754 * Get the last N authors
755 * @param $num Integer: number of revisions to get
756 * @param $revLatest String: the latest rev_id, selected from the master (optional)
757 * @return array Array of authors, duplicates not removed
759 public function getLastNAuthors( $num, $revLatest = 0 ) {
760 wfProfileIn( __METHOD__
);
761 // First try the slave
762 // If that doesn't have the latest revision, try the master
764 $db = wfGetDB( DB_SLAVE
);
767 $res = $db->select( array( 'page', 'revision' ),
768 array( 'rev_id', 'rev_user_text' ),
770 'page_namespace' => $this->mTitle
->getNamespace(),
771 'page_title' => $this->mTitle
->getDBkey(),
775 'ORDER BY' => 'rev_timestamp DESC',
781 wfProfileOut( __METHOD__
);
785 $row = $db->fetchObject( $res );
787 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
788 $db = wfGetDB( DB_MASTER
);
793 } while ( $continue );
795 $authors = array( $row->rev_user_text
);
797 foreach ( $res as $row ) {
798 $authors[] = $row->rev_user_text
;
801 wfProfileOut( __METHOD__
);
806 * Should the parser cache be used?
808 * @param $parserOptions ParserOptions to check
812 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
813 global $wgEnableParserCache;
815 return $wgEnableParserCache
816 && $parserOptions->getStubThreshold() == 0
817 && $this->mTitle
->exists()
818 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
819 && $this->mTitle
->isWikitextPage(); #FIXME: ask ContentHandler if cachable!
823 * Get a ParserOutput for the given ParserOptions and revision ID.
824 * The parser cache will be used if possible.
827 * @param $parserOptions ParserOptions to use for the parse operation
828 * @param $oldid Revision ID to get the text from, passing null or 0 will
829 * get the current revision (default value)
830 * @return ParserOutput or false if the revision was not found
832 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
833 wfProfileIn( __METHOD__
);
835 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
836 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
837 if ( $parserOptions->getStubThreshold() ) {
838 wfIncrStats( 'pcache_miss_stub' );
841 if ( $useParserCache ) {
842 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
843 if ( $parserOutput !== false ) {
844 wfProfileOut( __METHOD__
);
845 return $parserOutput;
849 if ( $oldid === null ||
$oldid === 0 ) {
850 $oldid = $this->getLatest();
853 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
856 wfProfileOut( __METHOD__
);
858 return $pool->getParserOutput();
862 * Do standard deferred updates after page view
863 * @param $user User The relevant user
865 public function doViewUpdates( User
$user ) {
866 global $wgDisableCounters;
867 if ( wfReadOnly() ) {
871 # Don't update page view counters on views from bot users (bug 14044)
872 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
873 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
874 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
877 # Update newtalk / watchlist notification status
878 $user->clearNotification( $this->mTitle
);
882 * Perform the actions of a page purging
884 public function doPurge() {
887 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
891 // Invalidate the cache
892 $this->mTitle
->invalidateCache();
896 // Commit the transaction before the purge is sent
897 $dbw = wfGetDB( DB_MASTER
);
901 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
905 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
906 if ( $this->mTitle
->exists() ) {
907 $text = $this->getRawText();
912 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
918 * Insert a new empty page record for this article.
919 * This *must* be followed up by creating a revision
920 * and running $this->updateRevisionOn( ... );
921 * or else the record will be left in a funky state.
922 * Best if all done inside a transaction.
924 * @param $dbw DatabaseBase
925 * @return int The newly created page_id key, or false if the title already existed
927 public function insertOn( $dbw ) {
928 wfProfileIn( __METHOD__
);
930 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
931 $dbw->insert( 'page', array(
932 'page_id' => $page_id,
933 'page_namespace' => $this->mTitle
->getNamespace(),
934 'page_title' => $this->mTitle
->getDBkey(),
936 'page_restrictions' => '',
937 'page_is_redirect' => 0, # Will set this shortly...
939 'page_random' => wfRandom(),
940 'page_touched' => $dbw->timestamp(),
941 'page_latest' => 0, # Fill this in shortly...
942 'page_len' => 0, # Fill this in shortly...
943 ), __METHOD__
, 'IGNORE' );
945 $affected = $dbw->affectedRows();
948 $newid = $dbw->insertId();
949 $this->mTitle
->resetArticleID( $newid );
951 wfProfileOut( __METHOD__
);
953 return $affected ?
$newid : false;
957 * Update the page record to point to a newly saved revision.
959 * @param $dbw DatabaseBase: object
960 * @param $revision Revision: For ID number, and text used to set
961 * length and redirect status fields
962 * @param $lastRevision Integer: if given, will not overwrite the page field
963 * when different from the currently set value.
964 * Giving 0 indicates the new page flag should be set
966 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
967 * removing rows in redirect table.
968 * @return bool true on success, false on failure
971 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
972 wfProfileIn( __METHOD__
);
974 $text = $revision->getText();
975 $len = strlen( $text );
976 $rt = Title
::newFromRedirectRecurse( $text );
978 $conditions = array( 'page_id' => $this->getId() );
980 if ( !is_null( $lastRevision ) ) {
981 # An extra check against threads stepping on each other
982 $conditions['page_latest'] = $lastRevision;
985 $now = wfTimestampNow();
986 $dbw->update( 'page',
988 'page_latest' => $revision->getId(),
989 'page_touched' => $dbw->timestamp( $now ),
990 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
991 'page_is_redirect' => $rt !== null ?
1 : 0,
997 $result = $dbw->affectedRows() != 0;
999 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1000 $this->setLastEdit( $revision );
1001 $this->setCachedLastEditTime( $now );
1002 $this->mLatest
= $revision->getId();
1003 $this->mIsRedirect
= (bool)$rt;
1004 # Update the LinkCache.
1005 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1008 wfProfileOut( __METHOD__
);
1013 * Add row to the redirect table if this is a redirect, remove otherwise.
1015 * @param $dbw DatabaseBase
1016 * @param $redirectTitle Title object pointing to the redirect target,
1017 * or NULL if this is not a redirect
1018 * @param $lastRevIsRedirect If given, will optimize adding and
1019 * removing rows in redirect table.
1020 * @return bool true on success, false on failure
1023 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1024 // Always update redirects (target link might have changed)
1025 // Update/Insert if we don't know if the last revision was a redirect or not
1026 // Delete if changing from redirect to non-redirect
1027 $isRedirect = !is_null( $redirectTitle );
1029 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1033 wfProfileIn( __METHOD__
);
1034 if ( $isRedirect ) {
1035 $this->insertRedirectEntry( $redirectTitle );
1037 // This is not a redirect, remove row from redirect table
1038 $where = array( 'rd_from' => $this->getId() );
1039 $dbw->delete( 'redirect', $where, __METHOD__
);
1042 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1043 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1045 wfProfileOut( __METHOD__
);
1047 return ( $dbw->affectedRows() != 0 );
1051 * If the given revision is newer than the currently set page_latest,
1052 * update the page record. Otherwise, do nothing.
1054 * @param $dbw Database object
1055 * @param $revision Revision object
1058 public function updateIfNewerOn( $dbw, $revision ) {
1059 wfProfileIn( __METHOD__
);
1061 $row = $dbw->selectRow(
1062 array( 'revision', 'page' ),
1063 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1065 'page_id' => $this->getId(),
1066 'page_latest=rev_id' ),
1070 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1071 wfProfileOut( __METHOD__
);
1074 $prev = $row->rev_id
;
1075 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1077 # No or missing previous revision; mark the page as new
1079 $lastRevIsRedirect = null;
1082 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1084 wfProfileOut( __METHOD__
);
1089 * Get the text that needs to be saved in order to undo all revisions
1090 * between $undo and $undoafter. Revisions must belong to the same page,
1091 * must exist and must not be deleted
1092 * @param $undo Revision
1093 * @param $undoafter Revision Must be an earlier revision than $undo
1094 * @return mixed string on success, false on failure
1096 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1097 $cur_text = $this->getRawText();
1098 if ( $cur_text === false ) {
1099 return false; // no page
1101 $undo_text = $undo->getText();
1102 $undoafter_text = $undoafter->getText();
1104 if ( $cur_text == $undo_text ) {
1105 # No use doing a merge if it's just a straight revert.
1106 return $undoafter_text;
1111 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1115 return $undone_text;
1119 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1120 * @param $text String: new text of the section
1121 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1122 * @param $edittime String: revision timestamp or null to use the current revision
1123 * @return string Complete article text, or null if error
1125 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1126 wfProfileIn( __METHOD__
);
1128 if ( strval( $section ) == '' ) {
1129 // Whole-page edit; let the whole text through
1131 // Bug 30711: always use current version when adding a new section
1132 if ( is_null( $edittime ) ||
$section == 'new' ) {
1133 $oldtext = $this->getRawText();
1134 if ( $oldtext === false ) {
1135 wfDebug( __METHOD__
. ": no page text\n" );
1136 wfProfileOut( __METHOD__
);
1140 $dbw = wfGetDB( DB_MASTER
);
1141 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1144 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1145 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1146 wfProfileOut( __METHOD__
);
1150 $oldtext = $rev->getText();
1153 if ( $section == 'new' ) {
1154 # Inserting a new section
1155 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1156 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1157 $text = strlen( trim( $oldtext ) ) > 0
1158 ?
"{$oldtext}\n\n{$subject}{$text}"
1159 : "{$subject}{$text}";
1162 # Replacing an existing section; roll out the big guns
1165 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1169 wfProfileOut( __METHOD__
);
1174 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1176 * @return Int updated $flags
1178 function checkFlags( $flags ) {
1179 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1180 if ( $this->mTitle
->getArticleID() ) {
1181 $flags |
= EDIT_UPDATE
;
1191 * Change an existing article or create a new article. Updates RC and all necessary caches,
1192 * optionally via the deferred update array.
1194 * @param $text String: new text
1195 * @param $summary String: edit summary
1196 * @param $flags Integer bitfield:
1198 * Article is known or assumed to be non-existent, create a new one
1200 * Article is known or assumed to be pre-existing, update it
1202 * Mark this edit minor, if the user is allowed to do so
1204 * Do not log the change in recentchanges
1206 * Mark the edit a "bot" edit regardless of user rights
1207 * EDIT_DEFER_UPDATES
1208 * Defer some of the updates until the end of index.php
1210 * Fill in blank summaries with generated text where possible
1212 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1213 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1214 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1215 * edit-already-exists error will be returned. These two conditions are also possible with
1216 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1218 * @param $baseRevId the revision ID this edit was based off, if any
1219 * @param $user User the user doing the edit
1221 * @return Status object. Possible errors:
1222 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1223 * edit-gone-missing: In update mode, but the article didn't exist
1224 * edit-conflict: In update mode, the article changed unexpectedly
1225 * edit-no-change: Warning that the text was the same as before
1226 * edit-already-exists: In creation mode, but the article already exists
1228 * Extensions may define additional errors.
1230 * $return->value will contain an associative array with members as follows:
1231 * new: Boolean indicating if the function attempted to create a new article
1232 * revision: The revision object for the inserted revision, or null
1234 * Compatibility note: this function previously returned a boolean value indicating success/failure
1236 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1237 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1239 # Low-level sanity check
1240 if ( $this->mTitle
->getText() === '' ) {
1241 throw new MWException( 'Something is trying to edit an article with an empty title' );
1244 wfProfileIn( __METHOD__
);
1246 $user = is_null( $user ) ?
$wgUser : $user;
1247 $status = Status
::newGood( array() );
1249 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1250 $this->loadPageData( 'fromdbmaster' );
1252 $flags = $this->checkFlags( $flags );
1254 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1255 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1257 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1259 if ( $status->isOK() ) {
1260 $status->fatal( 'edit-hook-aborted' );
1263 wfProfileOut( __METHOD__
);
1267 # Silently ignore EDIT_MINOR if not allowed
1268 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1269 $bot = $flags & EDIT_FORCE_BOT
;
1271 $oldtext = $this->getRawText(); // current revision
1272 $oldsize = strlen( $oldtext );
1273 $oldid = $this->getLatest();
1274 $oldIsRedirect = $this->isRedirect();
1275 $oldcountable = $this->isCountable();
1277 # Provide autosummaries if one is not provided and autosummaries are enabled.
1278 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1279 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1282 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1283 $text = $editInfo->pst
;
1284 $newsize = strlen( $text );
1286 $dbw = wfGetDB( DB_MASTER
);
1287 $now = wfTimestampNow();
1288 $this->mTimestamp
= $now;
1290 if ( $flags & EDIT_UPDATE
) {
1291 # Update article, but only if changed.
1292 $status->value
['new'] = false;
1295 # Article gone missing
1296 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1297 $status->fatal( 'edit-gone-missing' );
1299 wfProfileOut( __METHOD__
);
1303 # Make sure the revision is either completely inserted or not inserted at all
1304 if ( !$wgDBtransactions ) {
1305 $userAbort = ignore_user_abort( true );
1308 $revision = new Revision( array(
1309 'page' => $this->getId(),
1310 'comment' => $summary,
1311 'minor_edit' => $isminor,
1312 'text' => $text, #FIXME: set content instead, leavfe serialization to revision?!
1313 'parent_id' => $oldid,
1314 'user' => $user->getId(),
1315 'user_text' => $user->getName(),
1319 $changed = ( strcmp( $text, $oldtext ) != 0 );
1323 $revisionId = $revision->insertOn( $dbw );
1327 # Note that we use $this->mLatest instead of fetching a value from the master DB
1328 # during the course of this function. This makes sure that EditPage can detect
1329 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1330 # before this function is called. A previous function used a separate query, this
1331 # creates a window where concurrent edits can cause an ignored edit conflict.
1332 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1335 /* Belated edit conflict! Run away!! */
1336 $status->fatal( 'edit-conflict' );
1338 # Delete the invalid revision if the DB is not transactional
1339 if ( !$wgDBtransactions ) {
1340 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1346 global $wgUseRCPatrol;
1347 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1348 # Update recentchanges
1349 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1350 # Mark as patrolled if the user can do so
1351 $patrolled = $wgUseRCPatrol && !count(
1352 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1353 # Add RC row to the DB
1354 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1355 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1356 $revisionId, $patrolled
1359 # Log auto-patrolled edits
1361 PatrolLog
::record( $rc, true );
1364 $user->incEditCount();
1368 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1369 // related variables correctly
1370 $revision->setId( $this->getLatest() );
1373 if ( !$wgDBtransactions ) {
1374 ignore_user_abort( $userAbort );
1377 // Now that ignore_user_abort is restored, we can respond to fatal errors
1378 if ( !$status->isOK() ) {
1379 wfProfileOut( __METHOD__
);
1383 # Update links tables, site stats, etc.
1384 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1385 'oldcountable' => $oldcountable ) );
1388 $status->warning( 'edit-no-change' );
1390 // Update page_touched, this is usually implicit in the page update
1391 // Other cache updates are done in onArticleEdit()
1392 $this->mTitle
->invalidateCache();
1395 # Create new article
1396 $status->value
['new'] = true;
1400 # Add the page record; stake our claim on this title!
1401 # This will return false if the article already exists
1402 $newid = $this->insertOn( $dbw );
1404 if ( $newid === false ) {
1406 $status->fatal( 'edit-already-exists' );
1408 wfProfileOut( __METHOD__
);
1412 # Save the revision text...
1413 $revision = new Revision( array(
1415 'comment' => $summary,
1416 'minor_edit' => $isminor,
1418 'user' => $user->getId(),
1419 'user_text' => $user->getName(),
1422 $revisionId = $revision->insertOn( $dbw );
1424 # Update the page record with revision data
1425 $this->updateRevisionOn( $dbw, $revision, 0 );
1427 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1429 # Update recentchanges
1430 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1431 global $wgUseRCPatrol, $wgUseNPPatrol;
1433 # Mark as patrolled if the user can do so
1434 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1435 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1436 # Add RC row to the DB
1437 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1438 '', strlen( $text ), $revisionId, $patrolled );
1440 # Log auto-patrolled edits
1442 PatrolLog
::record( $rc, true );
1445 $user->incEditCount();
1448 # Update links, etc.
1449 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1451 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1452 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1455 # Do updates right now unless deferral was requested
1456 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1457 DeferredUpdates
::doUpdates();
1460 // Return the new revision (or null) to the caller
1461 $status->value
['revision'] = $revision;
1463 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1464 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1466 # Promote user to any groups they meet the criteria for
1467 $user->addAutopromoteOnceGroups( 'onEdit' );
1469 wfProfileOut( __METHOD__
);
1474 * Get parser options suitable for rendering the primary article wikitext
1475 * @param User|string $user User object or 'canonical'
1476 * @return ParserOptions
1478 public function makeParserOptions( $user ) {
1480 if ( $user instanceof User
) { // settings per user (even anons)
1481 $options = ParserOptions
::newFromUser( $user );
1482 } else { // canonical settings
1483 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1485 $options->enableLimitReport(); // show inclusion/loop reports
1486 $options->setTidy( true ); // fix bad HTML
1491 * Prepare text which is about to be saved.
1492 * Returns a stdclass with source, pst and output members
1494 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1495 global $wgParser, $wgContLang, $wgUser;
1496 $user = is_null( $user ) ?
$wgUser : $user;
1497 // @TODO fixme: check $user->getId() here???
1498 if ( $this->mPreparedEdit
1499 && $this->mPreparedEdit
->newText
== $text
1500 && $this->mPreparedEdit
->revid
== $revid
1503 return $this->mPreparedEdit
;
1506 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1507 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1509 $edit = (object)array();
1510 $edit->revid
= $revid;
1511 $edit->newText
= $text;
1512 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1513 $edit->popts
= $this->makeParserOptions( 'canonical' );
1514 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1515 $edit->oldText
= $this->getRawText();
1517 $this->mPreparedEdit
= $edit;
1523 * Do standard deferred updates after page edit.
1524 * Update links tables, site stats, search index and message cache.
1525 * Purges pages that include this page if the text was changed here.
1526 * Every 100th edit, prune the recent changes table.
1529 * @param $revision Revision object
1530 * @param $user User object that did the revision
1531 * @param $options Array of options, following indexes are used:
1532 * - changed: boolean, whether the revision changed the content (default true)
1533 * - created: boolean, whether the revision created the page (default false)
1534 * - oldcountable: boolean or null (default null):
1535 * - boolean: whether the page was counted as an article before that
1536 * revision, only used in changed is true and created is false
1537 * - null: don't change the article count
1539 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1540 global $wgEnableParserCache;
1542 wfProfileIn( __METHOD__
);
1544 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1545 $text = $revision->getText();
1548 # Be careful not to double-PST: $text is usually already PST-ed once
1549 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1550 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1551 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1553 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1554 $editInfo = $this->mPreparedEdit
;
1557 # Save it to the parser cache
1558 if ( $wgEnableParserCache ) {
1559 $parserCache = ParserCache
::singleton();
1560 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1563 # Update the links tables
1564 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1567 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1569 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1570 if ( 0 == mt_rand( 0, 99 ) ) {
1571 // Flush old entries from the `recentchanges` table; we do this on
1572 // random requests so as to avoid an increase in writes for no good reason
1575 $dbw = wfGetDB( DB_MASTER
);
1576 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1579 array( "rc_timestamp < '$cutoff'" ),
1585 if ( !$this->mTitle
->exists() ) {
1586 wfProfileOut( __METHOD__
);
1590 $id = $this->getId();
1591 $title = $this->mTitle
->getPrefixedDBkey();
1592 $shortTitle = $this->mTitle
->getDBkey();
1594 if ( !$options['changed'] ) {
1597 } elseif ( $options['created'] ) {
1598 $good = (int)$this->isCountable( $editInfo );
1600 } elseif ( $options['oldcountable'] !== null ) {
1601 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1608 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1609 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1611 # If this is another user's talk page, update newtalk.
1612 # Don't do this if $options['changed'] = false (null-edits) nor if
1613 # it's a minor edit and the user doesn't want notifications for those.
1614 if ( $options['changed']
1615 && $this->mTitle
->getNamespace() == NS_USER_TALK
1616 && $shortTitle != $user->getTitleKey()
1617 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1619 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1620 $other = User
::newFromName( $shortTitle, false );
1622 wfDebug( __METHOD__
. ": invalid username\n" );
1623 } elseif ( User
::isIP( $shortTitle ) ) {
1624 // An anonymous user
1625 $other->setNewtalk( true );
1626 } elseif ( $other->isLoggedIn() ) {
1627 $other->setNewtalk( true );
1629 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1634 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1635 MessageCache
::singleton()->replace( $shortTitle, $text );
1638 if( $options['created'] ) {
1639 self
::onArticleCreate( $this->mTitle
);
1641 self
::onArticleEdit( $this->mTitle
);
1644 wfProfileOut( __METHOD__
);
1648 * Edit an article without doing all that other stuff
1649 * The article must already exist; link tables etc
1650 * are not updated, caches are not flushed.
1652 * @param $text String: text submitted
1653 * @param $user User The relevant user
1654 * @param $comment String: comment submitted
1655 * @param $minor Boolean: whereas it's a minor modification
1657 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1658 wfProfileIn( __METHOD__
);
1660 $dbw = wfGetDB( DB_MASTER
);
1661 $revision = new Revision( array(
1662 'page' => $this->getId(),
1664 'comment' => $comment,
1665 'minor_edit' => $minor ?
1 : 0,
1667 $revision->insertOn( $dbw );
1668 $this->updateRevisionOn( $dbw, $revision );
1670 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1672 wfProfileOut( __METHOD__
);
1676 * Update the article's restriction field, and leave a log entry.
1677 * This works for protection both existing and non-existing pages.
1679 * @param $limit Array: set of restriction keys
1680 * @param $reason String
1681 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1682 * @param $expiry Array: per restriction type expiration
1683 * @param $user User The user updating the restrictions
1684 * @return bool true on success
1686 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1689 if ( wfReadOnly() ) {
1690 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1693 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1695 $id = $this->mTitle
->getArticleID();
1701 // Take this opportunity to purge out expired restrictions
1702 Title
::purgeExpiredRestrictions();
1704 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1705 # we expect a single selection, but the schema allows otherwise.
1706 $isProtected = false;
1710 $dbw = wfGetDB( DB_MASTER
);
1712 foreach ( $restrictionTypes as $action ) {
1713 if ( !isset( $expiry[$action] ) ) {
1714 $expiry[$action] = $dbw->getInfinity();
1716 if ( !isset( $limit[$action] ) ) {
1717 $limit[$action] = '';
1718 } elseif ( $limit[$action] != '' ) {
1722 # Get current restrictions on $action
1723 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1724 if ( $current != '' ) {
1725 $isProtected = true;
1728 if ( $limit[$action] != $current ) {
1730 } elseif ( $limit[$action] != '' ) {
1731 # Only check expiry change if the action is actually being
1732 # protected, since expiry does nothing on an not-protected
1734 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1740 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1744 # If nothing's changed, do nothing
1746 return Status
::newGood();
1749 if ( !$protect ) { # No protection at all means unprotection
1750 $revCommentMsg = 'unprotectedarticle';
1751 $logAction = 'unprotect';
1752 } elseif ( $isProtected ) {
1753 $revCommentMsg = 'modifiedarticleprotection';
1754 $logAction = 'modify';
1756 $revCommentMsg = 'protectedarticle';
1757 $logAction = 'protect';
1760 $encodedExpiry = array();
1761 $protectDescription = '';
1762 foreach ( $limit as $action => $restrictions ) {
1763 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1764 if ( $restrictions != '' ) {
1765 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1766 if ( $encodedExpiry[$action] != 'infinity' ) {
1767 $protectDescription .= wfMsgForContent( 'protect-expiring',
1768 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1769 $wgContLang->date( $expiry[$action], false, false ) ,
1770 $wgContLang->time( $expiry[$action], false, false ) );
1772 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1775 $protectDescription .= ') ';
1778 $protectDescription = trim( $protectDescription );
1780 if ( $id ) { # Protection of existing page
1781 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1782 return Status
::newGood();
1785 # Only restrictions with the 'protect' right can cascade...
1786 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1787 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1789 # The schema allows multiple restrictions
1790 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1794 # Update restrictions table
1795 foreach ( $limit as $action => $restrictions ) {
1796 if ( $restrictions != '' ) {
1797 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1798 array( 'pr_page' => $id,
1799 'pr_type' => $action,
1800 'pr_level' => $restrictions,
1801 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1802 'pr_expiry' => $encodedExpiry[$action]
1807 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1808 'pr_type' => $action ), __METHOD__
);
1812 # Prepare a null revision to be added to the history
1813 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1815 $editComment .= ": $reason";
1817 if ( $protectDescription ) {
1818 $editComment .= " ($protectDescription)";
1821 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1824 # Insert a null revision
1825 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1826 $nullRevId = $nullRevision->insertOn( $dbw );
1828 $latest = $this->getLatest();
1829 # Update page record
1830 $dbw->update( 'page',
1832 'page_touched' => $dbw->timestamp(),
1833 'page_restrictions' => '',
1834 'page_latest' => $nullRevId
1835 ), array( /* WHERE */
1840 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1841 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1842 } else { # Protection of non-existing page (also known as "title protection")
1843 # Cascade protection is meaningless in this case
1846 if ( $limit['create'] != '' ) {
1847 $dbw->replace( 'protected_titles',
1848 array( array( 'pt_namespace', 'pt_title' ) ),
1850 'pt_namespace' => $this->mTitle
->getNamespace(),
1851 'pt_title' => $this->mTitle
->getDBkey(),
1852 'pt_create_perm' => $limit['create'],
1853 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1854 'pt_expiry' => $encodedExpiry['create'],
1855 'pt_user' => $user->getId(),
1856 'pt_reason' => $reason,
1860 $dbw->delete( 'protected_titles',
1862 'pt_namespace' => $this->mTitle
->getNamespace(),
1863 'pt_title' => $this->mTitle
->getDBkey()
1869 $this->mTitle
->flushRestrictions();
1871 if ( $logAction == 'unprotect' ) {
1872 $logParams = array();
1874 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1877 # Update the protection log
1878 $log = new LogPage( 'protect' );
1879 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1881 return Status
::newGood();
1885 * Take an array of page restrictions and flatten it to a string
1886 * suitable for insertion into the page_restrictions field.
1887 * @param $limit Array
1890 protected static function flattenRestrictions( $limit ) {
1891 if ( !is_array( $limit ) ) {
1892 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1898 foreach ( $limit as $action => $restrictions ) {
1899 if ( $restrictions != '' ) {
1900 $bits[] = "$action=$restrictions";
1904 return implode( ':', $bits );
1908 * Back-end article deletion
1909 * Deletes the article with database consistency, writes logs, purges caches
1911 * @param $reason string delete reason for deletion log
1912 * @param $suppress bitfield
1913 * Revision::DELETED_TEXT
1914 * Revision::DELETED_COMMENT
1915 * Revision::DELETED_USER
1916 * Revision::DELETED_RESTRICTED
1917 * @param $id int article ID
1918 * @param $commit boolean defaults to true, triggers transaction end
1919 * @param &$errors Array of errors to append to
1920 * @param $user User The relevant user
1921 * @return boolean true if successful
1923 public function doDeleteArticle(
1924 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1927 $user = is_null( $user ) ?
$wgUser : $user;
1929 wfDebug( __METHOD__
. "\n" );
1931 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1934 $dbw = wfGetDB( DB_MASTER
);
1935 $t = $this->mTitle
->getDBkey();
1936 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1938 if ( $t === '' ||
$id == 0 ) {
1942 // Bitfields to further suppress the content
1945 // This should be 15...
1946 $bitfield |
= Revision
::DELETED_TEXT
;
1947 $bitfield |
= Revision
::DELETED_COMMENT
;
1948 $bitfield |
= Revision
::DELETED_USER
;
1949 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1951 $bitfield = 'rev_deleted';
1955 // For now, shunt the revision data into the archive table.
1956 // Text is *not* removed from the text table; bulk storage
1957 // is left intact to avoid breaking block-compression or
1958 // immutable storage schemes.
1960 // For backwards compatibility, note that some older archive
1961 // table entries will have ar_text and ar_flags fields still.
1963 // In the future, we may keep revisions and mark them with
1964 // the rev_deleted field, which is reserved for this purpose.
1965 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1967 'ar_namespace' => 'page_namespace',
1968 'ar_title' => 'page_title',
1969 'ar_comment' => 'rev_comment',
1970 'ar_user' => 'rev_user',
1971 'ar_user_text' => 'rev_user_text',
1972 'ar_timestamp' => 'rev_timestamp',
1973 'ar_minor_edit' => 'rev_minor_edit',
1974 'ar_rev_id' => 'rev_id',
1975 'ar_parent_id' => 'rev_parent_id',
1976 'ar_text_id' => 'rev_text_id',
1977 'ar_text' => '\'\'', // Be explicit to appease
1978 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1979 'ar_len' => 'rev_len',
1980 'ar_page_id' => 'page_id',
1981 'ar_deleted' => $bitfield,
1982 'ar_sha1' => 'rev_content_model',
1983 'ar_content_format' => 'rev_content_format',
1984 'ar_content_format' => 'rev_sha1'
1987 'page_id = rev_page'
1991 # Now that it's safely backed up, delete it
1992 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1993 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2000 $this->doDeleteUpdates( $id );
2002 # Log the deletion, if the page was suppressed, log it at Oversight instead
2003 $logtype = $suppress ?
'suppress' : 'delete';
2005 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2006 $logEntry->setPerformer( $user );
2007 $logEntry->setTarget( $this->mTitle
);
2008 $logEntry->setComment( $reason );
2009 $logid = $logEntry->insert();
2010 $logEntry->publish( $logid );
2016 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2021 * Do some database updates after deletion
2023 * @param $id Int: page_id value of the page being deleted
2025 public function doDeleteUpdates( $id ) {
2026 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2028 $dbw = wfGetDB( DB_MASTER
);
2030 # Delete restrictions for it
2031 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2033 # Fix category table counts
2035 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2037 foreach ( $res as $row ) {
2038 $cats [] = $row->cl_to
;
2041 $this->updateCategoryCounts( array(), $cats );
2043 # If using cascading deletes, we can skip some explicit deletes
2044 if ( !$dbw->cascadingDeletes() ) {
2045 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2047 # Delete outgoing links
2048 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2049 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2050 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2051 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2052 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2053 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2054 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2055 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2056 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2059 # If using cleanup triggers, we can skip some manual deletes
2060 if ( !$dbw->cleanupTriggers() ) {
2061 # Clean up recentchanges entries...
2062 $dbw->delete( 'recentchanges',
2063 array( 'rc_type != ' . RC_LOG
,
2064 'rc_namespace' => $this->mTitle
->getNamespace(),
2065 'rc_title' => $this->mTitle
->getDBkey() ),
2067 $dbw->delete( 'recentchanges',
2068 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2073 self
::onArticleDelete( $this->mTitle
);
2075 # Clear the cached article id so the interface doesn't act like we exist
2076 $this->mTitle
->resetArticleID( 0 );
2080 * Roll back the most recent consecutive set of edits to a page
2081 * from the same user; fails if there are no eligible edits to
2082 * roll back to, e.g. user is the sole contributor. This function
2083 * performs permissions checks on $user, then calls commitRollback()
2084 * to do the dirty work
2086 * @todo: seperate the business/permission stuff out from backend code
2088 * @param $fromP String: Name of the user whose edits to rollback.
2089 * @param $summary String: Custom summary. Set to default summary if empty.
2090 * @param $token String: Rollback token.
2091 * @param $bot Boolean: If true, mark all reverted edits as bot.
2093 * @param $resultDetails Array: contains result-specific array of additional values
2094 * 'alreadyrolled' : 'current' (rev)
2095 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2097 * @param $user User The user performing the rollback
2098 * @return array of errors, each error formatted as
2099 * array(messagekey, param1, param2, ...).
2100 * On success, the array is empty. This array can also be passed to
2101 * OutputPage::showPermissionsErrorPage().
2103 public function doRollback(
2104 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2106 $resultDetails = null;
2109 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2110 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2111 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2113 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2114 $errors[] = array( 'sessionfailure' );
2117 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2118 $errors[] = array( 'actionthrottledtext' );
2121 # If there were errors, bail out now
2122 if ( !empty( $errors ) ) {
2126 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2130 * Backend implementation of doRollback(), please refer there for parameter
2131 * and return value documentation
2133 * NOTE: This function does NOT check ANY permissions, it just commits the
2134 * rollback to the DB. Therefore, you should only call this function direct-
2135 * ly if you want to use custom permissions checks. If you don't, use
2136 * doRollback() instead.
2137 * @param $fromP String: Name of the user whose edits to rollback.
2138 * @param $summary String: Custom summary. Set to default summary if empty.
2139 * @param $bot Boolean: If true, mark all reverted edits as bot.
2141 * @param $resultDetails Array: contains result-specific array of additional values
2142 * @param $guser User The user performing the rollback
2144 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2145 global $wgUseRCPatrol, $wgContLang;
2147 $dbw = wfGetDB( DB_MASTER
);
2149 if ( wfReadOnly() ) {
2150 return array( array( 'readonlytext' ) );
2153 # Get the last editor
2154 $current = Revision
::newFromTitle( $this->mTitle
);
2155 if ( is_null( $current ) ) {
2156 # Something wrong... no page?
2157 return array( array( 'notanarticle' ) );
2160 $from = str_replace( '_', ' ', $fromP );
2161 # User name given should match up with the top revision.
2162 # If the user was deleted then $from should be empty.
2163 if ( $from != $current->getUserText() ) {
2164 $resultDetails = array( 'current' => $current );
2165 return array( array( 'alreadyrolled',
2166 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2167 htmlspecialchars( $fromP ),
2168 htmlspecialchars( $current->getUserText() )
2172 # Get the last edit not by this guy...
2173 # Note: these may not be public values
2174 $user = intval( $current->getRawUser() );
2175 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2176 $s = $dbw->selectRow( 'revision',
2177 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2178 array( 'rev_page' => $current->getPage(),
2179 "rev_user != {$user} OR rev_user_text != {$user_text}"
2181 array( 'USE INDEX' => 'page_timestamp',
2182 'ORDER BY' => 'rev_timestamp DESC' )
2184 if ( $s === false ) {
2185 # No one else ever edited this page
2186 return array( array( 'cantrollback' ) );
2187 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2188 # Only admins can see this text
2189 return array( array( 'notvisiblerev' ) );
2193 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2194 # Mark all reverted edits as bot
2198 if ( $wgUseRCPatrol ) {
2199 # Mark all reverted edits as patrolled
2200 $set['rc_patrolled'] = 1;
2203 if ( count( $set ) ) {
2204 $dbw->update( 'recentchanges', $set,
2206 'rc_cur_id' => $current->getPage(),
2207 'rc_user_text' => $current->getUserText(),
2208 "rc_timestamp > '{$s->rev_timestamp}'",
2213 # Generate the edit summary if necessary
2214 $target = Revision
::newFromId( $s->rev_id
);
2215 if ( empty( $summary ) ) {
2216 if ( $from == '' ) { // no public user name
2217 $summary = wfMsgForContent( 'revertpage-nouser' );
2219 $summary = wfMsgForContent( 'revertpage' );
2223 # Allow the custom summary to use the same args as the default message
2225 $target->getUserText(), $from, $s->rev_id
,
2226 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2227 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2229 $summary = wfMsgReplaceArgs( $summary, $args );
2232 $flags = EDIT_UPDATE
;
2234 if ( $guser->isAllowed( 'minoredit' ) ) {
2235 $flags |
= EDIT_MINOR
;
2238 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2239 $flags |
= EDIT_FORCE_BOT
;
2242 # Actually store the edit
2243 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2244 if ( !empty( $status->value
['revision'] ) ) {
2245 $revId = $status->value
['revision']->getId();
2250 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2252 $resultDetails = array(
2253 'summary' => $summary,
2254 'current' => $current,
2255 'target' => $target,
2263 * The onArticle*() functions are supposed to be a kind of hooks
2264 * which should be called whenever any of the specified actions
2267 * This is a good place to put code to clear caches, for instance.
2269 * This is called on page move and undelete, as well as edit
2271 * @param $title Title object
2273 public static function onArticleCreate( $title ) {
2274 # Update existence markers on article/talk tabs...
2275 if ( $title->isTalkPage() ) {
2276 $other = $title->getSubjectPage();
2278 $other = $title->getTalkPage();
2281 $other->invalidateCache();
2282 $other->purgeSquid();
2284 $title->touchLinks();
2285 $title->purgeSquid();
2286 $title->deleteTitleProtection();
2290 * Clears caches when article is deleted
2292 * @param $title Title
2294 public static function onArticleDelete( $title ) {
2295 # Update existence markers on article/talk tabs...
2296 if ( $title->isTalkPage() ) {
2297 $other = $title->getSubjectPage();
2299 $other = $title->getTalkPage();
2302 $other->invalidateCache();
2303 $other->purgeSquid();
2305 $title->touchLinks();
2306 $title->purgeSquid();
2309 HTMLFileCache
::clearFileCache( $title );
2312 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2313 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2317 if ( $title->getNamespace() == NS_FILE
) {
2318 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2319 $update->doUpdate();
2323 if ( $title->getNamespace() == NS_USER_TALK
) {
2324 $user = User
::newFromName( $title->getText(), false );
2326 $user->setNewtalk( false );
2331 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2335 * Purge caches on page update etc
2337 * @param $title Title object
2338 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2340 public static function onArticleEdit( $title ) {
2341 // Invalidate caches of articles which include this page
2342 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2345 // Invalidate the caches of all pages which redirect here
2346 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2348 # Purge squid for this page only
2349 $title->purgeSquid();
2351 # Clear file cache for this page only
2352 HTMLFileCache
::clearFileCache( $title );
2358 * Returns a list of hidden categories this page is a member of.
2359 * Uses the page_props and categorylinks tables.
2361 * @return Array of Title objects
2363 public function getHiddenCategories() {
2365 $id = $this->mTitle
->getArticleID();
2371 $dbr = wfGetDB( DB_SLAVE
);
2372 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2374 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2375 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2378 if ( $res !== false ) {
2379 foreach ( $res as $row ) {
2380 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2388 * Return an applicable autosummary if one exists for the given edit.
2389 * @param $oldtext String: the previous text of the page.
2390 * @param $newtext String: The submitted text of the page.
2391 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2392 * @return string An appropriate autosummary, or an empty string.
2394 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2397 # Decide what kind of autosummary is needed.
2399 # Redirect autosummaries
2400 $ot = Title
::newFromRedirect( $oldtext );
2401 $rt = Title
::newFromRedirect( $newtext );
2403 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2404 $truncatedtext = $wgContLang->truncate(
2405 str_replace( "\n", ' ', $newtext ),
2407 - strlen( wfMsgForContent( 'autoredircomment' ) )
2408 - strlen( $rt->getFullText() )
2410 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2413 # New page autosummaries
2414 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2415 # If they're making a new article, give its text, truncated, in the summary.
2417 $truncatedtext = $wgContLang->truncate(
2418 str_replace( "\n", ' ', $newtext ),
2419 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2421 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2424 # Blanking autosummaries
2425 if ( $oldtext != '' && $newtext == '' ) {
2426 return wfMsgForContent( 'autosumm-blank' );
2427 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2428 # Removing more than 90% of the article
2430 $truncatedtext = $wgContLang->truncate(
2432 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2434 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2437 # If we reach this point, there's no applicable autosummary for our case, so our
2438 # autosummary is empty.
2443 * Auto-generates a deletion reason
2445 * @param &$hasHistory Boolean: whether the page has a history
2446 * @return mixed String containing deletion reason or empty string, or boolean false
2447 * if no revision occurred
2449 public function getAutoDeleteReason( &$hasHistory ) {
2452 $dbw = wfGetDB( DB_MASTER
);
2453 // Get the last revision
2454 $rev = Revision
::newFromTitle( $this->getTitle() );
2456 if ( is_null( $rev ) ) {
2460 // Get the article's contents
2461 $contents = $rev->getText();
2464 // If the page is blank, use the text from the previous revision,
2465 // which can only be blank if there's a move/import/protect dummy revision involved
2466 if ( $contents == '' ) {
2467 $prev = $rev->getPrevious();
2470 $contents = $prev->getText();
2475 // Find out if there was only one contributor
2476 // Only scan the last 20 revisions
2477 $res = $dbw->select( 'revision', 'rev_user_text',
2478 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2480 array( 'LIMIT' => 20 )
2483 if ( $res === false ) {
2484 // This page has no revisions, which is very weird
2488 $hasHistory = ( $res->numRows() > 1 );
2489 $row = $dbw->fetchObject( $res );
2491 if ( $row ) { // $row is false if the only contributor is hidden
2492 $onlyAuthor = $row->rev_user_text
;
2493 // Try to find a second contributor
2494 foreach ( $res as $row ) {
2495 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2496 $onlyAuthor = false;
2501 $onlyAuthor = false;
2504 // Generate the summary with a '$1' placeholder
2506 // The current revision is blank and the one before is also
2507 // blank. It's just not our lucky day
2508 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2510 if ( $onlyAuthor ) {
2511 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2513 $reason = wfMsgForContent( 'excontent', '$1' );
2517 if ( $reason == '-' ) {
2518 // Allow these UI messages to be blanked out cleanly
2522 // Replace newlines with spaces to prevent uglyness
2523 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2524 // Calculate the maximum amount of chars to get
2525 // Max content length = max comment length - length of the comment (excl. $1)
2526 $maxLength = 255 - ( strlen( $reason ) - 2 );
2527 $contents = $wgContLang->truncate( $contents, $maxLength );
2528 // Remove possible unfinished links
2529 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2530 // Now replace the '$1' placeholder
2531 $reason = str_replace( '$1', $contents, $reason );
2537 * Update all the appropriate counts in the category table, given that
2538 * we've added the categories $added and deleted the categories $deleted.
2540 * @param $added array The names of categories that were added
2541 * @param $deleted array The names of categories that were deleted
2543 public function updateCategoryCounts( $added, $deleted ) {
2544 $ns = $this->mTitle
->getNamespace();
2545 $dbw = wfGetDB( DB_MASTER
);
2547 # First make sure the rows exist. If one of the "deleted" ones didn't
2548 # exist, we might legitimately not create it, but it's simpler to just
2549 # create it and then give it a negative value, since the value is bogus
2552 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2553 $insertCats = array_merge( $added, $deleted );
2554 if ( !$insertCats ) {
2555 # Okay, nothing to do
2559 $insertRows = array();
2561 foreach ( $insertCats as $cat ) {
2562 $insertRows[] = array(
2563 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2567 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2569 $addFields = array( 'cat_pages = cat_pages + 1' );
2570 $removeFields = array( 'cat_pages = cat_pages - 1' );
2572 if ( $ns == NS_CATEGORY
) {
2573 $addFields[] = 'cat_subcats = cat_subcats + 1';
2574 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2575 } elseif ( $ns == NS_FILE
) {
2576 $addFields[] = 'cat_files = cat_files + 1';
2577 $removeFields[] = 'cat_files = cat_files - 1';
2584 array( 'cat_title' => $added ),
2593 array( 'cat_title' => $deleted ),
2600 * Updates cascading protections
2602 * @param $parserOutput ParserOutput object for the current version
2604 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2605 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2609 // templatelinks table may have become out of sync,
2610 // especially if using variable-based transclusions.
2611 // For paranoia, check if things have changed and if
2612 // so apply updates to the database. This will ensure
2613 // that cascaded protections apply as soon as the changes
2616 # Get templates from templatelinks
2617 $id = $this->mTitle
->getArticleID();
2619 $tlTemplates = array();
2621 $dbr = wfGetDB( DB_SLAVE
);
2622 $res = $dbr->select( array( 'templatelinks' ),
2623 array( 'tl_namespace', 'tl_title' ),
2624 array( 'tl_from' => $id ),
2628 foreach ( $res as $row ) {
2629 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2632 # Get templates from parser output.
2633 $poTemplates = array();
2634 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2635 foreach ( $templates as $dbk => $id ) {
2636 $poTemplates["$ns:$dbk"] = true;
2641 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2643 if ( count( $templates_diff ) > 0 ) {
2644 # Whee, link updates time.
2645 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2651 * Return a list of templates used by this article.
2652 * Uses the templatelinks table
2654 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2655 * @return Array of Title objects
2657 public function getUsedTemplates() {
2658 return $this->mTitle
->getTemplateLinksFrom();
2662 * Perform article updates on a special page creation.
2664 * @param $rev Revision object
2666 * @todo This is a shitty interface function. Kill it and replace the
2667 * other shitty functions like doEditUpdates and such so it's not needed
2669 * @deprecated since 1.18, use doEditUpdates()
2671 public function createUpdates( $rev ) {
2672 wfDeprecated( __METHOD__
, '1.18' );
2674 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2678 * This function is called right before saving the wikitext,
2679 * so we can do things like signatures and links-in-context.
2681 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2682 * @param $text String article contents
2683 * @param $user User object: user doing the edit
2684 * @param $popts ParserOptions object: parser options, default options for
2685 * the user loaded if null given
2686 * @return string article contents with altered wikitext markup (signatures
2687 * converted, {{subst:}}, templates, etc.)
2689 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2690 global $wgParser, $wgUser;
2692 wfDeprecated( __METHOD__
, '1.19' );
2694 $user = is_null( $user ) ?
$wgUser : $user;
2696 if ( $popts === null ) {
2697 $popts = ParserOptions
::newFromUser( $user );
2700 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2704 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2706 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2709 public function isBigDeletion() {
2710 wfDeprecated( __METHOD__
, '1.19' );
2711 return $this->mTitle
->isBigDeletion();
2715 * Get the approximate revision count of this page.
2717 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2720 public function estimateRevisionCount() {
2721 wfDeprecated( __METHOD__
, '1.19' );
2722 return $this->mTitle
->estimateRevisionCount();
2726 * Update the article's restriction field, and leave a log entry.
2728 * @deprecated since 1.19
2729 * @param $limit Array: set of restriction keys
2730 * @param $reason String
2731 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2732 * @param $expiry Array: per restriction type expiration
2733 * @param $user User The user updating the restrictions
2734 * @return bool true on success
2736 public function updateRestrictions(
2737 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2741 $user = is_null( $user ) ?
$wgUser : $user;
2743 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2747 * @deprecated since 1.18
2749 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2750 wfDeprecated( __METHOD__
, '1.18' );
2752 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2756 * @deprecated since 1.18
2758 public function viewUpdates() {
2759 wfDeprecated( __METHOD__
, '1.18' );
2761 return $this->doViewUpdates( $wgUser );
2765 * @deprecated since 1.18
2767 public function useParserCache( $oldid ) {
2768 wfDeprecated( __METHOD__
, '1.18' );
2770 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2774 class PoolWorkArticleView
extends PoolCounterWork
{
2792 * @var ParserOptions
2794 private $parserOptions;
2802 * @var ParserOutput|false
2804 private $parserOutput = false;
2809 private $isDirty = false;
2814 private $error = false;
2820 * @param $revid Integer: ID of the revision being parsed
2821 * @param $useParserCache Boolean: whether to use the parser cache
2822 * @param $parserOptions parserOptions to use for the parse operation
2823 * @param $text String: text to parse or null to load it
2825 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2826 $this->page
= $page;
2827 $this->revid
= $revid;
2828 $this->cacheable
= $useParserCache;
2829 $this->parserOptions
= $parserOptions;
2830 $this->text
= $text;
2831 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2832 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2836 * Get the ParserOutput from this object, or false in case of failure
2838 * @return ParserOutput
2840 public function getParserOutput() {
2841 return $this->parserOutput
;
2845 * Get whether the ParserOutput is a dirty one (i.e. expired)
2849 public function getIsDirty() {
2850 return $this->isDirty
;
2854 * Get a Status object in case of error or false otherwise
2856 * @return Status|false
2858 public function getError() {
2859 return $this->error
;
2866 global $wgParser, $wgUseFileCache;
2868 $isCurrent = $this->revid
=== $this->page
->getLatest();
2870 if ( $this->text
!== null ) {
2871 $text = $this->text
;
2872 } elseif ( $isCurrent ) {
2873 $text = $this->page
->getRawText();
2875 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2876 if ( $rev === null ) {
2879 $text = $rev->getText();
2883 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2884 $this->parserOptions
, true, true, $this->revid
);
2889 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2890 $this->page
->getTitle()->getPrefixedDBkey() ) );
2893 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2894 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2897 // Make sure file cache is not used on uncacheable content.
2898 // Output that has magic words in it can still use the parser cache
2899 // (if enabled), though it will generally expire sooner.
2900 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2901 $wgUseFileCache = false;
2905 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2914 function getCachedWork() {
2915 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2917 if ( $this->parserOutput
=== false ) {
2918 wfDebug( __METHOD__
. ": parser cache miss\n" );
2921 wfDebug( __METHOD__
. ": parser cache hit\n" );
2929 function fallback() {
2930 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2932 if ( $this->parserOutput
=== false ) {
2933 wfDebugLog( 'dirty', "dirty missing\n" );
2934 wfDebug( __METHOD__
. ": no dirty cache\n" );
2937 wfDebug( __METHOD__
. ": sending dirty output\n" );
2938 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2939 $this->isDirty
= true;
2945 * @param $status Status
2947 function error( $status ) {
2948 $this->error
= $status;