(bug 10323) Special:Undelete should have "inverse selection" button
[mediawiki.git] / includes / Article.php
blob88a7bfa33f1a253f131ba7f5b8758b6696af7c61
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
7 /**
8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
15 class Article {
16 /**@{{
17 * @private
19 var $mComment = ''; //!<
20 var $mContent; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
29 var $mMinorEdit; //!<
30 var $mOldId; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
36 var $mRevision; //!<
37 var $mTimestamp = ''; //!<
38 var $mTitle; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
43 /**@}}*/
45 /**
46 * Constructor and clear the article
47 * @param $title Reference to a Title object.
48 * @param $oldId Integer revision ID, null to fetch from request, zero for current
50 function __construct( Title $title, $oldId = null ) {
51 $this->mTitle =& $title;
52 $this->mOldId = $oldId;
55 /**
56 * Constructor from an article article
57 * @param $id The article ID to load
59 public static function newFromID( $id ) {
60 $t = Title::newFromID( $id );
62 return $t == null ? null : new Article( $t );
65 /**
66 * Tell the page view functions that this view was redirected
67 * from another page on the wiki.
68 * @param $from Title object.
70 function setRedirectedFrom( $from ) {
71 $this->mRedirectedFrom = $from;
74 /**
75 * If this page is a redirect, get its target
77 * The target will be fetched from the redirect table if possible.
78 * If this page doesn't have an entry there, call insertRedirect()
79 * @return mixed Title object, or null if this page is not a redirect
81 public function getRedirectTarget() {
82 if(!$this->mTitle || !$this->mTitle->isRedirect())
83 return null;
84 if(!is_null($this->mRedirectTarget))
85 return $this->mRedirectTarget;
87 # Query the redirect table
88 $dbr = wfGetDB(DB_SLAVE);
89 $res = $dbr->select('redirect',
90 array('rd_namespace', 'rd_title'),
91 array('rd_from' => $this->getID()),
92 __METHOD__
94 $row = $dbr->fetchObject($res);
95 if($row)
96 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
98 # This page doesn't have an entry in the redirect table
99 return $this->mRedirectTarget = $this->insertRedirect();
103 * Insert an entry for this page into the redirect table.
105 * Don't call this function directly unless you know what you're doing.
106 * @return Title object
108 public function insertRedirect() {
109 $retval = Title::newFromRedirect($this->getContent());
110 if(!$retval)
111 return null;
112 $dbw = wfGetDB(DB_MASTER);
113 $dbw->replace('redirect', array('rd_from'), array(
114 'rd_from' => $this->getID(),
115 'rd_namespace' => $retval->getNamespace(),
116 'rd_title' => $retval->getDBKey()
117 ), __METHOD__);
118 return $retval;
122 * Get the Title object this page redirects to
124 * @return mixed false, Title of in-wiki target, or string with URL
126 public function followRedirect() {
127 $text = $this->getContent();
128 return $this->followRedirectText( $text );
132 * Get the Title object this text redirects to
134 * @return mixed false, Title of in-wiki target, or string with URL
136 public function followRedirectText( $text ) {
137 $rt = Title::newFromRedirect( $text );
138 # process if title object is valid and not special:userlogout
139 if( $rt ) {
140 if( $rt->getInterwiki() != '' ) {
141 if( $rt->isLocal() ) {
142 // Offsite wikis need an HTTP redirect.
144 // This can be hard to reverse and may produce loops,
145 // so they may be disabled in the site configuration.
147 $source = $this->mTitle->getFullURL( 'redirect=no' );
148 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
150 } else {
151 if( $rt->getNamespace() == NS_SPECIAL ) {
152 // Gotta handle redirects to special pages differently:
153 // Fill the HTTP response "Location" header and ignore
154 // the rest of the page we're on.
156 // This can be hard to reverse, so they may be disabled.
158 if( $rt->isSpecial( 'Userlogout' ) ) {
159 // rolleyes
160 } else {
161 return $rt->getFullURL();
164 return $rt;
167 // No or invalid redirect
168 return false;
172 * get the title object of the article
174 function getTitle() {
175 return $this->mTitle;
179 * Clear the object
180 * @private
182 function clear() {
183 $this->mDataLoaded = false;
184 $this->mContentLoaded = false;
186 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
187 $this->mRedirectedFrom = null; # Title object if set
188 $this->mRedirectTarget = null; # Title object if set
189 $this->mUserText =
190 $this->mTimestamp = $this->mComment = '';
191 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
192 $this->mTouched = '19700101000000';
193 $this->mForUpdate = false;
194 $this->mIsRedirect = false;
195 $this->mRevIdFetched = 0;
196 $this->mRedirectUrl = false;
197 $this->mLatest = false;
198 $this->mPreparedEdit = false;
202 * Note that getContent/loadContent do not follow redirects anymore.
203 * If you need to fetch redirectable content easily, try
204 * the shortcut in Article::followContent()
205 * FIXME
206 * @todo There are still side-effects in this!
207 * In general, you should use the Revision class, not Article,
208 * to fetch text for purposes other than page views.
210 * @return Return the text of this revision
212 function getContent() {
213 global $wgUser, $wgOut, $wgMessageCache;
215 wfProfileIn( __METHOD__ );
217 if ( 0 == $this->getID() ) {
218 wfProfileOut( __METHOD__ );
219 $wgOut->setRobotPolicy( 'noindex,nofollow' );
221 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
222 $wgMessageCache->loadAllMessages();
223 $ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
224 } else {
225 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
228 return "<div class='noarticletext'>\n$ret\n</div>";
229 } else {
230 $this->loadContent();
231 wfProfileOut( __METHOD__ );
232 return $this->mContent;
237 * This function returns the text of a section, specified by a number ($section).
238 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
239 * the first section before any such heading (section 0).
241 * If a section contains subsections, these are also returned.
243 * @param $text String: text to look in
244 * @param $section Integer: section number
245 * @return string text of the requested section
246 * @deprecated
248 function getSection($text,$section) {
249 global $wgParser;
250 return $wgParser->getSection( $text, $section );
254 * @return int The oldid of the article that is to be shown, 0 for the
255 * current revision
257 function getOldID() {
258 if ( is_null( $this->mOldId ) ) {
259 $this->mOldId = $this->getOldIDFromRequest();
261 return $this->mOldId;
265 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
267 * @return int The old id for the request
269 public function getOldIDFromRequest() {
270 global $wgRequest;
271 $this->mRedirectUrl = false;
272 $oldid = $wgRequest->getVal( 'oldid' );
273 if ( isset( $oldid ) ) {
274 $oldid = intval( $oldid );
275 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
276 $nextid = $this->mTitle->getNextRevisionID( $oldid );
277 if ( $nextid ) {
278 $oldid = $nextid;
279 } else {
280 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
282 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
283 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
284 if ( $previd ) {
285 $oldid = $previd;
286 } else {
287 # TODO
290 # unused:
291 # $lastid = $oldid;
294 if ( !$oldid ) {
295 $oldid = 0;
297 return $oldid;
301 * Load the revision (including text) into this object
303 function loadContent() {
304 if ( $this->mContentLoaded ) return;
306 # Query variables :P
307 $oldid = $this->getOldID();
309 # Pre-fill content with error message so that if something
310 # fails we'll have something telling us what we intended.
311 $this->mOldId = $oldid;
312 $this->fetchContent( $oldid );
317 * Fetch a page record with the given conditions
318 * @param Database $dbr
319 * @param array $conditions
320 * @private
322 function pageData( $dbr, $conditions ) {
323 $fields = array(
324 'page_id',
325 'page_namespace',
326 'page_title',
327 'page_restrictions',
328 'page_counter',
329 'page_is_redirect',
330 'page_is_new',
331 'page_random',
332 'page_touched',
333 'page_latest',
334 'page_len',
336 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
337 $row = $dbr->selectRow(
338 'page',
339 $fields,
340 $conditions,
341 __METHOD__
343 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
344 return $row ;
348 * @param Database $dbr
349 * @param Title $title
351 function pageDataFromTitle( $dbr, $title ) {
352 return $this->pageData( $dbr, array(
353 'page_namespace' => $title->getNamespace(),
354 'page_title' => $title->getDBkey() ) );
358 * @param Database $dbr
359 * @param int $id
361 function pageDataFromId( $dbr, $id ) {
362 return $this->pageData( $dbr, array( 'page_id' => $id ) );
366 * Set the general counter, title etc data loaded from
367 * some source.
369 * @param object $data
370 * @private
372 function loadPageData( $data = 'fromdb' ) {
373 if ( $data === 'fromdb' ) {
374 $dbr = wfGetDB( DB_MASTER );
375 $data = $this->pageDataFromId( $dbr, $this->getId() );
378 $lc = LinkCache::singleton();
379 if ( $data ) {
380 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
382 $this->mTitle->mArticleID = $data->page_id;
384 # Old-fashioned restrictions.
385 $this->mTitle->loadRestrictions( $data->page_restrictions );
387 $this->mCounter = $data->page_counter;
388 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
389 $this->mIsRedirect = $data->page_is_redirect;
390 $this->mLatest = $data->page_latest;
391 } else {
392 if ( is_object( $this->mTitle ) ) {
393 $lc->addBadLinkObj( $this->mTitle );
395 $this->mTitle->mArticleID = 0;
398 $this->mDataLoaded = true;
402 * Get text of an article from database
403 * Does *NOT* follow redirects.
404 * @param int $oldid 0 for whatever the latest revision is
405 * @return string
407 function fetchContent( $oldid = 0 ) {
408 if ( $this->mContentLoaded ) {
409 return $this->mContent;
412 $dbr = wfGetDB( DB_MASTER );
414 # Pre-fill content with error message so that if something
415 # fails we'll have something telling us what we intended.
416 $t = $this->mTitle->getPrefixedText();
417 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
418 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
420 if( $oldid ) {
421 $revision = Revision::newFromId( $oldid );
422 if( is_null( $revision ) ) {
423 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
424 return false;
426 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
427 if( !$data ) {
428 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
429 return false;
431 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
432 $this->loadPageData( $data );
433 } else {
434 if( !$this->mDataLoaded ) {
435 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
436 if( !$data ) {
437 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
438 return false;
440 $this->loadPageData( $data );
442 $revision = Revision::newFromId( $this->mLatest );
443 if( is_null( $revision ) ) {
444 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
445 return false;
449 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
450 // We should instead work with the Revision object when we need it...
451 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
453 $this->mUser = $revision->getUser();
454 $this->mUserText = $revision->getUserText();
455 $this->mComment = $revision->getComment();
456 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
458 $this->mRevIdFetched = $revision->getId();
459 $this->mContentLoaded = true;
460 $this->mRevision =& $revision;
462 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
464 return $this->mContent;
468 * Read/write accessor to select FOR UPDATE
470 * @param $x Mixed: FIXME
472 function forUpdate( $x = NULL ) {
473 return wfSetVar( $this->mForUpdate, $x );
477 * Get the database which should be used for reads
479 * @return Database
480 * @deprecated - just call wfGetDB( DB_MASTER ) instead
482 function getDB() {
483 wfDeprecated( __METHOD__ );
484 return wfGetDB( DB_MASTER );
488 * Get options for all SELECT statements
490 * @param $options Array: an optional options array which'll be appended to
491 * the default
492 * @return Array: options
494 function getSelectOptions( $options = '' ) {
495 if ( $this->mForUpdate ) {
496 if ( is_array( $options ) ) {
497 $options[] = 'FOR UPDATE';
498 } else {
499 $options = 'FOR UPDATE';
502 return $options;
506 * @return int Page ID
508 function getID() {
509 if( $this->mTitle ) {
510 return $this->mTitle->getArticleID();
511 } else {
512 return 0;
517 * @return bool Whether or not the page exists in the database
519 function exists() {
520 return $this->getId() != 0;
524 * @return int The view count for the page
526 function getCount() {
527 if ( -1 == $this->mCounter ) {
528 $id = $this->getID();
529 if ( $id == 0 ) {
530 $this->mCounter = 0;
531 } else {
532 $dbr = wfGetDB( DB_SLAVE );
533 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
534 'Article::getCount', $this->getSelectOptions() );
537 return $this->mCounter;
541 * Determine whether a page would be suitable for being counted as an
542 * article in the site_stats table based on the title & its content
544 * @param $text String: text to analyze
545 * @return bool
547 function isCountable( $text ) {
548 global $wgUseCommaCount;
550 $token = $wgUseCommaCount ? ',' : '[[';
551 return
552 $this->mTitle->isContentPage()
553 && !$this->isRedirect( $text )
554 && in_string( $token, $text );
558 * Tests if the article text represents a redirect
560 * @param $text String: FIXME
561 * @return bool
563 function isRedirect( $text = false ) {
564 if ( $text === false ) {
565 if ( $this->mDataLoaded )
566 return $this->mIsRedirect;
568 // Apparently loadPageData was never called
569 $this->loadContent();
570 $titleObj = Title::newFromRedirect( $this->fetchContent() );
571 } else {
572 $titleObj = Title::newFromRedirect( $text );
574 return $titleObj !== NULL;
578 * Returns true if the currently-referenced revision is the current edit
579 * to this page (and it exists).
580 * @return bool
582 function isCurrent() {
583 # If no oldid, this is the current version.
584 if ($this->getOldID() == 0)
585 return true;
587 return $this->exists() &&
588 isset( $this->mRevision ) &&
589 $this->mRevision->isCurrent();
593 * Loads everything except the text
594 * This isn't necessary for all uses, so it's only done if needed.
595 * @private
597 function loadLastEdit() {
598 if ( -1 != $this->mUser )
599 return;
601 # New or non-existent articles have no user information
602 $id = $this->getID();
603 if ( 0 == $id ) return;
605 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
606 if( !is_null( $this->mLastRevision ) ) {
607 $this->mUser = $this->mLastRevision->getUser();
608 $this->mUserText = $this->mLastRevision->getUserText();
609 $this->mTimestamp = $this->mLastRevision->getTimestamp();
610 $this->mComment = $this->mLastRevision->getComment();
611 $this->mMinorEdit = $this->mLastRevision->isMinor();
612 $this->mRevIdFetched = $this->mLastRevision->getId();
616 function getTimestamp() {
617 // Check if the field has been filled by ParserCache::get()
618 if ( !$this->mTimestamp ) {
619 $this->loadLastEdit();
621 return wfTimestamp(TS_MW, $this->mTimestamp);
624 function getUser() {
625 $this->loadLastEdit();
626 return $this->mUser;
629 function getUserText() {
630 $this->loadLastEdit();
631 return $this->mUserText;
634 function getComment() {
635 $this->loadLastEdit();
636 return $this->mComment;
639 function getMinorEdit() {
640 $this->loadLastEdit();
641 return $this->mMinorEdit;
644 function getRevIdFetched() {
645 $this->loadLastEdit();
646 return $this->mRevIdFetched;
650 * @param $limit Integer: default 0.
651 * @param $offset Integer: default 0.
653 function getContributors($limit = 0, $offset = 0) {
654 # XXX: this is expensive; cache this info somewhere.
656 $contribs = array();
657 $dbr = wfGetDB( DB_SLAVE );
658 $revTable = $dbr->tableName( 'revision' );
659 $userTable = $dbr->tableName( 'user' );
660 $user = $this->getUser();
661 $pageId = $this->getId();
663 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
664 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
665 WHERE rev_page = $pageId
666 AND rev_user != $user
667 GROUP BY rev_user, rev_user_text, user_real_name
668 ORDER BY timestamp DESC";
670 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
671 if ($offset > 0) { $sql .= ' OFFSET '.$offset; }
673 $sql .= ' '. $this->getSelectOptions();
675 $res = $dbr->query($sql, __METHOD__ );
677 return new UserArrayFromResult( $res );
681 * This is the default action of the script: just view the page of
682 * the given title.
684 function view() {
685 global $wgUser, $wgOut, $wgRequest, $wgContLang;
686 global $wgEnableParserCache, $wgStylePath, $wgParser;
687 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
688 global $wgDefaultRobotPolicy;
689 $sk = $wgUser->getSkin();
691 wfProfileIn( __METHOD__ );
693 $parserCache = ParserCache::singleton();
694 $ns = $this->mTitle->getNamespace(); # shortcut
696 # Get variables from query string
697 $oldid = $this->getOldID();
699 # getOldID may want us to redirect somewhere else
700 if ( $this->mRedirectUrl ) {
701 $wgOut->redirect( $this->mRedirectUrl );
702 wfProfileOut( __METHOD__ );
703 return;
706 $diff = $wgRequest->getVal( 'diff' );
707 $rcid = $wgRequest->getVal( 'rcid' );
708 $rdfrom = $wgRequest->getVal( 'rdfrom' );
709 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
710 $purge = $wgRequest->getVal( 'action' ) == 'purge';
712 $wgOut->setArticleFlag( true );
714 # Discourage indexing of printable versions, but encourage following
715 if( $wgOut->isPrintable() ) {
716 $policy = 'noindex,follow';
717 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
718 $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
719 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
720 # Honour customised robot policies for this namespace
721 $policy = $wgNamespaceRobotPolicies[$ns];
722 } else {
723 $policy = $wgDefaultRobotPolicy;
725 $wgOut->setRobotPolicy( $policy );
727 # If we got diff and oldid in the query, we want to see a
728 # diff page instead of the article.
730 if ( !is_null( $diff ) ) {
731 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
733 $diff = $wgRequest->getVal( 'diff' );
734 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
735 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff);
736 // DifferenceEngine directly fetched the revision:
737 $this->mRevIdFetched = $de->mNewid;
738 $de->showDiffPage( $diffOnly );
740 // Needed to get the page's current revision
741 $this->loadPageData();
742 if( $diff == 0 || $diff == $this->mLatest ) {
743 # Run view updates for current revision only
744 $this->viewUpdates();
746 wfProfileOut( __METHOD__ );
747 return;
750 if ( empty( $oldid ) && $this->checkTouched() ) {
751 $wgOut->setETag($parserCache->getETag($this, $wgUser));
753 if( $wgOut->checkLastModified( $this->mTouched ) ){
754 wfProfileOut( __METHOD__ );
755 return;
756 } else if ( $this->tryFileCache() ) {
757 # tell wgOut that output is taken care of
758 $wgOut->disable();
759 $this->viewUpdates();
760 wfProfileOut( __METHOD__ );
761 return;
765 # Should the parser cache be used?
766 $pcache = $this->useParserCache( $oldid );
767 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
768 if ( $wgUser->getOption( 'stubthreshold' ) ) {
769 wfIncrStats( 'pcache_miss_stub' );
772 $wasRedirected = false;
773 if ( isset( $this->mRedirectedFrom ) ) {
774 // This is an internally redirected page view.
775 // We'll need a backlink to the source page for navigation.
776 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
777 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
778 $s = wfMsg( 'redirectedfrom', $redir );
779 $wgOut->setSubtitle( $s );
781 // Set the fragment if one was specified in the redirect
782 if ( strval( $this->mTitle->getFragment() ) != '' ) {
783 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
784 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
786 $wasRedirected = true;
788 } elseif ( !empty( $rdfrom ) ) {
789 // This is an externally redirected view, from some other wiki.
790 // If it was reported from a trusted site, supply a backlink.
791 global $wgRedirectSources;
792 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
793 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
794 $s = wfMsg( 'redirectedfrom', $redir );
795 $wgOut->setSubtitle( $s );
796 $wasRedirected = true;
800 # Optional notices on a per-namespace and per-page basis
801 $mw = MagicWord::get( 'noheader' );
802 $ignoreheader = false;
803 $text = $this->getContent();
804 if( $mw->match( $text ) ) {
805 $ignoreheader = true;
807 $pageheader_ns = 'pageheader-'.$this->mTitle->getNamespace();
808 $pageheader_page = $pageheader_ns.'-'.$this->mTitle->getDBkey();
809 if ( !wfEmptyMsg( $pageheader_ns, wfMsgForContent( $pageheader_ns ) ) && !$ignoreheader ) {
810 $wgOut->addWikiText( wfMsgForContent( $pageheader_ns ) );
813 if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) && !$ignoreheader ) {
814 $parts = explode( '/', $this->mTitle->getDBkey() );
815 $pageheader_base = $pageheader_ns;
816 while ( count( $parts ) > 0 ) {
817 $pageheader_base .= '-'.array_shift( $parts );
818 if ( !wfEmptyMsg( $pageheader_base, wfMsgForContent( $pageheader_base ) ) ) {
819 $wgOut->addWikiText( wfMsgForContent( $pageheader_base ) );
822 } else if ( !wfEmptyMsg( $pageheader_page, wfMsgForContent( $pageheader_page ) ) && !$ignoreheader ) {
823 $wgOut->addWikiText( wfMsgForContent( $pageheader_page ) );
826 $outputDone = false;
827 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
828 if ( $pcache ) {
829 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
830 // Ensure that UI elements requiring revision ID have
831 // the correct version information.
832 $wgOut->setRevisionId( $this->mLatest );
833 $outputDone = true;
836 # Fetch content and check for errors
837 if ( !$outputDone ) {
838 # If the article does not exist and was deleted, show the log
839 if ($this->getID() == 0) {
840 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
841 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
842 $count = $pager->getNumRows();
843 if( $count > 0 ) {
844 $pager->mLimit = 10;
845 $wgOut->addHtml( '<div id="mw-deleted-notice">' );
846 $wgOut->addWikiMsg( 'deleted-notice' );
847 $wgOut->addHTML(
848 $loglist->beginLogEventsList() .
849 $pager->getBody() .
850 $loglist->endLogEventsList()
852 if($count > 10){
853 $wgOut->addHtml( $wgUser->getSkin()->link(
854 SpecialPage::getTitleFor( 'Log' ),
855 wfMsgHtml( 'deletelog-fulllog' ),
856 array(),
857 array(
858 'type' => 'delete',
859 'page' => $this->mTitle->getPrefixedText() ) ) );
861 $wgOut->addHtml( '</div>' );
864 if ( $text === false ) {
865 # Failed to load, replace text with error message
866 $t = $this->mTitle->getPrefixedText();
867 if( $oldid ) {
868 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
869 $text = wfMsg( 'missing-article', $t, $d );
870 } else {
871 $text = wfMsg( 'noarticletext' );
875 # Another whitelist check in case oldid is altering the title
876 if ( !$this->mTitle->userCanRead() ) {
877 $wgOut->loginToUse();
878 $wgOut->output();
879 wfProfileOut( __METHOD__ );
880 exit;
883 # We're looking at an old revision
884 if ( !empty( $oldid ) ) {
885 $wgOut->setRobotPolicy( 'noindex,nofollow' );
886 if( is_null( $this->mRevision ) ) {
887 // FIXME: This would be a nice place to load the 'no such page' text.
888 } else {
889 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
890 if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
891 if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
892 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
893 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
894 wfProfileOut( __METHOD__ );
895 return;
896 } else {
897 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
898 // and we are allowed to see...
904 $wgOut->setRevisionId( $this->getRevIdFetched() );
906 // Pages containing custom CSS or JavaScript get special treatment
907 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
908 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
909 // Give hooks a chance to customise the output
910 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
911 // Wrap the whole lot in a <pre> and don't parse
912 $m = array();
913 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
914 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
915 $wgOut->addHtml( htmlspecialchars( $this->mContent ) );
916 $wgOut->addHtml( "\n</pre>\n" );
918 } else if ( $rt = Title::newFromRedirect( $text ) ) {
919 # Don't append the subtitle if this was an old revision
920 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
921 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
922 $wgOut->addParserOutputNoText( $parseout );
923 } else if ( $pcache ) {
924 # Display content and save to parser cache
925 $this->outputWikiText( $text );
926 } else {
927 # Display content, don't attempt to save to parser cache
928 # Don't show section-edit links on old revisions... this way lies madness.
929 if( !$this->isCurrent() ) {
930 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
932 # Display content and don't save to parser cache
933 # With timing hack -- TS 2006-07-26
934 $time = -wfTime();
935 $this->outputWikiText( $text, false );
936 $time += wfTime();
938 # Timing hack
939 if ( $time > 3 ) {
940 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
941 $this->mTitle->getPrefixedDBkey()));
944 if( !$this->isCurrent() ) {
945 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
949 /* title may have been set from the cache */
950 $t = $wgOut->getPageTitle();
951 if( empty( $t ) ) {
952 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
954 # For the main page, overwrite the <title> element with the con-
955 # tents of 'pagetitle-view-mainpage' instead of the default (if
956 # that's not empty).
957 if( $this->mTitle->equals( Title::newMainPage() ) &&
958 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
959 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
963 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
964 if( $ns == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
965 $wgOut->addWikiMsg('anontalkpagetext');
968 # If we have been passed an &rcid= parameter, we want to give the user a
969 # chance to mark this new article as patrolled.
970 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle->exists() ) {
971 $wgOut->addHTML(
972 "<div class='patrollink'>" .
973 wfMsgHtml( 'markaspatrolledlink',
974 $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
975 "action=markpatrolled&rcid=$rcid" )
977 '</div>'
981 # Trackbacks
982 if ($wgUseTrackbacks)
983 $this->addTrackbacks();
985 $this->viewUpdates();
986 wfProfileOut( __METHOD__ );
990 * Should the parser cache be used?
992 protected function useParserCache( $oldid ) {
993 global $wgUser, $wgEnableParserCache;
995 return $wgEnableParserCache
996 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
997 && $this->exists()
998 && empty( $oldid )
999 && !$this->mTitle->isCssOrJsPage()
1000 && !$this->mTitle->isCssJsSubpage();
1004 * View redirect
1005 * @param Title $target Title of destination to redirect
1006 * @param Bool $appendSubtitle Object[optional]
1007 * @param Bool $forceKnown Should the image be shown as a bluelink regardless of existence?
1009 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1010 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1012 # Display redirect
1013 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1014 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
1016 if( $appendSubtitle ) {
1017 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1019 $sk = $wgUser->getSkin();
1020 if ( $forceKnown )
1021 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1022 else
1023 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1025 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1026 '<span class="redirectText">'.$link.'</span>';
1030 function addTrackbacks() {
1031 global $wgOut, $wgUser;
1033 $dbr = wfGetDB(DB_SLAVE);
1034 $tbs = $dbr->select(
1035 /* FROM */ 'trackbacks',
1036 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1037 /* WHERE */ array('tb_page' => $this->getID())
1040 if (!$dbr->numrows($tbs))
1041 return;
1043 $tbtext = "";
1044 while ($o = $dbr->fetchObject($tbs)) {
1045 $rmvtxt = "";
1046 if ($wgUser->isAllowed( 'trackback' )) {
1047 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
1048 . $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1049 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1051 $tbtext .= "\n";
1052 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1053 $o->tb_title,
1054 $o->tb_url,
1055 $o->tb_ex,
1056 $o->tb_name,
1057 $rmvtxt);
1059 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1062 function deletetrackback() {
1063 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1065 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
1066 $wgOut->addWikiMsg( 'sessionfailure' );
1067 return;
1070 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1072 if (count($permission_errors)>0)
1074 $wgOut->showPermissionsErrorPage( $permission_errors );
1075 return;
1078 $db = wfGetDB(DB_MASTER);
1079 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1080 $wgTitle->invalidateCache();
1081 $wgOut->addWikiMsg('trackbackdeleteok');
1084 function render() {
1085 global $wgOut;
1087 $wgOut->setArticleBodyOnly(true);
1088 $this->view();
1092 * Handle action=purge
1094 function purge() {
1095 global $wgUser, $wgRequest, $wgOut;
1097 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1098 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1099 $this->doPurge();
1100 $this->view();
1102 } else {
1103 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1104 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1105 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1106 $msg = str_replace( '$1',
1107 "<form method=\"post\" action=\"$action\">\n" .
1108 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1109 "</form>\n", $msg );
1111 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1112 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1113 $wgOut->addHTML( $msg );
1118 * Perform the actions of a page purging
1120 function doPurge() {
1121 global $wgUseSquid;
1122 // Invalidate the cache
1123 $this->mTitle->invalidateCache();
1125 if ( $wgUseSquid ) {
1126 // Commit the transaction before the purge is sent
1127 $dbw = wfGetDB( DB_MASTER );
1128 $dbw->immediateCommit();
1130 // Send purge
1131 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1132 $update->doUpdate();
1134 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1135 global $wgMessageCache;
1136 if ( $this->getID() == 0 ) {
1137 $text = false;
1138 } else {
1139 $text = $this->getContent();
1141 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1146 * Insert a new empty page record for this article.
1147 * This *must* be followed up by creating a revision
1148 * and running $this->updateToLatest( $rev_id );
1149 * or else the record will be left in a funky state.
1150 * Best if all done inside a transaction.
1152 * @param Database $dbw
1153 * @return int The newly created page_id key, or false if the title already existed
1154 * @private
1156 function insertOn( $dbw ) {
1157 wfProfileIn( __METHOD__ );
1159 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1160 $dbw->insert( 'page', array(
1161 'page_id' => $page_id,
1162 'page_namespace' => $this->mTitle->getNamespace(),
1163 'page_title' => $this->mTitle->getDBkey(),
1164 'page_counter' => 0,
1165 'page_restrictions' => '',
1166 'page_is_redirect' => 0, # Will set this shortly...
1167 'page_is_new' => 1,
1168 'page_random' => wfRandom(),
1169 'page_touched' => $dbw->timestamp(),
1170 'page_latest' => 0, # Fill this in shortly...
1171 'page_len' => 0, # Fill this in shortly...
1172 ), __METHOD__, 'IGNORE' );
1174 $affected = $dbw->affectedRows();
1175 if ( $affected ) {
1176 $newid = $dbw->insertId();
1177 $this->mTitle->resetArticleId( $newid );
1179 wfProfileOut( __METHOD__ );
1180 return $affected ? $newid : false;
1184 * Update the page record to point to a newly saved revision.
1186 * @param Database $dbw
1187 * @param Revision $revision For ID number, and text used to set
1188 length and redirect status fields
1189 * @param int $lastRevision If given, will not overwrite the page field
1190 * when different from the currently set value.
1191 * Giving 0 indicates the new page flag should
1192 * be set on.
1193 * @param bool $lastRevIsRedirect If given, will optimize adding and
1194 * removing rows in redirect table.
1195 * @return bool true on success, false on failure
1196 * @private
1198 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1199 wfProfileIn( __METHOD__ );
1201 $text = $revision->getText();
1202 $rt = Title::newFromRedirect( $text );
1204 $conditions = array( 'page_id' => $this->getId() );
1205 if( !is_null( $lastRevision ) ) {
1206 # An extra check against threads stepping on each other
1207 $conditions['page_latest'] = $lastRevision;
1210 $dbw->update( 'page',
1211 array( /* SET */
1212 'page_latest' => $revision->getId(),
1213 'page_touched' => $dbw->timestamp(),
1214 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1215 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1216 'page_len' => strlen( $text ),
1218 $conditions,
1219 __METHOD__ );
1221 $result = $dbw->affectedRows() != 0;
1223 if ($result) {
1224 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1227 wfProfileOut( __METHOD__ );
1228 return $result;
1232 * Add row to the redirect table if this is a redirect, remove otherwise.
1234 * @param Database $dbw
1235 * @param $redirectTitle a title object pointing to the redirect target,
1236 * or NULL if this is not a redirect
1237 * @param bool $lastRevIsRedirect If given, will optimize adding and
1238 * removing rows in redirect table.
1239 * @return bool true on success, false on failure
1240 * @private
1242 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1244 // Always update redirects (target link might have changed)
1245 // Update/Insert if we don't know if the last revision was a redirect or not
1246 // Delete if changing from redirect to non-redirect
1247 $isRedirect = !is_null($redirectTitle);
1248 if ($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1250 wfProfileIn( __METHOD__ );
1252 if ($isRedirect) {
1254 // This title is a redirect, Add/Update row in the redirect table
1255 $set = array( /* SET */
1256 'rd_namespace' => $redirectTitle->getNamespace(),
1257 'rd_title' => $redirectTitle->getDBkey(),
1258 'rd_from' => $this->getId(),
1261 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1262 } else {
1263 // This is not a redirect, remove row from redirect table
1264 $where = array( 'rd_from' => $this->getId() );
1265 $dbw->delete( 'redirect', $where, __METHOD__);
1268 if( $this->getTitle()->getNamespace() == NS_IMAGE )
1269 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1270 wfProfileOut( __METHOD__ );
1271 return ( $dbw->affectedRows() != 0 );
1274 return true;
1278 * If the given revision is newer than the currently set page_latest,
1279 * update the page record. Otherwise, do nothing.
1281 * @param Database $dbw
1282 * @param Revision $revision
1284 function updateIfNewerOn( &$dbw, $revision ) {
1285 wfProfileIn( __METHOD__ );
1287 $row = $dbw->selectRow(
1288 array( 'revision', 'page' ),
1289 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1290 array(
1291 'page_id' => $this->getId(),
1292 'page_latest=rev_id' ),
1293 __METHOD__ );
1294 if( $row ) {
1295 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1296 wfProfileOut( __METHOD__ );
1297 return false;
1299 $prev = $row->rev_id;
1300 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1301 } else {
1302 # No or missing previous revision; mark the page as new
1303 $prev = 0;
1304 $lastRevIsRedirect = null;
1307 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1308 wfProfileOut( __METHOD__ );
1309 return $ret;
1313 * @return string Complete article text, or null if error
1315 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1316 wfProfileIn( __METHOD__ );
1318 if( $section == '' ) {
1319 // Whole-page edit; let the text through unmolested.
1320 } else {
1321 if( is_null( $edittime ) ) {
1322 $rev = Revision::newFromTitle( $this->mTitle );
1323 } else {
1324 $dbw = wfGetDB( DB_MASTER );
1325 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1327 if( is_null( $rev ) ) {
1328 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1329 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1330 return null;
1332 $oldtext = $rev->getText();
1334 if( $section == 'new' ) {
1335 # Inserting a new section
1336 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1337 $text = strlen( trim( $oldtext ) ) > 0
1338 ? "{$oldtext}\n\n{$subject}{$text}"
1339 : "{$subject}{$text}";
1340 } else {
1341 # Replacing an existing section; roll out the big guns
1342 global $wgParser;
1343 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1348 wfProfileOut( __METHOD__ );
1349 return $text;
1353 * @deprecated use Article::doEdit()
1355 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1356 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1357 ( $isminor ? EDIT_MINOR : 0 ) |
1358 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1359 ( $bot ? EDIT_FORCE_BOT : 0 );
1361 # If this is a comment, add the summary as headline
1362 if ( $comment && $summary != "" ) {
1363 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1366 $this->doEdit( $text, $summary, $flags );
1368 $dbw = wfGetDB( DB_MASTER );
1369 if ($watchthis) {
1370 if (!$this->mTitle->userIsWatching()) {
1371 $dbw->begin();
1372 $this->doWatch();
1373 $dbw->commit();
1375 } else {
1376 if ( $this->mTitle->userIsWatching() ) {
1377 $dbw->begin();
1378 $this->doUnwatch();
1379 $dbw->commit();
1382 $this->doRedirect( $this->isRedirect( $text ) );
1386 * @deprecated use Article::doEdit()
1388 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1389 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1390 ( $minor ? EDIT_MINOR : 0 ) |
1391 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1393 $status = $this->doEdit( $text, $summary, $flags );
1394 if ( !$status->isOK() ) {
1395 return false;
1398 $dbw = wfGetDB( DB_MASTER );
1399 if ($watchthis) {
1400 if (!$this->mTitle->userIsWatching()) {
1401 $dbw->begin();
1402 $this->doWatch();
1403 $dbw->commit();
1405 } else {
1406 if ( $this->mTitle->userIsWatching() ) {
1407 $dbw->begin();
1408 $this->doUnwatch();
1409 $dbw->commit();
1413 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1414 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1416 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1417 return true;
1421 * Article::doEdit()
1423 * Change an existing article or create a new article. Updates RC and all necessary caches,
1424 * optionally via the deferred update array.
1426 * $wgUser must be set before calling this function.
1428 * @param string $text New text
1429 * @param string $summary Edit summary
1430 * @param integer $flags bitfield:
1431 * EDIT_NEW
1432 * Article is known or assumed to be non-existent, create a new one
1433 * EDIT_UPDATE
1434 * Article is known or assumed to be pre-existing, update it
1435 * EDIT_MINOR
1436 * Mark this edit minor, if the user is allowed to do so
1437 * EDIT_SUPPRESS_RC
1438 * Do not log the change in recentchanges
1439 * EDIT_FORCE_BOT
1440 * Mark the edit a "bot" edit regardless of user rights
1441 * EDIT_DEFER_UPDATES
1442 * Defer some of the updates until the end of index.php
1443 * EDIT_AUTOSUMMARY
1444 * Fill in blank summaries with generated text where possible
1446 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1447 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1448 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1449 * edit-already-exists error will be returned. These two conditions are also possible with
1450 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1452 * @param $baseRevId, the revision ID this edit was based off, if any
1454 * @return Status object. Possible errors:
1455 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1456 * edit-gone-missing: In update mode, but the article didn't exist
1457 * edit-conflict: In update mode, the article changed unexpectedly
1458 * edit-no-change: Warning that the text was the same as before
1459 * edit-already-exists: In creation mode, but the article already exists
1461 * Extensions may define additional errors.
1463 * $return->value will contain an associative array with members as follows:
1464 * new: Boolean indicating if the function attempted to create a new article
1465 * revision: The revision object for the inserted revision, or null
1467 * Compatibility note: this function previously returned a boolean value indicating success/failure
1469 function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1470 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1472 # Low-level sanity check
1473 if( $this->mTitle->getText() == '' ) {
1474 throw new MWException( 'Something is trying to edit an article with an empty title' );
1477 wfProfileIn( __METHOD__ );
1479 if ($user == null) {
1480 $user = $wgUser;
1482 $status = Status::newGood( array() );
1484 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1485 $this->loadPageData();
1487 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1488 $aid = $this->mTitle->getArticleID();
1489 if ( $aid ) {
1490 $flags |= EDIT_UPDATE;
1491 } else {
1492 $flags |= EDIT_NEW;
1496 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text,
1497 &$summary, $flags & EDIT_MINOR,
1498 null, null, &$flags, &$status ) ) )
1500 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1501 wfProfileOut( __METHOD__ );
1502 if ( $status->isOK() ) {
1503 $status->fatal( 'edit-hook-aborted');
1505 return $status;
1508 # Silently ignore EDIT_MINOR if not allowed
1509 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1510 $bot = $flags & EDIT_FORCE_BOT;
1512 $oldtext = $this->getContent();
1513 $oldsize = strlen( $oldtext );
1515 # Provide autosummaries if one is not provided and autosummaries are enabled.
1516 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1517 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1520 $editInfo = $this->prepareTextForEdit( $text );
1521 $text = $editInfo->pst;
1522 $newsize = strlen( $text );
1524 $dbw = wfGetDB( DB_MASTER );
1525 $now = wfTimestampNow();
1527 if ( $flags & EDIT_UPDATE ) {
1528 # Update article, but only if changed.
1529 $status->value['new'] = false;
1531 # Make sure the revision is either completely inserted or not inserted at all
1532 if( !$wgDBtransactions ) {
1533 $userAbort = ignore_user_abort( true );
1536 $revisionId = 0;
1538 $changed = ( strcmp( $text, $oldtext ) != 0 );
1540 if ( $changed ) {
1541 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1542 - (int)$this->isCountable( $oldtext );
1543 $this->mTotalAdjustment = 0;
1545 if ( !$this->mLatest ) {
1546 # Article gone missing
1547 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1548 $status->fatal( 'edit-gone-missing' );
1549 wfProfileOut( __METHOD__ );
1550 return $status;
1553 $revision = new Revision( array(
1554 'page' => $this->getId(),
1555 'comment' => $summary,
1556 'minor_edit' => $isminor,
1557 'text' => $text,
1558 'parent_id' => $this->mLatest,
1559 'user' => $user->getId(),
1560 'user_text' => $user->getName(),
1561 ) );
1563 $dbw->begin();
1564 $revisionId = $revision->insertOn( $dbw );
1566 # Update page
1568 # Note that we use $this->mLatest instead of fetching a value from the master DB
1569 # during the course of this function. This makes sure that EditPage can detect
1570 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1571 # before this function is called. A previous function used a separate query, this
1572 # creates a window where concurrent edits can cause an ignored edit conflict.
1573 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1575 if( !$ok ) {
1576 /* Belated edit conflict! Run away!! */
1577 $status->fatal( 'edit-conflict' );
1578 # Delete the invalid revision if the DB is not transactional
1579 if ( !$wgDBtransactions ) {
1580 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1582 $revisionId = 0;
1583 $dbw->rollback();
1584 } else {
1585 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
1587 # Update recentchanges
1588 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1589 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1590 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1591 $revisionId );
1593 # Mark as patrolled if the user can do so
1594 if( $GLOBALS['wgUseRCPatrol'] && $user->isAllowed( 'autopatrol' ) ) {
1595 RecentChange::markPatrolled( $rc, true );
1598 $user->incEditCount();
1599 $dbw->commit();
1601 } else {
1602 $status->warning( 'edit-no-change' );
1603 $revision = null;
1604 // Keep the same revision ID, but do some updates on it
1605 $revisionId = $this->getRevIdFetched();
1606 // Update page_touched, this is usually implicit in the page update
1607 // Other cache updates are done in onArticleEdit()
1608 $this->mTitle->invalidateCache();
1611 if( !$wgDBtransactions ) {
1612 ignore_user_abort( $userAbort );
1614 // Now that ignore_user_abort is restored, we can respond to fatal errors
1615 if ( !$status->isOK() ) {
1616 wfProfileOut( __METHOD__ );
1617 return $status;
1620 # Invalidate cache of this article and all pages using this article
1621 # as a template. Partly deferred.
1622 Article::onArticleEdit( $this->mTitle, false ); // leave templatelinks for editUpdates()
1623 # Update links tables, site stats, etc.
1624 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1625 } else {
1626 # Create new article
1627 $status->value['new'] = true;
1629 # Set statistics members
1630 # We work out if it's countable after PST to avoid counter drift
1631 # when articles are created with {{subst:}}
1632 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1633 $this->mTotalAdjustment = 1;
1635 $dbw->begin();
1637 # Add the page record; stake our claim on this title!
1638 # This will return false if the article already exists
1639 $newid = $this->insertOn( $dbw );
1641 if ( $newid === false ) {
1642 $dbw->rollback();
1643 $status->fatal( 'edit-already-exists' );
1644 wfProfileOut( __METHOD__ );
1645 return $status;
1648 # Save the revision text...
1649 $revision = new Revision( array(
1650 'page' => $newid,
1651 'comment' => $summary,
1652 'minor_edit' => $isminor,
1653 'text' => $text,
1654 'user' => $user->getId(),
1655 'user_text' => $user->getName(),
1656 ) );
1657 $revisionId = $revision->insertOn( $dbw );
1659 $this->mTitle->resetArticleID( $newid );
1661 # Update the page record with revision data
1662 $this->updateRevisionOn( $dbw, $revision, 0 );
1664 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1666 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1667 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1668 '', strlen( $text ), $revisionId );
1669 # Mark as patrolled if the user can
1670 if( ($GLOBALS['wgUseRCPatrol'] || $GLOBALS['wgUseNPPatrol']) && $user->isAllowed( 'autopatrol' ) ) {
1671 RecentChange::markPatrolled( $rc, true );
1674 $user->incEditCount();
1675 $dbw->commit();
1677 # Update links, etc.
1678 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1680 # Clear caches
1681 Article::onArticleCreate( $this->mTitle );
1683 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1684 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1687 # Do updates right now unless deferral was requested
1688 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1689 wfDoUpdates();
1692 // Return the new revision (or null) to the caller
1693 $status->value['revision'] = $revision;
1695 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1696 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status ) );
1698 wfProfileOut( __METHOD__ );
1699 return $status;
1703 * @deprecated wrapper for doRedirect
1705 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1706 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1710 * Output a redirect back to the article.
1711 * This is typically used after an edit.
1713 * @param boolean $noRedir Add redirect=no
1714 * @param string $sectionAnchor section to redirect to, including "#"
1715 * @param string $extraQuery, extra query params
1717 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1718 global $wgOut;
1719 if ( $noRedir ) {
1720 $query = 'redirect=no';
1721 if( $extraQuery )
1722 $query .= "&$query";
1723 } else {
1724 $query = $extraQuery;
1726 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1730 * Mark this particular edit/page as patrolled
1732 function markpatrolled() {
1733 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1734 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1736 # If we haven't been given an rc_id value, we can't do anything
1737 $rcid = (int) $wgRequest->getVal('rcid');
1738 $rc = RecentChange::newFromId($rcid);
1739 if ( is_null($rc) ) {
1740 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1741 return;
1744 #It would be nice to see where the user had actually come from, but for now just guess
1745 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1746 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1748 $dbw = wfGetDB( DB_MASTER );
1749 $errors = $rc->doMarkPatrolled();
1751 if ( in_array(array('rcpatroldisabled'), $errors) ) {
1752 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1753 return;
1756 if ( in_array(array('hookaborted'), $errors) ) {
1757 // The hook itself has handled any output
1758 return;
1761 if ( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1762 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1763 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1764 $wgOut->returnToMain( false, $return );
1765 return;
1768 if ( !empty($errors) ) {
1769 $wgOut->showPermissionsErrorPage( $errors );
1770 return;
1773 # Inform the user
1774 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1775 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1776 $wgOut->returnToMain( false, $return );
1780 * User-interface handler for the "watch" action
1783 function watch() {
1785 global $wgUser, $wgOut;
1787 if ( $wgUser->isAnon() ) {
1788 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1789 return;
1791 if ( wfReadOnly() ) {
1792 $wgOut->readOnlyPage();
1793 return;
1796 if( $this->doWatch() ) {
1797 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1798 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1800 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1803 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1807 * Add this page to $wgUser's watchlist
1808 * @return bool true on successful watch operation
1810 function doWatch() {
1811 global $wgUser;
1812 if( $wgUser->isAnon() ) {
1813 return false;
1816 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1817 $wgUser->addWatch( $this->mTitle );
1819 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1822 return false;
1826 * User interface handler for the "unwatch" action.
1828 function unwatch() {
1830 global $wgUser, $wgOut;
1832 if ( $wgUser->isAnon() ) {
1833 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1834 return;
1836 if ( wfReadOnly() ) {
1837 $wgOut->readOnlyPage();
1838 return;
1841 if( $this->doUnwatch() ) {
1842 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1843 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1845 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1848 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1852 * Stop watching a page
1853 * @return bool true on successful unwatch
1855 function doUnwatch() {
1856 global $wgUser;
1857 if( $wgUser->isAnon() ) {
1858 return false;
1861 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1862 $wgUser->removeWatch( $this->mTitle );
1864 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1867 return false;
1871 * action=protect handler
1873 function protect() {
1874 $form = new ProtectionForm( $this );
1875 $form->execute();
1879 * action=unprotect handler (alias)
1881 function unprotect() {
1882 $this->protect();
1886 * Update the article's restriction field, and leave a log entry.
1888 * @param array $limit set of restriction keys
1889 * @param string $reason
1890 * @return bool true on success
1892 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = array() ) {
1893 global $wgUser, $wgRestrictionTypes, $wgContLang;
1895 $id = $this->mTitle->getArticleID();
1896 if( array() != $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser ) || wfReadOnly() || $id == 0 ) {
1897 return false;
1900 if( !$cascade ) {
1901 $cascade = false;
1904 // Take this opportunity to purge out expired restrictions
1905 Title::purgeExpiredRestrictions();
1907 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1908 # we expect a single selection, but the schema allows otherwise.
1909 $current = array();
1910 $updated = Article::flattenRestrictions( $limit );
1911 $changed = false;
1912 foreach( $wgRestrictionTypes as $action ) {
1913 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1914 $changed = ($changed || ($this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action]) );
1917 $current = Article::flattenRestrictions( $current );
1919 $changed = ($changed || ( $current != $updated ) );
1920 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
1921 $protect = ( $updated != '' );
1923 # If nothing's changed, do nothing
1924 if( $changed ) {
1925 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1927 $dbw = wfGetDB( DB_MASTER );
1929 # Prepare a null revision to be added to the history
1930 $modified = $current != '' && $protect;
1931 if( $protect ) {
1932 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1933 } else {
1934 $comment_type = 'unprotectedarticle';
1936 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1938 # Only restrictions with the 'protect' right can cascade...
1939 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1940 foreach( $limit as $action => $restriction ) {
1941 # FIXME: can $restriction be an array or what? (same as fixme above)
1942 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1943 $cascade = false;
1944 break;
1947 $cascade_description = '';
1948 if( $cascade ) {
1949 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1952 if( $reason )
1953 $comment .= ": $reason";
1955 $editComment = $comment;
1956 $encodedExpiry = array();
1957 $protect_description = '';
1958 foreach( $limit as $action => $restrictions ) {
1959 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
1960 if( $restrictions != '' ) {
1961 $protect_description .= "[$action=$restrictions] (";
1962 if( $encodedExpiry[$action] != 'infinity' ) {
1963 $protect_description .= wfMsgForContent( 'protect-expiring',
1964 $wgContLang->timeanddate( $expiry[$action], false, false ) );
1965 } else {
1966 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1968 $protect_description .= ') ';
1971 $protect_description = trim($protect_description);
1973 if( $protect_description && $protect )
1974 $editComment .= " ($protect_description)";
1975 if( $cascade )
1976 $editComment .= "$cascade_description";
1977 # Update restrictions table
1978 foreach( $limit as $action => $restrictions ) {
1979 if ($restrictions != '' ) {
1980 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1981 array( 'pr_page' => $id,
1982 'pr_type' => $action,
1983 'pr_level' => $restrictions,
1984 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
1985 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
1986 } else {
1987 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1988 'pr_type' => $action ), __METHOD__ );
1992 # Insert a null revision
1993 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1994 $nullRevId = $nullRevision->insertOn( $dbw );
1996 $latest = $this->getLatest();
1997 # Update page record
1998 $dbw->update( 'page',
1999 array( /* SET */
2000 'page_touched' => $dbw->timestamp(),
2001 'page_restrictions' => '',
2002 'page_latest' => $nullRevId
2003 ), array( /* WHERE */
2004 'page_id' => $id
2005 ), 'Article::protect'
2008 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest) );
2009 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2011 # Update the protection log
2012 $log = new LogPage( 'protect' );
2013 if( $protect ) {
2014 $params = array($protect_description,$cascade ? 'cascade' : '');
2015 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
2016 } else {
2017 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2020 } # End hook
2021 } # End "changed" check
2023 return true;
2027 * Take an array of page restrictions and flatten it to a string
2028 * suitable for insertion into the page_restrictions field.
2029 * @param array $limit
2030 * @return string
2031 * @private
2033 function flattenRestrictions( $limit ) {
2034 if( !is_array( $limit ) ) {
2035 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2037 $bits = array();
2038 ksort( $limit );
2039 foreach( $limit as $action => $restrictions ) {
2040 if( $restrictions != '' ) {
2041 $bits[] = "$action=$restrictions";
2044 return implode( ':', $bits );
2048 * Auto-generates a deletion reason
2049 * @param bool &$hasHistory Whether the page has a history
2051 public function generateReason( &$hasHistory ) {
2052 global $wgContLang;
2053 $dbw = wfGetDB( DB_MASTER );
2054 // Get the last revision
2055 $rev = Revision::newFromTitle( $this->mTitle );
2056 if( is_null( $rev ) )
2057 return false;
2059 // Get the article's contents
2060 $contents = $rev->getText();
2061 $blank = false;
2062 // If the page is blank, use the text from the previous revision,
2063 // which can only be blank if there's a move/import/protect dummy revision involved
2064 if( $contents == '' ) {
2065 $prev = $rev->getPrevious();
2066 if( $prev ) {
2067 $contents = $prev->getText();
2068 $blank = true;
2072 // Find out if there was only one contributor
2073 // Only scan the last 20 revisions
2074 $limit = 20;
2075 $res = $dbw->select( 'revision', 'rev_user_text',
2076 array( 'rev_page' => $this->getID() ), __METHOD__,
2077 array( 'LIMIT' => $limit )
2079 if( $res === false )
2080 // This page has no revisions, which is very weird
2081 return false;
2082 if( $res->numRows() > 1 )
2083 $hasHistory = true;
2084 else
2085 $hasHistory = false;
2086 $row = $dbw->fetchObject( $res );
2087 $onlyAuthor = $row->rev_user_text;
2088 // Try to find a second contributor
2089 foreach( $res as $row ) {
2090 if( $row->rev_user_text != $onlyAuthor ) {
2091 $onlyAuthor = false;
2092 break;
2095 $dbw->freeResult( $res );
2097 // Generate the summary with a '$1' placeholder
2098 if( $blank ) {
2099 // The current revision is blank and the one before is also
2100 // blank. It's just not our lucky day
2101 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2102 } else {
2103 if( $onlyAuthor )
2104 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2105 else
2106 $reason = wfMsgForContent( 'excontent', '$1' );
2109 // Replace newlines with spaces to prevent uglyness
2110 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2111 // Calculate the maximum amount of chars to get
2112 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2113 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2114 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2115 // Remove possible unfinished links
2116 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2117 // Now replace the '$1' placeholder
2118 $reason = str_replace( '$1', $contents, $reason );
2119 return $reason;
2124 * UI entry point for page deletion
2126 function delete() {
2127 global $wgUser, $wgOut, $wgRequest;
2129 $confirm = $wgRequest->wasPosted() &&
2130 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2132 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2133 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2135 $reason = $this->DeleteReasonList;
2137 if ( $reason != 'other' && $this->DeleteReason != '') {
2138 // Entry from drop down menu + additional comment
2139 $reason .= ': ' . $this->DeleteReason;
2140 } elseif ( $reason == 'other' ) {
2141 $reason = $this->DeleteReason;
2143 # Flag to hide all contents of the archived revisions
2144 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2146 # This code desperately needs to be totally rewritten
2148 # Read-only check...
2149 if ( wfReadOnly() ) {
2150 $wgOut->readOnlyPage();
2151 return;
2154 # Check permissions
2155 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2157 if (count($permission_errors)>0) {
2158 $wgOut->showPermissionsErrorPage( $permission_errors );
2159 return;
2162 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2164 # Better double-check that it hasn't been deleted yet!
2165 $dbw = wfGetDB( DB_MASTER );
2166 $conds = $this->mTitle->pageCond();
2167 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2168 if ( $latest === false ) {
2169 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2170 return;
2173 # Hack for big sites
2174 $bigHistory = $this->isBigDeletion();
2175 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2176 global $wgLang, $wgDeleteRevisionsLimit;
2177 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2178 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2179 return;
2182 if( $confirm ) {
2183 $this->doDelete( $reason, $suppress );
2184 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2185 $this->doWatch();
2186 } elseif( $this->mTitle->userIsWatching() ) {
2187 $this->doUnwatch();
2189 return;
2192 // Generate deletion reason
2193 $hasHistory = false;
2194 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2196 // If the page has a history, insert a warning
2197 if( $hasHistory && !$confirm ) {
2198 $skin=$wgUser->getSkin();
2199 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2200 if( $bigHistory ) {
2201 global $wgLang, $wgDeleteRevisionsLimit;
2202 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2203 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2207 return $this->confirmDelete( $reason );
2211 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2213 function isBigDeletion() {
2214 global $wgDeleteRevisionsLimit;
2215 if( $wgDeleteRevisionsLimit ) {
2216 $revCount = $this->estimateRevisionCount();
2217 return $revCount > $wgDeleteRevisionsLimit;
2219 return false;
2223 * @return int approximate revision count
2225 function estimateRevisionCount() {
2226 $dbr = wfGetDB( DB_SLAVE );
2227 // For an exact count...
2228 //return $dbr->selectField( 'revision', 'COUNT(*)',
2229 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2230 return $dbr->estimateRowCount( 'revision', '*',
2231 array( 'rev_page' => $this->getId() ), __METHOD__ );
2235 * Get the last N authors
2236 * @param int $num Number of revisions to get
2237 * @param string $revLatest The latest rev_id, selected from the master (optional)
2238 * @return array Array of authors, duplicates not removed
2240 function getLastNAuthors( $num, $revLatest = 0 ) {
2241 wfProfileIn( __METHOD__ );
2243 // First try the slave
2244 // If that doesn't have the latest revision, try the master
2245 $continue = 2;
2246 $db = wfGetDB( DB_SLAVE );
2247 do {
2248 $res = $db->select( array( 'page', 'revision' ),
2249 array( 'rev_id', 'rev_user_text' ),
2250 array(
2251 'page_namespace' => $this->mTitle->getNamespace(),
2252 'page_title' => $this->mTitle->getDBkey(),
2253 'rev_page = page_id'
2254 ), __METHOD__, $this->getSelectOptions( array(
2255 'ORDER BY' => 'rev_timestamp DESC',
2256 'LIMIT' => $num
2259 if ( !$res ) {
2260 wfProfileOut( __METHOD__ );
2261 return array();
2263 $row = $db->fetchObject( $res );
2264 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2265 $db = wfGetDB( DB_MASTER );
2266 $continue--;
2267 } else {
2268 $continue = 0;
2270 } while ( $continue );
2272 $authors = array( $row->rev_user_text );
2273 while ( $row = $db->fetchObject( $res ) ) {
2274 $authors[] = $row->rev_user_text;
2276 wfProfileOut( __METHOD__ );
2277 return $authors;
2281 * Output deletion confirmation dialog
2282 * @param $reason string Prefilled reason
2284 function confirmDelete( $reason ) {
2285 global $wgOut, $wgUser, $wgContLang;
2286 $align = $wgContLang->isRtl() ? 'left' : 'right';
2288 wfDebug( "Article::confirmDelete\n" );
2290 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2291 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2292 $wgOut->addWikiMsg( 'confirmdeletetext' );
2294 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2295 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2296 $suppress .= Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2297 $suppress .= "</td></tr>";
2298 } else {
2299 $suppress = '';
2301 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2303 $form = Xml::openElement( 'form', array( 'method' => 'post',
2304 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2305 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2306 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2307 Xml::openElement( 'table' ) .
2308 "<tr id=\"wpDeleteReasonListRow\">
2309 <td align='$align'>" .
2310 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2311 "</td>
2312 <td>" .
2313 Xml::listDropDown( 'wpDeleteReasonList',
2314 wfMsgForContent( 'deletereason-dropdown' ),
2315 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2316 "</td>
2317 </tr>
2318 <tr id=\"wpDeleteReasonRow\">
2319 <td align='$align'>" .
2320 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2321 "</td>
2322 <td>" .
2323 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2324 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2325 "</td>
2326 </tr>
2327 <tr>
2328 <td></td>
2329 <td>" .
2330 Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2331 "</td>
2332 </tr>
2333 $suppress
2334 <tr>
2335 <td></td>
2336 <td>" .
2337 Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2338 "</td>
2339 </tr>" .
2340 Xml::closeElement( 'table' ) .
2341 Xml::closeElement( 'fieldset' ) .
2342 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2343 Xml::closeElement( 'form' );
2345 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2346 $skin = $wgUser->getSkin();
2347 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2348 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2351 $wgOut->addHTML( $form );
2352 $this->showLogExtract( $wgOut );
2357 * Show relevant lines from the deletion log
2359 function showLogExtract( $out ) {
2360 $out->addHtml( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2361 LogEventsList::showLogExtract( $out, 'delete', $this->mTitle->getPrefixedText() );
2366 * Perform a deletion and output success or failure messages
2368 function doDelete( $reason, $suppress = false ) {
2369 global $wgOut, $wgUser;
2370 wfDebug( __METHOD__."\n" );
2372 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2374 $error = '';
2376 if ( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2377 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2378 $deleted = $this->mTitle->getPrefixedText();
2380 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2381 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2383 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2385 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2386 $wgOut->returnToMain( false );
2387 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2388 } else {
2389 if ($error = '')
2390 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2391 else
2392 $wgOut->showFatalError( $error );
2398 * Back-end article deletion
2399 * Deletes the article with database consistency, writes logs, purges caches
2400 * Returns success
2402 function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2403 global $wgUseSquid, $wgDeferredUpdateList;
2404 global $wgUseTrackbacks;
2406 wfDebug( __METHOD__."\n" );
2408 $dbw = wfGetDB( DB_MASTER );
2409 $ns = $this->mTitle->getNamespace();
2410 $t = $this->mTitle->getDBkey();
2411 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2413 if ( $t == '' || $id == 0 ) {
2414 return false;
2417 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2418 array_push( $wgDeferredUpdateList, $u );
2420 // Bitfields to further suppress the content
2421 if ( $suppress ) {
2422 $bitfield = 0;
2423 // This should be 15...
2424 $bitfield |= Revision::DELETED_TEXT;
2425 $bitfield |= Revision::DELETED_COMMENT;
2426 $bitfield |= Revision::DELETED_USER;
2427 $bitfield |= Revision::DELETED_RESTRICTED;
2428 } else {
2429 $bitfield = 'rev_deleted';
2432 $dbw->begin();
2433 // For now, shunt the revision data into the archive table.
2434 // Text is *not* removed from the text table; bulk storage
2435 // is left intact to avoid breaking block-compression or
2436 // immutable storage schemes.
2438 // For backwards compatibility, note that some older archive
2439 // table entries will have ar_text and ar_flags fields still.
2441 // In the future, we may keep revisions and mark them with
2442 // the rev_deleted field, which is reserved for this purpose.
2443 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2444 array(
2445 'ar_namespace' => 'page_namespace',
2446 'ar_title' => 'page_title',
2447 'ar_comment' => 'rev_comment',
2448 'ar_user' => 'rev_user',
2449 'ar_user_text' => 'rev_user_text',
2450 'ar_timestamp' => 'rev_timestamp',
2451 'ar_minor_edit' => 'rev_minor_edit',
2452 'ar_rev_id' => 'rev_id',
2453 'ar_text_id' => 'rev_text_id',
2454 'ar_text' => '\'\'', // Be explicit to appease
2455 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2456 'ar_len' => 'rev_len',
2457 'ar_page_id' => 'page_id',
2458 'ar_deleted' => $bitfield
2459 ), array(
2460 'page_id' => $id,
2461 'page_id = rev_page'
2462 ), __METHOD__
2465 # Delete restrictions for it
2466 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2468 # Now that it's safely backed up, delete it
2469 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2470 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2471 if( !$ok ) {
2472 $dbw->rollback();
2473 return false;
2476 # If using cascading deletes, we can skip some explicit deletes
2477 if ( !$dbw->cascadingDeletes() ) {
2478 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2480 if ($wgUseTrackbacks)
2481 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2483 # Delete outgoing links
2484 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2485 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2486 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2487 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2488 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2489 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2490 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2493 # If using cleanup triggers, we can skip some manual deletes
2494 if ( !$dbw->cleanupTriggers() ) {
2495 # Clean up recentchanges entries...
2496 $dbw->delete( 'recentchanges',
2497 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2498 __METHOD__ );
2501 # Clear caches
2502 Article::onArticleDelete( $this->mTitle );
2504 # Fix category table counts
2505 $cats = array();
2506 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2507 foreach( $res as $row ) {
2508 $cats []= $row->cl_to;
2510 $this->updateCategoryCounts( array(), $cats );
2512 # Clear the cached article id so the interface doesn't act like we exist
2513 $this->mTitle->resetArticleID( 0 );
2514 $this->mTitle->mArticleID = 0;
2516 # Log the deletion, if the page was suppressed, log it at Oversight instead
2517 $logtype = $suppress ? 'suppress' : 'delete';
2518 $log = new LogPage( $logtype );
2520 # Make sure logging got through
2521 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2523 $dbw->commit();
2525 return true;
2529 * Roll back the most recent consecutive set of edits to a page
2530 * from the same user; fails if there are no eligible edits to
2531 * roll back to, e.g. user is the sole contributor. This function
2532 * performs permissions checks on $wgUser, then calls commitRollback()
2533 * to do the dirty work
2535 * @param string $fromP - Name of the user whose edits to rollback.
2536 * @param string $summary - Custom summary. Set to default summary if empty.
2537 * @param string $token - Rollback token.
2538 * @param bool $bot - If true, mark all reverted edits as bot.
2540 * @param array $resultDetails contains result-specific array of additional values
2541 * 'alreadyrolled' : 'current' (rev)
2542 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2544 * @return array of errors, each error formatted as
2545 * array(messagekey, param1, param2, ...).
2546 * On success, the array is empty. This array can also be passed to
2547 * OutputPage::showPermissionsErrorPage().
2549 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2550 global $wgUser;
2551 $resultDetails = null;
2553 # Check permissions
2554 $errors = array_merge( $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ),
2555 $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
2556 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2557 $errors[] = array( 'sessionfailure' );
2559 if ( $wgUser->pingLimiter('rollback') || $wgUser->pingLimiter() ) {
2560 $errors[] = array( 'actionthrottledtext' );
2562 # If there were errors, bail out now
2563 if(!empty($errors))
2564 return $errors;
2566 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2570 * Backend implementation of doRollback(), please refer there for parameter
2571 * and return value documentation
2573 * NOTE: This function does NOT check ANY permissions, it just commits the
2574 * rollback to the DB Therefore, you should only call this function direct-
2575 * ly if you want to use custom permissions checks. If you don't, use
2576 * doRollback() instead.
2578 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2579 global $wgUseRCPatrol, $wgUser, $wgLang;
2580 $dbw = wfGetDB( DB_MASTER );
2582 if( wfReadOnly() ) {
2583 return array( array( 'readonlytext' ) );
2586 # Get the last editor
2587 $current = Revision::newFromTitle( $this->mTitle );
2588 if( is_null( $current ) ) {
2589 # Something wrong... no page?
2590 return array(array('notanarticle'));
2593 $from = str_replace( '_', ' ', $fromP );
2594 if( $from != $current->getUserText() ) {
2595 $resultDetails = array( 'current' => $current );
2596 return array(array('alreadyrolled',
2597 htmlspecialchars($this->mTitle->getPrefixedText()),
2598 htmlspecialchars($fromP),
2599 htmlspecialchars($current->getUserText())
2603 # Get the last edit not by this guy
2604 $user = intval( $current->getUser() );
2605 $user_text = $dbw->addQuotes( $current->getUserText() );
2606 $s = $dbw->selectRow( 'revision',
2607 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2608 array( 'rev_page' => $current->getPage(),
2609 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2610 ), __METHOD__,
2611 array( 'USE INDEX' => 'page_timestamp',
2612 'ORDER BY' => 'rev_timestamp DESC' )
2614 if( $s === false ) {
2615 # No one else ever edited this page
2616 return array(array('cantrollback'));
2617 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2618 # Only admins can see this text
2619 return array(array('notvisiblerev'));
2622 $set = array();
2623 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2624 # Mark all reverted edits as bot
2625 $set['rc_bot'] = 1;
2627 if ( $wgUseRCPatrol ) {
2628 # Mark all reverted edits as patrolled
2629 $set['rc_patrolled'] = 1;
2632 if ( $set ) {
2633 $dbw->update( 'recentchanges', $set,
2634 array( /* WHERE */
2635 'rc_cur_id' => $current->getPage(),
2636 'rc_user_text' => $current->getUserText(),
2637 "rc_timestamp > '{$s->rev_timestamp}'",
2638 ), __METHOD__
2642 # Generate the edit summary if necessary
2643 $target = Revision::newFromId( $s->rev_id );
2644 if( empty( $summary ) ){
2645 $summary = wfMsgForContent( 'revertpage' );
2648 # Allow the custom summary to use the same args as the default message
2649 $args = array(
2650 $target->getUserText(), $from, $s->rev_id,
2651 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2652 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2654 $summary = wfMsgReplaceArgs( $summary, $args );
2656 # Save
2657 $flags = EDIT_UPDATE;
2659 if( $wgUser->isAllowed('minoredit') )
2660 $flags |= EDIT_MINOR;
2662 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2663 $flags |= EDIT_FORCE_BOT;
2664 # Actually store the edit
2665 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2666 if ( !empty( $status->value['revision'] ) ) {
2667 $revId = $status->value['revision']->getId();
2668 } else {
2669 $revId = false;
2672 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2674 $resultDetails = array(
2675 'summary' => $summary,
2676 'current' => $current,
2677 'target' => $target,
2678 'newid' => $revId
2680 return array();
2684 * User interface for rollback operations
2686 function rollback() {
2687 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2688 $details = null;
2690 $result = $this->doRollback(
2691 $wgRequest->getVal( 'from' ),
2692 $wgRequest->getText( 'summary' ),
2693 $wgRequest->getVal( 'token' ),
2694 $wgRequest->getBool( 'bot' ),
2695 $details
2698 if( in_array( array( 'blocked' ), $result ) ) {
2699 $wgOut->blockedPage();
2700 return;
2702 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2703 $wgOut->rateLimited();
2704 return;
2706 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
2707 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2708 $errArray = $result[0];
2709 $errMsg = array_shift( $errArray );
2710 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2711 if( isset( $details['current'] ) ){
2712 $current = $details['current'];
2713 if( $current->getComment() != '' ) {
2714 $wgOut->addWikiMsgArray( 'editcomment', array(
2715 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2718 return;
2720 # Display permissions errors before read-only message -- there's no
2721 # point in misleading the user into thinking the inability to rollback
2722 # is only temporary.
2723 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2724 # array_diff is completely broken for arrays of arrays, sigh. Re-
2725 # move any 'readonlytext' error manually.
2726 $out = array();
2727 foreach( $result as $error ) {
2728 if( $error != array( 'readonlytext' ) ) {
2729 $out []= $error;
2732 $wgOut->showPermissionsErrorPage( $out );
2733 return;
2735 if( $result == array( array('readonlytext') ) ) {
2736 $wgOut->readOnlyPage();
2737 return;
2740 $current = $details['current'];
2741 $target = $details['target'];
2742 $newId = $details['newid'];
2743 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2744 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2745 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2746 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2747 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2748 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2749 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2750 $wgOut->returnToMain( false, $this->mTitle );
2752 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2753 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
2754 $de->showDiff( '', '' );
2760 * Do standard deferred updates after page view
2761 * @private
2763 function viewUpdates() {
2764 global $wgDeferredUpdateList, $wgUser;
2766 if ( 0 != $this->getID() ) {
2767 # Don't update page view counters on views from bot users (bug 14044)
2768 global $wgDisableCounters;
2769 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2770 Article::incViewCount( $this->getID() );
2771 $u = new SiteStatsUpdate( 1, 0, 0 );
2772 array_push( $wgDeferredUpdateList, $u );
2776 # Update newtalk / watchlist notification status
2777 $wgUser->clearNotification( $this->mTitle );
2781 * Prepare text which is about to be saved.
2782 * Returns a stdclass with source, pst and output members
2784 function prepareTextForEdit( $text, $revid=null ) {
2785 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2786 // Already prepared
2787 return $this->mPreparedEdit;
2789 global $wgParser;
2790 $edit = (object)array();
2791 $edit->revid = $revid;
2792 $edit->newText = $text;
2793 $edit->pst = $this->preSaveTransform( $text );
2794 $options = new ParserOptions;
2795 $options->setTidy( true );
2796 $options->enableLimitReport();
2797 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2798 $edit->oldText = $this->getContent();
2799 $this->mPreparedEdit = $edit;
2800 return $edit;
2804 * Do standard deferred updates after page edit.
2805 * Update links tables, site stats, search index and message cache.
2806 * Purges pages that include this page if the text was changed here.
2807 * Every 100th edit, prune the recent changes table.
2809 * @private
2810 * @param $text New text of the article
2811 * @param $summary Edit summary
2812 * @param $minoredit Minor edit
2813 * @param $timestamp_of_pagechange Timestamp associated with the page change
2814 * @param $newid rev_id value of the new revision
2815 * @param $changed Whether or not the content actually changed
2817 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2818 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2820 wfProfileIn( __METHOD__ );
2822 # Parse the text
2823 # Be careful not to double-PST: $text is usually already PST-ed once
2824 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2825 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2826 $editInfo = $this->prepareTextForEdit( $text, $newid );
2827 } else {
2828 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2829 $editInfo = $this->mPreparedEdit;
2832 # Save it to the parser cache
2833 if ( $wgEnableParserCache ) {
2834 $parserCache = ParserCache::singleton();
2835 $parserCache->save( $editInfo->output, $this, $wgUser );
2838 # Update the links tables
2839 $u = new LinksUpdate( $this->mTitle, $editInfo->output, false );
2840 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2841 $u->doUpdate();
2843 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2845 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2846 if ( 0 == mt_rand( 0, 99 ) ) {
2847 // Flush old entries from the `recentchanges` table; we do this on
2848 // random requests so as to avoid an increase in writes for no good reason
2849 global $wgRCMaxAge;
2850 $dbw = wfGetDB( DB_MASTER );
2851 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2852 $recentchanges = $dbw->tableName( 'recentchanges' );
2853 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2854 $dbw->query( $sql );
2858 $id = $this->getID();
2859 $title = $this->mTitle->getPrefixedDBkey();
2860 $shortTitle = $this->mTitle->getDBkey();
2862 if ( 0 == $id ) {
2863 wfProfileOut( __METHOD__ );
2864 return;
2867 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2868 array_push( $wgDeferredUpdateList, $u );
2869 $u = new SearchUpdate( $id, $title, $text );
2870 array_push( $wgDeferredUpdateList, $u );
2872 # If this is another user's talk page, update newtalk
2873 # Don't do this if $changed = false otherwise some idiot can null-edit a
2874 # load of user talk pages and piss people off, nor if it's a minor edit
2875 # by a properly-flagged bot.
2876 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2877 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2878 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2879 $other = User::newFromName( $shortTitle, false );
2880 if ( !$other ) {
2881 wfDebug( __METHOD__.": invalid username\n" );
2882 } elseif( User::isIP( $shortTitle ) ) {
2883 // An anonymous user
2884 $other->setNewtalk( true );
2885 } elseif( $other->isLoggedIn() ) {
2886 $other->setNewtalk( true );
2887 } else {
2888 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
2893 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2894 $wgMessageCache->replace( $shortTitle, $text );
2897 wfProfileOut( __METHOD__ );
2901 * Perform article updates on a special page creation.
2903 * @param Revision $rev
2905 * @todo This is a shitty interface function. Kill it and replace the
2906 * other shitty functions like editUpdates and such so it's not needed
2907 * anymore.
2909 function createUpdates( $rev ) {
2910 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2911 $this->mTotalAdjustment = 1;
2912 $this->editUpdates( $rev->getText(), $rev->getComment(),
2913 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2917 * Generate the navigation links when browsing through an article revisions
2918 * It shows the information as:
2919 * Revision as of \<date\>; view current revision
2920 * \<- Previous version | Next Version -\>
2922 * @private
2923 * @param string $oldid Revision ID of this article revision
2925 function setOldSubtitle( $oldid=0 ) {
2926 global $wgLang, $wgOut, $wgUser;
2928 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2929 return;
2932 $revision = Revision::newFromId( $oldid );
2934 $current = ( $oldid == $this->mLatest );
2935 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2936 $sk = $wgUser->getSkin();
2937 $lnk = $current
2938 ? wfMsg( 'currentrevisionlink' )
2939 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2940 $curdiff = $current
2941 ? wfMsg( 'diff' )
2942 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2943 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2944 $prevlink = $prev
2945 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2946 : wfMsg( 'previousrevision' );
2947 $prevdiff = $prev
2948 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2949 : wfMsg( 'diff' );
2950 $nextlink = $current
2951 ? wfMsg( 'nextrevision' )
2952 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2953 $nextdiff = $current
2954 ? wfMsg( 'diff' )
2955 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2957 $cdel='';
2958 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2959 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2960 if( $revision->isCurrent() ) {
2961 // We don't handle top deleted edits too well
2962 $cdel = wfMsgHtml('rev-delundel');
2963 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2964 // If revision was hidden from sysops
2965 $cdel = wfMsgHtml('rev-delundel');
2966 } else {
2967 $cdel = $sk->makeKnownLinkObj( $revdel,
2968 wfMsgHtml('rev-delundel'),
2969 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2970 '&oldid=' . urlencode( $oldid ) );
2971 // Bolden oversighted content
2972 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2973 $cdel = "<strong>$cdel</strong>";
2975 $cdel = "(<small>$cdel</small>) ";
2977 # Show user links if allowed to see them. Normally they
2978 # are hidden regardless, but since we can already see the text here...
2979 $userlinks = $sk->revUserTools( $revision, false );
2981 $m = wfMsg( 'revision-info-current' );
2982 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2983 ? 'revision-info-current'
2984 : 'revision-info';
2986 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2988 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff,
2989 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2990 $wgOut->setSubtitle( $r );
2994 * This function is called right before saving the wikitext,
2995 * so we can do things like signatures and links-in-context.
2997 * @param string $text
2999 function preSaveTransform( $text ) {
3000 global $wgParser, $wgUser;
3001 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3004 /* Caching functions */
3007 * checkLastModified returns true if it has taken care of all
3008 * output to the client that is necessary for this request.
3009 * (that is, it has sent a cached version of the page)
3011 function tryFileCache() {
3012 static $called = false;
3013 if( $called ) {
3014 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3015 return false;
3017 $called = true;
3018 if( $this->isFileCacheable() ) {
3019 $touched = $this->mTouched;
3020 $cache = new HTMLFileCache( $this->mTitle );
3021 if( $cache->isFileCacheGood( $touched ) ) {
3022 wfDebug( "Article::tryFileCache(): about to load file\n" );
3023 $cache->loadFromFileCache();
3024 return true;
3025 } else {
3026 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3027 ob_start( array(&$cache, 'saveToFileCache' ) );
3029 } else {
3030 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3032 return false;
3036 * Check if the page can be cached
3037 * @return bool
3039 function isFileCacheable() {
3040 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
3041 // Get all query values
3042 $queryVals = $wgRequest->getValues();
3043 foreach( $queryVals as $query => $val ) {
3044 if( $query == 'title' || ($query == 'action' && $val == 'view') ) {
3045 // Normal page view in query form
3046 } else {
3047 return false;
3050 // Check for non-standard user language; this covers uselang,
3051 // and extensions for auto-detecting user language.
3052 $ulang = $wgLang->getCode();
3053 $clang = $wgContLang->getCode();
3055 $cacheable = $wgUseFileCache
3056 && (!$wgShowIPinHeader)
3057 && ($this->getID() > 0)
3058 && ($wgUser->isAnon())
3059 && (!$wgUser->getNewtalk())
3060 && (!$this->mRedirectedFrom)
3061 && ($ulang === $clang);
3062 // Extension may have reason to disable file caching on some pages.
3063 if( $cacheable ) {
3064 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3066 return $cacheable;
3070 * Loads page_touched and returns a value indicating if it should be used
3073 function checkTouched() {
3074 if( !$this->mDataLoaded ) {
3075 $this->loadPageData();
3077 return !$this->mIsRedirect;
3081 * Get the page_touched field
3083 function getTouched() {
3084 # Ensure that page data has been loaded
3085 if( !$this->mDataLoaded ) {
3086 $this->loadPageData();
3088 return $this->mTouched;
3092 * Get the page_latest field
3094 function getLatest() {
3095 if ( !$this->mDataLoaded ) {
3096 $this->loadPageData();
3098 return $this->mLatest;
3102 * Edit an article without doing all that other stuff
3103 * The article must already exist; link tables etc
3104 * are not updated, caches are not flushed.
3106 * @param string $text text submitted
3107 * @param string $comment comment submitted
3108 * @param bool $minor whereas it's a minor modification
3110 function quickEdit( $text, $comment = '', $minor = 0 ) {
3111 wfProfileIn( __METHOD__ );
3113 $dbw = wfGetDB( DB_MASTER );
3114 $revision = new Revision( array(
3115 'page' => $this->getId(),
3116 'text' => $text,
3117 'comment' => $comment,
3118 'minor_edit' => $minor ? 1 : 0,
3119 ) );
3120 $revision->insertOn( $dbw );
3121 $this->updateRevisionOn( $dbw, $revision );
3123 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
3125 wfProfileOut( __METHOD__ );
3129 * Used to increment the view counter
3131 * @static
3132 * @param integer $id article id
3134 function incViewCount( $id ) {
3135 $id = intval( $id );
3136 global $wgHitcounterUpdateFreq, $wgDBtype;
3138 $dbw = wfGetDB( DB_MASTER );
3139 $pageTable = $dbw->tableName( 'page' );
3140 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3141 $acchitsTable = $dbw->tableName( 'acchits' );
3143 if( $wgHitcounterUpdateFreq <= 1 ) {
3144 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3145 return;
3148 # Not important enough to warrant an error page in case of failure
3149 $oldignore = $dbw->ignoreErrors( true );
3151 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3153 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3154 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3155 # Most of the time (or on SQL errors), skip row count check
3156 $dbw->ignoreErrors( $oldignore );
3157 return;
3160 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3161 $row = $dbw->fetchObject( $res );
3162 $rown = intval( $row->n );
3163 if( $rown >= $wgHitcounterUpdateFreq ){
3164 wfProfileIn( 'Article::incViewCount-collect' );
3165 $old_user_abort = ignore_user_abort( true );
3167 if ($wgDBtype == 'mysql')
3168 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3169 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3170 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3171 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3172 'GROUP BY hc_id');
3173 $dbw->query("DELETE FROM $hitcounterTable");
3174 if ($wgDBtype == 'mysql') {
3175 $dbw->query('UNLOCK TABLES');
3176 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3177 'WHERE page_id = hc_id');
3179 else {
3180 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3181 "FROM $acchitsTable WHERE page_id = hc_id");
3183 $dbw->query("DROP TABLE $acchitsTable");
3185 ignore_user_abort( $old_user_abort );
3186 wfProfileOut( 'Article::incViewCount-collect' );
3188 $dbw->ignoreErrors( $oldignore );
3191 /**#@+
3192 * The onArticle*() functions are supposed to be a kind of hooks
3193 * which should be called whenever any of the specified actions
3194 * are done.
3196 * This is a good place to put code to clear caches, for instance.
3198 * This is called on page move and undelete, as well as edit
3199 * @static
3200 * @param $title_obj a title object
3203 public static function onArticleCreate( $title ) {
3204 # Update existence markers on article/talk tabs...
3205 if ( $title->isTalkPage() ) {
3206 $other = $title->getSubjectPage();
3207 } else {
3208 $other = $title->getTalkPage();
3210 $other->invalidateCache();
3211 $other->purgeSquid();
3213 $title->touchLinks();
3214 $title->purgeSquid();
3215 $title->deleteTitleProtection();
3218 public static function onArticleDelete( $title ) {
3219 global $wgUseFileCache, $wgMessageCache;
3220 # Update existence markers on article/talk tabs...
3221 if( $title->isTalkPage() ) {
3222 $other = $title->getSubjectPage();
3223 } else {
3224 $other = $title->getTalkPage();
3226 $other->invalidateCache();
3227 $other->purgeSquid();
3229 $title->touchLinks();
3230 $title->purgeSquid();
3232 # File cache
3233 if ( $wgUseFileCache ) {
3234 $cm = new HTMLFileCache( $title );
3235 @unlink( $cm->fileCacheName() );
3238 # Messages
3239 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3240 $wgMessageCache->replace( $title->getDBkey(), false );
3242 # Images
3243 if( $title->getNamespace() == NS_IMAGE ) {
3244 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3245 $update->doUpdate();
3247 # User talk pages
3248 if( $title->getNamespace() == NS_USER_TALK ) {
3249 $user = User::newFromName( $title->getText(), false );
3250 $user->setNewtalk( false );
3255 * Purge caches on page update etc
3257 public static function onArticleEdit( $title, $touchTemplates = true ) {
3258 global $wgDeferredUpdateList, $wgUseFileCache;
3260 // Invalidate caches of articles which include this page
3261 if( $touchTemplates )
3262 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3264 // Invalidate the caches of all pages which redirect here
3265 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3267 # Purge squid for this page only
3268 $title->purgeSquid();
3270 # Clear file cache for this page only
3271 if ( $wgUseFileCache ) {
3272 $cm = new HTMLFileCache( $title );
3273 @unlink( $cm->fileCacheName() );
3277 /**#@-*/
3280 * Overriden by ImagePage class, only present here to avoid a fatal error
3281 * Called for ?action=revert
3283 public function revert(){
3284 global $wgOut;
3285 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3289 * Info about this page
3290 * Called for ?action=info when $wgAllowPageInfo is on.
3292 * @public
3294 function info() {
3295 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3297 if ( !$wgAllowPageInfo ) {
3298 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3299 return;
3302 $page = $this->mTitle->getSubjectPage();
3304 $wgOut->setPagetitle( $page->getPrefixedText() );
3305 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3306 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3308 if( !$this->mTitle->exists() ) {
3309 $wgOut->addHtml( '<div class="noarticletext">' );
3310 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3311 // This doesn't quite make sense; the user is asking for
3312 // information about the _page_, not the message... -- RC
3313 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3314 } else {
3315 $msg = $wgUser->isLoggedIn()
3316 ? 'noarticletext'
3317 : 'noarticletextanon';
3318 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3320 $wgOut->addHtml( '</div>' );
3321 } else {
3322 $dbr = wfGetDB( DB_SLAVE );
3323 $wl_clause = array(
3324 'wl_title' => $page->getDBkey(),
3325 'wl_namespace' => $page->getNamespace() );
3326 $numwatchers = $dbr->selectField(
3327 'watchlist',
3328 'COUNT(*)',
3329 $wl_clause,
3330 __METHOD__,
3331 $this->getSelectOptions() );
3333 $pageInfo = $this->pageCountInfo( $page );
3334 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3336 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3337 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3338 if( $talkInfo ) {
3339 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3341 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3342 if( $talkInfo ) {
3343 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3345 $wgOut->addHTML( '</ul>' );
3351 * Return the total number of edits and number of unique editors
3352 * on a given page. If page does not exist, returns false.
3354 * @param Title $title
3355 * @return array
3356 * @private
3358 function pageCountInfo( $title ) {
3359 $id = $title->getArticleId();
3360 if( $id == 0 ) {
3361 return false;
3364 $dbr = wfGetDB( DB_SLAVE );
3366 $rev_clause = array( 'rev_page' => $id );
3368 $edits = $dbr->selectField(
3369 'revision',
3370 'COUNT(rev_page)',
3371 $rev_clause,
3372 __METHOD__,
3373 $this->getSelectOptions() );
3375 $authors = $dbr->selectField(
3376 'revision',
3377 'COUNT(DISTINCT rev_user_text)',
3378 $rev_clause,
3379 __METHOD__,
3380 $this->getSelectOptions() );
3382 return array( 'edits' => $edits, 'authors' => $authors );
3386 * Return a list of templates used by this article.
3387 * Uses the templatelinks table
3389 * @return array Array of Title objects
3391 public function getUsedTemplates() {
3392 $result = array();
3393 $id = $this->mTitle->getArticleID();
3394 if( $id == 0 ) {
3395 return array();
3398 $dbr = wfGetDB( DB_SLAVE );
3399 $res = $dbr->select( array( 'templatelinks' ),
3400 array( 'tl_namespace', 'tl_title' ),
3401 array( 'tl_from' => $id ),
3402 __METHOD__ );
3403 if( false !== $res ) {
3404 foreach( $res as $row ) {
3405 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3408 $dbr->freeResult( $res );
3409 return $result;
3413 * Returns a list of hidden categories this page is a member of.
3414 * Uses the page_props and categorylinks tables.
3416 * @return array Array of Title objects
3418 public function getHiddenCategories() {
3419 $result = array();
3420 $id = $this->mTitle->getArticleID();
3421 if( $id == 0 ) {
3422 return array();
3425 $dbr = wfGetDB( DB_SLAVE );
3426 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3427 array( 'cl_to' ),
3428 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3429 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3430 __METHOD__ );
3431 if ( false !== $res ) {
3432 foreach( $res as $row ) {
3433 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3436 $dbr->freeResult( $res );
3437 return $result;
3441 * Return an applicable autosummary if one exists for the given edit.
3442 * @param string $oldtext The previous text of the page.
3443 * @param string $newtext The submitted text of the page.
3444 * @param bitmask $flags A bitmask of flags submitted for the edit.
3445 * @return string An appropriate autosummary, or an empty string.
3447 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3448 # Decide what kind of autosummary is needed.
3450 # Redirect autosummaries
3451 $rt = Title::newFromRedirect( $newtext );
3452 if( is_object( $rt ) ) {
3453 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3456 # New page autosummaries
3457 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3458 # If they're making a new article, give its text, truncated, in the summary.
3459 global $wgContLang;
3460 $truncatedtext = $wgContLang->truncate(
3461 str_replace("\n", ' ', $newtext),
3462 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3463 '...' );
3464 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3467 # Blanking autosummaries
3468 if( $oldtext != '' && $newtext == '' ) {
3469 return wfMsgForContent('autosumm-blank');
3470 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3471 # Removing more than 90% of the article
3472 global $wgContLang;
3473 $truncatedtext = $wgContLang->truncate(
3474 $newtext,
3475 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3476 '...'
3478 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3481 # If we reach this point, there's no applicable autosummary for our case, so our
3482 # autosummary is empty.
3483 return '';
3487 * Add the primary page-view wikitext to the output buffer
3488 * Saves the text into the parser cache if possible.
3489 * Updates templatelinks if it is out of date.
3491 * @param string $text
3492 * @param bool $cache
3494 public function outputWikiText( $text, $cache = true ) {
3495 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3497 $popts = $wgOut->parserOptions();
3498 $popts->setTidy(true);
3499 $popts->enableLimitReport();
3500 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3501 $popts, true, true, $this->getRevIdFetched() );
3502 $popts->setTidy(false);
3503 $popts->enableLimitReport( false );
3504 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3505 $parserCache = ParserCache::singleton();
3506 $parserCache->save( $parserOutput, $this, $wgUser );
3508 // Make sure file cache is not used on uncacheable content.
3509 // Output that has magic words in it can still use the parser cache
3510 // (if enabled), though it will generally expire sooner.
3511 if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
3512 $wgUseFileCache = false;
3515 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3516 // templatelinks table may have become out of sync,
3517 // especially if using variable-based transclusions.
3518 // For paranoia, check if things have changed and if
3519 // so apply updates to the database. This will ensure
3520 // that cascaded protections apply as soon as the changes
3521 // are visible.
3523 # Get templates from templatelinks
3524 $id = $this->mTitle->getArticleID();
3526 $tlTemplates = array();
3528 $dbr = wfGetDB( DB_SLAVE );
3529 $res = $dbr->select( array( 'templatelinks' ),
3530 array( 'tl_namespace', 'tl_title' ),
3531 array( 'tl_from' => $id ),
3532 __METHOD__ );
3534 global $wgContLang;
3536 if ( false !== $res ) {
3537 foreach( $res as $row ) {
3538 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3542 # Get templates from parser output.
3543 $poTemplates_allns = $parserOutput->getTemplates();
3545 $poTemplates = array ();
3546 foreach ( $poTemplates_allns as $ns_templates ) {
3547 $poTemplates = array_merge( $poTemplates, $ns_templates );
3550 # Get the diff
3551 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3553 if ( count( $templates_diff ) > 0 ) {
3554 # Whee, link updates time.
3555 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3556 $u->doUpdate();
3560 $wgOut->addParserOutput( $parserOutput );
3564 * Update all the appropriate counts in the category table, given that
3565 * we've added the categories $added and deleted the categories $deleted.
3567 * @param $added array The names of categories that were added
3568 * @param $deleted array The names of categories that were deleted
3569 * @return null
3571 public function updateCategoryCounts( $added, $deleted ) {
3572 $ns = $this->mTitle->getNamespace();
3573 $dbw = wfGetDB( DB_MASTER );
3575 # First make sure the rows exist. If one of the "deleted" ones didn't
3576 # exist, we might legitimately not create it, but it's simpler to just
3577 # create it and then give it a negative value, since the value is bogus
3578 # anyway.
3580 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3581 $insertCats = array_merge( $added, $deleted );
3582 if( !$insertCats ) {
3583 # Okay, nothing to do
3584 return;
3586 $insertRows = array();
3587 foreach( $insertCats as $cat ) {
3588 $insertRows[] = array( 'cat_title' => $cat );
3590 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3592 $addFields = array( 'cat_pages = cat_pages + 1' );
3593 $removeFields = array( 'cat_pages = cat_pages - 1' );
3594 if( $ns == NS_CATEGORY ) {
3595 $addFields[] = 'cat_subcats = cat_subcats + 1';
3596 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3597 } elseif( $ns == NS_IMAGE ) {
3598 $addFields[] = 'cat_files = cat_files + 1';
3599 $removeFields[] = 'cat_files = cat_files - 1';
3602 if ( $added ) {
3603 $dbw->update(
3604 'category',
3605 $addFields,
3606 array( 'cat_title' => $added ),
3607 __METHOD__
3610 if ( $deleted ) {
3611 $dbw->update(
3612 'category',
3613 $removeFields,
3614 array( 'cat_title' => $deleted ),
3615 __METHOD__