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
{
18 * Fields are public for backwards-compatibility. Use accessors.
19 * In the past, this class was part of Article.php and everything was public.
21 public $mTitle = null; // !< Title object
22 public $mCounter = -1; // !< Not loaded
23 public $mDataLoaded = false; // !<
24 public $mIsRedirect = false; // !<
25 public $mLatest = false; // !<
26 public $mPreparedEdit = false; // !<
27 public $mRedirectTarget = null; // !< Title object
28 public $mLastRevision = null; // !< Revision object
29 public $mTimestamp = ''; // !<
30 public $mTouched = '19700101000000'; // !<
35 * @var ParserOptions: ParserOptions object for $wgUser articles
37 public $mParserOptions;
40 * Constructor and clear the article
41 * @param $title Title Reference to a Title object.
43 public function __construct( Title
$title ) {
44 $this->mTitle
= $title;
48 * Constructor from a page id
50 * Always override this for all subclasses (until we use PHP with LSB)
52 * @param $id Int article ID to load
54 public static function newFromID( $id ) {
55 $t = Title
::newFromID( $id );
56 # @todo FIXME: Doesn't inherit right
57 return $t == null ?
null : new self( $t );
58 # return $t == null ? null : new static( $t ); // PHP 5.3
62 * If this page is a redirect, get its target
64 * The target will be fetched from the redirect table if possible.
65 * If this page doesn't have an entry there, call insertRedirect()
66 * @return Title|mixed object, or null if this page is not a redirect
68 public function getRedirectTarget() {
69 if ( !$this->mTitle
->isRedirect() ) {
73 if ( $this->mRedirectTarget
!== null ) {
74 return $this->mRedirectTarget
;
77 # Query the redirect table
78 $dbr = wfGetDB( DB_SLAVE
);
79 $row = $dbr->selectRow( 'redirect',
80 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
81 array( 'rd_from' => $this->getID() ),
85 // rd_fragment and rd_interwiki were added later, populate them if empty
86 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
87 return $this->mRedirectTarget
= Title
::makeTitle(
88 $row->rd_namespace
, $row->rd_title
,
89 $row->rd_fragment
, $row->rd_interwiki
);
92 # This page doesn't have an entry in the redirect table
93 return $this->mRedirectTarget
= $this->insertRedirect();
97 * Insert an entry for this page into the redirect table.
99 * Don't call this function directly unless you know what you're doing.
100 * @return Title object or null if not a redirect
102 public function insertRedirect() {
103 // recurse through to only get the final target
104 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
108 $this->insertRedirectEntry( $retval );
113 * Insert or update the redirect table entry for this page to indicate
114 * it redirects to $rt .
115 * @param $rt Title redirect target
117 public function insertRedirectEntry( $rt ) {
118 $dbw = wfGetDB( DB_MASTER
);
119 $dbw->replace( 'redirect', array( 'rd_from' ),
121 'rd_from' => $this->getID(),
122 'rd_namespace' => $rt->getNamespace(),
123 'rd_title' => $rt->getDBkey(),
124 'rd_fragment' => $rt->getFragment(),
125 'rd_interwiki' => $rt->getInterwiki(),
132 * Get the Title object or URL this page redirects to
134 * @return mixed false, Title of in-wiki target, or string with URL
136 public function followRedirect() {
137 return $this->getRedirectURL( $this->getRedirectTarget() );
141 * Get the Title object or URL to use for a redirect. We use Title
142 * objects for same-wiki, non-special redirects and URLs for everything
144 * @param $rt Title Redirect target
145 * @return mixed false, Title object of local target, or string with URL
147 public function getRedirectURL( $rt ) {
149 if ( $rt->getInterwiki() != '' ) {
150 if ( $rt->isLocal() ) {
151 // Offsite wikis need an HTTP redirect.
153 // This can be hard to reverse and may produce loops,
154 // so they may be disabled in the site configuration.
155 $source = $this->mTitle
->getFullURL( 'redirect=no' );
156 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
159 if ( $rt->getNamespace() == NS_SPECIAL
) {
160 // Gotta handle redirects to special pages differently:
161 // Fill the HTTP response "Location" header and ignore
162 // the rest of the page we're on.
164 // This can be hard to reverse, so they may be disabled.
165 if ( $rt->isSpecial( 'Userlogout' ) ) {
168 return $rt->getFullURL();
176 // No or invalid redirect
181 * Get the title object of the article
182 * @return Title object of this page
184 public function getTitle() {
185 return $this->mTitle
;
191 public function clear() {
192 $this->mDataLoaded
= false;
194 $this->mCounter
= -1; # Not loaded
195 $this->mRedirectTarget
= null; # Title object if set
196 $this->mLastRevision
= null; # Latest revision
197 $this->mTimestamp
= '';
198 $this->mTouched
= '19700101000000';
199 $this->mIsRedirect
= false;
200 $this->mLatest
= false;
201 $this->mPreparedEdit
= false;
205 * Get the text that needs to be saved in order to undo all revisions
206 * between $undo and $undoafter. Revisions must belong to the same page,
207 * must exist and must not be deleted
208 * @param $undo Revision
209 * @param $undoafter Revision Must be an earlier revision than $undo
210 * @return mixed string on success, false on failure
212 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
213 $cur_text = $this->getRawText();
214 if ( $cur_text === false ) {
215 return false; // no page
217 $undo_text = $undo->getText();
218 $undoafter_text = $undoafter->getText();
220 if ( $cur_text == $undo_text ) {
221 # No use doing a merge if it's just a straight revert.
222 return $undoafter_text;
227 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
235 * Return the list of revision fields that should be selected to create
238 public static function selectFields() {
255 * Fetch a page record with the given conditions
256 * @param $dbr DatabaseBase object
257 * @param $conditions Array
258 * @return mixed Database result resource, or false on failure
260 protected function pageData( $dbr, $conditions ) {
261 $fields = self
::selectFields();
263 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
265 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
267 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
273 * Fetch a page record matching the Title object's namespace and title
274 * using a sanitized title string
276 * @param $dbr DatabaseBase object
277 * @param $title Title object
278 * @return mixed Database result resource, or false on failure
280 public function pageDataFromTitle( $dbr, $title ) {
281 return $this->pageData( $dbr, array(
282 'page_namespace' => $title->getNamespace(),
283 'page_title' => $title->getDBkey() ) );
287 * Fetch a page record matching the requested ID
289 * @param $dbr DatabaseBase
291 * @return mixed Database result resource, or false on failure
293 public function pageDataFromId( $dbr, $id ) {
294 return $this->pageData( $dbr, array( 'page_id' => $id ) );
298 * Set the general counter, title etc data loaded from
301 * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
303 public function loadPageData( $data = 'fromdb' ) {
304 if ( $data === 'fromdb' ) {
305 $dbr = wfGetDB( DB_SLAVE
);
306 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
309 $lc = LinkCache
::singleton();
312 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
314 $this->mTitle
->mArticleID
= intval( $data->page_id
);
316 # Old-fashioned restrictions
317 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
319 $this->mCounter
= intval( $data->page_counter
);
320 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
321 $this->mIsRedirect
= intval( $data->page_is_redirect
);
322 $this->mLatest
= intval( $data->page_latest
);
324 $lc->addBadLinkObj( $this->mTitle
);
325 $this->mTitle
->mArticleID
= 0;
328 $this->mDataLoaded
= true;
332 * @return int Page ID
334 public function getID() {
335 return $this->mTitle
->getArticleID();
339 * @return bool Whether or not the page exists in the database
341 public function exists() {
342 return $this->getId() > 0;
346 * Check if this page is something we're going to be showing
347 * some sort of sensible content for. If we return false, page
348 * views (plain action=view) will return an HTTP 404 response,
349 * so spiders and robots can know they're following a bad link.
353 public function hasViewableContent() {
354 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
358 * @return int The view count for the page
360 public function getCount() {
361 if ( -1 == $this->mCounter
) {
362 $id = $this->getID();
367 $dbr = wfGetDB( DB_SLAVE
);
368 $this->mCounter
= $dbr->selectField( 'page',
370 array( 'page_id' => $id ),
376 return $this->mCounter
;
380 * Determine whether a page would be suitable for being counted as an
381 * article in the site_stats table based on the title & its content
383 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
384 * if false, the current database state will be used
387 public function isCountable( $editInfo = false ) {
388 global $wgArticleCountMethod;
390 if ( !$this->mTitle
->isContentPage() ) {
394 $text = $editInfo ?
$editInfo->pst
: false;
396 if ( $this->isRedirect( $text ) ) {
400 switch ( $wgArticleCountMethod ) {
404 if ( $text === false ) {
405 $text = $this->getRawText();
407 return strpos( $text, ',' ) !== false;
410 // ParserOutput::getLinks() is a 2D array of page links, so
411 // to be really correct we would need to recurse in the array
412 // but the main array should only have items in it if there are
414 return (bool)count( $editInfo->output
->getLinks() );
416 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
417 array( 'pl_from' => $this->getId() ), __METHOD__
);
423 * Tests if the article text represents a redirect
425 * @param $text mixed string containing article contents, or boolean
428 public function isRedirect( $text = false ) {
429 if ( $text === false ) {
430 if ( !$this->mDataLoaded
) {
431 $this->loadPageData();
434 return (bool)$this->mIsRedirect
;
436 return Title
::newFromRedirect( $text ) !== null;
441 * Loads everything except the text
442 * This isn't necessary for all uses, so it's only done if needed.
444 protected function loadLastEdit() {
445 if ( $this->mLastRevision
!== null ) {
446 return; // already loaded
449 # New or non-existent articles have no user information
450 $id = $this->getID();
455 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
457 $this->setLastEdit( $revision );
462 * Set the latest revision
464 protected function setLastEdit( Revision
$revision ) {
465 $this->mLastRevision
= $revision;
466 $this->mTimestamp
= $revision->getTimestamp();
470 * Get the latest revision
471 * @return Revision|false
473 public function getRevision() {
474 $this->loadLastEdit();
475 if ( $this->mLastRevision
) {
476 return $this->mLastRevision
;
482 * Get the text of the current revision. No side-effects...
484 * @param $audience Integer: one of:
485 * Revision::FOR_PUBLIC to be displayed to all users
486 * Revision::FOR_THIS_USER to be displayed to $wgUser
487 * Revision::RAW get the text regardless of permissions
488 * @return String|false The text of the current revision
490 public function getText( $audience = Revision
::FOR_PUBLIC
) {
491 $this->loadLastEdit();
492 if ( $this->mLastRevision
) {
493 return $this->mLastRevision
->getText( $audience );
499 * Get the text of the current revision. No side-effects...
501 * @return String|false The text of the current revision
503 public function getRawText() {
504 $this->loadLastEdit();
505 if ( $this->mLastRevision
) {
506 return $this->mLastRevision
->getRawText();
512 * @return string MW timestamp of last article revision
514 public function getTimestamp() {
515 // Check if the field has been filled by ParserCache::get()
516 if ( !$this->mTimestamp
) {
517 $this->loadLastEdit();
519 return wfTimestamp( TS_MW
, $this->mTimestamp
);
523 * Set the page timestamp (use only to avoid DB queries)
524 * @param $ts string MW timestamp of last article revision
527 public function setTimestamp( $ts ) {
528 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
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 int user ID for the user that made the last article revision
538 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
539 $this->loadLastEdit();
540 if ( $this->mLastRevision
) {
541 return $this->mLastRevision
->getUser( $audience );
548 * @param $audience Integer: one of:
549 * Revision::FOR_PUBLIC to be displayed to all users
550 * Revision::FOR_THIS_USER to be displayed to $wgUser
551 * Revision::RAW get the text regardless of permissions
552 * @return string username of the user that made the last article revision
554 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
555 $this->loadLastEdit();
556 if ( $this->mLastRevision
) {
557 return $this->mLastRevision
->getUserText( $audience );
564 * @param $audience Integer: one of:
565 * Revision::FOR_PUBLIC to be displayed to all users
566 * Revision::FOR_THIS_USER to be displayed to $wgUser
567 * Revision::RAW get the text regardless of permissions
568 * @return string Comment stored for the last article revision
570 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
571 $this->loadLastEdit();
572 if ( $this->mLastRevision
) {
573 return $this->mLastRevision
->getComment( $audience );
580 * Returns true if last revision was marked as "minor edit"
582 * @return boolean Minor edit indicator for the last article revision.
584 public function getMinorEdit() {
585 $this->loadLastEdit();
586 if ( $this->mLastRevision
) {
587 return $this->mLastRevision
->isMinor();
594 * Get a list of users who have edited this article, not including the user who made
595 * the most recent revision, which you can get from $article->getUser() if you want it
596 * @return UserArrayFromResult
598 public function getContributors() {
599 # @todo FIXME: This is expensive; cache this info somewhere.
601 $dbr = wfGetDB( DB_SLAVE
);
603 if ( $dbr->implicitGroupby() ) {
604 $realNameField = 'user_real_name';
606 $realNameField = 'FIRST(user_real_name) AS user_real_name';
609 $tables = array( 'revision', 'user' );
612 'rev_user as user_id',
613 'rev_user_text AS user_name',
615 'MAX(rev_timestamp) AS timestamp',
618 $conds = array( 'rev_page' => $this->getId() );
620 // The user who made the top revision gets credited as "this page was last edited by
621 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
622 $user = $this->getUser();
624 $conds[] = "rev_user != $user";
626 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
629 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
632 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
636 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
637 'ORDER BY' => 'timestamp DESC',
640 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
641 return new UserArrayFromResult( $res );
645 * Should the parser cache be used?
647 * @param $user User The relevant user
650 public function isParserCacheUsed( User
$user, $oldid ) {
651 global $wgEnableParserCache;
653 return $wgEnableParserCache
654 && $user->getStubThreshold() == 0
657 && !$this->mTitle
->isCssOrJsPage()
658 && !$this->mTitle
->isCssJsSubpage();
662 * Perform the actions of a page purging
664 public function doPurge() {
667 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
671 // Invalidate the cache
672 $this->mTitle
->invalidateCache();
676 // Commit the transaction before the purge is sent
677 $dbw = wfGetDB( DB_MASTER
);
681 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
685 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
686 if ( $this->getID() == 0 ) {
689 $text = $this->getRawText();
692 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
697 * Insert a new empty page record for this article.
698 * This *must* be followed up by creating a revision
699 * and running $this->updateRevisionOn( ... );
700 * or else the record will be left in a funky state.
701 * Best if all done inside a transaction.
703 * @param $dbw DatabaseBase
704 * @return int The newly created page_id key, or false if the title already existed
707 public function insertOn( $dbw ) {
708 wfProfileIn( __METHOD__
);
710 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
711 $dbw->insert( 'page', array(
712 'page_id' => $page_id,
713 'page_namespace' => $this->mTitle
->getNamespace(),
714 'page_title' => $this->mTitle
->getDBkey(),
716 'page_restrictions' => '',
717 'page_is_redirect' => 0, # Will set this shortly...
719 'page_random' => wfRandom(),
720 'page_touched' => $dbw->timestamp(),
721 'page_latest' => 0, # Fill this in shortly...
722 'page_len' => 0, # Fill this in shortly...
723 ), __METHOD__
, 'IGNORE' );
725 $affected = $dbw->affectedRows();
728 $newid = $dbw->insertId();
729 $this->mTitle
->resetArticleID( $newid );
731 wfProfileOut( __METHOD__
);
733 return $affected ?
$newid : false;
737 * Update the page record to point to a newly saved revision.
739 * @param $dbw DatabaseBase: object
740 * @param $revision Revision: For ID number, and text used to set
741 length and redirect status fields
742 * @param $lastRevision Integer: if given, will not overwrite the page field
743 * when different from the currently set value.
744 * Giving 0 indicates the new page flag should be set
746 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
747 * removing rows in redirect table.
748 * @return bool true on success, false on failure
751 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
752 wfProfileIn( __METHOD__
);
754 $text = $revision->getText();
755 $rt = Title
::newFromRedirectRecurse( $text );
757 $conditions = array( 'page_id' => $this->getId() );
759 if ( !is_null( $lastRevision ) ) {
760 # An extra check against threads stepping on each other
761 $conditions['page_latest'] = $lastRevision;
764 $dbw->update( 'page',
766 'page_latest' => $revision->getId(),
767 'page_touched' => $dbw->timestamp(),
768 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
769 'page_is_redirect' => $rt !== null ?
1 : 0,
770 'page_len' => strlen( $text ),
775 $result = $dbw->affectedRows() != 0;
777 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
780 wfProfileOut( __METHOD__
);
785 * Add row to the redirect table if this is a redirect, remove otherwise.
787 * @param $dbw DatabaseBase
788 * @param $redirectTitle Title object pointing to the redirect target,
789 * or NULL if this is not a redirect
790 * @param $lastRevIsRedirect If given, will optimize adding and
791 * removing rows in redirect table.
792 * @return bool true on success, false on failure
795 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
796 // Always update redirects (target link might have changed)
797 // Update/Insert if we don't know if the last revision was a redirect or not
798 // Delete if changing from redirect to non-redirect
799 $isRedirect = !is_null( $redirectTitle );
801 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
805 wfProfileIn( __METHOD__
);
807 $this->insertRedirectEntry( $redirectTitle );
809 // This is not a redirect, remove row from redirect table
810 $where = array( 'rd_from' => $this->getId() );
811 $dbw->delete( 'redirect', $where, __METHOD__
);
814 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
815 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
817 wfProfileOut( __METHOD__
);
819 return ( $dbw->affectedRows() != 0 );
823 * If the given revision is newer than the currently set page_latest,
824 * update the page record. Otherwise, do nothing.
826 * @param $dbw Database object
827 * @param $revision Revision object
830 public function updateIfNewerOn( $dbw, $revision ) {
831 wfProfileIn( __METHOD__
);
833 $row = $dbw->selectRow(
834 array( 'revision', 'page' ),
835 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
837 'page_id' => $this->getId(),
838 'page_latest=rev_id' ),
842 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
843 wfProfileOut( __METHOD__
);
846 $prev = $row->rev_id
;
847 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
849 # No or missing previous revision; mark the page as new
851 $lastRevIsRedirect = null;
854 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
856 wfProfileOut( __METHOD__
);
861 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
862 * @param $text String: new text of the section
863 * @param $summary String: new section's subject, only if $section is 'new'
864 * @param $edittime String: revision timestamp or null to use the current revision
865 * @return string Complete article text, or null if error
867 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
868 wfProfileIn( __METHOD__
);
870 if ( strval( $section ) == '' ) {
871 // Whole-page edit; let the whole text through
873 if ( is_null( $edittime ) ) {
874 $rev = Revision
::newFromTitle( $this->mTitle
);
876 $dbw = wfGetDB( DB_MASTER
);
877 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
881 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
882 $this->getId() . "; section: $section; edittime: $edittime)\n" );
883 wfProfileOut( __METHOD__
);
887 $oldtext = $rev->getText();
889 if ( $section == 'new' ) {
890 # Inserting a new section
891 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
892 $text = strlen( trim( $oldtext ) ) > 0
893 ?
"{$oldtext}\n\n{$subject}{$text}"
894 : "{$subject}{$text}";
896 # Replacing an existing section; roll out the big guns
899 $text = $wgParser->replaceSection( $oldtext, $section, $text );
903 wfProfileOut( __METHOD__
);
908 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
910 * @return Int updated $flags
912 function checkFlags( $flags ) {
913 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
914 if ( $this->mTitle
->getArticleID() ) {
915 $flags |
= EDIT_UPDATE
;
925 * Change an existing article or create a new article. Updates RC and all necessary caches,
926 * optionally via the deferred update array.
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 the user doing the edit
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 );
1007 $oldcountable = $this->isCountable();
1009 # Provide autosummaries if one is not provided and autosummaries are enabled.
1010 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1011 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1014 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1015 $text = $editInfo->pst
;
1016 $newsize = strlen( $text );
1018 $dbw = wfGetDB( DB_MASTER
);
1019 $now = wfTimestampNow();
1020 $this->mTimestamp
= $now;
1022 if ( $flags & EDIT_UPDATE
) {
1023 # Update article, but only if changed.
1024 $status->value
['new'] = false;
1026 # Make sure the revision is either completely inserted or not inserted at all
1027 if ( !$wgDBtransactions ) {
1028 $userAbort = ignore_user_abort( true );
1031 $revision = new Revision( array(
1032 'page' => $this->getId(),
1033 'comment' => $summary,
1034 'minor_edit' => $isminor,
1036 'parent_id' => $this->mLatest
,
1037 'user' => $user->getId(),
1038 'user_text' => $user->getName(),
1042 $changed = ( strcmp( $text, $oldtext ) != 0 );
1045 if ( !$this->mLatest
) {
1046 # Article gone missing
1047 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1048 $status->fatal( 'edit-gone-missing' );
1050 wfProfileOut( __METHOD__
);
1055 $revisionId = $revision->insertOn( $dbw );
1059 # Note that we use $this->mLatest instead of fetching a value from the master DB
1060 # during the course of this function. This makes sure that EditPage can detect
1061 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1062 # before this function is called. A previous function used a separate query, this
1063 # creates a window where concurrent edits can cause an ignored edit conflict.
1064 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1067 /* Belated edit conflict! Run away!! */
1068 $status->fatal( 'edit-conflict' );
1070 # Delete the invalid revision if the DB is not transactional
1071 if ( !$wgDBtransactions ) {
1072 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1078 global $wgUseRCPatrol;
1079 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1080 # Update recentchanges
1081 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1082 # Mark as patrolled if the user can do so
1083 $patrolled = $wgUseRCPatrol && !count(
1084 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1085 # Add RC row to the DB
1086 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1087 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1088 $revisionId, $patrolled
1091 # Log auto-patrolled edits
1093 PatrolLog
::record( $rc, true );
1096 $user->incEditCount();
1101 if ( !$wgDBtransactions ) {
1102 ignore_user_abort( $userAbort );
1105 // Now that ignore_user_abort is restored, we can respond to fatal errors
1106 if ( !$status->isOK() ) {
1107 wfProfileOut( __METHOD__
);
1111 # Update links tables, site stats, etc.
1112 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1113 'oldcountable' => $oldcountable ) );
1116 $status->warning( 'edit-no-change' );
1118 // Keep the same revision ID, but do some updates on it
1119 $revisionId = $this->getLatest();
1120 // Update page_touched, this is usually implicit in the page update
1121 // Other cache updates are done in onArticleEdit()
1122 $this->mTitle
->invalidateCache();
1125 # Create new article
1126 $status->value
['new'] = true;
1130 # Add the page record; stake our claim on this title!
1131 # This will return false if the article already exists
1132 $newid = $this->insertOn( $dbw );
1134 if ( $newid === false ) {
1136 $status->fatal( 'edit-already-exists' );
1138 wfProfileOut( __METHOD__
);
1142 # Save the revision text...
1143 $revision = new Revision( array(
1145 'comment' => $summary,
1146 'minor_edit' => $isminor,
1148 'user' => $user->getId(),
1149 'user_text' => $user->getName(),
1152 $revisionId = $revision->insertOn( $dbw );
1154 $this->mTitle
->resetArticleID( $newid );
1155 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
1157 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
1159 # Update the page record with revision data
1160 $this->updateRevisionOn( $dbw, $revision, 0 );
1162 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1164 # Update recentchanges
1165 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1166 global $wgUseRCPatrol, $wgUseNPPatrol;
1168 # Mark as patrolled if the user can do so
1169 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1170 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1171 # Add RC row to the DB
1172 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1173 '', strlen( $text ), $revisionId, $patrolled );
1175 # Log auto-patrolled edits
1177 PatrolLog
::record( $rc, true );
1180 $user->incEditCount();
1183 # Update links, etc.
1184 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1186 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1187 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1190 # Do updates right now unless deferral was requested
1191 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1195 // Return the new revision (or null) to the caller
1196 $status->value
['revision'] = $revision;
1198 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1199 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1201 # Promote user to any groups they meet the criteria for
1202 $user->addAutopromoteOnceGroups( 'onEdit' );
1204 wfProfileOut( __METHOD__
);
1209 * Update the article's restriction field, and leave a log entry.
1211 * @param $limit Array: set of restriction keys
1212 * @param $reason String
1213 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1214 * @param $expiry Array: per restriction type expiration
1215 * @param $user User The user updating the restrictions
1216 * @return bool true on success
1218 public function updateRestrictions(
1219 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
1221 global $wgUser, $wgContLang;
1222 $user = is_null( $user ) ?
$wgUser : $user;
1224 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1226 $id = $this->mTitle
->getArticleID();
1229 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1233 if ( wfReadOnly() ) {
1234 wfDebug( "updateRestrictions failed: read-only\n" );
1238 if ( !$this->mTitle
->userCan( 'protect' ) ) {
1239 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1247 // Take this opportunity to purge out expired restrictions
1248 Title
::purgeExpiredRestrictions();
1250 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1251 # we expect a single selection, but the schema allows otherwise.
1253 $updated = self
::flattenRestrictions( $limit );
1256 foreach ( $restrictionTypes as $action ) {
1257 if ( isset( $expiry[$action] ) ) {
1258 # Get current restrictions on $action
1259 $aLimits = $this->mTitle
->getRestrictions( $action );
1260 $current[$action] = implode( '', $aLimits );
1261 # Are any actual restrictions being dealt with here?
1262 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
1264 # If something changed, we need to log it. Checking $aRChanged
1265 # assures that "unprotecting" a page that is not protected does
1266 # not log just because the expiry was "changed".
1267 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
1273 $current = self
::flattenRestrictions( $current );
1275 $changed = ( $changed ||
$current != $updated );
1276 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
1277 $protect = ( $updated != '' );
1279 # If nothing's changed, do nothing
1281 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1282 $dbw = wfGetDB( DB_MASTER
);
1284 # Prepare a null revision to be added to the history
1285 $modified = $current != '' && $protect;
1288 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1290 $comment_type = 'unprotectedarticle';
1293 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1295 # Only restrictions with the 'protect' right can cascade...
1296 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1297 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1299 # The schema allows multiple restrictions
1300 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1304 $cascade_description = '';
1307 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1311 $comment .= ": $reason";
1314 $editComment = $comment;
1315 $encodedExpiry = array();
1316 $protect_description = '';
1317 foreach ( $limit as $action => $restrictions ) {
1318 if ( !isset( $expiry[$action] ) )
1319 $expiry[$action] = $dbw->getInfinity();
1321 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1322 if ( $restrictions != '' ) {
1323 $protect_description .= "[$action=$restrictions] (";
1324 if ( $encodedExpiry[$action] != 'infinity' ) {
1325 $protect_description .= wfMsgForContent( 'protect-expiring',
1326 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1327 $wgContLang->date( $expiry[$action], false, false ) ,
1328 $wgContLang->time( $expiry[$action], false, false ) );
1330 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1333 $protect_description .= ') ';
1336 $protect_description = trim( $protect_description );
1338 if ( $protect_description && $protect ) {
1339 $editComment .= " ($protect_description)";
1343 $editComment .= "$cascade_description";
1346 # Update restrictions table
1347 foreach ( $limit as $action => $restrictions ) {
1348 if ( $restrictions != '' ) {
1349 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1350 array( 'pr_page' => $id,
1351 'pr_type' => $action,
1352 'pr_level' => $restrictions,
1353 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1354 'pr_expiry' => $encodedExpiry[$action]
1359 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1360 'pr_type' => $action ), __METHOD__
);
1364 # Insert a null revision
1365 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1366 $nullRevId = $nullRevision->insertOn( $dbw );
1368 $latest = $this->getLatest();
1369 # Update page record
1370 $dbw->update( 'page',
1372 'page_touched' => $dbw->timestamp(),
1373 'page_restrictions' => '',
1374 'page_latest' => $nullRevId
1375 ), array( /* WHERE */
1380 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1381 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1383 # Update the protection log
1384 $log = new LogPage( 'protect' );
1386 $params = array( $protect_description, $cascade ?
'cascade' : '' );
1387 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
1389 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1392 } # End "changed" check
1398 * Take an array of page restrictions and flatten it to a string
1399 * suitable for insertion into the page_restrictions field.
1400 * @param $limit Array
1403 protected static function flattenRestrictions( $limit ) {
1404 if ( !is_array( $limit ) ) {
1405 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1411 foreach ( $limit as $action => $restrictions ) {
1412 if ( $restrictions != '' ) {
1413 $bits[] = "$action=$restrictions";
1417 return implode( ':', $bits );
1421 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1423 public function isBigDeletion() {
1424 global $wgDeleteRevisionsLimit;
1426 if ( $wgDeleteRevisionsLimit ) {
1427 $revCount = $this->estimateRevisionCount();
1429 return $revCount > $wgDeleteRevisionsLimit;
1436 * @return int approximate revision count
1438 public function estimateRevisionCount() {
1439 $dbr = wfGetDB( DB_SLAVE
);
1441 // For an exact count...
1442 // return $dbr->selectField( 'revision', 'COUNT(*)',
1443 // array( 'rev_page' => $this->getId() ), __METHOD__ );
1444 return $dbr->estimateRowCount( 'revision', '*',
1445 array( 'rev_page' => $this->getId() ), __METHOD__
);
1449 * Get the last N authors
1450 * @param $num Integer: number of revisions to get
1451 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1452 * @return array Array of authors, duplicates not removed
1454 public function getLastNAuthors( $num, $revLatest = 0 ) {
1455 wfProfileIn( __METHOD__
);
1456 // First try the slave
1457 // If that doesn't have the latest revision, try the master
1459 $db = wfGetDB( DB_SLAVE
);
1462 $res = $db->select( array( 'page', 'revision' ),
1463 array( 'rev_id', 'rev_user_text' ),
1465 'page_namespace' => $this->mTitle
->getNamespace(),
1466 'page_title' => $this->mTitle
->getDBkey(),
1467 'rev_page = page_id'
1470 'ORDER BY' => 'rev_timestamp DESC',
1476 wfProfileOut( __METHOD__
);
1480 $row = $db->fetchObject( $res );
1482 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1483 $db = wfGetDB( DB_MASTER
);
1488 } while ( $continue );
1490 $authors = array( $row->rev_user_text
);
1492 foreach ( $res as $row ) {
1493 $authors[] = $row->rev_user_text
;
1496 wfProfileOut( __METHOD__
);
1501 * Back-end article deletion
1502 * Deletes the article with database consistency, writes logs, purges caches
1504 * @param $reason string delete reason for deletion log
1505 * @param suppress bitfield
1506 * Revision::DELETED_TEXT
1507 * Revision::DELETED_COMMENT
1508 * Revision::DELETED_USER
1509 * Revision::DELETED_RESTRICTED
1510 * @param $id int article ID
1511 * @param $commit boolean defaults to true, triggers transaction end
1512 * @param &$errors Array of errors to append to
1513 * @param $user User The relevant user
1514 * @return boolean true if successful
1516 public function doDeleteArticle(
1517 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1519 global $wgDeferredUpdateList, $wgUseTrackbacks, $wgUser;
1520 $user = is_null( $user ) ?
$wgUser : $user;
1522 wfDebug( __METHOD__
. "\n" );
1524 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1527 $dbw = wfGetDB( DB_MASTER
);
1528 $t = $this->mTitle
->getDBkey();
1529 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1531 if ( $t === '' ||
$id == 0 ) {
1535 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
1536 array_push( $wgDeferredUpdateList, $u );
1538 // Bitfields to further suppress the content
1541 // This should be 15...
1542 $bitfield |
= Revision
::DELETED_TEXT
;
1543 $bitfield |
= Revision
::DELETED_COMMENT
;
1544 $bitfield |
= Revision
::DELETED_USER
;
1545 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1547 $bitfield = 'rev_deleted';
1551 // For now, shunt the revision data into the archive table.
1552 // Text is *not* removed from the text table; bulk storage
1553 // is left intact to avoid breaking block-compression or
1554 // immutable storage schemes.
1556 // For backwards compatibility, note that some older archive
1557 // table entries will have ar_text and ar_flags fields still.
1559 // In the future, we may keep revisions and mark them with
1560 // the rev_deleted field, which is reserved for this purpose.
1561 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1563 'ar_namespace' => 'page_namespace',
1564 'ar_title' => 'page_title',
1565 'ar_comment' => 'rev_comment',
1566 'ar_user' => 'rev_user',
1567 'ar_user_text' => 'rev_user_text',
1568 'ar_timestamp' => 'rev_timestamp',
1569 'ar_minor_edit' => 'rev_minor_edit',
1570 'ar_rev_id' => 'rev_id',
1571 'ar_text_id' => 'rev_text_id',
1572 'ar_text' => '\'\'', // Be explicit to appease
1573 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1574 'ar_len' => 'rev_len',
1575 'ar_page_id' => 'page_id',
1576 'ar_deleted' => $bitfield
1579 'page_id = rev_page'
1583 # Delete restrictions for it
1584 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1586 # Now that it's safely backed up, delete it
1587 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1588 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1595 # Fix category table counts
1597 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1599 foreach ( $res as $row ) {
1600 $cats [] = $row->cl_to
;
1603 $this->updateCategoryCounts( array(), $cats );
1605 # If using cascading deletes, we can skip some explicit deletes
1606 if ( !$dbw->cascadingDeletes() ) {
1607 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
1609 if ( $wgUseTrackbacks )
1610 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
1612 # Delete outgoing links
1613 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1614 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1615 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1616 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1617 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1618 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1619 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
1620 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
1623 # If using cleanup triggers, we can skip some manual deletes
1624 if ( !$dbw->cleanupTriggers() ) {
1625 # Clean up recentchanges entries...
1626 $dbw->delete( 'recentchanges',
1627 array( 'rc_type != ' . RC_LOG
,
1628 'rc_namespace' => $this->mTitle
->getNamespace(),
1629 'rc_title' => $this->mTitle
->getDBkey() ),
1631 $dbw->delete( 'recentchanges',
1632 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
1637 self
::onArticleDelete( $this->mTitle
);
1639 # Clear the cached article id so the interface doesn't act like we exist
1640 $this->mTitle
->resetArticleID( 0 );
1642 # Log the deletion, if the page was suppressed, log it at Oversight instead
1643 $logtype = $suppress ?
'suppress' : 'delete';
1644 $log = new LogPage( $logtype );
1646 # Make sure logging got through
1647 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
1653 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1658 * Roll back the most recent consecutive set of edits to a page
1659 * from the same user; fails if there are no eligible edits to
1660 * roll back to, e.g. user is the sole contributor. This function
1661 * performs permissions checks on $user, then calls commitRollback()
1662 * to do the dirty work
1664 * @param $fromP String: Name of the user whose edits to rollback.
1665 * @param $summary String: Custom summary. Set to default summary if empty.
1666 * @param $token String: Rollback token.
1667 * @param $bot Boolean: If true, mark all reverted edits as bot.
1669 * @param $resultDetails Array: contains result-specific array of additional values
1670 * 'alreadyrolled' : 'current' (rev)
1671 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1673 * @param $user User The user performing the rollback
1674 * @return array of errors, each error formatted as
1675 * array(messagekey, param1, param2, ...).
1676 * On success, the array is empty. This array can also be passed to
1677 * OutputPage::showPermissionsErrorPage().
1679 public function doRollback(
1680 $fromP, $summary, $token, $bot, &$resultDetails, User
$user = null
1683 $user = is_null( $user ) ?
$wgUser : $user;
1685 $resultDetails = null;
1688 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
1689 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
1690 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1692 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
1693 $errors[] = array( 'sessionfailure' );
1696 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
1697 $errors[] = array( 'actionthrottledtext' );
1700 # If there were errors, bail out now
1701 if ( !empty( $errors ) ) {
1705 return $this->commitRollback( $user, $fromP, $summary, $bot, $resultDetails );
1709 * Backend implementation of doRollback(), please refer there for parameter
1710 * and return value documentation
1712 * NOTE: This function does NOT check ANY permissions, it just commits the
1713 * rollback to the DB Therefore, you should only call this function direct-
1714 * ly if you want to use custom permissions checks. If you don't, use
1715 * doRollback() instead.
1716 * @param $fromP String: Name of the user whose edits to rollback.
1717 * @param $summary String: Custom summary. Set to default summary if empty.
1718 * @param $bot Boolean: If true, mark all reverted edits as bot.
1720 * @param $resultDetails Array: contains result-specific array of additional values
1721 * @param $guser User The user performing the rollback
1723 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser = null ) {
1724 global $wgUseRCPatrol, $wgUser, $wgContLang;
1725 $guser = is_null( $guser ) ?
$wgUser : $guser;
1727 $dbw = wfGetDB( DB_MASTER
);
1729 if ( wfReadOnly() ) {
1730 return array( array( 'readonlytext' ) );
1733 # Get the last editor
1734 $current = Revision
::newFromTitle( $this->mTitle
);
1735 if ( is_null( $current ) ) {
1736 # Something wrong... no page?
1737 return array( array( 'notanarticle' ) );
1740 $from = str_replace( '_', ' ', $fromP );
1741 # User name given should match up with the top revision.
1742 # If the user was deleted then $from should be empty.
1743 if ( $from != $current->getUserText() ) {
1744 $resultDetails = array( 'current' => $current );
1745 return array( array( 'alreadyrolled',
1746 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
1747 htmlspecialchars( $fromP ),
1748 htmlspecialchars( $current->getUserText() )
1752 # Get the last edit not by this guy...
1753 # Note: these may not be public values
1754 $user = intval( $current->getRawUser() );
1755 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1756 $s = $dbw->selectRow( 'revision',
1757 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1758 array( 'rev_page' => $current->getPage(),
1759 "rev_user != {$user} OR rev_user_text != {$user_text}"
1761 array( 'USE INDEX' => 'page_timestamp',
1762 'ORDER BY' => 'rev_timestamp DESC' )
1764 if ( $s === false ) {
1765 # No one else ever edited this page
1766 return array( array( 'cantrollback' ) );
1767 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
1768 # Only admins can see this text
1769 return array( array( 'notvisiblerev' ) );
1773 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1774 # Mark all reverted edits as bot
1778 if ( $wgUseRCPatrol ) {
1779 # Mark all reverted edits as patrolled
1780 $set['rc_patrolled'] = 1;
1783 if ( count( $set ) ) {
1784 $dbw->update( 'recentchanges', $set,
1786 'rc_cur_id' => $current->getPage(),
1787 'rc_user_text' => $current->getUserText(),
1788 "rc_timestamp > '{$s->rev_timestamp}'",
1793 # Generate the edit summary if necessary
1794 $target = Revision
::newFromId( $s->rev_id
);
1795 if ( empty( $summary ) ) {
1796 if ( $from == '' ) { // no public user name
1797 $summary = wfMsgForContent( 'revertpage-nouser' );
1799 $summary = wfMsgForContent( 'revertpage' );
1803 # Allow the custom summary to use the same args as the default message
1805 $target->getUserText(), $from, $s->rev_id
,
1806 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
1807 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1809 $summary = wfMsgReplaceArgs( $summary, $args );
1812 $flags = EDIT_UPDATE
;
1814 if ( $guser->isAllowed( 'minoredit' ) ) {
1815 $flags |
= EDIT_MINOR
;
1818 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1819 $flags |
= EDIT_FORCE_BOT
;
1822 # Actually store the edit
1823 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1824 if ( !empty( $status->value
['revision'] ) ) {
1825 $revId = $status->value
['revision']->getId();
1830 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1832 $resultDetails = array(
1833 'summary' => $summary,
1834 'current' => $current,
1835 'target' => $target,
1843 * Do standard deferred updates after page view
1844 * @param $user User The relevant user
1846 public function doViewUpdates( User
$user ) {
1847 global $wgDeferredUpdateList, $wgDisableCounters;
1848 if ( wfReadOnly() ) {
1852 # Don't update page view counters on views from bot users (bug 14044)
1853 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->getID() ) {
1854 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
1855 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
1858 # Update newtalk / watchlist notification status
1859 $user->clearNotification( $this->mTitle
);
1863 * Prepare text which is about to be saved.
1864 * Returns a stdclass with source, pst and output members
1866 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1867 global $wgParser, $wgUser;
1868 $user = is_null( $user ) ?
$wgUser : $user;
1869 // @TODO fixme: check $user->getId() here???
1870 if ( $this->mPreparedEdit
1871 && $this->mPreparedEdit
->newText
== $text
1872 && $this->mPreparedEdit
->revid
== $revid
1875 return $this->mPreparedEdit
;
1878 $popts = ParserOptions
::newFromUser( $user );
1879 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1881 $edit = (object)array();
1882 $edit->revid
= $revid;
1883 $edit->newText
= $text;
1884 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
1885 $edit->popts
= $this->getParserOptions( true );
1886 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1887 $edit->oldText
= $this->getRawText();
1889 $this->mPreparedEdit
= $edit;
1895 * Do standard deferred updates after page edit.
1896 * Update links tables, site stats, search index and message cache.
1897 * Purges pages that include this page if the text was changed here.
1898 * Every 100th edit, prune the recent changes table.
1901 * @param $revision Revision object
1902 * @param $user User object that did the revision
1903 * @param $options Array of options, following indexes are used:
1904 * - changed: boolean, whether the revision changed the content (default true)
1905 * - created: boolean, whether the revision created the page (default false)
1906 * - oldcountable: boolean or null (default null):
1907 * - boolean: whether the page was counted as an article before that
1908 * revision, only used in changed is true and created is false
1909 * - null: don't change the article count
1911 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1912 global $wgDeferredUpdateList, $wgEnableParserCache;
1914 wfProfileIn( __METHOD__
);
1916 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1917 $text = $revision->getText();
1920 # Be careful not to double-PST: $text is usually already PST-ed once
1921 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1922 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1923 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1925 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1926 $editInfo = $this->mPreparedEdit
;
1929 # Save it to the parser cache
1930 if ( $wgEnableParserCache ) {
1931 $parserCache = ParserCache
::singleton();
1932 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1935 # Update the links tables
1936 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1939 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1941 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1942 if ( 0 == mt_rand( 0, 99 ) ) {
1943 // Flush old entries from the `recentchanges` table; we do this on
1944 // random requests so as to avoid an increase in writes for no good reason
1947 $dbw = wfGetDB( DB_MASTER
);
1948 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1951 array( "rc_timestamp < '$cutoff'" ),
1957 $id = $this->getID();
1958 $title = $this->mTitle
->getPrefixedDBkey();
1959 $shortTitle = $this->mTitle
->getDBkey();
1962 wfProfileOut( __METHOD__
);
1966 if ( !$options['changed'] ) {
1969 } elseif ( $options['created'] ) {
1970 $good = (int)$this->isCountable( $editInfo );
1972 } elseif ( $options['oldcountable'] !== null ) {
1973 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1980 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
1981 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
1983 # If this is another user's talk page, update newtalk
1984 # Don't do this if $changed = false otherwise some idiot can null-edit a
1985 # load of user talk pages and piss people off, nor if it's a minor edit
1986 # by a properly-flagged bot.
1987 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $user->getTitleKey() && $changed
1988 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1990 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1991 $other = User
::newFromName( $shortTitle, false );
1993 wfDebug( __METHOD__
. ": invalid username\n" );
1994 } elseif ( User
::isIP( $shortTitle ) ) {
1995 // An anonymous user
1996 $other->setNewtalk( true );
1997 } elseif ( $other->isLoggedIn() ) {
1998 $other->setNewtalk( true );
2000 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2005 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2006 MessageCache
::singleton()->replace( $shortTitle, $text );
2009 if( $options['created'] ) {
2010 self
::onArticleCreate( $this->mTitle
);
2012 self
::onArticleEdit( $this->mTitle
);
2015 wfProfileOut( __METHOD__
);
2019 * Perform article updates on a special page creation.
2021 * @param $rev Revision object
2023 * @todo This is a shitty interface function. Kill it and replace the
2024 * other shitty functions like doEditUpdates and such so it's not needed
2026 * @deprecated since 1.19, use doEditUpdates()
2028 public function createUpdates( $rev ) {
2030 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2034 * This function is called right before saving the wikitext,
2035 * so we can do things like signatures and links-in-context.
2037 * @param $text String article contents
2038 * @param $user User object: user doing the edit
2039 * @param $popts ParserOptions object: parser options, default options for
2040 * the user loaded if null given
2041 * @return string article contents with altered wikitext markup (signatures
2042 * converted, {{subst:}}, templates, etc.)
2044 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2045 global $wgParser, $wgUser;
2046 $user = is_null( $user ) ?
$wgUser : $user;
2048 if ( $popts === null ) {
2049 $popts = ParserOptions
::newFromUser( $user );
2052 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2056 * Loads page_touched and returns a value indicating if it should be used
2057 * @return boolean true if not a redirect
2059 public function checkTouched() {
2060 if ( !$this->mDataLoaded
) {
2061 $this->loadPageData();
2064 return !$this->mIsRedirect
;
2068 * Get the page_touched field
2069 * @return string containing GMT timestamp
2071 public function getTouched() {
2072 if ( !$this->mDataLoaded
) {
2073 $this->loadPageData();
2076 return $this->mTouched
;
2080 * Get the page_latest field
2081 * @return integer rev_id of current revision
2083 public function getLatest() {
2084 if ( !$this->mDataLoaded
) {
2085 $this->loadPageData();
2088 return (int)$this->mLatest
;
2092 * Edit an article without doing all that other stuff
2093 * The article must already exist; link tables etc
2094 * are not updated, caches are not flushed.
2096 * @param $text String: text submitted
2097 * @param $user User The relevant user
2098 * @param $comment String: comment submitted
2099 * @param $minor Boolean: whereas it's a minor modification
2101 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2102 wfProfileIn( __METHOD__
);
2104 $dbw = wfGetDB( DB_MASTER
);
2105 $revision = new Revision( array(
2106 'page' => $this->getId(),
2108 'comment' => $comment,
2109 'minor_edit' => $minor ?
1 : 0,
2111 $revision->insertOn( $dbw );
2112 $this->updateRevisionOn( $dbw, $revision );
2114 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2116 wfProfileOut( __METHOD__
);
2120 * The onArticle*() functions are supposed to be a kind of hooks
2121 * which should be called whenever any of the specified actions
2124 * This is a good place to put code to clear caches, for instance.
2126 * This is called on page move and undelete, as well as edit
2128 * @param $title Title object
2130 public static function onArticleCreate( $title ) {
2131 # Update existence markers on article/talk tabs...
2132 if ( $title->isTalkPage() ) {
2133 $other = $title->getSubjectPage();
2135 $other = $title->getTalkPage();
2138 $other->invalidateCache();
2139 $other->purgeSquid();
2141 $title->touchLinks();
2142 $title->purgeSquid();
2143 $title->deleteTitleProtection();
2147 * Clears caches when article is deleted
2149 * @param $title Title
2151 public static function onArticleDelete( $title ) {
2152 # Update existence markers on article/talk tabs...
2153 if ( $title->isTalkPage() ) {
2154 $other = $title->getSubjectPage();
2156 $other = $title->getTalkPage();
2159 $other->invalidateCache();
2160 $other->purgeSquid();
2162 $title->touchLinks();
2163 $title->purgeSquid();
2166 HTMLFileCache
::clearFileCache( $title );
2169 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2170 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2174 if ( $title->getNamespace() == NS_FILE
) {
2175 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2176 $update->doUpdate();
2180 if ( $title->getNamespace() == NS_USER_TALK
) {
2181 $user = User
::newFromName( $title->getText(), false );
2182 $user->setNewtalk( false );
2186 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2190 * Purge caches on page update etc
2192 * @param $title Title object
2193 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2195 public static function onArticleEdit( $title ) {
2196 global $wgDeferredUpdateList;
2198 // Invalidate caches of articles which include this page
2199 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
2201 // Invalidate the caches of all pages which redirect here
2202 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
2204 # Purge squid for this page only
2205 $title->purgeSquid();
2207 # Clear file cache for this page only
2208 HTMLFileCache
::clearFileCache( $title );
2214 * Return a list of templates used by this article.
2215 * Uses the templatelinks table
2217 * @return Array of Title objects
2219 public function getUsedTemplates() {
2221 $id = $this->mTitle
->getArticleID();
2227 $dbr = wfGetDB( DB_SLAVE
);
2228 $res = $dbr->select( array( 'templatelinks' ),
2229 array( 'tl_namespace', 'tl_title' ),
2230 array( 'tl_from' => $id ),
2233 if ( $res !== false ) {
2234 foreach ( $res as $row ) {
2235 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2243 * Returns a list of hidden categories this page is a member of.
2244 * Uses the page_props and categorylinks tables.
2246 * @return Array of Title objects
2248 public function getHiddenCategories() {
2250 $id = $this->mTitle
->getArticleID();
2256 $dbr = wfGetDB( DB_SLAVE
);
2257 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2259 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2260 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2263 if ( $res !== false ) {
2264 foreach ( $res as $row ) {
2265 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2273 * Return an applicable autosummary if one exists for the given edit.
2274 * @param $oldtext String: the previous text of the page.
2275 * @param $newtext String: The submitted text of the page.
2276 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2277 * @return string An appropriate autosummary, or an empty string.
2279 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2282 # Decide what kind of autosummary is needed.
2284 # Redirect autosummaries
2285 $ot = Title
::newFromRedirect( $oldtext );
2286 $rt = Title
::newFromRedirect( $newtext );
2288 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2289 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2292 # New page autosummaries
2293 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2294 # If they're making a new article, give its text, truncated, in the summary.
2296 $truncatedtext = $wgContLang->truncate(
2297 str_replace( "\n", ' ', $newtext ),
2298 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2300 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2303 # Blanking autosummaries
2304 if ( $oldtext != '' && $newtext == '' ) {
2305 return wfMsgForContent( 'autosumm-blank' );
2306 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2307 # Removing more than 90% of the article
2309 $truncatedtext = $wgContLang->truncate(
2311 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2313 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2316 # If we reach this point, there's no applicable autosummary for our case, so our
2317 # autosummary is empty.
2322 * Get parser options suitable for rendering the primary article wikitext
2323 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
2324 * @return mixed ParserOptions object or boolean false
2326 public function getParserOptions( $canonical = false ) {
2327 global $wgUser, $wgLanguageCode;
2329 if ( !$this->mParserOptions ||
$canonical ) {
2330 $user = !$canonical ?
$wgUser : new User
;
2331 $parserOptions = new ParserOptions( $user );
2332 $parserOptions->setTidy( true );
2333 $parserOptions->enableLimitReport();
2336 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
2337 return $parserOptions;
2339 $this->mParserOptions
= $parserOptions;
2341 // Clone to allow modifications of the return value without affecting cache
2342 return clone $this->mParserOptions
;
2346 * Get parser options suitable for rendering the primary article wikitext
2348 * @return ParserOptions
2350 public function makeParserOptions( User
$user ) {
2351 $options = ParserOptions
::newFromUser( $user );
2352 $options->enableLimitReport(); // show inclusion/loop reports
2353 $options->setTidy( true ); // fix bad HTML
2358 * Update all the appropriate counts in the category table, given that
2359 * we've added the categories $added and deleted the categories $deleted.
2361 * @param $added array The names of categories that were added
2362 * @param $deleted array The names of categories that were deleted
2364 public function updateCategoryCounts( $added, $deleted ) {
2365 $ns = $this->mTitle
->getNamespace();
2366 $dbw = wfGetDB( DB_MASTER
);
2368 # First make sure the rows exist. If one of the "deleted" ones didn't
2369 # exist, we might legitimately not create it, but it's simpler to just
2370 # create it and then give it a negative value, since the value is bogus
2373 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2374 $insertCats = array_merge( $added, $deleted );
2375 if ( !$insertCats ) {
2376 # Okay, nothing to do
2380 $insertRows = array();
2382 foreach ( $insertCats as $cat ) {
2383 $insertRows[] = array(
2384 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2388 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2390 $addFields = array( 'cat_pages = cat_pages + 1' );
2391 $removeFields = array( 'cat_pages = cat_pages - 1' );
2393 if ( $ns == NS_CATEGORY
) {
2394 $addFields[] = 'cat_subcats = cat_subcats + 1';
2395 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2396 } elseif ( $ns == NS_FILE
) {
2397 $addFields[] = 'cat_files = cat_files + 1';
2398 $removeFields[] = 'cat_files = cat_files - 1';
2405 array( 'cat_title' => $added ),
2414 array( 'cat_title' => $deleted ),
2421 * @deprecated since 1.19
2423 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2425 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2429 * @deprecated since 1.19
2431 public function viewUpdates() {
2433 return $this->doViewUpdates( $wgUser );
2437 * @deprecated since 1.19
2439 public function useParserCache( $oldid ) {
2441 return $this->isParserCacheUsed( $wgUser, $oldid );