3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
8 * Class representing a MediaWiki article and history.
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
13 * @internal documentation reviewed 15 Mar 2010
15 class WikiPage
extends Page
{
16 // doDeleteArticleReal() return values. Values less than zero indicate fatal errors,
17 // values greater than zero indicate that there were problems not resulting in page
21 * Delete operation aborted by hook
23 const DELETE_HOOK_ABORTED
= -1;
28 const DELETE_SUCCESS
= 0;
33 const DELETE_NO_PAGE
= 1;
36 * No revisions found to delete
38 const DELETE_NO_REVISIONS
= 2;
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
51 public $mPreparedEdit = false; // !< Array
57 protected $mRedirectTarget = null;
62 protected $mLastRevision = null;
65 * @var string; timestamp of the current revision or empty string if not loaded
67 protected $mTimestamp = '';
72 protected $mTouched = '19700101000000';
77 protected $mCounter = null;
80 * Constructor and clear the article
81 * @param $title Title Reference to a Title object.
83 public function __construct( Title
$title ) {
84 $this->mTitle
= $title;
88 * Create a WikiPage object of the appropriate class for the given title.
91 * @return WikiPage object of the appropriate type
93 public static function factory( Title
$title ) {
94 $ns = $title->getNamespace();
96 if ( $ns == NS_MEDIA
) {
97 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
98 } elseif ( $ns < 0 ) {
99 throw new MWException( "Invalid or virtual namespace $ns given." );
104 $page = new WikiFilePage( $title );
107 $page = new WikiCategoryPage( $title );
110 $page = new WikiPage( $title );
117 * Constructor from a page id
119 * @param $id Int article ID to load
123 public static function newFromID( $id ) {
124 $t = Title
::newFromID( $id );
126 return self
::factory( $t );
132 * Returns overrides for action handlers.
133 * Classes listed here will be used instead of the default one when
134 * (and only when) $wgActions[$action] === true. This allows subclasses
135 * to override the default behavior.
137 * @todo: move this UI stuff somewhere else
141 public function getActionOverrides() {
146 * Get the title object of the article
147 * @return Title object of this page
149 public function getTitle() {
150 return $this->mTitle
;
156 public function clear() {
157 $this->mDataLoaded
= false;
159 $this->mCounter
= null;
160 $this->mRedirectTarget
= null; # Title object if set
161 $this->mLastRevision
= null; # Latest revision
162 $this->mTouched
= '19700101000000';
163 $this->mTimestamp
= '';
164 $this->mIsRedirect
= false;
165 $this->mLatest
= false;
166 $this->mPreparedEdit
= false;
170 * Return the list of revision fields that should be selected to create
175 public static function selectFields() {
192 * Fetch a page record with the given conditions
193 * @param $dbr DatabaseBase object
194 * @param $conditions Array
195 * @return mixed Database result resource, or false on failure
197 protected function pageData( $dbr, $conditions ) {
198 $fields = self
::selectFields();
200 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
202 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
204 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
210 * Fetch a page record matching the Title object's namespace and title
211 * using a sanitized title string
213 * @param $dbr DatabaseBase object
214 * @param $title Title object
215 * @return mixed Database result resource, or false on failure
217 public function pageDataFromTitle( $dbr, $title ) {
218 return $this->pageData( $dbr, array(
219 'page_namespace' => $title->getNamespace(),
220 'page_title' => $title->getDBkey() ) );
224 * Fetch a page record matching the requested ID
226 * @param $dbr DatabaseBase
228 * @return mixed Database result resource, or false on failure
230 public function pageDataFromId( $dbr, $id ) {
231 return $this->pageData( $dbr, array( 'page_id' => $id ) );
235 * Set the general counter, title etc data loaded from
238 * @param $data Object|String One of the following:
239 * A DB query result object or...
240 * "fromdb" to get from a slave DB or...
241 * "fromdbmaster" to get from the master DB
244 public function loadPageData( $data = 'fromdb' ) {
245 if ( $data === 'fromdbmaster' ) {
246 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
247 } elseif ( $data === 'fromdb' ) { // slave
248 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
249 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
250 # Note that DB also stores the master position in the session and checks it.
251 $touched = $this->getCachedLastEditTime();
252 if ( $touched ) { // key set
253 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
254 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
259 $lc = LinkCache
::singleton();
262 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
264 $this->mTitle
->loadFromRow( $data );
266 # Old-fashioned restrictions
267 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
269 $this->mCounter
= intval( $data->page_counter
);
270 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
271 $this->mIsRedirect
= intval( $data->page_is_redirect
);
272 $this->mLatest
= intval( $data->page_latest
);
274 $lc->addBadLinkObj( $this->mTitle
);
276 $this->mTitle
->loadFromRow( false );
279 $this->mDataLoaded
= true;
283 * @return int Page ID
285 public function getId() {
286 return $this->mTitle
->getArticleID();
290 * @return bool Whether or not the page exists in the database
292 public function exists() {
293 return $this->mTitle
->exists();
297 * Check if this page is something we're going to be showing
298 * some sort of sensible content for. If we return false, page
299 * views (plain action=view) will return an HTTP 404 response,
300 * so spiders and robots can know they're following a bad link.
304 public function hasViewableContent() {
305 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
309 * @return int The view count for the page
311 public function getCount() {
312 if ( !$this->mDataLoaded
) {
313 $this->loadPageData();
316 return $this->mCounter
;
320 * Tests if the article text represents a redirect
322 * @param $text mixed string containing article contents, or boolean
325 public function isRedirect( $text = false ) {
326 if ( $text === false ) {
327 if ( !$this->mDataLoaded
) {
328 $this->loadPageData();
331 return (bool)$this->mIsRedirect
;
333 return Title
::newFromRedirect( $text ) !== null;
338 * Loads page_touched and returns a value indicating if it should be used
339 * @return boolean true if not a redirect
341 public function checkTouched() {
342 if ( !$this->mDataLoaded
) {
343 $this->loadPageData();
345 return !$this->mIsRedirect
;
349 * Get the page_touched field
350 * @return string containing GMT timestamp
352 public function getTouched() {
353 if ( !$this->mDataLoaded
) {
354 $this->loadPageData();
356 return $this->mTouched
;
360 * Get the page_latest field
361 * @return integer rev_id of current revision
363 public function getLatest() {
364 if ( !$this->mDataLoaded
) {
365 $this->loadPageData();
367 return (int)$this->mLatest
;
371 * Loads everything except the text
372 * This isn't necessary for all uses, so it's only done if needed.
374 protected function loadLastEdit() {
375 if ( $this->mLastRevision
!== null ) {
376 return; // already loaded
379 $latest = $this->getLatest();
381 return; // page doesn't exist or is missing page_latest info
384 $revision = Revision
::newFromPageId( $this->getId(), $latest );
385 if ( $revision ) { // sanity
386 $this->setLastEdit( $revision );
391 * Set the latest revision
393 protected function setLastEdit( Revision
$revision ) {
394 $this->mLastRevision
= $revision;
395 $this->mTimestamp
= $revision->getTimestamp();
399 * Get the latest revision
400 * @return Revision|null
402 public function getRevision() {
403 $this->loadLastEdit();
404 if ( $this->mLastRevision
) {
405 return $this->mLastRevision
;
411 * Get the text of the current revision. No side-effects...
413 * @param $audience Integer: one of:
414 * Revision::FOR_PUBLIC to be displayed to all users
415 * Revision::FOR_THIS_USER to be displayed to $wgUser
416 * Revision::RAW get the text regardless of permissions
417 * @return String|bool The text of the current revision. False on failure
419 public function getText( $audience = Revision
::FOR_PUBLIC
) {
420 $this->loadLastEdit();
421 if ( $this->mLastRevision
) {
422 return $this->mLastRevision
->getText( $audience );
428 * Get the text of the current revision. No side-effects...
430 * @return String|bool The text of the current revision. False on failure
432 public function getRawText() {
433 $this->loadLastEdit();
434 if ( $this->mLastRevision
) {
435 return $this->mLastRevision
->getRawText();
441 * @return string MW timestamp of last article revision
443 public function getTimestamp() {
444 // Check if the field has been filled by WikiPage::setTimestamp()
445 if ( !$this->mTimestamp
) {
446 $this->loadLastEdit();
448 return wfTimestamp( TS_MW
, $this->mTimestamp
);
452 * Set the page timestamp (use only to avoid DB queries)
453 * @param $ts string MW timestamp of last article revision
456 public function setTimestamp( $ts ) {
457 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
461 * @param $audience Integer: one of:
462 * Revision::FOR_PUBLIC to be displayed to all users
463 * Revision::FOR_THIS_USER to be displayed to $wgUser
464 * Revision::RAW get the text regardless of permissions
465 * @return int user ID for the user that made the last article revision
467 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
468 $this->loadLastEdit();
469 if ( $this->mLastRevision
) {
470 return $this->mLastRevision
->getUser( $audience );
477 * @param $audience Integer: one of:
478 * Revision::FOR_PUBLIC to be displayed to all users
479 * Revision::FOR_THIS_USER to be displayed to $wgUser
480 * Revision::RAW get the text regardless of permissions
481 * @return string username of the user that made the last article revision
483 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
484 $this->loadLastEdit();
485 if ( $this->mLastRevision
) {
486 return $this->mLastRevision
->getUserText( $audience );
493 * @param $audience Integer: one of:
494 * Revision::FOR_PUBLIC to be displayed to all users
495 * Revision::FOR_THIS_USER to be displayed to $wgUser
496 * Revision::RAW get the text regardless of permissions
497 * @return string Comment stored for the last article revision
499 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
500 $this->loadLastEdit();
501 if ( $this->mLastRevision
) {
502 return $this->mLastRevision
->getComment( $audience );
509 * Returns true if last revision was marked as "minor edit"
511 * @return boolean Minor edit indicator for the last article revision.
513 public function getMinorEdit() {
514 $this->loadLastEdit();
515 if ( $this->mLastRevision
) {
516 return $this->mLastRevision
->isMinor();
523 * Get the cached timestamp for the last time the page changed.
524 * This is only used to help handle slave lag by comparing to page_touched.
525 * @return string MW timestamp
527 protected function getCachedLastEditTime() {
529 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
530 return $wgMemc->get( $key );
534 * Set the cached timestamp for the last time the page changed.
535 * This is only used to help handle slave lag by comparing to page_touched.
536 * @param $timestamp string
539 public function setCachedLastEditTime( $timestamp ) {
541 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
542 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
546 * Determine whether a page would be suitable for being counted as an
547 * article in the site_stats table based on the title & its content
549 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
550 * if false, the current database state will be used
553 public function isCountable( $editInfo = false ) {
554 global $wgArticleCountMethod;
556 if ( !$this->mTitle
->isContentPage() ) {
560 $text = $editInfo ?
$editInfo->pst
: false;
562 if ( $this->isRedirect( $text ) ) {
566 switch ( $wgArticleCountMethod ) {
570 if ( $text === false ) {
571 $text = $this->getRawText();
573 return strpos( $text, ',' ) !== false;
576 // ParserOutput::getLinks() is a 2D array of page links, so
577 // to be really correct we would need to recurse in the array
578 // but the main array should only have items in it if there are
580 return (bool)count( $editInfo->output
->getLinks() );
582 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
583 array( 'pl_from' => $this->getId() ), __METHOD__
);
589 * If this page is a redirect, get its target
591 * The target will be fetched from the redirect table if possible.
592 * If this page doesn't have an entry there, call insertRedirect()
593 * @return Title|mixed object, or null if this page is not a redirect
595 public function getRedirectTarget() {
596 if ( !$this->mTitle
->isRedirect() ) {
600 if ( $this->mRedirectTarget
!== null ) {
601 return $this->mRedirectTarget
;
604 # Query the redirect table
605 $dbr = wfGetDB( DB_SLAVE
);
606 $row = $dbr->selectRow( 'redirect',
607 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
608 array( 'rd_from' => $this->getId() ),
612 // rd_fragment and rd_interwiki were added later, populate them if empty
613 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
614 return $this->mRedirectTarget
= Title
::makeTitle(
615 $row->rd_namespace
, $row->rd_title
,
616 $row->rd_fragment
, $row->rd_interwiki
);
619 # This page doesn't have an entry in the redirect table
620 return $this->mRedirectTarget
= $this->insertRedirect();
624 * Insert an entry for this page into the redirect table.
626 * Don't call this function directly unless you know what you're doing.
627 * @return Title object or null if not a redirect
629 public function insertRedirect() {
630 // recurse through to only get the final target
631 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
635 $this->insertRedirectEntry( $retval );
640 * Insert or update the redirect table entry for this page to indicate
641 * it redirects to $rt .
642 * @param $rt Title redirect target
644 public function insertRedirectEntry( $rt ) {
645 $dbw = wfGetDB( DB_MASTER
);
646 $dbw->replace( 'redirect', array( 'rd_from' ),
648 'rd_from' => $this->getId(),
649 'rd_namespace' => $rt->getNamespace(),
650 'rd_title' => $rt->getDBkey(),
651 'rd_fragment' => $rt->getFragment(),
652 'rd_interwiki' => $rt->getInterwiki(),
659 * Get the Title object or URL this page redirects to
661 * @return mixed false, Title of in-wiki target, or string with URL
663 public function followRedirect() {
664 return $this->getRedirectURL( $this->getRedirectTarget() );
668 * Get the Title object or URL to use for a redirect. We use Title
669 * objects for same-wiki, non-special redirects and URLs for everything
671 * @param $rt Title Redirect target
672 * @return mixed false, Title object of local target, or string with URL
674 public function getRedirectURL( $rt ) {
679 if ( $rt->isExternal() ) {
680 if ( $rt->isLocal() ) {
681 // Offsite wikis need an HTTP redirect.
683 // This can be hard to reverse and may produce loops,
684 // so they may be disabled in the site configuration.
685 $source = $this->mTitle
->getFullURL( 'redirect=no' );
686 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
688 // External pages pages without "local" bit set are not valid
694 if ( $rt->isSpecialPage() ) {
695 // Gotta handle redirects to special pages differently:
696 // Fill the HTTP response "Location" header and ignore
697 // the rest of the page we're on.
699 // Some pages are not valid targets
700 if ( $rt->isValidRedirectTarget() ) {
701 return $rt->getFullURL();
711 * Get a list of users who have edited this article, not including the user who made
712 * the most recent revision, which you can get from $article->getUser() if you want it
713 * @return UserArrayFromResult
715 public function getContributors() {
716 # @todo FIXME: This is expensive; cache this info somewhere.
718 $dbr = wfGetDB( DB_SLAVE
);
720 if ( $dbr->implicitGroupby() ) {
721 $realNameField = 'user_real_name';
723 $realNameField = 'MIN(user_real_name) AS user_real_name';
726 $tables = array( 'revision', 'user' );
729 'rev_user as user_id',
730 'rev_user_text AS user_name',
732 'MAX(rev_timestamp) AS timestamp',
735 $conds = array( 'rev_page' => $this->getId() );
737 // The user who made the top revision gets credited as "this page was last edited by
738 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
739 $user = $this->getUser();
741 $conds[] = "rev_user != $user";
743 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
746 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
749 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
753 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
754 'ORDER BY' => 'timestamp DESC',
757 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
758 return new UserArrayFromResult( $res );
762 * Get the last N authors
763 * @param $num Integer: number of revisions to get
764 * @param $revLatest String: the latest rev_id, selected from the master (optional)
765 * @return array Array of authors, duplicates not removed
767 public function getLastNAuthors( $num, $revLatest = 0 ) {
768 wfProfileIn( __METHOD__
);
769 // First try the slave
770 // If that doesn't have the latest revision, try the master
772 $db = wfGetDB( DB_SLAVE
);
775 $res = $db->select( array( 'page', 'revision' ),
776 array( 'rev_id', 'rev_user_text' ),
778 'page_namespace' => $this->mTitle
->getNamespace(),
779 'page_title' => $this->mTitle
->getDBkey(),
783 'ORDER BY' => 'rev_timestamp DESC',
789 wfProfileOut( __METHOD__
);
793 $row = $db->fetchObject( $res );
795 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
796 $db = wfGetDB( DB_MASTER
);
801 } while ( $continue );
803 $authors = array( $row->rev_user_text
);
805 foreach ( $res as $row ) {
806 $authors[] = $row->rev_user_text
;
809 wfProfileOut( __METHOD__
);
814 * Should the parser cache be used?
816 * @param $parserOptions ParserOptions to check
820 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
821 global $wgEnableParserCache;
823 return $wgEnableParserCache
824 && $parserOptions->getStubThreshold() == 0
825 && $this->mTitle
->exists()
826 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
827 && $this->mTitle
->isWikitextPage();
831 * Get a ParserOutput for the given ParserOptions and revision ID.
832 * The parser cache will be used if possible.
835 * @param $parserOptions ParserOptions to use for the parse operation
836 * @param $oldid Revision ID to get the text from, passing null or 0 will
837 * get the current revision (default value)
838 * @return ParserOutput or false if the revision was not found
840 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
841 wfProfileIn( __METHOD__
);
843 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
844 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
845 if ( $parserOptions->getStubThreshold() ) {
846 wfIncrStats( 'pcache_miss_stub' );
849 if ( $useParserCache ) {
850 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
851 if ( $parserOutput !== false ) {
852 wfProfileOut( __METHOD__
);
853 return $parserOutput;
857 if ( $oldid === null ||
$oldid === 0 ) {
858 $oldid = $this->getLatest();
861 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
864 wfProfileOut( __METHOD__
);
866 return $pool->getParserOutput();
870 * Do standard deferred updates after page view
871 * @param $user User The relevant user
873 public function doViewUpdates( User
$user ) {
874 global $wgDisableCounters;
875 if ( wfReadOnly() ) {
879 # Don't update page view counters on views from bot users (bug 14044)
880 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
881 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
882 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
885 # Update newtalk / watchlist notification status
886 $user->clearNotification( $this->mTitle
);
890 * Perform the actions of a page purging
893 public function doPurge() {
896 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
900 // Invalidate the cache
901 $this->mTitle
->invalidateCache();
905 // Commit the transaction before the purge is sent
906 $dbw = wfGetDB( DB_MASTER
);
910 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
914 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
915 if ( $this->mTitle
->exists() ) {
916 $text = $this->getRawText();
921 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
927 * Insert a new empty page record for this article.
928 * This *must* be followed up by creating a revision
929 * and running $this->updateRevisionOn( ... );
930 * or else the record will be left in a funky state.
931 * Best if all done inside a transaction.
933 * @param $dbw DatabaseBase
934 * @return int The newly created page_id key, or false if the title already existed
936 public function insertOn( $dbw ) {
937 wfProfileIn( __METHOD__
);
939 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
940 $dbw->insert( 'page', array(
941 'page_id' => $page_id,
942 'page_namespace' => $this->mTitle
->getNamespace(),
943 'page_title' => $this->mTitle
->getDBkey(),
945 'page_restrictions' => '',
946 'page_is_redirect' => 0, # Will set this shortly...
948 'page_random' => wfRandom(),
949 'page_touched' => $dbw->timestamp(),
950 'page_latest' => 0, # Fill this in shortly...
951 'page_len' => 0, # Fill this in shortly...
952 ), __METHOD__
, 'IGNORE' );
954 $affected = $dbw->affectedRows();
957 $newid = $dbw->insertId();
958 $this->mTitle
->resetArticleID( $newid );
960 wfProfileOut( __METHOD__
);
962 return $affected ?
$newid : false;
966 * Update the page record to point to a newly saved revision.
968 * @param $dbw DatabaseBase: object
969 * @param $revision Revision: For ID number, and text used to set
970 * length and redirect status fields
971 * @param $lastRevision Integer: if given, will not overwrite the page field
972 * when different from the currently set value.
973 * Giving 0 indicates the new page flag should be set
975 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
976 * removing rows in redirect table.
977 * @return bool true on success, false on failure
980 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
981 wfProfileIn( __METHOD__
);
983 $text = $revision->getText();
984 $len = strlen( $text );
985 $rt = Title
::newFromRedirectRecurse( $text );
987 $conditions = array( 'page_id' => $this->getId() );
989 if ( !is_null( $lastRevision ) ) {
990 # An extra check against threads stepping on each other
991 $conditions['page_latest'] = $lastRevision;
994 $now = wfTimestampNow();
995 $dbw->update( 'page',
997 'page_latest' => $revision->getId(),
998 'page_touched' => $dbw->timestamp( $now ),
999 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1000 'page_is_redirect' => $rt !== null ?
1 : 0,
1006 $result = $dbw->affectedRows() != 0;
1008 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1009 $this->setLastEdit( $revision );
1010 $this->setCachedLastEditTime( $now );
1011 $this->mLatest
= $revision->getId();
1012 $this->mIsRedirect
= (bool)$rt;
1013 # Update the LinkCache.
1014 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1017 wfProfileOut( __METHOD__
);
1022 * Add row to the redirect table if this is a redirect, remove otherwise.
1024 * @param $dbw DatabaseBase
1025 * @param $redirectTitle Title object pointing to the redirect target,
1026 * or NULL if this is not a redirect
1027 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1028 * removing rows in redirect table.
1029 * @return bool true on success, false on failure
1032 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1033 // Always update redirects (target link might have changed)
1034 // Update/Insert if we don't know if the last revision was a redirect or not
1035 // Delete if changing from redirect to non-redirect
1036 $isRedirect = !is_null( $redirectTitle );
1038 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1042 wfProfileIn( __METHOD__
);
1043 if ( $isRedirect ) {
1044 $this->insertRedirectEntry( $redirectTitle );
1046 // This is not a redirect, remove row from redirect table
1047 $where = array( 'rd_from' => $this->getId() );
1048 $dbw->delete( 'redirect', $where, __METHOD__
);
1051 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1052 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1054 wfProfileOut( __METHOD__
);
1056 return ( $dbw->affectedRows() != 0 );
1060 * If the given revision is newer than the currently set page_latest,
1061 * update the page record. Otherwise, do nothing.
1063 * @param $dbw DatabaseBase object
1064 * @param $revision Revision object
1067 public function updateIfNewerOn( $dbw, $revision ) {
1068 wfProfileIn( __METHOD__
);
1070 $row = $dbw->selectRow(
1071 array( 'revision', 'page' ),
1072 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1074 'page_id' => $this->getId(),
1075 'page_latest=rev_id' ),
1079 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1080 wfProfileOut( __METHOD__
);
1083 $prev = $row->rev_id
;
1084 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1086 # No or missing previous revision; mark the page as new
1088 $lastRevIsRedirect = null;
1091 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1093 wfProfileOut( __METHOD__
);
1098 * Get the text that needs to be saved in order to undo all revisions
1099 * between $undo and $undoafter. Revisions must belong to the same page,
1100 * must exist and must not be deleted
1101 * @param $undo Revision
1102 * @param $undoafter Revision Must be an earlier revision than $undo
1103 * @return mixed string on success, false on failure
1105 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1106 $cur_text = $this->getRawText();
1107 if ( $cur_text === false ) {
1108 return false; // no page
1110 $undo_text = $undo->getText();
1111 $undoafter_text = $undoafter->getText();
1113 if ( $cur_text == $undo_text ) {
1114 # No use doing a merge if it's just a straight revert.
1115 return $undoafter_text;
1120 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1124 return $undone_text;
1128 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1129 * @param $text String: new text of the section
1130 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1131 * @param $edittime String: revision timestamp or null to use the current revision
1132 * @return string Complete article text, or null if error
1134 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1135 wfProfileIn( __METHOD__
);
1137 if ( strval( $section ) == '' ) {
1138 // Whole-page edit; let the whole text through
1140 // Bug 30711: always use current version when adding a new section
1141 if ( is_null( $edittime ) ||
$section == 'new' ) {
1142 $oldtext = $this->getRawText();
1143 if ( $oldtext === false ) {
1144 wfDebug( __METHOD__
. ": no page text\n" );
1145 wfProfileOut( __METHOD__
);
1149 $dbw = wfGetDB( DB_MASTER
);
1150 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1153 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1154 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1155 wfProfileOut( __METHOD__
);
1159 $oldtext = $rev->getText();
1162 if ( $section == 'new' ) {
1163 # Inserting a new section
1164 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1165 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1166 $text = strlen( trim( $oldtext ) ) > 0
1167 ?
"{$oldtext}\n\n{$subject}{$text}"
1168 : "{$subject}{$text}";
1171 # Replacing an existing section; roll out the big guns
1174 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1178 wfProfileOut( __METHOD__
);
1183 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1185 * @return Int updated $flags
1187 function checkFlags( $flags ) {
1188 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1189 if ( $this->mTitle
->getArticleID() ) {
1190 $flags |
= EDIT_UPDATE
;
1200 * Change an existing article or create a new article. Updates RC and all necessary caches,
1201 * optionally via the deferred update array.
1203 * @param $text String: new text
1204 * @param $summary String: edit summary
1205 * @param $flags Integer bitfield:
1207 * Article is known or assumed to be non-existent, create a new one
1209 * Article is known or assumed to be pre-existing, update it
1211 * Mark this edit minor, if the user is allowed to do so
1213 * Do not log the change in recentchanges
1215 * Mark the edit a "bot" edit regardless of user rights
1216 * EDIT_DEFER_UPDATES
1217 * Defer some of the updates until the end of index.php
1219 * Fill in blank summaries with generated text where possible
1221 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1222 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1223 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1224 * edit-already-exists error will be returned. These two conditions are also possible with
1225 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1227 * @param $baseRevId int the revision ID this edit was based off, if any
1228 * @param $user User the user doing the edit
1230 * @return Status object. Possible errors:
1231 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1232 * edit-gone-missing: In update mode, but the article didn't exist
1233 * edit-conflict: In update mode, the article changed unexpectedly
1234 * edit-no-change: Warning that the text was the same as before
1235 * edit-already-exists: In creation mode, but the article already exists
1237 * Extensions may define additional errors.
1239 * $return->value will contain an associative array with members as follows:
1240 * new: Boolean indicating if the function attempted to create a new article
1241 * revision: The revision object for the inserted revision, or null
1243 * Compatibility note: this function previously returned a boolean value indicating success/failure
1245 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1246 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1248 # Low-level sanity check
1249 if ( $this->mTitle
->getText() === '' ) {
1250 throw new MWException( 'Something is trying to edit an article with an empty title' );
1253 wfProfileIn( __METHOD__
);
1255 $user = is_null( $user ) ?
$wgUser : $user;
1256 $status = Status
::newGood( array() );
1258 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1259 $this->loadPageData( 'fromdbmaster' );
1261 $flags = $this->checkFlags( $flags );
1263 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1264 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1266 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1268 if ( $status->isOK() ) {
1269 $status->fatal( 'edit-hook-aborted' );
1272 wfProfileOut( __METHOD__
);
1276 # Silently ignore EDIT_MINOR if not allowed
1277 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1278 $bot = $flags & EDIT_FORCE_BOT
;
1280 $oldtext = $this->getRawText(); // current revision
1281 $oldsize = strlen( $oldtext );
1282 $oldid = $this->getLatest();
1283 $oldIsRedirect = $this->isRedirect();
1284 $oldcountable = $this->isCountable();
1286 # Provide autosummaries if one is not provided and autosummaries are enabled.
1287 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1288 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1291 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1292 $text = $editInfo->pst
;
1293 $newsize = strlen( $text );
1295 $dbw = wfGetDB( DB_MASTER
);
1296 $now = wfTimestampNow();
1297 $this->mTimestamp
= $now;
1299 if ( $flags & EDIT_UPDATE
) {
1300 # Update article, but only if changed.
1301 $status->value
['new'] = false;
1304 # Article gone missing
1305 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1306 $status->fatal( 'edit-gone-missing' );
1308 wfProfileOut( __METHOD__
);
1312 # Make sure the revision is either completely inserted or not inserted at all
1313 if ( !$wgDBtransactions ) {
1314 $userAbort = ignore_user_abort( true );
1317 $revision = new Revision( array(
1318 'page' => $this->getId(),
1319 'comment' => $summary,
1320 'minor_edit' => $isminor,
1322 'parent_id' => $oldid,
1323 'user' => $user->getId(),
1324 'user_text' => $user->getName(),
1328 $changed = ( strcmp( $text, $oldtext ) != 0 );
1332 $revisionId = $revision->insertOn( $dbw );
1336 # Note that we use $this->mLatest instead of fetching a value from the master DB
1337 # during the course of this function. This makes sure that EditPage can detect
1338 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1339 # before this function is called. A previous function used a separate query, this
1340 # creates a window where concurrent edits can cause an ignored edit conflict.
1341 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1344 /* Belated edit conflict! Run away!! */
1345 $status->fatal( 'edit-conflict' );
1347 # Delete the invalid revision if the DB is not transactional
1348 if ( !$wgDBtransactions ) {
1349 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1355 global $wgUseRCPatrol;
1356 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1357 # Update recentchanges
1358 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1359 # Mark as patrolled if the user can do so
1360 $patrolled = $wgUseRCPatrol && !count(
1361 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1362 # Add RC row to the DB
1363 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1364 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1365 $revisionId, $patrolled
1368 # Log auto-patrolled edits
1370 PatrolLog
::record( $rc, true );
1373 $user->incEditCount();
1377 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1378 // related variables correctly
1379 $revision->setId( $this->getLatest() );
1382 if ( !$wgDBtransactions ) {
1383 ignore_user_abort( $userAbort );
1386 // Now that ignore_user_abort is restored, we can respond to fatal errors
1387 if ( !$status->isOK() ) {
1388 wfProfileOut( __METHOD__
);
1392 # Update links tables, site stats, etc.
1393 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1394 'oldcountable' => $oldcountable ) );
1397 $status->warning( 'edit-no-change' );
1399 // Update page_touched, this is usually implicit in the page update
1400 // Other cache updates are done in onArticleEdit()
1401 $this->mTitle
->invalidateCache();
1404 # Create new article
1405 $status->value
['new'] = true;
1409 # Add the page record; stake our claim on this title!
1410 # This will return false if the article already exists
1411 $newid = $this->insertOn( $dbw );
1413 if ( $newid === false ) {
1415 $status->fatal( 'edit-already-exists' );
1417 wfProfileOut( __METHOD__
);
1421 # Save the revision text...
1422 $revision = new Revision( array(
1424 'comment' => $summary,
1425 'minor_edit' => $isminor,
1427 'user' => $user->getId(),
1428 'user_text' => $user->getName(),
1431 $revisionId = $revision->insertOn( $dbw );
1433 # Update the page record with revision data
1434 $this->updateRevisionOn( $dbw, $revision, 0 );
1436 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1438 # Update recentchanges
1439 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1440 global $wgUseRCPatrol, $wgUseNPPatrol;
1442 # Mark as patrolled if the user can do so
1443 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1444 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1445 # Add RC row to the DB
1446 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1447 '', strlen( $text ), $revisionId, $patrolled );
1449 # Log auto-patrolled edits
1451 PatrolLog
::record( $rc, true );
1454 $user->incEditCount();
1457 # Update links, etc.
1458 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1460 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1461 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1464 # Do updates right now unless deferral was requested
1465 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1466 DeferredUpdates
::doUpdates();
1469 // Return the new revision (or null) to the caller
1470 $status->value
['revision'] = $revision;
1472 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1473 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1475 # Promote user to any groups they meet the criteria for
1476 $user->addAutopromoteOnceGroups( 'onEdit' );
1478 wfProfileOut( __METHOD__
);
1483 * Get parser options suitable for rendering the primary article wikitext
1484 * @param User|string $user User object or 'canonical'
1485 * @return ParserOptions
1487 public function makeParserOptions( $user ) {
1489 if ( $user instanceof User
) { // settings per user (even anons)
1490 $options = ParserOptions
::newFromUser( $user );
1491 } else { // canonical settings
1492 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1494 $options->enableLimitReport(); // show inclusion/loop reports
1495 $options->setTidy( true ); // fix bad HTML
1500 * Prepare text which is about to be saved.
1501 * Returns a stdclass with source, pst and output members
1502 * @return bool|object
1504 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1505 global $wgParser, $wgContLang, $wgUser;
1506 $user = is_null( $user ) ?
$wgUser : $user;
1507 // @TODO fixme: check $user->getId() here???
1508 if ( $this->mPreparedEdit
1509 && $this->mPreparedEdit
->newText
== $text
1510 && $this->mPreparedEdit
->revid
== $revid
1513 return $this->mPreparedEdit
;
1516 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1517 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1519 $edit = (object)array();
1520 $edit->revid
= $revid;
1521 $edit->newText
= $text;
1522 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1523 $edit->popts
= $this->makeParserOptions( 'canonical' );
1524 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1525 $edit->oldText
= $this->getRawText();
1527 $this->mPreparedEdit
= $edit;
1533 * Do standard deferred updates after page edit.
1534 * Update links tables, site stats, search index and message cache.
1535 * Purges pages that include this page if the text was changed here.
1536 * Every 100th edit, prune the recent changes table.
1539 * @param $revision Revision object
1540 * @param $user User object that did the revision
1541 * @param $options Array of options, following indexes are used:
1542 * - changed: boolean, whether the revision changed the content (default true)
1543 * - created: boolean, whether the revision created the page (default false)
1544 * - oldcountable: boolean or null (default null):
1545 * - boolean: whether the page was counted as an article before that
1546 * revision, only used in changed is true and created is false
1547 * - null: don't change the article count
1549 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1550 global $wgEnableParserCache;
1552 wfProfileIn( __METHOD__
);
1554 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1555 $text = $revision->getText();
1558 # Be careful not to double-PST: $text is usually already PST-ed once
1559 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1560 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1561 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1563 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1564 $editInfo = $this->mPreparedEdit
;
1567 # Save it to the parser cache
1568 if ( $wgEnableParserCache ) {
1569 $parserCache = ParserCache
::singleton();
1570 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1573 # Update the links tables
1574 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1577 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1579 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1580 if ( 0 == mt_rand( 0, 99 ) ) {
1581 // Flush old entries from the `recentchanges` table; we do this on
1582 // random requests so as to avoid an increase in writes for no good reason
1585 $dbw = wfGetDB( DB_MASTER
);
1586 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1589 array( "rc_timestamp < '$cutoff'" ),
1595 if ( !$this->mTitle
->exists() ) {
1596 wfProfileOut( __METHOD__
);
1600 $id = $this->getId();
1601 $title = $this->mTitle
->getPrefixedDBkey();
1602 $shortTitle = $this->mTitle
->getDBkey();
1604 if ( !$options['changed'] ) {
1607 } elseif ( $options['created'] ) {
1608 $good = (int)$this->isCountable( $editInfo );
1610 } elseif ( $options['oldcountable'] !== null ) {
1611 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1618 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1619 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1621 # If this is another user's talk page, update newtalk.
1622 # Don't do this if $options['changed'] = false (null-edits) nor if
1623 # it's a minor edit and the user doesn't want notifications for those.
1624 if ( $options['changed']
1625 && $this->mTitle
->getNamespace() == NS_USER_TALK
1626 && $shortTitle != $user->getTitleKey()
1627 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1629 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1630 $other = User
::newFromName( $shortTitle, false );
1632 wfDebug( __METHOD__
. ": invalid username\n" );
1633 } elseif ( User
::isIP( $shortTitle ) ) {
1634 // An anonymous user
1635 $other->setNewtalk( true );
1636 } elseif ( $other->isLoggedIn() ) {
1637 $other->setNewtalk( true );
1639 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1644 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1645 MessageCache
::singleton()->replace( $shortTitle, $text );
1648 if( $options['created'] ) {
1649 self
::onArticleCreate( $this->mTitle
);
1651 self
::onArticleEdit( $this->mTitle
);
1654 wfProfileOut( __METHOD__
);
1658 * Edit an article without doing all that other stuff
1659 * The article must already exist; link tables etc
1660 * are not updated, caches are not flushed.
1662 * @param $text String: text submitted
1663 * @param $user User The relevant user
1664 * @param $comment String: comment submitted
1665 * @param $minor Boolean: whereas it's a minor modification
1667 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1668 wfProfileIn( __METHOD__
);
1670 $dbw = wfGetDB( DB_MASTER
);
1671 $revision = new Revision( array(
1672 'page' => $this->getId(),
1674 'comment' => $comment,
1675 'minor_edit' => $minor ?
1 : 0,
1677 $revision->insertOn( $dbw );
1678 $this->updateRevisionOn( $dbw, $revision );
1680 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1682 wfProfileOut( __METHOD__
);
1686 * Update the article's restriction field, and leave a log entry.
1687 * This works for protection both existing and non-existing pages.
1689 * @param $limit Array: set of restriction keys
1690 * @param $reason String
1691 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1692 * @param $expiry Array: per restriction type expiration
1693 * @param $user User The user updating the restrictions
1694 * @return bool true on success
1696 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1699 if ( wfReadOnly() ) {
1700 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1703 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1705 $id = $this->mTitle
->getArticleID();
1711 // Take this opportunity to purge out expired restrictions
1712 Title
::purgeExpiredRestrictions();
1714 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1715 # we expect a single selection, but the schema allows otherwise.
1716 $isProtected = false;
1720 $dbw = wfGetDB( DB_MASTER
);
1722 foreach ( $restrictionTypes as $action ) {
1723 if ( !isset( $expiry[$action] ) ) {
1724 $expiry[$action] = $dbw->getInfinity();
1726 if ( !isset( $limit[$action] ) ) {
1727 $limit[$action] = '';
1728 } elseif ( $limit[$action] != '' ) {
1732 # Get current restrictions on $action
1733 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1734 if ( $current != '' ) {
1735 $isProtected = true;
1738 if ( $limit[$action] != $current ) {
1740 } elseif ( $limit[$action] != '' ) {
1741 # Only check expiry change if the action is actually being
1742 # protected, since expiry does nothing on an not-protected
1744 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1750 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1754 # If nothing's changed, do nothing
1756 return Status
::newGood();
1759 if ( !$protect ) { # No protection at all means unprotection
1760 $revCommentMsg = 'unprotectedarticle';
1761 $logAction = 'unprotect';
1762 } elseif ( $isProtected ) {
1763 $revCommentMsg = 'modifiedarticleprotection';
1764 $logAction = 'modify';
1766 $revCommentMsg = 'protectedarticle';
1767 $logAction = 'protect';
1770 $encodedExpiry = array();
1771 $protectDescription = '';
1772 foreach ( $limit as $action => $restrictions ) {
1773 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1774 if ( $restrictions != '' ) {
1775 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1776 if ( $encodedExpiry[$action] != 'infinity' ) {
1777 $protectDescription .= wfMsgForContent( 'protect-expiring',
1778 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1779 $wgContLang->date( $expiry[$action], false, false ) ,
1780 $wgContLang->time( $expiry[$action], false, false ) );
1782 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1785 $protectDescription .= ') ';
1788 $protectDescription = trim( $protectDescription );
1790 if ( $id ) { # Protection of existing page
1791 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1792 return Status
::newGood();
1795 # Only restrictions with the 'protect' right can cascade...
1796 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1797 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1799 # The schema allows multiple restrictions
1800 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1804 # Update restrictions table
1805 foreach ( $limit as $action => $restrictions ) {
1806 if ( $restrictions != '' ) {
1807 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1808 array( 'pr_page' => $id,
1809 'pr_type' => $action,
1810 'pr_level' => $restrictions,
1811 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1812 'pr_expiry' => $encodedExpiry[$action]
1817 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1818 'pr_type' => $action ), __METHOD__
);
1822 # Prepare a null revision to be added to the history
1823 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1825 $editComment .= ": $reason";
1827 if ( $protectDescription ) {
1828 $editComment .= " ($protectDescription)";
1831 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1834 # Insert a null revision
1835 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1836 $nullRevId = $nullRevision->insertOn( $dbw );
1838 $latest = $this->getLatest();
1839 # Update page record
1840 $dbw->update( 'page',
1842 'page_touched' => $dbw->timestamp(),
1843 'page_restrictions' => '',
1844 'page_latest' => $nullRevId
1845 ), array( /* WHERE */
1850 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1851 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1852 } else { # Protection of non-existing page (also known as "title protection")
1853 # Cascade protection is meaningless in this case
1856 if ( $limit['create'] != '' ) {
1857 $dbw->replace( 'protected_titles',
1858 array( array( 'pt_namespace', 'pt_title' ) ),
1860 'pt_namespace' => $this->mTitle
->getNamespace(),
1861 'pt_title' => $this->mTitle
->getDBkey(),
1862 'pt_create_perm' => $limit['create'],
1863 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1864 'pt_expiry' => $encodedExpiry['create'],
1865 'pt_user' => $user->getId(),
1866 'pt_reason' => $reason,
1870 $dbw->delete( 'protected_titles',
1872 'pt_namespace' => $this->mTitle
->getNamespace(),
1873 'pt_title' => $this->mTitle
->getDBkey()
1879 $this->mTitle
->flushRestrictions();
1881 if ( $logAction == 'unprotect' ) {
1882 $logParams = array();
1884 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1887 # Update the protection log
1888 $log = new LogPage( 'protect' );
1889 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1891 return Status
::newGood();
1895 * Take an array of page restrictions and flatten it to a string
1896 * suitable for insertion into the page_restrictions field.
1897 * @param $limit Array
1900 protected static function flattenRestrictions( $limit ) {
1901 if ( !is_array( $limit ) ) {
1902 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1908 foreach ( $limit as $action => $restrictions ) {
1909 if ( $restrictions != '' ) {
1910 $bits[] = "$action=$restrictions";
1914 return implode( ':', $bits );
1918 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
1919 * Deletes the article with database consistency, writes logs, purges caches
1921 * @param $reason string delete reason for deletion log
1922 * @param $suppress int bitfield
1923 * Revision::DELETED_TEXT
1924 * Revision::DELETED_COMMENT
1925 * Revision::DELETED_USER
1926 * Revision::DELETED_RESTRICTED
1927 * @param $id int article ID
1928 * @param $commit boolean defaults to true, triggers transaction end
1929 * @param &$error Array of errors to append to
1930 * @param $user User The deleting user
1931 * @return boolean true if successful
1933 public function doDeleteArticle(
1934 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1936 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
1937 == WikiPage
::DELETE_SUCCESS
;
1941 * Back-end article deletion
1942 * Deletes the article with database consistency, writes logs, purges caches
1944 * @param $reason string delete reason for deletion log
1945 * @param $suppress int bitfield
1946 * Revision::DELETED_TEXT
1947 * Revision::DELETED_COMMENT
1948 * Revision::DELETED_USER
1949 * Revision::DELETED_RESTRICTED
1950 * @param $id int article ID
1951 * @param $commit boolean defaults to true, triggers transaction end
1952 * @param &$error Array of errors to append to
1953 * @param $user User The deleting user
1954 * @return int: One of WikiPage::DELETE_* constants
1956 public function doDeleteArticleReal(
1957 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1960 $user = is_null( $user ) ?
$wgUser : $user;
1962 wfDebug( __METHOD__
. "\n" );
1964 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1965 return WikiPage
::DELETE_HOOK_ABORTED
;
1967 $dbw = wfGetDB( DB_MASTER
);
1968 $t = $this->mTitle
->getDBkey();
1969 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1971 if ( $t === '' ||
$id == 0 ) {
1972 return WikiPage
::DELETE_NO_PAGE
;
1975 // Bitfields to further suppress the content
1978 // This should be 15...
1979 $bitfield |
= Revision
::DELETED_TEXT
;
1980 $bitfield |
= Revision
::DELETED_COMMENT
;
1981 $bitfield |
= Revision
::DELETED_USER
;
1982 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1984 $bitfield = 'rev_deleted';
1988 // For now, shunt the revision data into the archive table.
1989 // Text is *not* removed from the text table; bulk storage
1990 // is left intact to avoid breaking block-compression or
1991 // immutable storage schemes.
1993 // For backwards compatibility, note that some older archive
1994 // table entries will have ar_text and ar_flags fields still.
1996 // In the future, we may keep revisions and mark them with
1997 // the rev_deleted field, which is reserved for this purpose.
1998 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2000 'ar_namespace' => 'page_namespace',
2001 'ar_title' => 'page_title',
2002 'ar_comment' => 'rev_comment',
2003 'ar_user' => 'rev_user',
2004 'ar_user_text' => 'rev_user_text',
2005 'ar_timestamp' => 'rev_timestamp',
2006 'ar_minor_edit' => 'rev_minor_edit',
2007 'ar_rev_id' => 'rev_id',
2008 'ar_parent_id' => 'rev_parent_id',
2009 'ar_text_id' => 'rev_text_id',
2010 'ar_text' => '\'\'', // Be explicit to appease
2011 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2012 'ar_len' => 'rev_len',
2013 'ar_page_id' => 'page_id',
2014 'ar_deleted' => $bitfield,
2015 'ar_sha1' => 'rev_sha1'
2018 'page_id = rev_page'
2022 # Now that it's safely backed up, delete it
2023 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2024 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2028 return WikiPage
::DELETE_NO_REVISIONS
;
2031 $this->doDeleteUpdates( $id );
2033 # Log the deletion, if the page was suppressed, log it at Oversight instead
2034 $logtype = $suppress ?
'suppress' : 'delete';
2036 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2037 $logEntry->setPerformer( $user );
2038 $logEntry->setTarget( $this->mTitle
);
2039 $logEntry->setComment( $reason );
2040 $logid = $logEntry->insert();
2041 $logEntry->publish( $logid );
2047 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2048 return WikiPage
::DELETE_SUCCESS
;
2052 * Do some database updates after deletion
2054 * @param $id Int: page_id value of the page being deleted
2056 public function doDeleteUpdates( $id ) {
2057 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2059 $dbw = wfGetDB( DB_MASTER
);
2061 # Delete restrictions for it
2062 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2064 # Fix category table counts
2066 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2068 foreach ( $res as $row ) {
2069 $cats [] = $row->cl_to
;
2072 $this->updateCategoryCounts( array(), $cats );
2074 # If using cascading deletes, we can skip some explicit deletes
2075 if ( !$dbw->cascadingDeletes() ) {
2076 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2078 # Delete outgoing links
2079 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2080 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2081 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2082 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2083 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2084 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2085 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2086 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2087 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2090 # If using cleanup triggers, we can skip some manual deletes
2091 if ( !$dbw->cleanupTriggers() ) {
2092 # Clean up recentchanges entries...
2093 $dbw->delete( 'recentchanges',
2094 array( 'rc_type != ' . RC_LOG
,
2095 'rc_namespace' => $this->mTitle
->getNamespace(),
2096 'rc_title' => $this->mTitle
->getDBkey() ),
2098 $dbw->delete( 'recentchanges',
2099 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2104 self
::onArticleDelete( $this->mTitle
);
2106 # Clear the cached article id so the interface doesn't act like we exist
2107 $this->mTitle
->resetArticleID( 0 );
2111 * Roll back the most recent consecutive set of edits to a page
2112 * from the same user; fails if there are no eligible edits to
2113 * roll back to, e.g. user is the sole contributor. This function
2114 * performs permissions checks on $user, then calls commitRollback()
2115 * to do the dirty work
2117 * @todo: seperate the business/permission stuff out from backend code
2119 * @param $fromP String: Name of the user whose edits to rollback.
2120 * @param $summary String: Custom summary. Set to default summary if empty.
2121 * @param $token String: Rollback token.
2122 * @param $bot Boolean: If true, mark all reverted edits as bot.
2124 * @param $resultDetails Array: contains result-specific array of additional values
2125 * 'alreadyrolled' : 'current' (rev)
2126 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2128 * @param $user User The user performing the rollback
2129 * @return array of errors, each error formatted as
2130 * array(messagekey, param1, param2, ...).
2131 * On success, the array is empty. This array can also be passed to
2132 * OutputPage::showPermissionsErrorPage().
2134 public function doRollback(
2135 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2137 $resultDetails = null;
2140 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2141 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2142 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2144 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2145 $errors[] = array( 'sessionfailure' );
2148 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2149 $errors[] = array( 'actionthrottledtext' );
2152 # If there were errors, bail out now
2153 if ( !empty( $errors ) ) {
2157 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2161 * Backend implementation of doRollback(), please refer there for parameter
2162 * and return value documentation
2164 * NOTE: This function does NOT check ANY permissions, it just commits the
2165 * rollback to the DB. Therefore, you should only call this function direct-
2166 * ly if you want to use custom permissions checks. If you don't, use
2167 * doRollback() instead.
2168 * @param $fromP String: Name of the user whose edits to rollback.
2169 * @param $summary String: Custom summary. Set to default summary if empty.
2170 * @param $bot Boolean: If true, mark all reverted edits as bot.
2172 * @param $resultDetails Array: contains result-specific array of additional values
2173 * @param $guser User The user performing the rollback
2176 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2177 global $wgUseRCPatrol, $wgContLang;
2179 $dbw = wfGetDB( DB_MASTER
);
2181 if ( wfReadOnly() ) {
2182 return array( array( 'readonlytext' ) );
2185 # Get the last editor
2186 $current = $this->getRevision();
2187 if ( is_null( $current ) ) {
2188 # Something wrong... no page?
2189 return array( array( 'notanarticle' ) );
2192 $from = str_replace( '_', ' ', $fromP );
2193 # User name given should match up with the top revision.
2194 # If the user was deleted then $from should be empty.
2195 if ( $from != $current->getUserText() ) {
2196 $resultDetails = array( 'current' => $current );
2197 return array( array( 'alreadyrolled',
2198 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2199 htmlspecialchars( $fromP ),
2200 htmlspecialchars( $current->getUserText() )
2204 # Get the last edit not by this guy...
2205 # Note: these may not be public values
2206 $user = intval( $current->getRawUser() );
2207 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2208 $s = $dbw->selectRow( 'revision',
2209 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2210 array( 'rev_page' => $current->getPage(),
2211 "rev_user != {$user} OR rev_user_text != {$user_text}"
2213 array( 'USE INDEX' => 'page_timestamp',
2214 'ORDER BY' => 'rev_timestamp DESC' )
2216 if ( $s === false ) {
2217 # No one else ever edited this page
2218 return array( array( 'cantrollback' ) );
2219 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2220 # Only admins can see this text
2221 return array( array( 'notvisiblerev' ) );
2225 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2226 # Mark all reverted edits as bot
2230 if ( $wgUseRCPatrol ) {
2231 # Mark all reverted edits as patrolled
2232 $set['rc_patrolled'] = 1;
2235 if ( count( $set ) ) {
2236 $dbw->update( 'recentchanges', $set,
2238 'rc_cur_id' => $current->getPage(),
2239 'rc_user_text' => $current->getUserText(),
2240 "rc_timestamp > '{$s->rev_timestamp}'",
2245 # Generate the edit summary if necessary
2246 $target = Revision
::newFromId( $s->rev_id
);
2247 if ( empty( $summary ) ) {
2248 if ( $from == '' ) { // no public user name
2249 $summary = wfMsgForContent( 'revertpage-nouser' );
2251 $summary = wfMsgForContent( 'revertpage' );
2255 # Allow the custom summary to use the same args as the default message
2257 $target->getUserText(), $from, $s->rev_id
,
2258 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2259 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2261 $summary = wfMsgReplaceArgs( $summary, $args );
2264 $flags = EDIT_UPDATE
;
2266 if ( $guser->isAllowed( 'minoredit' ) ) {
2267 $flags |
= EDIT_MINOR
;
2270 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2271 $flags |
= EDIT_FORCE_BOT
;
2274 # Actually store the edit
2275 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2276 if ( !empty( $status->value
['revision'] ) ) {
2277 $revId = $status->value
['revision']->getId();
2282 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2284 $resultDetails = array(
2285 'summary' => $summary,
2286 'current' => $current,
2287 'target' => $target,
2295 * The onArticle*() functions are supposed to be a kind of hooks
2296 * which should be called whenever any of the specified actions
2299 * This is a good place to put code to clear caches, for instance.
2301 * This is called on page move and undelete, as well as edit
2303 * @param $title Title object
2305 public static function onArticleCreate( $title ) {
2306 # Update existence markers on article/talk tabs...
2307 if ( $title->isTalkPage() ) {
2308 $other = $title->getSubjectPage();
2310 $other = $title->getTalkPage();
2313 $other->invalidateCache();
2314 $other->purgeSquid();
2316 $title->touchLinks();
2317 $title->purgeSquid();
2318 $title->deleteTitleProtection();
2322 * Clears caches when article is deleted
2324 * @param $title Title
2326 public static function onArticleDelete( $title ) {
2327 # Update existence markers on article/talk tabs...
2328 if ( $title->isTalkPage() ) {
2329 $other = $title->getSubjectPage();
2331 $other = $title->getTalkPage();
2334 $other->invalidateCache();
2335 $other->purgeSquid();
2337 $title->touchLinks();
2338 $title->purgeSquid();
2341 HTMLFileCache
::clearFileCache( $title );
2344 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2345 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2349 if ( $title->getNamespace() == NS_FILE
) {
2350 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2351 $update->doUpdate();
2355 if ( $title->getNamespace() == NS_USER_TALK
) {
2356 $user = User
::newFromName( $title->getText(), false );
2358 $user->setNewtalk( false );
2363 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2367 * Purge caches on page update etc
2369 * @param $title Title object
2370 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2372 public static function onArticleEdit( $title ) {
2373 // Invalidate caches of articles which include this page
2374 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2377 // Invalidate the caches of all pages which redirect here
2378 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2380 # Purge squid for this page only
2381 $title->purgeSquid();
2383 # Clear file cache for this page only
2384 HTMLFileCache
::clearFileCache( $title );
2390 * Returns a list of hidden categories this page is a member of.
2391 * Uses the page_props and categorylinks tables.
2393 * @return Array of Title objects
2395 public function getHiddenCategories() {
2397 $id = $this->mTitle
->getArticleID();
2403 $dbr = wfGetDB( DB_SLAVE
);
2404 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2406 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2407 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2410 if ( $res !== false ) {
2411 foreach ( $res as $row ) {
2412 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2420 * Return an applicable autosummary if one exists for the given edit.
2421 * @param $oldtext String: the previous text of the page.
2422 * @param $newtext String: The submitted text of the page.
2423 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2424 * @return string An appropriate autosummary, or an empty string.
2426 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2429 # Decide what kind of autosummary is needed.
2431 # Redirect autosummaries
2432 $ot = Title
::newFromRedirect( $oldtext );
2433 $rt = Title
::newFromRedirect( $newtext );
2435 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2436 $truncatedtext = $wgContLang->truncate(
2437 str_replace( "\n", ' ', $newtext ),
2439 - strlen( wfMsgForContent( 'autoredircomment' ) )
2440 - strlen( $rt->getFullText() )
2442 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2445 # New page autosummaries
2446 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2447 # If they're making a new article, give its text, truncated, in the summary.
2449 $truncatedtext = $wgContLang->truncate(
2450 str_replace( "\n", ' ', $newtext ),
2451 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2453 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2456 # Blanking autosummaries
2457 if ( $oldtext != '' && $newtext == '' ) {
2458 return wfMsgForContent( 'autosumm-blank' );
2459 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2460 # Removing more than 90% of the article
2462 $truncatedtext = $wgContLang->truncate(
2464 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2466 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2469 # If we reach this point, there's no applicable autosummary for our case, so our
2470 # autosummary is empty.
2475 * Auto-generates a deletion reason
2477 * @param &$hasHistory Boolean: whether the page has a history
2478 * @return mixed String containing deletion reason or empty string, or boolean false
2479 * if no revision occurred
2481 public function getAutoDeleteReason( &$hasHistory ) {
2484 // Get the last revision
2485 $rev = $this->getRevision();
2487 if ( is_null( $rev ) ) {
2491 // Get the article's contents
2492 $contents = $rev->getText();
2495 // If the page is blank, use the text from the previous revision,
2496 // which can only be blank if there's a move/import/protect dummy revision involved
2497 if ( $contents == '' ) {
2498 $prev = $rev->getPrevious();
2501 $contents = $prev->getText();
2506 $dbw = wfGetDB( DB_MASTER
);
2508 // Find out if there was only one contributor
2509 // Only scan the last 20 revisions
2510 $res = $dbw->select( 'revision', 'rev_user_text',
2511 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2513 array( 'LIMIT' => 20 )
2516 if ( $res === false ) {
2517 // This page has no revisions, which is very weird
2521 $hasHistory = ( $res->numRows() > 1 );
2522 $row = $dbw->fetchObject( $res );
2524 if ( $row ) { // $row is false if the only contributor is hidden
2525 $onlyAuthor = $row->rev_user_text
;
2526 // Try to find a second contributor
2527 foreach ( $res as $row ) {
2528 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2529 $onlyAuthor = false;
2534 $onlyAuthor = false;
2537 // Generate the summary with a '$1' placeholder
2539 // The current revision is blank and the one before is also
2540 // blank. It's just not our lucky day
2541 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2543 if ( $onlyAuthor ) {
2544 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2546 $reason = wfMsgForContent( 'excontent', '$1' );
2550 if ( $reason == '-' ) {
2551 // Allow these UI messages to be blanked out cleanly
2555 // Replace newlines with spaces to prevent uglyness
2556 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2557 // Calculate the maximum amount of chars to get
2558 // Max content length = max comment length - length of the comment (excl. $1)
2559 $maxLength = 255 - ( strlen( $reason ) - 2 );
2560 $contents = $wgContLang->truncate( $contents, $maxLength );
2561 // Remove possible unfinished links
2562 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2563 // Now replace the '$1' placeholder
2564 $reason = str_replace( '$1', $contents, $reason );
2570 * Update all the appropriate counts in the category table, given that
2571 * we've added the categories $added and deleted the categories $deleted.
2573 * @param $added array The names of categories that were added
2574 * @param $deleted array The names of categories that were deleted
2576 public function updateCategoryCounts( $added, $deleted ) {
2577 $ns = $this->mTitle
->getNamespace();
2578 $dbw = wfGetDB( DB_MASTER
);
2580 # First make sure the rows exist. If one of the "deleted" ones didn't
2581 # exist, we might legitimately not create it, but it's simpler to just
2582 # create it and then give it a negative value, since the value is bogus
2585 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2586 $insertCats = array_merge( $added, $deleted );
2587 if ( !$insertCats ) {
2588 # Okay, nothing to do
2592 $insertRows = array();
2594 foreach ( $insertCats as $cat ) {
2595 $insertRows[] = array(
2596 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2600 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2602 $addFields = array( 'cat_pages = cat_pages + 1' );
2603 $removeFields = array( 'cat_pages = cat_pages - 1' );
2605 if ( $ns == NS_CATEGORY
) {
2606 $addFields[] = 'cat_subcats = cat_subcats + 1';
2607 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2608 } elseif ( $ns == NS_FILE
) {
2609 $addFields[] = 'cat_files = cat_files + 1';
2610 $removeFields[] = 'cat_files = cat_files - 1';
2617 array( 'cat_title' => $added ),
2626 array( 'cat_title' => $deleted ),
2633 * Updates cascading protections
2635 * @param $parserOutput ParserOutput object for the current version
2637 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2638 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2642 // templatelinks table may have become out of sync,
2643 // especially if using variable-based transclusions.
2644 // For paranoia, check if things have changed and if
2645 // so apply updates to the database. This will ensure
2646 // that cascaded protections apply as soon as the changes
2649 # Get templates from templatelinks
2650 $id = $this->mTitle
->getArticleID();
2652 $tlTemplates = array();
2654 $dbr = wfGetDB( DB_SLAVE
);
2655 $res = $dbr->select( array( 'templatelinks' ),
2656 array( 'tl_namespace', 'tl_title' ),
2657 array( 'tl_from' => $id ),
2661 foreach ( $res as $row ) {
2662 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2665 # Get templates from parser output.
2666 $poTemplates = array();
2667 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2668 foreach ( $templates as $dbk => $id ) {
2669 $poTemplates["$ns:$dbk"] = true;
2674 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2676 if ( count( $templates_diff ) > 0 ) {
2677 # Whee, link updates time.
2678 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2684 * Return a list of templates used by this article.
2685 * Uses the templatelinks table
2687 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2688 * @return Array of Title objects
2690 public function getUsedTemplates() {
2691 return $this->mTitle
->getTemplateLinksFrom();
2695 * Perform article updates on a special page creation.
2697 * @param $rev Revision object
2699 * @todo This is a shitty interface function. Kill it and replace the
2700 * other shitty functions like doEditUpdates and such so it's not needed
2702 * @deprecated since 1.18, use doEditUpdates()
2704 public function createUpdates( $rev ) {
2705 wfDeprecated( __METHOD__
, '1.18' );
2707 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2711 * This function is called right before saving the wikitext,
2712 * so we can do things like signatures and links-in-context.
2714 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2715 * @param $text String article contents
2716 * @param $user User object: user doing the edit
2717 * @param $popts ParserOptions object: parser options, default options for
2718 * the user loaded if null given
2719 * @return string article contents with altered wikitext markup (signatures
2720 * converted, {{subst:}}, templates, etc.)
2722 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2723 global $wgParser, $wgUser;
2725 wfDeprecated( __METHOD__
, '1.19' );
2727 $user = is_null( $user ) ?
$wgUser : $user;
2729 if ( $popts === null ) {
2730 $popts = ParserOptions
::newFromUser( $user );
2733 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2737 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2739 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2742 public function isBigDeletion() {
2743 wfDeprecated( __METHOD__
, '1.19' );
2744 return $this->mTitle
->isBigDeletion();
2748 * Get the approximate revision count of this page.
2750 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2753 public function estimateRevisionCount() {
2754 wfDeprecated( __METHOD__
, '1.19' );
2755 return $this->mTitle
->estimateRevisionCount();
2759 * Update the article's restriction field, and leave a log entry.
2761 * @deprecated since 1.19
2762 * @param $limit Array: set of restriction keys
2763 * @param $reason String
2764 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2765 * @param $expiry Array: per restriction type expiration
2766 * @param $user User The user updating the restrictions
2767 * @return bool true on success
2769 public function updateRestrictions(
2770 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2774 $user = is_null( $user ) ?
$wgUser : $user;
2776 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2780 * @deprecated since 1.18
2782 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2783 wfDeprecated( __METHOD__
, '1.18' );
2785 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2789 * @deprecated since 1.18
2791 public function viewUpdates() {
2792 wfDeprecated( __METHOD__
, '1.18' );
2794 return $this->doViewUpdates( $wgUser );
2798 * @deprecated since 1.18
2801 public function useParserCache( $oldid ) {
2802 wfDeprecated( __METHOD__
, '1.18' );
2804 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2808 class PoolWorkArticleView
extends PoolCounterWork
{
2826 * @var ParserOptions
2828 private $parserOptions;
2836 * @var ParserOutput|bool
2838 private $parserOutput = false;
2843 private $isDirty = false;
2848 private $error = false;
2854 * @param $revid Integer: ID of the revision being parsed
2855 * @param $useParserCache Boolean: whether to use the parser cache
2856 * @param $parserOptions parserOptions to use for the parse operation
2857 * @param $text String: text to parse or null to load it
2859 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2860 $this->page
= $page;
2861 $this->revid
= $revid;
2862 $this->cacheable
= $useParserCache;
2863 $this->parserOptions
= $parserOptions;
2864 $this->text
= $text;
2865 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2866 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2870 * Get the ParserOutput from this object, or false in case of failure
2872 * @return ParserOutput
2874 public function getParserOutput() {
2875 return $this->parserOutput
;
2879 * Get whether the ParserOutput is a dirty one (i.e. expired)
2883 public function getIsDirty() {
2884 return $this->isDirty
;
2888 * Get a Status object in case of error or false otherwise
2890 * @return Status|bool
2892 public function getError() {
2893 return $this->error
;
2900 global $wgParser, $wgUseFileCache;
2902 $isCurrent = $this->revid
=== $this->page
->getLatest();
2904 if ( $this->text
!== null ) {
2905 $text = $this->text
;
2906 } elseif ( $isCurrent ) {
2907 $text = $this->page
->getRawText();
2909 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2910 if ( $rev === null ) {
2913 $text = $rev->getText();
2916 $time = - microtime( true );
2917 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2918 $this->parserOptions
, true, true, $this->revid
);
2919 $time +
= microtime( true );
2923 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2924 $this->page
->getTitle()->getPrefixedDBkey() ) );
2927 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2928 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2931 // Make sure file cache is not used on uncacheable content.
2932 // Output that has magic words in it can still use the parser cache
2933 // (if enabled), though it will generally expire sooner.
2934 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2935 $wgUseFileCache = false;
2939 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2948 function getCachedWork() {
2949 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2951 if ( $this->parserOutput
=== false ) {
2952 wfDebug( __METHOD__
. ": parser cache miss\n" );
2955 wfDebug( __METHOD__
. ": parser cache hit\n" );
2963 function fallback() {
2964 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2966 if ( $this->parserOutput
=== false ) {
2967 wfDebugLog( 'dirty', "dirty missing\n" );
2968 wfDebug( __METHOD__
. ": no dirty cache\n" );
2971 wfDebug( __METHOD__
. ": sending dirty output\n" );
2972 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2973 $this->isDirty
= true;
2979 * @param $status Status
2982 function error( $status ) {
2983 $this->error
= $status;