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 of 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 ( $data === 'fromdbmaster' ) {
359 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
360 } elseif ( $data === 'fromdb' ) { // slave
361 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
362 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
363 # Note that DB also stores the master position in the session and checks it.
364 $touched = $this->getCachedLastEditTime();
365 if ( $touched ) { // key set
366 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
367 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
372 $lc = LinkCache
::singleton();
375 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
377 $this->mTitle
->loadFromRow( $data );
379 $this->mIsRedirect
= intval( $data->page_is_redirect
);
380 $this->mLatest
= intval( $data->page_latest
);
382 $lc->addBadLinkObj( $this->mTitle
);
384 $this->mTitle
->loadFromRow( false );
387 $this->mDataLoaded
= true;
391 * @return int Page ID
393 public function getId() {
394 return $this->mTitle
->getArticleID();
398 * @return bool Whether or not the page exists in the database
400 public function exists() {
401 return $this->mTitle
->exists();
405 * Check if this page is something we're going to be showing
406 * some sort of sensible content for. If we return false, page
407 * views (plain action=view) will return an HTTP 404 response,
408 * so spiders and robots can know they're following a bad link.
412 public function hasViewableContent() {
413 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
417 * Get the number of views of this page
419 * @return int The view count for the page
421 public function getCount() {
422 return $this->mTitle
->getCount();
426 * Determine whether a page would be suitable for being counted as an
427 * article in the site_stats table based on the title & its content
429 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
430 * if false, the current database state will be used
433 public function isCountable( $editInfo = false ) {
434 global $wgArticleCountMethod;
436 if ( !$this->mTitle
->isContentPage() ) {
440 $text = $editInfo ?
$editInfo->pst
: false;
442 if ( $this->isRedirect( $text ) ) {
446 switch ( $wgArticleCountMethod ) {
450 if ( $text === false ) {
451 $text = $this->getRawText();
453 return strpos( $text, ',' ) !== false;
456 // ParserOutput::getLinks() is a 2D array of page links, so
457 // to be really correct we would need to recurse in the array
458 // but the main array should only have items in it if there are
460 return (bool)count( $editInfo->output
->getLinks() );
462 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
463 array( 'pl_from' => $this->getId() ), __METHOD__
);
469 * Tests if the article text represents a redirect
471 * @param $text mixed string containing article contents, or boolean
474 public function isRedirect( $text = false ) {
475 if ( $text === false ) {
476 if ( !$this->mDataLoaded
) {
477 $this->loadPageData();
480 return (bool)$this->mIsRedirect
;
482 return Title
::newFromRedirect( $text ) !== null;
487 * Loads page_touched and returns a value indicating if it should be used
488 * @return boolean true if not a redirect
490 public function checkTouched() {
491 if ( !$this->mDataLoaded
) {
492 $this->loadPageData();
494 return !$this->mIsRedirect
;
498 * Get the page_touched field
499 * @return string containing GMT timestamp
501 public function getTouched() {
502 if ( !$this->mDataLoaded
) {
503 $this->loadPageData();
505 return $this->mTitle
->getTouched();
509 * Get the page_latest field
510 * @return integer rev_id of current revision
512 public function getLatest() {
513 if ( !$this->mDataLoaded
) {
514 $this->loadPageData();
516 return (int)$this->mLatest
;
520 * Loads everything except the text
521 * This isn't necessary for all uses, so it's only done if needed.
523 protected function loadLastEdit() {
524 if ( $this->mLastRevision
!== null ) {
525 return; // already loaded
528 $latest = $this->getLatest();
530 return; // page doesn't exist or is missing page_latest info
533 $revision = Revision
::newFromPageId( $this->getId(), $latest );
534 if ( $revision ) { // sanity
535 $this->setLastEdit( $revision );
540 * Set the latest revision
542 protected function setLastEdit( Revision
$revision ) {
543 $this->mLastRevision
= $revision;
544 $this->mTimestamp
= $revision->getTimestamp();
548 * Get the latest revision
549 * @return Revision|null
551 public function getRevision() {
552 $this->loadLastEdit();
553 if ( $this->mLastRevision
) {
554 return $this->mLastRevision
;
560 * Get the text of the current revision. No side-effects...
562 * @param $audience Integer: one of:
563 * Revision::FOR_PUBLIC to be displayed to all users
564 * Revision::FOR_THIS_USER to be displayed to $wgUser
565 * Revision::RAW get the text regardless of permissions
566 * @return String|false The text of the current revision
568 public function getText( $audience = Revision
::FOR_PUBLIC
) {
569 $this->loadLastEdit();
570 if ( $this->mLastRevision
) {
571 return $this->mLastRevision
->getText( $audience );
577 * Get the text of the current revision. No side-effects...
579 * @return String|false The text of the current revision
581 public function getRawText() {
582 $this->loadLastEdit();
583 if ( $this->mLastRevision
) {
584 return $this->mLastRevision
->getRawText();
590 * @return string MW timestamp of last article revision
592 public function getTimestamp() {
593 // Check if the field has been filled by WikiPage::setTimestamp()
594 if ( !$this->mTimestamp
) {
595 $this->loadLastEdit();
597 return wfTimestamp( TS_MW
, $this->mTimestamp
);
601 * Set the page timestamp (use only to avoid DB queries)
602 * @param $ts string MW timestamp of last article revision
605 public function setTimestamp( $ts ) {
606 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
610 * @param $audience Integer: one of:
611 * Revision::FOR_PUBLIC to be displayed to all users
612 * Revision::FOR_THIS_USER to be displayed to $wgUser
613 * Revision::RAW get the text regardless of permissions
614 * @return int user ID for the user that made the last article revision
616 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
617 $this->loadLastEdit();
618 if ( $this->mLastRevision
) {
619 return $this->mLastRevision
->getUser( $audience );
626 * @param $audience Integer: one of:
627 * Revision::FOR_PUBLIC to be displayed to all users
628 * Revision::FOR_THIS_USER to be displayed to $wgUser
629 * Revision::RAW get the text regardless of permissions
630 * @return string username of the user that made the last article revision
632 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
633 $this->loadLastEdit();
634 if ( $this->mLastRevision
) {
635 return $this->mLastRevision
->getUserText( $audience );
642 * @param $audience Integer: one of:
643 * Revision::FOR_PUBLIC to be displayed to all users
644 * Revision::FOR_THIS_USER to be displayed to $wgUser
645 * Revision::RAW get the text regardless of permissions
646 * @return string Comment stored for the last article revision
648 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
649 $this->loadLastEdit();
650 if ( $this->mLastRevision
) {
651 return $this->mLastRevision
->getComment( $audience );
658 * Returns true if last revision was marked as "minor edit"
660 * @return boolean Minor edit indicator for the last article revision.
662 public function getMinorEdit() {
663 $this->loadLastEdit();
664 if ( $this->mLastRevision
) {
665 return $this->mLastRevision
->isMinor();
672 * Get the cached timestamp for the last time the page changed.
673 * This is only used to help handle slave lag by comparing to page_touched.
674 * @return string MW timestamp
676 protected function getCachedLastEditTime() {
678 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
679 return $wgMemc->get( $key );
683 * Set the cached timestamp for the last time the page changed.
684 * This is only used to help handle slave lag by comparing to page_touched.
685 * @param $timestamp string
688 public function setCachedLastEditTime( $timestamp ) {
690 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
691 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
695 * Get a list of users who have edited this article, not including the user who made
696 * the most recent revision, which you can get from $article->getUser() if you want it
697 * @return UserArrayFromResult
699 public function getContributors() {
700 # @todo FIXME: This is expensive; cache this info somewhere.
702 $dbr = wfGetDB( DB_SLAVE
);
704 if ( $dbr->implicitGroupby() ) {
705 $realNameField = 'user_real_name';
707 $realNameField = 'MIN(user_real_name) AS user_real_name';
710 $tables = array( 'revision', 'user' );
713 'rev_user as user_id',
714 'rev_user_text AS user_name',
716 'MAX(rev_timestamp) AS timestamp',
719 $conds = array( 'rev_page' => $this->getId() );
721 // The user who made the top revision gets credited as "this page was last edited by
722 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
723 $user = $this->getUser();
725 $conds[] = "rev_user != $user";
727 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
730 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
733 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
737 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
738 'ORDER BY' => 'timestamp DESC',
741 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
742 return new UserArrayFromResult( $res );
746 * Get the last N authors
747 * @param $num Integer: number of revisions to get
748 * @param $revLatest String: the latest rev_id, selected from the master (optional)
749 * @return array Array of authors, duplicates not removed
751 public function getLastNAuthors( $num, $revLatest = 0 ) {
752 wfProfileIn( __METHOD__
);
753 // First try the slave
754 // If that doesn't have the latest revision, try the master
756 $db = wfGetDB( DB_SLAVE
);
759 $res = $db->select( array( 'page', 'revision' ),
760 array( 'rev_id', 'rev_user_text' ),
762 'page_namespace' => $this->mTitle
->getNamespace(),
763 'page_title' => $this->mTitle
->getDBkey(),
767 'ORDER BY' => 'rev_timestamp DESC',
773 wfProfileOut( __METHOD__
);
777 $row = $db->fetchObject( $res );
779 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
780 $db = wfGetDB( DB_MASTER
);
785 } while ( $continue );
787 $authors = array( $row->rev_user_text
);
789 foreach ( $res as $row ) {
790 $authors[] = $row->rev_user_text
;
793 wfProfileOut( __METHOD__
);
798 * Should the parser cache be used?
800 * @param $parserOptions ParserOptions to check
804 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
805 global $wgEnableParserCache;
807 return $wgEnableParserCache
808 && $parserOptions->getStubThreshold() == 0
809 && $this->mTitle
->exists()
810 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
811 && $this->mTitle
->isWikitextPage();
815 * Get a ParserOutput for the given ParserOptions and revision ID.
816 * The parser cache will be used if possible.
819 * @param $parserOptions ParserOptions to use for the parse operation
820 * @param $oldid Revision ID to get the text from, passing null or 0 will
821 * get the current revision (default value)
822 * @return ParserOutput or false if the revision was not found
824 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
825 wfProfileIn( __METHOD__
);
827 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
828 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
829 if ( $parserOptions->getStubThreshold() ) {
830 wfIncrStats( 'pcache_miss_stub' );
833 if ( $useParserCache ) {
834 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
835 if ( $parserOutput !== false ) {
836 wfProfileOut( __METHOD__
);
837 return $parserOutput;
841 if ( $oldid === null ||
$oldid === 0 ) {
842 $oldid = $this->getLatest();
845 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
848 wfProfileOut( __METHOD__
);
850 return $pool->getParserOutput();
854 * Do standard deferred updates after page view
855 * @param $user User The relevant user
857 public function doViewUpdates( User
$user ) {
858 global $wgDisableCounters;
859 if ( wfReadOnly() ) {
863 # Don't update page view counters on views from bot users (bug 14044)
864 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
865 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
866 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
869 # Update newtalk / watchlist notification status
870 $user->clearNotification( $this->mTitle
);
874 * Perform the actions of a page purging
876 public function doPurge() {
879 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
883 // Invalidate the cache
884 $this->mTitle
->invalidateCache();
888 // Commit the transaction before the purge is sent
889 $dbw = wfGetDB( DB_MASTER
);
893 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
897 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
898 if ( $this->mTitle
->exists() ) {
899 $text = $this->getRawText();
904 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
910 * Insert a new empty page record for this article.
911 * This *must* be followed up by creating a revision
912 * and running $this->updateRevisionOn( ... );
913 * or else the record will be left in a funky state.
914 * Best if all done inside a transaction.
916 * @param $dbw DatabaseBase
917 * @return int The newly created page_id key, or false if the title already existed
919 public function insertOn( $dbw ) {
920 wfProfileIn( __METHOD__
);
922 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
923 $dbw->insert( 'page', array(
924 'page_id' => $page_id,
925 'page_namespace' => $this->mTitle
->getNamespace(),
926 'page_title' => $this->mTitle
->getDBkey(),
928 'page_restrictions' => '',
929 'page_is_redirect' => 0, # Will set this shortly...
931 'page_random' => wfRandom(),
932 'page_touched' => $dbw->timestamp(),
933 'page_latest' => 0, # Fill this in shortly...
934 'page_len' => 0, # Fill this in shortly...
935 ), __METHOD__
, 'IGNORE' );
937 $affected = $dbw->affectedRows();
940 $newid = $dbw->insertId();
941 $this->mTitle
->resetArticleID( $newid );
943 wfProfileOut( __METHOD__
);
945 return $affected ?
$newid : false;
949 * Update the page record to point to a newly saved revision.
951 * @param $dbw DatabaseBase: object
952 * @param $revision Revision: For ID number, and text used to set
953 * length and redirect status fields
954 * @param $lastRevision Integer: if given, will not overwrite the page field
955 * when different from the currently set value.
956 * Giving 0 indicates the new page flag should be set
958 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
959 * removing rows in redirect table.
960 * @return bool true on success, false on failure
963 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
964 wfProfileIn( __METHOD__
);
966 $text = $revision->getText();
967 $len = strlen( $text );
968 $rt = Title
::newFromRedirectRecurse( $text );
970 $conditions = array( 'page_id' => $this->getId() );
972 if ( !is_null( $lastRevision ) ) {
973 # An extra check against threads stepping on each other
974 $conditions['page_latest'] = $lastRevision;
977 $now = wfTimestampNow();
978 $dbw->update( 'page',
980 'page_latest' => $revision->getId(),
981 'page_touched' => $dbw->timestamp( $now ),
982 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
983 'page_is_redirect' => $rt !== null ?
1 : 0,
989 $result = $dbw->affectedRows() != 0;
991 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
992 $this->setLastEdit( $revision );
993 $this->setCachedLastEditTime( $now );
994 $this->mLatest
= $revision->getId();
995 $this->mIsRedirect
= (bool)$rt;
996 # Update the LinkCache.
997 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1000 wfProfileOut( __METHOD__
);
1005 * Add row to the redirect table if this is a redirect, remove otherwise.
1007 * @param $dbw DatabaseBase
1008 * @param $redirectTitle Title object pointing to the redirect target,
1009 * or NULL if this is not a redirect
1010 * @param $lastRevIsRedirect If given, will optimize adding and
1011 * removing rows in redirect table.
1012 * @return bool true on success, false on failure
1015 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1016 // Always update redirects (target link might have changed)
1017 // Update/Insert if we don't know if the last revision was a redirect or not
1018 // Delete if changing from redirect to non-redirect
1019 $isRedirect = !is_null( $redirectTitle );
1021 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
1025 wfProfileIn( __METHOD__
);
1026 if ( $isRedirect ) {
1027 $this->insertRedirectEntry( $redirectTitle );
1029 // This is not a redirect, remove row from redirect table
1030 $where = array( 'rd_from' => $this->getId() );
1031 $dbw->delete( 'redirect', $where, __METHOD__
);
1034 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1035 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1037 wfProfileOut( __METHOD__
);
1039 return ( $dbw->affectedRows() != 0 );
1043 * If the given revision is newer than the currently set page_latest,
1044 * update the page record. Otherwise, do nothing.
1046 * @param $dbw Database object
1047 * @param $revision Revision object
1050 public function updateIfNewerOn( $dbw, $revision ) {
1051 wfProfileIn( __METHOD__
);
1053 $row = $dbw->selectRow(
1054 array( 'revision', 'page' ),
1055 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1057 'page_id' => $this->getId(),
1058 'page_latest=rev_id' ),
1062 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1063 wfProfileOut( __METHOD__
);
1066 $prev = $row->rev_id
;
1067 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1069 # No or missing previous revision; mark the page as new
1071 $lastRevIsRedirect = null;
1074 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1076 wfProfileOut( __METHOD__
);
1081 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1082 * @param $text String: new text of the section
1083 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1084 * @param $edittime String: revision timestamp or null to use the current revision
1085 * @return string Complete article text, or null if error
1087 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1088 wfProfileIn( __METHOD__
);
1090 if ( strval( $section ) == '' ) {
1091 // Whole-page edit; let the whole text through
1093 // Bug 30711: always use current version when adding a new section
1094 if ( is_null( $edittime ) ||
$section == 'new' ) {
1095 $oldtext = $this->getRawText();
1096 if ( $oldtext === false ) {
1097 wfDebug( __METHOD__
. ": no page text\n" );
1101 $dbw = wfGetDB( DB_MASTER
);
1102 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1105 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1106 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1107 wfProfileOut( __METHOD__
);
1111 $oldtext = $rev->getText();
1114 if ( $section == 'new' ) {
1115 # Inserting a new section
1116 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1117 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1118 $text = strlen( trim( $oldtext ) ) > 0
1119 ?
"{$oldtext}\n\n{$subject}{$text}"
1120 : "{$subject}{$text}";
1123 # Replacing an existing section; roll out the big guns
1126 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1130 wfProfileOut( __METHOD__
);
1135 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1137 * @return Int updated $flags
1139 function checkFlags( $flags ) {
1140 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1141 if ( $this->mTitle
->getArticleID() ) {
1142 $flags |
= EDIT_UPDATE
;
1152 * Change an existing article or create a new article. Updates RC and all necessary caches,
1153 * optionally via the deferred update array.
1155 * @param $text String: new text
1156 * @param $summary String: edit summary
1157 * @param $flags Integer bitfield:
1159 * Article is known or assumed to be non-existent, create a new one
1161 * Article is known or assumed to be pre-existing, update it
1163 * Mark this edit minor, if the user is allowed to do so
1165 * Do not log the change in recentchanges
1167 * Mark the edit a "bot" edit regardless of user rights
1168 * EDIT_DEFER_UPDATES
1169 * Defer some of the updates until the end of index.php
1171 * Fill in blank summaries with generated text where possible
1173 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1174 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1175 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1176 * edit-already-exists error will be returned. These two conditions are also possible with
1177 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1179 * @param $baseRevId the revision ID this edit was based off, if any
1180 * @param $user User the user doing the edit
1182 * @return Status object. Possible errors:
1183 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1184 * edit-gone-missing: In update mode, but the article didn't exist
1185 * edit-conflict: In update mode, the article changed unexpectedly
1186 * edit-no-change: Warning that the text was the same as before
1187 * edit-already-exists: In creation mode, but the article already exists
1189 * Extensions may define additional errors.
1191 * $return->value will contain an associative array with members as follows:
1192 * new: Boolean indicating if the function attempted to create a new article
1193 * revision: The revision object for the inserted revision, or null
1195 * Compatibility note: this function previously returned a boolean value indicating success/failure
1197 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1198 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1200 # Low-level sanity check
1201 if ( $this->mTitle
->getText() === '' ) {
1202 throw new MWException( 'Something is trying to edit an article with an empty title' );
1205 wfProfileIn( __METHOD__
);
1207 $user = is_null( $user ) ?
$wgUser : $user;
1208 $status = Status
::newGood( array() );
1210 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1211 $this->loadPageData( 'fromdbmaster' );
1213 $flags = $this->checkFlags( $flags );
1215 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1216 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1218 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1220 if ( $status->isOK() ) {
1221 $status->fatal( 'edit-hook-aborted' );
1224 wfProfileOut( __METHOD__
);
1228 # Silently ignore EDIT_MINOR if not allowed
1229 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1230 $bot = $flags & EDIT_FORCE_BOT
;
1232 $oldtext = $this->getRawText(); // current revision
1233 $oldsize = strlen( $oldtext );
1234 $oldid = $this->getLatest();
1235 $oldIsRedirect = $this->isRedirect();
1236 $oldcountable = $this->isCountable();
1238 # Provide autosummaries if one is not provided and autosummaries are enabled.
1239 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1240 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1243 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1244 $text = $editInfo->pst
;
1245 $newsize = strlen( $text );
1247 $dbw = wfGetDB( DB_MASTER
);
1248 $now = wfTimestampNow();
1249 $this->mTimestamp
= $now;
1251 if ( $flags & EDIT_UPDATE
) {
1252 # Update article, but only if changed.
1253 $status->value
['new'] = false;
1255 # Make sure the revision is either completely inserted or not inserted at all
1256 if ( !$wgDBtransactions ) {
1257 $userAbort = ignore_user_abort( true );
1260 $revision = new Revision( array(
1261 'page' => $this->getId(),
1262 'comment' => $summary,
1263 'minor_edit' => $isminor,
1265 'parent_id' => $oldid,
1266 'user' => $user->getId(),
1267 'user_text' => $user->getName(),
1271 $changed = ( strcmp( $text, $oldtext ) != 0 );
1274 if ( !$this->mLatest
) {
1275 # Article gone missing
1276 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1277 $status->fatal( 'edit-gone-missing' );
1279 wfProfileOut( __METHOD__
);
1284 $revisionId = $revision->insertOn( $dbw );
1288 # Note that we use $this->mLatest instead of fetching a value from the master DB
1289 # during the course of this function. This makes sure that EditPage can detect
1290 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1291 # before this function is called. A previous function used a separate query, this
1292 # creates a window where concurrent edits can cause an ignored edit conflict.
1293 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1296 /* Belated edit conflict! Run away!! */
1297 $status->fatal( 'edit-conflict' );
1299 # Delete the invalid revision if the DB is not transactional
1300 if ( !$wgDBtransactions ) {
1301 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1307 global $wgUseRCPatrol;
1308 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1309 # Update recentchanges
1310 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1311 # Mark as patrolled if the user can do so
1312 $patrolled = $wgUseRCPatrol && !count(
1313 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1314 # Add RC row to the DB
1315 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1316 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1317 $revisionId, $patrolled
1320 # Log auto-patrolled edits
1322 PatrolLog
::record( $rc, true );
1325 $user->incEditCount();
1330 if ( !$wgDBtransactions ) {
1331 ignore_user_abort( $userAbort );
1334 // Now that ignore_user_abort is restored, we can respond to fatal errors
1335 if ( !$status->isOK() ) {
1336 wfProfileOut( __METHOD__
);
1340 # Update links tables, site stats, etc.
1341 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1342 'oldcountable' => $oldcountable ) );
1345 $status->warning( 'edit-no-change' );
1347 // Keep the same revision ID, but do some updates on it
1348 $revisionId = $this->getLatest();
1349 // Update page_touched, this is usually implicit in the page update
1350 // Other cache updates are done in onArticleEdit()
1351 $this->mTitle
->invalidateCache();
1354 # Create new article
1355 $status->value
['new'] = true;
1359 # Add the page record; stake our claim on this title!
1360 # This will return false if the article already exists
1361 $newid = $this->insertOn( $dbw );
1363 if ( $newid === false ) {
1365 $status->fatal( 'edit-already-exists' );
1367 wfProfileOut( __METHOD__
);
1371 # Save the revision text...
1372 $revision = new Revision( array(
1374 'comment' => $summary,
1375 'minor_edit' => $isminor,
1377 'user' => $user->getId(),
1378 'user_text' => $user->getName(),
1381 $revisionId = $revision->insertOn( $dbw );
1383 # Update the page record with revision data
1384 $this->updateRevisionOn( $dbw, $revision, 0 );
1386 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1388 # Update recentchanges
1389 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1390 global $wgUseRCPatrol, $wgUseNPPatrol;
1392 # Mark as patrolled if the user can do so
1393 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1394 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1395 # Add RC row to the DB
1396 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1397 '', strlen( $text ), $revisionId, $patrolled );
1399 # Log auto-patrolled edits
1401 PatrolLog
::record( $rc, true );
1404 $user->incEditCount();
1407 # Update links, etc.
1408 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1410 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1411 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1414 # Do updates right now unless deferral was requested
1415 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1416 DeferredUpdates
::doUpdates();
1419 // Return the new revision (or null) to the caller
1420 $status->value
['revision'] = $revision;
1422 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1423 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1425 # Promote user to any groups they meet the criteria for
1426 $user->addAutopromoteOnceGroups( 'onEdit' );
1428 wfProfileOut( __METHOD__
);
1433 * Get parser options suitable for rendering the primary article wikitext
1434 * @param User|string $user User object or 'canonical'
1435 * @return ParserOptions
1437 public function makeParserOptions( $user ) {
1439 if ( $user instanceof User
) { // settings per user (even anons)
1440 $options = ParserOptions
::newFromUser( $user );
1441 } else { // canonical settings
1442 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1444 $options->enableLimitReport(); // show inclusion/loop reports
1445 $options->setTidy( true ); // fix bad HTML
1450 * Prepare text which is about to be saved.
1451 * Returns a stdclass with source, pst and output members
1453 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1454 global $wgParser, $wgContLang, $wgUser;
1455 $user = is_null( $user ) ?
$wgUser : $user;
1456 // @TODO fixme: check $user->getId() here???
1457 if ( $this->mPreparedEdit
1458 && $this->mPreparedEdit
->newText
== $text
1459 && $this->mPreparedEdit
->revid
== $revid
1462 return $this->mPreparedEdit
;
1465 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1466 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1468 $edit = (object)array();
1469 $edit->revid
= $revid;
1470 $edit->newText
= $text;
1471 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1472 $edit->popts
= $this->makeParserOptions( 'canonical' );
1473 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1474 $edit->oldText
= $this->getRawText();
1476 $this->mPreparedEdit
= $edit;
1482 * Do standard deferred updates after page edit.
1483 * Update links tables, site stats, search index and message cache.
1484 * Purges pages that include this page if the text was changed here.
1485 * Every 100th edit, prune the recent changes table.
1488 * @param $revision Revision object
1489 * @param $user User object that did the revision
1490 * @param $options Array of options, following indexes are used:
1491 * - changed: boolean, whether the revision changed the content (default true)
1492 * - created: boolean, whether the revision created the page (default false)
1493 * - oldcountable: boolean or null (default null):
1494 * - boolean: whether the page was counted as an article before that
1495 * revision, only used in changed is true and created is false
1496 * - null: don't change the article count
1498 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1499 global $wgEnableParserCache;
1501 wfProfileIn( __METHOD__
);
1503 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1504 $text = $revision->getText();
1507 # Be careful not to double-PST: $text is usually already PST-ed once
1508 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1509 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1510 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1512 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1513 $editInfo = $this->mPreparedEdit
;
1516 # Save it to the parser cache
1517 if ( $wgEnableParserCache ) {
1518 $parserCache = ParserCache
::singleton();
1519 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1522 # Update the links tables
1523 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1526 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1528 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1529 if ( 0 == mt_rand( 0, 99 ) ) {
1530 // Flush old entries from the `recentchanges` table; we do this on
1531 // random requests so as to avoid an increase in writes for no good reason
1534 $dbw = wfGetDB( DB_MASTER
);
1535 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1538 array( "rc_timestamp < '$cutoff'" ),
1544 if ( !$this->mTitle
->exists() ) {
1545 wfProfileOut( __METHOD__
);
1549 $id = $this->getId();
1550 $title = $this->mTitle
->getPrefixedDBkey();
1551 $shortTitle = $this->mTitle
->getDBkey();
1553 if ( !$options['changed'] ) {
1556 } elseif ( $options['created'] ) {
1557 $good = (int)$this->isCountable( $editInfo );
1559 } elseif ( $options['oldcountable'] !== null ) {
1560 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1567 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1568 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1570 # If this is another user's talk page, update newtalk.
1571 # Don't do this if $options['changed'] = false (null-edits) nor if
1572 # it's a minor edit and the user doesn't want notifications for those.
1573 if ( $options['changed']
1574 && $this->mTitle
->getNamespace() == NS_USER_TALK
1575 && $shortTitle != $user->getTitleKey()
1576 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1578 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1579 $other = User
::newFromName( $shortTitle, false );
1581 wfDebug( __METHOD__
. ": invalid username\n" );
1582 } elseif ( User
::isIP( $shortTitle ) ) {
1583 // An anonymous user
1584 $other->setNewtalk( true );
1585 } elseif ( $other->isLoggedIn() ) {
1586 $other->setNewtalk( true );
1588 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1593 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1594 MessageCache
::singleton()->replace( $shortTitle, $text );
1597 if( $options['created'] ) {
1598 self
::onArticleCreate( $this->mTitle
);
1600 self
::onArticleEdit( $this->mTitle
);
1603 wfProfileOut( __METHOD__
);
1607 * Edit an article without doing all that other stuff
1608 * The article must already exist; link tables etc
1609 * are not updated, caches are not flushed.
1611 * @param $text String: text submitted
1612 * @param $user User The relevant user
1613 * @param $comment String: comment submitted
1614 * @param $minor Boolean: whereas it's a minor modification
1616 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1617 wfProfileIn( __METHOD__
);
1619 $dbw = wfGetDB( DB_MASTER
);
1620 $revision = new Revision( array(
1621 'page' => $this->getId(),
1623 'comment' => $comment,
1624 'minor_edit' => $minor ?
1 : 0,
1626 $revision->insertOn( $dbw );
1627 $this->updateRevisionOn( $dbw, $revision );
1629 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1631 wfProfileOut( __METHOD__
);
1635 * Update the article's restriction field, and leave a log entry.
1636 * This works for protection both existing and non-existing pages.
1638 * @param $limit Array: set of restriction keys
1639 * @param $reason String
1640 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1641 * @param $expiry Array: per restriction type expiration
1642 * @param $user User The user updating the restrictions
1643 * @return bool true on success
1645 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1648 if ( wfReadOnly() ) {
1649 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1652 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1654 $id = $this->mTitle
->getArticleID();
1660 // Take this opportunity to purge out expired restrictions
1661 Title
::purgeExpiredRestrictions();
1663 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1664 # we expect a single selection, but the schema allows otherwise.
1665 $isProtected = false;
1669 $dbw = wfGetDB( DB_MASTER
);
1671 foreach ( $restrictionTypes as $action ) {
1672 if ( !isset( $expiry[$action] ) ) {
1673 $expiry[$action] = $dbw->getInfinity();
1675 if ( !isset( $limit[$action] ) ) {
1676 $limit[$action] = '';
1677 } elseif ( $limit[$action] != '' ) {
1681 # Get current restrictions on $action
1682 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1683 if ( $current != '' ) {
1684 $isProtected = true;
1687 if ( $limit[$action] != $current ) {
1689 } elseif ( $limit[$action] != '' ) {
1690 # Only check expiry change if the action is actually being
1691 # protected, since expiry does nothing on an not-protected
1693 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1699 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1703 # If nothing's changed, do nothing
1705 return Status
::newGood();
1708 if ( !$protect ) { # No protection at all means unprotection
1709 $revCommentMsg = 'unprotectedarticle';
1710 $logAction = 'unprotect';
1711 } elseif ( $isProtected ) {
1712 $revCommentMsg = 'modifiedarticleprotection';
1713 $logAction = 'modify';
1715 $revCommentMsg = 'protectedarticle';
1716 $logAction = 'protect';
1719 $encodedExpiry = array();
1720 $protectDescription = '';
1721 foreach ( $limit as $action => $restrictions ) {
1722 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1723 if ( $restrictions != '' ) {
1724 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1725 if ( $encodedExpiry[$action] != 'infinity' ) {
1726 $protectDescription .= wfMsgForContent( 'protect-expiring',
1727 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1728 $wgContLang->date( $expiry[$action], false, false ) ,
1729 $wgContLang->time( $expiry[$action], false, false ) );
1731 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1734 $protectDescription .= ') ';
1737 $protectDescription = trim( $protectDescription );
1739 if ( $id ) { # Protection of existing page
1740 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1741 return Status
::newGood();
1744 # Only restrictions with the 'protect' right can cascade...
1745 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1746 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1748 # The schema allows multiple restrictions
1749 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1753 # Update restrictions table
1754 foreach ( $limit as $action => $restrictions ) {
1755 if ( $restrictions != '' ) {
1756 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1757 array( 'pr_page' => $id,
1758 'pr_type' => $action,
1759 'pr_level' => $restrictions,
1760 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1761 'pr_expiry' => $encodedExpiry[$action]
1766 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1767 'pr_type' => $action ), __METHOD__
);
1771 # Prepare a null revision to be added to the history
1772 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1774 $editComment .= ": $reason";
1776 if ( $protectDescription ) {
1777 $editComment .= " ($protectDescription)";
1780 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1783 # Insert a null revision
1784 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1785 $nullRevId = $nullRevision->insertOn( $dbw );
1787 $latest = $this->getLatest();
1788 # Update page record
1789 $dbw->update( 'page',
1791 'page_touched' => $dbw->timestamp(),
1792 'page_restrictions' => '',
1793 'page_latest' => $nullRevId
1794 ), array( /* WHERE */
1799 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1800 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1801 } else { # Protection of non-existing page (also known as "title protection")
1802 # Cascade protection is meaningless in this case
1805 if ( $limit['create'] != '' ) {
1806 $dbw->replace( 'protected_titles',
1807 array( array( 'pt_namespace', 'pt_title' ) ),
1809 'pt_namespace' => $this->mTitle
->getNamespace(),
1810 'pt_title' => $this->mTitle
->getDBkey(),
1811 'pt_create_perm' => $limit['create'],
1812 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1813 'pt_expiry' => $encodedExpiry['create'],
1814 'pt_user' => $user->getId(),
1815 'pt_reason' => $reason,
1819 $dbw->delete( 'protected_titles',
1821 'pt_namespace' => $this->mTitle
->getNamespace(),
1822 'pt_title' => $this->mTitle
->getDBkey()
1828 $this->mTitle
->flushRestrictions();
1830 if ( $logAction == 'unprotect' ) {
1831 $logParams = array();
1833 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1836 # Update the protection log
1837 $log = new LogPage( 'protect' );
1838 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1840 return Status
::newGood();
1844 * Take an array of page restrictions and flatten it to a string
1845 * suitable for insertion into the page_restrictions field.
1846 * @param $limit Array
1849 protected static function flattenRestrictions( $limit ) {
1850 if ( !is_array( $limit ) ) {
1851 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1857 foreach ( $limit as $action => $restrictions ) {
1858 if ( $restrictions != '' ) {
1859 $bits[] = "$action=$restrictions";
1863 return implode( ':', $bits );
1867 * Back-end article deletion
1868 * Deletes the article with database consistency, writes logs, purges caches
1870 * @param $reason string delete reason for deletion log
1871 * @param $suppress bitfield
1872 * Revision::DELETED_TEXT
1873 * Revision::DELETED_COMMENT
1874 * Revision::DELETED_USER
1875 * Revision::DELETED_RESTRICTED
1876 * @param $id int article ID
1877 * @param $commit boolean defaults to true, triggers transaction end
1878 * @param &$errors Array of errors to append to
1879 * @param $user User The relevant user
1880 * @return boolean true if successful
1882 public function doDeleteArticle(
1883 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1886 $user = is_null( $user ) ?
$wgUser : $user;
1888 wfDebug( __METHOD__
. "\n" );
1890 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1893 $dbw = wfGetDB( DB_MASTER
);
1894 $t = $this->mTitle
->getDBkey();
1895 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1897 if ( $t === '' ||
$id == 0 ) {
1901 // Bitfields to further suppress the content
1904 // This should be 15...
1905 $bitfield |
= Revision
::DELETED_TEXT
;
1906 $bitfield |
= Revision
::DELETED_COMMENT
;
1907 $bitfield |
= Revision
::DELETED_USER
;
1908 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1910 $bitfield = 'rev_deleted';
1914 // For now, shunt the revision data into the archive table.
1915 // Text is *not* removed from the text table; bulk storage
1916 // is left intact to avoid breaking block-compression or
1917 // immutable storage schemes.
1919 // For backwards compatibility, note that some older archive
1920 // table entries will have ar_text and ar_flags fields still.
1922 // In the future, we may keep revisions and mark them with
1923 // the rev_deleted field, which is reserved for this purpose.
1924 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1926 'ar_namespace' => 'page_namespace',
1927 'ar_title' => 'page_title',
1928 'ar_comment' => 'rev_comment',
1929 'ar_user' => 'rev_user',
1930 'ar_user_text' => 'rev_user_text',
1931 'ar_timestamp' => 'rev_timestamp',
1932 'ar_minor_edit' => 'rev_minor_edit',
1933 'ar_rev_id' => 'rev_id',
1934 'ar_parent_id' => 'rev_parent_id',
1935 'ar_text_id' => 'rev_text_id',
1936 'ar_text' => '\'\'', // Be explicit to appease
1937 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1938 'ar_len' => 'rev_len',
1939 'ar_page_id' => 'page_id',
1940 'ar_deleted' => $bitfield,
1941 'ar_sha1' => 'rev_sha1'
1944 'page_id = rev_page'
1948 # Now that it's safely backed up, delete it
1949 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1950 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1957 $this->doDeleteUpdates( $id );
1959 # Log the deletion, if the page was suppressed, log it at Oversight instead
1960 $logtype = $suppress ?
'suppress' : 'delete';
1962 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1963 $logEntry->setPerformer( $user );
1964 $logEntry->setTarget( $this->mTitle
);
1965 $logEntry->setComment( $reason );
1966 $logid = $logEntry->insert();
1967 $logEntry->publish( $logid );
1973 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1978 * Do some database updates after deletion
1980 * @param $id Int: page_id value of the page being deleted
1982 public function doDeleteUpdates( $id ) {
1983 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
1985 $dbw = wfGetDB( DB_MASTER
);
1987 # Delete restrictions for it
1988 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1990 # Fix category table counts
1992 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1994 foreach ( $res as $row ) {
1995 $cats [] = $row->cl_to
;
1998 $this->updateCategoryCounts( array(), $cats );
2000 # If using cascading deletes, we can skip some explicit deletes
2001 if ( !$dbw->cascadingDeletes() ) {
2002 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2004 # Delete outgoing links
2005 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2006 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2007 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2008 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2009 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2010 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2011 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2012 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2013 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2016 # If using cleanup triggers, we can skip some manual deletes
2017 if ( !$dbw->cleanupTriggers() ) {
2018 # Clean up recentchanges entries...
2019 $dbw->delete( 'recentchanges',
2020 array( 'rc_type != ' . RC_LOG
,
2021 'rc_namespace' => $this->mTitle
->getNamespace(),
2022 'rc_title' => $this->mTitle
->getDBkey() ),
2024 $dbw->delete( 'recentchanges',
2025 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2030 self
::onArticleDelete( $this->mTitle
);
2032 # Clear the cached article id so the interface doesn't act like we exist
2033 $this->mTitle
->resetArticleID( 0 );
2037 * Roll back the most recent consecutive set of edits to a page
2038 * from the same user; fails if there are no eligible edits to
2039 * roll back to, e.g. user is the sole contributor. This function
2040 * performs permissions checks on $user, then calls commitRollback()
2041 * to do the dirty work
2043 * @todo: seperate the business/permission stuff out from backend code
2045 * @param $fromP String: Name of the user whose edits to rollback.
2046 * @param $summary String: Custom summary. Set to default summary if empty.
2047 * @param $token String: Rollback token.
2048 * @param $bot Boolean: If true, mark all reverted edits as bot.
2050 * @param $resultDetails Array: contains result-specific array of additional values
2051 * 'alreadyrolled' : 'current' (rev)
2052 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2054 * @param $user User The user performing the rollback
2055 * @return array of errors, each error formatted as
2056 * array(messagekey, param1, param2, ...).
2057 * On success, the array is empty. This array can also be passed to
2058 * OutputPage::showPermissionsErrorPage().
2060 public function doRollback(
2061 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2063 $resultDetails = null;
2066 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2067 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2068 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2070 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2071 $errors[] = array( 'sessionfailure' );
2074 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2075 $errors[] = array( 'actionthrottledtext' );
2078 # If there were errors, bail out now
2079 if ( !empty( $errors ) ) {
2083 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2087 * Backend implementation of doRollback(), please refer there for parameter
2088 * and return value documentation
2090 * NOTE: This function does NOT check ANY permissions, it just commits the
2091 * rollback to the DB. Therefore, you should only call this function direct-
2092 * ly if you want to use custom permissions checks. If you don't, use
2093 * doRollback() instead.
2094 * @param $fromP String: Name of the user whose edits to rollback.
2095 * @param $summary String: Custom summary. Set to default summary if empty.
2096 * @param $bot Boolean: If true, mark all reverted edits as bot.
2098 * @param $resultDetails Array: contains result-specific array of additional values
2099 * @param $guser User The user performing the rollback
2101 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2102 global $wgUseRCPatrol, $wgContLang;
2104 $dbw = wfGetDB( DB_MASTER
);
2106 if ( wfReadOnly() ) {
2107 return array( array( 'readonlytext' ) );
2110 # Get the last editor
2111 $current = Revision
::newFromTitle( $this->mTitle
);
2112 if ( is_null( $current ) ) {
2113 # Something wrong... no page?
2114 return array( array( 'notanarticle' ) );
2117 $from = str_replace( '_', ' ', $fromP );
2118 # User name given should match up with the top revision.
2119 # If the user was deleted then $from should be empty.
2120 if ( $from != $current->getUserText() ) {
2121 $resultDetails = array( 'current' => $current );
2122 return array( array( 'alreadyrolled',
2123 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2124 htmlspecialchars( $fromP ),
2125 htmlspecialchars( $current->getUserText() )
2129 # Get the last edit not by this guy...
2130 # Note: these may not be public values
2131 $user = intval( $current->getRawUser() );
2132 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2133 $s = $dbw->selectRow( 'revision',
2134 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2135 array( 'rev_page' => $current->getPage(),
2136 "rev_user != {$user} OR rev_user_text != {$user_text}"
2138 array( 'USE INDEX' => 'page_timestamp',
2139 'ORDER BY' => 'rev_timestamp DESC' )
2141 if ( $s === false ) {
2142 # No one else ever edited this page
2143 return array( array( 'cantrollback' ) );
2144 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2145 # Only admins can see this text
2146 return array( array( 'notvisiblerev' ) );
2150 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2151 # Mark all reverted edits as bot
2155 if ( $wgUseRCPatrol ) {
2156 # Mark all reverted edits as patrolled
2157 $set['rc_patrolled'] = 1;
2160 if ( count( $set ) ) {
2161 $dbw->update( 'recentchanges', $set,
2163 'rc_cur_id' => $current->getPage(),
2164 'rc_user_text' => $current->getUserText(),
2165 "rc_timestamp > '{$s->rev_timestamp}'",
2170 # Generate the edit summary if necessary
2171 $target = Revision
::newFromId( $s->rev_id
);
2172 if ( empty( $summary ) ) {
2173 if ( $from == '' ) { // no public user name
2174 $summary = wfMsgForContent( 'revertpage-nouser' );
2176 $summary = wfMsgForContent( 'revertpage' );
2180 # Allow the custom summary to use the same args as the default message
2182 $target->getUserText(), $from, $s->rev_id
,
2183 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2184 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2186 $summary = wfMsgReplaceArgs( $summary, $args );
2189 $flags = EDIT_UPDATE
;
2191 if ( $guser->isAllowed( 'minoredit' ) ) {
2192 $flags |
= EDIT_MINOR
;
2195 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2196 $flags |
= EDIT_FORCE_BOT
;
2199 # Actually store the edit
2200 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2201 if ( !empty( $status->value
['revision'] ) ) {
2202 $revId = $status->value
['revision']->getId();
2207 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2209 $resultDetails = array(
2210 'summary' => $summary,
2211 'current' => $current,
2212 'target' => $target,
2220 * The onArticle*() functions are supposed to be a kind of hooks
2221 * which should be called whenever any of the specified actions
2224 * This is a good place to put code to clear caches, for instance.
2226 * This is called on page move and undelete, as well as edit
2228 * @param $title Title object
2230 public static function onArticleCreate( $title ) {
2231 # Update existence markers on article/talk tabs...
2232 if ( $title->isTalkPage() ) {
2233 $other = $title->getSubjectPage();
2235 $other = $title->getTalkPage();
2238 $other->invalidateCache();
2239 $other->purgeSquid();
2241 $title->touchLinks();
2242 $title->purgeSquid();
2243 $title->deleteTitleProtection();
2247 * Clears caches when article is deleted
2249 * @param $title Title
2251 public static function onArticleDelete( $title ) {
2252 # Update existence markers on article/talk tabs...
2253 if ( $title->isTalkPage() ) {
2254 $other = $title->getSubjectPage();
2256 $other = $title->getTalkPage();
2259 $other->invalidateCache();
2260 $other->purgeSquid();
2262 $title->touchLinks();
2263 $title->purgeSquid();
2266 HTMLFileCache
::clearFileCache( $title );
2269 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2270 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2274 if ( $title->getNamespace() == NS_FILE
) {
2275 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2276 $update->doUpdate();
2280 if ( $title->getNamespace() == NS_USER_TALK
) {
2281 $user = User
::newFromName( $title->getText(), false );
2283 $user->setNewtalk( false );
2288 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2292 * Purge caches on page update etc
2294 * @param $title Title object
2295 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2297 public static function onArticleEdit( $title ) {
2298 // Invalidate caches of articles which include this page
2299 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2302 // Invalidate the caches of all pages which redirect here
2303 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2305 # Purge squid for this page only
2306 $title->purgeSquid();
2308 # Clear file cache for this page only
2309 HTMLFileCache
::clearFileCache( $title );
2315 * Returns a list of hidden categories this page is a member of.
2316 * Uses the page_props and categorylinks tables.
2318 * @return Array of Title objects
2320 public function getHiddenCategories() {
2322 $id = $this->mTitle
->getArticleID();
2328 $dbr = wfGetDB( DB_SLAVE
);
2329 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2331 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2332 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2335 if ( $res !== false ) {
2336 foreach ( $res as $row ) {
2337 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2345 * Return an applicable autosummary if one exists for the given edit.
2346 * @param $oldtext String: the previous text of the page.
2347 * @param $newtext String: The submitted text of the page.
2348 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2349 * @return string An appropriate autosummary, or an empty string.
2351 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2354 # Decide what kind of autosummary is needed.
2356 # Redirect autosummaries
2357 $ot = Title
::newFromRedirect( $oldtext );
2358 $rt = Title
::newFromRedirect( $newtext );
2360 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2361 $truncatedtext = $wgContLang->truncate(
2362 str_replace( "\n", ' ', $newtext ),
2364 - strlen( wfMsgForContent( 'autoredircomment' ) )
2365 - strlen( $rt->getFullText() )
2367 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2370 # New page autosummaries
2371 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2372 # If they're making a new article, give its text, truncated, in the summary.
2374 $truncatedtext = $wgContLang->truncate(
2375 str_replace( "\n", ' ', $newtext ),
2376 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2378 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2381 # Blanking autosummaries
2382 if ( $oldtext != '' && $newtext == '' ) {
2383 return wfMsgForContent( 'autosumm-blank' );
2384 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2385 # Removing more than 90% of the article
2387 $truncatedtext = $wgContLang->truncate(
2389 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2391 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2394 # If we reach this point, there's no applicable autosummary for our case, so our
2395 # autosummary is empty.
2400 * Auto-generates a deletion reason
2402 * @param &$hasHistory Boolean: whether the page has a history
2403 * @return mixed String containing deletion reason or empty string, or boolean false
2404 * if no revision occurred
2406 public function getAutoDeleteReason( &$hasHistory ) {
2409 $dbw = wfGetDB( DB_MASTER
);
2410 // Get the last revision
2411 $rev = Revision
::newFromTitle( $this->getTitle() );
2413 if ( is_null( $rev ) ) {
2417 // Get the article's contents
2418 $contents = $rev->getText();
2421 // If the page is blank, use the text from the previous revision,
2422 // which can only be blank if there's a move/import/protect dummy revision involved
2423 if ( $contents == '' ) {
2424 $prev = $rev->getPrevious();
2427 $contents = $prev->getText();
2432 // Find out if there was only one contributor
2433 // Only scan the last 20 revisions
2434 $res = $dbw->select( 'revision', 'rev_user_text',
2435 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2437 array( 'LIMIT' => 20 )
2440 if ( $res === false ) {
2441 // This page has no revisions, which is very weird
2445 $hasHistory = ( $res->numRows() > 1 );
2446 $row = $dbw->fetchObject( $res );
2448 if ( $row ) { // $row is false if the only contributor is hidden
2449 $onlyAuthor = $row->rev_user_text
;
2450 // Try to find a second contributor
2451 foreach ( $res as $row ) {
2452 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2453 $onlyAuthor = false;
2458 $onlyAuthor = false;
2461 // Generate the summary with a '$1' placeholder
2463 // The current revision is blank and the one before is also
2464 // blank. It's just not our lucky day
2465 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2467 if ( $onlyAuthor ) {
2468 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2470 $reason = wfMsgForContent( 'excontent', '$1' );
2474 if ( $reason == '-' ) {
2475 // Allow these UI messages to be blanked out cleanly
2479 // Replace newlines with spaces to prevent uglyness
2480 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2481 // Calculate the maximum amount of chars to get
2482 // Max content length = max comment length - length of the comment (excl. $1)
2483 $maxLength = 255 - ( strlen( $reason ) - 2 );
2484 $contents = $wgContLang->truncate( $contents, $maxLength );
2485 // Remove possible unfinished links
2486 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2487 // Now replace the '$1' placeholder
2488 $reason = str_replace( '$1', $contents, $reason );
2494 * Update all the appropriate counts in the category table, given that
2495 * we've added the categories $added and deleted the categories $deleted.
2497 * @param $added array The names of categories that were added
2498 * @param $deleted array The names of categories that were deleted
2500 public function updateCategoryCounts( $added, $deleted ) {
2501 $ns = $this->mTitle
->getNamespace();
2502 $dbw = wfGetDB( DB_MASTER
);
2504 # First make sure the rows exist. If one of the "deleted" ones didn't
2505 # exist, we might legitimately not create it, but it's simpler to just
2506 # create it and then give it a negative value, since the value is bogus
2509 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2510 $insertCats = array_merge( $added, $deleted );
2511 if ( !$insertCats ) {
2512 # Okay, nothing to do
2516 $insertRows = array();
2518 foreach ( $insertCats as $cat ) {
2519 $insertRows[] = array(
2520 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2524 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2526 $addFields = array( 'cat_pages = cat_pages + 1' );
2527 $removeFields = array( 'cat_pages = cat_pages - 1' );
2529 if ( $ns == NS_CATEGORY
) {
2530 $addFields[] = 'cat_subcats = cat_subcats + 1';
2531 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2532 } elseif ( $ns == NS_FILE
) {
2533 $addFields[] = 'cat_files = cat_files + 1';
2534 $removeFields[] = 'cat_files = cat_files - 1';
2541 array( 'cat_title' => $added ),
2550 array( 'cat_title' => $deleted ),
2557 * Updates cascading protections
2559 * @param $parserOutput ParserOutput object for the current version
2561 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2562 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2566 // templatelinks table may have become out of sync,
2567 // especially if using variable-based transclusions.
2568 // For paranoia, check if things have changed and if
2569 // so apply updates to the database. This will ensure
2570 // that cascaded protections apply as soon as the changes
2573 # Get templates from templatelinks
2574 $id = $this->mTitle
->getArticleID();
2576 $tlTemplates = array();
2578 $dbr = wfGetDB( DB_SLAVE
);
2579 $res = $dbr->select( array( 'templatelinks' ),
2580 array( 'tl_namespace', 'tl_title' ),
2581 array( 'tl_from' => $id ),
2585 foreach ( $res as $row ) {
2586 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2589 # Get templates from parser output.
2590 $poTemplates = array();
2591 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2592 foreach ( $templates as $dbk => $id ) {
2593 $poTemplates["$ns:$dbk"] = true;
2598 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2600 if ( count( $templates_diff ) > 0 ) {
2601 # Whee, link updates time.
2602 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2608 * Return a list of templates used by this article.
2609 * Uses the templatelinks table
2611 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2612 * @return Array of Title objects
2614 public function getUsedTemplates() {
2615 return $this->mTitle
->getTemplateLinksFrom();
2619 * Perform article updates on a special page creation.
2621 * @param $rev Revision object
2623 * @todo This is a shitty interface function. Kill it and replace the
2624 * other shitty functions like doEditUpdates and such so it's not needed
2626 * @deprecated since 1.18, use doEditUpdates()
2628 public function createUpdates( $rev ) {
2629 wfDeprecated( __METHOD__
, '1.18' );
2631 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2635 * This function is called right before saving the wikitext,
2636 * so we can do things like signatures and links-in-context.
2638 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2639 * @param $text String article contents
2640 * @param $user User object: user doing the edit
2641 * @param $popts ParserOptions object: parser options, default options for
2642 * the user loaded if null given
2643 * @return string article contents with altered wikitext markup (signatures
2644 * converted, {{subst:}}, templates, etc.)
2646 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2647 global $wgParser, $wgUser;
2649 wfDeprecated( __METHOD__
, '1.19' );
2651 $user = is_null( $user ) ?
$wgUser : $user;
2653 if ( $popts === null ) {
2654 $popts = ParserOptions
::newFromUser( $user );
2657 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2661 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2663 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2666 public function isBigDeletion() {
2667 wfDeprecated( __METHOD__
, '1.19' );
2668 return $this->mTitle
->isBigDeletion();
2672 * Get the approximate revision count of this page.
2674 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2677 public function estimateRevisionCount() {
2678 wfDeprecated( __METHOD__
, '1.19' );
2679 return $this->mTitle
->estimateRevisionCount();
2683 * Update the article's restriction field, and leave a log entry.
2685 * @deprecated since 1.19
2686 * @param $limit Array: set of restriction keys
2687 * @param $reason String
2688 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2689 * @param $expiry Array: per restriction type expiration
2690 * @param $user User The user updating the restrictions
2691 * @return bool true on success
2693 public function updateRestrictions(
2694 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2698 $user = is_null( $user ) ?
$wgUser : $user;
2700 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2704 * @deprecated since 1.18
2706 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2707 wfDeprecated( __METHOD__
, '1.18' );
2709 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2713 * @deprecated since 1.18
2715 public function viewUpdates() {
2716 wfDeprecated( __METHOD__
, '1.18' );
2718 return $this->doViewUpdates( $wgUser );
2722 * @deprecated since 1.18
2724 public function useParserCache( $oldid ) {
2725 wfDeprecated( __METHOD__
, '1.18' );
2727 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2731 class PoolWorkArticleView
extends PoolCounterWork
{
2749 * @var ParserOptions
2751 private $parserOptions;
2759 * @var ParserOutput|false
2761 private $parserOutput = false;
2766 private $isDirty = false;
2771 private $error = false;
2777 * @param $revid Integer: ID of the revision being parsed
2778 * @param $useParserCache Boolean: whether to use the parser cache
2779 * @param $parserOptions parserOptions to use for the parse operation
2780 * @param $text String: text to parse or null to load it
2782 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2783 $this->page
= $page;
2784 $this->revid
= $revid;
2785 $this->cacheable
= $useParserCache;
2786 $this->parserOptions
= $parserOptions;
2787 $this->text
= $text;
2788 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2789 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2793 * Get the ParserOutput from this object, or false in case of failure
2795 * @return ParserOutput
2797 public function getParserOutput() {
2798 return $this->parserOutput
;
2802 * Get whether the ParserOutput is a dirty one (i.e. expired)
2806 public function getIsDirty() {
2807 return $this->isDirty
;
2811 * Get a Status object in case of error or false otherwise
2813 * @return Status|false
2815 public function getError() {
2816 return $this->error
;
2823 global $wgParser, $wgUseFileCache;
2825 $isCurrent = $this->revid
=== $this->page
->getLatest();
2827 if ( $this->text
!== null ) {
2828 $text = $this->text
;
2829 } elseif ( $isCurrent ) {
2830 $text = $this->page
->getRawText();
2832 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2833 if ( $rev === null ) {
2836 $text = $rev->getText();
2840 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2841 $this->parserOptions
, true, true, $this->revid
);
2846 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2847 $this->page
->getTitle()->getPrefixedDBkey() ) );
2850 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2851 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2854 // Make sure file cache is not used on uncacheable content.
2855 // Output that has magic words in it can still use the parser cache
2856 // (if enabled), though it will generally expire sooner.
2857 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2858 $wgUseFileCache = false;
2862 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2871 function getCachedWork() {
2872 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2874 if ( $this->parserOutput
=== false ) {
2875 wfDebug( __METHOD__
. ": parser cache miss\n" );
2878 wfDebug( __METHOD__
. ": parser cache hit\n" );
2886 function fallback() {
2887 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2889 if ( $this->parserOutput
=== false ) {
2890 wfDebugLog( 'dirty', "dirty missing\n" );
2891 wfDebug( __METHOD__
. ": no dirty cache\n" );
2894 wfDebug( __METHOD__
. ": sending dirty output\n" );
2895 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2896 $this->isDirty
= true;
2902 * @param $status Status
2904 function error( $status ) {
2905 $this->error
= $status;