ed66879d4d9e551165c99f3979f5ae0badc31979
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 $mCounter = -1; // !< Integer (-1 means "not loaded")
25 public $mDataLoaded = false; // !< Boolean
26 public $mIsRedirect = false; // !< Boolean
27 public $mLatest = false; // !< Integer (false means "not loaded")
28 public $mPreparedEdit = false; // !< Array
33 protected $mRedirectTarget = null;
38 protected $mLastRevision = null;
40 protected $mTimestamp = ''; // !< String
41 protected $mTouched = '19700101000000'; // !< String
45 * Constructor and clear the article
46 * @param $title Title Reference to a Title object.
48 public function __construct( Title
$title ) {
49 $this->mTitle
= $title;
53 * Create a WikiPage object of the appropriate class for the given title.
56 * @return WikiPage object of the appropriate type
58 public static function factory( Title
$title ) {
59 $ns = $title->getNamespace();
61 if ( $ns == NS_MEDIA
) {
62 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
63 } elseif ( $ns < 0 ) {
64 throw new MWException( "Invalid or virtual namespace $ns given." );
69 $page = new WikiFilePage( $title );
72 $page = new WikiCategoryPage( $title );
75 $page = new WikiPage( $title );
82 * Constructor from a page id
84 * @param $id Int article ID to load
88 public static function newFromID( $id ) {
89 $t = Title
::newFromID( $id );
91 return self
::factory( $t );
97 * Returns overrides for action handlers.
98 * Classes listed here will be used instead of the default one when
99 * (and only when) $wgActions[$action] === true. This allows subclasses
100 * to override the default behavior.
102 * @todo: move this UI stuff somewhere else
106 public function getActionOverrides() {
111 * If this page is a redirect, get its target
113 * The target will be fetched from the redirect table if possible.
114 * If this page doesn't have an entry there, call insertRedirect()
115 * @return Title|mixed object, or null if this page is not a redirect
117 public function getRedirectTarget() {
118 if ( !$this->mTitle
->isRedirect() ) {
122 if ( $this->mRedirectTarget
!== null ) {
123 return $this->mRedirectTarget
;
126 # Query the redirect table
127 $dbr = wfGetDB( DB_SLAVE
);
128 $row = $dbr->selectRow( 'redirect',
129 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
130 array( 'rd_from' => $this->getId() ),
134 // rd_fragment and rd_interwiki were added later, populate them if empty
135 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
136 return $this->mRedirectTarget
= Title
::makeTitle(
137 $row->rd_namespace
, $row->rd_title
,
138 $row->rd_fragment
, $row->rd_interwiki
);
141 # This page doesn't have an entry in the redirect table
142 return $this->mRedirectTarget
= $this->insertRedirect();
146 * Insert an entry for this page into the redirect table.
148 * Don't call this function directly unless you know what you're doing.
149 * @return Title object or null if not a redirect
151 public function insertRedirect() {
152 // recurse through to only get the final target
153 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
157 $this->insertRedirectEntry( $retval );
162 * Insert or update the redirect table entry for this page to indicate
163 * it redirects to $rt .
164 * @param $rt Title redirect target
166 public function insertRedirectEntry( $rt ) {
167 $dbw = wfGetDB( DB_MASTER
);
168 $dbw->replace( 'redirect', array( 'rd_from' ),
170 'rd_from' => $this->getId(),
171 'rd_namespace' => $rt->getNamespace(),
172 'rd_title' => $rt->getDBkey(),
173 'rd_fragment' => $rt->getFragment(),
174 'rd_interwiki' => $rt->getInterwiki(),
181 * Get the Title object or URL this page redirects to
183 * @return mixed false, Title of in-wiki target, or string with URL
185 public function followRedirect() {
186 return $this->getRedirectURL( $this->getRedirectTarget() );
190 * Get the Title object or URL to use for a redirect. We use Title
191 * objects for same-wiki, non-special redirects and URLs for everything
193 * @param $rt Title Redirect target
194 * @return mixed false, Title object of local target, or string with URL
196 public function getRedirectURL( $rt ) {
198 if ( $rt->getInterwiki() != '' ) {
199 if ( $rt->isLocal() ) {
200 // Offsite wikis need an HTTP redirect.
202 // This can be hard to reverse and may produce loops,
203 // so they may be disabled in the site configuration.
204 $source = $this->mTitle
->getFullURL( 'redirect=no' );
205 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
208 if ( $rt->isSpecialPage() ) {
209 // Gotta handle redirects to special pages differently:
210 // Fill the HTTP response "Location" header and ignore
211 // the rest of the page we're on.
213 // This can be hard to reverse, so they may be disabled.
214 if ( $rt->isSpecial( 'Userlogout' ) ) {
217 return $rt->getFullURL();
225 // No or invalid redirect
230 * Get the title object of the article
231 * @return Title object of this page
233 public function getTitle() {
234 return $this->mTitle
;
240 public function clear() {
241 $this->mDataLoaded
= false;
243 $this->mCounter
= -1; # Not loaded
244 $this->mRedirectTarget
= null; # Title object if set
245 $this->mLastRevision
= null; # Latest revision
246 $this->mTimestamp
= '';
247 $this->mTouched
= '19700101000000';
248 $this->mIsRedirect
= false;
249 $this->mLatest
= false;
250 $this->mPreparedEdit
= false;
254 * Get the text that needs to be saved in order to undo all revisions
255 * between $undo and $undoafter. Revisions must belong to the same page,
256 * must exist and must not be deleted
257 * @param $undo Revision
258 * @param $undoafter Revision Must be an earlier revision than $undo
259 * @return mixed string on success, false on failure
261 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
262 $cur_text = $this->getRawText();
263 if ( $cur_text === false ) {
264 return false; // no page
266 $undo_text = $undo->getText();
267 $undoafter_text = $undoafter->getText();
269 if ( $cur_text == $undo_text ) {
270 # No use doing a merge if it's just a straight revert.
271 return $undoafter_text;
276 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
284 * Return the list of revision fields that should be selected to create
289 public static function selectFields() {
306 * Fetch a page record with the given conditions
307 * @param $dbr DatabaseBase object
308 * @param $conditions Array
309 * @return mixed Database result resource, or false on failure
311 protected function pageData( $dbr, $conditions ) {
312 $fields = self
::selectFields();
314 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
316 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
318 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
324 * Fetch a page record matching the Title object's namespace and title
325 * using a sanitized title string
327 * @param $dbr DatabaseBase object
328 * @param $title Title object
329 * @return mixed Database result resource, or false on failure
331 public function pageDataFromTitle( $dbr, $title ) {
332 return $this->pageData( $dbr, array(
333 'page_namespace' => $title->getNamespace(),
334 'page_title' => $title->getDBkey() ) );
338 * Fetch a page record matching the requested ID
340 * @param $dbr DatabaseBase
342 * @return mixed Database result resource, or false on failure
344 public function pageDataFromId( $dbr, $id ) {
345 return $this->pageData( $dbr, array( 'page_id' => $id ) );
349 * Set the general counter, title etc data loaded from
352 * @param $data Object|String One of the following:
353 * A DB query result object or...
354 * "fromdb" to get from a slave DB or...
355 * "fromdbmaster" to get from the master DB
358 public function loadPageData( $data = 'fromdb' ) {
359 if ( $data === 'fromdbmaster' ) {
360 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
361 } elseif ( $data === 'fromdb' ) { // slave
362 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
363 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
364 # Note that DB also stores the master position in the session and checks it.
365 $touched = $this->getCachedLastEditTime();
366 if ( $touched ) { // key set
367 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
368 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
373 $lc = LinkCache
::singleton();
376 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
378 $this->mTitle
->loadFromRow( $data );
380 # Old-fashioned restrictions
381 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
383 $this->mCounter
= intval( $data->page_counter
);
384 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
385 $this->mIsRedirect
= intval( $data->page_is_redirect
);
386 $this->mLatest
= intval( $data->page_latest
);
388 $lc->addBadLinkObj( $this->mTitle
);
390 $this->mTitle
->loadFromRow( false );
393 $this->mDataLoaded
= true;
397 * @return int Page ID
399 public function getId() {
400 return $this->mTitle
->getArticleID();
404 * @return bool Whether or not the page exists in the database
406 public function exists() {
407 return $this->getId() > 0;
411 * Check if this page is something we're going to be showing
412 * some sort of sensible content for. If we return false, page
413 * views (plain action=view) will return an HTTP 404 response,
414 * so spiders and robots can know they're following a bad link.
418 public function hasViewableContent() {
419 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
423 * @return int The view count for the page
425 public function getCount() {
426 if ( -1 == $this->mCounter
) {
427 $id = $this->getId();
432 $dbr = wfGetDB( DB_SLAVE
);
433 $this->mCounter
= $dbr->selectField( 'page',
435 array( 'page_id' => $id ),
441 return $this->mCounter
;
445 * Determine whether a page would be suitable for being counted as an
446 * article in the site_stats table based on the title & its content
448 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
449 * if false, the current database state will be used
452 public function isCountable( $editInfo = false ) {
453 global $wgArticleCountMethod;
455 if ( !$this->mTitle
->isContentPage() ) {
459 $text = $editInfo ?
$editInfo->pst
: false;
461 if ( $this->isRedirect( $text ) ) {
465 switch ( $wgArticleCountMethod ) {
469 if ( $text === false ) {
470 $text = $this->getRawText();
472 return strpos( $text, ',' ) !== false;
475 // ParserOutput::getLinks() is a 2D array of page links, so
476 // to be really correct we would need to recurse in the array
477 // but the main array should only have items in it if there are
479 return (bool)count( $editInfo->output
->getLinks() );
481 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
482 array( 'pl_from' => $this->getId() ), __METHOD__
);
488 * Tests if the article text represents a redirect
490 * @param $text mixed string containing article contents, or boolean
493 public function isRedirect( $text = false ) {
494 if ( $text === false ) {
495 if ( !$this->mDataLoaded
) {
496 $this->loadPageData();
499 return (bool)$this->mIsRedirect
;
501 return Title
::newFromRedirect( $text ) !== null;
506 * Loads everything except the text
507 * This isn't necessary for all uses, so it's only done if needed.
509 protected function loadLastEdit() {
510 if ( $this->mLastRevision
!== null ) {
511 return; // already loaded
514 $latest = $this->getLatest();
516 return; // page doesn't exist or is missing page_latest info
519 $revision = Revision
::newFromPageId( $this->getId(), $latest );
520 if ( $revision ) { // sanity
521 $this->setLastEdit( $revision );
526 * Set the latest revision
528 protected function setLastEdit( Revision
$revision ) {
529 $this->mLastRevision
= $revision;
530 $this->mTimestamp
= $revision->getTimestamp();
534 * Get the latest revision
535 * @return Revision|null
537 public function getRevision() {
538 $this->loadLastEdit();
539 if ( $this->mLastRevision
) {
540 return $this->mLastRevision
;
546 * Get the text of the current revision. No side-effects...
548 * @param $audience Integer: one of:
549 * Revision::FOR_PUBLIC to be displayed to all users
550 * Revision::FOR_THIS_USER to be displayed to $wgUser
551 * Revision::RAW get the text regardless of permissions
552 * @return String|false The text of the current revision
554 public function getText( $audience = Revision
::FOR_PUBLIC
) {
555 $this->loadLastEdit();
556 if ( $this->mLastRevision
) {
557 return $this->mLastRevision
->getText( $audience );
563 * Get the text of the current revision. No side-effects...
565 * @return String|false The text of the current revision
567 public function getRawText() {
568 $this->loadLastEdit();
569 if ( $this->mLastRevision
) {
570 return $this->mLastRevision
->getRawText();
576 * @return string MW timestamp of last article revision
578 public function getTimestamp() {
579 // Check if the field has been filled by WikiPage::setTimestamp()
580 if ( !$this->mTimestamp
) {
581 $this->loadLastEdit();
583 return wfTimestamp( TS_MW
, $this->mTimestamp
);
587 * Set the page timestamp (use only to avoid DB queries)
588 * @param $ts string MW timestamp of last article revision
591 public function setTimestamp( $ts ) {
592 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
596 * @param $audience Integer: one of:
597 * Revision::FOR_PUBLIC to be displayed to all users
598 * Revision::FOR_THIS_USER to be displayed to $wgUser
599 * Revision::RAW get the text regardless of permissions
600 * @return int user ID for the user that made the last article revision
602 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
603 $this->loadLastEdit();
604 if ( $this->mLastRevision
) {
605 return $this->mLastRevision
->getUser( $audience );
612 * @param $audience Integer: one of:
613 * Revision::FOR_PUBLIC to be displayed to all users
614 * Revision::FOR_THIS_USER to be displayed to $wgUser
615 * Revision::RAW get the text regardless of permissions
616 * @return string username of the user that made the last article revision
618 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
619 $this->loadLastEdit();
620 if ( $this->mLastRevision
) {
621 return $this->mLastRevision
->getUserText( $audience );
628 * @param $audience Integer: one of:
629 * Revision::FOR_PUBLIC to be displayed to all users
630 * Revision::FOR_THIS_USER to be displayed to $wgUser
631 * Revision::RAW get the text regardless of permissions
632 * @return string Comment stored for the last article revision
634 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
635 $this->loadLastEdit();
636 if ( $this->mLastRevision
) {
637 return $this->mLastRevision
->getComment( $audience );
644 * Returns true if last revision was marked as "minor edit"
646 * @return boolean Minor edit indicator for the last article revision.
648 public function getMinorEdit() {
649 $this->loadLastEdit();
650 if ( $this->mLastRevision
) {
651 return $this->mLastRevision
->isMinor();
658 * Get a list of users who have edited this article, not including the user who made
659 * the most recent revision, which you can get from $article->getUser() if you want it
660 * @return UserArrayFromResult
662 public function getContributors() {
663 # @todo FIXME: This is expensive; cache this info somewhere.
665 $dbr = wfGetDB( DB_SLAVE
);
667 if ( $dbr->implicitGroupby() ) {
668 $realNameField = 'user_real_name';
670 $realNameField = 'MIN(user_real_name) AS user_real_name';
673 $tables = array( 'revision', 'user' );
676 'rev_user as user_id',
677 'rev_user_text AS user_name',
679 'MAX(rev_timestamp) AS timestamp',
682 $conds = array( 'rev_page' => $this->getId() );
684 // The user who made the top revision gets credited as "this page was last edited by
685 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
686 $user = $this->getUser();
688 $conds[] = "rev_user != $user";
690 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
693 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
696 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
700 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
701 'ORDER BY' => 'timestamp DESC',
704 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
705 return new UserArrayFromResult( $res );
709 * Should the parser cache be used?
711 * @param $parserOptions ParserOptions to check
715 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
716 global $wgEnableParserCache;
718 return $wgEnableParserCache
719 && $parserOptions->getStubThreshold() == 0
721 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
722 && $this->mTitle
->isWikitextPage();
726 * Get a ParserOutput for the given ParserOptions and revision ID.
727 * The parser cache will be used if possible.
730 * @param $parserOptions ParserOptions to use for the parse operation
731 * @param $oldid Revision ID to get the text from, passing null or 0 will
732 * get the current revision (default value)
733 * @return ParserOutput or false if the revision was not found
735 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
736 wfProfileIn( __METHOD__
);
738 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
739 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
740 if ( $parserOptions->getStubThreshold() ) {
741 wfIncrStats( 'pcache_miss_stub' );
744 if ( $useParserCache ) {
745 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
746 if ( $parserOutput !== false ) {
747 wfProfileOut( __METHOD__
);
748 return $parserOutput;
752 if ( $oldid === null ||
$oldid === 0 ) {
753 $oldid = $this->getLatest();
756 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
759 wfProfileOut( __METHOD__
);
761 return $pool->getParserOutput();
765 * Perform the actions of a page purging
767 public function doPurge() {
770 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
774 // Invalidate the cache
775 $this->mTitle
->invalidateCache();
779 // Commit the transaction before the purge is sent
780 $dbw = wfGetDB( DB_MASTER
);
784 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
788 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
789 if ( $this->getId() == 0 ) {
792 $text = $this->getRawText();
795 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
801 * Insert a new empty page record for this article.
802 * This *must* be followed up by creating a revision
803 * and running $this->updateRevisionOn( ... );
804 * or else the record will be left in a funky state.
805 * Best if all done inside a transaction.
807 * @param $dbw DatabaseBase
808 * @return int The newly created page_id key, or false if the title already existed
810 public function insertOn( $dbw ) {
811 wfProfileIn( __METHOD__
);
813 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
814 $dbw->insert( 'page', array(
815 'page_id' => $page_id,
816 'page_namespace' => $this->mTitle
->getNamespace(),
817 'page_title' => $this->mTitle
->getDBkey(),
819 'page_restrictions' => '',
820 'page_is_redirect' => 0, # Will set this shortly...
822 'page_random' => wfRandom(),
823 'page_touched' => $dbw->timestamp(),
824 'page_latest' => 0, # Fill this in shortly...
825 'page_len' => 0, # Fill this in shortly...
826 ), __METHOD__
, 'IGNORE' );
828 $affected = $dbw->affectedRows();
831 $newid = $dbw->insertId();
832 $this->mTitle
->resetArticleID( $newid );
834 wfProfileOut( __METHOD__
);
836 return $affected ?
$newid : false;
840 * Update the page record to point to a newly saved revision.
842 * @param $dbw DatabaseBase: object
843 * @param $revision Revision: For ID number, and text used to set
844 * length and redirect status fields
845 * @param $lastRevision Integer: if given, will not overwrite the page field
846 * when different from the currently set value.
847 * Giving 0 indicates the new page flag should be set
849 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
850 * removing rows in redirect table.
851 * @return bool true on success, false on failure
854 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
855 wfProfileIn( __METHOD__
);
857 $text = $revision->getText();
858 $len = strlen( $text );
859 $rt = Title
::newFromRedirectRecurse( $text );
861 $conditions = array( 'page_id' => $this->getId() );
863 if ( !is_null( $lastRevision ) ) {
864 # An extra check against threads stepping on each other
865 $conditions['page_latest'] = $lastRevision;
868 $now = wfTimestampNow();
869 $dbw->update( 'page',
871 'page_latest' => $revision->getId(),
872 'page_touched' => $dbw->timestamp( $now ),
873 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
874 'page_is_redirect' => $rt !== null ?
1 : 0,
880 $result = $dbw->affectedRows() != 0;
882 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
883 $this->setLastEdit( $revision );
884 $this->setCachedLastEditTime( $now );
885 $this->mLatest
= $revision->getId();
886 $this->mIsRedirect
= (bool)$rt;
887 # Update the LinkCache.
888 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
891 wfProfileOut( __METHOD__
);
896 * Get the cached timestamp for the last time the page changed.
897 * This is only used to help handle slave lag by comparing to page_touched.
898 * @return string MW timestamp
900 protected function getCachedLastEditTime() {
902 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
903 return $wgMemc->get( $key );
907 * Set the cached timestamp for the last time the page changed.
908 * This is only used to help handle slave lag by comparing to page_touched.
909 * @param $timestamp string
912 public function setCachedLastEditTime( $timestamp ) {
914 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
915 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
919 * Add row to the redirect table if this is a redirect, remove otherwise.
921 * @param $dbw DatabaseBase
922 * @param $redirectTitle Title object pointing to the redirect target,
923 * or NULL if this is not a redirect
924 * @param $lastRevIsRedirect If given, will optimize adding and
925 * removing rows in redirect table.
926 * @return bool true on success, false on failure
929 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
930 // Always update redirects (target link might have changed)
931 // Update/Insert if we don't know if the last revision was a redirect or not
932 // Delete if changing from redirect to non-redirect
933 $isRedirect = !is_null( $redirectTitle );
935 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
939 wfProfileIn( __METHOD__
);
941 $this->insertRedirectEntry( $redirectTitle );
943 // This is not a redirect, remove row from redirect table
944 $where = array( 'rd_from' => $this->getId() );
945 $dbw->delete( 'redirect', $where, __METHOD__
);
948 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
949 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
951 wfProfileOut( __METHOD__
);
953 return ( $dbw->affectedRows() != 0 );
957 * If the given revision is newer than the currently set page_latest,
958 * update the page record. Otherwise, do nothing.
960 * @param $dbw Database object
961 * @param $revision Revision object
964 public function updateIfNewerOn( $dbw, $revision ) {
965 wfProfileIn( __METHOD__
);
967 $row = $dbw->selectRow(
968 array( 'revision', 'page' ),
969 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
971 'page_id' => $this->getId(),
972 'page_latest=rev_id' ),
976 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
977 wfProfileOut( __METHOD__
);
980 $prev = $row->rev_id
;
981 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
983 # No or missing previous revision; mark the page as new
985 $lastRevIsRedirect = null;
988 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
990 wfProfileOut( __METHOD__
);
995 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
996 * @param $text String: new text of the section
997 * @param $summary String: new section's subject, only if $section is 'new'
998 * @param $edittime String: revision timestamp or null to use the current revision
999 * @return string Complete article text, or null if error
1001 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1002 wfProfileIn( __METHOD__
);
1004 if ( strval( $section ) == '' ) {
1005 // Whole-page edit; let the whole text through
1007 if ( is_null( $edittime ) ) {
1008 $rev = Revision
::newFromTitle( $this->mTitle
);
1010 $dbw = wfGetDB( DB_MASTER
);
1011 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1015 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1016 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1017 wfProfileOut( __METHOD__
);
1021 $oldtext = $rev->getText();
1023 if ( $section == 'new' ) {
1024 # Inserting a new section
1025 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1026 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1027 $text = strlen( trim( $oldtext ) ) > 0
1028 ?
"{$oldtext}\n\n{$subject}{$text}"
1029 : "{$subject}{$text}";
1032 # Replacing an existing section; roll out the big guns
1035 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1039 wfProfileOut( __METHOD__
);
1044 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1046 * @return Int updated $flags
1048 function checkFlags( $flags ) {
1049 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1050 if ( $this->mTitle
->getArticleID() ) {
1051 $flags |
= EDIT_UPDATE
;
1061 * Change an existing article or create a new article. Updates RC and all necessary caches,
1062 * optionally via the deferred update array.
1064 * @param $text String: new text
1065 * @param $summary String: edit summary
1066 * @param $flags Integer bitfield:
1068 * Article is known or assumed to be non-existent, create a new one
1070 * Article is known or assumed to be pre-existing, update it
1072 * Mark this edit minor, if the user is allowed to do so
1074 * Do not log the change in recentchanges
1076 * Mark the edit a "bot" edit regardless of user rights
1077 * EDIT_DEFER_UPDATES
1078 * Defer some of the updates until the end of index.php
1080 * Fill in blank summaries with generated text where possible
1082 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1083 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1084 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1085 * edit-already-exists error will be returned. These two conditions are also possible with
1086 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1088 * @param $baseRevId the revision ID this edit was based off, if any
1089 * @param $user User the user doing the edit
1091 * @return Status object. Possible errors:
1092 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1093 * edit-gone-missing: In update mode, but the article didn't exist
1094 * edit-conflict: In update mode, the article changed unexpectedly
1095 * edit-no-change: Warning that the text was the same as before
1096 * edit-already-exists: In creation mode, but the article already exists
1098 * Extensions may define additional errors.
1100 * $return->value will contain an associative array with members as follows:
1101 * new: Boolean indicating if the function attempted to create a new article
1102 * revision: The revision object for the inserted revision, or null
1104 * Compatibility note: this function previously returned a boolean value indicating success/failure
1106 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1107 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1109 # Low-level sanity check
1110 if ( $this->mTitle
->getText() === '' ) {
1111 throw new MWException( 'Something is trying to edit an article with an empty title' );
1114 wfProfileIn( __METHOD__
);
1116 $user = is_null( $user ) ?
$wgUser : $user;
1117 $status = Status
::newGood( array() );
1119 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1120 $this->loadPageData( 'fromdbmaster' );
1122 $flags = $this->checkFlags( $flags );
1124 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1125 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1127 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1129 if ( $status->isOK() ) {
1130 $status->fatal( 'edit-hook-aborted' );
1133 wfProfileOut( __METHOD__
);
1137 # Silently ignore EDIT_MINOR if not allowed
1138 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1139 $bot = $flags & EDIT_FORCE_BOT
;
1141 $oldtext = $this->getRawText(); // current revision
1142 $oldsize = strlen( $oldtext );
1143 $oldid = $this->getLatest();
1144 $oldIsRedirect = $this->isRedirect();
1145 $oldcountable = $this->isCountable();
1147 # Provide autosummaries if one is not provided and autosummaries are enabled.
1148 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1149 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1152 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1153 $text = $editInfo->pst
;
1154 $newsize = strlen( $text );
1156 $dbw = wfGetDB( DB_MASTER
);
1157 $now = wfTimestampNow();
1158 $this->mTimestamp
= $now;
1160 if ( $flags & EDIT_UPDATE
) {
1161 # Update article, but only if changed.
1162 $status->value
['new'] = false;
1164 # Make sure the revision is either completely inserted or not inserted at all
1165 if ( !$wgDBtransactions ) {
1166 $userAbort = ignore_user_abort( true );
1169 $revision = new Revision( array(
1170 'page' => $this->getId(),
1171 'comment' => $summary,
1172 'minor_edit' => $isminor,
1174 'parent_id' => $oldid,
1175 'user' => $user->getId(),
1176 'user_text' => $user->getName(),
1180 $changed = ( strcmp( $text, $oldtext ) != 0 );
1183 if ( !$this->mLatest
) {
1184 # Article gone missing
1185 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1186 $status->fatal( 'edit-gone-missing' );
1188 wfProfileOut( __METHOD__
);
1193 $revisionId = $revision->insertOn( $dbw );
1197 # Note that we use $this->mLatest instead of fetching a value from the master DB
1198 # during the course of this function. This makes sure that EditPage can detect
1199 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1200 # before this function is called. A previous function used a separate query, this
1201 # creates a window where concurrent edits can cause an ignored edit conflict.
1202 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1205 /* Belated edit conflict! Run away!! */
1206 $status->fatal( 'edit-conflict' );
1208 # Delete the invalid revision if the DB is not transactional
1209 if ( !$wgDBtransactions ) {
1210 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1216 global $wgUseRCPatrol;
1217 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1218 # Update recentchanges
1219 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1220 # Mark as patrolled if the user can do so
1221 $patrolled = $wgUseRCPatrol && !count(
1222 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1223 # Add RC row to the DB
1224 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1225 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1226 $revisionId, $patrolled
1229 # Log auto-patrolled edits
1231 PatrolLog
::record( $rc, true );
1234 $user->incEditCount();
1239 if ( !$wgDBtransactions ) {
1240 ignore_user_abort( $userAbort );
1243 // Now that ignore_user_abort is restored, we can respond to fatal errors
1244 if ( !$status->isOK() ) {
1245 wfProfileOut( __METHOD__
);
1249 # Update links tables, site stats, etc.
1250 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1251 'oldcountable' => $oldcountable ) );
1254 $status->warning( 'edit-no-change' );
1256 // Keep the same revision ID, but do some updates on it
1257 $revisionId = $this->getLatest();
1258 // Update page_touched, this is usually implicit in the page update
1259 // Other cache updates are done in onArticleEdit()
1260 $this->mTitle
->invalidateCache();
1263 # Create new article
1264 $status->value
['new'] = true;
1268 # Add the page record; stake our claim on this title!
1269 # This will return false if the article already exists
1270 $newid = $this->insertOn( $dbw );
1272 if ( $newid === false ) {
1274 $status->fatal( 'edit-already-exists' );
1276 wfProfileOut( __METHOD__
);
1280 # Save the revision text...
1281 $revision = new Revision( array(
1283 'comment' => $summary,
1284 'minor_edit' => $isminor,
1286 'user' => $user->getId(),
1287 'user_text' => $user->getName(),
1290 $revisionId = $revision->insertOn( $dbw );
1292 # Update the page record with revision data
1293 $this->updateRevisionOn( $dbw, $revision, 0 );
1295 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1297 # Update recentchanges
1298 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1299 global $wgUseRCPatrol, $wgUseNPPatrol;
1301 # Mark as patrolled if the user can do so
1302 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1303 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1304 # Add RC row to the DB
1305 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1306 '', strlen( $text ), $revisionId, $patrolled );
1308 # Log auto-patrolled edits
1310 PatrolLog
::record( $rc, true );
1313 $user->incEditCount();
1316 # Update links, etc.
1317 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1319 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1320 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1323 # Do updates right now unless deferral was requested
1324 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1325 DeferredUpdates
::doUpdates();
1328 // Return the new revision (or null) to the caller
1329 $status->value
['revision'] = $revision;
1331 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1332 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1334 # Promote user to any groups they meet the criteria for
1335 $user->addAutopromoteOnceGroups( 'onEdit' );
1337 wfProfileOut( __METHOD__
);
1342 * Update the article's restriction field, and leave a log entry.
1344 * @todo: seperate the business/permission stuff out from backend code
1346 * @param $limit Array: set of restriction keys
1347 * @param $reason String
1348 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1349 * @param $expiry Array: per restriction type expiration
1350 * @param $user User The user updating the restrictions
1351 * @return bool true on success
1353 public function updateRestrictions(
1354 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
1356 global $wgUser, $wgContLang;
1357 $user = is_null( $user ) ?
$wgUser : $user;
1359 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1361 $id = $this->mTitle
->getArticleID();
1364 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1368 if ( wfReadOnly() ) {
1369 wfDebug( "updateRestrictions failed: read-only\n" );
1373 if ( count( $this->mTitle
->getUserPermissionsErrors( 'protect', $user ) ) ) {
1374 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1382 // Take this opportunity to purge out expired restrictions
1383 Title
::purgeExpiredRestrictions();
1385 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1386 # we expect a single selection, but the schema allows otherwise.
1388 $updated = self
::flattenRestrictions( $limit );
1391 foreach ( $restrictionTypes as $action ) {
1392 if ( isset( $expiry[$action] ) ) {
1393 # Get current restrictions on $action
1394 $aLimits = $this->mTitle
->getRestrictions( $action );
1395 $current[$action] = implode( '', $aLimits );
1396 # Are any actual restrictions being dealt with here?
1397 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
1399 # If something changed, we need to log it. Checking $aRChanged
1400 # assures that "unprotecting" a page that is not protected does
1401 # not log just because the expiry was "changed".
1403 $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] )
1410 $current = self
::flattenRestrictions( $current );
1412 $changed = ( $changed ||
$current != $updated );
1413 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
1414 $protect = ( $updated != '' );
1416 # If nothing's changed, do nothing
1418 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1419 $dbw = wfGetDB( DB_MASTER
);
1421 # Prepare a null revision to be added to the history
1422 $modified = $current != '' && $protect;
1425 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1427 $comment_type = 'unprotectedarticle';
1430 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1432 # Only restrictions with the 'protect' right can cascade...
1433 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1434 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1436 # The schema allows multiple restrictions
1437 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1441 $cascade_description = '';
1444 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1448 $comment .= ": $reason";
1451 $editComment = $comment;
1452 $encodedExpiry = array();
1453 $protect_description = '';
1454 foreach ( $limit as $action => $restrictions ) {
1455 if ( !isset( $expiry[$action] ) )
1456 $expiry[$action] = $dbw->getInfinity();
1458 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1459 if ( $restrictions != '' ) {
1460 $protect_description .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1461 if ( $encodedExpiry[$action] != 'infinity' ) {
1462 $protect_description .= wfMsgForContent( 'protect-expiring',
1463 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1464 $wgContLang->date( $expiry[$action], false, false ) ,
1465 $wgContLang->time( $expiry[$action], false, false ) );
1467 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1470 $protect_description .= ') ';
1473 $protect_description = trim( $protect_description );
1475 if ( $protect_description && $protect ) {
1476 $editComment .= " ($protect_description)";
1480 $editComment .= "$cascade_description";
1483 # Update restrictions table
1484 foreach ( $limit as $action => $restrictions ) {
1485 if ( $restrictions != '' ) {
1486 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1487 array( 'pr_page' => $id,
1488 'pr_type' => $action,
1489 'pr_level' => $restrictions,
1490 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1491 'pr_expiry' => $encodedExpiry[$action]
1496 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1497 'pr_type' => $action ), __METHOD__
);
1501 # Insert a null revision
1502 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1503 $nullRevId = $nullRevision->insertOn( $dbw );
1505 $latest = $this->getLatest();
1506 # Update page record
1507 $dbw->update( 'page',
1509 'page_touched' => $dbw->timestamp(),
1510 'page_restrictions' => '',
1511 'page_latest' => $nullRevId
1512 ), array( /* WHERE */
1517 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1518 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1520 # Update the protection log
1521 $log = new LogPage( 'protect' );
1523 $params = array( $protect_description, $cascade ?
'cascade' : '' );
1524 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
1526 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1529 } # End "changed" check
1535 * Take an array of page restrictions and flatten it to a string
1536 * suitable for insertion into the page_restrictions field.
1537 * @param $limit Array
1540 protected static function flattenRestrictions( $limit ) {
1541 if ( !is_array( $limit ) ) {
1542 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1548 foreach ( $limit as $action => $restrictions ) {
1549 if ( $restrictions != '' ) {
1550 $bits[] = "$action=$restrictions";
1554 return implode( ':', $bits );
1558 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1560 public function isBigDeletion() {
1561 global $wgDeleteRevisionsLimit;
1563 if ( $wgDeleteRevisionsLimit ) {
1564 $revCount = $this->estimateRevisionCount();
1566 return $revCount > $wgDeleteRevisionsLimit;
1573 * @return int approximate revision count
1575 public function estimateRevisionCount() {
1576 $dbr = wfGetDB( DB_SLAVE
);
1577 return $dbr->estimateRowCount( 'revision', '*',
1578 array( 'rev_page' => $this->getId() ), __METHOD__
);
1582 * Get the last N authors
1583 * @param $num Integer: number of revisions to get
1584 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1585 * @return array Array of authors, duplicates not removed
1587 public function getLastNAuthors( $num, $revLatest = 0 ) {
1588 wfProfileIn( __METHOD__
);
1589 // First try the slave
1590 // If that doesn't have the latest revision, try the master
1592 $db = wfGetDB( DB_SLAVE
);
1595 $res = $db->select( array( 'page', 'revision' ),
1596 array( 'rev_id', 'rev_user_text' ),
1598 'page_namespace' => $this->mTitle
->getNamespace(),
1599 'page_title' => $this->mTitle
->getDBkey(),
1600 'rev_page = page_id'
1603 'ORDER BY' => 'rev_timestamp DESC',
1609 wfProfileOut( __METHOD__
);
1613 $row = $db->fetchObject( $res );
1615 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1616 $db = wfGetDB( DB_MASTER
);
1621 } while ( $continue );
1623 $authors = array( $row->rev_user_text
);
1625 foreach ( $res as $row ) {
1626 $authors[] = $row->rev_user_text
;
1629 wfProfileOut( __METHOD__
);
1634 * Back-end article deletion
1635 * Deletes the article with database consistency, writes logs, purges caches
1637 * @param $reason string delete reason for deletion log
1638 * @param $suppress bitfield
1639 * Revision::DELETED_TEXT
1640 * Revision::DELETED_COMMENT
1641 * Revision::DELETED_USER
1642 * Revision::DELETED_RESTRICTED
1643 * @param $id int article ID
1644 * @param $commit boolean defaults to true, triggers transaction end
1645 * @param &$errors Array of errors to append to
1646 * @param $user User The relevant user
1647 * @return boolean true if successful
1649 public function doDeleteArticle(
1650 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1653 $user = is_null( $user ) ?
$wgUser : $user;
1655 wfDebug( __METHOD__
. "\n" );
1657 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1660 $dbw = wfGetDB( DB_MASTER
);
1661 $t = $this->mTitle
->getDBkey();
1662 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1664 if ( $t === '' ||
$id == 0 ) {
1668 DeferredUpdates
::addUpdate(
1669 new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 )
1672 // Bitfields to further suppress the content
1675 // This should be 15...
1676 $bitfield |
= Revision
::DELETED_TEXT
;
1677 $bitfield |
= Revision
::DELETED_COMMENT
;
1678 $bitfield |
= Revision
::DELETED_USER
;
1679 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1681 $bitfield = 'rev_deleted';
1685 // For now, shunt the revision data into the archive table.
1686 // Text is *not* removed from the text table; bulk storage
1687 // is left intact to avoid breaking block-compression or
1688 // immutable storage schemes.
1690 // For backwards compatibility, note that some older archive
1691 // table entries will have ar_text and ar_flags fields still.
1693 // In the future, we may keep revisions and mark them with
1694 // the rev_deleted field, which is reserved for this purpose.
1695 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1697 'ar_namespace' => 'page_namespace',
1698 'ar_title' => 'page_title',
1699 'ar_comment' => 'rev_comment',
1700 'ar_user' => 'rev_user',
1701 'ar_user_text' => 'rev_user_text',
1702 'ar_timestamp' => 'rev_timestamp',
1703 'ar_minor_edit' => 'rev_minor_edit',
1704 'ar_rev_id' => 'rev_id',
1705 'ar_parent_id' => 'rev_parent_id',
1706 'ar_text_id' => 'rev_text_id',
1707 'ar_text' => '\'\'', // Be explicit to appease
1708 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1709 'ar_len' => 'rev_len',
1710 'ar_page_id' => 'page_id',
1711 'ar_deleted' => $bitfield,
1712 'ar_sha1' => 'rev_sha1'
1715 'page_id = rev_page'
1719 # Delete restrictions for it
1720 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1722 # Now that it's safely backed up, delete it
1723 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1724 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1731 # Fix category table counts
1733 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1735 foreach ( $res as $row ) {
1736 $cats [] = $row->cl_to
;
1739 $this->updateCategoryCounts( array(), $cats );
1741 # If using cascading deletes, we can skip some explicit deletes
1742 if ( !$dbw->cascadingDeletes() ) {
1743 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
1745 # Delete outgoing links
1746 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
1747 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
1748 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
1749 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
1750 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
1751 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
1752 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
1753 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
1754 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
1757 # If using cleanup triggers, we can skip some manual deletes
1758 if ( !$dbw->cleanupTriggers() ) {
1759 # Clean up recentchanges entries...
1760 $dbw->delete( 'recentchanges',
1761 array( 'rc_type != ' . RC_LOG
,
1762 'rc_namespace' => $this->mTitle
->getNamespace(),
1763 'rc_title' => $this->mTitle
->getDBkey() ),
1765 $dbw->delete( 'recentchanges',
1766 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
1771 self
::onArticleDelete( $this->mTitle
);
1773 # Clear the cached article id so the interface doesn't act like we exist
1774 $this->mTitle
->resetArticleID( 0 );
1776 # Log the deletion, if the page was suppressed, log it at Oversight instead
1777 $logtype = $suppress ?
'suppress' : 'delete';
1779 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1780 $logEntry->setPerformer( $user );
1781 $logEntry->setTarget( $this->mTitle
);
1782 $logEntry->setComment( $reason );
1783 $logid = $logEntry->insert();
1784 $logEntry->publish( $logid );
1790 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1795 * Roll back the most recent consecutive set of edits to a page
1796 * from the same user; fails if there are no eligible edits to
1797 * roll back to, e.g. user is the sole contributor. This function
1798 * performs permissions checks on $user, then calls commitRollback()
1799 * to do the dirty work
1801 * @todo: seperate the business/permission stuff out from backend code
1803 * @param $fromP String: Name of the user whose edits to rollback.
1804 * @param $summary String: Custom summary. Set to default summary if empty.
1805 * @param $token String: Rollback token.
1806 * @param $bot Boolean: If true, mark all reverted edits as bot.
1808 * @param $resultDetails Array: contains result-specific array of additional values
1809 * 'alreadyrolled' : 'current' (rev)
1810 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1812 * @param $user User The user performing the rollback
1813 * @return array of errors, each error formatted as
1814 * array(messagekey, param1, param2, ...).
1815 * On success, the array is empty. This array can also be passed to
1816 * OutputPage::showPermissionsErrorPage().
1818 public function doRollback(
1819 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
1821 $resultDetails = null;
1824 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
1825 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
1826 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1828 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
1829 $errors[] = array( 'sessionfailure' );
1832 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
1833 $errors[] = array( 'actionthrottledtext' );
1836 # If there were errors, bail out now
1837 if ( !empty( $errors ) ) {
1841 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
1845 * Backend implementation of doRollback(), please refer there for parameter
1846 * and return value documentation
1848 * NOTE: This function does NOT check ANY permissions, it just commits the
1849 * rollback to the DB. Therefore, you should only call this function direct-
1850 * ly if you want to use custom permissions checks. If you don't, use
1851 * doRollback() instead.
1852 * @param $fromP String: Name of the user whose edits to rollback.
1853 * @param $summary String: Custom summary. Set to default summary if empty.
1854 * @param $bot Boolean: If true, mark all reverted edits as bot.
1856 * @param $resultDetails Array: contains result-specific array of additional values
1857 * @param $guser User The user performing the rollback
1859 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
1860 global $wgUseRCPatrol, $wgContLang;
1862 $dbw = wfGetDB( DB_MASTER
);
1864 if ( wfReadOnly() ) {
1865 return array( array( 'readonlytext' ) );
1868 # Get the last editor
1869 $current = Revision
::newFromTitle( $this->mTitle
);
1870 if ( is_null( $current ) ) {
1871 # Something wrong... no page?
1872 return array( array( 'notanarticle' ) );
1875 $from = str_replace( '_', ' ', $fromP );
1876 # User name given should match up with the top revision.
1877 # If the user was deleted then $from should be empty.
1878 if ( $from != $current->getUserText() ) {
1879 $resultDetails = array( 'current' => $current );
1880 return array( array( 'alreadyrolled',
1881 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
1882 htmlspecialchars( $fromP ),
1883 htmlspecialchars( $current->getUserText() )
1887 # Get the last edit not by this guy...
1888 # Note: these may not be public values
1889 $user = intval( $current->getRawUser() );
1890 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1891 $s = $dbw->selectRow( 'revision',
1892 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1893 array( 'rev_page' => $current->getPage(),
1894 "rev_user != {$user} OR rev_user_text != {$user_text}"
1896 array( 'USE INDEX' => 'page_timestamp',
1897 'ORDER BY' => 'rev_timestamp DESC' )
1899 if ( $s === false ) {
1900 # No one else ever edited this page
1901 return array( array( 'cantrollback' ) );
1902 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
1903 # Only admins can see this text
1904 return array( array( 'notvisiblerev' ) );
1908 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1909 # Mark all reverted edits as bot
1913 if ( $wgUseRCPatrol ) {
1914 # Mark all reverted edits as patrolled
1915 $set['rc_patrolled'] = 1;
1918 if ( count( $set ) ) {
1919 $dbw->update( 'recentchanges', $set,
1921 'rc_cur_id' => $current->getPage(),
1922 'rc_user_text' => $current->getUserText(),
1923 "rc_timestamp > '{$s->rev_timestamp}'",
1928 # Generate the edit summary if necessary
1929 $target = Revision
::newFromId( $s->rev_id
);
1930 if ( empty( $summary ) ) {
1931 if ( $from == '' ) { // no public user name
1932 $summary = wfMsgForContent( 'revertpage-nouser' );
1934 $summary = wfMsgForContent( 'revertpage' );
1938 # Allow the custom summary to use the same args as the default message
1940 $target->getUserText(), $from, $s->rev_id
,
1941 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
1942 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1944 $summary = wfMsgReplaceArgs( $summary, $args );
1947 $flags = EDIT_UPDATE
;
1949 if ( $guser->isAllowed( 'minoredit' ) ) {
1950 $flags |
= EDIT_MINOR
;
1953 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1954 $flags |
= EDIT_FORCE_BOT
;
1957 # Actually store the edit
1958 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1959 if ( !empty( $status->value
['revision'] ) ) {
1960 $revId = $status->value
['revision']->getId();
1965 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1967 $resultDetails = array(
1968 'summary' => $summary,
1969 'current' => $current,
1970 'target' => $target,
1978 * Do standard deferred updates after page view
1979 * @param $user User The relevant user
1981 public function doViewUpdates( User
$user ) {
1982 global $wgDisableCounters;
1983 if ( wfReadOnly() ) {
1987 # Don't update page view counters on views from bot users (bug 14044)
1988 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->getId() ) {
1989 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1990 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1993 # Update newtalk / watchlist notification status
1994 $user->clearNotification( $this->mTitle
);
1998 * Prepare text which is about to be saved.
1999 * Returns a stdclass with source, pst and output members
2001 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2002 global $wgParser, $wgContLang, $wgUser;
2003 $user = is_null( $user ) ?
$wgUser : $user;
2004 // @TODO fixme: check $user->getId() here???
2005 if ( $this->mPreparedEdit
2006 && $this->mPreparedEdit
->newText
== $text
2007 && $this->mPreparedEdit
->revid
== $revid
2010 return $this->mPreparedEdit
;
2013 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2014 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2016 $edit = (object)array();
2017 $edit->revid
= $revid;
2018 $edit->newText
= $text;
2019 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2020 $edit->popts
= $this->makeParserOptions( 'canonical' );
2021 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
2022 $edit->oldText
= $this->getRawText();
2024 $this->mPreparedEdit
= $edit;
2030 * Do standard deferred updates after page edit.
2031 * Update links tables, site stats, search index and message cache.
2032 * Purges pages that include this page if the text was changed here.
2033 * Every 100th edit, prune the recent changes table.
2036 * @param $revision Revision object
2037 * @param $user User object that did the revision
2038 * @param $options Array of options, following indexes are used:
2039 * - changed: boolean, whether the revision changed the content (default true)
2040 * - created: boolean, whether the revision created the page (default false)
2041 * - oldcountable: boolean or null (default null):
2042 * - boolean: whether the page was counted as an article before that
2043 * revision, only used in changed is true and created is false
2044 * - null: don't change the article count
2046 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2047 global $wgEnableParserCache;
2049 wfProfileIn( __METHOD__
);
2051 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2052 $text = $revision->getText();
2055 # Be careful not to double-PST: $text is usually already PST-ed once
2056 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2057 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2058 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
2060 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2061 $editInfo = $this->mPreparedEdit
;
2064 # Save it to the parser cache
2065 if ( $wgEnableParserCache ) {
2066 $parserCache = ParserCache
::singleton();
2067 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2070 # Update the links tables
2071 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2074 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2076 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2077 if ( 0 == mt_rand( 0, 99 ) ) {
2078 // Flush old entries from the `recentchanges` table; we do this on
2079 // random requests so as to avoid an increase in writes for no good reason
2082 $dbw = wfGetDB( DB_MASTER
);
2083 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2086 array( "rc_timestamp < '$cutoff'" ),
2092 $id = $this->getId();
2093 $title = $this->mTitle
->getPrefixedDBkey();
2094 $shortTitle = $this->mTitle
->getDBkey();
2097 wfProfileOut( __METHOD__
);
2101 if ( !$options['changed'] ) {
2104 } elseif ( $options['created'] ) {
2105 $good = (int)$this->isCountable( $editInfo );
2107 } elseif ( $options['oldcountable'] !== null ) {
2108 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2115 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2116 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
2118 # If this is another user's talk page, update newtalk.
2119 # Don't do this if $options['changed'] = false (null-edits) nor if
2120 # it's a minor edit and the user doesn't want notifications for those.
2121 if ( $options['changed']
2122 && $this->mTitle
->getNamespace() == NS_USER_TALK
2123 && $shortTitle != $user->getTitleKey()
2124 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2126 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2127 $other = User
::newFromName( $shortTitle, false );
2129 wfDebug( __METHOD__
. ": invalid username\n" );
2130 } elseif ( User
::isIP( $shortTitle ) ) {
2131 // An anonymous user
2132 $other->setNewtalk( true );
2133 } elseif ( $other->isLoggedIn() ) {
2134 $other->setNewtalk( true );
2136 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2141 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2142 MessageCache
::singleton()->replace( $shortTitle, $text );
2145 if( $options['created'] ) {
2146 self
::onArticleCreate( $this->mTitle
);
2148 self
::onArticleEdit( $this->mTitle
);
2151 wfProfileOut( __METHOD__
);
2155 * Perform article updates on a special page creation.
2157 * @param $rev Revision object
2159 * @todo This is a shitty interface function. Kill it and replace the
2160 * other shitty functions like doEditUpdates and such so it's not needed
2162 * @deprecated since 1.18, use doEditUpdates()
2164 public function createUpdates( $rev ) {
2166 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2170 * This function is called right before saving the wikitext,
2171 * so we can do things like signatures and links-in-context.
2173 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2174 * @param $text String article contents
2175 * @param $user User object: user doing the edit
2176 * @param $popts ParserOptions object: parser options, default options for
2177 * the user loaded if null given
2178 * @return string article contents with altered wikitext markup (signatures
2179 * converted, {{subst:}}, templates, etc.)
2181 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2182 global $wgParser, $wgUser;
2184 wfDeprecated( __METHOD__
);
2186 $user = is_null( $user ) ?
$wgUser : $user;
2188 if ( $popts === null ) {
2189 $popts = ParserOptions
::newFromUser( $user );
2192 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2196 * Loads page_touched and returns a value indicating if it should be used
2197 * @return boolean true if not a redirect
2199 public function checkTouched() {
2200 if ( !$this->mDataLoaded
) {
2201 $this->loadPageData();
2203 return !$this->mIsRedirect
;
2207 * Get the page_touched field
2208 * @return string containing GMT timestamp
2210 public function getTouched() {
2211 if ( !$this->mDataLoaded
) {
2212 $this->loadPageData();
2214 return $this->mTouched
;
2218 * Get the page_latest field
2219 * @return integer rev_id of current revision
2221 public function getLatest() {
2222 if ( !$this->mDataLoaded
) {
2223 $this->loadPageData();
2225 return (int)$this->mLatest
;
2229 * Edit an article without doing all that other stuff
2230 * The article must already exist; link tables etc
2231 * are not updated, caches are not flushed.
2233 * @param $text String: text submitted
2234 * @param $user User The relevant user
2235 * @param $comment String: comment submitted
2236 * @param $minor Boolean: whereas it's a minor modification
2238 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2239 wfProfileIn( __METHOD__
);
2241 $dbw = wfGetDB( DB_MASTER
);
2242 $revision = new Revision( array(
2243 'page' => $this->getId(),
2245 'comment' => $comment,
2246 'minor_edit' => $minor ?
1 : 0,
2248 $revision->insertOn( $dbw );
2249 $this->updateRevisionOn( $dbw, $revision );
2251 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2253 wfProfileOut( __METHOD__
);
2257 * The onArticle*() functions are supposed to be a kind of hooks
2258 * which should be called whenever any of the specified actions
2261 * This is a good place to put code to clear caches, for instance.
2263 * This is called on page move and undelete, as well as edit
2265 * @param $title Title object
2267 public static function onArticleCreate( $title ) {
2268 # Update existence markers on article/talk tabs...
2269 if ( $title->isTalkPage() ) {
2270 $other = $title->getSubjectPage();
2272 $other = $title->getTalkPage();
2275 $other->invalidateCache();
2276 $other->purgeSquid();
2278 $title->touchLinks();
2279 $title->purgeSquid();
2280 $title->deleteTitleProtection();
2284 * Clears caches when article is deleted
2286 * @param $title Title
2288 public static function onArticleDelete( $title ) {
2289 # Update existence markers on article/talk tabs...
2290 if ( $title->isTalkPage() ) {
2291 $other = $title->getSubjectPage();
2293 $other = $title->getTalkPage();
2296 $other->invalidateCache();
2297 $other->purgeSquid();
2299 $title->touchLinks();
2300 $title->purgeSquid();
2303 HTMLFileCache
::clearFileCache( $title );
2306 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2307 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2311 if ( $title->getNamespace() == NS_FILE
) {
2312 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2313 $update->doUpdate();
2317 if ( $title->getNamespace() == NS_USER_TALK
) {
2318 $user = User
::newFromName( $title->getText(), false );
2320 $user->setNewtalk( false );
2325 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2329 * Purge caches on page update etc
2331 * @param $title Title object
2332 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2334 public static function onArticleEdit( $title ) {
2335 // Invalidate caches of articles which include this page
2336 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2339 // Invalidate the caches of all pages which redirect here
2340 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2342 # Purge squid for this page only
2343 $title->purgeSquid();
2345 # Clear file cache for this page only
2346 HTMLFileCache
::clearFileCache( $title );
2352 * Return a list of templates used by this article.
2353 * Uses the templatelinks table
2355 * @return Array of Title objects
2357 public function getUsedTemplates() {
2359 $id = $this->mTitle
->getArticleID();
2365 $dbr = wfGetDB( DB_SLAVE
);
2366 $res = $dbr->select( array( 'templatelinks' ),
2367 array( 'tl_namespace', 'tl_title' ),
2368 array( 'tl_from' => $id ),
2371 if ( $res !== false ) {
2372 foreach ( $res as $row ) {
2373 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2381 * Returns a list of hidden categories this page is a member of.
2382 * Uses the page_props and categorylinks tables.
2384 * @return Array of Title objects
2386 public function getHiddenCategories() {
2388 $id = $this->mTitle
->getArticleID();
2394 $dbr = wfGetDB( DB_SLAVE
);
2395 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2397 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2398 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2401 if ( $res !== false ) {
2402 foreach ( $res as $row ) {
2403 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2411 * Return an applicable autosummary if one exists for the given edit.
2412 * @param $oldtext String: the previous text of the page.
2413 * @param $newtext String: The submitted text of the page.
2414 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2415 * @return string An appropriate autosummary, or an empty string.
2417 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2420 # Decide what kind of autosummary is needed.
2422 # Redirect autosummaries
2423 $ot = Title
::newFromRedirect( $oldtext );
2424 $rt = Title
::newFromRedirect( $newtext );
2426 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2427 $truncatedtext = $wgContLang->truncate(
2428 str_replace( "\n", ' ', $newtext ),
2430 - strlen( wfMsgForContent( 'autoredircomment' ) )
2431 - strlen( $rt->getFullText() )
2433 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2436 # New page autosummaries
2437 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2438 # If they're making a new article, give its text, truncated, in the summary.
2440 $truncatedtext = $wgContLang->truncate(
2441 str_replace( "\n", ' ', $newtext ),
2442 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2444 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2447 # Blanking autosummaries
2448 if ( $oldtext != '' && $newtext == '' ) {
2449 return wfMsgForContent( 'autosumm-blank' );
2450 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2451 # Removing more than 90% of the article
2453 $truncatedtext = $wgContLang->truncate(
2455 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2457 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2460 # If we reach this point, there's no applicable autosummary for our case, so our
2461 # autosummary is empty.
2466 * Auto-generates a deletion reason
2468 * @param &$hasHistory Boolean: whether the page has a history
2469 * @return mixed String containing deletion reason or empty string, or boolean false
2470 * if no revision occurred
2472 public function getAutoDeleteReason( &$hasHistory ) {
2475 $dbw = wfGetDB( DB_MASTER
);
2476 // Get the last revision
2477 $rev = Revision
::newFromTitle( $this->getTitle() );
2479 if ( is_null( $rev ) ) {
2483 // Get the article's contents
2484 $contents = $rev->getText();
2487 // If the page is blank, use the text from the previous revision,
2488 // which can only be blank if there's a move/import/protect dummy revision involved
2489 if ( $contents == '' ) {
2490 $prev = $rev->getPrevious();
2493 $contents = $prev->getText();
2498 // Find out if there was only one contributor
2499 // Only scan the last 20 revisions
2500 $res = $dbw->select( 'revision', 'rev_user_text',
2501 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2503 array( 'LIMIT' => 20 )
2506 if ( $res === false ) {
2507 // This page has no revisions, which is very weird
2511 $hasHistory = ( $res->numRows() > 1 );
2512 $row = $dbw->fetchObject( $res );
2514 if ( $row ) { // $row is false if the only contributor is hidden
2515 $onlyAuthor = $row->rev_user_text
;
2516 // Try to find a second contributor
2517 foreach ( $res as $row ) {
2518 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2519 $onlyAuthor = false;
2524 $onlyAuthor = false;
2527 // Generate the summary with a '$1' placeholder
2529 // The current revision is blank and the one before is also
2530 // blank. It's just not our lucky day
2531 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2533 if ( $onlyAuthor ) {
2534 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2536 $reason = wfMsgForContent( 'excontent', '$1' );
2540 if ( $reason == '-' ) {
2541 // Allow these UI messages to be blanked out cleanly
2545 // Replace newlines with spaces to prevent uglyness
2546 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2547 // Calculate the maximum amount of chars to get
2548 // Max content length = max comment length - length of the comment (excl. $1)
2549 $maxLength = 255 - ( strlen( $reason ) - 2 );
2550 $contents = $wgContLang->truncate( $contents, $maxLength );
2551 // Remove possible unfinished links
2552 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2553 // Now replace the '$1' placeholder
2554 $reason = str_replace( '$1', $contents, $reason );
2560 * Get parser options suitable for rendering the primary article wikitext
2561 * @param User|string $user User object or 'canonical'
2562 * @return ParserOptions
2564 public function makeParserOptions( $user ) {
2566 if ( $user instanceof User
) { // settings per user (even anons)
2567 $options = ParserOptions
::newFromUser( $user );
2568 } else { // canonical settings
2569 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
2571 $options->enableLimitReport(); // show inclusion/loop reports
2572 $options->setTidy( true ); // fix bad HTML
2577 * Update all the appropriate counts in the category table, given that
2578 * we've added the categories $added and deleted the categories $deleted.
2580 * @param $added array The names of categories that were added
2581 * @param $deleted array The names of categories that were deleted
2583 public function updateCategoryCounts( $added, $deleted ) {
2584 $ns = $this->mTitle
->getNamespace();
2585 $dbw = wfGetDB( DB_MASTER
);
2587 # First make sure the rows exist. If one of the "deleted" ones didn't
2588 # exist, we might legitimately not create it, but it's simpler to just
2589 # create it and then give it a negative value, since the value is bogus
2592 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2593 $insertCats = array_merge( $added, $deleted );
2594 if ( !$insertCats ) {
2595 # Okay, nothing to do
2599 $insertRows = array();
2601 foreach ( $insertCats as $cat ) {
2602 $insertRows[] = array(
2603 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2607 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2609 $addFields = array( 'cat_pages = cat_pages + 1' );
2610 $removeFields = array( 'cat_pages = cat_pages - 1' );
2612 if ( $ns == NS_CATEGORY
) {
2613 $addFields[] = 'cat_subcats = cat_subcats + 1';
2614 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2615 } elseif ( $ns == NS_FILE
) {
2616 $addFields[] = 'cat_files = cat_files + 1';
2617 $removeFields[] = 'cat_files = cat_files - 1';
2624 array( 'cat_title' => $added ),
2633 array( 'cat_title' => $deleted ),
2640 * Updates cascading protections
2642 * @param $parserOutput ParserOutput object for the current version
2644 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2645 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2649 // templatelinks table may have become out of sync,
2650 // especially if using variable-based transclusions.
2651 // For paranoia, check if things have changed and if
2652 // so apply updates to the database. This will ensure
2653 // that cascaded protections apply as soon as the changes
2656 # Get templates from templatelinks
2657 $id = $this->mTitle
->getArticleID();
2659 $tlTemplates = array();
2661 $dbr = wfGetDB( DB_SLAVE
);
2662 $res = $dbr->select( array( 'templatelinks' ),
2663 array( 'tl_namespace', 'tl_title' ),
2664 array( 'tl_from' => $id ),
2668 foreach ( $res as $row ) {
2669 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2672 # Get templates from parser output.
2673 $poTemplates = array();
2674 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2675 foreach ( $templates as $dbk => $id ) {
2676 $poTemplates["$ns:$dbk"] = true;
2681 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2683 if ( count( $templates_diff ) > 0 ) {
2684 # Whee, link updates time.
2685 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2691 * @deprecated since 1.18
2693 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2695 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2699 * @deprecated since 1.18
2701 public function viewUpdates() {
2703 return $this->doViewUpdates( $wgUser );
2707 * @deprecated since 1.18
2709 public function useParserCache( $oldid ) {
2711 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2715 class PoolWorkArticleView
extends PoolCounterWork
{
2733 * @var ParserOptions
2735 private $parserOptions;
2743 * @var ParserOutput|false
2745 private $parserOutput = false;
2750 private $isDirty = false;
2755 private $error = false;
2761 * @param $revid Integer: ID of the revision being parsed
2762 * @param $useParserCache Boolean: whether to use the parser cache
2763 * @param $parserOptions parserOptions to use for the parse operation
2764 * @param $text String: text to parse or null to load it
2766 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2767 $this->page
= $page;
2768 $this->revid
= $revid;
2769 $this->cacheable
= $useParserCache;
2770 $this->parserOptions
= $parserOptions;
2771 $this->text
= $text;
2772 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2773 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2777 * Get the ParserOutput from this object, or false in case of failure
2779 * @return ParserOutput
2781 public function getParserOutput() {
2782 return $this->parserOutput
;
2786 * Get whether the ParserOutput is a dirty one (i.e. expired)
2790 public function getIsDirty() {
2791 return $this->isDirty
;
2795 * Get a Status object in case of error or false otherwise
2797 * @return Status|false
2799 public function getError() {
2800 return $this->error
;
2807 global $wgParser, $wgUseFileCache;
2809 $isCurrent = $this->revid
=== $this->page
->getLatest();
2811 if ( $this->text
!== null ) {
2812 $text = $this->text
;
2813 } elseif ( $isCurrent ) {
2814 $text = $this->page
->getRawText();
2816 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2817 if ( $rev === null ) {
2820 $text = $rev->getText();
2824 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2825 $this->parserOptions
, true, true, $this->revid
);
2830 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2831 $this->page
->getTitle()->getPrefixedDBkey() ) );
2834 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2835 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2838 // Make sure file cache is not used on uncacheable content.
2839 // Output that has magic words in it can still use the parser cache
2840 // (if enabled), though it will generally expire sooner.
2841 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2842 $wgUseFileCache = false;
2846 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2855 function getCachedWork() {
2856 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2858 if ( $this->parserOutput
=== false ) {
2859 wfDebug( __METHOD__
. ": parser cache miss\n" );
2862 wfDebug( __METHOD__
. ": parser cache hit\n" );
2870 function fallback() {
2871 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2873 if ( $this->parserOutput
=== false ) {
2874 wfDebugLog( 'dirty', "dirty missing\n" );
2875 wfDebug( __METHOD__
. ": no dirty cache\n" );
2878 wfDebug( __METHOD__
. ": sending dirty output\n" );
2879 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2880 $this->isDirty
= true;
2886 * @param $status Status
2888 function error( $status ) {
2889 $this->error
= $status;