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
32 protected $mRedirectTarget = null;
37 protected $mLastRevision = null;
39 protected $mTimestamp = ''; // !< String
40 protected $mTouched = '19700101000000'; // !< String
44 * Constructor and clear the article
45 * @param $title Title Reference to a Title object.
47 public function __construct( Title
$title ) {
48 $this->mTitle
= $title;
52 * Create a WikiPage object of the appropriate class for the given title.
55 * @return WikiPage object of the appropriate type
57 public static function factory( Title
$title ) {
58 $ns = $title->getNamespace();
60 if ( $ns == NS_MEDIA
) {
61 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
62 } elseif ( $ns < 0 ) {
63 throw new MWException( "Invalid or virtual namespace $ns given." );
68 $page = new WikiFilePage( $title );
71 $page = new WikiCategoryPage( $title );
74 $page = new WikiPage( $title );
81 * Constructor from a page id
83 * @param $id Int article ID to load
87 public static function newFromID( $id ) {
88 $t = Title
::newFromID( $id );
90 return self
::factory( $t );
96 * Returns overrides for action handlers.
97 * Classes listed here will be used instead of the default one when
98 * (and only when) $wgActions[$action] === true. This allows subclasses
99 * to override the default behavior.
101 * @todo: move this UI stuff somewhere else
105 public function getActionOverrides() {
110 * If this page is a redirect, get its target
112 * The target will be fetched from the redirect table if possible.
113 * If this page doesn't have an entry there, call insertRedirect()
114 * @return Title|mixed object, or null if this page is not a redirect
116 public function getRedirectTarget() {
117 if ( !$this->mTitle
->isRedirect() ) {
121 if ( $this->mRedirectTarget
!== null ) {
122 return $this->mRedirectTarget
;
125 # Query the redirect table
126 $dbr = wfGetDB( DB_SLAVE
);
127 $row = $dbr->selectRow( 'redirect',
128 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
129 array( 'rd_from' => $this->getId() ),
133 // rd_fragment and rd_interwiki were added later, populate them if empty
134 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
135 return $this->mRedirectTarget
= Title
::makeTitle(
136 $row->rd_namespace
, $row->rd_title
,
137 $row->rd_fragment
, $row->rd_interwiki
);
140 # This page doesn't have an entry in the redirect table
141 return $this->mRedirectTarget
= $this->insertRedirect();
145 * Insert an entry for this page into the redirect table.
147 * Don't call this function directly unless you know what you're doing.
148 * @return Title object or null if not a redirect
150 public function insertRedirect() {
151 // recurse through to only get the final target
152 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
156 $this->insertRedirectEntry( $retval );
161 * Insert or update the redirect table entry for this page to indicate
162 * it redirects to $rt .
163 * @param $rt Title redirect target
165 public function insertRedirectEntry( $rt ) {
166 $dbw = wfGetDB( DB_MASTER
);
167 $dbw->replace( 'redirect', array( 'rd_from' ),
169 'rd_from' => $this->getId(),
170 'rd_namespace' => $rt->getNamespace(),
171 'rd_title' => $rt->getDBkey(),
172 'rd_fragment' => $rt->getFragment(),
173 'rd_interwiki' => $rt->getInterwiki(),
180 * Get the Title object or URL this page redirects to
182 * @return mixed false, Title of in-wiki target, or string with URL
184 public function followRedirect() {
185 return $this->getRedirectURL( $this->getRedirectTarget() );
189 * Get the Title object or URL to use for a redirect. We use Title
190 * objects for same-wiki, non-special redirects and URLs for everything
192 * @param $rt Title Redirect target
193 * @return mixed false, Title object of local target, or string with URL
195 public function getRedirectURL( $rt ) {
197 if ( $rt->getInterwiki() != '' ) {
198 if ( $rt->isLocal() ) {
199 // Offsite wikis need an HTTP redirect.
201 // This can be hard to reverse and may produce loops,
202 // so they may be disabled in the site configuration.
203 $source = $this->mTitle
->getFullURL( 'redirect=no' );
204 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
207 if ( $rt->isSpecialPage() ) {
208 // Gotta handle redirects to special pages differently:
209 // Fill the HTTP response "Location" header and ignore
210 // the rest of the page we're on.
212 // This can be hard to reverse, so they may be disabled.
213 if ( $rt->isSpecial( 'Userlogout' ) ) {
216 return $rt->getFullURL();
224 // No or invalid redirect
229 * Get the title object of the article
230 * @return Title object of this page
232 public function getTitle() {
233 return $this->mTitle
;
239 public function clear() {
240 $this->mDataLoaded
= false;
242 $this->mRedirectTarget
= null; # Title object if set
243 $this->mLastRevision
= null; # Latest revision
244 $this->mTimestamp
= '';
245 $this->mTouched
= '19700101000000';
246 $this->mIsRedirect
= false;
247 $this->mLatest
= false;
248 $this->mPreparedEdit
= false;
252 * Get the text that needs to be saved in order to undo all revisions
253 * between $undo and $undoafter. Revisions must belong to the same page,
254 * must exist and must not be deleted
255 * @param $undo Revision
256 * @param $undoafter Revision Must be an earlier revision than $undo
257 * @return mixed string on success, false on failure
259 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
260 $cur_text = $this->getRawText();
261 if ( $cur_text === false ) {
262 return false; // no page
264 $undo_text = $undo->getText();
265 $undoafter_text = $undoafter->getText();
267 if ( $cur_text == $undo_text ) {
268 # No use doing a merge if it's just a straight revert.
269 return $undoafter_text;
274 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
282 * Return the list of revision fields that should be selected to create
287 public static function selectFields() {
304 * Fetch a page record with the given conditions
305 * @param $dbr DatabaseBase object
306 * @param $conditions Array
307 * @return mixed Database result resource, or false on failure
309 protected function pageData( $dbr, $conditions ) {
310 $fields = self
::selectFields();
312 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
314 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
316 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
322 * Fetch a page record matching the Title object's namespace and title
323 * using a sanitized title string
325 * @param $dbr DatabaseBase object
326 * @param $title Title object
327 * @return mixed Database result resource, or false on failure
329 public function pageDataFromTitle( $dbr, $title ) {
330 return $this->pageData( $dbr, array(
331 'page_namespace' => $title->getNamespace(),
332 'page_title' => $title->getDBkey() ) );
336 * Fetch a page record matching the requested ID
338 * @param $dbr DatabaseBase
340 * @return mixed Database result resource, or false on failure
342 public function pageDataFromId( $dbr, $id ) {
343 return $this->pageData( $dbr, array( 'page_id' => $id ) );
347 * Set the general counter, title etc data loaded from
350 * @param $data Object|String One of the following:
351 * A DB query result object or...
352 * "fromdb" to get from a slave DB or...
353 * "fromdbmaster" to get from the master DB
356 public function loadPageData( $data = 'fromdb' ) {
357 if ( $data === 'fromdbmaster' ) {
358 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
359 } elseif ( $data === 'fromdb' ) { // slave
360 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
361 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
362 # Note that DB also stores the master position in the session and checks it.
363 $touched = $this->getCachedLastEditTime();
364 if ( $touched ) { // key set
365 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
366 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
371 $lc = LinkCache
::singleton();
374 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
376 $this->mTitle
->loadFromRow( $data );
378 # Old-fashioned restrictions
379 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
381 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
382 $this->mIsRedirect
= intval( $data->page_is_redirect
);
383 $this->mLatest
= intval( $data->page_latest
);
385 $lc->addBadLinkObj( $this->mTitle
);
387 $this->mTitle
->loadFromRow( false );
390 $this->mDataLoaded
= true;
394 * @return int Page ID
396 public function getId() {
397 return $this->mTitle
->getArticleID();
401 * @return bool Whether or not the page exists in the database
403 public function exists() {
404 return $this->mTitle
->exists();
408 * Check if this page is something we're going to be showing
409 * some sort of sensible content for. If we return false, page
410 * views (plain action=view) will return an HTTP 404 response,
411 * so spiders and robots can know they're following a bad link.
415 public function hasViewableContent() {
416 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
420 * Get the number of views of this page
422 * @return int The view count for the page
424 public function getCount() {
425 return $this->mTitle
->getCount();
429 * Determine whether a page would be suitable for being counted as an
430 * article in the site_stats table based on the title & its content
432 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
433 * if false, the current database state will be used
436 public function isCountable( $editInfo = false ) {
437 global $wgArticleCountMethod;
439 if ( !$this->mTitle
->isContentPage() ) {
443 $text = $editInfo ?
$editInfo->pst
: false;
445 if ( $this->isRedirect( $text ) ) {
449 switch ( $wgArticleCountMethod ) {
453 if ( $text === false ) {
454 $text = $this->getRawText();
456 return strpos( $text, ',' ) !== false;
459 // ParserOutput::getLinks() is a 2D array of page links, so
460 // to be really correct we would need to recurse in the array
461 // but the main array should only have items in it if there are
463 return (bool)count( $editInfo->output
->getLinks() );
465 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
466 array( 'pl_from' => $this->getId() ), __METHOD__
);
472 * Tests if the article text represents a redirect
474 * @param $text mixed string containing article contents, or boolean
477 public function isRedirect( $text = false ) {
478 if ( $text === false ) {
479 if ( !$this->mDataLoaded
) {
480 $this->loadPageData();
483 return (bool)$this->mIsRedirect
;
485 return Title
::newFromRedirect( $text ) !== null;
490 * Loads page_touched and returns a value indicating if it should be used
491 * @return boolean true if not a redirect
493 public function checkTouched() {
494 if ( !$this->mDataLoaded
) {
495 $this->loadPageData();
497 return !$this->mIsRedirect
;
501 * Get the page_touched field
502 * @return string containing GMT timestamp
504 public function getTouched() {
505 if ( !$this->mDataLoaded
) {
506 $this->loadPageData();
508 return $this->mTouched
;
512 * Get the page_latest field
513 * @return integer rev_id of current revision
515 public function getLatest() {
516 if ( !$this->mDataLoaded
) {
517 $this->loadPageData();
519 return (int)$this->mLatest
;
523 * Loads everything except the text
524 * This isn't necessary for all uses, so it's only done if needed.
526 protected function loadLastEdit() {
527 if ( $this->mLastRevision
!== null ) {
528 return; // already loaded
531 $latest = $this->getLatest();
533 return; // page doesn't exist or is missing page_latest info
536 $revision = Revision
::newFromPageId( $this->getId(), $latest );
537 if ( $revision ) { // sanity
538 $this->setLastEdit( $revision );
543 * Set the latest revision
545 protected function setLastEdit( Revision
$revision ) {
546 $this->mLastRevision
= $revision;
547 $this->mTimestamp
= $revision->getTimestamp();
551 * Get the latest revision
552 * @return Revision|null
554 public function getRevision() {
555 $this->loadLastEdit();
556 if ( $this->mLastRevision
) {
557 return $this->mLastRevision
;
563 * Get the text of the current revision. No side-effects...
565 * @param $audience Integer: one of:
566 * Revision::FOR_PUBLIC to be displayed to all users
567 * Revision::FOR_THIS_USER to be displayed to $wgUser
568 * Revision::RAW get the text regardless of permissions
569 * @return String|false The text of the current revision
571 public function getText( $audience = Revision
::FOR_PUBLIC
) {
572 $this->loadLastEdit();
573 if ( $this->mLastRevision
) {
574 return $this->mLastRevision
->getText( $audience );
580 * Get the text of the current revision. No side-effects...
582 * @return String|false The text of the current revision
584 public function getRawText() {
585 $this->loadLastEdit();
586 if ( $this->mLastRevision
) {
587 return $this->mLastRevision
->getRawText();
593 * @return string MW timestamp of last article revision
595 public function getTimestamp() {
596 // Check if the field has been filled by WikiPage::setTimestamp()
597 if ( !$this->mTimestamp
) {
598 $this->loadLastEdit();
600 return wfTimestamp( TS_MW
, $this->mTimestamp
);
604 * Set the page timestamp (use only to avoid DB queries)
605 * @param $ts string MW timestamp of last article revision
608 public function setTimestamp( $ts ) {
609 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
613 * @param $audience Integer: one of:
614 * Revision::FOR_PUBLIC to be displayed to all users
615 * Revision::FOR_THIS_USER to be displayed to $wgUser
616 * Revision::RAW get the text regardless of permissions
617 * @return int user ID for the user that made the last article revision
619 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
620 $this->loadLastEdit();
621 if ( $this->mLastRevision
) {
622 return $this->mLastRevision
->getUser( $audience );
629 * @param $audience Integer: one of:
630 * Revision::FOR_PUBLIC to be displayed to all users
631 * Revision::FOR_THIS_USER to be displayed to $wgUser
632 * Revision::RAW get the text regardless of permissions
633 * @return string username of the user that made the last article revision
635 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
636 $this->loadLastEdit();
637 if ( $this->mLastRevision
) {
638 return $this->mLastRevision
->getUserText( $audience );
645 * @param $audience Integer: one of:
646 * Revision::FOR_PUBLIC to be displayed to all users
647 * Revision::FOR_THIS_USER to be displayed to $wgUser
648 * Revision::RAW get the text regardless of permissions
649 * @return string Comment stored for the last article revision
651 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
652 $this->loadLastEdit();
653 if ( $this->mLastRevision
) {
654 return $this->mLastRevision
->getComment( $audience );
661 * Returns true if last revision was marked as "minor edit"
663 * @return boolean Minor edit indicator for the last article revision.
665 public function getMinorEdit() {
666 $this->loadLastEdit();
667 if ( $this->mLastRevision
) {
668 return $this->mLastRevision
->isMinor();
675 * Get the cached timestamp for the last time the page changed.
676 * This is only used to help handle slave lag by comparing to page_touched.
677 * @return string MW timestamp
679 protected function getCachedLastEditTime() {
681 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
682 return $wgMemc->get( $key );
686 * Set the cached timestamp for the last time the page changed.
687 * This is only used to help handle slave lag by comparing to page_touched.
688 * @param $timestamp string
691 public function setCachedLastEditTime( $timestamp ) {
693 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
694 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
698 * Get a list of users who have edited this article, not including the user who made
699 * the most recent revision, which you can get from $article->getUser() if you want it
700 * @return UserArrayFromResult
702 public function getContributors() {
703 # @todo FIXME: This is expensive; cache this info somewhere.
705 $dbr = wfGetDB( DB_SLAVE
);
707 if ( $dbr->implicitGroupby() ) {
708 $realNameField = 'user_real_name';
710 $realNameField = 'MIN(user_real_name) AS user_real_name';
713 $tables = array( 'revision', 'user' );
716 'rev_user as user_id',
717 'rev_user_text AS user_name',
719 'MAX(rev_timestamp) AS timestamp',
722 $conds = array( 'rev_page' => $this->getId() );
724 // The user who made the top revision gets credited as "this page was last edited by
725 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
726 $user = $this->getUser();
728 $conds[] = "rev_user != $user";
730 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
733 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
736 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
740 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
741 'ORDER BY' => 'timestamp DESC',
744 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
745 return new UserArrayFromResult( $res );
749 * Get the last N authors
750 * @param $num Integer: number of revisions to get
751 * @param $revLatest String: the latest rev_id, selected from the master (optional)
752 * @return array Array of authors, duplicates not removed
754 public function getLastNAuthors( $num, $revLatest = 0 ) {
755 wfProfileIn( __METHOD__
);
756 // First try the slave
757 // If that doesn't have the latest revision, try the master
759 $db = wfGetDB( DB_SLAVE
);
762 $res = $db->select( array( 'page', 'revision' ),
763 array( 'rev_id', 'rev_user_text' ),
765 'page_namespace' => $this->mTitle
->getNamespace(),
766 'page_title' => $this->mTitle
->getDBkey(),
770 'ORDER BY' => 'rev_timestamp DESC',
776 wfProfileOut( __METHOD__
);
780 $row = $db->fetchObject( $res );
782 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
783 $db = wfGetDB( DB_MASTER
);
788 } while ( $continue );
790 $authors = array( $row->rev_user_text
);
792 foreach ( $res as $row ) {
793 $authors[] = $row->rev_user_text
;
796 wfProfileOut( __METHOD__
);
801 * Should the parser cache be used?
803 * @param $parserOptions ParserOptions to check
807 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
808 global $wgEnableParserCache;
810 return $wgEnableParserCache
811 && $parserOptions->getStubThreshold() == 0
812 && $this->mTitle
->exists()
813 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
814 && $this->mTitle
->isWikitextPage();
818 * Get a ParserOutput for the given ParserOptions and revision ID.
819 * The parser cache will be used if possible.
822 * @param $parserOptions ParserOptions to use for the parse operation
823 * @param $oldid Revision ID to get the text from, passing null or 0 will
824 * get the current revision (default value)
825 * @return ParserOutput or false if the revision was not found
827 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
828 wfProfileIn( __METHOD__
);
830 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
831 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
832 if ( $parserOptions->getStubThreshold() ) {
833 wfIncrStats( 'pcache_miss_stub' );
836 if ( $useParserCache ) {
837 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
838 if ( $parserOutput !== false ) {
839 wfProfileOut( __METHOD__
);
840 return $parserOutput;
844 if ( $oldid === null ||
$oldid === 0 ) {
845 $oldid = $this->getLatest();
848 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
851 wfProfileOut( __METHOD__
);
853 return $pool->getParserOutput();
857 * Do standard deferred updates after page view
858 * @param $user User The relevant user
860 public function doViewUpdates( User
$user ) {
861 global $wgDisableCounters;
862 if ( wfReadOnly() ) {
866 # Don't update page view counters on views from bot users (bug 14044)
867 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
868 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
869 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
872 # Update newtalk / watchlist notification status
873 $user->clearNotification( $this->mTitle
);
877 * Perform the actions of a page purging
879 public function doPurge() {
882 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
886 // Invalidate the cache
887 $this->mTitle
->invalidateCache();
891 // Commit the transaction before the purge is sent
892 $dbw = wfGetDB( DB_MASTER
);
896 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
900 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
901 if ( $this->mTitle
->exists() ) {
902 $text = $this->getRawText();
907 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
913 * Insert a new empty page record for this article.
914 * This *must* be followed up by creating a revision
915 * and running $this->updateRevisionOn( ... );
916 * or else the record will be left in a funky state.
917 * Best if all done inside a transaction.
919 * @param $dbw DatabaseBase
920 * @return int The newly created page_id key, or false if the title already existed
922 public function insertOn( $dbw ) {
923 wfProfileIn( __METHOD__
);
925 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
926 $dbw->insert( 'page', array(
927 'page_id' => $page_id,
928 'page_namespace' => $this->mTitle
->getNamespace(),
929 'page_title' => $this->mTitle
->getDBkey(),
931 'page_restrictions' => '',
932 'page_is_redirect' => 0, # Will set this shortly...
934 'page_random' => wfRandom(),
935 'page_touched' => $dbw->timestamp(),
936 'page_latest' => 0, # Fill this in shortly...
937 'page_len' => 0, # Fill this in shortly...
938 ), __METHOD__
, 'IGNORE' );
940 $affected = $dbw->affectedRows();
943 $newid = $dbw->insertId();
944 $this->mTitle
->resetArticleID( $newid );
946 wfProfileOut( __METHOD__
);
948 return $affected ?
$newid : false;
952 * Update the page record to point to a newly saved revision.
954 * @param $dbw DatabaseBase: object
955 * @param $revision Revision: For ID number, and text used to set
956 * length and redirect status fields
957 * @param $lastRevision Integer: if given, will not overwrite the page field
958 * when different from the currently set value.
959 * Giving 0 indicates the new page flag should be set
961 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
962 * removing rows in redirect table.
963 * @return bool true on success, false on failure
966 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
967 wfProfileIn( __METHOD__
);
969 $text = $revision->getText();
970 $len = strlen( $text );
971 $rt = Title
::newFromRedirectRecurse( $text );
973 $conditions = array( 'page_id' => $this->getId() );
975 if ( !is_null( $lastRevision ) ) {
976 # An extra check against threads stepping on each other
977 $conditions['page_latest'] = $lastRevision;
980 $now = wfTimestampNow();
981 $dbw->update( 'page',
983 'page_latest' => $revision->getId(),
984 'page_touched' => $dbw->timestamp( $now ),
985 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
986 'page_is_redirect' => $rt !== null ?
1 : 0,
992 $result = $dbw->affectedRows() != 0;
994 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
995 $this->setLastEdit( $revision );
996 $this->setCachedLastEditTime( $now );
997 $this->mLatest
= $revision->getId();
998 $this->mIsRedirect
= (bool)$rt;
999 # Update the LinkCache.
1000 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1003 wfProfileOut( __METHOD__
);
1008 * Add row to the redirect table if this is a redirect, remove otherwise.
1010 * @param $dbw DatabaseBase
1011 * @param $redirectTitle Title object pointing to the redirect target,
1012 * or NULL if this is not a redirect
1013 * @param $lastRevIsRedirect If given, will optimize adding and
1014 * removing rows in redirect table.
1015 * @return bool true on success, false on failure
1018 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1019 // Always update redirects (target link might have changed)
1020 // Update/Insert if we don't know if the last revision was a redirect or not
1021 // Delete if changing from redirect to non-redirect
1022 $isRedirect = !is_null( $redirectTitle );
1024 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1028 wfProfileIn( __METHOD__
);
1029 if ( $isRedirect ) {
1030 $this->insertRedirectEntry( $redirectTitle );
1032 // This is not a redirect, remove row from redirect table
1033 $where = array( 'rd_from' => $this->getId() );
1034 $dbw->delete( 'redirect', $where, __METHOD__
);
1037 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1038 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1040 wfProfileOut( __METHOD__
);
1042 return ( $dbw->affectedRows() != 0 );
1046 * If the given revision is newer than the currently set page_latest,
1047 * update the page record. Otherwise, do nothing.
1049 * @param $dbw Database object
1050 * @param $revision Revision object
1053 public function updateIfNewerOn( $dbw, $revision ) {
1054 wfProfileIn( __METHOD__
);
1056 $row = $dbw->selectRow(
1057 array( 'revision', 'page' ),
1058 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1060 'page_id' => $this->getId(),
1061 'page_latest=rev_id' ),
1065 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1066 wfProfileOut( __METHOD__
);
1069 $prev = $row->rev_id
;
1070 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1072 # No or missing previous revision; mark the page as new
1074 $lastRevIsRedirect = null;
1077 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1079 wfProfileOut( __METHOD__
);
1084 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1085 * @param $text String: new text of the section
1086 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1087 * @param $edittime String: revision timestamp or null to use the current revision
1088 * @return string Complete article text, or null if error
1090 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1091 wfProfileIn( __METHOD__
);
1093 if ( strval( $section ) == '' ) {
1094 // Whole-page edit; let the whole text through
1096 // Bug 30711: always use current version when adding a new section
1097 if ( is_null( $edittime ) ||
$section == 'new' ) {
1098 $oldtext = $this->getRawText();
1099 if ( $oldtext === false ) {
1100 wfDebug( __METHOD__
. ": no page text\n" );
1104 $dbw = wfGetDB( DB_MASTER
);
1105 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1108 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1109 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1110 wfProfileOut( __METHOD__
);
1114 $oldtext = $rev->getText();
1117 if ( $section == 'new' ) {
1118 # Inserting a new section
1119 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1120 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1121 $text = strlen( trim( $oldtext ) ) > 0
1122 ?
"{$oldtext}\n\n{$subject}{$text}"
1123 : "{$subject}{$text}";
1126 # Replacing an existing section; roll out the big guns
1129 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1133 wfProfileOut( __METHOD__
);
1138 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1140 * @return Int updated $flags
1142 function checkFlags( $flags ) {
1143 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1144 if ( $this->mTitle
->getArticleID() ) {
1145 $flags |
= EDIT_UPDATE
;
1155 * Change an existing article or create a new article. Updates RC and all necessary caches,
1156 * optionally via the deferred update array.
1158 * @param $text String: new text
1159 * @param $summary String: edit summary
1160 * @param $flags Integer bitfield:
1162 * Article is known or assumed to be non-existent, create a new one
1164 * Article is known or assumed to be pre-existing, update it
1166 * Mark this edit minor, if the user is allowed to do so
1168 * Do not log the change in recentchanges
1170 * Mark the edit a "bot" edit regardless of user rights
1171 * EDIT_DEFER_UPDATES
1172 * Defer some of the updates until the end of index.php
1174 * Fill in blank summaries with generated text where possible
1176 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1177 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1178 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1179 * edit-already-exists error will be returned. These two conditions are also possible with
1180 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1182 * @param $baseRevId the revision ID this edit was based off, if any
1183 * @param $user User the user doing the edit
1185 * @return Status object. Possible errors:
1186 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1187 * edit-gone-missing: In update mode, but the article didn't exist
1188 * edit-conflict: In update mode, the article changed unexpectedly
1189 * edit-no-change: Warning that the text was the same as before
1190 * edit-already-exists: In creation mode, but the article already exists
1192 * Extensions may define additional errors.
1194 * $return->value will contain an associative array with members as follows:
1195 * new: Boolean indicating if the function attempted to create a new article
1196 * revision: The revision object for the inserted revision, or null
1198 * Compatibility note: this function previously returned a boolean value indicating success/failure
1200 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1201 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1203 # Low-level sanity check
1204 if ( $this->mTitle
->getText() === '' ) {
1205 throw new MWException( 'Something is trying to edit an article with an empty title' );
1208 wfProfileIn( __METHOD__
);
1210 $user = is_null( $user ) ?
$wgUser : $user;
1211 $status = Status
::newGood( array() );
1213 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1214 $this->loadPageData( 'fromdbmaster' );
1216 $flags = $this->checkFlags( $flags );
1218 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1219 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1221 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1223 if ( $status->isOK() ) {
1224 $status->fatal( 'edit-hook-aborted' );
1227 wfProfileOut( __METHOD__
);
1231 # Silently ignore EDIT_MINOR if not allowed
1232 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1233 $bot = $flags & EDIT_FORCE_BOT
;
1235 $oldtext = $this->getRawText(); // current revision
1236 $oldsize = strlen( $oldtext );
1237 $oldid = $this->getLatest();
1238 $oldIsRedirect = $this->isRedirect();
1239 $oldcountable = $this->isCountable();
1241 # Provide autosummaries if one is not provided and autosummaries are enabled.
1242 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1243 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1246 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1247 $text = $editInfo->pst
;
1248 $newsize = strlen( $text );
1250 $dbw = wfGetDB( DB_MASTER
);
1251 $now = wfTimestampNow();
1252 $this->mTimestamp
= $now;
1254 if ( $flags & EDIT_UPDATE
) {
1255 # Update article, but only if changed.
1256 $status->value
['new'] = false;
1258 # Make sure the revision is either completely inserted or not inserted at all
1259 if ( !$wgDBtransactions ) {
1260 $userAbort = ignore_user_abort( true );
1263 $revision = new Revision( array(
1264 'page' => $this->getId(),
1265 'comment' => $summary,
1266 'minor_edit' => $isminor,
1268 'parent_id' => $oldid,
1269 'user' => $user->getId(),
1270 'user_text' => $user->getName(),
1274 $changed = ( strcmp( $text, $oldtext ) != 0 );
1277 if ( !$this->mLatest
) {
1278 # Article gone missing
1279 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1280 $status->fatal( 'edit-gone-missing' );
1282 wfProfileOut( __METHOD__
);
1287 $revisionId = $revision->insertOn( $dbw );
1291 # Note that we use $this->mLatest instead of fetching a value from the master DB
1292 # during the course of this function. This makes sure that EditPage can detect
1293 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1294 # before this function is called. A previous function used a separate query, this
1295 # creates a window where concurrent edits can cause an ignored edit conflict.
1296 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1299 /* Belated edit conflict! Run away!! */
1300 $status->fatal( 'edit-conflict' );
1302 # Delete the invalid revision if the DB is not transactional
1303 if ( !$wgDBtransactions ) {
1304 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1310 global $wgUseRCPatrol;
1311 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1312 # Update recentchanges
1313 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1314 # Mark as patrolled if the user can do so
1315 $patrolled = $wgUseRCPatrol && !count(
1316 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1317 # Add RC row to the DB
1318 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1319 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1320 $revisionId, $patrolled
1323 # Log auto-patrolled edits
1325 PatrolLog
::record( $rc, true );
1328 $user->incEditCount();
1333 if ( !$wgDBtransactions ) {
1334 ignore_user_abort( $userAbort );
1337 // Now that ignore_user_abort is restored, we can respond to fatal errors
1338 if ( !$status->isOK() ) {
1339 wfProfileOut( __METHOD__
);
1343 # Update links tables, site stats, etc.
1344 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1345 'oldcountable' => $oldcountable ) );
1348 $status->warning( 'edit-no-change' );
1350 // Keep the same revision ID, but do some updates on it
1351 $revisionId = $this->getLatest();
1352 // Update page_touched, this is usually implicit in the page update
1353 // Other cache updates are done in onArticleEdit()
1354 $this->mTitle
->invalidateCache();
1357 # Create new article
1358 $status->value
['new'] = true;
1362 # Add the page record; stake our claim on this title!
1363 # This will return false if the article already exists
1364 $newid = $this->insertOn( $dbw );
1366 if ( $newid === false ) {
1368 $status->fatal( 'edit-already-exists' );
1370 wfProfileOut( __METHOD__
);
1374 # Save the revision text...
1375 $revision = new Revision( array(
1377 'comment' => $summary,
1378 'minor_edit' => $isminor,
1380 'user' => $user->getId(),
1381 'user_text' => $user->getName(),
1384 $revisionId = $revision->insertOn( $dbw );
1386 # Update the page record with revision data
1387 $this->updateRevisionOn( $dbw, $revision, 0 );
1389 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1391 # Update recentchanges
1392 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1393 global $wgUseRCPatrol, $wgUseNPPatrol;
1395 # Mark as patrolled if the user can do so
1396 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1397 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1398 # Add RC row to the DB
1399 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1400 '', strlen( $text ), $revisionId, $patrolled );
1402 # Log auto-patrolled edits
1404 PatrolLog
::record( $rc, true );
1407 $user->incEditCount();
1410 # Update links, etc.
1411 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1413 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1414 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1417 # Do updates right now unless deferral was requested
1418 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1419 DeferredUpdates
::doUpdates();
1422 // Return the new revision (or null) to the caller
1423 $status->value
['revision'] = $revision;
1425 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1426 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1428 # Promote user to any groups they meet the criteria for
1429 $user->addAutopromoteOnceGroups( 'onEdit' );
1431 wfProfileOut( __METHOD__
);
1436 * Get parser options suitable for rendering the primary article wikitext
1437 * @param User|string $user User object or 'canonical'
1438 * @return ParserOptions
1440 public function makeParserOptions( $user ) {
1442 if ( $user instanceof User
) { // settings per user (even anons)
1443 $options = ParserOptions
::newFromUser( $user );
1444 } else { // canonical settings
1445 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1447 $options->enableLimitReport(); // show inclusion/loop reports
1448 $options->setTidy( true ); // fix bad HTML
1453 * Prepare text which is about to be saved.
1454 * Returns a stdclass with source, pst and output members
1456 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1457 global $wgParser, $wgContLang, $wgUser;
1458 $user = is_null( $user ) ?
$wgUser : $user;
1459 // @TODO fixme: check $user->getId() here???
1460 if ( $this->mPreparedEdit
1461 && $this->mPreparedEdit
->newText
== $text
1462 && $this->mPreparedEdit
->revid
== $revid
1465 return $this->mPreparedEdit
;
1468 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1469 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1471 $edit = (object)array();
1472 $edit->revid
= $revid;
1473 $edit->newText
= $text;
1474 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1475 $edit->popts
= $this->makeParserOptions( 'canonical' );
1476 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1477 $edit->oldText
= $this->getRawText();
1479 $this->mPreparedEdit
= $edit;
1485 * Do standard deferred updates after page edit.
1486 * Update links tables, site stats, search index and message cache.
1487 * Purges pages that include this page if the text was changed here.
1488 * Every 100th edit, prune the recent changes table.
1491 * @param $revision Revision object
1492 * @param $user User object that did the revision
1493 * @param $options Array of options, following indexes are used:
1494 * - changed: boolean, whether the revision changed the content (default true)
1495 * - created: boolean, whether the revision created the page (default false)
1496 * - oldcountable: boolean or null (default null):
1497 * - boolean: whether the page was counted as an article before that
1498 * revision, only used in changed is true and created is false
1499 * - null: don't change the article count
1501 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1502 global $wgEnableParserCache;
1504 wfProfileIn( __METHOD__
);
1506 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1507 $text = $revision->getText();
1510 # Be careful not to double-PST: $text is usually already PST-ed once
1511 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1512 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1513 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1515 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1516 $editInfo = $this->mPreparedEdit
;
1519 # Save it to the parser cache
1520 if ( $wgEnableParserCache ) {
1521 $parserCache = ParserCache
::singleton();
1522 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1525 # Update the links tables
1526 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1529 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1531 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1532 if ( 0 == mt_rand( 0, 99 ) ) {
1533 // Flush old entries from the `recentchanges` table; we do this on
1534 // random requests so as to avoid an increase in writes for no good reason
1537 $dbw = wfGetDB( DB_MASTER
);
1538 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1541 array( "rc_timestamp < '$cutoff'" ),
1547 if ( !$this->mTitle
->exists() ) {
1548 wfProfileOut( __METHOD__
);
1552 $id = $this->getId();
1553 $title = $this->mTitle
->getPrefixedDBkey();
1554 $shortTitle = $this->mTitle
->getDBkey();
1556 if ( !$options['changed'] ) {
1559 } elseif ( $options['created'] ) {
1560 $good = (int)$this->isCountable( $editInfo );
1562 } elseif ( $options['oldcountable'] !== null ) {
1563 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1570 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1571 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1573 # If this is another user's talk page, update newtalk.
1574 # Don't do this if $options['changed'] = false (null-edits) nor if
1575 # it's a minor edit and the user doesn't want notifications for those.
1576 if ( $options['changed']
1577 && $this->mTitle
->getNamespace() == NS_USER_TALK
1578 && $shortTitle != $user->getTitleKey()
1579 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1581 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1582 $other = User
::newFromName( $shortTitle, false );
1584 wfDebug( __METHOD__
. ": invalid username\n" );
1585 } elseif ( User
::isIP( $shortTitle ) ) {
1586 // An anonymous user
1587 $other->setNewtalk( true );
1588 } elseif ( $other->isLoggedIn() ) {
1589 $other->setNewtalk( true );
1591 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1596 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1597 MessageCache
::singleton()->replace( $shortTitle, $text );
1600 if( $options['created'] ) {
1601 self
::onArticleCreate( $this->mTitle
);
1603 self
::onArticleEdit( $this->mTitle
);
1606 wfProfileOut( __METHOD__
);
1610 * Edit an article without doing all that other stuff
1611 * The article must already exist; link tables etc
1612 * are not updated, caches are not flushed.
1614 * @param $text String: text submitted
1615 * @param $user User The relevant user
1616 * @param $comment String: comment submitted
1617 * @param $minor Boolean: whereas it's a minor modification
1619 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1620 wfProfileIn( __METHOD__
);
1622 $dbw = wfGetDB( DB_MASTER
);
1623 $revision = new Revision( array(
1624 'page' => $this->getId(),
1626 'comment' => $comment,
1627 'minor_edit' => $minor ?
1 : 0,
1629 $revision->insertOn( $dbw );
1630 $this->updateRevisionOn( $dbw, $revision );
1632 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1634 wfProfileOut( __METHOD__
);
1638 * Update the article's restriction field, and leave a log entry.
1639 * This works for protection both existing and non-existing pages.
1641 * @param $limit Array: set of restriction keys
1642 * @param $reason String
1643 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1644 * @param $expiry Array: per restriction type expiration
1645 * @param $user User The user updating the restrictions
1646 * @return bool true on success
1648 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1651 if ( wfReadOnly() ) {
1652 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1655 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1657 $id = $this->mTitle
->getArticleID();
1663 // Take this opportunity to purge out expired restrictions
1664 Title
::purgeExpiredRestrictions();
1666 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1667 # we expect a single selection, but the schema allows otherwise.
1668 $isProtected = false;
1672 $dbw = wfGetDB( DB_MASTER
);
1674 foreach ( $restrictionTypes as $action ) {
1675 if ( !isset( $expiry[$action] ) ) {
1676 $expiry[$action] = $dbw->getInfinity();
1678 if ( !isset( $limit[$action] ) ) {
1679 $limit[$action] = '';
1680 } elseif ( $limit[$action] != '' ) {
1684 # Get current restrictions on $action
1685 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1686 if ( $current != '' ) {
1687 $isProtected = true;
1690 if ( $limit[$action] != $current ) {
1692 } elseif ( $limit[$action] != '' ) {
1693 # Only check expiry change if the action is actually being
1694 # protected, since expiry does nothing on an not-protected
1696 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1702 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1706 # If nothing's changed, do nothing
1708 return Status
::newGood();
1711 if ( !$protect ) { # No protection at all means unprotection
1712 $revCommentMsg = 'unprotectedarticle';
1713 $logAction = 'unprotect';
1714 } elseif ( $isProtected ) {
1715 $revCommentMsg = 'modifiedarticleprotection';
1716 $logAction = 'modify';
1718 $revCommentMsg = 'protectedarticle';
1719 $logAction = 'protect';
1722 $encodedExpiry = array();
1723 $protectDescription = '';
1724 foreach ( $limit as $action => $restrictions ) {
1725 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1726 if ( $restrictions != '' ) {
1727 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1728 if ( $encodedExpiry[$action] != 'infinity' ) {
1729 $protectDescription .= wfMsgForContent( 'protect-expiring',
1730 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1731 $wgContLang->date( $expiry[$action], false, false ) ,
1732 $wgContLang->time( $expiry[$action], false, false ) );
1734 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1737 $protectDescription .= ') ';
1740 $protectDescription = trim( $protectDescription );
1742 if ( $id ) { # Protection of existing page
1743 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1744 return Status
::newGood();
1747 # Only restrictions with the 'protect' right can cascade...
1748 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1749 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1751 # The schema allows multiple restrictions
1752 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1756 # Update restrictions table
1757 foreach ( $limit as $action => $restrictions ) {
1758 if ( $restrictions != '' ) {
1759 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1760 array( 'pr_page' => $id,
1761 'pr_type' => $action,
1762 'pr_level' => $restrictions,
1763 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1764 'pr_expiry' => $encodedExpiry[$action]
1769 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1770 'pr_type' => $action ), __METHOD__
);
1774 # Prepare a null revision to be added to the history
1775 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1777 $editComment .= ": $reason";
1779 if ( $protectDescription ) {
1780 $editComment .= " ($protectDescription)";
1783 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1786 # Insert a null revision
1787 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1788 $nullRevId = $nullRevision->insertOn( $dbw );
1790 $latest = $this->getLatest();
1791 # Update page record
1792 $dbw->update( 'page',
1794 'page_touched' => $dbw->timestamp(),
1795 'page_restrictions' => '',
1796 'page_latest' => $nullRevId
1797 ), array( /* WHERE */
1802 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1803 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1804 } else { # Protection of non-existing page (also known as "title protection")
1805 # Cascade protection is meaningless in this case
1808 if ( $limit['create'] != '' ) {
1809 $dbw->replace( 'protected_titles',
1810 array( array( 'pt_namespace', 'pt_title' ) ),
1812 'pt_namespace' => $this->mTitle
->getNamespace(),
1813 'pt_title' => $this->mTitle
->getDBkey(),
1814 'pt_create_perm' => $limit['create'],
1815 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1816 'pt_expiry' => $encodedExpiry['create'],
1817 'pt_user' => $user->getId(),
1818 'pt_reason' => $reason,
1822 $dbw->delete( 'protected_titles',
1824 'pt_namespace' => $this->mTitle
->getNamespace(),
1825 'pt_title' => $this->mTitle
->getDBkey()
1831 $this->mTitle
->flushRestrictions();
1833 if ( $logAction == 'unprotect' ) {
1834 $logParams = array();
1836 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1839 # Update the protection log
1840 $log = new LogPage( 'protect' );
1841 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1843 return Status
::newGood();
1847 * Take an array of page restrictions and flatten it to a string
1848 * suitable for insertion into the page_restrictions field.
1849 * @param $limit Array
1852 protected static function flattenRestrictions( $limit ) {
1853 if ( !is_array( $limit ) ) {
1854 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1860 foreach ( $limit as $action => $restrictions ) {
1861 if ( $restrictions != '' ) {
1862 $bits[] = "$action=$restrictions";
1866 return implode( ':', $bits );
1870 * Back-end article deletion
1871 * Deletes the article with database consistency, writes logs, purges caches
1873 * @param $reason string delete reason for deletion log
1874 * @param $suppress bitfield
1875 * Revision::DELETED_TEXT
1876 * Revision::DELETED_COMMENT
1877 * Revision::DELETED_USER
1878 * Revision::DELETED_RESTRICTED
1879 * @param $id int article ID
1880 * @param $commit boolean defaults to true, triggers transaction end
1881 * @param &$errors Array of errors to append to
1882 * @param $user User The relevant user
1883 * @return boolean true if successful
1885 public function doDeleteArticle(
1886 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1889 $user = is_null( $user ) ?
$wgUser : $user;
1891 wfDebug( __METHOD__
. "\n" );
1893 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1896 $dbw = wfGetDB( DB_MASTER
);
1897 $t = $this->mTitle
->getDBkey();
1898 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1900 if ( $t === '' ||
$id == 0 ) {
1904 // Bitfields to further suppress the content
1907 // This should be 15...
1908 $bitfield |
= Revision
::DELETED_TEXT
;
1909 $bitfield |
= Revision
::DELETED_COMMENT
;
1910 $bitfield |
= Revision
::DELETED_USER
;
1911 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1913 $bitfield = 'rev_deleted';
1917 // For now, shunt the revision data into the archive table.
1918 // Text is *not* removed from the text table; bulk storage
1919 // is left intact to avoid breaking block-compression or
1920 // immutable storage schemes.
1922 // For backwards compatibility, note that some older archive
1923 // table entries will have ar_text and ar_flags fields still.
1925 // In the future, we may keep revisions and mark them with
1926 // the rev_deleted field, which is reserved for this purpose.
1927 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1929 'ar_namespace' => 'page_namespace',
1930 'ar_title' => 'page_title',
1931 'ar_comment' => 'rev_comment',
1932 'ar_user' => 'rev_user',
1933 'ar_user_text' => 'rev_user_text',
1934 'ar_timestamp' => 'rev_timestamp',
1935 'ar_minor_edit' => 'rev_minor_edit',
1936 'ar_rev_id' => 'rev_id',
1937 'ar_parent_id' => 'rev_parent_id',
1938 'ar_text_id' => 'rev_text_id',
1939 'ar_text' => '\'\'', // Be explicit to appease
1940 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1941 'ar_len' => 'rev_len',
1942 'ar_page_id' => 'page_id',
1943 'ar_deleted' => $bitfield,
1944 'ar_sha1' => 'rev_sha1'
1947 'page_id = rev_page'
1951 # Now that it's safely backed up, delete it
1952 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1953 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1960 $this->doDeleteUpdates( $id );
1962 # Log the deletion, if the page was suppressed, log it at Oversight instead
1963 $logtype = $suppress ?
'suppress' : 'delete';
1965 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1966 $logEntry->setPerformer( $user );
1967 $logEntry->setTarget( $this->mTitle
);
1968 $logEntry->setComment( $reason );
1969 $logid = $logEntry->insert();
1970 $logEntry->publish( $logid );
1976 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1981 * Do some database updates after deletion
1983 * @param $id Int: page_id value of the page being deleted
1985 public function doDeleteUpdates( $id ) {
1986 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
1988 $dbw = wfGetDB( DB_MASTER
);
1990 # Delete restrictions for it
1991 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1993 # Fix category table counts
1995 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1997 foreach ( $res as $row ) {
1998 $cats [] = $row->cl_to
;
2001 $this->updateCategoryCounts( array(), $cats );
2003 # If using cascading deletes, we can skip some explicit deletes
2004 if ( !$dbw->cascadingDeletes() ) {
2005 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2007 # Delete outgoing links
2008 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2009 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2010 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2011 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2012 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2013 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2014 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2015 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2016 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2019 # If using cleanup triggers, we can skip some manual deletes
2020 if ( !$dbw->cleanupTriggers() ) {
2021 # Clean up recentchanges entries...
2022 $dbw->delete( 'recentchanges',
2023 array( 'rc_type != ' . RC_LOG
,
2024 'rc_namespace' => $this->mTitle
->getNamespace(),
2025 'rc_title' => $this->mTitle
->getDBkey() ),
2027 $dbw->delete( 'recentchanges',
2028 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2033 self
::onArticleDelete( $this->mTitle
);
2035 # Clear the cached article id so the interface doesn't act like we exist
2036 $this->mTitle
->resetArticleID( 0 );
2040 * Roll back the most recent consecutive set of edits to a page
2041 * from the same user; fails if there are no eligible edits to
2042 * roll back to, e.g. user is the sole contributor. This function
2043 * performs permissions checks on $user, then calls commitRollback()
2044 * to do the dirty work
2046 * @todo: seperate the business/permission stuff out from backend code
2048 * @param $fromP String: Name of the user whose edits to rollback.
2049 * @param $summary String: Custom summary. Set to default summary if empty.
2050 * @param $token String: Rollback token.
2051 * @param $bot Boolean: If true, mark all reverted edits as bot.
2053 * @param $resultDetails Array: contains result-specific array of additional values
2054 * 'alreadyrolled' : 'current' (rev)
2055 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2057 * @param $user User The user performing the rollback
2058 * @return array of errors, each error formatted as
2059 * array(messagekey, param1, param2, ...).
2060 * On success, the array is empty. This array can also be passed to
2061 * OutputPage::showPermissionsErrorPage().
2063 public function doRollback(
2064 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2066 $resultDetails = null;
2069 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2070 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2071 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2073 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2074 $errors[] = array( 'sessionfailure' );
2077 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2078 $errors[] = array( 'actionthrottledtext' );
2081 # If there were errors, bail out now
2082 if ( !empty( $errors ) ) {
2086 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2090 * Backend implementation of doRollback(), please refer there for parameter
2091 * and return value documentation
2093 * NOTE: This function does NOT check ANY permissions, it just commits the
2094 * rollback to the DB. Therefore, you should only call this function direct-
2095 * ly if you want to use custom permissions checks. If you don't, use
2096 * doRollback() instead.
2097 * @param $fromP String: Name of the user whose edits to rollback.
2098 * @param $summary String: Custom summary. Set to default summary if empty.
2099 * @param $bot Boolean: If true, mark all reverted edits as bot.
2101 * @param $resultDetails Array: contains result-specific array of additional values
2102 * @param $guser User The user performing the rollback
2104 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2105 global $wgUseRCPatrol, $wgContLang;
2107 $dbw = wfGetDB( DB_MASTER
);
2109 if ( wfReadOnly() ) {
2110 return array( array( 'readonlytext' ) );
2113 # Get the last editor
2114 $current = Revision
::newFromTitle( $this->mTitle
);
2115 if ( is_null( $current ) ) {
2116 # Something wrong... no page?
2117 return array( array( 'notanarticle' ) );
2120 $from = str_replace( '_', ' ', $fromP );
2121 # User name given should match up with the top revision.
2122 # If the user was deleted then $from should be empty.
2123 if ( $from != $current->getUserText() ) {
2124 $resultDetails = array( 'current' => $current );
2125 return array( array( 'alreadyrolled',
2126 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2127 htmlspecialchars( $fromP ),
2128 htmlspecialchars( $current->getUserText() )
2132 # Get the last edit not by this guy...
2133 # Note: these may not be public values
2134 $user = intval( $current->getRawUser() );
2135 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2136 $s = $dbw->selectRow( 'revision',
2137 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2138 array( 'rev_page' => $current->getPage(),
2139 "rev_user != {$user} OR rev_user_text != {$user_text}"
2141 array( 'USE INDEX' => 'page_timestamp',
2142 'ORDER BY' => 'rev_timestamp DESC' )
2144 if ( $s === false ) {
2145 # No one else ever edited this page
2146 return array( array( 'cantrollback' ) );
2147 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2148 # Only admins can see this text
2149 return array( array( 'notvisiblerev' ) );
2153 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2154 # Mark all reverted edits as bot
2158 if ( $wgUseRCPatrol ) {
2159 # Mark all reverted edits as patrolled
2160 $set['rc_patrolled'] = 1;
2163 if ( count( $set ) ) {
2164 $dbw->update( 'recentchanges', $set,
2166 'rc_cur_id' => $current->getPage(),
2167 'rc_user_text' => $current->getUserText(),
2168 "rc_timestamp > '{$s->rev_timestamp}'",
2173 # Generate the edit summary if necessary
2174 $target = Revision
::newFromId( $s->rev_id
);
2175 if ( empty( $summary ) ) {
2176 if ( $from == '' ) { // no public user name
2177 $summary = wfMsgForContent( 'revertpage-nouser' );
2179 $summary = wfMsgForContent( 'revertpage' );
2183 # Allow the custom summary to use the same args as the default message
2185 $target->getUserText(), $from, $s->rev_id
,
2186 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2187 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2189 $summary = wfMsgReplaceArgs( $summary, $args );
2192 $flags = EDIT_UPDATE
;
2194 if ( $guser->isAllowed( 'minoredit' ) ) {
2195 $flags |
= EDIT_MINOR
;
2198 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2199 $flags |
= EDIT_FORCE_BOT
;
2202 # Actually store the edit
2203 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2204 if ( !empty( $status->value
['revision'] ) ) {
2205 $revId = $status->value
['revision']->getId();
2210 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2212 $resultDetails = array(
2213 'summary' => $summary,
2214 'current' => $current,
2215 'target' => $target,
2223 * The onArticle*() functions are supposed to be a kind of hooks
2224 * which should be called whenever any of the specified actions
2227 * This is a good place to put code to clear caches, for instance.
2229 * This is called on page move and undelete, as well as edit
2231 * @param $title Title object
2233 public static function onArticleCreate( $title ) {
2234 # Update existence markers on article/talk tabs...
2235 if ( $title->isTalkPage() ) {
2236 $other = $title->getSubjectPage();
2238 $other = $title->getTalkPage();
2241 $other->invalidateCache();
2242 $other->purgeSquid();
2244 $title->touchLinks();
2245 $title->purgeSquid();
2246 $title->deleteTitleProtection();
2250 * Clears caches when article is deleted
2252 * @param $title Title
2254 public static function onArticleDelete( $title ) {
2255 # Update existence markers on article/talk tabs...
2256 if ( $title->isTalkPage() ) {
2257 $other = $title->getSubjectPage();
2259 $other = $title->getTalkPage();
2262 $other->invalidateCache();
2263 $other->purgeSquid();
2265 $title->touchLinks();
2266 $title->purgeSquid();
2269 HTMLFileCache
::clearFileCache( $title );
2272 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2273 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2277 if ( $title->getNamespace() == NS_FILE
) {
2278 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2279 $update->doUpdate();
2283 if ( $title->getNamespace() == NS_USER_TALK
) {
2284 $user = User
::newFromName( $title->getText(), false );
2286 $user->setNewtalk( false );
2291 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2295 * Purge caches on page update etc
2297 * @param $title Title object
2298 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2300 public static function onArticleEdit( $title ) {
2301 // Invalidate caches of articles which include this page
2302 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2305 // Invalidate the caches of all pages which redirect here
2306 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2308 # Purge squid for this page only
2309 $title->purgeSquid();
2311 # Clear file cache for this page only
2312 HTMLFileCache
::clearFileCache( $title );
2318 * Returns a list of hidden categories this page is a member of.
2319 * Uses the page_props and categorylinks tables.
2321 * @return Array of Title objects
2323 public function getHiddenCategories() {
2325 $id = $this->mTitle
->getArticleID();
2331 $dbr = wfGetDB( DB_SLAVE
);
2332 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2334 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2335 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2338 if ( $res !== false ) {
2339 foreach ( $res as $row ) {
2340 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2348 * Return an applicable autosummary if one exists for the given edit.
2349 * @param $oldtext String: the previous text of the page.
2350 * @param $newtext String: The submitted text of the page.
2351 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2352 * @return string An appropriate autosummary, or an empty string.
2354 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2357 # Decide what kind of autosummary is needed.
2359 # Redirect autosummaries
2360 $ot = Title
::newFromRedirect( $oldtext );
2361 $rt = Title
::newFromRedirect( $newtext );
2363 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2364 $truncatedtext = $wgContLang->truncate(
2365 str_replace( "\n", ' ', $newtext ),
2367 - strlen( wfMsgForContent( 'autoredircomment' ) )
2368 - strlen( $rt->getFullText() )
2370 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2373 # New page autosummaries
2374 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2375 # If they're making a new article, give its text, truncated, in the summary.
2377 $truncatedtext = $wgContLang->truncate(
2378 str_replace( "\n", ' ', $newtext ),
2379 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2381 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2384 # Blanking autosummaries
2385 if ( $oldtext != '' && $newtext == '' ) {
2386 return wfMsgForContent( 'autosumm-blank' );
2387 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2388 # Removing more than 90% of the article
2390 $truncatedtext = $wgContLang->truncate(
2392 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2394 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2397 # If we reach this point, there's no applicable autosummary for our case, so our
2398 # autosummary is empty.
2403 * Auto-generates a deletion reason
2405 * @param &$hasHistory Boolean: whether the page has a history
2406 * @return mixed String containing deletion reason or empty string, or boolean false
2407 * if no revision occurred
2409 public function getAutoDeleteReason( &$hasHistory ) {
2412 $dbw = wfGetDB( DB_MASTER
);
2413 // Get the last revision
2414 $rev = Revision
::newFromTitle( $this->getTitle() );
2416 if ( is_null( $rev ) ) {
2420 // Get the article's contents
2421 $contents = $rev->getText();
2424 // If the page is blank, use the text from the previous revision,
2425 // which can only be blank if there's a move/import/protect dummy revision involved
2426 if ( $contents == '' ) {
2427 $prev = $rev->getPrevious();
2430 $contents = $prev->getText();
2435 // Find out if there was only one contributor
2436 // Only scan the last 20 revisions
2437 $res = $dbw->select( 'revision', 'rev_user_text',
2438 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2440 array( 'LIMIT' => 20 )
2443 if ( $res === false ) {
2444 // This page has no revisions, which is very weird
2448 $hasHistory = ( $res->numRows() > 1 );
2449 $row = $dbw->fetchObject( $res );
2451 if ( $row ) { // $row is false if the only contributor is hidden
2452 $onlyAuthor = $row->rev_user_text
;
2453 // Try to find a second contributor
2454 foreach ( $res as $row ) {
2455 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2456 $onlyAuthor = false;
2461 $onlyAuthor = false;
2464 // Generate the summary with a '$1' placeholder
2466 // The current revision is blank and the one before is also
2467 // blank. It's just not our lucky day
2468 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2470 if ( $onlyAuthor ) {
2471 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2473 $reason = wfMsgForContent( 'excontent', '$1' );
2477 if ( $reason == '-' ) {
2478 // Allow these UI messages to be blanked out cleanly
2482 // Replace newlines with spaces to prevent uglyness
2483 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2484 // Calculate the maximum amount of chars to get
2485 // Max content length = max comment length - length of the comment (excl. $1)
2486 $maxLength = 255 - ( strlen( $reason ) - 2 );
2487 $contents = $wgContLang->truncate( $contents, $maxLength );
2488 // Remove possible unfinished links
2489 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2490 // Now replace the '$1' placeholder
2491 $reason = str_replace( '$1', $contents, $reason );
2497 * Update all the appropriate counts in the category table, given that
2498 * we've added the categories $added and deleted the categories $deleted.
2500 * @param $added array The names of categories that were added
2501 * @param $deleted array The names of categories that were deleted
2503 public function updateCategoryCounts( $added, $deleted ) {
2504 $ns = $this->mTitle
->getNamespace();
2505 $dbw = wfGetDB( DB_MASTER
);
2507 # First make sure the rows exist. If one of the "deleted" ones didn't
2508 # exist, we might legitimately not create it, but it's simpler to just
2509 # create it and then give it a negative value, since the value is bogus
2512 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2513 $insertCats = array_merge( $added, $deleted );
2514 if ( !$insertCats ) {
2515 # Okay, nothing to do
2519 $insertRows = array();
2521 foreach ( $insertCats as $cat ) {
2522 $insertRows[] = array(
2523 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2527 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2529 $addFields = array( 'cat_pages = cat_pages + 1' );
2530 $removeFields = array( 'cat_pages = cat_pages - 1' );
2532 if ( $ns == NS_CATEGORY
) {
2533 $addFields[] = 'cat_subcats = cat_subcats + 1';
2534 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2535 } elseif ( $ns == NS_FILE
) {
2536 $addFields[] = 'cat_files = cat_files + 1';
2537 $removeFields[] = 'cat_files = cat_files - 1';
2544 array( 'cat_title' => $added ),
2553 array( 'cat_title' => $deleted ),
2560 * Updates cascading protections
2562 * @param $parserOutput ParserOutput object for the current version
2564 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2565 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2569 // templatelinks table may have become out of sync,
2570 // especially if using variable-based transclusions.
2571 // For paranoia, check if things have changed and if
2572 // so apply updates to the database. This will ensure
2573 // that cascaded protections apply as soon as the changes
2576 # Get templates from templatelinks
2577 $id = $this->mTitle
->getArticleID();
2579 $tlTemplates = array();
2581 $dbr = wfGetDB( DB_SLAVE
);
2582 $res = $dbr->select( array( 'templatelinks' ),
2583 array( 'tl_namespace', 'tl_title' ),
2584 array( 'tl_from' => $id ),
2588 foreach ( $res as $row ) {
2589 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2592 # Get templates from parser output.
2593 $poTemplates = array();
2594 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2595 foreach ( $templates as $dbk => $id ) {
2596 $poTemplates["$ns:$dbk"] = true;
2601 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2603 if ( count( $templates_diff ) > 0 ) {
2604 # Whee, link updates time.
2605 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2611 * Return a list of templates used by this article.
2612 * Uses the templatelinks table
2614 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2615 * @return Array of Title objects
2617 public function getUsedTemplates() {
2618 return $this->mTitle
->getTemplateLinksFrom();
2622 * Perform article updates on a special page creation.
2624 * @param $rev Revision object
2626 * @todo This is a shitty interface function. Kill it and replace the
2627 * other shitty functions like doEditUpdates and such so it's not needed
2629 * @deprecated since 1.18, use doEditUpdates()
2631 public function createUpdates( $rev ) {
2632 wfDeprecated( __METHOD__
, '1.18' );
2634 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2638 * This function is called right before saving the wikitext,
2639 * so we can do things like signatures and links-in-context.
2641 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2642 * @param $text String article contents
2643 * @param $user User object: user doing the edit
2644 * @param $popts ParserOptions object: parser options, default options for
2645 * the user loaded if null given
2646 * @return string article contents with altered wikitext markup (signatures
2647 * converted, {{subst:}}, templates, etc.)
2649 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2650 global $wgParser, $wgUser;
2652 wfDeprecated( __METHOD__
, '1.19' );
2654 $user = is_null( $user ) ?
$wgUser : $user;
2656 if ( $popts === null ) {
2657 $popts = ParserOptions
::newFromUser( $user );
2660 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2664 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2666 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2669 public function isBigDeletion() {
2670 wfDeprecated( __METHOD__
, '1.19' );
2671 return $this->mTitle
->isBigDeletion();
2675 * Get the approximate revision count of this page.
2677 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2680 public function estimateRevisionCount() {
2681 wfDeprecated( __METHOD__
, '1.19' );
2682 return $this->mTitle
->estimateRevisionCount();
2686 * Update the article's restriction field, and leave a log entry.
2688 * @deprecated since 1.19
2689 * @param $limit Array: set of restriction keys
2690 * @param $reason String
2691 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2692 * @param $expiry Array: per restriction type expiration
2693 * @param $user User The user updating the restrictions
2694 * @return bool true on success
2696 public function updateRestrictions(
2697 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2701 $user = is_null( $user ) ?
$wgUser : $user;
2703 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2707 * @deprecated since 1.18
2709 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2710 wfDeprecated( __METHOD__
, '1.18' );
2712 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2716 * @deprecated since 1.18
2718 public function viewUpdates() {
2719 wfDeprecated( __METHOD__
, '1.18' );
2721 return $this->doViewUpdates( $wgUser );
2725 * @deprecated since 1.18
2727 public function useParserCache( $oldid ) {
2728 wfDeprecated( __METHOD__
, '1.18' );
2730 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2734 class PoolWorkArticleView
extends PoolCounterWork
{
2752 * @var ParserOptions
2754 private $parserOptions;
2762 * @var ParserOutput|false
2764 private $parserOutput = false;
2769 private $isDirty = false;
2774 private $error = false;
2780 * @param $revid Integer: ID of the revision being parsed
2781 * @param $useParserCache Boolean: whether to use the parser cache
2782 * @param $parserOptions parserOptions to use for the parse operation
2783 * @param $text String: text to parse or null to load it
2785 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2786 $this->page
= $page;
2787 $this->revid
= $revid;
2788 $this->cacheable
= $useParserCache;
2789 $this->parserOptions
= $parserOptions;
2790 $this->text
= $text;
2791 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2792 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2796 * Get the ParserOutput from this object, or false in case of failure
2798 * @return ParserOutput
2800 public function getParserOutput() {
2801 return $this->parserOutput
;
2805 * Get whether the ParserOutput is a dirty one (i.e. expired)
2809 public function getIsDirty() {
2810 return $this->isDirty
;
2814 * Get a Status object in case of error or false otherwise
2816 * @return Status|false
2818 public function getError() {
2819 return $this->error
;
2826 global $wgParser, $wgUseFileCache;
2828 $isCurrent = $this->revid
=== $this->page
->getLatest();
2830 if ( $this->text
!== null ) {
2831 $text = $this->text
;
2832 } elseif ( $isCurrent ) {
2833 $text = $this->page
->getRawText();
2835 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2836 if ( $rev === null ) {
2839 $text = $rev->getText();
2843 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2844 $this->parserOptions
, true, true, $this->revid
);
2849 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2850 $this->page
->getTitle()->getPrefixedDBkey() ) );
2853 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2854 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2857 // Make sure file cache is not used on uncacheable content.
2858 // Output that has magic words in it can still use the parser cache
2859 // (if enabled), though it will generally expire sooner.
2860 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2861 $wgUseFileCache = false;
2865 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2874 function getCachedWork() {
2875 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2877 if ( $this->parserOutput
=== false ) {
2878 wfDebug( __METHOD__
. ": parser cache miss\n" );
2881 wfDebug( __METHOD__
. ": parser cache hit\n" );
2889 function fallback() {
2890 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2892 if ( $this->parserOutput
=== false ) {
2893 wfDebugLog( 'dirty', "dirty missing\n" );
2894 wfDebug( __METHOD__
. ": no dirty cache\n" );
2897 wfDebug( __METHOD__
. ": sending dirty output\n" );
2898 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2899 $this->isDirty
= true;
2905 * @param $status Status
2907 function error( $status ) {
2908 $this->error
= $status;