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
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
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
892 public function doPurge() {
895 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
899 // Invalidate the cache
900 $this->mTitle
->invalidateCache();
904 // Commit the transaction before the purge is sent
905 $dbw = wfGetDB( DB_MASTER
);
909 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
913 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
914 if ( $this->mTitle
->exists() ) {
915 $text = $this->getRawText();
920 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
926 * Insert a new empty page record for this article.
927 * This *must* be followed up by creating a revision
928 * and running $this->updateRevisionOn( ... );
929 * or else the record will be left in a funky state.
930 * Best if all done inside a transaction.
932 * @param $dbw DatabaseBase
933 * @return int The newly created page_id key, or false if the title already existed
935 public function insertOn( $dbw ) {
936 wfProfileIn( __METHOD__
);
938 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
939 $dbw->insert( 'page', array(
940 'page_id' => $page_id,
941 'page_namespace' => $this->mTitle
->getNamespace(),
942 'page_title' => $this->mTitle
->getDBkey(),
944 'page_restrictions' => '',
945 'page_is_redirect' => 0, # Will set this shortly...
947 'page_random' => wfRandom(),
948 'page_touched' => $dbw->timestamp(),
949 'page_latest' => 0, # Fill this in shortly...
950 'page_len' => 0, # Fill this in shortly...
951 ), __METHOD__
, 'IGNORE' );
953 $affected = $dbw->affectedRows();
956 $newid = $dbw->insertId();
957 $this->mTitle
->resetArticleID( $newid );
959 wfProfileOut( __METHOD__
);
961 return $affected ?
$newid : false;
965 * Update the page record to point to a newly saved revision.
967 * @param $dbw DatabaseBase: object
968 * @param $revision Revision: For ID number, and text used to set
969 * length and redirect status fields
970 * @param $lastRevision Integer: if given, will not overwrite the page field
971 * when different from the currently set value.
972 * Giving 0 indicates the new page flag should be set
974 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
975 * removing rows in redirect table.
976 * @return bool true on success, false on failure
979 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
980 wfProfileIn( __METHOD__
);
982 $text = $revision->getText();
983 $len = strlen( $text );
984 $rt = Title
::newFromRedirectRecurse( $text );
986 $conditions = array( 'page_id' => $this->getId() );
988 if ( !is_null( $lastRevision ) ) {
989 # An extra check against threads stepping on each other
990 $conditions['page_latest'] = $lastRevision;
993 $now = wfTimestampNow();
994 $dbw->update( 'page',
996 'page_latest' => $revision->getId(),
997 'page_touched' => $dbw->timestamp( $now ),
998 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
999 'page_is_redirect' => $rt !== null ?
1 : 0,
1005 $result = $dbw->affectedRows() != 0;
1007 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1008 $this->setLastEdit( $revision );
1009 $this->setCachedLastEditTime( $now );
1010 $this->mLatest
= $revision->getId();
1011 $this->mIsRedirect
= (bool)$rt;
1012 # Update the LinkCache.
1013 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1016 wfProfileOut( __METHOD__
);
1021 * Add row to the redirect table if this is a redirect, remove otherwise.
1023 * @param $dbw DatabaseBase
1024 * @param $redirectTitle Title object pointing to the redirect target,
1025 * or NULL if this is not a redirect
1026 * @param $lastRevIsRedirect If given, will optimize adding and
1027 * removing rows in redirect table.
1028 * @return bool true on success, false on failure
1031 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1032 // Always update redirects (target link might have changed)
1033 // Update/Insert if we don't know if the last revision was a redirect or not
1034 // Delete if changing from redirect to non-redirect
1035 $isRedirect = !is_null( $redirectTitle );
1037 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1041 wfProfileIn( __METHOD__
);
1042 if ( $isRedirect ) {
1043 $this->insertRedirectEntry( $redirectTitle );
1045 // This is not a redirect, remove row from redirect table
1046 $where = array( 'rd_from' => $this->getId() );
1047 $dbw->delete( 'redirect', $where, __METHOD__
);
1050 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1051 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1053 wfProfileOut( __METHOD__
);
1055 return ( $dbw->affectedRows() != 0 );
1059 * If the given revision is newer than the currently set page_latest,
1060 * update the page record. Otherwise, do nothing.
1062 * @param $dbw DatabaseBase object
1063 * @param $revision Revision object
1066 public function updateIfNewerOn( $dbw, $revision ) {
1067 wfProfileIn( __METHOD__
);
1069 $row = $dbw->selectRow(
1070 array( 'revision', 'page' ),
1071 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1073 'page_id' => $this->getId(),
1074 'page_latest=rev_id' ),
1078 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1079 wfProfileOut( __METHOD__
);
1082 $prev = $row->rev_id
;
1083 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1085 # No or missing previous revision; mark the page as new
1087 $lastRevIsRedirect = null;
1090 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1092 wfProfileOut( __METHOD__
);
1097 * Get the text that needs to be saved in order to undo all revisions
1098 * between $undo and $undoafter. Revisions must belong to the same page,
1099 * must exist and must not be deleted
1100 * @param $undo Revision
1101 * @param $undoafter Revision Must be an earlier revision than $undo
1102 * @return mixed string on success, false on failure
1104 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1105 $cur_text = $this->getRawText();
1106 if ( $cur_text === false ) {
1107 return false; // no page
1109 $undo_text = $undo->getText();
1110 $undoafter_text = $undoafter->getText();
1112 if ( $cur_text == $undo_text ) {
1113 # No use doing a merge if it's just a straight revert.
1114 return $undoafter_text;
1119 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1123 return $undone_text;
1127 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1128 * @param $text String: new text of the section
1129 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1130 * @param $edittime String: revision timestamp or null to use the current revision
1131 * @return string Complete article text, or null if error
1133 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1134 wfProfileIn( __METHOD__
);
1136 if ( strval( $section ) == '' ) {
1137 // Whole-page edit; let the whole text through
1139 // Bug 30711: always use current version when adding a new section
1140 if ( is_null( $edittime ) ||
$section == 'new' ) {
1141 $oldtext = $this->getRawText();
1142 if ( $oldtext === false ) {
1143 wfDebug( __METHOD__
. ": no page text\n" );
1144 wfProfileOut( __METHOD__
);
1148 $dbw = wfGetDB( DB_MASTER
);
1149 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1152 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1153 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1154 wfProfileOut( __METHOD__
);
1158 $oldtext = $rev->getText();
1161 if ( $section == 'new' ) {
1162 # Inserting a new section
1163 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1164 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1165 $text = strlen( trim( $oldtext ) ) > 0
1166 ?
"{$oldtext}\n\n{$subject}{$text}"
1167 : "{$subject}{$text}";
1170 # Replacing an existing section; roll out the big guns
1173 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1177 wfProfileOut( __METHOD__
);
1182 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1184 * @return Int updated $flags
1186 function checkFlags( $flags ) {
1187 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1188 if ( $this->mTitle
->getArticleID() ) {
1189 $flags |
= EDIT_UPDATE
;
1199 * Change an existing article or create a new article. Updates RC and all necessary caches,
1200 * optionally via the deferred update array.
1202 * @param $text String: new text
1203 * @param $summary String: edit summary
1204 * @param $flags Integer bitfield:
1206 * Article is known or assumed to be non-existent, create a new one
1208 * Article is known or assumed to be pre-existing, update it
1210 * Mark this edit minor, if the user is allowed to do so
1212 * Do not log the change in recentchanges
1214 * Mark the edit a "bot" edit regardless of user rights
1215 * EDIT_DEFER_UPDATES
1216 * Defer some of the updates until the end of index.php
1218 * Fill in blank summaries with generated text where possible
1220 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1221 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1222 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1223 * edit-already-exists error will be returned. These two conditions are also possible with
1224 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1226 * @param $baseRevId the revision ID this edit was based off, if any
1227 * @param $user User the user doing the edit
1229 * @return Status object. Possible errors:
1230 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1231 * edit-gone-missing: In update mode, but the article didn't exist
1232 * edit-conflict: In update mode, the article changed unexpectedly
1233 * edit-no-change: Warning that the text was the same as before
1234 * edit-already-exists: In creation mode, but the article already exists
1236 * Extensions may define additional errors.
1238 * $return->value will contain an associative array with members as follows:
1239 * new: Boolean indicating if the function attempted to create a new article
1240 * revision: The revision object for the inserted revision, or null
1242 * Compatibility note: this function previously returned a boolean value indicating success/failure
1244 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1245 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1247 # Low-level sanity check
1248 if ( $this->mTitle
->getText() === '' ) {
1249 throw new MWException( 'Something is trying to edit an article with an empty title' );
1252 wfProfileIn( __METHOD__
);
1254 $user = is_null( $user ) ?
$wgUser : $user;
1255 $status = Status
::newGood( array() );
1257 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1258 $this->loadPageData( 'fromdbmaster' );
1260 $flags = $this->checkFlags( $flags );
1262 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1263 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1265 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1267 if ( $status->isOK() ) {
1268 $status->fatal( 'edit-hook-aborted' );
1271 wfProfileOut( __METHOD__
);
1275 # Silently ignore EDIT_MINOR if not allowed
1276 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1277 $bot = $flags & EDIT_FORCE_BOT
;
1279 $oldtext = $this->getRawText(); // current revision
1280 $oldsize = strlen( $oldtext );
1281 $oldid = $this->getLatest();
1282 $oldIsRedirect = $this->isRedirect();
1283 $oldcountable = $this->isCountable();
1285 # Provide autosummaries if one is not provided and autosummaries are enabled.
1286 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1287 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1290 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1291 $text = $editInfo->pst
;
1292 $newsize = strlen( $text );
1294 $dbw = wfGetDB( DB_MASTER
);
1295 $now = wfTimestampNow();
1296 $this->mTimestamp
= $now;
1298 if ( $flags & EDIT_UPDATE
) {
1299 # Update article, but only if changed.
1300 $status->value
['new'] = false;
1303 # Article gone missing
1304 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1305 $status->fatal( 'edit-gone-missing' );
1307 wfProfileOut( __METHOD__
);
1311 # Make sure the revision is either completely inserted or not inserted at all
1312 if ( !$wgDBtransactions ) {
1313 $userAbort = ignore_user_abort( true );
1316 $revision = new Revision( array(
1317 'page' => $this->getId(),
1318 'comment' => $summary,
1319 'minor_edit' => $isminor,
1321 'parent_id' => $oldid,
1322 'user' => $user->getId(),
1323 'user_text' => $user->getName(),
1327 $changed = ( strcmp( $text, $oldtext ) != 0 );
1331 $revisionId = $revision->insertOn( $dbw );
1335 # Note that we use $this->mLatest instead of fetching a value from the master DB
1336 # during the course of this function. This makes sure that EditPage can detect
1337 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1338 # before this function is called. A previous function used a separate query, this
1339 # creates a window where concurrent edits can cause an ignored edit conflict.
1340 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1343 /* Belated edit conflict! Run away!! */
1344 $status->fatal( 'edit-conflict' );
1346 # Delete the invalid revision if the DB is not transactional
1347 if ( !$wgDBtransactions ) {
1348 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1354 global $wgUseRCPatrol;
1355 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1356 # Update recentchanges
1357 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1358 # Mark as patrolled if the user can do so
1359 $patrolled = $wgUseRCPatrol && !count(
1360 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1361 # Add RC row to the DB
1362 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1363 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1364 $revisionId, $patrolled
1367 # Log auto-patrolled edits
1369 PatrolLog
::record( $rc, true );
1372 $user->incEditCount();
1376 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1377 // related variables correctly
1378 $revision->setId( $this->getLatest() );
1381 if ( !$wgDBtransactions ) {
1382 ignore_user_abort( $userAbort );
1385 // Now that ignore_user_abort is restored, we can respond to fatal errors
1386 if ( !$status->isOK() ) {
1387 wfProfileOut( __METHOD__
);
1391 # Update links tables, site stats, etc.
1392 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1393 'oldcountable' => $oldcountable ) );
1396 $status->warning( 'edit-no-change' );
1398 // Update page_touched, this is usually implicit in the page update
1399 // Other cache updates are done in onArticleEdit()
1400 $this->mTitle
->invalidateCache();
1403 # Create new article
1404 $status->value
['new'] = true;
1408 # Add the page record; stake our claim on this title!
1409 # This will return false if the article already exists
1410 $newid = $this->insertOn( $dbw );
1412 if ( $newid === false ) {
1414 $status->fatal( 'edit-already-exists' );
1416 wfProfileOut( __METHOD__
);
1420 # Save the revision text...
1421 $revision = new Revision( array(
1423 'comment' => $summary,
1424 'minor_edit' => $isminor,
1426 'user' => $user->getId(),
1427 'user_text' => $user->getName(),
1430 $revisionId = $revision->insertOn( $dbw );
1432 # Update the page record with revision data
1433 $this->updateRevisionOn( $dbw, $revision, 0 );
1435 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1437 # Update recentchanges
1438 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1439 global $wgUseRCPatrol, $wgUseNPPatrol;
1441 # Mark as patrolled if the user can do so
1442 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1443 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1444 # Add RC row to the DB
1445 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1446 '', strlen( $text ), $revisionId, $patrolled );
1448 # Log auto-patrolled edits
1450 PatrolLog
::record( $rc, true );
1453 $user->incEditCount();
1456 # Update links, etc.
1457 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1459 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1460 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1463 # Do updates right now unless deferral was requested
1464 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1465 DeferredUpdates
::doUpdates();
1468 // Return the new revision (or null) to the caller
1469 $status->value
['revision'] = $revision;
1471 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1472 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1474 # Promote user to any groups they meet the criteria for
1475 $user->addAutopromoteOnceGroups( 'onEdit' );
1477 wfProfileOut( __METHOD__
);
1482 * Get parser options suitable for rendering the primary article wikitext
1483 * @param User|string $user User object or 'canonical'
1484 * @return ParserOptions
1486 public function makeParserOptions( $user ) {
1488 if ( $user instanceof User
) { // settings per user (even anons)
1489 $options = ParserOptions
::newFromUser( $user );
1490 } else { // canonical settings
1491 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1493 $options->enableLimitReport(); // show inclusion/loop reports
1494 $options->setTidy( true ); // fix bad HTML
1499 * Prepare text which is about to be saved.
1500 * Returns a stdclass with source, pst and output members
1502 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1503 global $wgParser, $wgContLang, $wgUser;
1504 $user = is_null( $user ) ?
$wgUser : $user;
1505 // @TODO fixme: check $user->getId() here???
1506 if ( $this->mPreparedEdit
1507 && $this->mPreparedEdit
->newText
== $text
1508 && $this->mPreparedEdit
->revid
== $revid
1511 return $this->mPreparedEdit
;
1514 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1515 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1517 $edit = (object)array();
1518 $edit->revid
= $revid;
1519 $edit->newText
= $text;
1520 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1521 $edit->popts
= $this->makeParserOptions( 'canonical' );
1522 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1523 $edit->oldText
= $this->getRawText();
1525 $this->mPreparedEdit
= $edit;
1531 * Do standard deferred updates after page edit.
1532 * Update links tables, site stats, search index and message cache.
1533 * Purges pages that include this page if the text was changed here.
1534 * Every 100th edit, prune the recent changes table.
1537 * @param $revision Revision object
1538 * @param $user User object that did the revision
1539 * @param $options Array of options, following indexes are used:
1540 * - changed: boolean, whether the revision changed the content (default true)
1541 * - created: boolean, whether the revision created the page (default false)
1542 * - oldcountable: boolean or null (default null):
1543 * - boolean: whether the page was counted as an article before that
1544 * revision, only used in changed is true and created is false
1545 * - null: don't change the article count
1547 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1548 global $wgEnableParserCache;
1550 wfProfileIn( __METHOD__
);
1552 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1553 $text = $revision->getText();
1556 # Be careful not to double-PST: $text is usually already PST-ed once
1557 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1558 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1559 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1561 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1562 $editInfo = $this->mPreparedEdit
;
1565 # Save it to the parser cache
1566 if ( $wgEnableParserCache ) {
1567 $parserCache = ParserCache
::singleton();
1568 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1571 # Update the links tables
1572 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1575 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1577 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1578 if ( 0 == mt_rand( 0, 99 ) ) {
1579 // Flush old entries from the `recentchanges` table; we do this on
1580 // random requests so as to avoid an increase in writes for no good reason
1583 $dbw = wfGetDB( DB_MASTER
);
1584 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1587 array( "rc_timestamp < '$cutoff'" ),
1593 if ( !$this->mTitle
->exists() ) {
1594 wfProfileOut( __METHOD__
);
1598 $id = $this->getId();
1599 $title = $this->mTitle
->getPrefixedDBkey();
1600 $shortTitle = $this->mTitle
->getDBkey();
1602 if ( !$options['changed'] ) {
1605 } elseif ( $options['created'] ) {
1606 $good = (int)$this->isCountable( $editInfo );
1608 } elseif ( $options['oldcountable'] !== null ) {
1609 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1616 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1617 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1619 # If this is another user's talk page, update newtalk.
1620 # Don't do this if $options['changed'] = false (null-edits) nor if
1621 # it's a minor edit and the user doesn't want notifications for those.
1622 if ( $options['changed']
1623 && $this->mTitle
->getNamespace() == NS_USER_TALK
1624 && $shortTitle != $user->getTitleKey()
1625 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1627 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1628 $other = User
::newFromName( $shortTitle, false );
1630 wfDebug( __METHOD__
. ": invalid username\n" );
1631 } elseif ( User
::isIP( $shortTitle ) ) {
1632 // An anonymous user
1633 $other->setNewtalk( true );
1634 } elseif ( $other->isLoggedIn() ) {
1635 $other->setNewtalk( true );
1637 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1642 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1643 MessageCache
::singleton()->replace( $shortTitle, $text );
1646 if( $options['created'] ) {
1647 self
::onArticleCreate( $this->mTitle
);
1649 self
::onArticleEdit( $this->mTitle
);
1652 wfProfileOut( __METHOD__
);
1656 * Edit an article without doing all that other stuff
1657 * The article must already exist; link tables etc
1658 * are not updated, caches are not flushed.
1660 * @param $text String: text submitted
1661 * @param $user User The relevant user
1662 * @param $comment String: comment submitted
1663 * @param $minor Boolean: whereas it's a minor modification
1665 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1666 wfProfileIn( __METHOD__
);
1668 $dbw = wfGetDB( DB_MASTER
);
1669 $revision = new Revision( array(
1670 'page' => $this->getId(),
1672 'comment' => $comment,
1673 'minor_edit' => $minor ?
1 : 0,
1675 $revision->insertOn( $dbw );
1676 $this->updateRevisionOn( $dbw, $revision );
1678 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1680 wfProfileOut( __METHOD__
);
1684 * Update the article's restriction field, and leave a log entry.
1685 * This works for protection both existing and non-existing pages.
1687 * @param $limit Array: set of restriction keys
1688 * @param $reason String
1689 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1690 * @param $expiry Array: per restriction type expiration
1691 * @param $user User The user updating the restrictions
1692 * @return bool true on success
1694 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1697 if ( wfReadOnly() ) {
1698 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1701 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1703 $id = $this->mTitle
->getArticleID();
1709 // Take this opportunity to purge out expired restrictions
1710 Title
::purgeExpiredRestrictions();
1712 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1713 # we expect a single selection, but the schema allows otherwise.
1714 $isProtected = false;
1718 $dbw = wfGetDB( DB_MASTER
);
1720 foreach ( $restrictionTypes as $action ) {
1721 if ( !isset( $expiry[$action] ) ) {
1722 $expiry[$action] = $dbw->getInfinity();
1724 if ( !isset( $limit[$action] ) ) {
1725 $limit[$action] = '';
1726 } elseif ( $limit[$action] != '' ) {
1730 # Get current restrictions on $action
1731 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1732 if ( $current != '' ) {
1733 $isProtected = true;
1736 if ( $limit[$action] != $current ) {
1738 } elseif ( $limit[$action] != '' ) {
1739 # Only check expiry change if the action is actually being
1740 # protected, since expiry does nothing on an not-protected
1742 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1748 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1752 # If nothing's changed, do nothing
1754 return Status
::newGood();
1757 if ( !$protect ) { # No protection at all means unprotection
1758 $revCommentMsg = 'unprotectedarticle';
1759 $logAction = 'unprotect';
1760 } elseif ( $isProtected ) {
1761 $revCommentMsg = 'modifiedarticleprotection';
1762 $logAction = 'modify';
1764 $revCommentMsg = 'protectedarticle';
1765 $logAction = 'protect';
1768 $encodedExpiry = array();
1769 $protectDescription = '';
1770 foreach ( $limit as $action => $restrictions ) {
1771 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1772 if ( $restrictions != '' ) {
1773 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1774 if ( $encodedExpiry[$action] != 'infinity' ) {
1775 $protectDescription .= wfMsgForContent( 'protect-expiring',
1776 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1777 $wgContLang->date( $expiry[$action], false, false ) ,
1778 $wgContLang->time( $expiry[$action], false, false ) );
1780 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1783 $protectDescription .= ') ';
1786 $protectDescription = trim( $protectDescription );
1788 if ( $id ) { # Protection of existing page
1789 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1790 return Status
::newGood();
1793 # Only restrictions with the 'protect' right can cascade...
1794 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1795 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1797 # The schema allows multiple restrictions
1798 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1802 # Update restrictions table
1803 foreach ( $limit as $action => $restrictions ) {
1804 if ( $restrictions != '' ) {
1805 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1806 array( 'pr_page' => $id,
1807 'pr_type' => $action,
1808 'pr_level' => $restrictions,
1809 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1810 'pr_expiry' => $encodedExpiry[$action]
1815 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1816 'pr_type' => $action ), __METHOD__
);
1820 # Prepare a null revision to be added to the history
1821 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1823 $editComment .= ": $reason";
1825 if ( $protectDescription ) {
1826 $editComment .= " ($protectDescription)";
1829 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1832 # Insert a null revision
1833 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1834 $nullRevId = $nullRevision->insertOn( $dbw );
1836 $latest = $this->getLatest();
1837 # Update page record
1838 $dbw->update( 'page',
1840 'page_touched' => $dbw->timestamp(),
1841 'page_restrictions' => '',
1842 'page_latest' => $nullRevId
1843 ), array( /* WHERE */
1848 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1849 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1850 } else { # Protection of non-existing page (also known as "title protection")
1851 # Cascade protection is meaningless in this case
1854 if ( $limit['create'] != '' ) {
1855 $dbw->replace( 'protected_titles',
1856 array( array( 'pt_namespace', 'pt_title' ) ),
1858 'pt_namespace' => $this->mTitle
->getNamespace(),
1859 'pt_title' => $this->mTitle
->getDBkey(),
1860 'pt_create_perm' => $limit['create'],
1861 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1862 'pt_expiry' => $encodedExpiry['create'],
1863 'pt_user' => $user->getId(),
1864 'pt_reason' => $reason,
1868 $dbw->delete( 'protected_titles',
1870 'pt_namespace' => $this->mTitle
->getNamespace(),
1871 'pt_title' => $this->mTitle
->getDBkey()
1877 $this->mTitle
->flushRestrictions();
1879 if ( $logAction == 'unprotect' ) {
1880 $logParams = array();
1882 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1885 # Update the protection log
1886 $log = new LogPage( 'protect' );
1887 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1889 return Status
::newGood();
1893 * Take an array of page restrictions and flatten it to a string
1894 * suitable for insertion into the page_restrictions field.
1895 * @param $limit Array
1898 protected static function flattenRestrictions( $limit ) {
1899 if ( !is_array( $limit ) ) {
1900 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1906 foreach ( $limit as $action => $restrictions ) {
1907 if ( $restrictions != '' ) {
1908 $bits[] = "$action=$restrictions";
1912 return implode( ':', $bits );
1916 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
1917 * Deletes the article with database consistency, writes logs, purges caches
1919 * @param $reason string delete reason for deletion log
1920 * @param $suppress bitfield
1921 * Revision::DELETED_TEXT
1922 * Revision::DELETED_COMMENT
1923 * Revision::DELETED_USER
1924 * Revision::DELETED_RESTRICTED
1925 * @param $id int article ID
1926 * @param $commit boolean defaults to true, triggers transaction end
1927 * @param &$error Array of errors to append to
1928 * @param $user User The deleting user
1929 * @return boolean true if successful
1931 public function doDeleteArticle(
1932 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1934 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
1935 == WikiPage
::DELETE_SUCCESS
;
1939 * Back-end article deletion
1940 * Deletes the article with database consistency, writes logs, purges caches
1942 * @param $reason string delete reason for deletion log
1943 * @param $suppress bitfield
1944 * Revision::DELETED_TEXT
1945 * Revision::DELETED_COMMENT
1946 * Revision::DELETED_USER
1947 * Revision::DELETED_RESTRICTED
1948 * @param $id int article ID
1949 * @param $commit boolean defaults to true, triggers transaction end
1950 * @param &$error Array of errors to append to
1951 * @param $user User The deleting user
1952 * @return int: One of WikiPage::DELETE_* constants
1954 public function doDeleteArticleReal(
1955 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1958 $user = is_null( $user ) ?
$wgUser : $user;
1960 wfDebug( __METHOD__
. "\n" );
1962 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1963 return WikiPage
::DELETE_HOOK_ABORTED
;
1965 $dbw = wfGetDB( DB_MASTER
);
1966 $t = $this->mTitle
->getDBkey();
1967 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1969 if ( $t === '' ||
$id == 0 ) {
1970 return WikiPage
::DELETE_NO_PAGE
;
1973 // Bitfields to further suppress the content
1976 // This should be 15...
1977 $bitfield |
= Revision
::DELETED_TEXT
;
1978 $bitfield |
= Revision
::DELETED_COMMENT
;
1979 $bitfield |
= Revision
::DELETED_USER
;
1980 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1982 $bitfield = 'rev_deleted';
1986 // For now, shunt the revision data into the archive table.
1987 // Text is *not* removed from the text table; bulk storage
1988 // is left intact to avoid breaking block-compression or
1989 // immutable storage schemes.
1991 // For backwards compatibility, note that some older archive
1992 // table entries will have ar_text and ar_flags fields still.
1994 // In the future, we may keep revisions and mark them with
1995 // the rev_deleted field, which is reserved for this purpose.
1996 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1998 'ar_namespace' => 'page_namespace',
1999 'ar_title' => 'page_title',
2000 'ar_comment' => 'rev_comment',
2001 'ar_user' => 'rev_user',
2002 'ar_user_text' => 'rev_user_text',
2003 'ar_timestamp' => 'rev_timestamp',
2004 'ar_minor_edit' => 'rev_minor_edit',
2005 'ar_rev_id' => 'rev_id',
2006 'ar_parent_id' => 'rev_parent_id',
2007 'ar_text_id' => 'rev_text_id',
2008 'ar_text' => '\'\'', // Be explicit to appease
2009 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2010 'ar_len' => 'rev_len',
2011 'ar_page_id' => 'page_id',
2012 'ar_deleted' => $bitfield,
2013 'ar_sha1' => 'rev_sha1'
2016 'page_id = rev_page'
2020 # Now that it's safely backed up, delete it
2021 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2022 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2026 return WikiPage
::DELETE_NO_REVISIONS
;
2029 $this->doDeleteUpdates( $id );
2031 # Log the deletion, if the page was suppressed, log it at Oversight instead
2032 $logtype = $suppress ?
'suppress' : 'delete';
2034 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2035 $logEntry->setPerformer( $user );
2036 $logEntry->setTarget( $this->mTitle
);
2037 $logEntry->setComment( $reason );
2038 $logid = $logEntry->insert();
2039 $logEntry->publish( $logid );
2045 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2046 return WikiPage
::DELETE_SUCCESS
;
2050 * Do some database updates after deletion
2052 * @param $id Int: page_id value of the page being deleted
2054 public function doDeleteUpdates( $id ) {
2055 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2057 $dbw = wfGetDB( DB_MASTER
);
2059 # Delete restrictions for it
2060 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2062 # Fix category table counts
2064 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2066 foreach ( $res as $row ) {
2067 $cats [] = $row->cl_to
;
2070 $this->updateCategoryCounts( array(), $cats );
2072 # If using cascading deletes, we can skip some explicit deletes
2073 if ( !$dbw->cascadingDeletes() ) {
2074 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2076 # Delete outgoing links
2077 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2078 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2079 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2080 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2081 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2082 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2083 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2084 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2085 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2088 # If using cleanup triggers, we can skip some manual deletes
2089 if ( !$dbw->cleanupTriggers() ) {
2090 # Clean up recentchanges entries...
2091 $dbw->delete( 'recentchanges',
2092 array( 'rc_type != ' . RC_LOG
,
2093 'rc_namespace' => $this->mTitle
->getNamespace(),
2094 'rc_title' => $this->mTitle
->getDBkey() ),
2096 $dbw->delete( 'recentchanges',
2097 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2102 self
::onArticleDelete( $this->mTitle
);
2104 # Clear the cached article id so the interface doesn't act like we exist
2105 $this->mTitle
->resetArticleID( 0 );
2109 * Roll back the most recent consecutive set of edits to a page
2110 * from the same user; fails if there are no eligible edits to
2111 * roll back to, e.g. user is the sole contributor. This function
2112 * performs permissions checks on $user, then calls commitRollback()
2113 * to do the dirty work
2115 * @todo: seperate the business/permission stuff out from backend code
2117 * @param $fromP String: Name of the user whose edits to rollback.
2118 * @param $summary String: Custom summary. Set to default summary if empty.
2119 * @param $token String: Rollback token.
2120 * @param $bot Boolean: If true, mark all reverted edits as bot.
2122 * @param $resultDetails Array: contains result-specific array of additional values
2123 * 'alreadyrolled' : 'current' (rev)
2124 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2126 * @param $user User The user performing the rollback
2127 * @return array of errors, each error formatted as
2128 * array(messagekey, param1, param2, ...).
2129 * On success, the array is empty. This array can also be passed to
2130 * OutputPage::showPermissionsErrorPage().
2132 public function doRollback(
2133 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2135 $resultDetails = null;
2138 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2139 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2140 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2142 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2143 $errors[] = array( 'sessionfailure' );
2146 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2147 $errors[] = array( 'actionthrottledtext' );
2150 # If there were errors, bail out now
2151 if ( !empty( $errors ) ) {
2155 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2159 * Backend implementation of doRollback(), please refer there for parameter
2160 * and return value documentation
2162 * NOTE: This function does NOT check ANY permissions, it just commits the
2163 * rollback to the DB. Therefore, you should only call this function direct-
2164 * ly if you want to use custom permissions checks. If you don't, use
2165 * doRollback() instead.
2166 * @param $fromP String: Name of the user whose edits to rollback.
2167 * @param $summary String: Custom summary. Set to default summary if empty.
2168 * @param $bot Boolean: If true, mark all reverted edits as bot.
2170 * @param $resultDetails Array: contains result-specific array of additional values
2171 * @param $guser User The user performing the rollback
2173 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2174 global $wgUseRCPatrol, $wgContLang;
2176 $dbw = wfGetDB( DB_MASTER
);
2178 if ( wfReadOnly() ) {
2179 return array( array( 'readonlytext' ) );
2182 # Get the last editor
2183 $current = $this->getRevision();
2184 if ( is_null( $current ) ) {
2185 # Something wrong... no page?
2186 return array( array( 'notanarticle' ) );
2189 $from = str_replace( '_', ' ', $fromP );
2190 # User name given should match up with the top revision.
2191 # If the user was deleted then $from should be empty.
2192 if ( $from != $current->getUserText() ) {
2193 $resultDetails = array( 'current' => $current );
2194 return array( array( 'alreadyrolled',
2195 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2196 htmlspecialchars( $fromP ),
2197 htmlspecialchars( $current->getUserText() )
2201 # Get the last edit not by this guy...
2202 # Note: these may not be public values
2203 $user = intval( $current->getRawUser() );
2204 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2205 $s = $dbw->selectRow( 'revision',
2206 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2207 array( 'rev_page' => $current->getPage(),
2208 "rev_user != {$user} OR rev_user_text != {$user_text}"
2210 array( 'USE INDEX' => 'page_timestamp',
2211 'ORDER BY' => 'rev_timestamp DESC' )
2213 if ( $s === false ) {
2214 # No one else ever edited this page
2215 return array( array( 'cantrollback' ) );
2216 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2217 # Only admins can see this text
2218 return array( array( 'notvisiblerev' ) );
2222 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2223 # Mark all reverted edits as bot
2227 if ( $wgUseRCPatrol ) {
2228 # Mark all reverted edits as patrolled
2229 $set['rc_patrolled'] = 1;
2232 if ( count( $set ) ) {
2233 $dbw->update( 'recentchanges', $set,
2235 'rc_cur_id' => $current->getPage(),
2236 'rc_user_text' => $current->getUserText(),
2237 "rc_timestamp > '{$s->rev_timestamp}'",
2242 # Generate the edit summary if necessary
2243 $target = Revision
::newFromId( $s->rev_id
);
2244 if ( empty( $summary ) ) {
2245 if ( $from == '' ) { // no public user name
2246 $summary = wfMsgForContent( 'revertpage-nouser' );
2248 $summary = wfMsgForContent( 'revertpage' );
2252 # Allow the custom summary to use the same args as the default message
2254 $target->getUserText(), $from, $s->rev_id
,
2255 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2256 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2258 $summary = wfMsgReplaceArgs( $summary, $args );
2261 $flags = EDIT_UPDATE
;
2263 if ( $guser->isAllowed( 'minoredit' ) ) {
2264 $flags |
= EDIT_MINOR
;
2267 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2268 $flags |
= EDIT_FORCE_BOT
;
2271 # Actually store the edit
2272 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2273 if ( !empty( $status->value
['revision'] ) ) {
2274 $revId = $status->value
['revision']->getId();
2279 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2281 $resultDetails = array(
2282 'summary' => $summary,
2283 'current' => $current,
2284 'target' => $target,
2292 * The onArticle*() functions are supposed to be a kind of hooks
2293 * which should be called whenever any of the specified actions
2296 * This is a good place to put code to clear caches, for instance.
2298 * This is called on page move and undelete, as well as edit
2300 * @param $title Title object
2302 public static function onArticleCreate( $title ) {
2303 # Update existence markers on article/talk tabs...
2304 if ( $title->isTalkPage() ) {
2305 $other = $title->getSubjectPage();
2307 $other = $title->getTalkPage();
2310 $other->invalidateCache();
2311 $other->purgeSquid();
2313 $title->touchLinks();
2314 $title->purgeSquid();
2315 $title->deleteTitleProtection();
2319 * Clears caches when article is deleted
2321 * @param $title Title
2323 public static function onArticleDelete( $title ) {
2324 # Update existence markers on article/talk tabs...
2325 if ( $title->isTalkPage() ) {
2326 $other = $title->getSubjectPage();
2328 $other = $title->getTalkPage();
2331 $other->invalidateCache();
2332 $other->purgeSquid();
2334 $title->touchLinks();
2335 $title->purgeSquid();
2338 HTMLFileCache
::clearFileCache( $title );
2341 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2342 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2346 if ( $title->getNamespace() == NS_FILE
) {
2347 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2348 $update->doUpdate();
2352 if ( $title->getNamespace() == NS_USER_TALK
) {
2353 $user = User
::newFromName( $title->getText(), false );
2355 $user->setNewtalk( false );
2360 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2364 * Purge caches on page update etc
2366 * @param $title Title object
2367 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2369 public static function onArticleEdit( $title ) {
2370 // Invalidate caches of articles which include this page
2371 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2374 // Invalidate the caches of all pages which redirect here
2375 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2377 # Purge squid for this page only
2378 $title->purgeSquid();
2380 # Clear file cache for this page only
2381 HTMLFileCache
::clearFileCache( $title );
2387 * Returns a list of hidden categories this page is a member of.
2388 * Uses the page_props and categorylinks tables.
2390 * @return Array of Title objects
2392 public function getHiddenCategories() {
2394 $id = $this->mTitle
->getArticleID();
2400 $dbr = wfGetDB( DB_SLAVE
);
2401 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2403 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2404 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2407 if ( $res !== false ) {
2408 foreach ( $res as $row ) {
2409 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2417 * Return an applicable autosummary if one exists for the given edit.
2418 * @param $oldtext String: the previous text of the page.
2419 * @param $newtext String: The submitted text of the page.
2420 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2421 * @return string An appropriate autosummary, or an empty string.
2423 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2426 # Decide what kind of autosummary is needed.
2428 # Redirect autosummaries
2429 $ot = Title
::newFromRedirect( $oldtext );
2430 $rt = Title
::newFromRedirect( $newtext );
2432 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2433 $truncatedtext = $wgContLang->truncate(
2434 str_replace( "\n", ' ', $newtext ),
2436 - strlen( wfMsgForContent( 'autoredircomment' ) )
2437 - strlen( $rt->getFullText() )
2439 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2442 # New page autosummaries
2443 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2444 # If they're making a new article, give its text, truncated, in the summary.
2446 $truncatedtext = $wgContLang->truncate(
2447 str_replace( "\n", ' ', $newtext ),
2448 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2450 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2453 # Blanking autosummaries
2454 if ( $oldtext != '' && $newtext == '' ) {
2455 return wfMsgForContent( 'autosumm-blank' );
2456 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2457 # Removing more than 90% of the article
2459 $truncatedtext = $wgContLang->truncate(
2461 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2463 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2466 # If we reach this point, there's no applicable autosummary for our case, so our
2467 # autosummary is empty.
2472 * Auto-generates a deletion reason
2474 * @param &$hasHistory Boolean: whether the page has a history
2475 * @return mixed String containing deletion reason or empty string, or boolean false
2476 * if no revision occurred
2478 public function getAutoDeleteReason( &$hasHistory ) {
2481 // Get the last revision
2482 $rev = $this->getRevision();
2484 if ( is_null( $rev ) ) {
2488 // Get the article's contents
2489 $contents = $rev->getText();
2492 // If the page is blank, use the text from the previous revision,
2493 // which can only be blank if there's a move/import/protect dummy revision involved
2494 if ( $contents == '' ) {
2495 $prev = $rev->getPrevious();
2498 $contents = $prev->getText();
2503 $dbw = wfGetDB( DB_MASTER
);
2505 // Find out if there was only one contributor
2506 // Only scan the last 20 revisions
2507 $res = $dbw->select( 'revision', 'rev_user_text',
2508 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2510 array( 'LIMIT' => 20 )
2513 if ( $res === false ) {
2514 // This page has no revisions, which is very weird
2518 $hasHistory = ( $res->numRows() > 1 );
2519 $row = $dbw->fetchObject( $res );
2521 if ( $row ) { // $row is false if the only contributor is hidden
2522 $onlyAuthor = $row->rev_user_text
;
2523 // Try to find a second contributor
2524 foreach ( $res as $row ) {
2525 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2526 $onlyAuthor = false;
2531 $onlyAuthor = false;
2534 // Generate the summary with a '$1' placeholder
2536 // The current revision is blank and the one before is also
2537 // blank. It's just not our lucky day
2538 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2540 if ( $onlyAuthor ) {
2541 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2543 $reason = wfMsgForContent( 'excontent', '$1' );
2547 if ( $reason == '-' ) {
2548 // Allow these UI messages to be blanked out cleanly
2552 // Replace newlines with spaces to prevent uglyness
2553 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2554 // Calculate the maximum amount of chars to get
2555 // Max content length = max comment length - length of the comment (excl. $1)
2556 $maxLength = 255 - ( strlen( $reason ) - 2 );
2557 $contents = $wgContLang->truncate( $contents, $maxLength );
2558 // Remove possible unfinished links
2559 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2560 // Now replace the '$1' placeholder
2561 $reason = str_replace( '$1', $contents, $reason );
2567 * Update all the appropriate counts in the category table, given that
2568 * we've added the categories $added and deleted the categories $deleted.
2570 * @param $added array The names of categories that were added
2571 * @param $deleted array The names of categories that were deleted
2573 public function updateCategoryCounts( $added, $deleted ) {
2574 $ns = $this->mTitle
->getNamespace();
2575 $dbw = wfGetDB( DB_MASTER
);
2577 # First make sure the rows exist. If one of the "deleted" ones didn't
2578 # exist, we might legitimately not create it, but it's simpler to just
2579 # create it and then give it a negative value, since the value is bogus
2582 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2583 $insertCats = array_merge( $added, $deleted );
2584 if ( !$insertCats ) {
2585 # Okay, nothing to do
2589 $insertRows = array();
2591 foreach ( $insertCats as $cat ) {
2592 $insertRows[] = array(
2593 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2597 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2599 $addFields = array( 'cat_pages = cat_pages + 1' );
2600 $removeFields = array( 'cat_pages = cat_pages - 1' );
2602 if ( $ns == NS_CATEGORY
) {
2603 $addFields[] = 'cat_subcats = cat_subcats + 1';
2604 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2605 } elseif ( $ns == NS_FILE
) {
2606 $addFields[] = 'cat_files = cat_files + 1';
2607 $removeFields[] = 'cat_files = cat_files - 1';
2614 array( 'cat_title' => $added ),
2623 array( 'cat_title' => $deleted ),
2630 * Updates cascading protections
2632 * @param $parserOutput ParserOutput object for the current version
2634 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2635 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2639 // templatelinks table may have become out of sync,
2640 // especially if using variable-based transclusions.
2641 // For paranoia, check if things have changed and if
2642 // so apply updates to the database. This will ensure
2643 // that cascaded protections apply as soon as the changes
2646 # Get templates from templatelinks
2647 $id = $this->mTitle
->getArticleID();
2649 $tlTemplates = array();
2651 $dbr = wfGetDB( DB_SLAVE
);
2652 $res = $dbr->select( array( 'templatelinks' ),
2653 array( 'tl_namespace', 'tl_title' ),
2654 array( 'tl_from' => $id ),
2658 foreach ( $res as $row ) {
2659 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2662 # Get templates from parser output.
2663 $poTemplates = array();
2664 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2665 foreach ( $templates as $dbk => $id ) {
2666 $poTemplates["$ns:$dbk"] = true;
2671 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2673 if ( count( $templates_diff ) > 0 ) {
2674 # Whee, link updates time.
2675 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2681 * Return a list of templates used by this article.
2682 * Uses the templatelinks table
2684 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2685 * @return Array of Title objects
2687 public function getUsedTemplates() {
2688 return $this->mTitle
->getTemplateLinksFrom();
2692 * Perform article updates on a special page creation.
2694 * @param $rev Revision object
2696 * @todo This is a shitty interface function. Kill it and replace the
2697 * other shitty functions like doEditUpdates and such so it's not needed
2699 * @deprecated since 1.18, use doEditUpdates()
2701 public function createUpdates( $rev ) {
2702 wfDeprecated( __METHOD__
, '1.18' );
2704 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2708 * This function is called right before saving the wikitext,
2709 * so we can do things like signatures and links-in-context.
2711 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2712 * @param $text String article contents
2713 * @param $user User object: user doing the edit
2714 * @param $popts ParserOptions object: parser options, default options for
2715 * the user loaded if null given
2716 * @return string article contents with altered wikitext markup (signatures
2717 * converted, {{subst:}}, templates, etc.)
2719 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2720 global $wgParser, $wgUser;
2722 wfDeprecated( __METHOD__
, '1.19' );
2724 $user = is_null( $user ) ?
$wgUser : $user;
2726 if ( $popts === null ) {
2727 $popts = ParserOptions
::newFromUser( $user );
2730 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2734 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2736 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2739 public function isBigDeletion() {
2740 wfDeprecated( __METHOD__
, '1.19' );
2741 return $this->mTitle
->isBigDeletion();
2745 * Get the approximate revision count of this page.
2747 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2750 public function estimateRevisionCount() {
2751 wfDeprecated( __METHOD__
, '1.19' );
2752 return $this->mTitle
->estimateRevisionCount();
2756 * Update the article's restriction field, and leave a log entry.
2758 * @deprecated since 1.19
2759 * @param $limit Array: set of restriction keys
2760 * @param $reason String
2761 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2762 * @param $expiry Array: per restriction type expiration
2763 * @param $user User The user updating the restrictions
2764 * @return bool true on success
2766 public function updateRestrictions(
2767 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2771 $user = is_null( $user ) ?
$wgUser : $user;
2773 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2777 * @deprecated since 1.18
2779 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2780 wfDeprecated( __METHOD__
, '1.18' );
2782 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2786 * @deprecated since 1.18
2788 public function viewUpdates() {
2789 wfDeprecated( __METHOD__
, '1.18' );
2791 return $this->doViewUpdates( $wgUser );
2795 * @deprecated since 1.18
2797 public function useParserCache( $oldid ) {
2798 wfDeprecated( __METHOD__
, '1.18' );
2800 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2804 class PoolWorkArticleView
extends PoolCounterWork
{
2822 * @var ParserOptions
2824 private $parserOptions;
2832 * @var ParserOutput|false
2834 private $parserOutput = false;
2839 private $isDirty = false;
2844 private $error = false;
2850 * @param $revid Integer: ID of the revision being parsed
2851 * @param $useParserCache Boolean: whether to use the parser cache
2852 * @param $parserOptions parserOptions to use for the parse operation
2853 * @param $text String: text to parse or null to load it
2855 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2856 $this->page
= $page;
2857 $this->revid
= $revid;
2858 $this->cacheable
= $useParserCache;
2859 $this->parserOptions
= $parserOptions;
2860 $this->text
= $text;
2861 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2862 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2866 * Get the ParserOutput from this object, or false in case of failure
2868 * @return ParserOutput
2870 public function getParserOutput() {
2871 return $this->parserOutput
;
2875 * Get whether the ParserOutput is a dirty one (i.e. expired)
2879 public function getIsDirty() {
2880 return $this->isDirty
;
2884 * Get a Status object in case of error or false otherwise
2886 * @return Status|false
2888 public function getError() {
2889 return $this->error
;
2896 global $wgParser, $wgUseFileCache;
2898 $isCurrent = $this->revid
=== $this->page
->getLatest();
2900 if ( $this->text
!== null ) {
2901 $text = $this->text
;
2902 } elseif ( $isCurrent ) {
2903 $text = $this->page
->getRawText();
2905 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2906 if ( $rev === null ) {
2909 $text = $rev->getText();
2912 $time = - microtime( true );
2913 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2914 $this->parserOptions
, true, true, $this->revid
);
2915 $time +
= microtime( true );
2919 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2920 $this->page
->getTitle()->getPrefixedDBkey() ) );
2923 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2924 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2927 // Make sure file cache is not used on uncacheable content.
2928 // Output that has magic words in it can still use the parser cache
2929 // (if enabled), though it will generally expire sooner.
2930 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2931 $wgUseFileCache = false;
2935 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2944 function getCachedWork() {
2945 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2947 if ( $this->parserOutput
=== false ) {
2948 wfDebug( __METHOD__
. ": parser cache miss\n" );
2951 wfDebug( __METHOD__
. ": parser cache hit\n" );
2959 function fallback() {
2960 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2962 if ( $this->parserOutput
=== false ) {
2963 wfDebugLog( 'dirty', "dirty missing\n" );
2964 wfDebug( __METHOD__
. ": no dirty cache\n" );
2967 wfDebug( __METHOD__
. ": sending dirty output\n" );
2968 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2969 $this->isDirty
= true;
2975 * @param $status Status
2977 function error( $status ) {
2978 $this->error
= $status;