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 * @TODO: dependency inject $wgUser as an argument to functions
15 * @internal documentation reviewed 15 Mar 2010
17 class WikiPage
extends Page
{
20 * Fields are public for backwards-compatibility. Use accessors.
21 * In the past, this class was part of Article.php and everything was public.
23 public $mTitle = null; // !< Title object
24 public $mCounter = -1; // !< Not loaded
25 public $mDataLoaded = false; // !<
26 public $mIsRedirect = false; // !<
27 public $mLatest = false; // !<
28 public $mPreparedEdit = false; // !<
29 public $mRedirectTarget = null; // !< Title object
30 public $mLastRevision = null; // !< Revision object
31 public $mTimestamp = ''; // !<
32 public $mTouched = '19700101000000'; // !<
37 * @var ParserOptions: ParserOptions object for $wgUser articles
39 public $mParserOptions;
42 * Constructor and clear the article
43 * @param $title Title Reference to a Title object.
45 public function __construct( Title
$title ) {
46 $this->mTitle
= $title;
50 * Constructor from a page id
51 * @param $id Int article ID to load
53 public static function newFromID( $id ) {
54 $t = Title
::newFromID( $id );
55 # @todo FIXME: Doesn't inherit right
56 return $t == null ?
null : new self( $t );
57 # return $t == null ? null : new static( $t ); // PHP 5.3
61 * If this page is a redirect, get its target
63 * The target will be fetched from the redirect table if possible.
64 * If this page doesn't have an entry there, call insertRedirect()
65 * @return Title|mixed object, or null if this page is not a redirect
67 public function getRedirectTarget() {
68 if ( !$this->mTitle
->isRedirect() ) {
72 if ( $this->mRedirectTarget
!== null ) {
73 return $this->mRedirectTarget
;
76 # Query the redirect table
77 $dbr = wfGetDB( DB_SLAVE
);
78 $row = $dbr->selectRow( 'redirect',
79 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
80 array( 'rd_from' => $this->getID() ),
84 // rd_fragment and rd_interwiki were added later, populate them if empty
85 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
86 return $this->mRedirectTarget
= Title
::makeTitle(
87 $row->rd_namespace
, $row->rd_title
,
88 $row->rd_fragment
, $row->rd_interwiki
);
91 # This page doesn't have an entry in the redirect table
92 return $this->mRedirectTarget
= $this->insertRedirect();
96 * Insert an entry for this page into the redirect table.
98 * Don't call this function directly unless you know what you're doing.
99 * @return Title object or null if not a redirect
101 public function insertRedirect() {
102 // recurse through to only get the final target
103 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
107 $this->insertRedirectEntry( $retval );
112 * Insert or update the redirect table entry for this page to indicate
113 * it redirects to $rt .
114 * @param $rt Title redirect target
116 public function insertRedirectEntry( $rt ) {
117 $dbw = wfGetDB( DB_MASTER
);
118 $dbw->replace( 'redirect', array( 'rd_from' ),
120 'rd_from' => $this->getID(),
121 'rd_namespace' => $rt->getNamespace(),
122 'rd_title' => $rt->getDBkey(),
123 'rd_fragment' => $rt->getFragment(),
124 'rd_interwiki' => $rt->getInterwiki(),
131 * Get the Title object or URL this page redirects to
133 * @return mixed false, Title of in-wiki target, or string with URL
135 public function followRedirect() {
136 return $this->getRedirectURL( $this->getRedirectTarget() );
140 * Get the Title object or URL to use for a redirect. We use Title
141 * objects for same-wiki, non-special redirects and URLs for everything
143 * @param $rt Title Redirect target
144 * @return mixed false, Title object of local target, or string with URL
146 public function getRedirectURL( $rt ) {
148 if ( $rt->getInterwiki() != '' ) {
149 if ( $rt->isLocal() ) {
150 // Offsite wikis need an HTTP redirect.
152 // This can be hard to reverse and may produce loops,
153 // so they may be disabled in the site configuration.
154 $source = $this->mTitle
->getFullURL( 'redirect=no' );
155 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
158 if ( $rt->getNamespace() == NS_SPECIAL
) {
159 // Gotta handle redirects to special pages differently:
160 // Fill the HTTP response "Location" header and ignore
161 // the rest of the page we're on.
163 // This can be hard to reverse, so they may be disabled.
164 if ( $rt->isSpecial( 'Userlogout' ) ) {
167 return $rt->getFullURL();
175 // No or invalid redirect
180 * Get the title object of the article
181 * @return Title object of this page
183 public function getTitle() {
184 return $this->mTitle
;
190 public function clear() {
191 $this->mDataLoaded
= false;
193 $this->mCounter
= -1; # Not loaded
194 $this->mRedirectTarget
= null; # Title object if set
195 $this->mLastRevision
= null; # Latest revision
196 $this->mTimestamp
= '';
197 $this->mTouched
= '19700101000000';
198 $this->mIsRedirect
= false;
199 $this->mLatest
= false;
200 $this->mPreparedEdit
= false;
204 * Get the text that needs to be saved in order to undo all revisions
205 * between $undo and $undoafter. Revisions must belong to the same page,
206 * must exist and must not be deleted
207 * @param $undo Revision
208 * @param $undoafter Revision Must be an earlier revision than $undo
209 * @return mixed string on success, false on failure
211 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
212 $cur_text = $this->getRawText();
213 if ( $cur_text === false ) {
214 return false; // no page
216 $undo_text = $undo->getText();
217 $undoafter_text = $undoafter->getText();
219 if ( $cur_text == $undo_text ) {
220 # No use doing a merge if it's just a straight revert.
221 return $undoafter_text;
226 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
234 * Return the list of revision fields that should be selected to create
237 public static function selectFields() {
254 * Fetch a page record with the given conditions
255 * @param $dbr DatabaseBase object
256 * @param $conditions Array
257 * @return mixed Database result resource, or false on failure
259 protected function pageData( $dbr, $conditions ) {
260 $fields = self
::selectFields();
262 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
264 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
266 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
272 * Fetch a page record matching the Title object's namespace and title
273 * using a sanitized title string
275 * @param $dbr DatabaseBase object
276 * @param $title Title object
277 * @return mixed Database result resource, or false on failure
279 protected function pageDataFromTitle( $dbr, $title ) {
280 return $this->pageData( $dbr, array(
281 'page_namespace' => $title->getNamespace(),
282 'page_title' => $title->getDBkey() ) );
286 * Fetch a page record matching the requested ID
288 * @param $dbr DatabaseBase
290 * @return mixed Database result resource, or false on failure
292 protected function pageDataFromId( $dbr, $id ) {
293 return $this->pageData( $dbr, array( 'page_id' => $id ) );
297 * Set the general counter, title etc data loaded from
300 * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
302 public function loadPageData( $data = 'fromdb' ) {
303 if ( $data === 'fromdb' ) {
304 $dbr = wfGetDB( DB_SLAVE
);
305 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
308 $lc = LinkCache
::singleton();
311 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
313 $this->mTitle
->mArticleID
= intval( $data->page_id
);
315 # Old-fashioned restrictions
316 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
318 $this->mCounter
= intval( $data->page_counter
);
319 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
320 $this->mIsRedirect
= intval( $data->page_is_redirect
);
321 $this->mLatest
= intval( $data->page_latest
);
323 $lc->addBadLinkObj( $this->mTitle
);
324 $this->mTitle
->mArticleID
= 0;
327 $this->mDataLoaded
= true;
331 * @return int Page ID
333 public function getID() {
334 return $this->mTitle
->getArticleID();
338 * @return bool Whether or not the page exists in the database
340 public function exists() {
341 return $this->getId() > 0;
345 * Check if this page is something we're going to be showing
346 * some sort of sensible content for. If we return false, page
347 * views (plain action=view) will return an HTTP 404 response,
348 * so spiders and robots can know they're following a bad link.
352 public function hasViewableContent() {
353 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
357 * @return int The view count for the page
359 public function getCount() {
360 if ( -1 == $this->mCounter
) {
361 $id = $this->getID();
366 $dbr = wfGetDB( DB_SLAVE
);
367 $this->mCounter
= $dbr->selectField( 'page',
369 array( 'page_id' => $id ),
375 return $this->mCounter
;
379 * Determine whether a page would be suitable for being counted as an
380 * article in the site_stats table based on the title & its content
382 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
383 * if false, the current database state will be used
386 public function isCountable( $editInfo = false ) {
387 global $wgArticleCountMethod;
389 if ( !$this->mTitle
->isContentPage() ) {
393 $text = $editInfo ?
$editInfo->pst
: false;
395 if ( $this->isRedirect( $text ) ) {
399 switch ( $wgArticleCountMethod ) {
403 if ( $text === false ) {
404 $text = $this->getRawText();
406 return strpos( $text, ',' ) !== false;
409 // ParserOutput::getLinks() is a 2D array of page links, so
410 // to be really correct we would need to recurse in the array
411 // but the main array should only have items in it if there are
413 return (bool)count( $editInfo->output
->getLinks() );
415 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
416 array( 'pl_from' => $this->getId() ), __METHOD__
);
422 * Tests if the article text represents a redirect
424 * @param $text mixed string containing article contents, or boolean
427 public function isRedirect( $text = false ) {
428 if ( $text === false ) {
429 if ( !$this->mDataLoaded
) {
430 $this->loadPageData();
433 return (bool)$this->mIsRedirect
;
435 return Title
::newFromRedirect( $text ) !== null;
440 * Loads everything except the text
441 * This isn't necessary for all uses, so it's only done if needed.
443 protected function loadLastEdit() {
444 if ( $this->mLastRevision
!== null ) {
445 return; // already loaded
448 # New or non-existent articles have no user information
449 $id = $this->getID();
454 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
456 $this->setLastEdit( $revision );
461 * Set the latest revision
463 protected function setLastEdit( Revision
$revision ) {
464 $this->mLastRevision
= $revision;
465 $this->mTimestamp
= $revision->getTimestamp();
469 * Get the latest revision
470 * @return Revision|false
472 public function getRevision() {
473 $this->loadLastEdit();
474 if ( $this->mLastRevision
) {
475 return $this->mLastRevision
;
481 * Get the text of the current revision. No side-effects...
483 * @param $audience Integer: one of:
484 * Revision::FOR_PUBLIC to be displayed to all users
485 * Revision::FOR_THIS_USER to be displayed to $wgUser
486 * Revision::RAW get the text regardless of permissions
487 * @return String|false The text of the current revision
489 public function getText( $audience = Revision
::FOR_PUBLIC
) {
490 $this->loadLastEdit();
491 if ( $this->mLastRevision
) {
492 return $this->mLastRevision
->getText( $audience );
498 * Get the text of the current revision. No side-effects...
500 * @return String|false The text of the current revision
502 public function getRawText() {
503 $this->loadLastEdit();
504 if ( $this->mLastRevision
) {
505 return $this->mLastRevision
->getRawText();
511 * @return string MW timestamp of last article revision
513 public function getTimestamp() {
514 // Check if the field has been filled by ParserCache::get()
515 if ( !$this->mTimestamp
) {
516 $this->loadLastEdit();
518 return wfTimestamp( TS_MW
, $this->mTimestamp
);
522 * Set the page timestamp (use only to avoid DB queries)
523 * @param $ts string MW timestamp of last article revision
526 public function setTimestamp( $ts ) {
527 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
531 * @param $audience Integer: one of:
532 * Revision::FOR_PUBLIC to be displayed to all users
533 * Revision::FOR_THIS_USER to be displayed to $wgUser
534 * Revision::RAW get the text regardless of permissions
535 * @return int user ID for the user that made the last article revision
537 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
538 $this->loadLastEdit();
539 if ( $this->mLastRevision
) {
540 return $this->mLastRevision
->getUser( $audience );
547 * @param $audience Integer: one of:
548 * Revision::FOR_PUBLIC to be displayed to all users
549 * Revision::FOR_THIS_USER to be displayed to $wgUser
550 * Revision::RAW get the text regardless of permissions
551 * @return string username of the user that made the last article revision
553 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
554 $this->loadLastEdit();
555 if ( $this->mLastRevision
) {
556 return $this->mLastRevision
->getUserText( $audience );
563 * @param $audience Integer: one of:
564 * Revision::FOR_PUBLIC to be displayed to all users
565 * Revision::FOR_THIS_USER to be displayed to $wgUser
566 * Revision::RAW get the text regardless of permissions
567 * @return string Comment stored for the last article revision
569 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
570 $this->loadLastEdit();
571 if ( $this->mLastRevision
) {
572 return $this->mLastRevision
->getComment( $audience );
579 * Returns true if last revision was marked as "minor edit"
581 * @return boolean Minor edit indicator for the last article revision.
583 public function getMinorEdit() {
584 $this->loadLastEdit();
585 if ( $this->mLastRevision
) {
586 return $this->mLastRevision
->isMinor();
593 * Get a list of users who have edited this article, not including the user who made
594 * the most recent revision, which you can get from $article->getUser() if you want it
595 * @return UserArrayFromResult
597 public function getContributors() {
598 # @todo FIXME: This is expensive; cache this info somewhere.
600 $dbr = wfGetDB( DB_SLAVE
);
602 if ( $dbr->implicitGroupby() ) {
603 $realNameField = 'user_real_name';
605 $realNameField = 'FIRST(user_real_name) AS user_real_name';
608 $tables = array( 'revision', 'user' );
611 'rev_user as user_id',
612 'rev_user_text AS user_name',
614 'MAX(rev_timestamp) AS timestamp',
617 $conds = array( 'rev_page' => $this->getId() );
619 // The user who made the top revision gets credited as "this page was last edited by
620 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
621 $user = $this->getUser();
623 $conds[] = "rev_user != $user";
625 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
628 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
631 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
635 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
636 'ORDER BY' => 'timestamp DESC',
639 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
640 return new UserArrayFromResult( $res );
644 * Should the parser cache be used?
648 public function useParserCache( $oldid ) {
649 global $wgUser, $wgEnableParserCache;
651 return $wgEnableParserCache
652 && $wgUser->getStubThreshold() == 0
655 && !$this->mTitle
->isCssOrJsPage()
656 && !$this->mTitle
->isCssJsSubpage();
660 * Perform the actions of a page purging
662 public function doPurge() {
665 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
669 // Invalidate the cache
670 $this->mTitle
->invalidateCache();
674 // Commit the transaction before the purge is sent
675 $dbw = wfGetDB( DB_MASTER
);
679 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
683 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
684 if ( $this->getID() == 0 ) {
687 $text = $this->getRawText();
690 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
695 * Insert a new empty page record for this article.
696 * This *must* be followed up by creating a revision
697 * and running $this->updateRevisionOn( ... );
698 * or else the record will be left in a funky state.
699 * Best if all done inside a transaction.
701 * @param $dbw DatabaseBase
702 * @return int The newly created page_id key, or false if the title already existed
705 public function insertOn( $dbw ) {
706 wfProfileIn( __METHOD__
);
708 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
709 $dbw->insert( 'page', array(
710 'page_id' => $page_id,
711 'page_namespace' => $this->mTitle
->getNamespace(),
712 'page_title' => $this->mTitle
->getDBkey(),
714 'page_restrictions' => '',
715 'page_is_redirect' => 0, # Will set this shortly...
717 'page_random' => wfRandom(),
718 'page_touched' => $dbw->timestamp(),
719 'page_latest' => 0, # Fill this in shortly...
720 'page_len' => 0, # Fill this in shortly...
721 ), __METHOD__
, 'IGNORE' );
723 $affected = $dbw->affectedRows();
726 $newid = $dbw->insertId();
727 $this->mTitle
->resetArticleID( $newid );
729 wfProfileOut( __METHOD__
);
731 return $affected ?
$newid : false;
735 * Update the page record to point to a newly saved revision.
737 * @param $dbw DatabaseBase: object
738 * @param $revision Revision: For ID number, and text used to set
739 length and redirect status fields
740 * @param $lastRevision Integer: if given, will not overwrite the page field
741 * when different from the currently set value.
742 * Giving 0 indicates the new page flag should be set
744 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
745 * removing rows in redirect table.
746 * @return bool true on success, false on failure
749 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
750 wfProfileIn( __METHOD__
);
752 $text = $revision->getText();
753 $rt = Title
::newFromRedirectRecurse( $text );
755 $conditions = array( 'page_id' => $this->getId() );
757 if ( !is_null( $lastRevision ) ) {
758 # An extra check against threads stepping on each other
759 $conditions['page_latest'] = $lastRevision;
762 $dbw->update( 'page',
764 'page_latest' => $revision->getId(),
765 'page_touched' => $dbw->timestamp(),
766 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
767 'page_is_redirect' => $rt !== null ?
1 : 0,
768 'page_len' => strlen( $text ),
773 $result = $dbw->affectedRows() != 0;
775 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
778 wfProfileOut( __METHOD__
);
783 * Add row to the redirect table if this is a redirect, remove otherwise.
785 * @param $dbw DatabaseBase
786 * @param $redirectTitle Title object pointing to the redirect target,
787 * or NULL if this is not a redirect
788 * @param $lastRevIsRedirect If given, will optimize adding and
789 * removing rows in redirect table.
790 * @return bool true on success, false on failure
793 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
794 // Always update redirects (target link might have changed)
795 // Update/Insert if we don't know if the last revision was a redirect or not
796 // Delete if changing from redirect to non-redirect
797 $isRedirect = !is_null( $redirectTitle );
799 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
803 wfProfileIn( __METHOD__
);
805 $this->insertRedirectEntry( $redirectTitle );
807 // This is not a redirect, remove row from redirect table
808 $where = array( 'rd_from' => $this->getId() );
809 $dbw->delete( 'redirect', $where, __METHOD__
);
812 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
813 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
815 wfProfileOut( __METHOD__
);
817 return ( $dbw->affectedRows() != 0 );
821 * If the given revision is newer than the currently set page_latest,
822 * update the page record. Otherwise, do nothing.
824 * @param $dbw Database object
825 * @param $revision Revision object
828 public function updateIfNewerOn( $dbw, $revision ) {
829 wfProfileIn( __METHOD__
);
831 $row = $dbw->selectRow(
832 array( 'revision', 'page' ),
833 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
835 'page_id' => $this->getId(),
836 'page_latest=rev_id' ),
840 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
841 wfProfileOut( __METHOD__
);
844 $prev = $row->rev_id
;
845 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
847 # No or missing previous revision; mark the page as new
849 $lastRevIsRedirect = null;
852 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
854 wfProfileOut( __METHOD__
);
859 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
860 * @param $text String: new text of the section
861 * @param $summary String: new section's subject, only if $section is 'new'
862 * @param $edittime String: revision timestamp or null to use the current revision
863 * @return string Complete article text, or null if error
865 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
866 wfProfileIn( __METHOD__
);
868 if ( strval( $section ) == '' ) {
869 // Whole-page edit; let the whole text through
871 if ( is_null( $edittime ) ) {
872 $rev = Revision
::newFromTitle( $this->mTitle
);
874 $dbw = wfGetDB( DB_MASTER
);
875 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
879 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
880 $this->getId() . "; section: $section; edittime: $edittime)\n" );
881 wfProfileOut( __METHOD__
);
885 $oldtext = $rev->getText();
887 if ( $section == 'new' ) {
888 # Inserting a new section
889 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
890 $text = strlen( trim( $oldtext ) ) > 0
891 ?
"{$oldtext}\n\n{$subject}{$text}"
892 : "{$subject}{$text}";
894 # Replacing an existing section; roll out the big guns
897 $text = $wgParser->replaceSection( $oldtext, $section, $text );
901 wfProfileOut( __METHOD__
);
906 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
908 * @return Int updated $flags
910 function checkFlags( $flags ) {
911 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
912 if ( $this->mTitle
->getArticleID() ) {
913 $flags |
= EDIT_UPDATE
;
923 * Change an existing article or create a new article. Updates RC and all necessary caches,
924 * optionally via the deferred update array.
926 * $wgUser must be set before calling this function.
928 * @param $text String: new text
929 * @param $summary String: edit summary
930 * @param $flags Integer bitfield:
932 * Article is known or assumed to be non-existent, create a new one
934 * Article is known or assumed to be pre-existing, update it
936 * Mark this edit minor, if the user is allowed to do so
938 * Do not log the change in recentchanges
940 * Mark the edit a "bot" edit regardless of user rights
942 * Defer some of the updates until the end of index.php
944 * Fill in blank summaries with generated text where possible
946 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
947 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
948 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
949 * edit-already-exists error will be returned. These two conditions are also possible with
950 * auto-detection due to MediaWiki's performance-optimised locking strategy.
952 * @param $baseRevId the revision ID this edit was based off, if any
953 * @param $user User (optional), $wgUser will be used if not passed
955 * @return Status object. Possible errors:
956 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
957 * edit-gone-missing: In update mode, but the article didn't exist
958 * edit-conflict: In update mode, the article changed unexpectedly
959 * edit-no-change: Warning that the text was the same as before
960 * edit-already-exists: In creation mode, but the article already exists
962 * Extensions may define additional errors.
964 * $return->value will contain an associative array with members as follows:
965 * new: Boolean indicating if the function attempted to create a new article
966 * revision: The revision object for the inserted revision, or null
968 * Compatibility note: this function previously returned a boolean value indicating success/failure
970 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
971 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
973 # Low-level sanity check
974 if ( $this->mTitle
->getText() === '' ) {
975 throw new MWException( 'Something is trying to edit an article with an empty title' );
978 wfProfileIn( __METHOD__
);
980 $user = is_null( $user ) ?
$wgUser : $user;
981 $status = Status
::newGood( array() );
983 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
984 $this->loadPageData();
986 $flags = $this->checkFlags( $flags );
988 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
989 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
991 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
993 if ( $status->isOK() ) {
994 $status->fatal( 'edit-hook-aborted' );
997 wfProfileOut( __METHOD__
);
1001 # Silently ignore EDIT_MINOR if not allowed
1002 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1003 $bot = $flags & EDIT_FORCE_BOT
;
1005 $oldtext = $this->getRawText(); // current revision
1006 $oldsize = strlen( $oldtext );
1008 # Provide autosummaries if one is not provided and autosummaries are enabled.
1009 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1010 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1013 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1014 $text = $editInfo->pst
;
1015 $newsize = strlen( $text );
1017 $dbw = wfGetDB( DB_MASTER
);
1018 $now = wfTimestampNow();
1019 $this->mTimestamp
= $now;
1021 if ( $flags & EDIT_UPDATE
) {
1022 # Update article, but only if changed.
1023 $status->value
['new'] = false;
1025 # Make sure the revision is either completely inserted or not inserted at all
1026 if ( !$wgDBtransactions ) {
1027 $userAbort = ignore_user_abort( true );
1030 $changed = ( strcmp( $text, $oldtext ) != 0 );
1033 if ( !$this->mLatest
) {
1034 # Article gone missing
1035 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1036 $status->fatal( 'edit-gone-missing' );
1038 wfProfileOut( __METHOD__
);
1042 $revision = new Revision( array(
1043 'page' => $this->getId(),
1044 'comment' => $summary,
1045 'minor_edit' => $isminor,
1047 'parent_id' => $this->mLatest
,
1048 'user' => $user->getId(),
1049 'user_text' => $user->getName(),
1054 $revisionId = $revision->insertOn( $dbw );
1058 # Note that we use $this->mLatest instead of fetching a value from the master DB
1059 # during the course of this function. This makes sure that EditPage can detect
1060 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1061 # before this function is called. A previous function used a separate query, this
1062 # creates a window where concurrent edits can cause an ignored edit conflict.
1063 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1066 /* Belated edit conflict! Run away!! */
1067 $status->fatal( 'edit-conflict' );
1069 # Delete the invalid revision if the DB is not transactional
1070 if ( !$wgDBtransactions ) {
1071 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1077 global $wgUseRCPatrol;
1078 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1079 # Update recentchanges
1080 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1081 # Mark as patrolled if the user can do so
1082 $patrolled = $wgUseRCPatrol && !count(
1083 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1084 # Add RC row to the DB
1085 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1086 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1087 $revisionId, $patrolled
1090 # Log auto-patrolled edits
1092 PatrolLog
::record( $rc, true );
1095 $user->incEditCount();
1099 $status->warning( 'edit-no-change' );
1101 // Keep the same revision ID, but do some updates on it
1102 $revisionId = $this->getLatest();
1103 // Update page_touched, this is usually implicit in the page update
1104 // Other cache updates are done in onArticleEdit()
1105 $this->mTitle
->invalidateCache();
1108 if ( !$wgDBtransactions ) {
1109 ignore_user_abort( $userAbort );
1112 // Now that ignore_user_abort is restored, we can respond to fatal errors
1113 if ( !$status->isOK() ) {
1114 wfProfileOut( __METHOD__
);
1118 # Invalidate cache of this article and all pages using this article
1119 # as a template. Partly deferred.
1120 self
::onArticleEdit( $this->mTitle
);
1121 # Update links tables, site stats, etc.
1122 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
1124 # Create new article
1125 $status->value
['new'] = true;
1129 # Add the page record; stake our claim on this title!
1130 # This will return false if the article already exists
1131 $newid = $this->insertOn( $dbw );
1133 if ( $newid === false ) {
1135 $status->fatal( 'edit-already-exists' );
1137 wfProfileOut( __METHOD__
);
1141 # Save the revision text...
1142 $revision = new Revision( array(
1144 'comment' => $summary,
1145 'minor_edit' => $isminor,
1147 'user' => $user->getId(),
1148 'user_text' => $user->getName(),
1151 $revisionId = $revision->insertOn( $dbw );
1153 $this->mTitle
->resetArticleID( $newid );
1154 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
1156 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
1158 # Update the page record with revision data
1159 $this->updateRevisionOn( $dbw, $revision, 0 );
1161 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1163 # Update recentchanges
1164 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1165 global $wgUseRCPatrol, $wgUseNPPatrol;
1167 # Mark as patrolled if the user can do so
1168 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1169 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1170 # Add RC row to the DB
1171 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1172 '', strlen( $text ), $revisionId, $patrolled );
1174 # Log auto-patrolled edits
1176 PatrolLog
::record( $rc, true );
1179 $user->incEditCount();
1182 # Update links, etc.
1183 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user, true );
1186 self
::onArticleCreate( $this->mTitle
);
1188 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1189 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1192 # Do updates right now unless deferral was requested
1193 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1197 // Return the new revision (or null) to the caller
1198 $status->value
['revision'] = $revision;
1200 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1201 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1203 # Promote user to any groups they meet the criteria for
1204 $user->addAutopromoteOnceGroups( 'onEdit' );
1206 wfProfileOut( __METHOD__
);
1211 * Update the article's restriction field, and leave a log entry.
1213 * @param $limit Array: set of restriction keys
1214 * @param $reason String
1215 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1216 * @param $expiry Array: per restriction type expiration
1217 * @return bool true on success
1219 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1220 global $wgUser, $wgContLang;
1222 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1224 $id = $this->mTitle
->getArticleID();
1227 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1231 if ( wfReadOnly() ) {
1232 wfDebug( "updateRestrictions failed: read-only\n" );
1236 if ( !$this->mTitle
->userCan( 'protect' ) ) {
1237 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1245 // Take this opportunity to purge out expired restrictions
1246 Title
::purgeExpiredRestrictions();
1248 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1249 # we expect a single selection, but the schema allows otherwise.
1251 $updated = self
::flattenRestrictions( $limit );
1254 foreach ( $restrictionTypes as $action ) {
1255 if ( isset( $expiry[$action] ) ) {
1256 # Get current restrictions on $action
1257 $aLimits = $this->mTitle
->getRestrictions( $action );
1258 $current[$action] = implode( '', $aLimits );
1259 # Are any actual restrictions being dealt with here?
1260 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
1262 # If something changed, we need to log it. Checking $aRChanged
1263 # assures that "unprotecting" a page that is not protected does
1264 # not log just because the expiry was "changed".
1265 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
1271 $current = self
::flattenRestrictions( $current );
1273 $changed = ( $changed ||
$current != $updated );
1274 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
1275 $protect = ( $updated != '' );
1277 # If nothing's changed, do nothing
1279 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1280 $dbw = wfGetDB( DB_MASTER
);
1282 # Prepare a null revision to be added to the history
1283 $modified = $current != '' && $protect;
1286 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1288 $comment_type = 'unprotectedarticle';
1291 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1293 # Only restrictions with the 'protect' right can cascade...
1294 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1295 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1297 # The schema allows multiple restrictions
1298 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1302 $cascade_description = '';
1305 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1309 $comment .= ": $reason";
1312 $editComment = $comment;
1313 $encodedExpiry = array();
1314 $protect_description = '';
1315 foreach ( $limit as $action => $restrictions ) {
1316 if ( !isset( $expiry[$action] ) )
1317 $expiry[$action] = $dbw->getInfinity();
1319 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1320 if ( $restrictions != '' ) {
1321 $protect_description .= "[$action=$restrictions] (";
1322 if ( $encodedExpiry[$action] != 'infinity' ) {
1323 $protect_description .= wfMsgForContent( 'protect-expiring',
1324 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1325 $wgContLang->date( $expiry[$action], false, false ) ,
1326 $wgContLang->time( $expiry[$action], false, false ) );
1328 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1331 $protect_description .= ') ';
1334 $protect_description = trim( $protect_description );
1336 if ( $protect_description && $protect ) {
1337 $editComment .= " ($protect_description)";
1341 $editComment .= "$cascade_description";
1344 # Update restrictions table
1345 foreach ( $limit as $action => $restrictions ) {
1346 if ( $restrictions != '' ) {
1347 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1348 array( 'pr_page' => $id,
1349 'pr_type' => $action,
1350 'pr_level' => $restrictions,
1351 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1352 'pr_expiry' => $encodedExpiry[$action]
1357 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1358 'pr_type' => $action ), __METHOD__
);
1362 # Insert a null revision
1363 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1364 $nullRevId = $nullRevision->insertOn( $dbw );
1366 $latest = $this->getLatest();
1367 # Update page record
1368 $dbw->update( 'page',
1370 'page_touched' => $dbw->timestamp(),
1371 'page_restrictions' => '',
1372 'page_latest' => $nullRevId
1373 ), array( /* WHERE */
1378 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
1379 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1381 # Update the protection log
1382 $log = new LogPage( 'protect' );
1384 $params = array( $protect_description, $cascade ?
'cascade' : '' );
1385 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
1387 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1390 } # End "changed" check
1396 * Take an array of page restrictions and flatten it to a string
1397 * suitable for insertion into the page_restrictions field.
1398 * @param $limit Array
1401 protected static function flattenRestrictions( $limit ) {
1402 if ( !is_array( $limit ) ) {
1403 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1409 foreach ( $limit as $action => $restrictions ) {
1410 if ( $restrictions != '' ) {
1411 $bits[] = "$action=$restrictions";
1415 return implode( ':', $bits );
1419 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1421 public function isBigDeletion() {
1422 global $wgDeleteRevisionsLimit;
1424 if ( $wgDeleteRevisionsLimit ) {
1425 $revCount = $this->estimateRevisionCount();
1427 return $revCount > $wgDeleteRevisionsLimit;
1434 * @return int approximate revision count
1436 public function estimateRevisionCount() {
1437 $dbr = wfGetDB( DB_SLAVE
);
1439 // For an exact count...
1440 // return $dbr->selectField( 'revision', 'COUNT(*)',
1441 // array( 'rev_page' => $this->getId() ), __METHOD__ );
1442 return $dbr->estimateRowCount( 'revision', '*',
1443 array( 'rev_page' => $this->getId() ), __METHOD__
);
1447 * Get the last N authors
1448 * @param $num Integer: number of revisions to get
1449 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1450 * @return array Array of authors, duplicates not removed
1452 public function getLastNAuthors( $num, $revLatest = 0 ) {
1453 wfProfileIn( __METHOD__
);
1454 // First try the slave
1455 // If that doesn't have the latest revision, try the master
1457 $db = wfGetDB( DB_SLAVE
);
1460 $res = $db->select( array( 'page', 'revision' ),
1461 array( 'rev_id', 'rev_user_text' ),
1463 'page_namespace' => $this->mTitle
->getNamespace(),
1464 'page_title' => $this->mTitle
->getDBkey(),
1465 'rev_page = page_id'
1468 'ORDER BY' => 'rev_timestamp DESC',
1474 wfProfileOut( __METHOD__
);
1478 $row = $db->fetchObject( $res );
1480 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1481 $db = wfGetDB( DB_MASTER
);
1486 } while ( $continue );
1488 $authors = array( $row->rev_user_text
);
1490 foreach ( $res as $row ) {
1491 $authors[] = $row->rev_user_text
;
1494 wfProfileOut( __METHOD__
);
1499 * Back-end article deletion
1500 * Deletes the article with database consistency, writes logs, purges caches
1502 * @param $reason string delete reason for deletion log
1503 * @param suppress bitfield
1504 * Revision::DELETED_TEXT
1505 * Revision::DELETED_COMMENT
1506 * Revision::DELETED_USER
1507 * Revision::DELETED_RESTRICTED
1508 * @param $id int article ID
1509 * @param $commit boolean defaults to true, triggers transaction end
1510 * @return boolean true if successful
1512 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
1513 global $wgDeferredUpdateList, $wgUseTrackbacks;
1516 wfDebug( __METHOD__
. "\n" );
1518 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
1521 $dbw = wfGetDB( DB_MASTER
);
1522 $t = $this->mTitle
->getDBkey();
1523 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1525 if ( $t === '' ||
$id == 0 ) {
1529 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
1530 array_push( $wgDeferredUpdateList, $u );
1532 // Bitfields to further suppress the content
1535 // This should be 15...
1536 $bitfield |
= Revision
::DELETED_TEXT
;
1537 $bitfield |
= Revision
::DELETED_COMMENT
;
1538 $bitfield |
= Revision
::DELETED_USER
;
1539 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1541 $bitfield = 'rev_deleted';
1545 // For now, shunt the revision data into the archive table.
1546 // Text is *not* removed from the text table; bulk storage
1547 // is left intact to avoid breaking block-compression or
1548 // immutable storage schemes.
1550 // For backwards compatibility, note that some older archive
1551 // table entries will have ar_text and ar_flags fields still.
1553 // In the future, we may keep revisions and mark them with
1554 // the rev_deleted field, which is reserved for this purpose.
1555 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1557 'ar_namespace' => 'page_namespace',
1558 'ar_title' => 'page_title',
1559 'ar_comment' => 'rev_comment',
1560 'ar_user' => 'rev_user',
1561 'ar_user_text' => 'rev_user_text',
1562 'ar_timestamp' => 'rev_timestamp',
1563 'ar_minor_edit' => 'rev_minor_edit',
1564 'ar_rev_id' => 'rev_id',
1565 'ar_text_id' => 'rev_text_id',
1566 'ar_text' => '\'\'', // Be explicit to appease
1567 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1568 'ar_len' => 'rev_len',
1569 'ar_page_id' => 'page_id',
1570 'ar_deleted' => $bitfield
1573 'page_id = rev_page'
1577 # Delete restrictions for it
1578 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1580 # Now that it's safely backed up, delete it
1581 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1582 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1589 # Fix category table counts
1591 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1593 foreach ( $res as $row ) {
1594 $cats [] = $row->cl_to
;
1597 $this->updateCategoryCounts( array(), $cats );
1599 # If using cascading deletes, we can skip some explicit deletes
1600 if ( !$dbw->cascadingDeletes() ) {
1601 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
1603 if ( $wgUseTrackbacks )
1604 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
1606 # Delete outgoing links
1607 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1608 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1609 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1610 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1611 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1612 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1613 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
1614 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
1617 # If using cleanup triggers, we can skip some manual deletes
1618 if ( !$dbw->cleanupTriggers() ) {
1619 # Clean up recentchanges entries...
1620 $dbw->delete( 'recentchanges',
1621 array( 'rc_type != ' . RC_LOG
,
1622 'rc_namespace' => $this->mTitle
->getNamespace(),
1623 'rc_title' => $this->mTitle
->getDBkey() ),
1625 $dbw->delete( 'recentchanges',
1626 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
1631 self
::onArticleDelete( $this->mTitle
);
1633 # Clear the cached article id so the interface doesn't act like we exist
1634 $this->mTitle
->resetArticleID( 0 );
1636 # Log the deletion, if the page was suppressed, log it at Oversight instead
1637 $logtype = $suppress ?
'suppress' : 'delete';
1638 $log = new LogPage( $logtype );
1640 # Make sure logging got through
1641 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
1647 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
1652 * Roll back the most recent consecutive set of edits to a page
1653 * from the same user; fails if there are no eligible edits to
1654 * roll back to, e.g. user is the sole contributor. This function
1655 * performs permissions checks on $wgUser, then calls commitRollback()
1656 * to do the dirty work
1658 * @param $fromP String: Name of the user whose edits to rollback.
1659 * @param $summary String: Custom summary. Set to default summary if empty.
1660 * @param $token String: Rollback token.
1661 * @param $bot Boolean: If true, mark all reverted edits as bot.
1663 * @param $resultDetails Array: contains result-specific array of additional values
1664 * 'alreadyrolled' : 'current' (rev)
1665 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1667 * @return array of errors, each error formatted as
1668 * array(messagekey, param1, param2, ...).
1669 * On success, the array is empty. This array can also be passed to
1670 * OutputPage::showPermissionsErrorPage().
1672 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
1675 $resultDetails = null;
1678 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
1679 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser );
1680 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1682 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
1683 $errors[] = array( 'sessionfailure' );
1686 if ( $wgUser->pingLimiter( 'rollback' ) ||
$wgUser->pingLimiter() ) {
1687 $errors[] = array( 'actionthrottledtext' );
1690 # If there were errors, bail out now
1691 if ( !empty( $errors ) ) {
1695 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
1699 * Backend implementation of doRollback(), please refer there for parameter
1700 * and return value documentation
1702 * NOTE: This function does NOT check ANY permissions, it just commits the
1703 * rollback to the DB Therefore, you should only call this function direct-
1704 * ly if you want to use custom permissions checks. If you don't, use
1705 * doRollback() instead.
1707 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
1708 global $wgUseRCPatrol, $wgUser, $wgContLang;
1710 $dbw = wfGetDB( DB_MASTER
);
1712 if ( wfReadOnly() ) {
1713 return array( array( 'readonlytext' ) );
1716 # Get the last editor
1717 $current = Revision
::newFromTitle( $this->mTitle
);
1718 if ( is_null( $current ) ) {
1719 # Something wrong... no page?
1720 return array( array( 'notanarticle' ) );
1723 $from = str_replace( '_', ' ', $fromP );
1724 # User name given should match up with the top revision.
1725 # If the user was deleted then $from should be empty.
1726 if ( $from != $current->getUserText() ) {
1727 $resultDetails = array( 'current' => $current );
1728 return array( array( 'alreadyrolled',
1729 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
1730 htmlspecialchars( $fromP ),
1731 htmlspecialchars( $current->getUserText() )
1735 # Get the last edit not by this guy...
1736 # Note: these may not be public values
1737 $user = intval( $current->getRawUser() );
1738 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1739 $s = $dbw->selectRow( 'revision',
1740 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1741 array( 'rev_page' => $current->getPage(),
1742 "rev_user != {$user} OR rev_user_text != {$user_text}"
1744 array( 'USE INDEX' => 'page_timestamp',
1745 'ORDER BY' => 'rev_timestamp DESC' )
1747 if ( $s === false ) {
1748 # No one else ever edited this page
1749 return array( array( 'cantrollback' ) );
1750 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
1751 # Only admins can see this text
1752 return array( array( 'notvisiblerev' ) );
1756 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
1757 # Mark all reverted edits as bot
1761 if ( $wgUseRCPatrol ) {
1762 # Mark all reverted edits as patrolled
1763 $set['rc_patrolled'] = 1;
1766 if ( count( $set ) ) {
1767 $dbw->update( 'recentchanges', $set,
1769 'rc_cur_id' => $current->getPage(),
1770 'rc_user_text' => $current->getUserText(),
1771 "rc_timestamp > '{$s->rev_timestamp}'",
1776 # Generate the edit summary if necessary
1777 $target = Revision
::newFromId( $s->rev_id
);
1778 if ( empty( $summary ) ) {
1779 if ( $from == '' ) { // no public user name
1780 $summary = wfMsgForContent( 'revertpage-nouser' );
1782 $summary = wfMsgForContent( 'revertpage' );
1786 # Allow the custom summary to use the same args as the default message
1788 $target->getUserText(), $from, $s->rev_id
,
1789 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
1790 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1792 $summary = wfMsgReplaceArgs( $summary, $args );
1795 $flags = EDIT_UPDATE
;
1797 if ( $wgUser->isAllowed( 'minoredit' ) ) {
1798 $flags |
= EDIT_MINOR
;
1801 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1802 $flags |
= EDIT_FORCE_BOT
;
1805 # Actually store the edit
1806 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1807 if ( !empty( $status->value
['revision'] ) ) {
1808 $revId = $status->value
['revision']->getId();
1813 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
1815 $resultDetails = array(
1816 'summary' => $summary,
1817 'current' => $current,
1818 'target' => $target,
1826 * Do standard deferred updates after page view
1828 public function viewUpdates() {
1829 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
1830 if ( wfReadOnly() ) {
1834 # Don't update page view counters on views from bot users (bug 14044)
1835 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
1836 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
1837 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
1840 # Update newtalk / watchlist notification status
1841 $wgUser->clearNotification( $this->mTitle
);
1845 * Prepare text which is about to be saved.
1846 * Returns a stdclass with source, pst and output members
1848 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1849 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid ) {
1851 return $this->mPreparedEdit
;
1856 if( $user === null ) {
1860 $popts = ParserOptions
::newFromUser( $user );
1861 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1863 $edit = (object)array();
1864 $edit->revid
= $revid;
1865 $edit->newText
= $text;
1866 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
1867 $edit->popts
= $this->getParserOptions( true );
1868 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1869 $edit->oldText
= $this->getRawText();
1871 $this->mPreparedEdit
= $edit;
1877 * Do standard deferred updates after page edit.
1878 * Update links tables, site stats, search index and message cache.
1879 * Purges pages that include this page if the text was changed here.
1880 * Every 100th edit, prune the recent changes table.
1883 * @param $text String: New text of the article
1884 * @param $summary String: Edit summary
1885 * @param $minoredit Boolean: Minor edit
1886 * @param $timestamp_of_pagechange String timestamp associated with the page change
1887 * @param $newid Integer: rev_id value of the new revision
1888 * @param $changed Boolean: Whether or not the content actually changed
1889 * @param $user User object: User doing the edit
1890 * @param $created Boolean: Whether the edit created the page
1892 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
1893 $changed = true, User
$user = null, $created = false )
1895 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
1897 wfProfileIn( __METHOD__
);
1900 # Be careful not to double-PST: $text is usually already PST-ed once
1901 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1902 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1903 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
1905 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1906 $editInfo = $this->mPreparedEdit
;
1909 # Save it to the parser cache
1910 if ( $wgEnableParserCache ) {
1911 $parserCache = ParserCache
::singleton();
1912 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1915 # Update the links tables
1916 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1919 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
1921 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1922 if ( 0 == mt_rand( 0, 99 ) ) {
1923 // Flush old entries from the `recentchanges` table; we do this on
1924 // random requests so as to avoid an increase in writes for no good reason
1927 $dbw = wfGetDB( DB_MASTER
);
1928 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1931 array( "rc_timestamp < '$cutoff'" ),
1937 $id = $this->getID();
1938 $title = $this->mTitle
->getPrefixedDBkey();
1939 $shortTitle = $this->mTitle
->getDBkey();
1942 wfProfileOut( __METHOD__
);
1949 } elseif ( $created ) {
1950 $good = (int)$this->isCountable( $editInfo );
1953 $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
1957 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
1958 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
1960 # If this is another user's talk page, update newtalk
1961 # Don't do this if $changed = false otherwise some idiot can null-edit a
1962 # load of user talk pages and piss people off, nor if it's a minor edit
1963 # by a properly-flagged bot.
1964 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
1965 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
1967 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1968 $other = User
::newFromName( $shortTitle, false );
1970 wfDebug( __METHOD__
. ": invalid username\n" );
1971 } elseif ( User
::isIP( $shortTitle ) ) {
1972 // An anonymous user
1973 $other->setNewtalk( true );
1974 } elseif ( $other->isLoggedIn() ) {
1975 $other->setNewtalk( true );
1977 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1982 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1983 MessageCache
::singleton()->replace( $shortTitle, $text );
1986 wfProfileOut( __METHOD__
);
1990 * Perform article updates on a special page creation.
1992 * @param $rev Revision object
1994 * @todo This is a shitty interface function. Kill it and replace the
1995 * other shitty functions like editUpdates and such so it's not needed
1998 public function createUpdates( $rev ) {
1999 $this->editUpdates( $rev->getText(), $rev->getComment(),
2000 $rev->isMinor(), wfTimestamp(), $rev->getId(), true, null, true );
2004 * This function is called right before saving the wikitext,
2005 * so we can do things like signatures and links-in-context.
2007 * @param $text String article contents
2008 * @param $user User object: user doing the edit, $wgUser will be used if
2010 * @param $popts ParserOptions object: parser options, default options for
2011 * the user loaded if null given
2012 * @return string article contents with altered wikitext markup (signatures
2013 * converted, {{subst:}}, templates, etc.)
2015 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2018 if ( $user === null ) {
2023 if ( $popts === null ) {
2024 $popts = ParserOptions
::newFromUser( $user );
2027 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2031 * Loads page_touched and returns a value indicating if it should be used
2032 * @return boolean true if not a redirect
2034 public function checkTouched() {
2035 if ( !$this->mDataLoaded
) {
2036 $this->loadPageData();
2039 return !$this->mIsRedirect
;
2043 * Get the page_touched field
2044 * @return string containing GMT timestamp
2046 public function getTouched() {
2047 if ( !$this->mDataLoaded
) {
2048 $this->loadPageData();
2051 return $this->mTouched
;
2055 * Get the page_latest field
2056 * @return integer rev_id of current revision
2058 public function getLatest() {
2059 if ( !$this->mDataLoaded
) {
2060 $this->loadPageData();
2063 return (int)$this->mLatest
;
2067 * Edit an article without doing all that other stuff
2068 * The article must already exist; link tables etc
2069 * are not updated, caches are not flushed.
2071 * @param $text String: text submitted
2072 * @param $comment String: comment submitted
2073 * @param $minor Boolean: whereas it's a minor modification
2075 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2076 wfProfileIn( __METHOD__
);
2078 $dbw = wfGetDB( DB_MASTER
);
2079 $revision = new Revision( array(
2080 'page' => $this->getId(),
2082 'comment' => $comment,
2083 'minor_edit' => $minor ?
1 : 0,
2085 $revision->insertOn( $dbw );
2086 $this->updateRevisionOn( $dbw, $revision );
2089 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
2091 wfProfileOut( __METHOD__
);
2095 * The onArticle*() functions are supposed to be a kind of hooks
2096 * which should be called whenever any of the specified actions
2099 * This is a good place to put code to clear caches, for instance.
2101 * This is called on page move and undelete, as well as edit
2103 * @param $title Title object
2105 public static function onArticleCreate( $title ) {
2106 # Update existence markers on article/talk tabs...
2107 if ( $title->isTalkPage() ) {
2108 $other = $title->getSubjectPage();
2110 $other = $title->getTalkPage();
2113 $other->invalidateCache();
2114 $other->purgeSquid();
2116 $title->touchLinks();
2117 $title->purgeSquid();
2118 $title->deleteTitleProtection();
2122 * Clears caches when article is deleted
2124 * @param $title Title
2126 public static function onArticleDelete( $title ) {
2127 # Update existence markers on article/talk tabs...
2128 if ( $title->isTalkPage() ) {
2129 $other = $title->getSubjectPage();
2131 $other = $title->getTalkPage();
2134 $other->invalidateCache();
2135 $other->purgeSquid();
2137 $title->touchLinks();
2138 $title->purgeSquid();
2141 HTMLFileCache
::clearFileCache( $title );
2144 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2145 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2149 if ( $title->getNamespace() == NS_FILE
) {
2150 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2151 $update->doUpdate();
2155 if ( $title->getNamespace() == NS_USER_TALK
) {
2156 $user = User
::newFromName( $title->getText(), false );
2157 $user->setNewtalk( false );
2161 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2165 * Purge caches on page update etc
2167 * @param $title Title object
2168 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2170 public static function onArticleEdit( $title ) {
2171 global $wgDeferredUpdateList;
2173 // Invalidate caches of articles which include this page
2174 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
2176 // Invalidate the caches of all pages which redirect here
2177 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
2179 # Purge squid for this page only
2180 $title->purgeSquid();
2182 # Clear file cache for this page only
2183 HTMLFileCache
::clearFileCache( $title );
2189 * Return a list of templates used by this article.
2190 * Uses the templatelinks table
2192 * @return Array of Title objects
2194 public function getUsedTemplates() {
2196 $id = $this->mTitle
->getArticleID();
2202 $dbr = wfGetDB( DB_SLAVE
);
2203 $res = $dbr->select( array( 'templatelinks' ),
2204 array( 'tl_namespace', 'tl_title' ),
2205 array( 'tl_from' => $id ),
2208 if ( $res !== false ) {
2209 foreach ( $res as $row ) {
2210 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2218 * Returns a list of hidden categories this page is a member of.
2219 * Uses the page_props and categorylinks tables.
2221 * @return Array of Title objects
2223 public function getHiddenCategories() {
2225 $id = $this->mTitle
->getArticleID();
2231 $dbr = wfGetDB( DB_SLAVE
);
2232 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2234 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2235 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2238 if ( $res !== false ) {
2239 foreach ( $res as $row ) {
2240 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2248 * Return an applicable autosummary if one exists for the given edit.
2249 * @param $oldtext String: the previous text of the page.
2250 * @param $newtext String: The submitted text of the page.
2251 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2252 * @return string An appropriate autosummary, or an empty string.
2254 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2257 # Decide what kind of autosummary is needed.
2259 # Redirect autosummaries
2260 $ot = Title
::newFromRedirect( $oldtext );
2261 $rt = Title
::newFromRedirect( $newtext );
2263 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2264 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2267 # New page autosummaries
2268 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2269 # If they're making a new article, give its text, truncated, in the summary.
2271 $truncatedtext = $wgContLang->truncate(
2272 str_replace( "\n", ' ', $newtext ),
2273 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2275 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2278 # Blanking autosummaries
2279 if ( $oldtext != '' && $newtext == '' ) {
2280 return wfMsgForContent( 'autosumm-blank' );
2281 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2282 # Removing more than 90% of the article
2284 $truncatedtext = $wgContLang->truncate(
2286 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2288 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2291 # If we reach this point, there's no applicable autosummary for our case, so our
2292 # autosummary is empty.
2297 * Get parser options suitable for rendering the primary article wikitext
2298 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
2299 * @return mixed ParserOptions object or boolean false
2301 public function getParserOptions( $canonical = false ) {
2302 global $wgUser, $wgLanguageCode;
2304 if ( !$this->mParserOptions ||
$canonical ) {
2305 $user = !$canonical ?
$wgUser : new User
;
2306 $parserOptions = new ParserOptions( $user );
2307 $parserOptions->setTidy( true );
2308 $parserOptions->enableLimitReport();
2311 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
2312 return $parserOptions;
2314 $this->mParserOptions
= $parserOptions;
2316 // Clone to allow modifications of the return value without affecting cache
2317 return clone $this->mParserOptions
;
2321 * Get parser options suitable for rendering the primary article wikitext
2323 * @return ParserOptions
2325 public function makeParserOptions( User
$user ) {
2326 $options = ParserOptions
::newFromUser( $user );
2327 $options->enableLimitReport(); // show inclusion/loop reports
2328 $options->setTidy( true ); // fix bad HTML
2333 * Update all the appropriate counts in the category table, given that
2334 * we've added the categories $added and deleted the categories $deleted.
2336 * @param $added array The names of categories that were added
2337 * @param $deleted array The names of categories that were deleted
2339 public function updateCategoryCounts( $added, $deleted ) {
2340 $ns = $this->mTitle
->getNamespace();
2341 $dbw = wfGetDB( DB_MASTER
);
2343 # First make sure the rows exist. If one of the "deleted" ones didn't
2344 # exist, we might legitimately not create it, but it's simpler to just
2345 # create it and then give it a negative value, since the value is bogus
2348 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2349 $insertCats = array_merge( $added, $deleted );
2350 if ( !$insertCats ) {
2351 # Okay, nothing to do
2355 $insertRows = array();
2357 foreach ( $insertCats as $cat ) {
2358 $insertRows[] = array(
2359 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2363 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2365 $addFields = array( 'cat_pages = cat_pages + 1' );
2366 $removeFields = array( 'cat_pages = cat_pages - 1' );
2368 if ( $ns == NS_CATEGORY
) {
2369 $addFields[] = 'cat_subcats = cat_subcats + 1';
2370 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2371 } elseif ( $ns == NS_FILE
) {
2372 $addFields[] = 'cat_files = cat_files + 1';
2373 $removeFields[] = 'cat_files = cat_files - 1';
2380 array( 'cat_title' => $added ),
2389 array( 'cat_title' => $deleted ),
2396 * Lightweight method to get the parser output for a page, checking the parser cache
2397 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
2398 * consider, so it's not appropriate to use there.
2400 * @since 1.16 (r52326) for LiquidThreads
2402 * @param $oldid mixed integer Revision ID or null
2403 * @return ParserOutput or false if the given revsion ID is not found
2405 public function getParserOutput( $oldid = null ) {
2406 global $wgEnableParserCache, $wgUser;
2408 // Should the parser cache be used?
2409 $useParserCache = $wgEnableParserCache &&
2410 $wgUser->getStubThreshold() == 0 &&
2414 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
2416 if ( $wgUser->getStubThreshold() ) {
2417 wfIncrStats( 'pcache_miss_stub' );
2420 if ( $useParserCache ) {
2421 $parserOutput = ParserCache
::singleton()->get( $this, $this->getParserOptions() );
2422 if ( $parserOutput !== false ) {
2423 return $parserOutput;
2427 // Cache miss; parse and output it.
2428 if ( $oldid === null ) {
2429 $text = $this->getRawText();
2431 $rev = Revision
::newFromTitle( $this->getTitle(), $oldid );
2432 if ( $rev === null ) {
2435 $text = $rev->getText();
2438 return $this->getOutputFromWikitext( $text, $useParserCache );