3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
8 * Class representing a MediaWiki article and history.
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
13 * @internal documentation reviewed 15 Mar 2010
15 class WikiPage
extends Page
{
19 public $mTitle = null;
24 public $mDataLoaded = false; // !< Boolean
25 public $mIsRedirect = false; // !< Boolean
26 public $mLatest = false; // !< Integer (false means "not loaded")
27 public $mPreparedEdit = false; // !< Array
32 protected $mRedirectTarget = null;
37 protected $mLastRevision = null;
39 protected $mTimestamp = ''; // !< String
40 protected $mTouched = '19700101000000'; // !< String
44 * Constructor and clear the article
45 * @param $title Title Reference to a Title object.
47 public function __construct( Title
$title ) {
48 $this->mTitle
= $title;
52 * Create a WikiPage object of the appropriate class for the given title.
55 * @return WikiPage object of the appropriate type
57 public static function factory( Title
$title ) {
58 $ns = $title->getNamespace();
60 if ( $ns == NS_MEDIA
) {
61 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
62 } elseif ( $ns < 0 ) {
63 throw new MWException( "Invalid or virtual namespace $ns given." );
68 $page = new WikiFilePage( $title );
71 $page = new WikiCategoryPage( $title );
74 $page = new WikiPage( $title );
81 * Constructor from a page id
83 * @param $id Int article ID to load
87 public static function newFromID( $id ) {
88 $t = Title
::newFromID( $id );
90 return self
::factory( $t );
96 * Returns overrides for action handlers.
97 * Classes listed here will be used instead of the default one when
98 * (and only when) $wgActions[$action] === true. This allows subclasses
99 * to override the default behavior.
101 * @todo: move this UI stuff somewhere else
105 public function getActionOverrides() {
110 * If this page is a redirect, get its target
112 * The target will be fetched from the redirect table if possible.
113 * If this page doesn't have an entry there, call insertRedirect()
114 * @return Title|mixed object, or null if this page is not a redirect
116 public function getRedirectTarget() {
117 if ( !$this->mTitle
->isRedirect() ) {
121 if ( $this->mRedirectTarget
!== null ) {
122 return $this->mRedirectTarget
;
125 # Query the redirect table
126 $dbr = wfGetDB( DB_SLAVE
);
127 $row = $dbr->selectRow( 'redirect',
128 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
129 array( 'rd_from' => $this->getId() ),
133 // rd_fragment and rd_interwiki were added later, populate them if empty
134 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
135 return $this->mRedirectTarget
= Title
::makeTitle(
136 $row->rd_namespace
, $row->rd_title
,
137 $row->rd_fragment
, $row->rd_interwiki
);
140 # This page doesn't have an entry in the redirect table
141 return $this->mRedirectTarget
= $this->insertRedirect();
145 * Insert an entry for this page into the redirect table.
147 * Don't call this function directly unless you know what you're doing.
148 * @return Title object or null if not a redirect
150 public function insertRedirect() {
151 // recurse through to only get the final target
152 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
156 $this->insertRedirectEntry( $retval );
161 * Insert or update the redirect table entry for this page to indicate
162 * it redirects to $rt .
163 * @param $rt Title redirect target
165 public function insertRedirectEntry( $rt ) {
166 $dbw = wfGetDB( DB_MASTER
);
167 $dbw->replace( 'redirect', array( 'rd_from' ),
169 'rd_from' => $this->getId(),
170 'rd_namespace' => $rt->getNamespace(),
171 'rd_title' => $rt->getDBkey(),
172 'rd_fragment' => $rt->getFragment(),
173 'rd_interwiki' => $rt->getInterwiki(),
180 * Get the Title object or URL this page redirects to
182 * @return mixed false, Title of in-wiki target, or string with URL
184 public function followRedirect() {
185 return $this->getRedirectURL( $this->getRedirectTarget() );
189 * Get the Title object or URL to use for a redirect. We use Title
190 * objects for same-wiki, non-special redirects and URLs for everything
192 * @param $rt Title Redirect target
193 * @return mixed false, Title object of local target, or string with URL
195 public function getRedirectURL( $rt ) {
197 if ( $rt->getInterwiki() != '' ) {
198 if ( $rt->isLocal() ) {
199 // Offsite wikis need an HTTP redirect.
201 // This can be hard to reverse and may produce loops,
202 // so they may be disabled in the site configuration.
203 $source = $this->mTitle
->getFullURL( 'redirect=no' );
204 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
207 if ( $rt->isSpecialPage() ) {
208 // Gotta handle redirects to special pages differently:
209 // Fill the HTTP response "Location" header and ignore
210 // the rest of the page we're on.
212 // This can be hard to reverse, so they may be disabled.
213 if ( $rt->isSpecial( 'Userlogout' ) ) {
216 return $rt->getFullURL();
224 // No or invalid redirect
229 * Get the title object of the article
230 * @return Title object of this page
232 public function getTitle() {
233 return $this->mTitle
;
239 public function clear() {
240 $this->mDataLoaded
= false;
242 $this->mRedirectTarget
= null; # Title object if set
243 $this->mLastRevision
= null; # Latest revision
244 $this->mTimestamp
= '';
245 $this->mTouched
= '19700101000000';
246 $this->mIsRedirect
= false;
247 $this->mLatest
= false;
248 $this->mPreparedEdit
= false;
252 * Get the text that needs to be saved in order to undo all revisions
253 * between $undo and $undoafter. Revisions must belong to the same page,
254 * must exist and must not be deleted
255 * @param $undo Revision
256 * @param $undoafter Revision Must be an earlier revision than $undo
257 * @return mixed string on success, false on failure
259 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
260 $cur_text = $this->getRawText();
261 if ( $cur_text === false ) {
262 return false; // no page
264 $undo_text = $undo->getText();
265 $undoafter_text = $undoafter->getText();
267 if ( $cur_text == $undo_text ) {
268 # No use doing a merge if it's just a straight revert.
269 return $undoafter_text;
274 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
282 * Return the list of revision fields that should be selected to create
287 public static function selectFields() {
304 * Fetch a page record with the given conditions
305 * @param $dbr DatabaseBase object
306 * @param $conditions Array
307 * @return mixed Database result resource, or false on failure
309 protected function pageData( $dbr, $conditions ) {
310 $fields = self
::selectFields();
312 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
314 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
316 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
322 * Fetch a page record matching the Title object's namespace and title
323 * using a sanitized title string
325 * @param $dbr DatabaseBase object
326 * @param $title Title object
327 * @return mixed Database result resource, or false on failure
329 public function pageDataFromTitle( $dbr, $title ) {
330 return $this->pageData( $dbr, array(
331 'page_namespace' => $title->getNamespace(),
332 'page_title' => $title->getDBkey() ) );
336 * Fetch a page record matching the requested ID
338 * @param $dbr DatabaseBase
340 * @return mixed Database result resource, or false on failure
342 public function pageDataFromId( $dbr, $id ) {
343 return $this->pageData( $dbr, array( 'page_id' => $id ) );
347 * Set the general counter, title etc data loaded from
350 * @param $data Object|String One of the following:
351 * A DB query result object or...
352 * "fromdb" to get from a slave DB or...
353 * "fromdbmaster" to get from the master DB
356 public function loadPageData( $data = 'fromdb' ) {
357 if ( $data === 'fromdbmaster' ) {
358 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
359 } elseif ( $data === 'fromdb' ) { // slave
360 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
361 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
362 # Note that DB also stores the master position in the session and checks it.
363 $touched = $this->getCachedLastEditTime();
364 if ( $touched ) { // key set
365 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
366 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
371 $lc = LinkCache
::singleton();
374 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
376 $this->mTitle
->loadFromRow( $data );
378 # Old-fashioned restrictions
379 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
381 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
382 $this->mIsRedirect
= intval( $data->page_is_redirect
);
383 $this->mLatest
= intval( $data->page_latest
);
385 $lc->addBadLinkObj( $this->mTitle
);
387 $this->mTitle
->loadFromRow( false );
390 $this->mDataLoaded
= true;
394 * @return int Page ID
396 public function getId() {
397 return $this->mTitle
->getArticleID();
401 * @return bool Whether or not the page exists in the database
403 public function exists() {
404 return $this->mTitle
->exists();
408 * Check if this page is something we're going to be showing
409 * some sort of sensible content for. If we return false, page
410 * views (plain action=view) will return an HTTP 404 response,
411 * so spiders and robots can know they're following a bad link.
415 public function hasViewableContent() {
416 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
420 * Get the number of views of this page
422 * @return int The view count for the page
424 public function getCount() {
425 return $this->mTitle
->getCount();
429 * Determine whether a page would be suitable for being counted as an
430 * article in the site_stats table based on the title & its content
432 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
433 * if false, the current database state will be used
436 public function isCountable( $editInfo = false ) {
437 global $wgArticleCountMethod;
439 if ( !$this->mTitle
->isContentPage() ) {
443 $text = $editInfo ?
$editInfo->pst
: false;
445 if ( $this->isRedirect( $text ) ) {
449 switch ( $wgArticleCountMethod ) {
453 if ( $text === false ) {
454 $text = $this->getRawText();
456 return strpos( $text, ',' ) !== false;
459 // ParserOutput::getLinks() is a 2D array of page links, so
460 // to be really correct we would need to recurse in the array
461 // but the main array should only have items in it if there are
463 return (bool)count( $editInfo->output
->getLinks() );
465 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
466 array( 'pl_from' => $this->getId() ), __METHOD__
);
472 * Tests if the article text represents a redirect
474 * @param $text mixed string containing article contents, or boolean
477 public function isRedirect( $text = false ) {
478 if ( $text === false ) {
479 if ( !$this->mDataLoaded
) {
480 $this->loadPageData();
483 return (bool)$this->mIsRedirect
;
485 return Title
::newFromRedirect( $text ) !== null;
490 * Loads everything except the text
491 * This isn't necessary for all uses, so it's only done if needed.
493 protected function loadLastEdit() {
494 if ( $this->mLastRevision
!== null ) {
495 return; // already loaded
498 $latest = $this->getLatest();
500 return; // page doesn't exist or is missing page_latest info
503 $revision = Revision
::newFromPageId( $this->getId(), $latest );
504 if ( $revision ) { // sanity
505 $this->setLastEdit( $revision );
510 * Set the latest revision
512 protected function setLastEdit( Revision
$revision ) {
513 $this->mLastRevision
= $revision;
514 $this->mTimestamp
= $revision->getTimestamp();
518 * Get the latest revision
519 * @return Revision|null
521 public function getRevision() {
522 $this->loadLastEdit();
523 if ( $this->mLastRevision
) {
524 return $this->mLastRevision
;
530 * Get the text of the current revision. No side-effects...
532 * @param $audience Integer: one of:
533 * Revision::FOR_PUBLIC to be displayed to all users
534 * Revision::FOR_THIS_USER to be displayed to $wgUser
535 * Revision::RAW get the text regardless of permissions
536 * @return String|false The text of the current revision
538 public function getText( $audience = Revision
::FOR_PUBLIC
) {
539 $this->loadLastEdit();
540 if ( $this->mLastRevision
) {
541 return $this->mLastRevision
->getText( $audience );
547 * Get the text of the current revision. No side-effects...
549 * @return String|false The text of the current revision
551 public function getRawText() {
552 $this->loadLastEdit();
553 if ( $this->mLastRevision
) {
554 return $this->mLastRevision
->getRawText();
560 * @return string MW timestamp of last article revision
562 public function getTimestamp() {
563 // Check if the field has been filled by WikiPage::setTimestamp()
564 if ( !$this->mTimestamp
) {
565 $this->loadLastEdit();
567 return wfTimestamp( TS_MW
, $this->mTimestamp
);
571 * Set the page timestamp (use only to avoid DB queries)
572 * @param $ts string MW timestamp of last article revision
575 public function setTimestamp( $ts ) {
576 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
580 * @param $audience Integer: one of:
581 * Revision::FOR_PUBLIC to be displayed to all users
582 * Revision::FOR_THIS_USER to be displayed to $wgUser
583 * Revision::RAW get the text regardless of permissions
584 * @return int user ID for the user that made the last article revision
586 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
587 $this->loadLastEdit();
588 if ( $this->mLastRevision
) {
589 return $this->mLastRevision
->getUser( $audience );
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 string username of the user that made the last article revision
602 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
603 $this->loadLastEdit();
604 if ( $this->mLastRevision
) {
605 return $this->mLastRevision
->getUserText( $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 Comment stored for the last article revision
618 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
619 $this->loadLastEdit();
620 if ( $this->mLastRevision
) {
621 return $this->mLastRevision
->getComment( $audience );
628 * Returns true if last revision was marked as "minor edit"
630 * @return boolean Minor edit indicator for the last article revision.
632 public function getMinorEdit() {
633 $this->loadLastEdit();
634 if ( $this->mLastRevision
) {
635 return $this->mLastRevision
->isMinor();
642 * Get a list of users who have edited this article, not including the user who made
643 * the most recent revision, which you can get from $article->getUser() if you want it
644 * @return UserArrayFromResult
646 public function getContributors() {
647 # @todo FIXME: This is expensive; cache this info somewhere.
649 $dbr = wfGetDB( DB_SLAVE
);
651 if ( $dbr->implicitGroupby() ) {
652 $realNameField = 'user_real_name';
654 $realNameField = 'MIN(user_real_name) AS user_real_name';
657 $tables = array( 'revision', 'user' );
660 'rev_user as user_id',
661 'rev_user_text AS user_name',
663 'MAX(rev_timestamp) AS timestamp',
666 $conds = array( 'rev_page' => $this->getId() );
668 // The user who made the top revision gets credited as "this page was last edited by
669 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
670 $user = $this->getUser();
672 $conds[] = "rev_user != $user";
674 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
677 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
680 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
684 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
685 'ORDER BY' => 'timestamp DESC',
688 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
689 return new UserArrayFromResult( $res );
693 * Should the parser cache be used?
695 * @param $parserOptions ParserOptions to check
699 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
700 global $wgEnableParserCache;
702 return $wgEnableParserCache
703 && $parserOptions->getStubThreshold() == 0
704 && $this->mTitle
->exists()
705 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
706 && $this->mTitle
->isWikitextPage();
710 * Get a ParserOutput for the given ParserOptions and revision ID.
711 * The parser cache will be used if possible.
714 * @param $parserOptions ParserOptions to use for the parse operation
715 * @param $oldid Revision ID to get the text from, passing null or 0 will
716 * get the current revision (default value)
717 * @return ParserOutput or false if the revision was not found
719 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
720 wfProfileIn( __METHOD__
);
722 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
723 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
724 if ( $parserOptions->getStubThreshold() ) {
725 wfIncrStats( 'pcache_miss_stub' );
728 if ( $useParserCache ) {
729 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
730 if ( $parserOutput !== false ) {
731 wfProfileOut( __METHOD__
);
732 return $parserOutput;
736 if ( $oldid === null ||
$oldid === 0 ) {
737 $oldid = $this->getLatest();
740 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
743 wfProfileOut( __METHOD__
);
745 return $pool->getParserOutput();
749 * Perform the actions of a page purging
751 public function doPurge() {
754 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
758 // Invalidate the cache
759 $this->mTitle
->invalidateCache();
763 // Commit the transaction before the purge is sent
764 $dbw = wfGetDB( DB_MASTER
);
768 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
772 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
773 if ( $this->mTitle
->exists() ) {
774 $text = $this->getRawText();
779 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
785 * Insert a new empty page record for this article.
786 * This *must* be followed up by creating a revision
787 * and running $this->updateRevisionOn( ... );
788 * or else the record will be left in a funky state.
789 * Best if all done inside a transaction.
791 * @param $dbw DatabaseBase
792 * @return int The newly created page_id key, or false if the title already existed
794 public function insertOn( $dbw ) {
795 wfProfileIn( __METHOD__
);
797 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
798 $dbw->insert( 'page', array(
799 'page_id' => $page_id,
800 'page_namespace' => $this->mTitle
->getNamespace(),
801 'page_title' => $this->mTitle
->getDBkey(),
803 'page_restrictions' => '',
804 'page_is_redirect' => 0, # Will set this shortly...
806 'page_random' => wfRandom(),
807 'page_touched' => $dbw->timestamp(),
808 'page_latest' => 0, # Fill this in shortly...
809 'page_len' => 0, # Fill this in shortly...
810 ), __METHOD__
, 'IGNORE' );
812 $affected = $dbw->affectedRows();
815 $newid = $dbw->insertId();
816 $this->mTitle
->resetArticleID( $newid );
818 wfProfileOut( __METHOD__
);
820 return $affected ?
$newid : false;
824 * Update the page record to point to a newly saved revision.
826 * @param $dbw DatabaseBase: object
827 * @param $revision Revision: For ID number, and text used to set
828 * length and redirect status fields
829 * @param $lastRevision Integer: if given, will not overwrite the page field
830 * when different from the currently set value.
831 * Giving 0 indicates the new page flag should be set
833 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
834 * removing rows in redirect table.
835 * @return bool true on success, false on failure
838 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
839 wfProfileIn( __METHOD__
);
841 $text = $revision->getText();
842 $len = strlen( $text );
843 $rt = Title
::newFromRedirectRecurse( $text );
845 $conditions = array( 'page_id' => $this->getId() );
847 if ( !is_null( $lastRevision ) ) {
848 # An extra check against threads stepping on each other
849 $conditions['page_latest'] = $lastRevision;
852 $now = wfTimestampNow();
853 $dbw->update( 'page',
855 'page_latest' => $revision->getId(),
856 'page_touched' => $dbw->timestamp( $now ),
857 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
858 'page_is_redirect' => $rt !== null ?
1 : 0,
864 $result = $dbw->affectedRows() != 0;
866 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
867 $this->setLastEdit( $revision );
868 $this->setCachedLastEditTime( $now );
869 $this->mLatest
= $revision->getId();
870 $this->mIsRedirect
= (bool)$rt;
871 # Update the LinkCache.
872 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
875 wfProfileOut( __METHOD__
);
880 * Get the cached timestamp for the last time the page changed.
881 * This is only used to help handle slave lag by comparing to page_touched.
882 * @return string MW timestamp
884 protected function getCachedLastEditTime() {
886 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
887 return $wgMemc->get( $key );
891 * Set the cached timestamp for the last time the page changed.
892 * This is only used to help handle slave lag by comparing to page_touched.
893 * @param $timestamp string
896 public function setCachedLastEditTime( $timestamp ) {
898 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
899 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
903 * Add row to the redirect table if this is a redirect, remove otherwise.
905 * @param $dbw DatabaseBase
906 * @param $redirectTitle Title object pointing to the redirect target,
907 * or NULL if this is not a redirect
908 * @param $lastRevIsRedirect If given, will optimize adding and
909 * removing rows in redirect table.
910 * @return bool true on success, false on failure
913 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
914 // Always update redirects (target link might have changed)
915 // Update/Insert if we don't know if the last revision was a redirect or not
916 // Delete if changing from redirect to non-redirect
917 $isRedirect = !is_null( $redirectTitle );
919 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
923 wfProfileIn( __METHOD__
);
925 $this->insertRedirectEntry( $redirectTitle );
927 // This is not a redirect, remove row from redirect table
928 $where = array( 'rd_from' => $this->getId() );
929 $dbw->delete( 'redirect', $where, __METHOD__
);
932 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
933 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
935 wfProfileOut( __METHOD__
);
937 return ( $dbw->affectedRows() != 0 );
941 * If the given revision is newer than the currently set page_latest,
942 * update the page record. Otherwise, do nothing.
944 * @param $dbw Database object
945 * @param $revision Revision object
948 public function updateIfNewerOn( $dbw, $revision ) {
949 wfProfileIn( __METHOD__
);
951 $row = $dbw->selectRow(
952 array( 'revision', 'page' ),
953 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
955 'page_id' => $this->getId(),
956 'page_latest=rev_id' ),
960 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
961 wfProfileOut( __METHOD__
);
964 $prev = $row->rev_id
;
965 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
967 # No or missing previous revision; mark the page as new
969 $lastRevIsRedirect = null;
972 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
974 wfProfileOut( __METHOD__
);
979 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
980 * @param $text String: new text of the section
981 * @param $summary String: new section's subject, only if $section is 'new'
982 * @param $edittime String: revision timestamp or null to use the current revision
983 * @return string Complete article text, or null if error
985 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
986 wfProfileIn( __METHOD__
);
988 if ( strval( $section ) == '' ) {
989 // Whole-page edit; let the whole text through
991 if ( is_null( $edittime ) ) {
992 $rev = Revision
::newFromTitle( $this->mTitle
);
994 $dbw = wfGetDB( DB_MASTER
);
995 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
999 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1000 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1001 wfProfileOut( __METHOD__
);
1005 $oldtext = $rev->getText();
1007 if ( $section == 'new' ) {
1008 # Inserting a new section
1009 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1010 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1011 $text = strlen( trim( $oldtext ) ) > 0
1012 ?
"{$oldtext}\n\n{$subject}{$text}"
1013 : "{$subject}{$text}";
1016 # Replacing an existing section; roll out the big guns
1019 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1023 wfProfileOut( __METHOD__
);
1028 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1030 * @return Int updated $flags
1032 function checkFlags( $flags ) {
1033 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1034 if ( $this->mTitle
->getArticleID() ) {
1035 $flags |
= EDIT_UPDATE
;
1045 * Change an existing article or create a new article. Updates RC and all necessary caches,
1046 * optionally via the deferred update array.
1048 * @param $text String: new text
1049 * @param $summary String: edit summary
1050 * @param $flags Integer bitfield:
1052 * Article is known or assumed to be non-existent, create a new one
1054 * Article is known or assumed to be pre-existing, update it
1056 * Mark this edit minor, if the user is allowed to do so
1058 * Do not log the change in recentchanges
1060 * Mark the edit a "bot" edit regardless of user rights
1061 * EDIT_DEFER_UPDATES
1062 * Defer some of the updates until the end of index.php
1064 * Fill in blank summaries with generated text where possible
1066 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1067 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1068 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1069 * edit-already-exists error will be returned. These two conditions are also possible with
1070 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1072 * @param $baseRevId the revision ID this edit was based off, if any
1073 * @param $user User the user doing the edit
1075 * @return Status object. Possible errors:
1076 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1077 * edit-gone-missing: In update mode, but the article didn't exist
1078 * edit-conflict: In update mode, the article changed unexpectedly
1079 * edit-no-change: Warning that the text was the same as before
1080 * edit-already-exists: In creation mode, but the article already exists
1082 * Extensions may define additional errors.
1084 * $return->value will contain an associative array with members as follows:
1085 * new: Boolean indicating if the function attempted to create a new article
1086 * revision: The revision object for the inserted revision, or null
1088 * Compatibility note: this function previously returned a boolean value indicating success/failure
1090 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1091 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1093 # Low-level sanity check
1094 if ( $this->mTitle
->getText() === '' ) {
1095 throw new MWException( 'Something is trying to edit an article with an empty title' );
1098 wfProfileIn( __METHOD__
);
1100 $user = is_null( $user ) ?
$wgUser : $user;
1101 $status = Status
::newGood( array() );
1103 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1104 $this->loadPageData( 'fromdbmaster' );
1106 $flags = $this->checkFlags( $flags );
1108 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1109 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1111 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1113 if ( $status->isOK() ) {
1114 $status->fatal( 'edit-hook-aborted' );
1117 wfProfileOut( __METHOD__
);
1121 # Silently ignore EDIT_MINOR if not allowed
1122 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1123 $bot = $flags & EDIT_FORCE_BOT
;
1125 $oldtext = $this->getRawText(); // current revision
1126 $oldsize = strlen( $oldtext );
1127 $oldid = $this->getLatest();
1128 $oldIsRedirect = $this->isRedirect();
1129 $oldcountable = $this->isCountable();
1131 # Provide autosummaries if one is not provided and autosummaries are enabled.
1132 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1133 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1136 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1137 $text = $editInfo->pst
;
1138 $newsize = strlen( $text );
1140 $dbw = wfGetDB( DB_MASTER
);
1141 $now = wfTimestampNow();
1142 $this->mTimestamp
= $now;
1144 if ( $flags & EDIT_UPDATE
) {
1145 # Update article, but only if changed.
1146 $status->value
['new'] = false;
1148 # Make sure the revision is either completely inserted or not inserted at all
1149 if ( !$wgDBtransactions ) {
1150 $userAbort = ignore_user_abort( true );
1153 $revision = new Revision( array(
1154 'page' => $this->getId(),
1155 'comment' => $summary,
1156 'minor_edit' => $isminor,
1158 'parent_id' => $oldid,
1159 'user' => $user->getId(),
1160 'user_text' => $user->getName(),
1164 $changed = ( strcmp( $text, $oldtext ) != 0 );
1167 if ( !$this->mLatest
) {
1168 # Article gone missing
1169 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1170 $status->fatal( 'edit-gone-missing' );
1172 wfProfileOut( __METHOD__
);
1177 $revisionId = $revision->insertOn( $dbw );
1181 # Note that we use $this->mLatest instead of fetching a value from the master DB
1182 # during the course of this function. This makes sure that EditPage can detect
1183 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1184 # before this function is called. A previous function used a separate query, this
1185 # creates a window where concurrent edits can cause an ignored edit conflict.
1186 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1189 /* Belated edit conflict! Run away!! */
1190 $status->fatal( 'edit-conflict' );
1192 # Delete the invalid revision if the DB is not transactional
1193 if ( !$wgDBtransactions ) {
1194 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1200 global $wgUseRCPatrol;
1201 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1202 # Update recentchanges
1203 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1204 # Mark as patrolled if the user can do so
1205 $patrolled = $wgUseRCPatrol && !count(
1206 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1207 # Add RC row to the DB
1208 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1209 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1210 $revisionId, $patrolled
1213 # Log auto-patrolled edits
1215 PatrolLog
::record( $rc, true );
1218 $user->incEditCount();
1223 if ( !$wgDBtransactions ) {
1224 ignore_user_abort( $userAbort );
1227 // Now that ignore_user_abort is restored, we can respond to fatal errors
1228 if ( !$status->isOK() ) {
1229 wfProfileOut( __METHOD__
);
1233 # Update links tables, site stats, etc.
1234 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1235 'oldcountable' => $oldcountable ) );
1238 $status->warning( 'edit-no-change' );
1240 // Keep the same revision ID, but do some updates on it
1241 $revisionId = $this->getLatest();
1242 // Update page_touched, this is usually implicit in the page update
1243 // Other cache updates are done in onArticleEdit()
1244 $this->mTitle
->invalidateCache();
1247 # Create new article
1248 $status->value
['new'] = true;
1252 # Add the page record; stake our claim on this title!
1253 # This will return false if the article already exists
1254 $newid = $this->insertOn( $dbw );
1256 if ( $newid === false ) {
1258 $status->fatal( 'edit-already-exists' );
1260 wfProfileOut( __METHOD__
);
1264 # Save the revision text...
1265 $revision = new Revision( array(
1267 'comment' => $summary,
1268 'minor_edit' => $isminor,
1270 'user' => $user->getId(),
1271 'user_text' => $user->getName(),
1274 $revisionId = $revision->insertOn( $dbw );
1276 # Update the page record with revision data
1277 $this->updateRevisionOn( $dbw, $revision, 0 );
1279 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1281 # Update recentchanges
1282 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1283 global $wgUseRCPatrol, $wgUseNPPatrol;
1285 # Mark as patrolled if the user can do so
1286 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1287 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1288 # Add RC row to the DB
1289 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1290 '', strlen( $text ), $revisionId, $patrolled );
1292 # Log auto-patrolled edits
1294 PatrolLog
::record( $rc, true );
1297 $user->incEditCount();
1300 # Update links, etc.
1301 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1303 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1304 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1307 # Do updates right now unless deferral was requested
1308 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1309 DeferredUpdates
::doUpdates();
1312 // Return the new revision (or null) to the caller
1313 $status->value
['revision'] = $revision;
1315 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1316 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1318 # Promote user to any groups they meet the criteria for
1319 $user->addAutopromoteOnceGroups( 'onEdit' );
1321 wfProfileOut( __METHOD__
);
1326 * Update the article's restriction field, and leave a log entry.
1328 * @todo: seperate the business/permission stuff out from backend code
1330 * @param $limit Array: set of restriction keys
1331 * @param $reason String
1332 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1333 * @param $expiry Array: per restriction type expiration
1334 * @param $user User The user updating the restrictions
1335 * @return bool true on success
1337 public function updateRestrictions(
1338 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
1340 global $wgUser, $wgContLang;
1341 $user = is_null( $user ) ?
$wgUser : $user;
1343 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1345 $id = $this->mTitle
->getArticleID();
1348 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1352 if ( wfReadOnly() ) {
1353 wfDebug( "updateRestrictions failed: read-only\n" );
1357 if ( count( $this->mTitle
->getUserPermissionsErrors( 'protect', $user ) ) ) {
1358 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1366 // Take this opportunity to purge out expired restrictions
1367 Title
::purgeExpiredRestrictions();
1369 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1370 # we expect a single selection, but the schema allows otherwise.
1372 $updated = self
::flattenRestrictions( $limit );
1375 foreach ( $restrictionTypes as $action ) {
1376 if ( isset( $expiry[$action] ) ) {
1377 # Get current restrictions on $action
1378 $aLimits = $this->mTitle
->getRestrictions( $action );
1379 $current[$action] = implode( '', $aLimits );
1380 # Are any actual restrictions being dealt with here?
1381 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
1383 # If something changed, we need to log it. Checking $aRChanged
1384 # assures that "unprotecting" a page that is not protected does
1385 # not log just because the expiry was "changed".
1387 $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] )
1394 $current = self
::flattenRestrictions( $current );
1396 $changed = ( $changed ||
$current != $updated );
1397 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
1398 $protect = ( $updated != '' );
1400 # If nothing's changed, do nothing
1402 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1403 $dbw = wfGetDB( DB_MASTER
);
1405 # Prepare a null revision to be added to the history
1406 $modified = $current != '' && $protect;
1409 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1411 $comment_type = 'unprotectedarticle';
1414 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1416 # Only restrictions with the 'protect' right can cascade...
1417 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1418 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1420 # The schema allows multiple restrictions
1421 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1425 $cascade_description = '';
1428 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1432 $comment .= ": $reason";
1435 $editComment = $comment;
1436 $encodedExpiry = array();
1437 $protect_description = '';
1438 foreach ( $limit as $action => $restrictions ) {
1439 if ( !isset( $expiry[$action] ) )
1440 $expiry[$action] = $dbw->getInfinity();
1442 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1443 if ( $restrictions != '' ) {
1444 $protect_description .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1445 if ( $encodedExpiry[$action] != 'infinity' ) {
1446 $protect_description .= wfMsgForContent( 'protect-expiring',
1447 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1448 $wgContLang->date( $expiry[$action], false, false ) ,
1449 $wgContLang->time( $expiry[$action], false, false ) );
1451 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1454 $protect_description .= ') ';
1457 $protect_description = trim( $protect_description );
1459 if ( $protect_description && $protect ) {
1460 $editComment .= " ($protect_description)";
1464 $editComment .= "$cascade_description";
1467 # Update restrictions table
1468 foreach ( $limit as $action => $restrictions ) {
1469 if ( $restrictions != '' ) {
1470 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1471 array( 'pr_page' => $id,
1472 'pr_type' => $action,
1473 'pr_level' => $restrictions,
1474 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1475 'pr_expiry' => $encodedExpiry[$action]
1480 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1481 'pr_type' => $action ), __METHOD__
);
1485 # Insert a null revision
1486 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1487 $nullRevId = $nullRevision->insertOn( $dbw );
1489 $latest = $this->getLatest();
1490 # Update page record
1491 $dbw->update( 'page',
1493 'page_touched' => $dbw->timestamp(),
1494 'page_restrictions' => '',
1495 'page_latest' => $nullRevId
1496 ), array( /* WHERE */
1501 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1502 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1504 # Update the protection log
1505 $log = new LogPage( 'protect' );
1507 $params = array( $protect_description, $cascade ?
'cascade' : '' );
1508 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
1510 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1513 } # End "changed" check
1519 * Take an array of page restrictions and flatten it to a string
1520 * suitable for insertion into the page_restrictions field.
1521 * @param $limit Array
1524 protected static function flattenRestrictions( $limit ) {
1525 if ( !is_array( $limit ) ) {
1526 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1532 foreach ( $limit as $action => $restrictions ) {
1533 if ( $restrictions != '' ) {
1534 $bits[] = "$action=$restrictions";
1538 return implode( ':', $bits );
1542 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1544 public function isBigDeletion() {
1545 global $wgDeleteRevisionsLimit;
1547 if ( $wgDeleteRevisionsLimit ) {
1548 $revCount = $this->estimateRevisionCount();
1550 return $revCount > $wgDeleteRevisionsLimit;
1557 * @return int approximate revision count
1559 public function estimateRevisionCount() {
1560 $dbr = wfGetDB( DB_SLAVE
);
1561 return $dbr->estimateRowCount( 'revision', '*',
1562 array( 'rev_page' => $this->getId() ), __METHOD__
);
1566 * Get the last N authors
1567 * @param $num Integer: number of revisions to get
1568 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1569 * @return array Array of authors, duplicates not removed
1571 public function getLastNAuthors( $num, $revLatest = 0 ) {
1572 wfProfileIn( __METHOD__
);
1573 // First try the slave
1574 // If that doesn't have the latest revision, try the master
1576 $db = wfGetDB( DB_SLAVE
);
1579 $res = $db->select( array( 'page', 'revision' ),
1580 array( 'rev_id', 'rev_user_text' ),
1582 'page_namespace' => $this->mTitle
->getNamespace(),
1583 'page_title' => $this->mTitle
->getDBkey(),
1584 'rev_page = page_id'
1587 'ORDER BY' => 'rev_timestamp DESC',
1593 wfProfileOut( __METHOD__
);
1597 $row = $db->fetchObject( $res );
1599 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1600 $db = wfGetDB( DB_MASTER
);
1605 } while ( $continue );
1607 $authors = array( $row->rev_user_text
);
1609 foreach ( $res as $row ) {
1610 $authors[] = $row->rev_user_text
;
1613 wfProfileOut( __METHOD__
);
1618 * Back-end article deletion
1619 * Deletes the article with database consistency, writes logs, purges caches
1621 * @param $reason string delete reason for deletion log
1622 * @param $suppress bitfield
1623 * Revision::DELETED_TEXT
1624 * Revision::DELETED_COMMENT
1625 * Revision::DELETED_USER
1626 * Revision::DELETED_RESTRICTED
1627 * @param $id int article ID
1628 * @param $commit boolean defaults to true, triggers transaction end
1629 * @param &$errors Array of errors to append to
1630 * @param $user User The relevant user
1631 * @return boolean true if successful
1633 public function doDeleteArticle(
1634 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1637 $user = is_null( $user ) ?
$wgUser : $user;
1639 wfDebug( __METHOD__
. "\n" );
1641 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1644 $dbw = wfGetDB( DB_MASTER
);
1645 $t = $this->mTitle
->getDBkey();
1646 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1648 if ( $t === '' ||
$id == 0 ) {
1652 DeferredUpdates
::addUpdate(
1653 new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 )
1656 // Bitfields to further suppress the content
1659 // This should be 15...
1660 $bitfield |
= Revision
::DELETED_TEXT
;
1661 $bitfield |
= Revision
::DELETED_COMMENT
;
1662 $bitfield |
= Revision
::DELETED_USER
;
1663 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1665 $bitfield = 'rev_deleted';
1669 // For now, shunt the revision data into the archive table.
1670 // Text is *not* removed from the text table; bulk storage
1671 // is left intact to avoid breaking block-compression or
1672 // immutable storage schemes.
1674 // For backwards compatibility, note that some older archive
1675 // table entries will have ar_text and ar_flags fields still.
1677 // In the future, we may keep revisions and mark them with
1678 // the rev_deleted field, which is reserved for this purpose.
1679 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1681 'ar_namespace' => 'page_namespace',
1682 'ar_title' => 'page_title',
1683 'ar_comment' => 'rev_comment',
1684 'ar_user' => 'rev_user',
1685 'ar_user_text' => 'rev_user_text',
1686 'ar_timestamp' => 'rev_timestamp',
1687 'ar_minor_edit' => 'rev_minor_edit',
1688 'ar_rev_id' => 'rev_id',
1689 'ar_parent_id' => 'rev_parent_id',
1690 'ar_text_id' => 'rev_text_id',
1691 'ar_text' => '\'\'', // Be explicit to appease
1692 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1693 'ar_len' => 'rev_len',
1694 'ar_page_id' => 'page_id',
1695 'ar_deleted' => $bitfield,
1696 'ar_sha1' => 'rev_sha1'
1699 'page_id = rev_page'
1703 # Delete restrictions for it
1704 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1706 # Now that it's safely backed up, delete it
1707 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1708 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1715 # Fix category table counts
1717 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1719 foreach ( $res as $row ) {
1720 $cats [] = $row->cl_to
;
1723 $this->updateCategoryCounts( array(), $cats );
1725 # If using cascading deletes, we can skip some explicit deletes
1726 if ( !$dbw->cascadingDeletes() ) {
1727 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
1729 # Delete outgoing links
1730 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
1731 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
1732 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
1733 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
1734 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
1735 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
1736 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
1737 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
1738 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
1741 # If using cleanup triggers, we can skip some manual deletes
1742 if ( !$dbw->cleanupTriggers() ) {
1743 # Clean up recentchanges entries...
1744 $dbw->delete( 'recentchanges',
1745 array( 'rc_type != ' . RC_LOG
,
1746 'rc_namespace' => $this->mTitle
->getNamespace(),
1747 'rc_title' => $this->mTitle
->getDBkey() ),
1749 $dbw->delete( 'recentchanges',
1750 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
1755 self
::onArticleDelete( $this->mTitle
);
1757 # Clear the cached article id so the interface doesn't act like we exist
1758 $this->mTitle
->resetArticleID( 0 );
1760 # Log the deletion, if the page was suppressed, log it at Oversight instead
1761 $logtype = $suppress ?
'suppress' : 'delete';
1763 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1764 $logEntry->setPerformer( $user );
1765 $logEntry->setTarget( $this->mTitle
);
1766 $logEntry->setComment( $reason );
1767 $logid = $logEntry->insert();
1768 $logEntry->publish( $logid );
1774 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1779 * Roll back the most recent consecutive set of edits to a page
1780 * from the same user; fails if there are no eligible edits to
1781 * roll back to, e.g. user is the sole contributor. This function
1782 * performs permissions checks on $user, then calls commitRollback()
1783 * to do the dirty work
1785 * @todo: seperate the business/permission stuff out from backend code
1787 * @param $fromP String: Name of the user whose edits to rollback.
1788 * @param $summary String: Custom summary. Set to default summary if empty.
1789 * @param $token String: Rollback token.
1790 * @param $bot Boolean: If true, mark all reverted edits as bot.
1792 * @param $resultDetails Array: contains result-specific array of additional values
1793 * 'alreadyrolled' : 'current' (rev)
1794 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1796 * @param $user User The user performing the rollback
1797 * @return array of errors, each error formatted as
1798 * array(messagekey, param1, param2, ...).
1799 * On success, the array is empty. This array can also be passed to
1800 * OutputPage::showPermissionsErrorPage().
1802 public function doRollback(
1803 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
1805 $resultDetails = null;
1808 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
1809 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
1810 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1812 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
1813 $errors[] = array( 'sessionfailure' );
1816 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
1817 $errors[] = array( 'actionthrottledtext' );
1820 # If there were errors, bail out now
1821 if ( !empty( $errors ) ) {
1825 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
1829 * Backend implementation of doRollback(), please refer there for parameter
1830 * and return value documentation
1832 * NOTE: This function does NOT check ANY permissions, it just commits the
1833 * rollback to the DB. Therefore, you should only call this function direct-
1834 * ly if you want to use custom permissions checks. If you don't, use
1835 * doRollback() instead.
1836 * @param $fromP String: Name of the user whose edits to rollback.
1837 * @param $summary String: Custom summary. Set to default summary if empty.
1838 * @param $bot Boolean: If true, mark all reverted edits as bot.
1840 * @param $resultDetails Array: contains result-specific array of additional values
1841 * @param $guser User The user performing the rollback
1843 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
1844 global $wgUseRCPatrol, $wgContLang;
1846 $dbw = wfGetDB( DB_MASTER
);
1848 if ( wfReadOnly() ) {
1849 return array( array( 'readonlytext' ) );
1852 # Get the last editor
1853 $current = Revision
::newFromTitle( $this->mTitle
);
1854 if ( is_null( $current ) ) {
1855 # Something wrong... no page?
1856 return array( array( 'notanarticle' ) );
1859 $from = str_replace( '_', ' ', $fromP );
1860 # User name given should match up with the top revision.
1861 # If the user was deleted then $from should be empty.
1862 if ( $from != $current->getUserText() ) {
1863 $resultDetails = array( 'current' => $current );
1864 return array( array( 'alreadyrolled',
1865 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
1866 htmlspecialchars( $fromP ),
1867 htmlspecialchars( $current->getUserText() )
1871 # Get the last edit not by this guy...
1872 # Note: these may not be public values
1873 $user = intval( $current->getRawUser() );
1874 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1875 $s = $dbw->selectRow( 'revision',
1876 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1877 array( 'rev_page' => $current->getPage(),
1878 "rev_user != {$user} OR rev_user_text != {$user_text}"
1880 array( 'USE INDEX' => 'page_timestamp',
1881 'ORDER BY' => 'rev_timestamp DESC' )
1883 if ( $s === false ) {
1884 # No one else ever edited this page
1885 return array( array( 'cantrollback' ) );
1886 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
1887 # Only admins can see this text
1888 return array( array( 'notvisiblerev' ) );
1892 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1893 # Mark all reverted edits as bot
1897 if ( $wgUseRCPatrol ) {
1898 # Mark all reverted edits as patrolled
1899 $set['rc_patrolled'] = 1;
1902 if ( count( $set ) ) {
1903 $dbw->update( 'recentchanges', $set,
1905 'rc_cur_id' => $current->getPage(),
1906 'rc_user_text' => $current->getUserText(),
1907 "rc_timestamp > '{$s->rev_timestamp}'",
1912 # Generate the edit summary if necessary
1913 $target = Revision
::newFromId( $s->rev_id
);
1914 if ( empty( $summary ) ) {
1915 if ( $from == '' ) { // no public user name
1916 $summary = wfMsgForContent( 'revertpage-nouser' );
1918 $summary = wfMsgForContent( 'revertpage' );
1922 # Allow the custom summary to use the same args as the default message
1924 $target->getUserText(), $from, $s->rev_id
,
1925 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
1926 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1928 $summary = wfMsgReplaceArgs( $summary, $args );
1931 $flags = EDIT_UPDATE
;
1933 if ( $guser->isAllowed( 'minoredit' ) ) {
1934 $flags |
= EDIT_MINOR
;
1937 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1938 $flags |
= EDIT_FORCE_BOT
;
1941 # Actually store the edit
1942 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1943 if ( !empty( $status->value
['revision'] ) ) {
1944 $revId = $status->value
['revision']->getId();
1949 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1951 $resultDetails = array(
1952 'summary' => $summary,
1953 'current' => $current,
1954 'target' => $target,
1962 * Do standard deferred updates after page view
1963 * @param $user User The relevant user
1965 public function doViewUpdates( User
$user ) {
1966 global $wgDisableCounters;
1967 if ( wfReadOnly() ) {
1971 # Don't update page view counters on views from bot users (bug 14044)
1972 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1973 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1974 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1977 # Update newtalk / watchlist notification status
1978 $user->clearNotification( $this->mTitle
);
1982 * Prepare text which is about to be saved.
1983 * Returns a stdclass with source, pst and output members
1985 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1986 global $wgParser, $wgContLang, $wgUser;
1987 $user = is_null( $user ) ?
$wgUser : $user;
1988 // @TODO fixme: check $user->getId() here???
1989 if ( $this->mPreparedEdit
1990 && $this->mPreparedEdit
->newText
== $text
1991 && $this->mPreparedEdit
->revid
== $revid
1994 return $this->mPreparedEdit
;
1997 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1998 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2000 $edit = (object)array();
2001 $edit->revid
= $revid;
2002 $edit->newText
= $text;
2003 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2004 $edit->popts
= $this->makeParserOptions( 'canonical' );
2006 // Bug 32858: For a CSS/JS page, put a blank parser output into the
2007 // prepared edit, so that links etc. won't be registered in the
2008 // database. We could have set $edit->output to false or something if
2009 // we thought of this bug earlier, but now that would break the
2010 // interface with AbuseFilter etc.
2011 if ( $this->mTitle
->isCssOrJsPage() ||
$this->getTitle()->isCssJsSubpage() ) {
2014 $input = $edit->pst
;
2016 $edit->output
= $wgParser->parse( $input, $this->mTitle
, $edit->popts
, true, true, $revid );
2017 $edit->oldText
= $this->getRawText();
2019 $this->mPreparedEdit
= $edit;
2025 * Do standard deferred updates after page edit.
2026 * Update links tables, site stats, search index and message cache.
2027 * Purges pages that include this page if the text was changed here.
2028 * Every 100th edit, prune the recent changes table.
2031 * @param $revision Revision object
2032 * @param $user User object that did the revision
2033 * @param $options Array of options, following indexes are used:
2034 * - changed: boolean, whether the revision changed the content (default true)
2035 * - created: boolean, whether the revision created the page (default false)
2036 * - oldcountable: boolean or null (default null):
2037 * - boolean: whether the page was counted as an article before that
2038 * revision, only used in changed is true and created is false
2039 * - null: don't change the article count
2041 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2042 global $wgEnableParserCache;
2044 wfProfileIn( __METHOD__
);
2046 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2047 $text = $revision->getText();
2050 # Be careful not to double-PST: $text is usually already PST-ed once
2051 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2052 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2053 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
2055 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2056 $editInfo = $this->mPreparedEdit
;
2059 # Save it to the parser cache
2060 if ( $wgEnableParserCache ) {
2061 $parserCache = ParserCache
::singleton();
2062 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2065 # Update the links tables
2066 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2069 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2071 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2072 if ( 0 == mt_rand( 0, 99 ) ) {
2073 // Flush old entries from the `recentchanges` table; we do this on
2074 // random requests so as to avoid an increase in writes for no good reason
2077 $dbw = wfGetDB( DB_MASTER
);
2078 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2081 array( "rc_timestamp < '$cutoff'" ),
2087 if ( !$this->mTitle
->exists() ) {
2088 wfProfileOut( __METHOD__
);
2092 $id = $this->getId();
2093 $title = $this->mTitle
->getPrefixedDBkey();
2094 $shortTitle = $this->mTitle
->getDBkey();
2096 if ( !$options['changed'] ) {
2099 } elseif ( $options['created'] ) {
2100 $good = (int)$this->isCountable( $editInfo );
2102 } elseif ( $options['oldcountable'] !== null ) {
2103 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2110 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2111 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
2113 # If this is another user's talk page, update newtalk.
2114 # Don't do this if $options['changed'] = false (null-edits) nor if
2115 # it's a minor edit and the user doesn't want notifications for those.
2116 if ( $options['changed']
2117 && $this->mTitle
->getNamespace() == NS_USER_TALK
2118 && $shortTitle != $user->getTitleKey()
2119 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2121 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2122 $other = User
::newFromName( $shortTitle, false );
2124 wfDebug( __METHOD__
. ": invalid username\n" );
2125 } elseif ( User
::isIP( $shortTitle ) ) {
2126 // An anonymous user
2127 $other->setNewtalk( true );
2128 } elseif ( $other->isLoggedIn() ) {
2129 $other->setNewtalk( true );
2131 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2136 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2137 MessageCache
::singleton()->replace( $shortTitle, $text );
2140 if( $options['created'] ) {
2141 self
::onArticleCreate( $this->mTitle
);
2143 self
::onArticleEdit( $this->mTitle
);
2146 wfProfileOut( __METHOD__
);
2150 * Perform article updates on a special page creation.
2152 * @param $rev Revision object
2154 * @todo This is a shitty interface function. Kill it and replace the
2155 * other shitty functions like doEditUpdates and such so it's not needed
2157 * @deprecated since 1.18, use doEditUpdates()
2159 public function createUpdates( $rev ) {
2160 wfDeprecated( __METHOD__
, '1.18' );
2162 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2166 * This function is called right before saving the wikitext,
2167 * so we can do things like signatures and links-in-context.
2169 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2170 * @param $text String article contents
2171 * @param $user User object: user doing the edit
2172 * @param $popts ParserOptions object: parser options, default options for
2173 * the user loaded if null given
2174 * @return string article contents with altered wikitext markup (signatures
2175 * converted, {{subst:}}, templates, etc.)
2177 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2178 global $wgParser, $wgUser;
2180 wfDeprecated( __METHOD__
, '1.19' );
2182 $user = is_null( $user ) ?
$wgUser : $user;
2184 if ( $popts === null ) {
2185 $popts = ParserOptions
::newFromUser( $user );
2188 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2192 * Loads page_touched and returns a value indicating if it should be used
2193 * @return boolean true if not a redirect
2195 public function checkTouched() {
2196 if ( !$this->mDataLoaded
) {
2197 $this->loadPageData();
2199 return !$this->mIsRedirect
;
2203 * Get the page_touched field
2204 * @return string containing GMT timestamp
2206 public function getTouched() {
2207 if ( !$this->mDataLoaded
) {
2208 $this->loadPageData();
2210 return $this->mTouched
;
2214 * Get the page_latest field
2215 * @return integer rev_id of current revision
2217 public function getLatest() {
2218 if ( !$this->mDataLoaded
) {
2219 $this->loadPageData();
2221 return (int)$this->mLatest
;
2225 * Edit an article without doing all that other stuff
2226 * The article must already exist; link tables etc
2227 * are not updated, caches are not flushed.
2229 * @param $text String: text submitted
2230 * @param $user User The relevant user
2231 * @param $comment String: comment submitted
2232 * @param $minor Boolean: whereas it's a minor modification
2234 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2235 wfProfileIn( __METHOD__
);
2237 $dbw = wfGetDB( DB_MASTER
);
2238 $revision = new Revision( array(
2239 'page' => $this->getId(),
2241 'comment' => $comment,
2242 'minor_edit' => $minor ?
1 : 0,
2244 $revision->insertOn( $dbw );
2245 $this->updateRevisionOn( $dbw, $revision );
2247 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2249 wfProfileOut( __METHOD__
);
2253 * The onArticle*() functions are supposed to be a kind of hooks
2254 * which should be called whenever any of the specified actions
2257 * This is a good place to put code to clear caches, for instance.
2259 * This is called on page move and undelete, as well as edit
2261 * @param $title Title object
2263 public static function onArticleCreate( $title ) {
2264 # Update existence markers on article/talk tabs...
2265 if ( $title->isTalkPage() ) {
2266 $other = $title->getSubjectPage();
2268 $other = $title->getTalkPage();
2271 $other->invalidateCache();
2272 $other->purgeSquid();
2274 $title->touchLinks();
2275 $title->purgeSquid();
2276 $title->deleteTitleProtection();
2280 * Clears caches when article is deleted
2282 * @param $title Title
2284 public static function onArticleDelete( $title ) {
2285 # Update existence markers on article/talk tabs...
2286 if ( $title->isTalkPage() ) {
2287 $other = $title->getSubjectPage();
2289 $other = $title->getTalkPage();
2292 $other->invalidateCache();
2293 $other->purgeSquid();
2295 $title->touchLinks();
2296 $title->purgeSquid();
2299 HTMLFileCache
::clearFileCache( $title );
2302 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2303 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2307 if ( $title->getNamespace() == NS_FILE
) {
2308 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2309 $update->doUpdate();
2313 if ( $title->getNamespace() == NS_USER_TALK
) {
2314 $user = User
::newFromName( $title->getText(), false );
2316 $user->setNewtalk( false );
2321 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2325 * Purge caches on page update etc
2327 * @param $title Title object
2328 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2330 public static function onArticleEdit( $title ) {
2331 // Invalidate caches of articles which include this page
2332 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2335 // Invalidate the caches of all pages which redirect here
2336 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2338 # Purge squid for this page only
2339 $title->purgeSquid();
2341 # Clear file cache for this page only
2342 HTMLFileCache
::clearFileCache( $title );
2348 * Return a list of templates used by this article.
2349 * Uses the templatelinks table
2351 * @return Array of Title objects
2353 public function getUsedTemplates() {
2355 $id = $this->mTitle
->getArticleID();
2361 $dbr = wfGetDB( DB_SLAVE
);
2362 $res = $dbr->select( array( 'templatelinks' ),
2363 array( 'tl_namespace', 'tl_title' ),
2364 array( 'tl_from' => $id ),
2367 if ( $res !== false ) {
2368 foreach ( $res as $row ) {
2369 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2377 * Returns a list of hidden categories this page is a member of.
2378 * Uses the page_props and categorylinks tables.
2380 * @return Array of Title objects
2382 public function getHiddenCategories() {
2384 $id = $this->mTitle
->getArticleID();
2390 $dbr = wfGetDB( DB_SLAVE
);
2391 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2393 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2394 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2397 if ( $res !== false ) {
2398 foreach ( $res as $row ) {
2399 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2407 * Return an applicable autosummary if one exists for the given edit.
2408 * @param $oldtext String: the previous text of the page.
2409 * @param $newtext String: The submitted text of the page.
2410 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2411 * @return string An appropriate autosummary, or an empty string.
2413 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2416 # Decide what kind of autosummary is needed.
2418 # Redirect autosummaries
2419 $ot = Title
::newFromRedirect( $oldtext );
2420 $rt = Title
::newFromRedirect( $newtext );
2422 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2423 $truncatedtext = $wgContLang->truncate(
2424 str_replace( "\n", ' ', $newtext ),
2426 - strlen( wfMsgForContent( 'autoredircomment' ) )
2427 - strlen( $rt->getFullText() )
2429 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2432 # New page autosummaries
2433 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2434 # If they're making a new article, give its text, truncated, in the summary.
2436 $truncatedtext = $wgContLang->truncate(
2437 str_replace( "\n", ' ', $newtext ),
2438 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2440 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2443 # Blanking autosummaries
2444 if ( $oldtext != '' && $newtext == '' ) {
2445 return wfMsgForContent( 'autosumm-blank' );
2446 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2447 # Removing more than 90% of the article
2449 $truncatedtext = $wgContLang->truncate(
2451 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2453 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2456 # If we reach this point, there's no applicable autosummary for our case, so our
2457 # autosummary is empty.
2462 * Auto-generates a deletion reason
2464 * @param &$hasHistory Boolean: whether the page has a history
2465 * @return mixed String containing deletion reason or empty string, or boolean false
2466 * if no revision occurred
2468 public function getAutoDeleteReason( &$hasHistory ) {
2471 $dbw = wfGetDB( DB_MASTER
);
2472 // Get the last revision
2473 $rev = Revision
::newFromTitle( $this->getTitle() );
2475 if ( is_null( $rev ) ) {
2479 // Get the article's contents
2480 $contents = $rev->getText();
2483 // If the page is blank, use the text from the previous revision,
2484 // which can only be blank if there's a move/import/protect dummy revision involved
2485 if ( $contents == '' ) {
2486 $prev = $rev->getPrevious();
2489 $contents = $prev->getText();
2494 // Find out if there was only one contributor
2495 // Only scan the last 20 revisions
2496 $res = $dbw->select( 'revision', 'rev_user_text',
2497 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2499 array( 'LIMIT' => 20 )
2502 if ( $res === false ) {
2503 // This page has no revisions, which is very weird
2507 $hasHistory = ( $res->numRows() > 1 );
2508 $row = $dbw->fetchObject( $res );
2510 if ( $row ) { // $row is false if the only contributor is hidden
2511 $onlyAuthor = $row->rev_user_text
;
2512 // Try to find a second contributor
2513 foreach ( $res as $row ) {
2514 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2515 $onlyAuthor = false;
2520 $onlyAuthor = false;
2523 // Generate the summary with a '$1' placeholder
2525 // The current revision is blank and the one before is also
2526 // blank. It's just not our lucky day
2527 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2529 if ( $onlyAuthor ) {
2530 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2532 $reason = wfMsgForContent( 'excontent', '$1' );
2536 if ( $reason == '-' ) {
2537 // Allow these UI messages to be blanked out cleanly
2541 // Replace newlines with spaces to prevent uglyness
2542 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2543 // Calculate the maximum amount of chars to get
2544 // Max content length = max comment length - length of the comment (excl. $1)
2545 $maxLength = 255 - ( strlen( $reason ) - 2 );
2546 $contents = $wgContLang->truncate( $contents, $maxLength );
2547 // Remove possible unfinished links
2548 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2549 // Now replace the '$1' placeholder
2550 $reason = str_replace( '$1', $contents, $reason );
2556 * Get parser options suitable for rendering the primary article wikitext
2557 * @param User|string $user User object or 'canonical'
2558 * @return ParserOptions
2560 public function makeParserOptions( $user ) {
2562 if ( $user instanceof User
) { // settings per user (even anons)
2563 $options = ParserOptions
::newFromUser( $user );
2564 } else { // canonical settings
2565 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
2567 $options->enableLimitReport(); // show inclusion/loop reports
2568 $options->setTidy( true ); // fix bad HTML
2573 * Update all the appropriate counts in the category table, given that
2574 * we've added the categories $added and deleted the categories $deleted.
2576 * @param $added array The names of categories that were added
2577 * @param $deleted array The names of categories that were deleted
2579 public function updateCategoryCounts( $added, $deleted ) {
2580 $ns = $this->mTitle
->getNamespace();
2581 $dbw = wfGetDB( DB_MASTER
);
2583 # First make sure the rows exist. If one of the "deleted" ones didn't
2584 # exist, we might legitimately not create it, but it's simpler to just
2585 # create it and then give it a negative value, since the value is bogus
2588 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2589 $insertCats = array_merge( $added, $deleted );
2590 if ( !$insertCats ) {
2591 # Okay, nothing to do
2595 $insertRows = array();
2597 foreach ( $insertCats as $cat ) {
2598 $insertRows[] = array(
2599 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2603 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2605 $addFields = array( 'cat_pages = cat_pages + 1' );
2606 $removeFields = array( 'cat_pages = cat_pages - 1' );
2608 if ( $ns == NS_CATEGORY
) {
2609 $addFields[] = 'cat_subcats = cat_subcats + 1';
2610 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2611 } elseif ( $ns == NS_FILE
) {
2612 $addFields[] = 'cat_files = cat_files + 1';
2613 $removeFields[] = 'cat_files = cat_files - 1';
2620 array( 'cat_title' => $added ),
2629 array( 'cat_title' => $deleted ),
2636 * Updates cascading protections
2638 * @param $parserOutput ParserOutput object for the current version
2640 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2641 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2645 // templatelinks table may have become out of sync,
2646 // especially if using variable-based transclusions.
2647 // For paranoia, check if things have changed and if
2648 // so apply updates to the database. This will ensure
2649 // that cascaded protections apply as soon as the changes
2652 # Get templates from templatelinks
2653 $id = $this->mTitle
->getArticleID();
2655 $tlTemplates = array();
2657 $dbr = wfGetDB( DB_SLAVE
);
2658 $res = $dbr->select( array( 'templatelinks' ),
2659 array( 'tl_namespace', 'tl_title' ),
2660 array( 'tl_from' => $id ),
2664 foreach ( $res as $row ) {
2665 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2668 # Get templates from parser output.
2669 $poTemplates = array();
2670 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2671 foreach ( $templates as $dbk => $id ) {
2672 $poTemplates["$ns:$dbk"] = true;
2677 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2679 if ( count( $templates_diff ) > 0 ) {
2680 # Whee, link updates time.
2681 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2687 * @deprecated since 1.18
2689 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2690 wfDeprecated( __METHOD__
, '1.18' );
2692 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2696 * @deprecated since 1.18
2698 public function viewUpdates() {
2699 wfDeprecated( __METHOD__
, '1.18' );
2701 return $this->doViewUpdates( $wgUser );
2705 * @deprecated since 1.18
2707 public function useParserCache( $oldid ) {
2708 wfDeprecated( __METHOD__
, '1.18' );
2710 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2714 class PoolWorkArticleView
extends PoolCounterWork
{
2732 * @var ParserOptions
2734 private $parserOptions;
2742 * @var ParserOutput|false
2744 private $parserOutput = false;
2749 private $isDirty = false;
2754 private $error = false;
2760 * @param $revid Integer: ID of the revision being parsed
2761 * @param $useParserCache Boolean: whether to use the parser cache
2762 * @param $parserOptions parserOptions to use for the parse operation
2763 * @param $text String: text to parse or null to load it
2765 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2766 $this->page
= $page;
2767 $this->revid
= $revid;
2768 $this->cacheable
= $useParserCache;
2769 $this->parserOptions
= $parserOptions;
2770 $this->text
= $text;
2771 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2772 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2776 * Get the ParserOutput from this object, or false in case of failure
2778 * @return ParserOutput
2780 public function getParserOutput() {
2781 return $this->parserOutput
;
2785 * Get whether the ParserOutput is a dirty one (i.e. expired)
2789 public function getIsDirty() {
2790 return $this->isDirty
;
2794 * Get a Status object in case of error or false otherwise
2796 * @return Status|false
2798 public function getError() {
2799 return $this->error
;
2806 global $wgParser, $wgUseFileCache;
2808 $isCurrent = $this->revid
=== $this->page
->getLatest();
2810 if ( $this->text
!== null ) {
2811 $text = $this->text
;
2812 } elseif ( $isCurrent ) {
2813 $text = $this->page
->getRawText();
2815 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2816 if ( $rev === null ) {
2819 $text = $rev->getText();
2823 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2824 $this->parserOptions
, true, true, $this->revid
);
2829 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2830 $this->page
->getTitle()->getPrefixedDBkey() ) );
2833 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2834 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2837 // Make sure file cache is not used on uncacheable content.
2838 // Output that has magic words in it can still use the parser cache
2839 // (if enabled), though it will generally expire sooner.
2840 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2841 $wgUseFileCache = false;
2845 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2854 function getCachedWork() {
2855 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2857 if ( $this->parserOutput
=== false ) {
2858 wfDebug( __METHOD__
. ": parser cache miss\n" );
2861 wfDebug( __METHOD__
. ": parser cache hit\n" );
2869 function fallback() {
2870 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2872 if ( $this->parserOutput
=== false ) {
2873 wfDebugLog( 'dirty', "dirty missing\n" );
2874 wfDebug( __METHOD__
. ": no dirty cache\n" );
2877 wfDebug( __METHOD__
. ": sending dirty output\n" );
2878 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2879 $this->isDirty
= true;
2885 * @param $status Status
2887 function error( $status ) {
2888 $this->error
= $status;