3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
8 * Class representing a MediaWiki article and history.
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
13 * @internal documentation reviewed 15 Mar 2010
15 class WikiPage
extends Page
{
19 public $mTitle = null;
24 public $mDataLoaded = false; // !< Boolean
25 public $mIsRedirect = false; // !< Boolean
26 public $mLatest = false; // !< Integer (false means "not loaded")
27 public $mPreparedEdit = false; // !< Array
33 protected $mRedirectTarget = null;
38 protected $mLastRevision = null;
41 * @var string; timestamp of the current revision or empty string if not loaded
43 protected $mTimestamp = '';
46 * Constructor and clear the article
47 * @param $title Title Reference to a Title object.
49 public function __construct( Title
$title ) {
50 $this->mTitle
= $title;
54 * Create a WikiPage object of the appropriate class for the given title.
57 * @return WikiPage object of the appropriate type
59 public static function factory( Title
$title ) {
60 $ns = $title->getNamespace();
62 if ( $ns == NS_MEDIA
) {
63 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
64 } elseif ( $ns < 0 ) {
65 throw new MWException( "Invalid or virtual namespace $ns given." );
70 $page = new WikiFilePage( $title );
73 $page = new WikiCategoryPage( $title );
76 $page = new WikiPage( $title );
83 * Constructor from a page id
85 * @param $id Int article ID to load
89 public static function newFromID( $id ) {
90 $t = Title
::newFromID( $id );
92 return self
::factory( $t );
98 * Returns overrides for action handlers.
99 * Classes listed here will be used instead of the default one when
100 * (and only when) $wgActions[$action] === true. This allows subclasses
101 * to override the default behavior.
103 * @todo: move this UI stuff somewhere else
107 public function getActionOverrides() {
112 * If this page is a redirect, get its target
114 * The target will be fetched from the redirect table if possible.
115 * If this page doesn't have an entry there, call insertRedirect()
116 * @return Title|mixed object, or null if this page is not a redirect
118 public function getRedirectTarget() {
119 if ( !$this->mTitle
->isRedirect() ) {
123 if ( $this->mRedirectTarget
!== null ) {
124 return $this->mRedirectTarget
;
127 # Query the redirect table
128 $dbr = wfGetDB( DB_SLAVE
);
129 $row = $dbr->selectRow( 'redirect',
130 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
131 array( 'rd_from' => $this->getId() ),
135 // rd_fragment and rd_interwiki were added later, populate them if empty
136 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
137 return $this->mRedirectTarget
= Title
::makeTitle(
138 $row->rd_namespace
, $row->rd_title
,
139 $row->rd_fragment
, $row->rd_interwiki
);
142 # This page doesn't have an entry in the redirect table
143 return $this->mRedirectTarget
= $this->insertRedirect();
147 * Insert an entry for this page into the redirect table.
149 * Don't call this function directly unless you know what you're doing.
150 * @return Title object or null if not a redirect
152 public function insertRedirect() {
153 // recurse through to only get the final target
154 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
158 $this->insertRedirectEntry( $retval );
163 * Insert or update the redirect table entry for this page to indicate
164 * it redirects to $rt .
165 * @param $rt Title redirect target
167 public function insertRedirectEntry( $rt ) {
168 $dbw = wfGetDB( DB_MASTER
);
169 $dbw->replace( 'redirect', array( 'rd_from' ),
171 'rd_from' => $this->getId(),
172 'rd_namespace' => $rt->getNamespace(),
173 'rd_title' => $rt->getDBkey(),
174 'rd_fragment' => $rt->getFragment(),
175 'rd_interwiki' => $rt->getInterwiki(),
182 * Get the Title object or URL this page redirects to
184 * @return mixed false, Title of in-wiki target, or string with URL
186 public function followRedirect() {
187 return $this->getRedirectURL( $this->getRedirectTarget() );
191 * Get the Title object or URL to use for a redirect. We use Title
192 * objects for same-wiki, non-special redirects and URLs for everything
194 * @param $rt Title Redirect target
195 * @return mixed false, Title object of local target, or string with URL
197 public function getRedirectURL( $rt ) {
199 if ( $rt->getInterwiki() != '' ) {
200 if ( $rt->isLocal() ) {
201 // Offsite wikis need an HTTP redirect.
203 // This can be hard to reverse and may produce loops,
204 // so they may be disabled in the site configuration.
205 $source = $this->mTitle
->getFullURL( 'redirect=no' );
206 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
209 if ( $rt->isSpecialPage() ) {
210 // Gotta handle redirects to special pages differently:
211 // Fill the HTTP response "Location" header and ignore
212 // the rest of the page we're on.
214 // This can be hard to reverse, so they may be disabled.
215 if ( $rt->isSpecial( 'Userlogout' ) ) {
218 return $rt->getFullURL();
226 // No or invalid redirect
231 * Get the title object of the article
232 * @return Title object of this page
234 public function getTitle() {
235 return $this->mTitle
;
241 public function clear() {
242 $this->mDataLoaded
= false;
244 $this->mRedirectTarget
= null; # Title object if set
245 $this->mLastRevision
= null; # Latest revision
246 $this->mTimestamp
= '';
247 $this->mIsRedirect
= false;
248 $this->mLatest
= false;
249 $this->mPreparedEdit
= false;
253 * Get the text that needs to be saved in order to undo all revisions
254 * between $undo and $undoafter. Revisions must belong to the same page,
255 * must exist and must not be deleted
256 * @param $undo Revision
257 * @param $undoafter Revision Must be an earlier revision than $undo
258 * @return mixed string on success, false on failure
260 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
261 $cur_text = $this->getRawText();
262 if ( $cur_text === false ) {
263 return false; // no page
265 $undo_text = $undo->getText();
266 $undoafter_text = $undoafter->getText();
268 if ( $cur_text == $undo_text ) {
269 # No use doing a merge if it's just a straight revert.
270 return $undoafter_text;
275 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
283 * Return the list of revision fields that should be selected to create
288 public static function selectFields() {
305 * Fetch a page record with the given conditions
306 * @param $dbr DatabaseBase object
307 * @param $conditions Array
308 * @return mixed Database result resource, or false on failure
310 protected function pageData( $dbr, $conditions ) {
311 $fields = self
::selectFields();
313 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
315 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
317 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
323 * Fetch a page record matching the Title object's namespace and title
324 * using a sanitized title string
326 * @param $dbr DatabaseBase object
327 * @param $title Title object
328 * @return mixed Database result resource, or false on failure
330 public function pageDataFromTitle( $dbr, $title ) {
331 return $this->pageData( $dbr, array(
332 'page_namespace' => $title->getNamespace(),
333 'page_title' => $title->getDBkey() ) );
337 * Fetch a page record matching the requested ID
339 * @param $dbr DatabaseBase
341 * @return mixed Database result resource, or false on failure
343 public function pageDataFromId( $dbr, $id ) {
344 return $this->pageData( $dbr, array( 'page_id' => $id ) );
348 * Set the general counter, title etc data loaded from
351 * @param $data Object|String One of the following:
352 * A DB query result object or...
353 * "fromdb" to get from a slave DB or...
354 * "fromdbmaster" to get from the master DB
357 public function loadPageData( $data = 'fromdb' ) {
358 # If we get a DB row, God knows from where it comes
361 if ( $data === 'fromdbmaster' ) {
362 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
364 } elseif ( $data === 'fromdb' ) { // slave
365 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
366 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
367 # Note that DB also stores the master position in the session and checks it.
368 $touched = $this->getCachedLastEditTime();
369 if ( $touched ) { // key set
370 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
371 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
377 $this->mTitle
->loadFromRow( $data, $fromMaster );
380 $this->mIsRedirect
= intval( $data->page_is_redirect
);
381 $this->mLatest
= intval( $data->page_latest
);
384 $this->mDataLoaded
= true;
388 * @return int Page ID
390 public function getId() {
391 return $this->mTitle
->getArticleID();
395 * @return bool Whether or not the page exists in the database
397 public function exists() {
398 return $this->mTitle
->exists();
402 * Check if this page is something we're going to be showing
403 * some sort of sensible content for. If we return false, page
404 * views (plain action=view) will return an HTTP 404 response,
405 * so spiders and robots can know they're following a bad link.
409 public function hasViewableContent() {
410 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
414 * Get the number of views of this page
416 * @return int The view count for the page
418 public function getCount() {
419 return $this->mTitle
->getCount();
423 * Determine whether a page would be suitable for being counted as an
424 * article in the site_stats table based on the title & its content
426 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
427 * if false, the current database state will be used
430 public function isCountable( $editInfo = false ) {
431 global $wgArticleCountMethod;
433 if ( !$this->mTitle
->isContentPage() ) {
437 $text = $editInfo ?
$editInfo->pst
: false;
439 if ( $this->isRedirect( $text ) ) {
443 switch ( $wgArticleCountMethod ) {
447 if ( $text === false ) {
448 $text = $this->getRawText();
450 return strpos( $text, ',' ) !== false;
453 // ParserOutput::getLinks() is a 2D array of page links, so
454 // to be really correct we would need to recurse in the array
455 // but the main array should only have items in it if there are
457 return (bool)count( $editInfo->output
->getLinks() );
459 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
460 array( 'pl_from' => $this->getId() ), __METHOD__
);
466 * Tests if the article text represents a redirect
468 * @param $text mixed string containing article contents, or boolean
471 public function isRedirect( $text = false ) {
472 if ( $text === false ) {
473 if ( !$this->mDataLoaded
) {
474 $this->loadPageData();
477 return (bool)$this->mIsRedirect
;
479 return Title
::newFromRedirect( $text ) !== null;
484 * Loads page_touched and returns a value indicating if it should be used
485 * @return boolean true if not a redirect
487 public function checkTouched() {
488 if ( !$this->mDataLoaded
) {
489 $this->loadPageData();
491 return !$this->mIsRedirect
;
495 * Get the page_touched field
496 * @return string containing GMT timestamp
498 public function getTouched() {
499 if ( !$this->mDataLoaded
) {
500 $this->loadPageData();
502 $timestamp = $this->mTitle
->getTouched();
503 if ( $timestamp === false ) {
504 $timestamp = '19700101000000';
510 * Get the page_latest field
511 * @return integer rev_id of current revision
513 public function getLatest() {
514 if ( !$this->mDataLoaded
) {
515 $this->loadPageData();
517 return (int)$this->mLatest
;
521 * Loads everything except the text
522 * This isn't necessary for all uses, so it's only done if needed.
524 protected function loadLastEdit() {
525 if ( $this->mLastRevision
!== null ) {
526 return; // already loaded
529 $latest = $this->getLatest();
531 return; // page doesn't exist or is missing page_latest info
534 $revision = Revision
::newFromPageId( $this->getId(), $latest );
535 if ( $revision ) { // sanity
536 $this->setLastEdit( $revision );
541 * Set the latest revision
543 protected function setLastEdit( Revision
$revision ) {
544 $this->mLastRevision
= $revision;
545 $this->mTimestamp
= $revision->getTimestamp();
549 * Get the latest revision
550 * @return Revision|null
552 public function getRevision() {
553 $this->loadLastEdit();
554 if ( $this->mLastRevision
) {
555 return $this->mLastRevision
;
561 * Get the text of the current revision. No side-effects...
563 * @param $audience Integer: one of:
564 * Revision::FOR_PUBLIC to be displayed to all users
565 * Revision::FOR_THIS_USER to be displayed to $wgUser
566 * Revision::RAW get the text regardless of permissions
567 * @return String|false The text of the current revision
569 public function getText( $audience = Revision
::FOR_PUBLIC
) {
570 $this->loadLastEdit();
571 if ( $this->mLastRevision
) {
572 return $this->mLastRevision
->getText( $audience );
578 * Get the text of the current revision. No side-effects...
580 * @return String|false The text of the current revision
582 public function getRawText() {
583 $this->loadLastEdit();
584 if ( $this->mLastRevision
) {
585 return $this->mLastRevision
->getRawText();
591 * @return string MW timestamp of last article revision
593 public function getTimestamp() {
594 // Check if the field has been filled by WikiPage::setTimestamp()
595 if ( !$this->mTimestamp
) {
596 $this->loadLastEdit();
598 return wfTimestamp( TS_MW
, $this->mTimestamp
);
602 * Set the page timestamp (use only to avoid DB queries)
603 * @param $ts string MW timestamp of last article revision
606 public function setTimestamp( $ts ) {
607 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
611 * @param $audience Integer: one of:
612 * Revision::FOR_PUBLIC to be displayed to all users
613 * Revision::FOR_THIS_USER to be displayed to $wgUser
614 * Revision::RAW get the text regardless of permissions
615 * @return int user ID for the user that made the last article revision
617 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
618 $this->loadLastEdit();
619 if ( $this->mLastRevision
) {
620 return $this->mLastRevision
->getUser( $audience );
627 * @param $audience Integer: one of:
628 * Revision::FOR_PUBLIC to be displayed to all users
629 * Revision::FOR_THIS_USER to be displayed to $wgUser
630 * Revision::RAW get the text regardless of permissions
631 * @return string username of the user that made the last article revision
633 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
634 $this->loadLastEdit();
635 if ( $this->mLastRevision
) {
636 return $this->mLastRevision
->getUserText( $audience );
643 * @param $audience Integer: one of:
644 * Revision::FOR_PUBLIC to be displayed to all users
645 * Revision::FOR_THIS_USER to be displayed to $wgUser
646 * Revision::RAW get the text regardless of permissions
647 * @return string Comment stored for the last article revision
649 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
650 $this->loadLastEdit();
651 if ( $this->mLastRevision
) {
652 return $this->mLastRevision
->getComment( $audience );
659 * Returns true if last revision was marked as "minor edit"
661 * @return boolean Minor edit indicator for the last article revision.
663 public function getMinorEdit() {
664 $this->loadLastEdit();
665 if ( $this->mLastRevision
) {
666 return $this->mLastRevision
->isMinor();
673 * Get the cached timestamp for the last time the page changed.
674 * This is only used to help handle slave lag by comparing to page_touched.
675 * @return string MW timestamp
677 protected function getCachedLastEditTime() {
679 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
680 return $wgMemc->get( $key );
684 * Set the cached timestamp for the last time the page changed.
685 * This is only used to help handle slave lag by comparing to page_touched.
686 * @param $timestamp string
689 public function setCachedLastEditTime( $timestamp ) {
691 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
692 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
696 * Get a list of users who have edited this article, not including the user who made
697 * the most recent revision, which you can get from $article->getUser() if you want it
698 * @return UserArrayFromResult
700 public function getContributors() {
701 # @todo FIXME: This is expensive; cache this info somewhere.
703 $dbr = wfGetDB( DB_SLAVE
);
705 if ( $dbr->implicitGroupby() ) {
706 $realNameField = 'user_real_name';
708 $realNameField = 'MIN(user_real_name) AS user_real_name';
711 $tables = array( 'revision', 'user' );
714 'rev_user as user_id',
715 'rev_user_text AS user_name',
717 'MAX(rev_timestamp) AS timestamp',
720 $conds = array( 'rev_page' => $this->getId() );
722 // The user who made the top revision gets credited as "this page was last edited by
723 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
724 $user = $this->getUser();
726 $conds[] = "rev_user != $user";
728 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
731 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
734 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
738 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
739 'ORDER BY' => 'timestamp DESC',
742 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
743 return new UserArrayFromResult( $res );
747 * Get the last N authors
748 * @param $num Integer: number of revisions to get
749 * @param $revLatest String: the latest rev_id, selected from the master (optional)
750 * @return array Array of authors, duplicates not removed
752 public function getLastNAuthors( $num, $revLatest = 0 ) {
753 wfProfileIn( __METHOD__
);
754 // First try the slave
755 // If that doesn't have the latest revision, try the master
757 $db = wfGetDB( DB_SLAVE
);
760 $res = $db->select( array( 'page', 'revision' ),
761 array( 'rev_id', 'rev_user_text' ),
763 'page_namespace' => $this->mTitle
->getNamespace(),
764 'page_title' => $this->mTitle
->getDBkey(),
768 'ORDER BY' => 'rev_timestamp DESC',
774 wfProfileOut( __METHOD__
);
778 $row = $db->fetchObject( $res );
780 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
781 $db = wfGetDB( DB_MASTER
);
786 } while ( $continue );
788 $authors = array( $row->rev_user_text
);
790 foreach ( $res as $row ) {
791 $authors[] = $row->rev_user_text
;
794 wfProfileOut( __METHOD__
);
799 * Should the parser cache be used?
801 * @param $parserOptions ParserOptions to check
805 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
806 global $wgEnableParserCache;
808 return $wgEnableParserCache
809 && $parserOptions->getStubThreshold() == 0
810 && $this->mTitle
->exists()
811 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
812 && $this->mTitle
->isWikitextPage();
816 * Get a ParserOutput for the given ParserOptions and revision ID.
817 * The parser cache will be used if possible.
820 * @param $parserOptions ParserOptions to use for the parse operation
821 * @param $oldid Revision ID to get the text from, passing null or 0 will
822 * get the current revision (default value)
823 * @return ParserOutput or false if the revision was not found
825 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
826 wfProfileIn( __METHOD__
);
828 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
829 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
830 if ( $parserOptions->getStubThreshold() ) {
831 wfIncrStats( 'pcache_miss_stub' );
834 if ( $useParserCache ) {
835 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
836 if ( $parserOutput !== false ) {
837 wfProfileOut( __METHOD__
);
838 return $parserOutput;
842 if ( $oldid === null ||
$oldid === 0 ) {
843 $oldid = $this->getLatest();
846 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
849 wfProfileOut( __METHOD__
);
851 return $pool->getParserOutput();
855 * Do standard deferred updates after page view
856 * @param $user User The relevant user
858 public function doViewUpdates( User
$user ) {
859 global $wgDisableCounters;
860 if ( wfReadOnly() ) {
864 # Don't update page view counters on views from bot users (bug 14044)
865 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
866 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
867 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
870 # Update newtalk / watchlist notification status
871 $user->clearNotification( $this->mTitle
);
875 * Perform the actions of a page purging
877 public function doPurge() {
880 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
884 // Invalidate the cache
885 $this->mTitle
->invalidateCache();
889 // Commit the transaction before the purge is sent
890 $dbw = wfGetDB( DB_MASTER
);
894 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
898 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
899 if ( $this->mTitle
->exists() ) {
900 $text = $this->getRawText();
905 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
911 * Insert a new empty page record for this article.
912 * This *must* be followed up by creating a revision
913 * and running $this->updateRevisionOn( ... );
914 * or else the record will be left in a funky state.
915 * Best if all done inside a transaction.
917 * @param $dbw DatabaseBase
918 * @return int The newly created page_id key, or false if the title already existed
920 public function insertOn( $dbw ) {
921 wfProfileIn( __METHOD__
);
923 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
924 $dbw->insert( 'page', array(
925 'page_id' => $page_id,
926 'page_namespace' => $this->mTitle
->getNamespace(),
927 'page_title' => $this->mTitle
->getDBkey(),
929 'page_restrictions' => '',
930 'page_is_redirect' => 0, # Will set this shortly...
932 'page_random' => wfRandom(),
933 'page_touched' => $dbw->timestamp(),
934 'page_latest' => 0, # Fill this in shortly...
935 'page_len' => 0, # Fill this in shortly...
936 ), __METHOD__
, 'IGNORE' );
938 $affected = $dbw->affectedRows();
941 $newid = $dbw->insertId();
942 $this->mTitle
->resetArticleID( $newid );
944 wfProfileOut( __METHOD__
);
946 return $affected ?
$newid : false;
950 * Update the page record to point to a newly saved revision.
952 * @param $dbw DatabaseBase: object
953 * @param $revision Revision: For ID number, and text used to set
954 * length and redirect status fields
955 * @param $lastRevision Integer: if given, will not overwrite the page field
956 * when different from the currently set value.
957 * Giving 0 indicates the new page flag should be set
959 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
960 * removing rows in redirect table.
961 * @return bool true on success, false on failure
964 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
965 wfProfileIn( __METHOD__
);
967 $text = $revision->getText();
968 $len = strlen( $text );
969 $rt = Title
::newFromRedirectRecurse( $text );
971 $conditions = array( 'page_id' => $this->getId() );
973 if ( !is_null( $lastRevision ) ) {
974 # An extra check against threads stepping on each other
975 $conditions['page_latest'] = $lastRevision;
978 $now = wfTimestampNow();
979 $dbw->update( 'page',
981 'page_latest' => $revision->getId(),
982 'page_touched' => $dbw->timestamp( $now ),
983 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
984 'page_is_redirect' => $rt !== null ?
1 : 0,
990 $result = $dbw->affectedRows() != 0;
992 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
993 $this->setLastEdit( $revision );
994 $this->setCachedLastEditTime( $now );
995 $this->mLatest
= $revision->getId();
996 $this->mIsRedirect
= (bool)$rt;
997 # Update the LinkCache.
998 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1001 wfProfileOut( __METHOD__
);
1006 * Add row to the redirect table if this is a redirect, remove otherwise.
1008 * @param $dbw DatabaseBase
1009 * @param $redirectTitle Title object pointing to the redirect target,
1010 * or NULL if this is not a redirect
1011 * @param $lastRevIsRedirect If given, will optimize adding and
1012 * removing rows in redirect table.
1013 * @return bool true on success, false on failure
1016 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1017 // Always update redirects (target link might have changed)
1018 // Update/Insert if we don't know if the last revision was a redirect or not
1019 // Delete if changing from redirect to non-redirect
1020 $isRedirect = !is_null( $redirectTitle );
1022 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1026 wfProfileIn( __METHOD__
);
1027 if ( $isRedirect ) {
1028 $this->insertRedirectEntry( $redirectTitle );
1030 // This is not a redirect, remove row from redirect table
1031 $where = array( 'rd_from' => $this->getId() );
1032 $dbw->delete( 'redirect', $where, __METHOD__
);
1035 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1036 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1038 wfProfileOut( __METHOD__
);
1040 return ( $dbw->affectedRows() != 0 );
1044 * If the given revision is newer than the currently set page_latest,
1045 * update the page record. Otherwise, do nothing.
1047 * @param $dbw Database object
1048 * @param $revision Revision object
1051 public function updateIfNewerOn( $dbw, $revision ) {
1052 wfProfileIn( __METHOD__
);
1054 $row = $dbw->selectRow(
1055 array( 'revision', 'page' ),
1056 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1058 'page_id' => $this->getId(),
1059 'page_latest=rev_id' ),
1063 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1064 wfProfileOut( __METHOD__
);
1067 $prev = $row->rev_id
;
1068 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1070 # No or missing previous revision; mark the page as new
1072 $lastRevIsRedirect = null;
1075 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1077 wfProfileOut( __METHOD__
);
1082 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1083 * @param $text String: new text of the section
1084 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1085 * @param $edittime String: revision timestamp or null to use the current revision
1086 * @return string Complete article text, or null if error
1088 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1089 wfProfileIn( __METHOD__
);
1091 if ( strval( $section ) == '' ) {
1092 // Whole-page edit; let the whole text through
1094 // Bug 30711: always use current version when adding a new section
1095 if ( is_null( $edittime ) ||
$section == 'new' ) {
1096 $oldtext = $this->getRawText();
1097 if ( $oldtext === false ) {
1098 wfDebug( __METHOD__
. ": no page text\n" );
1102 $dbw = wfGetDB( DB_MASTER
);
1103 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1106 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1107 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1108 wfProfileOut( __METHOD__
);
1112 $oldtext = $rev->getText();
1115 if ( $section == 'new' ) {
1116 # Inserting a new section
1117 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1118 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1119 $text = strlen( trim( $oldtext ) ) > 0
1120 ?
"{$oldtext}\n\n{$subject}{$text}"
1121 : "{$subject}{$text}";
1124 # Replacing an existing section; roll out the big guns
1127 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1131 wfProfileOut( __METHOD__
);
1136 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1138 * @return Int updated $flags
1140 function checkFlags( $flags ) {
1141 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1142 if ( $this->mTitle
->getArticleID() ) {
1143 $flags |
= EDIT_UPDATE
;
1153 * Change an existing article or create a new article. Updates RC and all necessary caches,
1154 * optionally via the deferred update array.
1156 * @param $text String: new text
1157 * @param $summary String: edit summary
1158 * @param $flags Integer bitfield:
1160 * Article is known or assumed to be non-existent, create a new one
1162 * Article is known or assumed to be pre-existing, update it
1164 * Mark this edit minor, if the user is allowed to do so
1166 * Do not log the change in recentchanges
1168 * Mark the edit a "bot" edit regardless of user rights
1169 * EDIT_DEFER_UPDATES
1170 * Defer some of the updates until the end of index.php
1172 * Fill in blank summaries with generated text where possible
1174 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1175 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1176 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1177 * edit-already-exists error will be returned. These two conditions are also possible with
1178 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1180 * @param $baseRevId the revision ID this edit was based off, if any
1181 * @param $user User the user doing the edit
1183 * @return Status object. Possible errors:
1184 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1185 * edit-gone-missing: In update mode, but the article didn't exist
1186 * edit-conflict: In update mode, the article changed unexpectedly
1187 * edit-no-change: Warning that the text was the same as before
1188 * edit-already-exists: In creation mode, but the article already exists
1190 * Extensions may define additional errors.
1192 * $return->value will contain an associative array with members as follows:
1193 * new: Boolean indicating if the function attempted to create a new article
1194 * revision: The revision object for the inserted revision, or null
1196 * Compatibility note: this function previously returned a boolean value indicating success/failure
1198 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1199 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1201 # Low-level sanity check
1202 if ( $this->mTitle
->getText() === '' ) {
1203 throw new MWException( 'Something is trying to edit an article with an empty title' );
1206 wfProfileIn( __METHOD__
);
1208 $user = is_null( $user ) ?
$wgUser : $user;
1209 $status = Status
::newGood( array() );
1211 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1212 $this->loadPageData( 'fromdbmaster' );
1214 $flags = $this->checkFlags( $flags );
1216 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1217 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1219 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1221 if ( $status->isOK() ) {
1222 $status->fatal( 'edit-hook-aborted' );
1225 wfProfileOut( __METHOD__
);
1229 # Silently ignore EDIT_MINOR if not allowed
1230 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1231 $bot = $flags & EDIT_FORCE_BOT
;
1233 $oldtext = $this->getRawText(); // current revision
1234 $oldsize = strlen( $oldtext );
1235 $oldid = $this->getLatest();
1236 $oldIsRedirect = $this->isRedirect();
1237 $oldcountable = $this->isCountable();
1239 # Provide autosummaries if one is not provided and autosummaries are enabled.
1240 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1241 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1244 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1245 $text = $editInfo->pst
;
1246 $newsize = strlen( $text );
1248 $dbw = wfGetDB( DB_MASTER
);
1249 $now = wfTimestampNow();
1250 $this->mTimestamp
= $now;
1252 if ( $flags & EDIT_UPDATE
) {
1253 # Update article, but only if changed.
1254 $status->value
['new'] = false;
1256 # Make sure the revision is either completely inserted or not inserted at all
1257 if ( !$wgDBtransactions ) {
1258 $userAbort = ignore_user_abort( true );
1261 $revision = new Revision( array(
1262 'page' => $this->getId(),
1263 'comment' => $summary,
1264 'minor_edit' => $isminor,
1266 'parent_id' => $oldid,
1267 'user' => $user->getId(),
1268 'user_text' => $user->getName(),
1272 $changed = ( strcmp( $text, $oldtext ) != 0 );
1275 if ( !$this->mLatest
) {
1276 # Article gone missing
1277 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1278 $status->fatal( 'edit-gone-missing' );
1280 wfProfileOut( __METHOD__
);
1285 $revisionId = $revision->insertOn( $dbw );
1289 # Note that we use $this->mLatest instead of fetching a value from the master DB
1290 # during the course of this function. This makes sure that EditPage can detect
1291 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1292 # before this function is called. A previous function used a separate query, this
1293 # creates a window where concurrent edits can cause an ignored edit conflict.
1294 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1297 /* Belated edit conflict! Run away!! */
1298 $status->fatal( 'edit-conflict' );
1300 # Delete the invalid revision if the DB is not transactional
1301 if ( !$wgDBtransactions ) {
1302 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1308 global $wgUseRCPatrol;
1309 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1310 # Update recentchanges
1311 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1312 # Mark as patrolled if the user can do so
1313 $patrolled = $wgUseRCPatrol && !count(
1314 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1315 # Add RC row to the DB
1316 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1317 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1318 $revisionId, $patrolled
1321 # Log auto-patrolled edits
1323 PatrolLog
::record( $rc, true );
1326 $user->incEditCount();
1331 if ( !$wgDBtransactions ) {
1332 ignore_user_abort( $userAbort );
1335 // Now that ignore_user_abort is restored, we can respond to fatal errors
1336 if ( !$status->isOK() ) {
1337 wfProfileOut( __METHOD__
);
1341 # Update links tables, site stats, etc.
1342 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1343 'oldcountable' => $oldcountable ) );
1346 $status->warning( 'edit-no-change' );
1348 // Keep the same revision ID, but do some updates on it
1349 $revisionId = $this->getLatest();
1350 // Update page_touched, this is usually implicit in the page update
1351 // Other cache updates are done in onArticleEdit()
1352 $this->mTitle
->invalidateCache();
1355 # Create new article
1356 $status->value
['new'] = true;
1360 # Add the page record; stake our claim on this title!
1361 # This will return false if the article already exists
1362 $newid = $this->insertOn( $dbw );
1364 if ( $newid === false ) {
1366 $status->fatal( 'edit-already-exists' );
1368 wfProfileOut( __METHOD__
);
1372 # Save the revision text...
1373 $revision = new Revision( array(
1375 'comment' => $summary,
1376 'minor_edit' => $isminor,
1378 'user' => $user->getId(),
1379 'user_text' => $user->getName(),
1382 $revisionId = $revision->insertOn( $dbw );
1384 # Update the page record with revision data
1385 $this->updateRevisionOn( $dbw, $revision, 0 );
1387 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1389 # Update recentchanges
1390 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1391 global $wgUseRCPatrol, $wgUseNPPatrol;
1393 # Mark as patrolled if the user can do so
1394 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1395 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1396 # Add RC row to the DB
1397 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1398 '', strlen( $text ), $revisionId, $patrolled );
1400 # Log auto-patrolled edits
1402 PatrolLog
::record( $rc, true );
1405 $user->incEditCount();
1408 # Update links, etc.
1409 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1411 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1412 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1415 # Do updates right now unless deferral was requested
1416 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1417 DeferredUpdates
::doUpdates();
1420 // Return the new revision (or null) to the caller
1421 $status->value
['revision'] = $revision;
1423 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1424 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1426 # Promote user to any groups they meet the criteria for
1427 $user->addAutopromoteOnceGroups( 'onEdit' );
1429 wfProfileOut( __METHOD__
);
1434 * Get parser options suitable for rendering the primary article wikitext
1435 * @param User|string $user User object or 'canonical'
1436 * @return ParserOptions
1438 public function makeParserOptions( $user ) {
1440 if ( $user instanceof User
) { // settings per user (even anons)
1441 $options = ParserOptions
::newFromUser( $user );
1442 } else { // canonical settings
1443 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1445 $options->enableLimitReport(); // show inclusion/loop reports
1446 $options->setTidy( true ); // fix bad HTML
1451 * Prepare text which is about to be saved.
1452 * Returns a stdclass with source, pst and output members
1454 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1455 global $wgParser, $wgContLang, $wgUser;
1456 $user = is_null( $user ) ?
$wgUser : $user;
1457 // @TODO fixme: check $user->getId() here???
1458 if ( $this->mPreparedEdit
1459 && $this->mPreparedEdit
->newText
== $text
1460 && $this->mPreparedEdit
->revid
== $revid
1463 return $this->mPreparedEdit
;
1466 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1467 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1469 $edit = (object)array();
1470 $edit->revid
= $revid;
1471 $edit->newText
= $text;
1472 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1473 $edit->popts
= $this->makeParserOptions( 'canonical' );
1474 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1475 $edit->oldText
= $this->getRawText();
1477 $this->mPreparedEdit
= $edit;
1483 * Do standard deferred updates after page edit.
1484 * Update links tables, site stats, search index and message cache.
1485 * Purges pages that include this page if the text was changed here.
1486 * Every 100th edit, prune the recent changes table.
1489 * @param $revision Revision object
1490 * @param $user User object that did the revision
1491 * @param $options Array of options, following indexes are used:
1492 * - changed: boolean, whether the revision changed the content (default true)
1493 * - created: boolean, whether the revision created the page (default false)
1494 * - oldcountable: boolean or null (default null):
1495 * - boolean: whether the page was counted as an article before that
1496 * revision, only used in changed is true and created is false
1497 * - null: don't change the article count
1499 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1500 global $wgEnableParserCache;
1502 wfProfileIn( __METHOD__
);
1504 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1505 $text = $revision->getText();
1508 # Be careful not to double-PST: $text is usually already PST-ed once
1509 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1510 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1511 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1513 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1514 $editInfo = $this->mPreparedEdit
;
1517 # Save it to the parser cache
1518 if ( $wgEnableParserCache ) {
1519 $parserCache = ParserCache
::singleton();
1520 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1523 # Update the links tables
1524 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1527 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1529 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1530 if ( 0 == mt_rand( 0, 99 ) ) {
1531 // Flush old entries from the `recentchanges` table; we do this on
1532 // random requests so as to avoid an increase in writes for no good reason
1535 $dbw = wfGetDB( DB_MASTER
);
1536 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1539 array( "rc_timestamp < '$cutoff'" ),
1545 if ( !$this->mTitle
->exists() ) {
1546 wfProfileOut( __METHOD__
);
1550 $id = $this->getId();
1551 $title = $this->mTitle
->getPrefixedDBkey();
1552 $shortTitle = $this->mTitle
->getDBkey();
1554 if ( !$options['changed'] ) {
1557 } elseif ( $options['created'] ) {
1558 $good = (int)$this->isCountable( $editInfo );
1560 } elseif ( $options['oldcountable'] !== null ) {
1561 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1568 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1569 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1571 # If this is another user's talk page, update newtalk.
1572 # Don't do this if $options['changed'] = false (null-edits) nor if
1573 # it's a minor edit and the user doesn't want notifications for those.
1574 if ( $options['changed']
1575 && $this->mTitle
->getNamespace() == NS_USER_TALK
1576 && $shortTitle != $user->getTitleKey()
1577 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1579 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1580 $other = User
::newFromName( $shortTitle, false );
1582 wfDebug( __METHOD__
. ": invalid username\n" );
1583 } elseif ( User
::isIP( $shortTitle ) ) {
1584 // An anonymous user
1585 $other->setNewtalk( true );
1586 } elseif ( $other->isLoggedIn() ) {
1587 $other->setNewtalk( true );
1589 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1594 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1595 MessageCache
::singleton()->replace( $shortTitle, $text );
1598 if( $options['created'] ) {
1599 self
::onArticleCreate( $this->mTitle
);
1601 self
::onArticleEdit( $this->mTitle
);
1604 wfProfileOut( __METHOD__
);
1608 * Edit an article without doing all that other stuff
1609 * The article must already exist; link tables etc
1610 * are not updated, caches are not flushed.
1612 * @param $text String: text submitted
1613 * @param $user User The relevant user
1614 * @param $comment String: comment submitted
1615 * @param $minor Boolean: whereas it's a minor modification
1617 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1618 wfProfileIn( __METHOD__
);
1620 $dbw = wfGetDB( DB_MASTER
);
1621 $revision = new Revision( array(
1622 'page' => $this->getId(),
1624 'comment' => $comment,
1625 'minor_edit' => $minor ?
1 : 0,
1627 $revision->insertOn( $dbw );
1628 $this->updateRevisionOn( $dbw, $revision );
1630 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1632 wfProfileOut( __METHOD__
);
1636 * Update the article's restriction field, and leave a log entry.
1637 * This works for protection both existing and non-existing pages.
1639 * @param $limit Array: set of restriction keys
1640 * @param $reason String
1641 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1642 * @param $expiry Array: per restriction type expiration
1643 * @param $user User The user updating the restrictions
1644 * @return bool true on success
1646 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1649 if ( wfReadOnly() ) {
1650 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1653 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1655 $id = $this->mTitle
->getArticleID();
1661 // Take this opportunity to purge out expired restrictions
1662 Title
::purgeExpiredRestrictions();
1664 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1665 # we expect a single selection, but the schema allows otherwise.
1666 $isProtected = false;
1670 $dbw = wfGetDB( DB_MASTER
);
1672 foreach ( $restrictionTypes as $action ) {
1673 if ( !isset( $expiry[$action] ) ) {
1674 $expiry[$action] = $dbw->getInfinity();
1676 if ( !isset( $limit[$action] ) ) {
1677 $limit[$action] = '';
1678 } elseif ( $limit[$action] != '' ) {
1682 # Get current restrictions on $action
1683 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1684 if ( $current != '' ) {
1685 $isProtected = true;
1688 if ( $limit[$action] != $current ) {
1690 } elseif ( $limit[$action] != '' ) {
1691 # Only check expiry change if the action is actually being
1692 # protected, since expiry does nothing on an not-protected
1694 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1700 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1704 # If nothing's changed, do nothing
1706 return Status
::newGood();
1709 if ( !$protect ) { # No protection at all means unprotection
1710 $revCommentMsg = 'unprotectedarticle';
1711 $logAction = 'unprotect';
1712 } elseif ( $isProtected ) {
1713 $revCommentMsg = 'modifiedarticleprotection';
1714 $logAction = 'modify';
1716 $revCommentMsg = 'protectedarticle';
1717 $logAction = 'protect';
1720 $encodedExpiry = array();
1721 $protectDescription = '';
1722 foreach ( $limit as $action => $restrictions ) {
1723 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1724 if ( $restrictions != '' ) {
1725 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1726 if ( $encodedExpiry[$action] != 'infinity' ) {
1727 $protectDescription .= wfMsgForContent( 'protect-expiring',
1728 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1729 $wgContLang->date( $expiry[$action], false, false ) ,
1730 $wgContLang->time( $expiry[$action], false, false ) );
1732 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1735 $protectDescription .= ') ';
1738 $protectDescription = trim( $protectDescription );
1740 if ( $id ) { # Protection of existing page
1741 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1742 return Status
::newGood();
1745 # Only restrictions with the 'protect' right can cascade...
1746 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1747 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1749 # The schema allows multiple restrictions
1750 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1754 # Update restrictions table
1755 foreach ( $limit as $action => $restrictions ) {
1756 if ( $restrictions != '' ) {
1757 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1758 array( 'pr_page' => $id,
1759 'pr_type' => $action,
1760 'pr_level' => $restrictions,
1761 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1762 'pr_expiry' => $encodedExpiry[$action]
1767 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1768 'pr_type' => $action ), __METHOD__
);
1772 # Prepare a null revision to be added to the history
1773 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1775 $editComment .= ": $reason";
1777 if ( $protectDescription ) {
1778 $editComment .= " ($protectDescription)";
1781 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1784 # Insert a null revision
1785 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1786 $nullRevId = $nullRevision->insertOn( $dbw );
1788 $latest = $this->getLatest();
1789 # Update page record
1790 $dbw->update( 'page',
1792 'page_touched' => $dbw->timestamp(),
1793 'page_restrictions' => '',
1794 'page_latest' => $nullRevId
1795 ), array( /* WHERE */
1800 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1801 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1802 } else { # Protection of non-existing page (also known as "title protection")
1803 # Cascade protection is meaningless in this case
1806 if ( $limit['create'] != '' ) {
1807 $dbw->replace( 'protected_titles',
1808 array( array( 'pt_namespace', 'pt_title' ) ),
1810 'pt_namespace' => $this->mTitle
->getNamespace(),
1811 'pt_title' => $this->mTitle
->getDBkey(),
1812 'pt_create_perm' => $limit['create'],
1813 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1814 'pt_expiry' => $encodedExpiry['create'],
1815 'pt_user' => $user->getId(),
1816 'pt_reason' => $reason,
1820 $dbw->delete( 'protected_titles',
1822 'pt_namespace' => $this->mTitle
->getNamespace(),
1823 'pt_title' => $this->mTitle
->getDBkey()
1829 $this->mTitle
->flushRestrictions();
1831 if ( $logAction == 'unprotect' ) {
1832 $logParams = array();
1834 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1837 # Update the protection log
1838 $log = new LogPage( 'protect' );
1839 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1841 return Status
::newGood();
1845 * Take an array of page restrictions and flatten it to a string
1846 * suitable for insertion into the page_restrictions field.
1847 * @param $limit Array
1850 protected static function flattenRestrictions( $limit ) {
1851 if ( !is_array( $limit ) ) {
1852 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1858 foreach ( $limit as $action => $restrictions ) {
1859 if ( $restrictions != '' ) {
1860 $bits[] = "$action=$restrictions";
1864 return implode( ':', $bits );
1868 * Back-end article deletion
1869 * Deletes the article with database consistency, writes logs, purges caches
1871 * @param $reason string delete reason for deletion log
1872 * @param $suppress bitfield
1873 * Revision::DELETED_TEXT
1874 * Revision::DELETED_COMMENT
1875 * Revision::DELETED_USER
1876 * Revision::DELETED_RESTRICTED
1877 * @param $id int article ID
1878 * @param $commit boolean defaults to true, triggers transaction end
1879 * @param &$errors Array of errors to append to
1880 * @param $user User The relevant user
1881 * @return boolean true if successful
1883 public function doDeleteArticle(
1884 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1887 $user = is_null( $user ) ?
$wgUser : $user;
1889 wfDebug( __METHOD__
. "\n" );
1891 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1894 $dbw = wfGetDB( DB_MASTER
);
1895 $t = $this->mTitle
->getDBkey();
1896 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1898 if ( $t === '' ||
$id == 0 ) {
1902 // Bitfields to further suppress the content
1905 // This should be 15...
1906 $bitfield |
= Revision
::DELETED_TEXT
;
1907 $bitfield |
= Revision
::DELETED_COMMENT
;
1908 $bitfield |
= Revision
::DELETED_USER
;
1909 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1911 $bitfield = 'rev_deleted';
1915 // For now, shunt the revision data into the archive table.
1916 // Text is *not* removed from the text table; bulk storage
1917 // is left intact to avoid breaking block-compression or
1918 // immutable storage schemes.
1920 // For backwards compatibility, note that some older archive
1921 // table entries will have ar_text and ar_flags fields still.
1923 // In the future, we may keep revisions and mark them with
1924 // the rev_deleted field, which is reserved for this purpose.
1925 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1927 'ar_namespace' => 'page_namespace',
1928 'ar_title' => 'page_title',
1929 'ar_comment' => 'rev_comment',
1930 'ar_user' => 'rev_user',
1931 'ar_user_text' => 'rev_user_text',
1932 'ar_timestamp' => 'rev_timestamp',
1933 'ar_minor_edit' => 'rev_minor_edit',
1934 'ar_rev_id' => 'rev_id',
1935 'ar_parent_id' => 'rev_parent_id',
1936 'ar_text_id' => 'rev_text_id',
1937 'ar_text' => '\'\'', // Be explicit to appease
1938 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1939 'ar_len' => 'rev_len',
1940 'ar_page_id' => 'page_id',
1941 'ar_deleted' => $bitfield,
1942 'ar_sha1' => 'rev_sha1'
1945 'page_id = rev_page'
1949 # Now that it's safely backed up, delete it
1950 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1951 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1958 $this->doDeleteUpdates( $id );
1960 # Log the deletion, if the page was suppressed, log it at Oversight instead
1961 $logtype = $suppress ?
'suppress' : 'delete';
1963 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1964 $logEntry->setPerformer( $user );
1965 $logEntry->setTarget( $this->mTitle
);
1966 $logEntry->setComment( $reason );
1967 $logid = $logEntry->insert();
1968 $logEntry->publish( $logid );
1974 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1979 * Do some database updates after deletion
1981 * @param $id Int: page_id value of the page being deleted
1983 public function doDeleteUpdates( $id ) {
1984 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
1986 $dbw = wfGetDB( DB_MASTER
);
1988 # Delete restrictions for it
1989 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1991 # Fix category table counts
1993 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1995 foreach ( $res as $row ) {
1996 $cats [] = $row->cl_to
;
1999 $this->updateCategoryCounts( array(), $cats );
2001 # If using cascading deletes, we can skip some explicit deletes
2002 if ( !$dbw->cascadingDeletes() ) {
2003 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2005 # Delete outgoing links
2006 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2007 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2008 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2009 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2010 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2011 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2012 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2013 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2014 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2017 # If using cleanup triggers, we can skip some manual deletes
2018 if ( !$dbw->cleanupTriggers() ) {
2019 # Clean up recentchanges entries...
2020 $dbw->delete( 'recentchanges',
2021 array( 'rc_type != ' . RC_LOG
,
2022 'rc_namespace' => $this->mTitle
->getNamespace(),
2023 'rc_title' => $this->mTitle
->getDBkey() ),
2025 $dbw->delete( 'recentchanges',
2026 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2031 self
::onArticleDelete( $this->mTitle
);
2033 # Clear the cached article id so the interface doesn't act like we exist
2034 $this->mTitle
->resetArticleID( 0 );
2038 * Roll back the most recent consecutive set of edits to a page
2039 * from the same user; fails if there are no eligible edits to
2040 * roll back to, e.g. user is the sole contributor. This function
2041 * performs permissions checks on $user, then calls commitRollback()
2042 * to do the dirty work
2044 * @todo: seperate the business/permission stuff out from backend code
2046 * @param $fromP String: Name of the user whose edits to rollback.
2047 * @param $summary String: Custom summary. Set to default summary if empty.
2048 * @param $token String: Rollback token.
2049 * @param $bot Boolean: If true, mark all reverted edits as bot.
2051 * @param $resultDetails Array: contains result-specific array of additional values
2052 * 'alreadyrolled' : 'current' (rev)
2053 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2055 * @param $user User The user performing the rollback
2056 * @return array of errors, each error formatted as
2057 * array(messagekey, param1, param2, ...).
2058 * On success, the array is empty. This array can also be passed to
2059 * OutputPage::showPermissionsErrorPage().
2061 public function doRollback(
2062 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2064 $resultDetails = null;
2067 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2068 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2069 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2071 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2072 $errors[] = array( 'sessionfailure' );
2075 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2076 $errors[] = array( 'actionthrottledtext' );
2079 # If there were errors, bail out now
2080 if ( !empty( $errors ) ) {
2084 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2088 * Backend implementation of doRollback(), please refer there for parameter
2089 * and return value documentation
2091 * NOTE: This function does NOT check ANY permissions, it just commits the
2092 * rollback to the DB. Therefore, you should only call this function direct-
2093 * ly if you want to use custom permissions checks. If you don't, use
2094 * doRollback() instead.
2095 * @param $fromP String: Name of the user whose edits to rollback.
2096 * @param $summary String: Custom summary. Set to default summary if empty.
2097 * @param $bot Boolean: If true, mark all reverted edits as bot.
2099 * @param $resultDetails Array: contains result-specific array of additional values
2100 * @param $guser User The user performing the rollback
2102 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2103 global $wgUseRCPatrol, $wgContLang;
2105 $dbw = wfGetDB( DB_MASTER
);
2107 if ( wfReadOnly() ) {
2108 return array( array( 'readonlytext' ) );
2111 # Get the last editor
2112 $current = Revision
::newFromTitle( $this->mTitle
);
2113 if ( is_null( $current ) ) {
2114 # Something wrong... no page?
2115 return array( array( 'notanarticle' ) );
2118 $from = str_replace( '_', ' ', $fromP );
2119 # User name given should match up with the top revision.
2120 # If the user was deleted then $from should be empty.
2121 if ( $from != $current->getUserText() ) {
2122 $resultDetails = array( 'current' => $current );
2123 return array( array( 'alreadyrolled',
2124 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2125 htmlspecialchars( $fromP ),
2126 htmlspecialchars( $current->getUserText() )
2130 # Get the last edit not by this guy...
2131 # Note: these may not be public values
2132 $user = intval( $current->getRawUser() );
2133 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2134 $s = $dbw->selectRow( 'revision',
2135 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2136 array( 'rev_page' => $current->getPage(),
2137 "rev_user != {$user} OR rev_user_text != {$user_text}"
2139 array( 'USE INDEX' => 'page_timestamp',
2140 'ORDER BY' => 'rev_timestamp DESC' )
2142 if ( $s === false ) {
2143 # No one else ever edited this page
2144 return array( array( 'cantrollback' ) );
2145 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2146 # Only admins can see this text
2147 return array( array( 'notvisiblerev' ) );
2151 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2152 # Mark all reverted edits as bot
2156 if ( $wgUseRCPatrol ) {
2157 # Mark all reverted edits as patrolled
2158 $set['rc_patrolled'] = 1;
2161 if ( count( $set ) ) {
2162 $dbw->update( 'recentchanges', $set,
2164 'rc_cur_id' => $current->getPage(),
2165 'rc_user_text' => $current->getUserText(),
2166 "rc_timestamp > '{$s->rev_timestamp}'",
2171 # Generate the edit summary if necessary
2172 $target = Revision
::newFromId( $s->rev_id
);
2173 if ( empty( $summary ) ) {
2174 if ( $from == '' ) { // no public user name
2175 $summary = wfMsgForContent( 'revertpage-nouser' );
2177 $summary = wfMsgForContent( 'revertpage' );
2181 # Allow the custom summary to use the same args as the default message
2183 $target->getUserText(), $from, $s->rev_id
,
2184 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2185 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2187 $summary = wfMsgReplaceArgs( $summary, $args );
2190 $flags = EDIT_UPDATE
;
2192 if ( $guser->isAllowed( 'minoredit' ) ) {
2193 $flags |
= EDIT_MINOR
;
2196 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2197 $flags |
= EDIT_FORCE_BOT
;
2200 # Actually store the edit
2201 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2202 if ( !empty( $status->value
['revision'] ) ) {
2203 $revId = $status->value
['revision']->getId();
2208 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2210 $resultDetails = array(
2211 'summary' => $summary,
2212 'current' => $current,
2213 'target' => $target,
2221 * The onArticle*() functions are supposed to be a kind of hooks
2222 * which should be called whenever any of the specified actions
2225 * This is a good place to put code to clear caches, for instance.
2227 * This is called on page move and undelete, as well as edit
2229 * @param $title Title object
2231 public static function onArticleCreate( $title ) {
2232 # Update existence markers on article/talk tabs...
2233 if ( $title->isTalkPage() ) {
2234 $other = $title->getSubjectPage();
2236 $other = $title->getTalkPage();
2239 $other->invalidateCache();
2240 $other->purgeSquid();
2242 $title->touchLinks();
2243 $title->purgeSquid();
2244 $title->deleteTitleProtection();
2248 * Clears caches when article is deleted
2250 * @param $title Title
2252 public static function onArticleDelete( $title ) {
2253 # Update existence markers on article/talk tabs...
2254 if ( $title->isTalkPage() ) {
2255 $other = $title->getSubjectPage();
2257 $other = $title->getTalkPage();
2260 $other->invalidateCache();
2261 $other->purgeSquid();
2263 $title->touchLinks();
2264 $title->purgeSquid();
2267 HTMLFileCache
::clearFileCache( $title );
2270 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2271 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2275 if ( $title->getNamespace() == NS_FILE
) {
2276 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2277 $update->doUpdate();
2281 if ( $title->getNamespace() == NS_USER_TALK
) {
2282 $user = User
::newFromName( $title->getText(), false );
2284 $user->setNewtalk( false );
2289 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2293 * Purge caches on page update etc
2295 * @param $title Title object
2296 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2298 public static function onArticleEdit( $title ) {
2299 // Invalidate caches of articles which include this page
2300 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2303 // Invalidate the caches of all pages which redirect here
2304 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2306 # Purge squid for this page only
2307 $title->purgeSquid();
2309 # Clear file cache for this page only
2310 HTMLFileCache
::clearFileCache( $title );
2316 * Returns a list of hidden categories this page is a member of.
2317 * Uses the page_props and categorylinks tables.
2319 * @return Array of Title objects
2321 public function getHiddenCategories() {
2323 $id = $this->mTitle
->getArticleID();
2329 $dbr = wfGetDB( DB_SLAVE
);
2330 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2332 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2333 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2336 if ( $res !== false ) {
2337 foreach ( $res as $row ) {
2338 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2346 * Return an applicable autosummary if one exists for the given edit.
2347 * @param $oldtext String: the previous text of the page.
2348 * @param $newtext String: The submitted text of the page.
2349 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2350 * @return string An appropriate autosummary, or an empty string.
2352 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2355 # Decide what kind of autosummary is needed.
2357 # Redirect autosummaries
2358 $ot = Title
::newFromRedirect( $oldtext );
2359 $rt = Title
::newFromRedirect( $newtext );
2361 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2362 $truncatedtext = $wgContLang->truncate(
2363 str_replace( "\n", ' ', $newtext ),
2365 - strlen( wfMsgForContent( 'autoredircomment' ) )
2366 - strlen( $rt->getFullText() )
2368 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2371 # New page autosummaries
2372 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2373 # If they're making a new article, give its text, truncated, in the summary.
2375 $truncatedtext = $wgContLang->truncate(
2376 str_replace( "\n", ' ', $newtext ),
2377 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2379 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2382 # Blanking autosummaries
2383 if ( $oldtext != '' && $newtext == '' ) {
2384 return wfMsgForContent( 'autosumm-blank' );
2385 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2386 # Removing more than 90% of the article
2388 $truncatedtext = $wgContLang->truncate(
2390 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2392 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2395 # If we reach this point, there's no applicable autosummary for our case, so our
2396 # autosummary is empty.
2401 * Auto-generates a deletion reason
2403 * @param &$hasHistory Boolean: whether the page has a history
2404 * @return mixed String containing deletion reason or empty string, or boolean false
2405 * if no revision occurred
2407 public function getAutoDeleteReason( &$hasHistory ) {
2410 $dbw = wfGetDB( DB_MASTER
);
2411 // Get the last revision
2412 $rev = Revision
::newFromTitle( $this->getTitle() );
2414 if ( is_null( $rev ) ) {
2418 // Get the article's contents
2419 $contents = $rev->getText();
2422 // If the page is blank, use the text from the previous revision,
2423 // which can only be blank if there's a move/import/protect dummy revision involved
2424 if ( $contents == '' ) {
2425 $prev = $rev->getPrevious();
2428 $contents = $prev->getText();
2433 // Find out if there was only one contributor
2434 // Only scan the last 20 revisions
2435 $res = $dbw->select( 'revision', 'rev_user_text',
2436 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2438 array( 'LIMIT' => 20 )
2441 if ( $res === false ) {
2442 // This page has no revisions, which is very weird
2446 $hasHistory = ( $res->numRows() > 1 );
2447 $row = $dbw->fetchObject( $res );
2449 if ( $row ) { // $row is false if the only contributor is hidden
2450 $onlyAuthor = $row->rev_user_text
;
2451 // Try to find a second contributor
2452 foreach ( $res as $row ) {
2453 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2454 $onlyAuthor = false;
2459 $onlyAuthor = false;
2462 // Generate the summary with a '$1' placeholder
2464 // The current revision is blank and the one before is also
2465 // blank. It's just not our lucky day
2466 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2468 if ( $onlyAuthor ) {
2469 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2471 $reason = wfMsgForContent( 'excontent', '$1' );
2475 if ( $reason == '-' ) {
2476 // Allow these UI messages to be blanked out cleanly
2480 // Replace newlines with spaces to prevent uglyness
2481 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2482 // Calculate the maximum amount of chars to get
2483 // Max content length = max comment length - length of the comment (excl. $1)
2484 $maxLength = 255 - ( strlen( $reason ) - 2 );
2485 $contents = $wgContLang->truncate( $contents, $maxLength );
2486 // Remove possible unfinished links
2487 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2488 // Now replace the '$1' placeholder
2489 $reason = str_replace( '$1', $contents, $reason );
2495 * Update all the appropriate counts in the category table, given that
2496 * we've added the categories $added and deleted the categories $deleted.
2498 * @param $added array The names of categories that were added
2499 * @param $deleted array The names of categories that were deleted
2501 public function updateCategoryCounts( $added, $deleted ) {
2502 $ns = $this->mTitle
->getNamespace();
2503 $dbw = wfGetDB( DB_MASTER
);
2505 # First make sure the rows exist. If one of the "deleted" ones didn't
2506 # exist, we might legitimately not create it, but it's simpler to just
2507 # create it and then give it a negative value, since the value is bogus
2510 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2511 $insertCats = array_merge( $added, $deleted );
2512 if ( !$insertCats ) {
2513 # Okay, nothing to do
2517 $insertRows = array();
2519 foreach ( $insertCats as $cat ) {
2520 $insertRows[] = array(
2521 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2525 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2527 $addFields = array( 'cat_pages = cat_pages + 1' );
2528 $removeFields = array( 'cat_pages = cat_pages - 1' );
2530 if ( $ns == NS_CATEGORY
) {
2531 $addFields[] = 'cat_subcats = cat_subcats + 1';
2532 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2533 } elseif ( $ns == NS_FILE
) {
2534 $addFields[] = 'cat_files = cat_files + 1';
2535 $removeFields[] = 'cat_files = cat_files - 1';
2542 array( 'cat_title' => $added ),
2551 array( 'cat_title' => $deleted ),
2558 * Updates cascading protections
2560 * @param $parserOutput ParserOutput object for the current version
2562 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2563 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2567 // templatelinks table may have become out of sync,
2568 // especially if using variable-based transclusions.
2569 // For paranoia, check if things have changed and if
2570 // so apply updates to the database. This will ensure
2571 // that cascaded protections apply as soon as the changes
2574 # Get templates from templatelinks
2575 $id = $this->mTitle
->getArticleID();
2577 $tlTemplates = array();
2579 $dbr = wfGetDB( DB_SLAVE
);
2580 $res = $dbr->select( array( 'templatelinks' ),
2581 array( 'tl_namespace', 'tl_title' ),
2582 array( 'tl_from' => $id ),
2586 foreach ( $res as $row ) {
2587 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2590 # Get templates from parser output.
2591 $poTemplates = array();
2592 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2593 foreach ( $templates as $dbk => $id ) {
2594 $poTemplates["$ns:$dbk"] = true;
2599 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2601 if ( count( $templates_diff ) > 0 ) {
2602 # Whee, link updates time.
2603 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2609 * Return a list of templates used by this article.
2610 * Uses the templatelinks table
2612 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2613 * @return Array of Title objects
2615 public function getUsedTemplates() {
2616 return $this->mTitle
->getTemplateLinksFrom();
2620 * Perform article updates on a special page creation.
2622 * @param $rev Revision object
2624 * @todo This is a shitty interface function. Kill it and replace the
2625 * other shitty functions like doEditUpdates and such so it's not needed
2627 * @deprecated since 1.18, use doEditUpdates()
2629 public function createUpdates( $rev ) {
2630 wfDeprecated( __METHOD__
, '1.18' );
2632 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2636 * This function is called right before saving the wikitext,
2637 * so we can do things like signatures and links-in-context.
2639 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2640 * @param $text String article contents
2641 * @param $user User object: user doing the edit
2642 * @param $popts ParserOptions object: parser options, default options for
2643 * the user loaded if null given
2644 * @return string article contents with altered wikitext markup (signatures
2645 * converted, {{subst:}}, templates, etc.)
2647 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2648 global $wgParser, $wgUser;
2650 wfDeprecated( __METHOD__
, '1.19' );
2652 $user = is_null( $user ) ?
$wgUser : $user;
2654 if ( $popts === null ) {
2655 $popts = ParserOptions
::newFromUser( $user );
2658 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2662 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2664 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2667 public function isBigDeletion() {
2668 wfDeprecated( __METHOD__
, '1.19' );
2669 return $this->mTitle
->isBigDeletion();
2673 * Get the approximate revision count of this page.
2675 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2678 public function estimateRevisionCount() {
2679 wfDeprecated( __METHOD__
, '1.19' );
2680 return $this->mTitle
->estimateRevisionCount();
2684 * Update the article's restriction field, and leave a log entry.
2686 * @deprecated since 1.19
2687 * @param $limit Array: set of restriction keys
2688 * @param $reason String
2689 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2690 * @param $expiry Array: per restriction type expiration
2691 * @param $user User The user updating the restrictions
2692 * @return bool true on success
2694 public function updateRestrictions(
2695 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2699 $user = is_null( $user ) ?
$wgUser : $user;
2701 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2705 * @deprecated since 1.18
2707 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2708 wfDeprecated( __METHOD__
, '1.18' );
2710 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2714 * @deprecated since 1.18
2716 public function viewUpdates() {
2717 wfDeprecated( __METHOD__
, '1.18' );
2719 return $this->doViewUpdates( $wgUser );
2723 * @deprecated since 1.18
2725 public function useParserCache( $oldid ) {
2726 wfDeprecated( __METHOD__
, '1.18' );
2728 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2732 class PoolWorkArticleView
extends PoolCounterWork
{
2750 * @var ParserOptions
2752 private $parserOptions;
2760 * @var ParserOutput|false
2762 private $parserOutput = false;
2767 private $isDirty = false;
2772 private $error = false;
2778 * @param $revid Integer: ID of the revision being parsed
2779 * @param $useParserCache Boolean: whether to use the parser cache
2780 * @param $parserOptions parserOptions to use for the parse operation
2781 * @param $text String: text to parse or null to load it
2783 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2784 $this->page
= $page;
2785 $this->revid
= $revid;
2786 $this->cacheable
= $useParserCache;
2787 $this->parserOptions
= $parserOptions;
2788 $this->text
= $text;
2789 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2790 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2794 * Get the ParserOutput from this object, or false in case of failure
2796 * @return ParserOutput
2798 public function getParserOutput() {
2799 return $this->parserOutput
;
2803 * Get whether the ParserOutput is a dirty one (i.e. expired)
2807 public function getIsDirty() {
2808 return $this->isDirty
;
2812 * Get a Status object in case of error or false otherwise
2814 * @return Status|false
2816 public function getError() {
2817 return $this->error
;
2824 global $wgParser, $wgUseFileCache;
2826 $isCurrent = $this->revid
=== $this->page
->getLatest();
2828 if ( $this->text
!== null ) {
2829 $text = $this->text
;
2830 } elseif ( $isCurrent ) {
2831 $text = $this->page
->getRawText();
2833 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2834 if ( $rev === null ) {
2837 $text = $rev->getText();
2841 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2842 $this->parserOptions
, true, true, $this->revid
);
2847 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2848 $this->page
->getTitle()->getPrefixedDBkey() ) );
2851 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2852 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2855 // Make sure file cache is not used on uncacheable content.
2856 // Output that has magic words in it can still use the parser cache
2857 // (if enabled), though it will generally expire sooner.
2858 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2859 $wgUseFileCache = false;
2863 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2872 function getCachedWork() {
2873 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2875 if ( $this->parserOutput
=== false ) {
2876 wfDebug( __METHOD__
. ": parser cache miss\n" );
2879 wfDebug( __METHOD__
. ": parser cache hit\n" );
2887 function fallback() {
2888 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2890 if ( $this->parserOutput
=== false ) {
2891 wfDebugLog( 'dirty', "dirty missing\n" );
2892 wfDebug( __METHOD__
. ": no dirty cache\n" );
2895 wfDebug( __METHOD__
. ": sending dirty output\n" );
2896 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2897 $this->isDirty
= true;
2903 * @param $status Status
2905 function error( $status ) {
2906 $this->error
= $status;