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
{
20 public $mTitle = null;
25 public $mCounter = -1; // !< Integer (-1 means "not loaded")
26 public $mDataLoaded = false; // !< Boolean
27 public $mIsRedirect = false; // !< Boolean
28 public $mLatest = false; // !< Boolean
29 public $mPreparedEdit = false; // !< Array
30 public $mRedirectTarget = null; // !< Title object
31 public $mLastRevision = null; // !< Revision object
32 public $mTimestamp = ''; // !< String
33 public $mTouched = '19700101000000'; // !< String
38 * @var ParserOptions: ParserOptions object for $wgUser articles
40 public $mParserOptions;
43 * Constructor and clear the article
44 * @param $title Title Reference to a Title object.
46 public function __construct( Title
$title ) {
47 $this->mTitle
= $title;
51 * Constructor from a page id
53 * Always override this for all subclasses (until we use PHP with LSB)
55 * @param $id Int article ID to load
57 public static function newFromID( $id ) {
58 $t = Title
::newFromID( $id );
59 # @todo FIXME: Doesn't inherit right
60 return $t == null ?
null : new self( $t );
61 # return $t == null ? null : new static( $t ); // PHP 5.3
65 * If this page is a redirect, get its target
67 * The target will be fetched from the redirect table if possible.
68 * If this page doesn't have an entry there, call insertRedirect()
69 * @return Title|mixed object, or null if this page is not a redirect
71 public function getRedirectTarget() {
72 if ( !$this->mTitle
->isRedirect() ) {
76 if ( $this->mRedirectTarget
!== null ) {
77 return $this->mRedirectTarget
;
80 # Query the redirect table
81 $dbr = wfGetDB( DB_SLAVE
);
82 $row = $dbr->selectRow( 'redirect',
83 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
84 array( 'rd_from' => $this->getId() ),
88 // rd_fragment and rd_interwiki were added later, populate them if empty
89 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
90 return $this->mRedirectTarget
= Title
::makeTitle(
91 $row->rd_namespace
, $row->rd_title
,
92 $row->rd_fragment
, $row->rd_interwiki
);
95 # This page doesn't have an entry in the redirect table
96 return $this->mRedirectTarget
= $this->insertRedirect();
100 * Insert an entry for this page into the redirect table.
102 * Don't call this function directly unless you know what you're doing.
103 * @return Title object or null if not a redirect
105 public function insertRedirect() {
106 // recurse through to only get the final target
107 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
111 $this->insertRedirectEntry( $retval );
116 * Insert or update the redirect table entry for this page to indicate
117 * it redirects to $rt .
118 * @param $rt Title redirect target
120 public function insertRedirectEntry( $rt ) {
121 $dbw = wfGetDB( DB_MASTER
);
122 $dbw->replace( 'redirect', array( 'rd_from' ),
124 'rd_from' => $this->getId(),
125 'rd_namespace' => $rt->getNamespace(),
126 'rd_title' => $rt->getDBkey(),
127 'rd_fragment' => $rt->getFragment(),
128 'rd_interwiki' => $rt->getInterwiki(),
135 * Get the Title object or URL this page redirects to
137 * @return mixed false, Title of in-wiki target, or string with URL
139 public function followRedirect() {
140 return $this->getRedirectURL( $this->getRedirectTarget() );
144 * Get the Title object or URL to use for a redirect. We use Title
145 * objects for same-wiki, non-special redirects and URLs for everything
147 * @param $rt Title Redirect target
148 * @return mixed false, Title object of local target, or string with URL
150 public function getRedirectURL( $rt ) {
152 if ( $rt->getInterwiki() != '' ) {
153 if ( $rt->isLocal() ) {
154 // Offsite wikis need an HTTP redirect.
156 // This can be hard to reverse and may produce loops,
157 // so they may be disabled in the site configuration.
158 $source = $this->mTitle
->getFullURL( 'redirect=no' );
159 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
162 if ( $rt->getNamespace() == NS_SPECIAL
) {
163 // Gotta handle redirects to special pages differently:
164 // Fill the HTTP response "Location" header and ignore
165 // the rest of the page we're on.
167 // This can be hard to reverse, so they may be disabled.
168 if ( $rt->isSpecial( 'Userlogout' ) ) {
171 return $rt->getFullURL();
179 // No or invalid redirect
184 * Get the title object of the article
185 * @return Title object of this page
187 public function getTitle() {
188 return $this->mTitle
;
194 public function clear() {
195 $this->mDataLoaded
= false;
197 $this->mCounter
= -1; # Not loaded
198 $this->mRedirectTarget
= null; # Title object if set
199 $this->mLastRevision
= null; # Latest revision
200 $this->mTimestamp
= '';
201 $this->mTouched
= '19700101000000';
202 $this->mIsRedirect
= false;
203 $this->mLatest
= false;
204 $this->mPreparedEdit
= false;
208 * Get the text that needs to be saved in order to undo all revisions
209 * between $undo and $undoafter. Revisions must belong to the same page,
210 * must exist and must not be deleted
211 * @param $undo Revision
212 * @param $undoafter Revision Must be an earlier revision than $undo
213 * @return mixed string on success, false on failure
215 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
216 $cur_text = $this->getRawText();
217 if ( $cur_text === false ) {
218 return false; // no page
220 $undo_text = $undo->getText();
221 $undoafter_text = $undoafter->getText();
223 if ( $cur_text == $undo_text ) {
224 # No use doing a merge if it's just a straight revert.
225 return $undoafter_text;
230 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
238 * Return the list of revision fields that should be selected to create
241 public static function selectFields() {
258 * Fetch a page record with the given conditions
259 * @param $dbr DatabaseBase object
260 * @param $conditions Array
261 * @return mixed Database result resource, or false on failure
263 protected function pageData( $dbr, $conditions ) {
264 $fields = self
::selectFields();
266 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
268 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
270 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
276 * Fetch a page record matching the Title object's namespace and title
277 * using a sanitized title string
279 * @param $dbr DatabaseBase object
280 * @param $title Title object
281 * @return mixed Database result resource, or false on failure
283 public function pageDataFromTitle( $dbr, $title ) {
284 return $this->pageData( $dbr, array(
285 'page_namespace' => $title->getNamespace(),
286 'page_title' => $title->getDBkey() ) );
290 * Fetch a page record matching the requested ID
292 * @param $dbr DatabaseBase
294 * @return mixed Database result resource, or false on failure
296 public function pageDataFromId( $dbr, $id ) {
297 return $this->pageData( $dbr, array( 'page_id' => $id ) );
301 * Set the general counter, title etc data loaded from
304 * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
306 public function loadPageData( $data = 'fromdb' ) {
307 if ( $data === 'fromdb' ) {
308 $dbr = wfGetDB( DB_SLAVE
);
309 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
312 $lc = LinkCache
::singleton();
315 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
, $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
317 $this->mTitle
->mArticleID
= intval( $data->page_id
);
319 # Old-fashioned restrictions
320 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
322 $this->mCounter
= intval( $data->page_counter
);
323 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
324 $this->mIsRedirect
= intval( $data->page_is_redirect
);
325 $this->mLatest
= intval( $data->page_latest
);
327 $lc->addBadLinkObj( $this->mTitle
);
328 $this->mTitle
->mArticleID
= 0;
331 $this->mDataLoaded
= true;
335 * @return int Page ID
337 public function getId() {
338 return $this->mTitle
->getArticleID();
342 * @return bool Whether or not the page exists in the database
344 public function exists() {
345 return $this->getId() > 0;
349 * Check if this page is something we're going to be showing
350 * some sort of sensible content for. If we return false, page
351 * views (plain action=view) will return an HTTP 404 response,
352 * so spiders and robots can know they're following a bad link.
356 public function hasViewableContent() {
357 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
361 * @return int The view count for the page
363 public function getCount() {
364 if ( -1 == $this->mCounter
) {
365 $id = $this->getId();
370 $dbr = wfGetDB( DB_SLAVE
);
371 $this->mCounter
= $dbr->selectField( 'page',
373 array( 'page_id' => $id ),
379 return $this->mCounter
;
383 * Determine whether a page would be suitable for being counted as an
384 * article in the site_stats table based on the title & its content
386 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
387 * if false, the current database state will be used
390 public function isCountable( $editInfo = false ) {
391 global $wgArticleCountMethod;
393 if ( !$this->mTitle
->isContentPage() ) {
397 $text = $editInfo ?
$editInfo->pst
: false;
399 if ( $this->isRedirect( $text ) ) {
403 switch ( $wgArticleCountMethod ) {
407 if ( $text === false ) {
408 $text = $this->getRawText();
410 return strpos( $text, ',' ) !== false;
413 // ParserOutput::getLinks() is a 2D array of page links, so
414 // to be really correct we would need to recurse in the array
415 // but the main array should only have items in it if there are
417 return (bool)count( $editInfo->output
->getLinks() );
419 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
420 array( 'pl_from' => $this->getId() ), __METHOD__
);
426 * Tests if the article text represents a redirect
428 * @param $text mixed string containing article contents, or boolean
431 public function isRedirect( $text = false ) {
432 if ( $text === false ) {
433 if ( !$this->mDataLoaded
) {
434 $this->loadPageData();
437 return (bool)$this->mIsRedirect
;
439 return Title
::newFromRedirect( $text ) !== null;
444 * Loads everything except the text
445 * This isn't necessary for all uses, so it's only done if needed.
447 protected function loadLastEdit() {
448 if ( $this->mLastRevision
!== null ) {
449 return; // already loaded
452 # New or non-existent articles have no user information
453 $id = $this->getId();
458 $revision = Revision
::loadFromPageId( wfGetDB( DB_MASTER
), $id );
460 $this->setLastEdit( $revision );
465 * Set the latest revision
467 protected function setLastEdit( Revision
$revision ) {
468 $this->mLastRevision
= $revision;
469 $this->mTimestamp
= $revision->getTimestamp();
473 * Get the latest revision
474 * @return Revision|null
476 public function getRevision() {
477 $this->loadLastEdit();
478 if ( $this->mLastRevision
) {
479 return $this->mLastRevision
;
485 * Get the text of the current revision. No side-effects...
487 * @param $audience Integer: one of:
488 * Revision::FOR_PUBLIC to be displayed to all users
489 * Revision::FOR_THIS_USER to be displayed to $wgUser
490 * Revision::RAW get the text regardless of permissions
491 * @return String|false The text of the current revision
493 public function getText( $audience = Revision
::FOR_PUBLIC
) {
494 $this->loadLastEdit();
495 if ( $this->mLastRevision
) {
496 return $this->mLastRevision
->getText( $audience );
502 * Get the text of the current revision. No side-effects...
504 * @return String|false The text of the current revision
506 public function getRawText() {
507 $this->loadLastEdit();
508 if ( $this->mLastRevision
) {
509 return $this->mLastRevision
->getRawText();
515 * @return string MW timestamp of last article revision
517 public function getTimestamp() {
518 // Check if the field has been filled by ParserCache::get()
519 if ( !$this->mTimestamp
) {
520 $this->loadLastEdit();
522 return wfTimestamp( TS_MW
, $this->mTimestamp
);
526 * Set the page timestamp (use only to avoid DB queries)
527 * @param $ts string MW timestamp of last article revision
530 public function setTimestamp( $ts ) {
531 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
535 * @param $audience Integer: one of:
536 * Revision::FOR_PUBLIC to be displayed to all users
537 * Revision::FOR_THIS_USER to be displayed to $wgUser
538 * Revision::RAW get the text regardless of permissions
539 * @return int user ID for the user that made the last article revision
541 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
542 $this->loadLastEdit();
543 if ( $this->mLastRevision
) {
544 return $this->mLastRevision
->getUser( $audience );
551 * @param $audience Integer: one of:
552 * Revision::FOR_PUBLIC to be displayed to all users
553 * Revision::FOR_THIS_USER to be displayed to $wgUser
554 * Revision::RAW get the text regardless of permissions
555 * @return string username of the user that made the last article revision
557 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
558 $this->loadLastEdit();
559 if ( $this->mLastRevision
) {
560 return $this->mLastRevision
->getUserText( $audience );
567 * @param $audience Integer: one of:
568 * Revision::FOR_PUBLIC to be displayed to all users
569 * Revision::FOR_THIS_USER to be displayed to $wgUser
570 * Revision::RAW get the text regardless of permissions
571 * @return string Comment stored for the last article revision
573 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
574 $this->loadLastEdit();
575 if ( $this->mLastRevision
) {
576 return $this->mLastRevision
->getComment( $audience );
583 * Returns true if last revision was marked as "minor edit"
585 * @return boolean Minor edit indicator for the last article revision.
587 public function getMinorEdit() {
588 $this->loadLastEdit();
589 if ( $this->mLastRevision
) {
590 return $this->mLastRevision
->isMinor();
597 * Get a list of users who have edited this article, not including the user who made
598 * the most recent revision, which you can get from $article->getUser() if you want it
599 * @return UserArrayFromResult
601 public function getContributors() {
602 # @todo FIXME: This is expensive; cache this info somewhere.
604 $dbr = wfGetDB( DB_SLAVE
);
606 if ( $dbr->implicitGroupby() ) {
607 $realNameField = 'user_real_name';
609 $realNameField = 'FIRST(user_real_name) AS user_real_name';
612 $tables = array( 'revision', 'user' );
615 'rev_user as user_id',
616 'rev_user_text AS user_name',
618 'MAX(rev_timestamp) AS timestamp',
621 $conds = array( 'rev_page' => $this->getId() );
623 // The user who made the top revision gets credited as "this page was last edited by
624 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
625 $user = $this->getUser();
627 $conds[] = "rev_user != $user";
629 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
632 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
635 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
639 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
640 'ORDER BY' => 'timestamp DESC',
643 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
644 return new UserArrayFromResult( $res );
648 * Should the parser cache be used?
650 * @param $user User The relevant user
653 public function isParserCacheUsed( User
$user, $oldid ) {
654 global $wgEnableParserCache;
656 return $wgEnableParserCache
657 && $user->getStubThreshold() == 0
660 && !$this->mTitle
->isCssOrJsPage()
661 && !$this->mTitle
->isCssJsSubpage();
665 * Perform the actions of a page purging
667 public function doPurge() {
670 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
674 // Invalidate the cache
675 $this->mTitle
->invalidateCache();
679 // Commit the transaction before the purge is sent
680 $dbw = wfGetDB( DB_MASTER
);
684 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
688 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
689 if ( $this->getId() == 0 ) {
692 $text = $this->getRawText();
695 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
700 * Insert a new empty page record for this article.
701 * This *must* be followed up by creating a revision
702 * and running $this->updateRevisionOn( ... );
703 * or else the record will be left in a funky state.
704 * Best if all done inside a transaction.
706 * @param $dbw DatabaseBase
707 * @return int The newly created page_id key, or false if the title already existed
710 public function insertOn( $dbw ) {
711 wfProfileIn( __METHOD__
);
713 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
714 $dbw->insert( 'page', array(
715 'page_id' => $page_id,
716 'page_namespace' => $this->mTitle
->getNamespace(),
717 'page_title' => $this->mTitle
->getDBkey(),
719 'page_restrictions' => '',
720 'page_is_redirect' => 0, # Will set this shortly...
722 'page_random' => wfRandom(),
723 'page_touched' => $dbw->timestamp(),
724 'page_latest' => 0, # Fill this in shortly...
725 'page_len' => 0, # Fill this in shortly...
726 ), __METHOD__
, 'IGNORE' );
728 $affected = $dbw->affectedRows();
731 $newid = $dbw->insertId();
732 $this->mTitle
->resetArticleID( $newid );
734 wfProfileOut( __METHOD__
);
736 return $affected ?
$newid : false;
740 * Update the page record to point to a newly saved revision.
742 * @param $dbw DatabaseBase: object
743 * @param $revision Revision: For ID number, and text used to set
744 length and redirect status fields
745 * @param $lastRevision Integer: if given, will not overwrite the page field
746 * when different from the currently set value.
747 * Giving 0 indicates the new page flag should be set
749 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
750 * removing rows in redirect table.
751 * @return bool true on success, false on failure
754 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
755 wfProfileIn( __METHOD__
);
757 $text = $revision->getText();
758 $rt = Title
::newFromRedirectRecurse( $text );
760 $conditions = array( 'page_id' => $this->getId() );
762 if ( !is_null( $lastRevision ) ) {
763 # An extra check against threads stepping on each other
764 $conditions['page_latest'] = $lastRevision;
767 $dbw->update( 'page',
769 'page_latest' => $revision->getId(),
770 'page_touched' => $dbw->timestamp(),
771 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
772 'page_is_redirect' => $rt !== null ?
1 : 0,
773 'page_len' => strlen( $text ),
778 $result = $dbw->affectedRows() != 0;
780 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
783 wfProfileOut( __METHOD__
);
788 * Add row to the redirect table if this is a redirect, remove otherwise.
790 * @param $dbw DatabaseBase
791 * @param $redirectTitle Title object pointing to the redirect target,
792 * or NULL if this is not a redirect
793 * @param $lastRevIsRedirect If given, will optimize adding and
794 * removing rows in redirect table.
795 * @return bool true on success, false on failure
798 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
799 // Always update redirects (target link might have changed)
800 // Update/Insert if we don't know if the last revision was a redirect or not
801 // Delete if changing from redirect to non-redirect
802 $isRedirect = !is_null( $redirectTitle );
804 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
808 wfProfileIn( __METHOD__
);
810 $this->insertRedirectEntry( $redirectTitle );
812 // This is not a redirect, remove row from redirect table
813 $where = array( 'rd_from' => $this->getId() );
814 $dbw->delete( 'redirect', $where, __METHOD__
);
817 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
818 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
820 wfProfileOut( __METHOD__
);
822 return ( $dbw->affectedRows() != 0 );
826 * If the given revision is newer than the currently set page_latest,
827 * update the page record. Otherwise, do nothing.
829 * @param $dbw Database object
830 * @param $revision Revision object
833 public function updateIfNewerOn( $dbw, $revision ) {
834 wfProfileIn( __METHOD__
);
836 $row = $dbw->selectRow(
837 array( 'revision', 'page' ),
838 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
840 'page_id' => $this->getId(),
841 'page_latest=rev_id' ),
845 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
846 wfProfileOut( __METHOD__
);
849 $prev = $row->rev_id
;
850 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
852 # No or missing previous revision; mark the page as new
854 $lastRevIsRedirect = null;
857 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
859 wfProfileOut( __METHOD__
);
864 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
865 * @param $text String: new text of the section
866 * @param $summary String: new section's subject, only if $section is 'new'
867 * @param $edittime String: revision timestamp or null to use the current revision
868 * @return string Complete article text, or null if error
870 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
871 wfProfileIn( __METHOD__
);
873 if ( strval( $section ) == '' ) {
874 // Whole-page edit; let the whole text through
876 if ( is_null( $edittime ) ) {
877 $rev = Revision
::newFromTitle( $this->mTitle
);
879 $dbw = wfGetDB( DB_MASTER
);
880 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
884 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
885 $this->getId() . "; section: $section; edittime: $edittime)\n" );
886 wfProfileOut( __METHOD__
);
890 $oldtext = $rev->getText();
892 if ( $section == 'new' ) {
893 # Inserting a new section
894 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
895 $text = strlen( trim( $oldtext ) ) > 0
896 ?
"{$oldtext}\n\n{$subject}{$text}"
897 : "{$subject}{$text}";
899 # Replacing an existing section; roll out the big guns
902 $text = $wgParser->replaceSection( $oldtext, $section, $text );
906 wfProfileOut( __METHOD__
);
911 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
913 * @return Int updated $flags
915 function checkFlags( $flags ) {
916 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
917 if ( $this->mTitle
->getArticleID() ) {
918 $flags |
= EDIT_UPDATE
;
928 * Change an existing article or create a new article. Updates RC and all necessary caches,
929 * optionally via the deferred update array.
931 * @param $text String: new text
932 * @param $summary String: edit summary
933 * @param $flags Integer bitfield:
935 * Article is known or assumed to be non-existent, create a new one
937 * Article is known or assumed to be pre-existing, update it
939 * Mark this edit minor, if the user is allowed to do so
941 * Do not log the change in recentchanges
943 * Mark the edit a "bot" edit regardless of user rights
945 * Defer some of the updates until the end of index.php
947 * Fill in blank summaries with generated text where possible
949 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
950 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
951 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
952 * edit-already-exists error will be returned. These two conditions are also possible with
953 * auto-detection due to MediaWiki's performance-optimised locking strategy.
955 * @param $baseRevId the revision ID this edit was based off, if any
956 * @param $user User the user doing the edit
958 * @return Status object. Possible errors:
959 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
960 * edit-gone-missing: In update mode, but the article didn't exist
961 * edit-conflict: In update mode, the article changed unexpectedly
962 * edit-no-change: Warning that the text was the same as before
963 * edit-already-exists: In creation mode, but the article already exists
965 * Extensions may define additional errors.
967 * $return->value will contain an associative array with members as follows:
968 * new: Boolean indicating if the function attempted to create a new article
969 * revision: The revision object for the inserted revision, or null
971 * Compatibility note: this function previously returned a boolean value indicating success/failure
973 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
974 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
976 # Low-level sanity check
977 if ( $this->mTitle
->getText() === '' ) {
978 throw new MWException( 'Something is trying to edit an article with an empty title' );
981 wfProfileIn( __METHOD__
);
983 $user = is_null( $user ) ?
$wgUser : $user;
984 $status = Status
::newGood( array() );
986 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
987 $this->loadPageData();
989 $flags = $this->checkFlags( $flags );
991 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
992 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
994 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
996 if ( $status->isOK() ) {
997 $status->fatal( 'edit-hook-aborted' );
1000 wfProfileOut( __METHOD__
);
1004 # Silently ignore EDIT_MINOR if not allowed
1005 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1006 $bot = $flags & EDIT_FORCE_BOT
;
1008 $oldtext = $this->getRawText(); // current revision
1009 $oldsize = strlen( $oldtext );
1010 $oldcountable = $this->isCountable();
1012 # Provide autosummaries if one is not provided and autosummaries are enabled.
1013 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1014 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1017 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1018 $text = $editInfo->pst
;
1019 $newsize = strlen( $text );
1021 $dbw = wfGetDB( DB_MASTER
);
1022 $now = wfTimestampNow();
1023 $this->mTimestamp
= $now;
1025 if ( $flags & EDIT_UPDATE
) {
1026 # Update article, but only if changed.
1027 $status->value
['new'] = false;
1029 # Make sure the revision is either completely inserted or not inserted at all
1030 if ( !$wgDBtransactions ) {
1031 $userAbort = ignore_user_abort( true );
1034 $revision = new Revision( array(
1035 'page' => $this->getId(),
1036 'comment' => $summary,
1037 'minor_edit' => $isminor,
1039 'parent_id' => $this->mLatest
,
1040 'user' => $user->getId(),
1041 'user_text' => $user->getName(),
1045 $changed = ( strcmp( $text, $oldtext ) != 0 );
1048 if ( !$this->mLatest
) {
1049 # Article gone missing
1050 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1051 $status->fatal( 'edit-gone-missing' );
1053 wfProfileOut( __METHOD__
);
1058 $revisionId = $revision->insertOn( $dbw );
1062 # Note that we use $this->mLatest instead of fetching a value from the master DB
1063 # during the course of this function. This makes sure that EditPage can detect
1064 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1065 # before this function is called. A previous function used a separate query, this
1066 # creates a window where concurrent edits can cause an ignored edit conflict.
1067 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1070 /* Belated edit conflict! Run away!! */
1071 $status->fatal( 'edit-conflict' );
1073 # Delete the invalid revision if the DB is not transactional
1074 if ( !$wgDBtransactions ) {
1075 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1081 global $wgUseRCPatrol;
1082 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1083 # Update recentchanges
1084 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1085 # Mark as patrolled if the user can do so
1086 $patrolled = $wgUseRCPatrol && !count(
1087 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1088 # Add RC row to the DB
1089 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1090 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1091 $revisionId, $patrolled
1094 # Log auto-patrolled edits
1096 PatrolLog
::record( $rc, true );
1099 $user->incEditCount();
1104 if ( !$wgDBtransactions ) {
1105 ignore_user_abort( $userAbort );
1108 // Now that ignore_user_abort is restored, we can respond to fatal errors
1109 if ( !$status->isOK() ) {
1110 wfProfileOut( __METHOD__
);
1114 # Update links tables, site stats, etc.
1115 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1116 'oldcountable' => $oldcountable ) );
1119 $status->warning( 'edit-no-change' );
1121 // Keep the same revision ID, but do some updates on it
1122 $revisionId = $this->getLatest();
1123 // Update page_touched, this is usually implicit in the page update
1124 // Other cache updates are done in onArticleEdit()
1125 $this->mTitle
->invalidateCache();
1128 # Create new article
1129 $status->value
['new'] = true;
1133 # Add the page record; stake our claim on this title!
1134 # This will return false if the article already exists
1135 $newid = $this->insertOn( $dbw );
1137 if ( $newid === false ) {
1139 $status->fatal( 'edit-already-exists' );
1141 wfProfileOut( __METHOD__
);
1145 # Save the revision text...
1146 $revision = new Revision( array(
1148 'comment' => $summary,
1149 'minor_edit' => $isminor,
1151 'user' => $user->getId(),
1152 'user_text' => $user->getName(),
1155 $revisionId = $revision->insertOn( $dbw );
1157 $this->mTitle
->resetArticleID( $newid );
1158 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
1160 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
1162 # Update the page record with revision data
1163 $this->updateRevisionOn( $dbw, $revision, 0 );
1165 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1167 # Update recentchanges
1168 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1169 global $wgUseRCPatrol, $wgUseNPPatrol;
1171 # Mark as patrolled if the user can do so
1172 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1173 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1174 # Add RC row to the DB
1175 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1176 '', strlen( $text ), $revisionId, $patrolled );
1178 # Log auto-patrolled edits
1180 PatrolLog
::record( $rc, true );
1183 $user->incEditCount();
1186 # Update links, etc.
1187 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1189 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1190 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1193 # Do updates right now unless deferral was requested
1194 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1198 // Return the new revision (or null) to the caller
1199 $status->value
['revision'] = $revision;
1201 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1202 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1204 # Promote user to any groups they meet the criteria for
1205 $user->addAutopromoteOnceGroups( 'onEdit' );
1207 wfProfileOut( __METHOD__
);
1212 * Update the article's restriction field, and leave a log entry.
1214 * @param $limit Array: set of restriction keys
1215 * @param $reason String
1216 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1217 * @param $expiry Array: per restriction type expiration
1218 * @param $user User The user updating the restrictions
1219 * @return bool true on success
1221 public function updateRestrictions(
1222 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
1224 global $wgUser, $wgContLang;
1225 $user = is_null( $user ) ?
$wgUser : $user;
1227 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1229 $id = $this->mTitle
->getArticleID();
1232 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1236 if ( wfReadOnly() ) {
1237 wfDebug( "updateRestrictions failed: read-only\n" );
1241 if ( !$this->mTitle
->userCan( 'protect' ) ) {
1242 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1250 // Take this opportunity to purge out expired restrictions
1251 Title
::purgeExpiredRestrictions();
1253 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1254 # we expect a single selection, but the schema allows otherwise.
1256 $updated = self
::flattenRestrictions( $limit );
1259 foreach ( $restrictionTypes as $action ) {
1260 if ( isset( $expiry[$action] ) ) {
1261 # Get current restrictions on $action
1262 $aLimits = $this->mTitle
->getRestrictions( $action );
1263 $current[$action] = implode( '', $aLimits );
1264 # Are any actual restrictions being dealt with here?
1265 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
1267 # If something changed, we need to log it. Checking $aRChanged
1268 # assures that "unprotecting" a page that is not protected does
1269 # not log just because the expiry was "changed".
1270 if ( $aRChanged && $this->mTitle
->mRestrictionsExpiry
[$action] != $expiry[$action] ) {
1276 $current = self
::flattenRestrictions( $current );
1278 $changed = ( $changed ||
$current != $updated );
1279 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
1280 $protect = ( $updated != '' );
1282 # If nothing's changed, do nothing
1284 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1285 $dbw = wfGetDB( DB_MASTER
);
1287 # Prepare a null revision to be added to the history
1288 $modified = $current != '' && $protect;
1291 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1293 $comment_type = 'unprotectedarticle';
1296 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1298 # Only restrictions with the 'protect' right can cascade...
1299 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1300 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1302 # The schema allows multiple restrictions
1303 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1307 $cascade_description = '';
1310 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1314 $comment .= ": $reason";
1317 $editComment = $comment;
1318 $encodedExpiry = array();
1319 $protect_description = '';
1320 foreach ( $limit as $action => $restrictions ) {
1321 if ( !isset( $expiry[$action] ) )
1322 $expiry[$action] = $dbw->getInfinity();
1324 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1325 if ( $restrictions != '' ) {
1326 $protect_description .= "[$action=$restrictions] (";
1327 if ( $encodedExpiry[$action] != 'infinity' ) {
1328 $protect_description .= wfMsgForContent( 'protect-expiring',
1329 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1330 $wgContLang->date( $expiry[$action], false, false ) ,
1331 $wgContLang->time( $expiry[$action], false, false ) );
1333 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1336 $protect_description .= ') ';
1339 $protect_description = trim( $protect_description );
1341 if ( $protect_description && $protect ) {
1342 $editComment .= " ($protect_description)";
1346 $editComment .= "$cascade_description";
1349 # Update restrictions table
1350 foreach ( $limit as $action => $restrictions ) {
1351 if ( $restrictions != '' ) {
1352 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1353 array( 'pr_page' => $id,
1354 'pr_type' => $action,
1355 'pr_level' => $restrictions,
1356 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1357 'pr_expiry' => $encodedExpiry[$action]
1362 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1363 'pr_type' => $action ), __METHOD__
);
1367 # Insert a null revision
1368 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1369 $nullRevId = $nullRevision->insertOn( $dbw );
1371 $latest = $this->getLatest();
1372 # Update page record
1373 $dbw->update( 'page',
1375 'page_touched' => $dbw->timestamp(),
1376 'page_restrictions' => '',
1377 'page_latest' => $nullRevId
1378 ), array( /* WHERE */
1383 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1384 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1386 # Update the protection log
1387 $log = new LogPage( 'protect' );
1389 $params = array( $protect_description, $cascade ?
'cascade' : '' );
1390 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
1392 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1395 } # End "changed" check
1401 * Take an array of page restrictions and flatten it to a string
1402 * suitable for insertion into the page_restrictions field.
1403 * @param $limit Array
1406 protected static function flattenRestrictions( $limit ) {
1407 if ( !is_array( $limit ) ) {
1408 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1414 foreach ( $limit as $action => $restrictions ) {
1415 if ( $restrictions != '' ) {
1416 $bits[] = "$action=$restrictions";
1420 return implode( ':', $bits );
1424 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1426 public function isBigDeletion() {
1427 global $wgDeleteRevisionsLimit;
1429 if ( $wgDeleteRevisionsLimit ) {
1430 $revCount = $this->estimateRevisionCount();
1432 return $revCount > $wgDeleteRevisionsLimit;
1439 * @return int approximate revision count
1441 public function estimateRevisionCount() {
1442 $dbr = wfGetDB( DB_SLAVE
);
1444 // For an exact count...
1445 // return $dbr->selectField( 'revision', 'COUNT(*)',
1446 // array( 'rev_page' => $this->getId() ), __METHOD__ );
1447 return $dbr->estimateRowCount( 'revision', '*',
1448 array( 'rev_page' => $this->getId() ), __METHOD__
);
1452 * Get the last N authors
1453 * @param $num Integer: number of revisions to get
1454 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1455 * @return array Array of authors, duplicates not removed
1457 public function getLastNAuthors( $num, $revLatest = 0 ) {
1458 wfProfileIn( __METHOD__
);
1459 // First try the slave
1460 // If that doesn't have the latest revision, try the master
1462 $db = wfGetDB( DB_SLAVE
);
1465 $res = $db->select( array( 'page', 'revision' ),
1466 array( 'rev_id', 'rev_user_text' ),
1468 'page_namespace' => $this->mTitle
->getNamespace(),
1469 'page_title' => $this->mTitle
->getDBkey(),
1470 'rev_page = page_id'
1473 'ORDER BY' => 'rev_timestamp DESC',
1479 wfProfileOut( __METHOD__
);
1483 $row = $db->fetchObject( $res );
1485 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1486 $db = wfGetDB( DB_MASTER
);
1491 } while ( $continue );
1493 $authors = array( $row->rev_user_text
);
1495 foreach ( $res as $row ) {
1496 $authors[] = $row->rev_user_text
;
1499 wfProfileOut( __METHOD__
);
1504 * Back-end article deletion
1505 * Deletes the article with database consistency, writes logs, purges caches
1507 * @param $reason string delete reason for deletion log
1508 * @param suppress bitfield
1509 * Revision::DELETED_TEXT
1510 * Revision::DELETED_COMMENT
1511 * Revision::DELETED_USER
1512 * Revision::DELETED_RESTRICTED
1513 * @param $id int article ID
1514 * @param $commit boolean defaults to true, triggers transaction end
1515 * @param &$errors Array of errors to append to
1516 * @param $user User The relevant user
1517 * @return boolean true if successful
1519 public function doDeleteArticle(
1520 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1522 global $wgDeferredUpdateList, $wgUseTrackbacks, $wgUser;
1523 $user = is_null( $user ) ?
$wgUser : $user;
1525 wfDebug( __METHOD__
. "\n" );
1527 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1530 $dbw = wfGetDB( DB_MASTER
);
1531 $t = $this->mTitle
->getDBkey();
1532 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1534 if ( $t === '' ||
$id == 0 ) {
1538 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
1539 array_push( $wgDeferredUpdateList, $u );
1541 // Bitfields to further suppress the content
1544 // This should be 15...
1545 $bitfield |
= Revision
::DELETED_TEXT
;
1546 $bitfield |
= Revision
::DELETED_COMMENT
;
1547 $bitfield |
= Revision
::DELETED_USER
;
1548 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1550 $bitfield = 'rev_deleted';
1554 // For now, shunt the revision data into the archive table.
1555 // Text is *not* removed from the text table; bulk storage
1556 // is left intact to avoid breaking block-compression or
1557 // immutable storage schemes.
1559 // For backwards compatibility, note that some older archive
1560 // table entries will have ar_text and ar_flags fields still.
1562 // In the future, we may keep revisions and mark them with
1563 // the rev_deleted field, which is reserved for this purpose.
1564 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1566 'ar_namespace' => 'page_namespace',
1567 'ar_title' => 'page_title',
1568 'ar_comment' => 'rev_comment',
1569 'ar_user' => 'rev_user',
1570 'ar_user_text' => 'rev_user_text',
1571 'ar_timestamp' => 'rev_timestamp',
1572 'ar_minor_edit' => 'rev_minor_edit',
1573 'ar_rev_id' => 'rev_id',
1574 'ar_text_id' => 'rev_text_id',
1575 'ar_text' => '\'\'', // Be explicit to appease
1576 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1577 'ar_len' => 'rev_len',
1578 'ar_page_id' => 'page_id',
1579 'ar_deleted' => $bitfield
1582 'page_id = rev_page'
1586 # Delete restrictions for it
1587 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1589 # Now that it's safely backed up, delete it
1590 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1591 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1598 # Fix category table counts
1600 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1602 foreach ( $res as $row ) {
1603 $cats [] = $row->cl_to
;
1606 $this->updateCategoryCounts( array(), $cats );
1608 # If using cascading deletes, we can skip some explicit deletes
1609 if ( !$dbw->cascadingDeletes() ) {
1610 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
1612 if ( $wgUseTrackbacks )
1613 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
1615 # Delete outgoing links
1616 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1617 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1618 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1619 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1620 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1621 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1622 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
1623 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
1626 # If using cleanup triggers, we can skip some manual deletes
1627 if ( !$dbw->cleanupTriggers() ) {
1628 # Clean up recentchanges entries...
1629 $dbw->delete( 'recentchanges',
1630 array( 'rc_type != ' . RC_LOG
,
1631 'rc_namespace' => $this->mTitle
->getNamespace(),
1632 'rc_title' => $this->mTitle
->getDBkey() ),
1634 $dbw->delete( 'recentchanges',
1635 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
1640 self
::onArticleDelete( $this->mTitle
);
1642 # Clear the cached article id so the interface doesn't act like we exist
1643 $this->mTitle
->resetArticleID( 0 );
1645 # Log the deletion, if the page was suppressed, log it at Oversight instead
1646 $logtype = $suppress ?
'suppress' : 'delete';
1647 $log = new LogPage( $logtype );
1649 # Make sure logging got through
1650 $log->addEntry( 'delete', $this->mTitle
, $reason, array() );
1656 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1661 * Roll back the most recent consecutive set of edits to a page
1662 * from the same user; fails if there are no eligible edits to
1663 * roll back to, e.g. user is the sole contributor. This function
1664 * performs permissions checks on $user, then calls commitRollback()
1665 * to do the dirty work
1667 * @param $fromP String: Name of the user whose edits to rollback.
1668 * @param $summary String: Custom summary. Set to default summary if empty.
1669 * @param $token String: Rollback token.
1670 * @param $bot Boolean: If true, mark all reverted edits as bot.
1672 * @param $resultDetails Array: contains result-specific array of additional values
1673 * 'alreadyrolled' : 'current' (rev)
1674 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1676 * @param $user User The user performing the rollback
1677 * @return array of errors, each error formatted as
1678 * array(messagekey, param1, param2, ...).
1679 * On success, the array is empty. This array can also be passed to
1680 * OutputPage::showPermissionsErrorPage().
1682 public function doRollback(
1683 $fromP, $summary, $token, $bot, &$resultDetails, User
$user = null
1686 $user = is_null( $user ) ?
$wgUser : $user;
1688 $resultDetails = null;
1691 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
1692 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
1693 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1695 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
1696 $errors[] = array( 'sessionfailure' );
1699 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
1700 $errors[] = array( 'actionthrottledtext' );
1703 # If there were errors, bail out now
1704 if ( !empty( $errors ) ) {
1708 return $this->commitRollback( $user, $fromP, $summary, $bot, $resultDetails );
1712 * Backend implementation of doRollback(), please refer there for parameter
1713 * and return value documentation
1715 * NOTE: This function does NOT check ANY permissions, it just commits the
1716 * rollback to the DB Therefore, you should only call this function direct-
1717 * ly if you want to use custom permissions checks. If you don't, use
1718 * doRollback() instead.
1719 * @param $fromP String: Name of the user whose edits to rollback.
1720 * @param $summary String: Custom summary. Set to default summary if empty.
1721 * @param $bot Boolean: If true, mark all reverted edits as bot.
1723 * @param $resultDetails Array: contains result-specific array of additional values
1724 * @param $guser User The user performing the rollback
1726 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser = null ) {
1727 global $wgUseRCPatrol, $wgUser, $wgContLang;
1728 $guser = is_null( $guser ) ?
$wgUser : $guser;
1730 $dbw = wfGetDB( DB_MASTER
);
1732 if ( wfReadOnly() ) {
1733 return array( array( 'readonlytext' ) );
1736 # Get the last editor
1737 $current = Revision
::newFromTitle( $this->mTitle
);
1738 if ( is_null( $current ) ) {
1739 # Something wrong... no page?
1740 return array( array( 'notanarticle' ) );
1743 $from = str_replace( '_', ' ', $fromP );
1744 # User name given should match up with the top revision.
1745 # If the user was deleted then $from should be empty.
1746 if ( $from != $current->getUserText() ) {
1747 $resultDetails = array( 'current' => $current );
1748 return array( array( 'alreadyrolled',
1749 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
1750 htmlspecialchars( $fromP ),
1751 htmlspecialchars( $current->getUserText() )
1755 # Get the last edit not by this guy...
1756 # Note: these may not be public values
1757 $user = intval( $current->getRawUser() );
1758 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1759 $s = $dbw->selectRow( 'revision',
1760 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1761 array( 'rev_page' => $current->getPage(),
1762 "rev_user != {$user} OR rev_user_text != {$user_text}"
1764 array( 'USE INDEX' => 'page_timestamp',
1765 'ORDER BY' => 'rev_timestamp DESC' )
1767 if ( $s === false ) {
1768 # No one else ever edited this page
1769 return array( array( 'cantrollback' ) );
1770 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
1771 # Only admins can see this text
1772 return array( array( 'notvisiblerev' ) );
1776 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1777 # Mark all reverted edits as bot
1781 if ( $wgUseRCPatrol ) {
1782 # Mark all reverted edits as patrolled
1783 $set['rc_patrolled'] = 1;
1786 if ( count( $set ) ) {
1787 $dbw->update( 'recentchanges', $set,
1789 'rc_cur_id' => $current->getPage(),
1790 'rc_user_text' => $current->getUserText(),
1791 "rc_timestamp > '{$s->rev_timestamp}'",
1796 # Generate the edit summary if necessary
1797 $target = Revision
::newFromId( $s->rev_id
);
1798 if ( empty( $summary ) ) {
1799 if ( $from == '' ) { // no public user name
1800 $summary = wfMsgForContent( 'revertpage-nouser' );
1802 $summary = wfMsgForContent( 'revertpage' );
1806 # Allow the custom summary to use the same args as the default message
1808 $target->getUserText(), $from, $s->rev_id
,
1809 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
1810 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1812 $summary = wfMsgReplaceArgs( $summary, $args );
1815 $flags = EDIT_UPDATE
;
1817 if ( $guser->isAllowed( 'minoredit' ) ) {
1818 $flags |
= EDIT_MINOR
;
1821 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1822 $flags |
= EDIT_FORCE_BOT
;
1825 # Actually store the edit
1826 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1827 if ( !empty( $status->value
['revision'] ) ) {
1828 $revId = $status->value
['revision']->getId();
1833 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1835 $resultDetails = array(
1836 'summary' => $summary,
1837 'current' => $current,
1838 'target' => $target,
1846 * Do standard deferred updates after page view
1847 * @param $user User The relevant user
1849 public function doViewUpdates( User
$user ) {
1850 global $wgDeferredUpdateList, $wgDisableCounters;
1851 if ( wfReadOnly() ) {
1855 # Don't update page view counters on views from bot users (bug 14044)
1856 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->getId() ) {
1857 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getId() );
1858 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
1861 # Update newtalk / watchlist notification status
1862 $user->clearNotification( $this->mTitle
);
1866 * Prepare text which is about to be saved.
1867 * Returns a stdclass with source, pst and output members
1869 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1870 global $wgParser, $wgUser;
1871 $user = is_null( $user ) ?
$wgUser : $user;
1872 // @TODO fixme: check $user->getId() here???
1873 if ( $this->mPreparedEdit
1874 && $this->mPreparedEdit
->newText
== $text
1875 && $this->mPreparedEdit
->revid
== $revid
1878 return $this->mPreparedEdit
;
1881 $popts = ParserOptions
::newFromUser( $user );
1882 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1884 $edit = (object)array();
1885 $edit->revid
= $revid;
1886 $edit->newText
= $text;
1887 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
1888 $edit->popts
= $this->getParserOptions( true );
1889 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1890 $edit->oldText
= $this->getRawText();
1892 $this->mPreparedEdit
= $edit;
1898 * Do standard deferred updates after page edit.
1899 * Update links tables, site stats, search index and message cache.
1900 * Purges pages that include this page if the text was changed here.
1901 * Every 100th edit, prune the recent changes table.
1904 * @param $revision Revision object
1905 * @param $user User object that did the revision
1906 * @param $options Array of options, following indexes are used:
1907 * - changed: boolean, whether the revision changed the content (default true)
1908 * - created: boolean, whether the revision created the page (default false)
1909 * - oldcountable: boolean or null (default null):
1910 * - boolean: whether the page was counted as an article before that
1911 * revision, only used in changed is true and created is false
1912 * - null: don't change the article count
1914 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1915 global $wgDeferredUpdateList, $wgEnableParserCache;
1917 wfProfileIn( __METHOD__
);
1919 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1920 $text = $revision->getText();
1923 # Be careful not to double-PST: $text is usually already PST-ed once
1924 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1925 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1926 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1928 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1929 $editInfo = $this->mPreparedEdit
;
1932 # Save it to the parser cache
1933 if ( $wgEnableParserCache ) {
1934 $parserCache = ParserCache
::singleton();
1935 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1938 # Update the links tables
1939 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1942 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1944 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1945 if ( 0 == mt_rand( 0, 99 ) ) {
1946 // Flush old entries from the `recentchanges` table; we do this on
1947 // random requests so as to avoid an increase in writes for no good reason
1950 $dbw = wfGetDB( DB_MASTER
);
1951 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1954 array( "rc_timestamp < '$cutoff'" ),
1960 $id = $this->getId();
1961 $title = $this->mTitle
->getPrefixedDBkey();
1962 $shortTitle = $this->mTitle
->getDBkey();
1965 wfProfileOut( __METHOD__
);
1969 if ( !$options['changed'] ) {
1972 } elseif ( $options['created'] ) {
1973 $good = (int)$this->isCountable( $editInfo );
1975 } elseif ( $options['oldcountable'] !== null ) {
1976 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1983 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
1984 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
1986 # If this is another user's talk page, update newtalk.
1987 # Don't do this if $options['changed'] = false (null-edits) nor if
1988 # it's a minor edit and the user doesn't want notifications for those.
1989 if ( $options['changed']
1990 && $this->mTitle
->getNamespace() == NS_USER_TALK
1991 && $shortTitle != $user->getTitleKey()
1992 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1994 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1995 $other = User
::newFromName( $shortTitle, false );
1997 wfDebug( __METHOD__
. ": invalid username\n" );
1998 } elseif ( User
::isIP( $shortTitle ) ) {
1999 // An anonymous user
2000 $other->setNewtalk( true );
2001 } elseif ( $other->isLoggedIn() ) {
2002 $other->setNewtalk( true );
2004 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2009 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2010 MessageCache
::singleton()->replace( $shortTitle, $text );
2013 if( $options['created'] ) {
2014 self
::onArticleCreate( $this->mTitle
);
2016 self
::onArticleEdit( $this->mTitle
);
2019 wfProfileOut( __METHOD__
);
2023 * Perform article updates on a special page creation.
2025 * @param $rev Revision object
2027 * @todo This is a shitty interface function. Kill it and replace the
2028 * other shitty functions like doEditUpdates and such so it's not needed
2030 * @deprecated since 1.19, use doEditUpdates()
2032 public function createUpdates( $rev ) {
2034 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2038 * This function is called right before saving the wikitext,
2039 * so we can do things like signatures and links-in-context.
2041 * @param $text String article contents
2042 * @param $user User object: user doing the edit
2043 * @param $popts ParserOptions object: parser options, default options for
2044 * the user loaded if null given
2045 * @return string article contents with altered wikitext markup (signatures
2046 * converted, {{subst:}}, templates, etc.)
2048 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2049 global $wgParser, $wgUser;
2050 $user = is_null( $user ) ?
$wgUser : $user;
2052 if ( $popts === null ) {
2053 $popts = ParserOptions
::newFromUser( $user );
2056 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2060 * Loads page_touched and returns a value indicating if it should be used
2061 * @return boolean true if not a redirect
2063 public function checkTouched() {
2064 if ( !$this->mDataLoaded
) {
2065 $this->loadPageData();
2068 return !$this->mIsRedirect
;
2072 * Get the page_touched field
2073 * @return string containing GMT timestamp
2075 public function getTouched() {
2076 if ( !$this->mDataLoaded
) {
2077 $this->loadPageData();
2080 return $this->mTouched
;
2084 * Get the page_latest field
2085 * @return integer rev_id of current revision
2087 public function getLatest() {
2088 if ( !$this->mDataLoaded
) {
2089 $this->loadPageData();
2092 return (int)$this->mLatest
;
2096 * Edit an article without doing all that other stuff
2097 * The article must already exist; link tables etc
2098 * are not updated, caches are not flushed.
2100 * @param $text String: text submitted
2101 * @param $user User The relevant user
2102 * @param $comment String: comment submitted
2103 * @param $minor Boolean: whereas it's a minor modification
2105 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2106 wfProfileIn( __METHOD__
);
2108 $dbw = wfGetDB( DB_MASTER
);
2109 $revision = new Revision( array(
2110 'page' => $this->getId(),
2112 'comment' => $comment,
2113 'minor_edit' => $minor ?
1 : 0,
2115 $revision->insertOn( $dbw );
2116 $this->updateRevisionOn( $dbw, $revision );
2118 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2120 wfProfileOut( __METHOD__
);
2124 * The onArticle*() functions are supposed to be a kind of hooks
2125 * which should be called whenever any of the specified actions
2128 * This is a good place to put code to clear caches, for instance.
2130 * This is called on page move and undelete, as well as edit
2132 * @param $title Title object
2134 public static function onArticleCreate( $title ) {
2135 # Update existence markers on article/talk tabs...
2136 if ( $title->isTalkPage() ) {
2137 $other = $title->getSubjectPage();
2139 $other = $title->getTalkPage();
2142 $other->invalidateCache();
2143 $other->purgeSquid();
2145 $title->touchLinks();
2146 $title->purgeSquid();
2147 $title->deleteTitleProtection();
2151 * Clears caches when article is deleted
2153 * @param $title Title
2155 public static function onArticleDelete( $title ) {
2156 # Update existence markers on article/talk tabs...
2157 if ( $title->isTalkPage() ) {
2158 $other = $title->getSubjectPage();
2160 $other = $title->getTalkPage();
2163 $other->invalidateCache();
2164 $other->purgeSquid();
2166 $title->touchLinks();
2167 $title->purgeSquid();
2170 HTMLFileCache
::clearFileCache( $title );
2173 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2174 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2178 if ( $title->getNamespace() == NS_FILE
) {
2179 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2180 $update->doUpdate();
2184 if ( $title->getNamespace() == NS_USER_TALK
) {
2185 $user = User
::newFromName( $title->getText(), false );
2186 $user->setNewtalk( false );
2190 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2194 * Purge caches on page update etc
2196 * @param $title Title object
2197 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2199 public static function onArticleEdit( $title ) {
2200 global $wgDeferredUpdateList;
2202 // Invalidate caches of articles which include this page
2203 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
2205 // Invalidate the caches of all pages which redirect here
2206 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
2208 # Purge squid for this page only
2209 $title->purgeSquid();
2211 # Clear file cache for this page only
2212 HTMLFileCache
::clearFileCache( $title );
2218 * Return a list of templates used by this article.
2219 * Uses the templatelinks table
2221 * @return Array of Title objects
2223 public function getUsedTemplates() {
2225 $id = $this->mTitle
->getArticleID();
2231 $dbr = wfGetDB( DB_SLAVE
);
2232 $res = $dbr->select( array( 'templatelinks' ),
2233 array( 'tl_namespace', 'tl_title' ),
2234 array( 'tl_from' => $id ),
2237 if ( $res !== false ) {
2238 foreach ( $res as $row ) {
2239 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2247 * Returns a list of hidden categories this page is a member of.
2248 * Uses the page_props and categorylinks tables.
2250 * @return Array of Title objects
2252 public function getHiddenCategories() {
2254 $id = $this->mTitle
->getArticleID();
2260 $dbr = wfGetDB( DB_SLAVE
);
2261 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2263 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2264 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2267 if ( $res !== false ) {
2268 foreach ( $res as $row ) {
2269 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2277 * Return an applicable autosummary if one exists for the given edit.
2278 * @param $oldtext String: the previous text of the page.
2279 * @param $newtext String: The submitted text of the page.
2280 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2281 * @return string An appropriate autosummary, or an empty string.
2283 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2286 # Decide what kind of autosummary is needed.
2288 # Redirect autosummaries
2289 $ot = Title
::newFromRedirect( $oldtext );
2290 $rt = Title
::newFromRedirect( $newtext );
2292 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2293 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2296 # New page autosummaries
2297 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2298 # If they're making a new article, give its text, truncated, in the summary.
2300 $truncatedtext = $wgContLang->truncate(
2301 str_replace( "\n", ' ', $newtext ),
2302 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2304 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2307 # Blanking autosummaries
2308 if ( $oldtext != '' && $newtext == '' ) {
2309 return wfMsgForContent( 'autosumm-blank' );
2310 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2311 # Removing more than 90% of the article
2313 $truncatedtext = $wgContLang->truncate(
2315 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2317 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2320 # If we reach this point, there's no applicable autosummary for our case, so our
2321 # autosummary is empty.
2326 * Get parser options suitable for rendering the primary article wikitext
2327 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
2328 * @return mixed ParserOptions object or boolean false
2330 public function getParserOptions( $canonical = false ) {
2331 global $wgUser, $wgLanguageCode;
2333 if ( !$this->mParserOptions ||
$canonical ) {
2334 $user = !$canonical ?
$wgUser : new User
;
2335 $parserOptions = new ParserOptions( $user );
2336 $parserOptions->setTidy( true );
2337 $parserOptions->enableLimitReport();
2340 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
2341 return $parserOptions;
2343 $this->mParserOptions
= $parserOptions;
2345 // Clone to allow modifications of the return value without affecting cache
2346 return clone $this->mParserOptions
;
2350 * Get parser options suitable for rendering the primary article wikitext
2352 * @return ParserOptions
2354 public function makeParserOptions( User
$user ) {
2355 $options = ParserOptions
::newFromUser( $user );
2356 $options->enableLimitReport(); // show inclusion/loop reports
2357 $options->setTidy( true ); // fix bad HTML
2362 * Update all the appropriate counts in the category table, given that
2363 * we've added the categories $added and deleted the categories $deleted.
2365 * @param $added array The names of categories that were added
2366 * @param $deleted array The names of categories that were deleted
2368 public function updateCategoryCounts( $added, $deleted ) {
2369 $ns = $this->mTitle
->getNamespace();
2370 $dbw = wfGetDB( DB_MASTER
);
2372 # First make sure the rows exist. If one of the "deleted" ones didn't
2373 # exist, we might legitimately not create it, but it's simpler to just
2374 # create it and then give it a negative value, since the value is bogus
2377 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2378 $insertCats = array_merge( $added, $deleted );
2379 if ( !$insertCats ) {
2380 # Okay, nothing to do
2384 $insertRows = array();
2386 foreach ( $insertCats as $cat ) {
2387 $insertRows[] = array(
2388 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2392 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2394 $addFields = array( 'cat_pages = cat_pages + 1' );
2395 $removeFields = array( 'cat_pages = cat_pages - 1' );
2397 if ( $ns == NS_CATEGORY
) {
2398 $addFields[] = 'cat_subcats = cat_subcats + 1';
2399 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2400 } elseif ( $ns == NS_FILE
) {
2401 $addFields[] = 'cat_files = cat_files + 1';
2402 $removeFields[] = 'cat_files = cat_files - 1';
2409 array( 'cat_title' => $added ),
2418 array( 'cat_title' => $deleted ),
2425 * @deprecated since 1.19
2427 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2429 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2433 * @deprecated since 1.19
2435 public function viewUpdates() {
2437 return $this->doViewUpdates( $wgUser );
2441 * @deprecated since 1.19
2443 public function useParserCache( $oldid ) {
2445 return $this->isParserCacheUsed( $wgUser, $oldid );