3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
8 * Class representing a MediaWiki article and history.
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
13 * @internal documentation reviewed 15 Mar 2010
15 class WikiPage
extends Page
{
19 public $mTitle = null;
24 public $mCounter = -1; // !< Integer (-1 means "not loaded")
25 public $mDataLoaded = false; // !< Boolean
26 public $mIsRedirect = false; // !< Boolean
27 public $mLatest = false; // !< Boolean
28 public $mPreparedEdit = false; // !< Array
29 public $mRedirectTarget = null; // !< Title object
30 public $mLastRevision = null; // !< Revision object
31 public $mTimestamp = ''; // !< String
32 public $mTouched = '19700101000000'; // !< String
36 * Constructor and clear the article
37 * @param $title Title Reference to a Title object.
39 public function __construct( Title
$title ) {
40 $this->mTitle
= $title;
44 * Create a WikiPage object of the appropriate class for the given title.
47 * @return WikiPage object of the appropriate type
49 public static function factory( Title
$title ) {
50 $ns = $title->getNamespace();
52 if ( $ns == NS_MEDIA
) {
53 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
54 } elseif ( $ns < 0 ) {
55 throw new MWException( "Invalid or virtual namespace $ns given." );
60 $page = new WikiFilePage( $title );
63 $page = new WikiCategoryPage( $title );
66 $page = new WikiPage( $title );
73 * Constructor from a page id
75 * @param $id Int article ID to load
79 public static function newFromID( $id ) {
80 $t = Title
::newFromID( $id );
82 return self
::factory( $t );
88 * Returns overrides for action handlers.
89 * Classes listed here will be used instead of the default one when
90 * (and only when) $wgActions[$action] === true. This allows subclasses
91 * to override the default behavior.
93 * @todo: move this UI stuff somewhere else
97 public function getActionOverrides() {
102 * If this page is a redirect, get its target
104 * The target will be fetched from the redirect table if possible.
105 * If this page doesn't have an entry there, call insertRedirect()
106 * @return Title|mixed object, or null if this page is not a redirect
108 public function getRedirectTarget() {
109 if ( !$this->mTitle
->isRedirect() ) {
113 if ( $this->mRedirectTarget
!== null ) {
114 return $this->mRedirectTarget
;
117 # Query the redirect table
118 $dbr = wfGetDB( DB_SLAVE
);
119 $row = $dbr->selectRow( 'redirect',
120 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
121 array( 'rd_from' => $this->getId() ),
125 // rd_fragment and rd_interwiki were added later, populate them if empty
126 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
127 return $this->mRedirectTarget
= Title
::makeTitle(
128 $row->rd_namespace
, $row->rd_title
,
129 $row->rd_fragment
, $row->rd_interwiki
);
132 # This page doesn't have an entry in the redirect table
133 return $this->mRedirectTarget
= $this->insertRedirect();
137 * Insert an entry for this page into the redirect table.
139 * Don't call this function directly unless you know what you're doing.
140 * @return Title object or null if not a redirect
142 public function insertRedirect() {
143 // recurse through to only get the final target
144 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
148 $this->insertRedirectEntry( $retval );
153 * Insert or update the redirect table entry for this page to indicate
154 * it redirects to $rt .
155 * @param $rt Title redirect target
157 public function insertRedirectEntry( $rt ) {
158 $dbw = wfGetDB( DB_MASTER
);
159 $dbw->replace( 'redirect', array( 'rd_from' ),
161 'rd_from' => $this->getId(),
162 'rd_namespace' => $rt->getNamespace(),
163 'rd_title' => $rt->getDBkey(),
164 'rd_fragment' => $rt->getFragment(),
165 'rd_interwiki' => $rt->getInterwiki(),
172 * Get the Title object or URL this page redirects to
174 * @return mixed false, Title of in-wiki target, or string with URL
176 public function followRedirect() {
177 return $this->getRedirectURL( $this->getRedirectTarget() );
181 * Get the Title object or URL to use for a redirect. We use Title
182 * objects for same-wiki, non-special redirects and URLs for everything
184 * @param $rt Title Redirect target
185 * @return mixed false, Title object of local target, or string with URL
187 public function getRedirectURL( $rt ) {
189 if ( $rt->getInterwiki() != '' ) {
190 if ( $rt->isLocal() ) {
191 // Offsite wikis need an HTTP redirect.
193 // This can be hard to reverse and may produce loops,
194 // so they may be disabled in the site configuration.
195 $source = $this->mTitle
->getFullURL( 'redirect=no' );
196 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
199 if ( $rt->getNamespace() == NS_SPECIAL
) {
200 // Gotta handle redirects to special pages differently:
201 // Fill the HTTP response "Location" header and ignore
202 // the rest of the page we're on.
204 // This can be hard to reverse, so they may be disabled.
205 if ( $rt->isSpecial( 'Userlogout' ) ) {
208 return $rt->getFullURL();
216 // No or invalid redirect
221 * Get the title object of the article
222 * @return Title object of this page
224 public function getTitle() {
225 return $this->mTitle
;
231 public function clear() {
232 $this->mDataLoaded
= false;
234 $this->mCounter
= -1; # Not loaded
235 $this->mRedirectTarget
= null; # Title object if set
236 $this->mLastRevision
= null; # Latest revision
237 $this->mTimestamp
= '';
238 $this->mTouched
= '19700101000000';
239 $this->mIsRedirect
= false;
240 $this->mLatest
= false;
241 $this->mPreparedEdit
= false;
245 * Get the text that needs to be saved in order to undo all revisions
246 * between $undo and $undoafter. Revisions must belong to the same page,
247 * must exist and must not be deleted
248 * @param $undo Revision
249 * @param $undoafter Revision Must be an earlier revision than $undo
250 * @return mixed string on success, false on failure
252 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
253 $cur_text = $this->getRawText();
254 if ( $cur_text === false ) {
255 return false; // no page
257 $undo_text = $undo->getText();
258 $undoafter_text = $undoafter->getText();
260 if ( $cur_text == $undo_text ) {
261 # No use doing a merge if it's just a straight revert.
262 return $undoafter_text;
267 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
275 * Return the list of revision fields that should be selected to create
280 public static function selectFields() {
297 * Fetch a page record with the given conditions
298 * @param $dbr DatabaseBase object
299 * @param $conditions Array
300 * @return mixed Database result resource, or false on failure
302 protected function pageData( $dbr, $conditions ) {
303 $fields = self
::selectFields();
305 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
307 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
309 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
315 * Fetch a page record matching the Title object's namespace and title
316 * using a sanitized title string
318 * @param $dbr DatabaseBase object
319 * @param $title Title object
320 * @return mixed Database result resource, or false on failure
322 public function pageDataFromTitle( $dbr, $title ) {
323 return $this->pageData( $dbr, array(
324 'page_namespace' => $title->getNamespace(),
325 'page_title' => $title->getDBkey() ) );
329 * Fetch a page record matching the requested ID
331 * @param $dbr DatabaseBase
333 * @return mixed Database result resource, or false on failure
335 public function pageDataFromId( $dbr, $id ) {
336 return $this->pageData( $dbr, array( 'page_id' => $id ) );
340 * Set the general counter, title etc data loaded from
343 * @param $data Object|String One of the following:
344 * A DB query result object or...
345 * "fromdb" to get from a slave DB or...
346 * "fromdbmaster" to get from the master DB
349 public function loadPageData( $data = 'fromdb' ) {
350 if ( $data === 'fromdbmaster' ) {
351 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
352 } elseif ( $data === 'fromdb' ) { // slave
353 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
354 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
355 # Note that DB also stores the master position in the session and checks it.
356 $touched = $this->getCachedLastEditTime();
357 if ( $touched ) { // key set
358 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
359 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
364 $lc = LinkCache
::singleton();
367 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
369 $this->mTitle
->loadFromRow( $data );
371 # Old-fashioned restrictions
372 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
374 $this->mCounter
= intval( $data->page_counter
);
375 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
376 $this->mIsRedirect
= intval( $data->page_is_redirect
);
377 $this->mLatest
= intval( $data->page_latest
);
379 $lc->addBadLinkObj( $this->mTitle
);
381 $this->mTitle
->loadFromRow( false );
384 $this->mDataLoaded
= true;
388 * @return int Page ID
390 public function getId() {
391 return $this->mTitle
->getArticleID();
395 * @return bool Whether or not the page exists in the database
397 public function exists() {
398 return $this->getId() > 0;
402 * Check if this page is something we're going to be showing
403 * some sort of sensible content for. If we return false, page
404 * views (plain action=view) will return an HTTP 404 response,
405 * so spiders and robots can know they're following a bad link.
409 public function hasViewableContent() {
410 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
414 * @return int The view count for the page
416 public function getCount() {
417 if ( -1 == $this->mCounter
) {
418 $id = $this->getId();
423 $dbr = wfGetDB( DB_SLAVE
);
424 $this->mCounter
= $dbr->selectField( 'page',
426 array( 'page_id' => $id ),
432 return $this->mCounter
;
436 * Determine whether a page would be suitable for being counted as an
437 * article in the site_stats table based on the title & its content
439 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
440 * if false, the current database state will be used
443 public function isCountable( $editInfo = false ) {
444 global $wgArticleCountMethod;
446 if ( !$this->mTitle
->isContentPage() ) {
450 $text = $editInfo ?
$editInfo->pst
: false;
452 if ( $this->isRedirect( $text ) ) {
456 switch ( $wgArticleCountMethod ) {
460 if ( $text === false ) {
461 $text = $this->getRawText();
463 return strpos( $text, ',' ) !== false;
466 // ParserOutput::getLinks() is a 2D array of page links, so
467 // to be really correct we would need to recurse in the array
468 // but the main array should only have items in it if there are
470 return (bool)count( $editInfo->output
->getLinks() );
472 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
473 array( 'pl_from' => $this->getId() ), __METHOD__
);
479 * Tests if the article text represents a redirect
481 * @param $text mixed string containing article contents, or boolean
484 public function isRedirect( $text = false ) {
485 if ( $text === false ) {
486 if ( !$this->mDataLoaded
) {
487 $this->loadPageData();
490 return (bool)$this->mIsRedirect
;
492 return Title
::newFromRedirect( $text ) !== null;
497 * Loads everything except the text
498 * This isn't necessary for all uses, so it's only done if needed.
500 protected function loadLastEdit() {
501 if ( $this->mLastRevision
!== null ) {
502 return; // already loaded
505 $latest = $this->getLatest();
507 return; // page doesn't exist or is missing page_latest info
510 $revision = Revision
::newFromPageId( $this->getId(), $latest );
511 if ( $revision ) { // sanity
512 $this->setLastEdit( $revision );
517 * Set the latest revision
519 protected function setLastEdit( Revision
$revision ) {
520 $this->mLastRevision
= $revision;
521 $this->mTimestamp
= $revision->getTimestamp();
525 * Get the latest revision
526 * @return Revision|null
528 public function getRevision() {
529 $this->loadLastEdit();
530 if ( $this->mLastRevision
) {
531 return $this->mLastRevision
;
537 * Get the text of the current revision. No side-effects...
539 * @param $audience Integer: one of:
540 * Revision::FOR_PUBLIC to be displayed to all users
541 * Revision::FOR_THIS_USER to be displayed to $wgUser
542 * Revision::RAW get the text regardless of permissions
543 * @return String|false The text of the current revision
545 public function getText( $audience = Revision
::FOR_PUBLIC
) {
546 $this->loadLastEdit();
547 if ( $this->mLastRevision
) {
548 return $this->mLastRevision
->getText( $audience );
554 * Get the text of the current revision. No side-effects...
556 * @return String|false The text of the current revision
558 public function getRawText() {
559 $this->loadLastEdit();
560 if ( $this->mLastRevision
) {
561 return $this->mLastRevision
->getRawText();
567 * @return string MW timestamp of last article revision
569 public function getTimestamp() {
570 // Check if the field has been filled by WikiPage::setTimestamp()
571 if ( !$this->mTimestamp
) {
572 $this->loadLastEdit();
574 return wfTimestamp( TS_MW
, $this->mTimestamp
);
578 * Set the page timestamp (use only to avoid DB queries)
579 * @param $ts string MW timestamp of last article revision
582 public function setTimestamp( $ts ) {
583 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
587 * @param $audience Integer: one of:
588 * Revision::FOR_PUBLIC to be displayed to all users
589 * Revision::FOR_THIS_USER to be displayed to $wgUser
590 * Revision::RAW get the text regardless of permissions
591 * @return int user ID for the user that made the last article revision
593 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
594 $this->loadLastEdit();
595 if ( $this->mLastRevision
) {
596 return $this->mLastRevision
->getUser( $audience );
603 * @param $audience Integer: one of:
604 * Revision::FOR_PUBLIC to be displayed to all users
605 * Revision::FOR_THIS_USER to be displayed to $wgUser
606 * Revision::RAW get the text regardless of permissions
607 * @return string username of the user that made the last article revision
609 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
610 $this->loadLastEdit();
611 if ( $this->mLastRevision
) {
612 return $this->mLastRevision
->getUserText( $audience );
619 * @param $audience Integer: one of:
620 * Revision::FOR_PUBLIC to be displayed to all users
621 * Revision::FOR_THIS_USER to be displayed to $wgUser
622 * Revision::RAW get the text regardless of permissions
623 * @return string Comment stored for the last article revision
625 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
626 $this->loadLastEdit();
627 if ( $this->mLastRevision
) {
628 return $this->mLastRevision
->getComment( $audience );
635 * Returns true if last revision was marked as "minor edit"
637 * @return boolean Minor edit indicator for the last article revision.
639 public function getMinorEdit() {
640 $this->loadLastEdit();
641 if ( $this->mLastRevision
) {
642 return $this->mLastRevision
->isMinor();
649 * Get a list of users who have edited this article, not including the user who made
650 * the most recent revision, which you can get from $article->getUser() if you want it
651 * @return UserArrayFromResult
653 public function getContributors() {
654 # @todo FIXME: This is expensive; cache this info somewhere.
656 $dbr = wfGetDB( DB_SLAVE
);
658 if ( $dbr->implicitGroupby() ) {
659 $realNameField = 'user_real_name';
661 $realNameField = 'MIN(user_real_name) AS user_real_name';
664 $tables = array( 'revision', 'user' );
667 'rev_user as user_id',
668 'rev_user_text AS user_name',
670 'MAX(rev_timestamp) AS timestamp',
673 $conds = array( 'rev_page' => $this->getId() );
675 // The user who made the top revision gets credited as "this page was last edited by
676 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
677 $user = $this->getUser();
679 $conds[] = "rev_user != $user";
681 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
684 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
687 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
691 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
692 'ORDER BY' => 'timestamp DESC',
695 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
696 return new UserArrayFromResult( $res );
700 * Should the parser cache be used?
702 * @param $user User The relevant user
705 public function isParserCacheUsed( User
$user, $oldid ) {
706 global $wgEnableParserCache;
708 return $wgEnableParserCache
709 && $user->getStubThreshold() == 0
712 && $this->mTitle
->isWikitextPage();
716 * Perform the actions of a page purging
718 public function doPurge() {
721 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
725 // Invalidate the cache
726 $this->mTitle
->invalidateCache();
730 // Commit the transaction before the purge is sent
731 $dbw = wfGetDB( DB_MASTER
);
735 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
739 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
740 if ( $this->getId() == 0 ) {
743 $text = $this->getRawText();
746 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
751 * Insert a new empty page record for this article.
752 * This *must* be followed up by creating a revision
753 * and running $this->updateRevisionOn( ... );
754 * or else the record will be left in a funky state.
755 * Best if all done inside a transaction.
757 * @param $dbw DatabaseBase
758 * @return int The newly created page_id key, or false if the title already existed
761 public function insertOn( $dbw ) {
762 wfProfileIn( __METHOD__
);
764 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
765 $dbw->insert( 'page', array(
766 'page_id' => $page_id,
767 'page_namespace' => $this->mTitle
->getNamespace(),
768 'page_title' => $this->mTitle
->getDBkey(),
770 'page_restrictions' => '',
771 'page_is_redirect' => 0, # Will set this shortly...
773 'page_random' => wfRandom(),
774 'page_touched' => $dbw->timestamp(),
775 'page_latest' => 0, # Fill this in shortly...
776 'page_len' => 0, # Fill this in shortly...
777 ), __METHOD__
, 'IGNORE' );
779 $affected = $dbw->affectedRows();
782 $newid = $dbw->insertId();
783 $this->mTitle
->resetArticleID( $newid );
785 wfProfileOut( __METHOD__
);
787 return $affected ?
$newid : false;
791 * Update the page record to point to a newly saved revision.
793 * @param $dbw DatabaseBase: object
794 * @param $revision Revision: For ID number, and text used to set
795 * length and redirect status fields
796 * @param $lastRevision Integer: if given, will not overwrite the page field
797 * when different from the currently set value.
798 * Giving 0 indicates the new page flag should be set
800 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
801 * removing rows in redirect table.
802 * @return bool true on success, false on failure
805 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
806 wfProfileIn( __METHOD__
);
808 $text = $revision->getText();
809 $rt = Title
::newFromRedirectRecurse( $text );
811 $conditions = array( 'page_id' => $this->getId() );
813 if ( !is_null( $lastRevision ) ) {
814 # An extra check against threads stepping on each other
815 $conditions['page_latest'] = $lastRevision;
818 $now = wfTimestampNow();
819 $dbw->update( 'page',
821 'page_latest' => $revision->getId(),
822 'page_touched' => $dbw->timestamp( $now ),
823 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
824 'page_is_redirect' => $rt !== null ?
1 : 0,
825 'page_len' => strlen( $text ),
830 $result = $dbw->affectedRows() != 0;
832 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
833 $this->setCachedLastEditTime( $now );
836 wfProfileOut( __METHOD__
);
841 * Get the cached timestamp for the last time the page changed.
842 * This is only used to help handle slave lag by comparing to page_touched.
843 * @return string MW timestamp
845 protected function getCachedLastEditTime() {
847 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
848 return $wgMemc->get( $key );
852 * Set the cached timestamp for the last time the page changed.
853 * This is only used to help handle slave lag by comparing to page_touched.
854 * @param $timestamp string
857 public function setCachedLastEditTime( $timestamp ) {
859 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
860 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
864 * Add row to the redirect table if this is a redirect, remove otherwise.
866 * @param $dbw DatabaseBase
867 * @param $redirectTitle Title object pointing to the redirect target,
868 * or NULL if this is not a redirect
869 * @param $lastRevIsRedirect If given, will optimize adding and
870 * removing rows in redirect table.
871 * @return bool true on success, false on failure
874 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
875 // Always update redirects (target link might have changed)
876 // Update/Insert if we don't know if the last revision was a redirect or not
877 // Delete if changing from redirect to non-redirect
878 $isRedirect = !is_null( $redirectTitle );
880 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
884 wfProfileIn( __METHOD__
);
886 $this->insertRedirectEntry( $redirectTitle );
888 // This is not a redirect, remove row from redirect table
889 $where = array( 'rd_from' => $this->getId() );
890 $dbw->delete( 'redirect', $where, __METHOD__
);
893 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
894 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
896 wfProfileOut( __METHOD__
);
898 return ( $dbw->affectedRows() != 0 );
902 * If the given revision is newer than the currently set page_latest,
903 * update the page record. Otherwise, do nothing.
905 * @param $dbw Database object
906 * @param $revision Revision object
909 public function updateIfNewerOn( $dbw, $revision ) {
910 wfProfileIn( __METHOD__
);
912 $row = $dbw->selectRow(
913 array( 'revision', 'page' ),
914 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
916 'page_id' => $this->getId(),
917 'page_latest=rev_id' ),
921 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
922 wfProfileOut( __METHOD__
);
925 $prev = $row->rev_id
;
926 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
928 # No or missing previous revision; mark the page as new
930 $lastRevIsRedirect = null;
933 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
935 wfProfileOut( __METHOD__
);
940 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
941 * @param $text String: new text of the section
942 * @param $summary String: new section's subject, only if $section is 'new'
943 * @param $edittime String: revision timestamp or null to use the current revision
944 * @return string Complete article text, or null if error
946 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
947 wfProfileIn( __METHOD__
);
949 if ( strval( $section ) == '' ) {
950 // Whole-page edit; let the whole text through
952 if ( is_null( $edittime ) ) {
953 $rev = Revision
::newFromTitle( $this->mTitle
);
955 $dbw = wfGetDB( DB_MASTER
);
956 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
960 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
961 $this->getId() . "; section: $section; edittime: $edittime)\n" );
962 wfProfileOut( __METHOD__
);
966 $oldtext = $rev->getText();
968 if ( $section == 'new' ) {
969 # Inserting a new section
970 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
971 $text = strlen( trim( $oldtext ) ) > 0
972 ?
"{$oldtext}\n\n{$subject}{$text}"
973 : "{$subject}{$text}";
975 # Replacing an existing section; roll out the big guns
978 $text = $wgParser->replaceSection( $oldtext, $section, $text );
982 wfProfileOut( __METHOD__
);
987 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
989 * @return Int updated $flags
991 function checkFlags( $flags ) {
992 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
993 if ( $this->mTitle
->getArticleID() ) {
994 $flags |
= EDIT_UPDATE
;
1004 * Change an existing article or create a new article. Updates RC and all necessary caches,
1005 * optionally via the deferred update array.
1007 * @param $text String: new text
1008 * @param $summary String: edit summary
1009 * @param $flags Integer bitfield:
1011 * Article is known or assumed to be non-existent, create a new one
1013 * Article is known or assumed to be pre-existing, update it
1015 * Mark this edit minor, if the user is allowed to do so
1017 * Do not log the change in recentchanges
1019 * Mark the edit a "bot" edit regardless of user rights
1020 * EDIT_DEFER_UPDATES
1021 * Defer some of the updates until the end of index.php
1023 * Fill in blank summaries with generated text where possible
1025 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1026 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1027 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1028 * edit-already-exists error will be returned. These two conditions are also possible with
1029 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1031 * @param $baseRevId the revision ID this edit was based off, if any
1032 * @param $user User the user doing the edit
1034 * @return Status object. Possible errors:
1035 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1036 * edit-gone-missing: In update mode, but the article didn't exist
1037 * edit-conflict: In update mode, the article changed unexpectedly
1038 * edit-no-change: Warning that the text was the same as before
1039 * edit-already-exists: In creation mode, but the article already exists
1041 * Extensions may define additional errors.
1043 * $return->value will contain an associative array with members as follows:
1044 * new: Boolean indicating if the function attempted to create a new article
1045 * revision: The revision object for the inserted revision, or null
1047 * Compatibility note: this function previously returned a boolean value indicating success/failure
1049 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1050 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1052 # Low-level sanity check
1053 if ( $this->mTitle
->getText() === '' ) {
1054 throw new MWException( 'Something is trying to edit an article with an empty title' );
1057 wfProfileIn( __METHOD__
);
1059 $user = is_null( $user ) ?
$wgUser : $user;
1060 $status = Status
::newGood( array() );
1062 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1063 $this->loadPageData( 'fromdbmaster' );
1065 $flags = $this->checkFlags( $flags );
1067 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1068 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1070 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1072 if ( $status->isOK() ) {
1073 $status->fatal( 'edit-hook-aborted' );
1076 wfProfileOut( __METHOD__
);
1080 # Silently ignore EDIT_MINOR if not allowed
1081 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1082 $bot = $flags & EDIT_FORCE_BOT
;
1084 $oldtext = $this->getRawText(); // current revision
1085 $oldsize = strlen( $oldtext );
1086 $oldcountable = $this->isCountable();
1088 # Provide autosummaries if one is not provided and autosummaries are enabled.
1089 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1090 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1093 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1094 $text = $editInfo->pst
;
1095 $newsize = strlen( $text );
1097 $dbw = wfGetDB( DB_MASTER
);
1098 $now = wfTimestampNow();
1099 $this->mTimestamp
= $now;
1101 if ( $flags & EDIT_UPDATE
) {
1102 # Update article, but only if changed.
1103 $status->value
['new'] = false;
1105 # Make sure the revision is either completely inserted or not inserted at all
1106 if ( !$wgDBtransactions ) {
1107 $userAbort = ignore_user_abort( true );
1110 $revision = new Revision( array(
1111 'page' => $this->getId(),
1112 'comment' => $summary,
1113 'minor_edit' => $isminor,
1115 'parent_id' => $this->mLatest
,
1116 'user' => $user->getId(),
1117 'user_text' => $user->getName(),
1121 $changed = ( strcmp( $text, $oldtext ) != 0 );
1124 if ( !$this->mLatest
) {
1125 # Article gone missing
1126 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1127 $status->fatal( 'edit-gone-missing' );
1129 wfProfileOut( __METHOD__
);
1134 $revisionId = $revision->insertOn( $dbw );
1138 # Note that we use $this->mLatest instead of fetching a value from the master DB
1139 # during the course of this function. This makes sure that EditPage can detect
1140 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1141 # before this function is called. A previous function used a separate query, this
1142 # creates a window where concurrent edits can cause an ignored edit conflict.
1143 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1146 /* Belated edit conflict! Run away!! */
1147 $status->fatal( 'edit-conflict' );
1149 # Delete the invalid revision if the DB is not transactional
1150 if ( !$wgDBtransactions ) {
1151 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1157 global $wgUseRCPatrol;
1158 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1159 # Update recentchanges
1160 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1161 # Mark as patrolled if the user can do so
1162 $patrolled = $wgUseRCPatrol && !count(
1163 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1164 # Add RC row to the DB
1165 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1166 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1167 $revisionId, $patrolled
1170 # Log auto-patrolled edits
1172 PatrolLog
::record( $rc, true );
1175 $user->incEditCount();
1180 if ( !$wgDBtransactions ) {
1181 ignore_user_abort( $userAbort );
1184 // Now that ignore_user_abort is restored, we can respond to fatal errors
1185 if ( !$status->isOK() ) {
1186 wfProfileOut( __METHOD__
);
1190 # Update links tables, site stats, etc.
1191 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1192 'oldcountable' => $oldcountable ) );
1195 $status->warning( 'edit-no-change' );
1197 // Keep the same revision ID, but do some updates on it
1198 $revisionId = $this->getLatest();
1199 // Update page_touched, this is usually implicit in the page update
1200 // Other cache updates are done in onArticleEdit()
1201 $this->mTitle
->invalidateCache();
1204 # Create new article
1205 $status->value
['new'] = true;
1209 # Add the page record; stake our claim on this title!
1210 # This will return false if the article already exists
1211 $newid = $this->insertOn( $dbw );
1213 if ( $newid === false ) {
1215 $status->fatal( 'edit-already-exists' );
1217 wfProfileOut( __METHOD__
);
1221 # Save the revision text...
1222 $revision = new Revision( array(
1224 'comment' => $summary,
1225 'minor_edit' => $isminor,
1227 'user' => $user->getId(),
1228 'user_text' => $user->getName(),
1231 $revisionId = $revision->insertOn( $dbw );
1233 $this->mTitle
->resetArticleID( $newid );
1234 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
1236 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
1238 # Update the page record with revision data
1239 $this->updateRevisionOn( $dbw, $revision, 0 );
1241 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1243 # Update recentchanges
1244 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1245 global $wgUseRCPatrol, $wgUseNPPatrol;
1247 # Mark as patrolled if the user can do so
1248 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1249 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1250 # Add RC row to the DB
1251 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1252 '', strlen( $text ), $revisionId, $patrolled );
1254 # Log auto-patrolled edits
1256 PatrolLog
::record( $rc, true );
1259 $user->incEditCount();
1262 # Update links, etc.
1263 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1265 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1266 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1269 # Do updates right now unless deferral was requested
1270 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1271 DeferredUpdates
::doUpdates();
1274 // Return the new revision (or null) to the caller
1275 $status->value
['revision'] = $revision;
1277 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1278 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1280 # Promote user to any groups they meet the criteria for
1281 $user->addAutopromoteOnceGroups( 'onEdit' );
1283 wfProfileOut( __METHOD__
);
1288 * Update the article's restriction field, and leave a log entry.
1290 * @todo: seperate the business/permission stuff out from backend code
1292 * @param $limit Array: set of restriction keys
1293 * @param $reason String
1294 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1295 * @param $expiry Array: per restriction type expiration
1296 * @param $user User The user updating the restrictions
1297 * @return bool true on success
1299 public function updateRestrictions(
1300 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
1302 global $wgUser, $wgContLang;
1303 $user = is_null( $user ) ?
$wgUser : $user;
1305 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1307 $id = $this->mTitle
->getArticleID();
1310 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1314 if ( wfReadOnly() ) {
1315 wfDebug( "updateRestrictions failed: read-only\n" );
1319 if ( count( $this->mTitle
->getUserPermissionsErrors( 'protect', $user ) ) ) {
1320 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1328 // Take this opportunity to purge out expired restrictions
1329 Title
::purgeExpiredRestrictions();
1331 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1332 # we expect a single selection, but the schema allows otherwise.
1334 $updated = self
::flattenRestrictions( $limit );
1337 foreach ( $restrictionTypes as $action ) {
1338 if ( isset( $expiry[$action] ) ) {
1339 # Get current restrictions on $action
1340 $aLimits = $this->mTitle
->getRestrictions( $action );
1341 $current[$action] = implode( '', $aLimits );
1342 # Are any actual restrictions being dealt with here?
1343 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
1345 # If something changed, we need to log it. Checking $aRChanged
1346 # assures that "unprotecting" a page that is not protected does
1347 # not log just because the expiry was "changed".
1349 $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] )
1356 $current = self
::flattenRestrictions( $current );
1358 $changed = ( $changed ||
$current != $updated );
1359 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
1360 $protect = ( $updated != '' );
1362 # If nothing's changed, do nothing
1364 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1365 $dbw = wfGetDB( DB_MASTER
);
1367 # Prepare a null revision to be added to the history
1368 $modified = $current != '' && $protect;
1371 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1373 $comment_type = 'unprotectedarticle';
1376 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1378 # Only restrictions with the 'protect' right can cascade...
1379 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1380 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1382 # The schema allows multiple restrictions
1383 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1387 $cascade_description = '';
1390 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1394 $comment .= ": $reason";
1397 $editComment = $comment;
1398 $encodedExpiry = array();
1399 $protect_description = '';
1400 foreach ( $limit as $action => $restrictions ) {
1401 if ( !isset( $expiry[$action] ) )
1402 $expiry[$action] = $dbw->getInfinity();
1404 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1405 if ( $restrictions != '' ) {
1406 $protect_description .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1407 if ( $encodedExpiry[$action] != 'infinity' ) {
1408 $protect_description .= wfMsgForContent( 'protect-expiring',
1409 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1410 $wgContLang->date( $expiry[$action], false, false ) ,
1411 $wgContLang->time( $expiry[$action], false, false ) );
1413 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1416 $protect_description .= ') ';
1419 $protect_description = trim( $protect_description );
1421 if ( $protect_description && $protect ) {
1422 $editComment .= " ($protect_description)";
1426 $editComment .= "$cascade_description";
1429 # Update restrictions table
1430 foreach ( $limit as $action => $restrictions ) {
1431 if ( $restrictions != '' ) {
1432 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1433 array( 'pr_page' => $id,
1434 'pr_type' => $action,
1435 'pr_level' => $restrictions,
1436 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1437 'pr_expiry' => $encodedExpiry[$action]
1442 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1443 'pr_type' => $action ), __METHOD__
);
1447 # Insert a null revision
1448 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1449 $nullRevId = $nullRevision->insertOn( $dbw );
1451 $latest = $this->getLatest();
1452 # Update page record
1453 $dbw->update( 'page',
1455 'page_touched' => $dbw->timestamp(),
1456 'page_restrictions' => '',
1457 'page_latest' => $nullRevId
1458 ), array( /* WHERE */
1463 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1464 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1466 # Update the protection log
1467 $log = new LogPage( 'protect' );
1469 $params = array( $protect_description, $cascade ?
'cascade' : '' );
1470 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
1472 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1475 } # End "changed" check
1481 * Take an array of page restrictions and flatten it to a string
1482 * suitable for insertion into the page_restrictions field.
1483 * @param $limit Array
1486 protected static function flattenRestrictions( $limit ) {
1487 if ( !is_array( $limit ) ) {
1488 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1494 foreach ( $limit as $action => $restrictions ) {
1495 if ( $restrictions != '' ) {
1496 $bits[] = "$action=$restrictions";
1500 return implode( ':', $bits );
1504 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1506 public function isBigDeletion() {
1507 global $wgDeleteRevisionsLimit;
1509 if ( $wgDeleteRevisionsLimit ) {
1510 $revCount = $this->estimateRevisionCount();
1512 return $revCount > $wgDeleteRevisionsLimit;
1519 * @return int approximate revision count
1521 public function estimateRevisionCount() {
1522 $dbr = wfGetDB( DB_SLAVE
);
1524 // For an exact count...
1525 // return $dbr->selectField( 'revision', 'COUNT(*)',
1526 // array( 'rev_page' => $this->getId() ), __METHOD__ );
1527 return $dbr->estimateRowCount( 'revision', '*',
1528 array( 'rev_page' => $this->getId() ), __METHOD__
);
1532 * Get the last N authors
1533 * @param $num Integer: number of revisions to get
1534 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1535 * @return array Array of authors, duplicates not removed
1537 public function getLastNAuthors( $num, $revLatest = 0 ) {
1538 wfProfileIn( __METHOD__
);
1539 // First try the slave
1540 // If that doesn't have the latest revision, try the master
1542 $db = wfGetDB( DB_SLAVE
);
1545 $res = $db->select( array( 'page', 'revision' ),
1546 array( 'rev_id', 'rev_user_text' ),
1548 'page_namespace' => $this->mTitle
->getNamespace(),
1549 'page_title' => $this->mTitle
->getDBkey(),
1550 'rev_page = page_id'
1553 'ORDER BY' => 'rev_timestamp DESC',
1559 wfProfileOut( __METHOD__
);
1563 $row = $db->fetchObject( $res );
1565 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1566 $db = wfGetDB( DB_MASTER
);
1571 } while ( $continue );
1573 $authors = array( $row->rev_user_text
);
1575 foreach ( $res as $row ) {
1576 $authors[] = $row->rev_user_text
;
1579 wfProfileOut( __METHOD__
);
1584 * Back-end article deletion
1585 * Deletes the article with database consistency, writes logs, purges caches
1587 * @param $reason string delete reason for deletion log
1588 * @param suppress bitfield
1589 * Revision::DELETED_TEXT
1590 * Revision::DELETED_COMMENT
1591 * Revision::DELETED_USER
1592 * Revision::DELETED_RESTRICTED
1593 * @param $id int article ID
1594 * @param $commit boolean defaults to true, triggers transaction end
1595 * @param &$errors Array of errors to append to
1596 * @param $user User The relevant user
1597 * @return boolean true if successful
1599 public function doDeleteArticle(
1600 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1602 global $wgDeferredUpdateList, $wgUseTrackbacks, $wgUser;
1603 $user = is_null( $user ) ?
$wgUser : $user;
1605 wfDebug( __METHOD__
. "\n" );
1607 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1610 $dbw = wfGetDB( DB_MASTER
);
1611 $t = $this->mTitle
->getDBkey();
1612 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1614 if ( $t === '' ||
$id == 0 ) {
1618 DeferredUpdates
::addUpdate(
1619 new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 )
1622 // Bitfields to further suppress the content
1625 // This should be 15...
1626 $bitfield |
= Revision
::DELETED_TEXT
;
1627 $bitfield |
= Revision
::DELETED_COMMENT
;
1628 $bitfield |
= Revision
::DELETED_USER
;
1629 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1631 $bitfield = 'rev_deleted';
1635 // For now, shunt the revision data into the archive table.
1636 // Text is *not* removed from the text table; bulk storage
1637 // is left intact to avoid breaking block-compression or
1638 // immutable storage schemes.
1640 // For backwards compatibility, note that some older archive
1641 // table entries will have ar_text and ar_flags fields still.
1643 // In the future, we may keep revisions and mark them with
1644 // the rev_deleted field, which is reserved for this purpose.
1645 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1647 'ar_namespace' => 'page_namespace',
1648 'ar_title' => 'page_title',
1649 'ar_comment' => 'rev_comment',
1650 'ar_user' => 'rev_user',
1651 'ar_user_text' => 'rev_user_text',
1652 'ar_timestamp' => 'rev_timestamp',
1653 'ar_minor_edit' => 'rev_minor_edit',
1654 'ar_rev_id' => 'rev_id',
1655 'ar_parent_id' => 'rev_parent_id',
1656 'ar_text_id' => 'rev_text_id',
1657 'ar_text' => '\'\'', // Be explicit to appease
1658 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1659 'ar_len' => 'rev_len',
1660 'ar_page_id' => 'page_id',
1661 'ar_deleted' => $bitfield
1664 'page_id = rev_page'
1668 # Delete restrictions for it
1669 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1671 # Now that it's safely backed up, delete it
1672 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1673 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1680 # Fix category table counts
1682 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1684 foreach ( $res as $row ) {
1685 $cats [] = $row->cl_to
;
1688 $this->updateCategoryCounts( array(), $cats );
1690 # If using cascading deletes, we can skip some explicit deletes
1691 if ( !$dbw->cascadingDeletes() ) {
1692 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
1694 if ( $wgUseTrackbacks ) {
1695 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
1698 # Delete outgoing links
1699 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
1700 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
1701 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
1702 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
1703 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
1704 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
1705 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
1706 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
1707 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
1710 # If using cleanup triggers, we can skip some manual deletes
1711 if ( !$dbw->cleanupTriggers() ) {
1712 # Clean up recentchanges entries...
1713 $dbw->delete( 'recentchanges',
1714 array( 'rc_type != ' . RC_LOG
,
1715 'rc_namespace' => $this->mTitle
->getNamespace(),
1716 'rc_title' => $this->mTitle
->getDBkey() ),
1718 $dbw->delete( 'recentchanges',
1719 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
1724 self
::onArticleDelete( $this->mTitle
);
1726 # Clear the cached article id so the interface doesn't act like we exist
1727 $this->mTitle
->resetArticleID( 0 );
1729 # Log the deletion, if the page was suppressed, log it at Oversight instead
1730 $logtype = $suppress ?
'suppress' : 'delete';
1732 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1733 $logEntry->setPerformer( $user );
1734 $logEntry->setTarget( $this->mTitle
);
1735 $logEntry->setComment( $reason );
1736 $logid = $logEntry->insert();
1737 $logEntry->publish( $logid );
1743 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1748 * Roll back the most recent consecutive set of edits to a page
1749 * from the same user; fails if there are no eligible edits to
1750 * roll back to, e.g. user is the sole contributor. This function
1751 * performs permissions checks on $user, then calls commitRollback()
1752 * to do the dirty work
1754 * @param $fromP String: Name of the user whose edits to rollback.
1755 * @param $summary String: Custom summary. Set to default summary if empty.
1756 * @param $token String: Rollback token.
1757 * @param $bot Boolean: If true, mark all reverted edits as bot.
1759 * @param $resultDetails Array: contains result-specific array of additional values
1760 * 'alreadyrolled' : 'current' (rev)
1761 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1763 * @param $user User The user performing the rollback
1764 * @return array of errors, each error formatted as
1765 * array(messagekey, param1, param2, ...).
1766 * On success, the array is empty. This array can also be passed to
1767 * OutputPage::showPermissionsErrorPage().
1769 public function doRollback(
1770 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
1772 $resultDetails = null;
1775 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
1776 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
1777 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1779 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
1780 $errors[] = array( 'sessionfailure' );
1783 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
1784 $errors[] = array( 'actionthrottledtext' );
1787 # If there were errors, bail out now
1788 if ( !empty( $errors ) ) {
1792 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
1796 * Backend implementation of doRollback(), please refer there for parameter
1797 * and return value documentation
1799 * NOTE: This function does NOT check ANY permissions, it just commits the
1800 * rollback to the DB. Therefore, you should only call this function direct-
1801 * ly if you want to use custom permissions checks. If you don't, use
1802 * doRollback() instead.
1803 * @param $fromP String: Name of the user whose edits to rollback.
1804 * @param $summary String: Custom summary. Set to default summary if empty.
1805 * @param $bot Boolean: If true, mark all reverted edits as bot.
1807 * @param $resultDetails Array: contains result-specific array of additional values
1808 * @param $guser User The user performing the rollback
1810 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
1811 global $wgUseRCPatrol, $wgContLang;
1813 $dbw = wfGetDB( DB_MASTER
);
1815 if ( wfReadOnly() ) {
1816 return array( array( 'readonlytext' ) );
1819 # Get the last editor
1820 $current = Revision
::newFromTitle( $this->mTitle
);
1821 if ( is_null( $current ) ) {
1822 # Something wrong... no page?
1823 return array( array( 'notanarticle' ) );
1826 $from = str_replace( '_', ' ', $fromP );
1827 # User name given should match up with the top revision.
1828 # If the user was deleted then $from should be empty.
1829 if ( $from != $current->getUserText() ) {
1830 $resultDetails = array( 'current' => $current );
1831 return array( array( 'alreadyrolled',
1832 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
1833 htmlspecialchars( $fromP ),
1834 htmlspecialchars( $current->getUserText() )
1838 # Get the last edit not by this guy...
1839 # Note: these may not be public values
1840 $user = intval( $current->getRawUser() );
1841 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1842 $s = $dbw->selectRow( 'revision',
1843 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1844 array( 'rev_page' => $current->getPage(),
1845 "rev_user != {$user} OR rev_user_text != {$user_text}"
1847 array( 'USE INDEX' => 'page_timestamp',
1848 'ORDER BY' => 'rev_timestamp DESC' )
1850 if ( $s === false ) {
1851 # No one else ever edited this page
1852 return array( array( 'cantrollback' ) );
1853 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
1854 # Only admins can see this text
1855 return array( array( 'notvisiblerev' ) );
1859 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1860 # Mark all reverted edits as bot
1864 if ( $wgUseRCPatrol ) {
1865 # Mark all reverted edits as patrolled
1866 $set['rc_patrolled'] = 1;
1869 if ( count( $set ) ) {
1870 $dbw->update( 'recentchanges', $set,
1872 'rc_cur_id' => $current->getPage(),
1873 'rc_user_text' => $current->getUserText(),
1874 "rc_timestamp > '{$s->rev_timestamp}'",
1879 # Generate the edit summary if necessary
1880 $target = Revision
::newFromId( $s->rev_id
);
1881 if ( empty( $summary ) ) {
1882 if ( $from == '' ) { // no public user name
1883 $summary = wfMsgForContent( 'revertpage-nouser' );
1885 $summary = wfMsgForContent( 'revertpage' );
1889 # Allow the custom summary to use the same args as the default message
1891 $target->getUserText(), $from, $s->rev_id
,
1892 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
1893 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1895 $summary = wfMsgReplaceArgs( $summary, $args );
1898 $flags = EDIT_UPDATE
;
1900 if ( $guser->isAllowed( 'minoredit' ) ) {
1901 $flags |
= EDIT_MINOR
;
1904 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1905 $flags |
= EDIT_FORCE_BOT
;
1908 # Actually store the edit
1909 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1910 if ( !empty( $status->value
['revision'] ) ) {
1911 $revId = $status->value
['revision']->getId();
1916 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1918 $resultDetails = array(
1919 'summary' => $summary,
1920 'current' => $current,
1921 'target' => $target,
1929 * Do standard deferred updates after page view
1930 * @param $user User The relevant user
1932 public function doViewUpdates( User
$user ) {
1933 global $wgDisableCounters;
1934 if ( wfReadOnly() ) {
1938 # Don't update page view counters on views from bot users (bug 14044)
1939 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->getId() ) {
1940 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1941 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1944 # Update newtalk / watchlist notification status
1945 $user->clearNotification( $this->mTitle
);
1949 * Prepare text which is about to be saved.
1950 * Returns a stdclass with source, pst and output members
1952 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1953 global $wgParser, $wgContLang, $wgUser;
1954 $user = is_null( $user ) ?
$wgUser : $user;
1955 // @TODO fixme: check $user->getId() here???
1956 if ( $this->mPreparedEdit
1957 && $this->mPreparedEdit
->newText
== $text
1958 && $this->mPreparedEdit
->revid
== $revid
1961 return $this->mPreparedEdit
;
1964 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1965 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1967 $edit = (object)array();
1968 $edit->revid
= $revid;
1969 $edit->newText
= $text;
1970 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
1971 $edit->popts
= $this->makeParserOptions( 'canonical' );
1972 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1973 $edit->oldText
= $this->getRawText();
1975 $this->mPreparedEdit
= $edit;
1981 * Do standard deferred updates after page edit.
1982 * Update links tables, site stats, search index and message cache.
1983 * Purges pages that include this page if the text was changed here.
1984 * Every 100th edit, prune the recent changes table.
1987 * @param $revision Revision object
1988 * @param $user User object that did the revision
1989 * @param $options Array of options, following indexes are used:
1990 * - changed: boolean, whether the revision changed the content (default true)
1991 * - created: boolean, whether the revision created the page (default false)
1992 * - oldcountable: boolean or null (default null):
1993 * - boolean: whether the page was counted as an article before that
1994 * revision, only used in changed is true and created is false
1995 * - null: don't change the article count
1997 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1998 global $wgEnableParserCache;
2000 wfProfileIn( __METHOD__
);
2002 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2003 $text = $revision->getText();
2006 # Be careful not to double-PST: $text is usually already PST-ed once
2007 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2008 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2009 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
2011 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2012 $editInfo = $this->mPreparedEdit
;
2015 # Save it to the parser cache
2016 if ( $wgEnableParserCache ) {
2017 $parserCache = ParserCache
::singleton();
2018 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2021 # Update the links tables
2022 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2025 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2027 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2028 if ( 0 == mt_rand( 0, 99 ) ) {
2029 // Flush old entries from the `recentchanges` table; we do this on
2030 // random requests so as to avoid an increase in writes for no good reason
2033 $dbw = wfGetDB( DB_MASTER
);
2034 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2037 array( "rc_timestamp < '$cutoff'" ),
2043 $id = $this->getId();
2044 $title = $this->mTitle
->getPrefixedDBkey();
2045 $shortTitle = $this->mTitle
->getDBkey();
2048 wfProfileOut( __METHOD__
);
2052 if ( !$options['changed'] ) {
2055 } elseif ( $options['created'] ) {
2056 $good = (int)$this->isCountable( $editInfo );
2058 } elseif ( $options['oldcountable'] !== null ) {
2059 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2066 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2067 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
2069 # If this is another user's talk page, update newtalk.
2070 # Don't do this if $options['changed'] = false (null-edits) nor if
2071 # it's a minor edit and the user doesn't want notifications for those.
2072 if ( $options['changed']
2073 && $this->mTitle
->getNamespace() == NS_USER_TALK
2074 && $shortTitle != $user->getTitleKey()
2075 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2077 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2078 $other = User
::newFromName( $shortTitle, false );
2080 wfDebug( __METHOD__
. ": invalid username\n" );
2081 } elseif ( User
::isIP( $shortTitle ) ) {
2082 // An anonymous user
2083 $other->setNewtalk( true );
2084 } elseif ( $other->isLoggedIn() ) {
2085 $other->setNewtalk( true );
2087 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2092 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2093 MessageCache
::singleton()->replace( $shortTitle, $text );
2096 if( $options['created'] ) {
2097 self
::onArticleCreate( $this->mTitle
);
2099 self
::onArticleEdit( $this->mTitle
);
2102 wfProfileOut( __METHOD__
);
2106 * Perform article updates on a special page creation.
2108 * @param $rev Revision object
2110 * @todo This is a shitty interface function. Kill it and replace the
2111 * other shitty functions like doEditUpdates and such so it's not needed
2113 * @deprecated since 1.18, use doEditUpdates()
2115 public function createUpdates( $rev ) {
2117 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2121 * This function is called right before saving the wikitext,
2122 * so we can do things like signatures and links-in-context.
2124 * @param $text String article contents
2125 * @param $user User object: user doing the edit
2126 * @param $popts ParserOptions object: parser options, default options for
2127 * the user loaded if null given
2128 * @return string article contents with altered wikitext markup (signatures
2129 * converted, {{subst:}}, templates, etc.)
2131 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2132 global $wgParser, $wgUser;
2133 $user = is_null( $user ) ?
$wgUser : $user;
2135 if ( $popts === null ) {
2136 $popts = ParserOptions
::newFromUser( $user );
2139 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2143 * Loads page_touched and returns a value indicating if it should be used
2144 * @return boolean true if not a redirect
2146 public function checkTouched() {
2147 if ( !$this->mDataLoaded
) {
2148 $this->loadPageData();
2150 return !$this->mIsRedirect
;
2154 * Get the page_touched field
2155 * @return string containing GMT timestamp
2157 public function getTouched() {
2158 if ( !$this->mDataLoaded
) {
2159 $this->loadPageData();
2161 return $this->mTouched
;
2165 * Get the page_latest field
2166 * @return integer rev_id of current revision
2168 public function getLatest() {
2169 if ( !$this->mDataLoaded
) {
2170 $this->loadPageData();
2172 return (int)$this->mLatest
;
2176 * Edit an article without doing all that other stuff
2177 * The article must already exist; link tables etc
2178 * are not updated, caches are not flushed.
2180 * @param $text String: text submitted
2181 * @param $user User The relevant user
2182 * @param $comment String: comment submitted
2183 * @param $minor Boolean: whereas it's a minor modification
2185 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2186 wfProfileIn( __METHOD__
);
2188 $dbw = wfGetDB( DB_MASTER
);
2189 $revision = new Revision( array(
2190 'page' => $this->getId(),
2192 'comment' => $comment,
2193 'minor_edit' => $minor ?
1 : 0,
2195 $revision->insertOn( $dbw );
2196 $this->updateRevisionOn( $dbw, $revision );
2198 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2200 wfProfileOut( __METHOD__
);
2204 * The onArticle*() functions are supposed to be a kind of hooks
2205 * which should be called whenever any of the specified actions
2208 * This is a good place to put code to clear caches, for instance.
2210 * This is called on page move and undelete, as well as edit
2212 * @param $title Title object
2214 public static function onArticleCreate( $title ) {
2215 # Update existence markers on article/talk tabs...
2216 if ( $title->isTalkPage() ) {
2217 $other = $title->getSubjectPage();
2219 $other = $title->getTalkPage();
2222 $other->invalidateCache();
2223 $other->purgeSquid();
2225 $title->touchLinks();
2226 $title->purgeSquid();
2227 $title->deleteTitleProtection();
2231 * Clears caches when article is deleted
2233 * @param $title Title
2235 public static function onArticleDelete( $title ) {
2236 # Update existence markers on article/talk tabs...
2237 if ( $title->isTalkPage() ) {
2238 $other = $title->getSubjectPage();
2240 $other = $title->getTalkPage();
2243 $other->invalidateCache();
2244 $other->purgeSquid();
2246 $title->touchLinks();
2247 $title->purgeSquid();
2250 HTMLFileCache
::clearFileCache( $title );
2253 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2254 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2258 if ( $title->getNamespace() == NS_FILE
) {
2259 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2260 $update->doUpdate();
2264 if ( $title->getNamespace() == NS_USER_TALK
) {
2265 $user = User
::newFromName( $title->getText(), false );
2266 $user->setNewtalk( false );
2270 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2274 * Purge caches on page update etc
2276 * @param $title Title object
2277 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2279 public static function onArticleEdit( $title ) {
2280 // Invalidate caches of articles which include this page
2281 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2284 // Invalidate the caches of all pages which redirect here
2285 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2287 # Purge squid for this page only
2288 $title->purgeSquid();
2290 # Clear file cache for this page only
2291 HTMLFileCache
::clearFileCache( $title );
2297 * Return a list of templates used by this article.
2298 * Uses the templatelinks table
2300 * @return Array of Title objects
2302 public function getUsedTemplates() {
2304 $id = $this->mTitle
->getArticleID();
2310 $dbr = wfGetDB( DB_SLAVE
);
2311 $res = $dbr->select( array( 'templatelinks' ),
2312 array( 'tl_namespace', 'tl_title' ),
2313 array( 'tl_from' => $id ),
2316 if ( $res !== false ) {
2317 foreach ( $res as $row ) {
2318 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2326 * Returns a list of hidden categories this page is a member of.
2327 * Uses the page_props and categorylinks tables.
2329 * @return Array of Title objects
2331 public function getHiddenCategories() {
2333 $id = $this->mTitle
->getArticleID();
2339 $dbr = wfGetDB( DB_SLAVE
);
2340 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2342 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2343 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2346 if ( $res !== false ) {
2347 foreach ( $res as $row ) {
2348 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2356 * Return an applicable autosummary if one exists for the given edit.
2357 * @param $oldtext String: the previous text of the page.
2358 * @param $newtext String: The submitted text of the page.
2359 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2360 * @return string An appropriate autosummary, or an empty string.
2362 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2365 # Decide what kind of autosummary is needed.
2367 # Redirect autosummaries
2368 $ot = Title
::newFromRedirect( $oldtext );
2369 $rt = Title
::newFromRedirect( $newtext );
2371 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2372 $truncatedtext = $wgContLang->truncate(
2373 str_replace( "\n", ' ', $newtext ),
2375 - strlen( wfMsgForContent( 'autoredircomment' ) )
2376 - strlen( $rt->getFullText() )
2378 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2381 # New page autosummaries
2382 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2383 # If they're making a new article, give its text, truncated, in the summary.
2385 $truncatedtext = $wgContLang->truncate(
2386 str_replace( "\n", ' ', $newtext ),
2387 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2389 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2392 # Blanking autosummaries
2393 if ( $oldtext != '' && $newtext == '' ) {
2394 return wfMsgForContent( 'autosumm-blank' );
2395 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2396 # Removing more than 90% of the article
2398 $truncatedtext = $wgContLang->truncate(
2400 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2402 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2405 # If we reach this point, there's no applicable autosummary for our case, so our
2406 # autosummary is empty.
2411 * Auto-generates a deletion reason
2413 * @param &$hasHistory Boolean: whether the page has a history
2414 * @return mixed String containing deletion reason or empty string, or boolean false
2415 * if no revision occurred
2417 public function getAutoDeleteReason( &$hasHistory ) {
2420 $dbw = wfGetDB( DB_MASTER
);
2421 // Get the last revision
2422 $rev = Revision
::newFromTitle( $this->getTitle() );
2424 if ( is_null( $rev ) ) {
2428 // Get the article's contents
2429 $contents = $rev->getText();
2432 // If the page is blank, use the text from the previous revision,
2433 // which can only be blank if there's a move/import/protect dummy revision involved
2434 if ( $contents == '' ) {
2435 $prev = $rev->getPrevious();
2438 $contents = $prev->getText();
2443 // Find out if there was only one contributor
2444 // Only scan the last 20 revisions
2445 $res = $dbw->select( 'revision', 'rev_user_text',
2446 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2448 array( 'LIMIT' => 20 )
2451 if ( $res === false ) {
2452 // This page has no revisions, which is very weird
2456 $hasHistory = ( $res->numRows() > 1 );
2457 $row = $dbw->fetchObject( $res );
2459 if ( $row ) { // $row is false if the only contributor is hidden
2460 $onlyAuthor = $row->rev_user_text
;
2461 // Try to find a second contributor
2462 foreach ( $res as $row ) {
2463 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2464 $onlyAuthor = false;
2469 $onlyAuthor = false;
2472 // Generate the summary with a '$1' placeholder
2474 // The current revision is blank and the one before is also
2475 // blank. It's just not our lucky day
2476 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2478 if ( $onlyAuthor ) {
2479 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2481 $reason = wfMsgForContent( 'excontent', '$1' );
2485 if ( $reason == '-' ) {
2486 // Allow these UI messages to be blanked out cleanly
2490 // Replace newlines with spaces to prevent uglyness
2491 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2492 // Calculate the maximum amount of chars to get
2493 // Max content length = max comment length - length of the comment (excl. $1)
2494 $maxLength = 255 - ( strlen( $reason ) - 2 );
2495 $contents = $wgContLang->truncate( $contents, $maxLength );
2496 // Remove possible unfinished links
2497 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2498 // Now replace the '$1' placeholder
2499 $reason = str_replace( '$1', $contents, $reason );
2505 * Get parser options suitable for rendering the primary article wikitext
2506 * @param User|string $user User object or 'canonical'
2507 * @return ParserOptions
2509 public function makeParserOptions( $user ) {
2511 if ( $user instanceof User
) { // settings per user (even anons)
2512 $options = ParserOptions
::newFromUser( $user );
2513 } else { // canonical settings
2514 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
2516 $options->enableLimitReport(); // show inclusion/loop reports
2517 $options->setTidy( true ); // fix bad HTML
2522 * Update all the appropriate counts in the category table, given that
2523 * we've added the categories $added and deleted the categories $deleted.
2525 * @param $added array The names of categories that were added
2526 * @param $deleted array The names of categories that were deleted
2528 public function updateCategoryCounts( $added, $deleted ) {
2529 $ns = $this->mTitle
->getNamespace();
2530 $dbw = wfGetDB( DB_MASTER
);
2532 # First make sure the rows exist. If one of the "deleted" ones didn't
2533 # exist, we might legitimately not create it, but it's simpler to just
2534 # create it and then give it a negative value, since the value is bogus
2537 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2538 $insertCats = array_merge( $added, $deleted );
2539 if ( !$insertCats ) {
2540 # Okay, nothing to do
2544 $insertRows = array();
2546 foreach ( $insertCats as $cat ) {
2547 $insertRows[] = array(
2548 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2552 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2554 $addFields = array( 'cat_pages = cat_pages + 1' );
2555 $removeFields = array( 'cat_pages = cat_pages - 1' );
2557 if ( $ns == NS_CATEGORY
) {
2558 $addFields[] = 'cat_subcats = cat_subcats + 1';
2559 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2560 } elseif ( $ns == NS_FILE
) {
2561 $addFields[] = 'cat_files = cat_files + 1';
2562 $removeFields[] = 'cat_files = cat_files - 1';
2569 array( 'cat_title' => $added ),
2578 array( 'cat_title' => $deleted ),
2585 * Updates cascading protections
2587 * @param $parserOutput ParserOutput object for the current version
2589 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2590 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2594 // templatelinks table may have become out of sync,
2595 // especially if using variable-based transclusions.
2596 // For paranoia, check if things have changed and if
2597 // so apply updates to the database. This will ensure
2598 // that cascaded protections apply as soon as the changes
2601 # Get templates from templatelinks
2602 $id = $this->mTitle
->getArticleID();
2604 $tlTemplates = array();
2606 $dbr = wfGetDB( DB_SLAVE
);
2607 $res = $dbr->select( array( 'templatelinks' ),
2608 array( 'tl_namespace', 'tl_title' ),
2609 array( 'tl_from' => $id ),
2613 foreach ( $res as $row ) {
2614 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2617 # Get templates from parser output.
2618 $poTemplates = array();
2619 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2620 foreach ( $templates as $dbk => $id ) {
2621 $poTemplates["$ns:$dbk"] = true;
2626 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2628 if ( count( $templates_diff ) > 0 ) {
2629 # Whee, link updates time.
2630 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2636 * @deprecated since 1.18
2638 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2640 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2644 * @deprecated since 1.18
2646 public function viewUpdates() {
2648 return $this->doViewUpdates( $wgUser );
2652 * @deprecated since 1.18
2654 public function useParserCache( $oldid ) {
2656 return $this->isParserCacheUsed( $wgUser, $oldid );