* An attempt to fix bug 11119
[mediawiki.git] / includes / Article.php
blobcc409482a5691db96ad4b6e6cf12ea3c876e18fb
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 $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 return "<div class='noarticletext'>\n$ret\n</div>";
225 } else {
226 return $this->getNoSuchPageText();
228 } else {
229 $this->loadContent();
230 wfProfileOut( __METHOD__ );
231 return $this->mContent;
236 * HACK HACK! We pre-parse them with parsemag to get GRAMMAR working right.
237 * It should be safe to do this and then do the full parse.
239 function getNoSuchPageText() {
240 global $wgUser;
241 if ( $wgUser->isLoggedIn() ) {
242 $text = wfMsgExt( 'noarticletext', 'parsemag' );
243 } else {
244 $text = wfMsgExt( 'noarticletextanon', 'parsemag' );
246 return "<div class='noarticletext'>\n$text\n</div>";
250 * This function returns the text of a section, specified by a number ($section).
251 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
252 * the first section before any such heading (section 0).
254 * If a section contains subsections, these are also returned.
256 * @param $text String: text to look in
257 * @param $section Integer: section number
258 * @return string text of the requested section
259 * @deprecated
261 function getSection($text,$section) {
262 global $wgParser;
263 return $wgParser->getSection( $text, $section );
267 * @return int The oldid of the article that is to be shown, 0 for the
268 * current revision
270 function getOldID() {
271 if ( is_null( $this->mOldId ) ) {
272 $this->mOldId = $this->getOldIDFromRequest();
274 return $this->mOldId;
278 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
280 * @return int The old id for the request
282 public function getOldIDFromRequest() {
283 global $wgRequest;
284 $this->mRedirectUrl = false;
285 $oldid = $wgRequest->getVal( 'oldid' );
286 if ( isset( $oldid ) ) {
287 $oldid = intval( $oldid );
288 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
289 $nextid = $this->mTitle->getNextRevisionID( $oldid );
290 if ( $nextid ) {
291 $oldid = $nextid;
292 } else {
293 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
295 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
296 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
297 if ( $previd ) {
298 $oldid = $previd;
299 } else {
300 # TODO
303 # unused:
304 # $lastid = $oldid;
307 if ( !$oldid ) {
308 $oldid = 0;
310 return $oldid;
314 * Load the revision (including text) into this object
316 function loadContent() {
317 if ( $this->mContentLoaded ) return;
319 # Query variables :P
320 $oldid = $this->getOldID();
322 # Pre-fill content with error message so that if something
323 # fails we'll have something telling us what we intended.
324 $this->mOldId = $oldid;
325 $this->fetchContent( $oldid );
330 * Fetch a page record with the given conditions
331 * @param Database $dbr
332 * @param array $conditions
333 * @private
335 function pageData( $dbr, $conditions ) {
336 $fields = array(
337 'page_id',
338 'page_namespace',
339 'page_title',
340 'page_restrictions',
341 'page_counter',
342 'page_is_redirect',
343 'page_is_new',
344 'page_random',
345 'page_touched',
346 'page_latest',
347 'page_len',
349 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
350 $row = $dbr->selectRow(
351 'page',
352 $fields,
353 $conditions,
354 __METHOD__
356 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
357 return $row ;
361 * @param Database $dbr
362 * @param Title $title
364 function pageDataFromTitle( $dbr, $title ) {
365 return $this->pageData( $dbr, array(
366 'page_namespace' => $title->getNamespace(),
367 'page_title' => $title->getDBkey() ) );
371 * @param Database $dbr
372 * @param int $id
374 function pageDataFromId( $dbr, $id ) {
375 return $this->pageData( $dbr, array( 'page_id' => $id ) );
379 * Set the general counter, title etc data loaded from
380 * some source.
382 * @param object $data
383 * @private
385 function loadPageData( $data = 'fromdb' ) {
386 if ( $data === 'fromdb' ) {
387 $dbr = wfGetDB( DB_MASTER );
388 $data = $this->pageDataFromId( $dbr, $this->getId() );
391 $lc = LinkCache::singleton();
392 if ( $data ) {
393 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
395 $this->mTitle->mArticleID = $data->page_id;
397 # Old-fashioned restrictions.
398 $this->mTitle->loadRestrictions( $data->page_restrictions );
400 $this->mCounter = $data->page_counter;
401 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
402 $this->mIsRedirect = $data->page_is_redirect;
403 $this->mLatest = $data->page_latest;
404 } else {
405 if ( is_object( $this->mTitle ) ) {
406 $lc->addBadLinkObj( $this->mTitle );
408 $this->mTitle->mArticleID = 0;
411 $this->mDataLoaded = true;
415 * Get text of an article from database
416 * Does *NOT* follow redirects.
417 * @param int $oldid 0 for whatever the latest revision is
418 * @return string
420 function fetchContent( $oldid = 0 ) {
421 if ( $this->mContentLoaded ) {
422 return $this->mContent;
425 $dbr = wfGetDB( DB_MASTER );
427 # Pre-fill content with error message so that if something
428 # fails we'll have something telling us what we intended.
429 $t = $this->mTitle->getPrefixedText();
430 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
431 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
433 if( $oldid ) {
434 $revision = Revision::newFromId( $oldid );
435 if( is_null( $revision ) ) {
436 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
437 return false;
439 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
440 if( !$data ) {
441 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
442 return false;
444 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
445 $this->loadPageData( $data );
446 } else {
447 if( !$this->mDataLoaded ) {
448 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
449 if( !$data ) {
450 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
451 return false;
453 $this->loadPageData( $data );
455 $revision = Revision::newFromId( $this->mLatest );
456 if( is_null( $revision ) ) {
457 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
458 return false;
462 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
463 // We should instead work with the Revision object when we need it...
464 $this->mContent = $revision->revText(); // Loads if user is allowed
466 $this->mUser = $revision->getUser();
467 $this->mUserText = $revision->getUserText();
468 $this->mComment = $revision->getComment();
469 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
471 $this->mRevIdFetched = $revision->getId();
472 $this->mContentLoaded = true;
473 $this->mRevision =& $revision;
475 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
477 return $this->mContent;
481 * Read/write accessor to select FOR UPDATE
483 * @param $x Mixed: FIXME
485 function forUpdate( $x = NULL ) {
486 return wfSetVar( $this->mForUpdate, $x );
490 * Get the database which should be used for reads
492 * @return Database
493 * @deprecated - just call wfGetDB( DB_MASTER ) instead
495 function getDB() {
496 wfDeprecated( __METHOD__ );
497 return wfGetDB( DB_MASTER );
501 * Get options for all SELECT statements
503 * @param $options Array: an optional options array which'll be appended to
504 * the default
505 * @return Array: options
507 function getSelectOptions( $options = '' ) {
508 if ( $this->mForUpdate ) {
509 if ( is_array( $options ) ) {
510 $options[] = 'FOR UPDATE';
511 } else {
512 $options = 'FOR UPDATE';
515 return $options;
519 * @return int Page ID
521 function getID() {
522 if( $this->mTitle ) {
523 return $this->mTitle->getArticleID();
524 } else {
525 return 0;
530 * @return bool Whether or not the page exists in the database
532 function exists() {
533 return $this->getId() != 0;
537 * @return int The view count for the page
539 function getCount() {
540 if ( -1 == $this->mCounter ) {
541 $id = $this->getID();
542 if ( $id == 0 ) {
543 $this->mCounter = 0;
544 } else {
545 $dbr = wfGetDB( DB_SLAVE );
546 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
547 'Article::getCount', $this->getSelectOptions() );
550 return $this->mCounter;
554 * Determine whether a page would be suitable for being counted as an
555 * article in the site_stats table based on the title & its content
557 * @param $text String: text to analyze
558 * @return bool
560 function isCountable( $text ) {
561 global $wgUseCommaCount;
563 $token = $wgUseCommaCount ? ',' : '[[';
564 return
565 $this->mTitle->isContentPage()
566 && !$this->isRedirect( $text )
567 && in_string( $token, $text );
571 * Tests if the article text represents a redirect
573 * @param $text String: FIXME
574 * @return bool
576 function isRedirect( $text = false ) {
577 if ( $text === false ) {
578 if ( $this->mDataLoaded )
579 return $this->mIsRedirect;
581 // Apparently loadPageData was never called
582 $this->loadContent();
583 $titleObj = Title::newFromRedirect( $this->fetchContent() );
584 } else {
585 $titleObj = Title::newFromRedirect( $text );
587 return $titleObj !== NULL;
591 * Returns true if the currently-referenced revision is the current edit
592 * to this page (and it exists).
593 * @return bool
595 function isCurrent() {
596 # If no oldid, this is the current version.
597 if ($this->getOldID() == 0)
598 return true;
600 return $this->exists() &&
601 isset( $this->mRevision ) &&
602 $this->mRevision->isCurrent();
606 * Loads everything except the text
607 * This isn't necessary for all uses, so it's only done if needed.
608 * @private
610 function loadLastEdit() {
611 if ( -1 != $this->mUser )
612 return;
614 # New or non-existent articles have no user information
615 $id = $this->getID();
616 if ( 0 == $id ) return;
618 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
619 if( !is_null( $this->mLastRevision ) ) {
620 $this->mUser = $this->mLastRevision->getUser();
621 $this->mUserText = $this->mLastRevision->getUserText();
622 $this->mTimestamp = $this->mLastRevision->getTimestamp();
623 $this->mComment = $this->mLastRevision->getComment();
624 $this->mMinorEdit = $this->mLastRevision->isMinor();
625 $this->mRevIdFetched = $this->mLastRevision->getId();
629 function getTimestamp() {
630 // Check if the field has been filled by ParserCache::get()
631 if ( !$this->mTimestamp ) {
632 $this->loadLastEdit();
634 return wfTimestamp(TS_MW, $this->mTimestamp);
637 function getUser() {
638 $this->loadLastEdit();
639 return $this->mUser;
642 function getUserText() {
643 $this->loadLastEdit();
644 return $this->mUserText;
647 function getComment() {
648 $this->loadLastEdit();
649 return $this->mComment;
652 function getMinorEdit() {
653 $this->loadLastEdit();
654 return $this->mMinorEdit;
657 function getRevIdFetched() {
658 $this->loadLastEdit();
659 return $this->mRevIdFetched;
663 * @param $limit Integer: default 0.
664 * @param $offset Integer: default 0.
666 function getContributors($limit = 0, $offset = 0) {
667 # XXX: this is expensive; cache this info somewhere.
669 $contribs = array();
670 $dbr = wfGetDB( DB_SLAVE );
671 $revTable = $dbr->tableName( 'revision' );
672 $userTable = $dbr->tableName( 'user' );
673 $user = $this->getUser();
674 $pageId = $this->getId();
676 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
677 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
678 WHERE rev_page = $pageId
679 AND rev_user != $user
680 GROUP BY rev_user, rev_user_text, user_real_name
681 ORDER BY timestamp DESC";
683 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
684 if ($offset > 0) { $sql .= ' OFFSET '.$offset; }
686 $sql .= ' '. $this->getSelectOptions();
688 $res = $dbr->query($sql, __METHOD__ );
690 return new UserArrayFromResult( $res );
694 * This is the default action of the script: just view the page of
695 * the given title.
697 function view() {
698 global $wgUser, $wgOut, $wgRequest, $wgContLang;
699 global $wgEnableParserCache, $wgStylePath, $wgParser;
700 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
701 global $wgDefaultRobotPolicy;
702 $sk = $wgUser->getSkin();
704 wfProfileIn( __METHOD__ );
706 $parserCache = ParserCache::singleton();
707 $ns = $this->mTitle->getNamespace(); # shortcut
709 # Get variables from query string
710 $oldid = $this->getOldID();
712 # getOldID may want us to redirect somewhere else
713 if ( $this->mRedirectUrl ) {
714 $wgOut->redirect( $this->mRedirectUrl );
715 wfProfileOut( __METHOD__ );
716 return;
719 $diff = $wgRequest->getVal( 'diff' );
720 $rcid = $wgRequest->getVal( 'rcid' );
721 $rdfrom = $wgRequest->getVal( 'rdfrom' );
722 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
723 $purge = $wgRequest->getVal( 'action' ) == 'purge';
725 $wgOut->setArticleFlag( true );
727 # Discourage indexing of printable versions, but encourage following
728 if( $wgOut->isPrintable() ) {
729 $policy = 'noindex,follow';
730 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
731 $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
732 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
733 # Honour customised robot policies for this namespace
734 $policy = $wgNamespaceRobotPolicies[$ns];
735 } else {
736 $policy = $wgDefaultRobotPolicy;
738 $wgOut->setRobotPolicy( $policy );
740 # If we got diff and oldid in the query, we want to see a
741 # diff page instead of the article.
743 if ( !is_null( $diff ) ) {
744 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
746 $diff = $wgRequest->getVal( 'diff' );
747 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
748 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff);
749 // DifferenceEngine directly fetched the revision:
750 $this->mRevIdFetched = $de->mNewid;
751 $de->showDiffPage( $diffOnly );
753 // Needed to get the page's current revision
754 $this->loadPageData();
755 if( $diff == 0 || $diff == $this->mLatest ) {
756 # Run view updates for current revision only
757 $this->viewUpdates();
759 wfProfileOut( __METHOD__ );
760 return;
763 if ( empty( $oldid ) && $this->checkTouched() ) {
764 $wgOut->setETag($parserCache->getETag($this, $wgUser));
766 if( $wgOut->checkLastModified( $this->mTouched ) ){
767 wfProfileOut( __METHOD__ );
768 return;
769 } else if ( $this->tryFileCache() ) {
770 # tell wgOut that output is taken care of
771 $wgOut->disable();
772 $this->viewUpdates();
773 wfProfileOut( __METHOD__ );
774 return;
778 # Should the parser cache be used?
779 $pcache = $this->useParserCache( $oldid );
780 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
781 if ( $wgUser->getOption( 'stubthreshold' ) ) {
782 wfIncrStats( 'pcache_miss_stub' );
785 $wasRedirected = false;
786 if ( isset( $this->mRedirectedFrom ) ) {
787 // This is an internally redirected page view.
788 // We'll need a backlink to the source page for navigation.
789 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
790 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
791 $s = wfMsg( 'redirectedfrom', $redir );
792 $wgOut->setSubtitle( $s );
794 // Set the fragment if one was specified in the redirect
795 if ( strval( $this->mTitle->getFragment() ) != '' ) {
796 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
797 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
799 $wasRedirected = true;
801 } elseif ( !empty( $rdfrom ) ) {
802 // This is an externally redirected view, from some other wiki.
803 // If it was reported from a trusted site, supply a backlink.
804 global $wgRedirectSources;
805 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
806 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
807 $s = wfMsg( 'redirectedfrom', $redir );
808 $wgOut->setSubtitle( $s );
809 $wasRedirected = true;
813 $outputDone = false;
814 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
815 if ( $pcache ) {
816 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
817 // Ensure that UI elements requiring revision ID have
818 // the correct version information.
819 $wgOut->setRevisionId( $this->mLatest );
820 $outputDone = true;
823 # Fetch content and check for errors
824 if ( !$outputDone ) {
825 # If the article does not exist and was deleted, show the log
826 if ($this->getID() == 0) {
827 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
828 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
829 if( $pager->getNumRows() > 0 ) {
830 $wgOut->addHtml( '<div id="mw-deleted-notice">' );
831 $wgOut->addWikiMsg( 'deleted-notice' );
832 $wgOut->addHTML(
833 $loglist->beginLogEventsList() .
834 $pager->getBody() .
835 $loglist->endLogEventsList()
837 $wgOut->addHtml( '</div>' );
840 $text = $this->getContent();
841 if ( $text === false ) {
842 # Failed to load, replace text with error message
843 $t = $this->mTitle->getPrefixedText();
844 if( $oldid ) {
845 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
846 $text = wfMsg( 'missing-article', $t, $d );
847 } else {
848 $text = wfMsg( 'noarticletext' );
852 # Another whitelist check in case oldid is altering the title
853 if ( !$this->mTitle->userCanRead() ) {
854 $wgOut->loginToUse();
855 $wgOut->output();
856 wfProfileOut( __METHOD__ );
857 exit;
860 # We're looking at an old revision
861 if ( !empty( $oldid ) ) {
862 $wgOut->setRobotPolicy( 'noindex,nofollow' );
863 if( is_null( $this->mRevision ) ) {
864 // FIXME: This would be a nice place to load the 'no such page' text.
865 } else {
866 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
867 if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
868 if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
869 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
870 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
871 wfProfileOut( __METHOD__ );
872 return;
873 } else {
874 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
875 // and we are allowed to see...
881 $wgOut->setRevisionId( $this->getRevIdFetched() );
883 // Pages containing custom CSS or JavaScript get special treatment
884 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
885 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
886 // Give hooks a chance to customise the output
887 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
888 // Wrap the whole lot in a <pre> and don't parse
889 $m = array();
890 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
891 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
892 $wgOut->addHtml( htmlspecialchars( $this->mContent ) );
893 $wgOut->addHtml( "\n</pre>\n" );
895 } else if ( $rt = Title::newFromRedirect( $text ) ) {
896 # Don't append the subtitle if this was an old revision
897 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
898 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
899 $wgOut->addParserOutputNoText( $parseout );
900 } else if ( $pcache ) {
901 # Display content and save to parser cache
902 $this->outputWikiText( $text );
903 } else {
904 # Display content, don't attempt to save to parser cache
905 # Don't show section-edit links on old revisions... this way lies madness.
906 if( !$this->isCurrent() ) {
907 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
909 # Display content and don't save to parser cache
910 # With timing hack -- TS 2006-07-26
911 $time = -wfTime();
912 $this->outputWikiText( $text, false );
913 $time += wfTime();
915 # Timing hack
916 if ( $time > 3 ) {
917 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
918 $this->mTitle->getPrefixedDBkey()));
921 if( !$this->isCurrent() ) {
922 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
926 /* title may have been set from the cache */
927 $t = $wgOut->getPageTitle();
928 if( empty( $t ) ) {
929 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
931 # For the main page, overwrite the <title> element with the con-
932 # tents of 'pagetitle-view-mainpage' instead of the default (if
933 # that's not empty).
934 if( $this->mTitle->equals( Title::newMainPage() ) &&
935 wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
936 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
940 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
941 if( $ns == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
942 $wgOut->addWikiMsg('anontalkpagetext');
945 # If we have been passed an &rcid= parameter, we want to give the user a
946 # chance to mark this new article as patrolled.
947 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle->exists() ) {
948 $wgOut->addHTML(
949 "<div class='patrollink'>" .
950 wfMsgHtml( 'markaspatrolledlink',
951 $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
952 "action=markpatrolled&rcid=$rcid" )
954 '</div>'
958 # Trackbacks
959 if ($wgUseTrackbacks)
960 $this->addTrackbacks();
962 $this->viewUpdates();
963 wfProfileOut( __METHOD__ );
967 * Should the parser cache be used?
969 protected function useParserCache( $oldid ) {
970 global $wgUser, $wgEnableParserCache;
972 return $wgEnableParserCache
973 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
974 && $this->exists()
975 && empty( $oldid )
976 && !$this->mTitle->isCssOrJsPage()
977 && !$this->mTitle->isCssJsSubpage();
981 * View redirect
982 * @param Title $target Title of destination to redirect
983 * @param Bool $appendSubtitle Object[optional]
984 * @param Bool $forceKnown Should the image be shown as a bluelink regardless of existence?
986 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
987 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
989 # Display redirect
990 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
991 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
993 if( $appendSubtitle ) {
994 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
996 $sk = $wgUser->getSkin();
997 if ( $forceKnown )
998 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
999 else
1000 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1002 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1003 '<span class="redirectText">'.$link.'</span>';
1007 function addTrackbacks() {
1008 global $wgOut, $wgUser;
1010 $dbr = wfGetDB(DB_SLAVE);
1011 $tbs = $dbr->select(
1012 /* FROM */ 'trackbacks',
1013 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1014 /* WHERE */ array('tb_page' => $this->getID())
1017 if (!$dbr->numrows($tbs))
1018 return;
1020 $tbtext = "";
1021 while ($o = $dbr->fetchObject($tbs)) {
1022 $rmvtxt = "";
1023 if ($wgUser->isAllowed( 'trackback' )) {
1024 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
1025 . $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1026 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1028 $tbtext .= "\n";
1029 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1030 $o->tb_title,
1031 $o->tb_url,
1032 $o->tb_ex,
1033 $o->tb_name,
1034 $rmvtxt);
1036 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1039 function deletetrackback() {
1040 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1042 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
1043 $wgOut->addWikiMsg( 'sessionfailure' );
1044 return;
1047 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1049 if (count($permission_errors)>0)
1051 $wgOut->showPermissionsErrorPage( $permission_errors );
1052 return;
1055 $db = wfGetDB(DB_MASTER);
1056 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1057 $wgTitle->invalidateCache();
1058 $wgOut->addWikiMsg('trackbackdeleteok');
1061 function render() {
1062 global $wgOut;
1064 $wgOut->setArticleBodyOnly(true);
1065 $this->view();
1069 * Handle action=purge
1071 function purge() {
1072 global $wgUser, $wgRequest, $wgOut;
1074 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1075 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1076 $this->doPurge();
1077 $this->view();
1079 } else {
1080 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1081 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1082 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1083 $msg = str_replace( '$1',
1084 "<form method=\"post\" action=\"$action\">\n" .
1085 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1086 "</form>\n", $msg );
1088 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1089 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1090 $wgOut->addHTML( $msg );
1095 * Perform the actions of a page purging
1097 function doPurge() {
1098 global $wgUseSquid;
1099 // Invalidate the cache
1100 $this->mTitle->invalidateCache();
1102 if ( $wgUseSquid ) {
1103 // Commit the transaction before the purge is sent
1104 $dbw = wfGetDB( DB_MASTER );
1105 $dbw->immediateCommit();
1107 // Send purge
1108 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1109 $update->doUpdate();
1111 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1112 global $wgMessageCache;
1113 if ( $this->getID() == 0 ) {
1114 $text = false;
1115 } else {
1116 $text = $this->getContent();
1118 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1123 * Insert a new empty page record for this article.
1124 * This *must* be followed up by creating a revision
1125 * and running $this->updateToLatest( $rev_id );
1126 * or else the record will be left in a funky state.
1127 * Best if all done inside a transaction.
1129 * @param Database $dbw
1130 * @return int The newly created page_id key
1131 * @private
1133 function insertOn( $dbw ) {
1134 wfProfileIn( __METHOD__ );
1136 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1137 $dbw->insert( 'page', array(
1138 'page_id' => $page_id,
1139 'page_namespace' => $this->mTitle->getNamespace(),
1140 'page_title' => $this->mTitle->getDBkey(),
1141 'page_counter' => 0,
1142 'page_restrictions' => '',
1143 'page_is_redirect' => 0, # Will set this shortly...
1144 'page_is_new' => 1,
1145 'page_random' => wfRandom(),
1146 'page_touched' => $dbw->timestamp(),
1147 'page_latest' => 0, # Fill this in shortly...
1148 'page_len' => 0, # Fill this in shortly...
1149 ), __METHOD__ );
1150 $newid = $dbw->insertId();
1152 $this->mTitle->resetArticleId( $newid );
1154 wfProfileOut( __METHOD__ );
1155 return $newid;
1159 * Update the page record to point to a newly saved revision.
1161 * @param Database $dbw
1162 * @param Revision $revision For ID number, and text used to set
1163 length and redirect status fields
1164 * @param int $lastRevision If given, will not overwrite the page field
1165 * when different from the currently set value.
1166 * Giving 0 indicates the new page flag should
1167 * be set on.
1168 * @param bool $lastRevIsRedirect If given, will optimize adding and
1169 * removing rows in redirect table.
1170 * @return bool true on success, false on failure
1171 * @private
1173 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1174 wfProfileIn( __METHOD__ );
1176 $text = $revision->getText();
1177 $rt = Title::newFromRedirect( $text );
1179 $conditions = array( 'page_id' => $this->getId() );
1180 if( !is_null( $lastRevision ) ) {
1181 # An extra check against threads stepping on each other
1182 $conditions['page_latest'] = $lastRevision;
1185 $dbw->update( 'page',
1186 array( /* SET */
1187 'page_latest' => $revision->getId(),
1188 'page_touched' => $dbw->timestamp(),
1189 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1190 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1191 'page_len' => strlen( $text ),
1193 $conditions,
1194 __METHOD__ );
1196 $result = $dbw->affectedRows() != 0;
1198 if ($result) {
1199 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1202 wfProfileOut( __METHOD__ );
1203 return $result;
1207 * Add row to the redirect table if this is a redirect, remove otherwise.
1209 * @param Database $dbw
1210 * @param $redirectTitle a title object pointing to the redirect target,
1211 * or NULL if this is not a redirect
1212 * @param bool $lastRevIsRedirect If given, will optimize adding and
1213 * removing rows in redirect table.
1214 * @return bool true on success, false on failure
1215 * @private
1217 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1219 // Always update redirects (target link might have changed)
1220 // Update/Insert if we don't know if the last revision was a redirect or not
1221 // Delete if changing from redirect to non-redirect
1222 $isRedirect = !is_null($redirectTitle);
1223 if ($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1225 wfProfileIn( __METHOD__ );
1227 if ($isRedirect) {
1229 // This title is a redirect, Add/Update row in the redirect table
1230 $set = array( /* SET */
1231 'rd_namespace' => $redirectTitle->getNamespace(),
1232 'rd_title' => $redirectTitle->getDBkey(),
1233 'rd_from' => $this->getId(),
1236 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1237 } else {
1238 // This is not a redirect, remove row from redirect table
1239 $where = array( 'rd_from' => $this->getId() );
1240 $dbw->delete( 'redirect', $where, __METHOD__);
1243 if( $this->getTitle()->getNamespace() == NS_IMAGE )
1244 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1245 wfProfileOut( __METHOD__ );
1246 return ( $dbw->affectedRows() != 0 );
1249 return true;
1253 * If the given revision is newer than the currently set page_latest,
1254 * update the page record. Otherwise, do nothing.
1256 * @param Database $dbw
1257 * @param Revision $revision
1259 function updateIfNewerOn( &$dbw, $revision ) {
1260 wfProfileIn( __METHOD__ );
1262 $row = $dbw->selectRow(
1263 array( 'revision', 'page' ),
1264 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1265 array(
1266 'page_id' => $this->getId(),
1267 'page_latest=rev_id' ),
1268 __METHOD__ );
1269 if( $row ) {
1270 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1271 wfProfileOut( __METHOD__ );
1272 return false;
1274 $prev = $row->rev_id;
1275 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1276 } else {
1277 # No or missing previous revision; mark the page as new
1278 $prev = 0;
1279 $lastRevIsRedirect = null;
1282 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1283 wfProfileOut( __METHOD__ );
1284 return $ret;
1288 * @return string Complete article text, or null if error
1290 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1291 wfProfileIn( __METHOD__ );
1293 if( $section == '' ) {
1294 // Whole-page edit; let the text through unmolested.
1295 } else {
1296 if( is_null( $edittime ) ) {
1297 $rev = Revision::newFromTitle( $this->mTitle );
1298 } else {
1299 $dbw = wfGetDB( DB_MASTER );
1300 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1302 if( is_null( $rev ) ) {
1303 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1304 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1305 return null;
1307 $oldtext = $rev->getText();
1309 if( $section == 'new' ) {
1310 # Inserting a new section
1311 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1312 $text = strlen( trim( $oldtext ) ) > 0
1313 ? "{$oldtext}\n\n{$subject}{$text}"
1314 : "{$subject}{$text}";
1315 } else {
1316 # Replacing an existing section; roll out the big guns
1317 global $wgParser;
1318 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1323 wfProfileOut( __METHOD__ );
1324 return $text;
1328 * @deprecated use Article::doEdit()
1330 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1331 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1332 ( $isminor ? EDIT_MINOR : 0 ) |
1333 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1334 ( $bot ? EDIT_FORCE_BOT : 0 );
1336 # If this is a comment, add the summary as headline
1337 if ( $comment && $summary != "" ) {
1338 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1341 $this->doEdit( $text, $summary, $flags );
1343 $dbw = wfGetDB( DB_MASTER );
1344 if ($watchthis) {
1345 if (!$this->mTitle->userIsWatching()) {
1346 $dbw->begin();
1347 $this->doWatch();
1348 $dbw->commit();
1350 } else {
1351 if ( $this->mTitle->userIsWatching() ) {
1352 $dbw->begin();
1353 $this->doUnwatch();
1354 $dbw->commit();
1357 $this->doRedirect( $this->isRedirect( $text ) );
1361 * @deprecated use Article::doEdit()
1363 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1364 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1365 ( $minor ? EDIT_MINOR : 0 ) |
1366 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1368 $good = $this->doEdit( $text, $summary, $flags );
1369 if ( $good ) {
1370 $dbw = wfGetDB( DB_MASTER );
1371 if ($watchthis) {
1372 if (!$this->mTitle->userIsWatching()) {
1373 $dbw->begin();
1374 $this->doWatch();
1375 $dbw->commit();
1377 } else {
1378 if ( $this->mTitle->userIsWatching() ) {
1379 $dbw->begin();
1380 $this->doUnwatch();
1381 $dbw->commit();
1385 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1386 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1388 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1390 return $good;
1394 * Article::doEdit()
1396 * Change an existing article or create a new article. Updates RC and all necessary caches,
1397 * optionally via the deferred update array.
1399 * $wgUser must be set before calling this function.
1401 * @param string $text New text
1402 * @param string $summary Edit summary
1403 * @param integer $flags bitfield:
1404 * EDIT_NEW
1405 * Article is known or assumed to be non-existent, create a new one
1406 * EDIT_UPDATE
1407 * Article is known or assumed to be pre-existing, update it
1408 * EDIT_MINOR
1409 * Mark this edit minor, if the user is allowed to do so
1410 * EDIT_SUPPRESS_RC
1411 * Do not log the change in recentchanges
1412 * EDIT_FORCE_BOT
1413 * Mark the edit a "bot" edit regardless of user rights
1414 * EDIT_DEFER_UPDATES
1415 * Defer some of the updates until the end of index.php
1416 * EDIT_AUTOSUMMARY
1417 * Fill in blank summaries with generated text where possible
1419 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1420 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1421 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1422 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1423 * to MediaWiki's performance-optimised locking strategy.
1424 * @param $baseRevId, the revision ID this edit was based off, if any
1426 * @return bool success
1428 function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1429 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1431 # Low-level sanity check
1432 if( $this->mTitle->getText() == '' ) {
1433 throw new MWException( 'Something is trying to edit an article with an empty title' );
1436 wfProfileIn( __METHOD__ );
1438 if ($user == null) {
1439 $user = $wgUser;
1441 $good = true;
1443 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1444 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1445 if ( $aid ) {
1446 $flags |= EDIT_UPDATE;
1447 } else {
1448 $flags |= EDIT_NEW;
1452 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text,
1453 &$summary, $flags & EDIT_MINOR,
1454 null, null, &$flags ) ) )
1456 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1457 wfProfileOut( __METHOD__ );
1458 return false;
1461 # Silently ignore EDIT_MINOR if not allowed
1462 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1463 $bot = $flags & EDIT_FORCE_BOT;
1465 $oldtext = $this->getContent();
1466 $oldsize = strlen( $oldtext );
1468 # Provide autosummaries if one is not provided and autosummaries are enabled.
1469 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1470 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1473 $editInfo = $this->prepareTextForEdit( $text );
1474 $text = $editInfo->pst;
1475 $newsize = strlen( $text );
1477 $dbw = wfGetDB( DB_MASTER );
1478 $now = wfTimestampNow();
1480 if ( $flags & EDIT_UPDATE ) {
1481 # Update article, but only if changed.
1483 # Make sure the revision is either completely inserted or not inserted at all
1484 if( !$wgDBtransactions ) {
1485 $userAbort = ignore_user_abort( true );
1488 $lastRevision = 0;
1489 $revisionId = 0;
1491 $changed = ( strcmp( $text, $oldtext ) != 0 );
1493 if ( $changed ) {
1494 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1495 - (int)$this->isCountable( $oldtext );
1496 $this->mTotalAdjustment = 0;
1498 $lastRevision = $dbw->selectField(
1499 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1501 if ( !$lastRevision ) {
1502 # Article gone missing
1503 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1504 wfProfileOut( __METHOD__ );
1505 return false;
1508 $revision = new Revision( array(
1509 'page' => $this->getId(),
1510 'comment' => $summary,
1511 'minor_edit' => $isminor,
1512 'text' => $text,
1513 'parent_id' => $lastRevision,
1514 'user' => $user->getId(),
1515 'user_text' => $user->getName(),
1516 ) );
1518 $dbw->begin();
1519 $revisionId = $revision->insertOn( $dbw );
1521 # Update page
1522 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1524 if( !$ok ) {
1525 /* Belated edit conflict! Run away!! */
1526 $good = false;
1527 $dbw->rollback();
1528 } else {
1529 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
1531 # Update recentchanges
1532 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1533 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1534 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1535 $revisionId );
1537 # Mark as patrolled if the user can do so
1538 if( $GLOBALS['wgUseRCPatrol'] && $user->isAllowed( 'autopatrol' ) ) {
1539 RecentChange::markPatrolled( $rc, true );
1542 $user->incEditCount();
1543 $dbw->commit();
1545 } else {
1546 $revision = null;
1547 // Keep the same revision ID, but do some updates on it
1548 $revisionId = $this->getRevIdFetched();
1549 // Update page_touched, this is usually implicit in the page update
1550 // Other cache updates are done in onArticleEdit()
1551 $this->mTitle->invalidateCache();
1554 if( !$wgDBtransactions ) {
1555 ignore_user_abort( $userAbort );
1558 if ( $good ) {
1559 # Invalidate cache of this article and all pages using this article
1560 # as a template. Partly deferred.
1561 Article::onArticleEdit( $this->mTitle, false ); // leave templatelinks for editUpdates()
1562 # Update links tables, site stats, etc.
1563 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1565 } else {
1566 # Create new article
1568 # Set statistics members
1569 # We work out if it's countable after PST to avoid counter drift
1570 # when articles are created with {{subst:}}
1571 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1572 $this->mTotalAdjustment = 1;
1574 # Add the page record; stake our claim on this title!
1575 # This will fail with a database query exception if the article already exists
1576 $newid = $this->insertOn( $dbw );
1578 # Save the revision text...
1579 $revision = new Revision( array(
1580 'page' => $newid,
1581 'comment' => $summary,
1582 'minor_edit' => $isminor,
1583 'text' => $text,
1584 'user' => $user->getId(),
1585 'user_text' => $user->getName(),
1586 ) );
1587 $revisionId = $revision->insertOn( $dbw );
1589 $this->mTitle->resetArticleID( $newid );
1591 # Update the page record with revision data
1592 $this->updateRevisionOn( $dbw, $revision, 0 );
1594 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1596 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1597 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1598 '', strlen( $text ), $revisionId );
1599 # Mark as patrolled if the user can
1600 if( ($GLOBALS['wgUseRCPatrol'] || $GLOBALS['wgUseNPPatrol']) && $user->isAllowed( 'autopatrol' ) ) {
1601 RecentChange::markPatrolled( $rc, true );
1604 $user->incEditCount();
1606 # Update links, etc.
1607 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1609 # Clear caches
1610 Article::onArticleCreate( $this->mTitle );
1612 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1613 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1616 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1617 wfDoUpdates();
1620 if ( $good ) {
1621 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1622 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1625 wfProfileOut( __METHOD__ );
1626 return $good;
1630 * @deprecated wrapper for doRedirect
1632 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1633 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1637 * Output a redirect back to the article.
1638 * This is typically used after an edit.
1640 * @param boolean $noRedir Add redirect=no
1641 * @param string $sectionAnchor section to redirect to, including "#"
1642 * @param string $extraQuery, extra query params
1644 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1645 global $wgOut;
1646 if ( $noRedir ) {
1647 $query = 'redirect=no';
1648 if( $extraQuery )
1649 $query .= "&$query";
1650 } else {
1651 $query = $extraQuery;
1653 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1657 * Mark this particular edit/page as patrolled
1659 function markpatrolled() {
1660 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1661 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1663 # If we haven't been given an rc_id value, we can't do anything
1664 $rcid = (int) $wgRequest->getVal('rcid');
1665 $rc = RecentChange::newFromId($rcid);
1666 if ( is_null($rc) ) {
1667 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1668 return;
1671 #It would be nice to see where the user had actually come from, but for now just guess
1672 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1673 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1675 $dbw = wfGetDB( DB_MASTER );
1676 $errors = $rc->doMarkPatrolled();
1678 if ( in_array(array('rcpatroldisabled'), $errors) ) {
1679 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1680 return;
1683 if ( in_array(array('hookaborted'), $errors) ) {
1684 // The hook itself has handled any output
1685 return;
1688 if ( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1689 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1690 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1691 $wgOut->returnToMain( false, $return );
1692 return;
1695 if ( !empty($errors) ) {
1696 $wgOut->showPermissionsErrorPage( $errors );
1697 return;
1700 # Inform the user
1701 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1702 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1703 $wgOut->returnToMain( false, $return );
1707 * User-interface handler for the "watch" action
1710 function watch() {
1712 global $wgUser, $wgOut;
1714 if ( $wgUser->isAnon() ) {
1715 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1716 return;
1718 if ( wfReadOnly() ) {
1719 $wgOut->readOnlyPage();
1720 return;
1723 if( $this->doWatch() ) {
1724 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1725 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1727 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1730 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1734 * Add this page to $wgUser's watchlist
1735 * @return bool true on successful watch operation
1737 function doWatch() {
1738 global $wgUser;
1739 if( $wgUser->isAnon() ) {
1740 return false;
1743 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1744 $wgUser->addWatch( $this->mTitle );
1746 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1749 return false;
1753 * User interface handler for the "unwatch" action.
1755 function unwatch() {
1757 global $wgUser, $wgOut;
1759 if ( $wgUser->isAnon() ) {
1760 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1761 return;
1763 if ( wfReadOnly() ) {
1764 $wgOut->readOnlyPage();
1765 return;
1768 if( $this->doUnwatch() ) {
1769 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1770 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1772 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1775 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1779 * Stop watching a page
1780 * @return bool true on successful unwatch
1782 function doUnwatch() {
1783 global $wgUser;
1784 if( $wgUser->isAnon() ) {
1785 return false;
1788 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1789 $wgUser->removeWatch( $this->mTitle );
1791 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1794 return false;
1798 * action=protect handler
1800 function protect() {
1801 $form = new ProtectionForm( $this );
1802 $form->execute();
1806 * action=unprotect handler (alias)
1808 function unprotect() {
1809 $this->protect();
1813 * Update the article's restriction field, and leave a log entry.
1815 * @param array $limit set of restriction keys
1816 * @param string $reason
1817 * @return bool true on success
1819 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = array() ) {
1820 global $wgUser, $wgRestrictionTypes, $wgContLang;
1822 $id = $this->mTitle->getArticleID();
1823 if( array() != $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser ) || wfReadOnly() || $id == 0 ) {
1824 return false;
1827 if( !$cascade ) {
1828 $cascade = false;
1831 // Take this opportunity to purge out expired restrictions
1832 Title::purgeExpiredRestrictions();
1834 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1835 # we expect a single selection, but the schema allows otherwise.
1836 $current = array();
1837 $updated = Article::flattenRestrictions( $limit );
1838 $changed = false;
1839 foreach( $wgRestrictionTypes as $action ) {
1840 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1841 $changed = ($changed || ($this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action]) );
1844 $current = Article::flattenRestrictions( $current );
1846 $changed = ($changed || ( $current != $updated ) );
1847 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
1848 $protect = ( $updated != '' );
1850 # If nothing's changed, do nothing
1851 if( $changed ) {
1852 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1854 $dbw = wfGetDB( DB_MASTER );
1856 # Prepare a null revision to be added to the history
1857 $modified = $current != '' && $protect;
1858 if( $protect ) {
1859 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1860 } else {
1861 $comment_type = 'unprotectedarticle';
1863 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1865 # Only restrictions with the 'protect' right can cascade...
1866 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1867 foreach( $limit as $action => $restriction ) {
1868 # FIXME: can $restriction be an array or what? (same as fixme above)
1869 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1870 $cascade = false;
1871 break;
1874 $cascade_description = '';
1875 if( $cascade ) {
1876 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
1879 if( $reason )
1880 $comment .= ": $reason";
1882 $editComment = $comment;
1883 $encodedExpiry = array();
1884 $protect_description = '';
1885 foreach( $limit as $action => $restrictions ) {
1886 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
1887 if( $restrictions != '' ) {
1888 $protect_description .= "[$action=$restrictions] (";
1889 if( $encodedExpiry[$action] != 'infinity' ) {
1890 $protect_description .= wfMsgForContent( 'protect-expiring',
1891 $wgContLang->timeanddate( $expiry[$action], false, false ) );
1892 } else {
1893 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1895 $protect_description .= ') ';
1898 $protect_description = trim($protect_description);
1900 if( $protect_description && $protect )
1901 $editComment .= " ($protect_description)";
1902 if( $cascade )
1903 $editComment .= "$cascade_description";
1904 # Update restrictions table
1905 foreach( $limit as $action => $restrictions ) {
1906 if ($restrictions != '' ) {
1907 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1908 array( 'pr_page' => $id,
1909 'pr_type' => $action,
1910 'pr_level' => $restrictions,
1911 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
1912 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
1913 } else {
1914 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1915 'pr_type' => $action ), __METHOD__ );
1919 # Insert a null revision
1920 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1921 $nullRevId = $nullRevision->insertOn( $dbw );
1923 $latest = $this->getLatest();
1924 # Update page record
1925 $dbw->update( 'page',
1926 array( /* SET */
1927 'page_touched' => $dbw->timestamp(),
1928 'page_restrictions' => '',
1929 'page_latest' => $nullRevId
1930 ), array( /* WHERE */
1931 'page_id' => $id
1932 ), 'Article::protect'
1935 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest) );
1936 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1938 # Update the protection log
1939 $log = new LogPage( 'protect' );
1940 if( $protect ) {
1941 $params = array($protect_description,$cascade ? 'cascade' : '');
1942 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
1943 } else {
1944 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1947 } # End hook
1948 } # End "changed" check
1950 return true;
1954 * Take an array of page restrictions and flatten it to a string
1955 * suitable for insertion into the page_restrictions field.
1956 * @param array $limit
1957 * @return string
1958 * @private
1960 function flattenRestrictions( $limit ) {
1961 if( !is_array( $limit ) ) {
1962 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1964 $bits = array();
1965 ksort( $limit );
1966 foreach( $limit as $action => $restrictions ) {
1967 if( $restrictions != '' ) {
1968 $bits[] = "$action=$restrictions";
1971 return implode( ':', $bits );
1975 * Auto-generates a deletion reason
1976 * @param bool &$hasHistory Whether the page has a history
1978 public function generateReason( &$hasHistory ) {
1979 global $wgContLang;
1980 $dbw = wfGetDB( DB_MASTER );
1981 // Get the last revision
1982 $rev = Revision::newFromTitle( $this->mTitle );
1983 if( is_null( $rev ) )
1984 return false;
1986 // Get the article's contents
1987 $contents = $rev->getText();
1988 $blank = false;
1989 // If the page is blank, use the text from the previous revision,
1990 // which can only be blank if there's a move/import/protect dummy revision involved
1991 if( $contents == '' ) {
1992 $prev = $rev->getPrevious();
1993 if( $prev ) {
1994 $contents = $prev->getText();
1995 $blank = true;
1999 // Find out if there was only one contributor
2000 // Only scan the last 20 revisions
2001 $limit = 20;
2002 $res = $dbw->select( 'revision', 'rev_user_text',
2003 array( 'rev_page' => $this->getID() ), __METHOD__,
2004 array( 'LIMIT' => $limit )
2006 if( $res === false )
2007 // This page has no revisions, which is very weird
2008 return false;
2009 if( $res->numRows() > 1 )
2010 $hasHistory = true;
2011 else
2012 $hasHistory = false;
2013 $row = $dbw->fetchObject( $res );
2014 $onlyAuthor = $row->rev_user_text;
2015 // Try to find a second contributor
2016 foreach( $res as $row ) {
2017 if( $row->rev_user_text != $onlyAuthor ) {
2018 $onlyAuthor = false;
2019 break;
2022 $dbw->freeResult( $res );
2024 // Generate the summary with a '$1' placeholder
2025 if( $blank ) {
2026 // The current revision is blank and the one before is also
2027 // blank. It's just not our lucky day
2028 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2029 } else {
2030 if( $onlyAuthor )
2031 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2032 else
2033 $reason = wfMsgForContent( 'excontent', '$1' );
2036 // Replace newlines with spaces to prevent uglyness
2037 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2038 // Calculate the maximum amount of chars to get
2039 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2040 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2041 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2042 // Remove possible unfinished links
2043 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2044 // Now replace the '$1' placeholder
2045 $reason = str_replace( '$1', $contents, $reason );
2046 return $reason;
2051 * UI entry point for page deletion
2053 function delete() {
2054 global $wgUser, $wgOut, $wgRequest;
2056 $confirm = $wgRequest->wasPosted() &&
2057 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2059 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2060 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2062 $reason = $this->DeleteReasonList;
2064 if ( $reason != 'other' && $this->DeleteReason != '') {
2065 // Entry from drop down menu + additional comment
2066 $reason .= ': ' . $this->DeleteReason;
2067 } elseif ( $reason == 'other' ) {
2068 $reason = $this->DeleteReason;
2070 # Flag to hide all contents of the archived revisions
2071 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2073 # This code desperately needs to be totally rewritten
2075 # Read-only check...
2076 if ( wfReadOnly() ) {
2077 $wgOut->readOnlyPage();
2078 return;
2081 # Check permissions
2082 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2084 if (count($permission_errors)>0) {
2085 $wgOut->showPermissionsErrorPage( $permission_errors );
2086 return;
2089 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2091 # Better double-check that it hasn't been deleted yet!
2092 $dbw = wfGetDB( DB_MASTER );
2093 $conds = $this->mTitle->pageCond();
2094 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2095 if ( $latest === false ) {
2096 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2097 return;
2100 # Hack for big sites
2101 $bigHistory = $this->isBigDeletion();
2102 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2103 global $wgLang, $wgDeleteRevisionsLimit;
2104 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2105 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2106 return;
2109 if( $confirm ) {
2110 $this->doDelete( $reason, $suppress );
2111 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2112 $this->doWatch();
2113 } elseif( $this->mTitle->userIsWatching() ) {
2114 $this->doUnwatch();
2116 return;
2119 // Generate deletion reason
2120 $hasHistory = false;
2121 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2123 // If the page has a history, insert a warning
2124 if( $hasHistory && !$confirm ) {
2125 $skin=$wgUser->getSkin();
2126 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2127 if( $bigHistory ) {
2128 global $wgLang, $wgDeleteRevisionsLimit;
2129 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2130 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2134 return $this->confirmDelete( $reason );
2138 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2140 function isBigDeletion() {
2141 global $wgDeleteRevisionsLimit;
2142 if( $wgDeleteRevisionsLimit ) {
2143 $revCount = $this->estimateRevisionCount();
2144 return $revCount > $wgDeleteRevisionsLimit;
2146 return false;
2150 * @return int approximate revision count
2152 function estimateRevisionCount() {
2153 $dbr = wfGetDB( DB_SLAVE );
2154 // For an exact count...
2155 //return $dbr->selectField( 'revision', 'COUNT(*)',
2156 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2157 return $dbr->estimateRowCount( 'revision', '*',
2158 array( 'rev_page' => $this->getId() ), __METHOD__ );
2162 * Get the last N authors
2163 * @param int $num Number of revisions to get
2164 * @param string $revLatest The latest rev_id, selected from the master (optional)
2165 * @return array Array of authors, duplicates not removed
2167 function getLastNAuthors( $num, $revLatest = 0 ) {
2168 wfProfileIn( __METHOD__ );
2170 // First try the slave
2171 // If that doesn't have the latest revision, try the master
2172 $continue = 2;
2173 $db = wfGetDB( DB_SLAVE );
2174 do {
2175 $res = $db->select( array( 'page', 'revision' ),
2176 array( 'rev_id', 'rev_user_text' ),
2177 array(
2178 'page_namespace' => $this->mTitle->getNamespace(),
2179 'page_title' => $this->mTitle->getDBkey(),
2180 'rev_page = page_id'
2181 ), __METHOD__, $this->getSelectOptions( array(
2182 'ORDER BY' => 'rev_timestamp DESC',
2183 'LIMIT' => $num
2186 if ( !$res ) {
2187 wfProfileOut( __METHOD__ );
2188 return array();
2190 $row = $db->fetchObject( $res );
2191 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2192 $db = wfGetDB( DB_MASTER );
2193 $continue--;
2194 } else {
2195 $continue = 0;
2197 } while ( $continue );
2199 $authors = array( $row->rev_user_text );
2200 while ( $row = $db->fetchObject( $res ) ) {
2201 $authors[] = $row->rev_user_text;
2203 wfProfileOut( __METHOD__ );
2204 return $authors;
2208 * Output deletion confirmation dialog
2209 * @param $reason string Prefilled reason
2211 function confirmDelete( $reason ) {
2212 global $wgOut, $wgUser, $wgContLang;
2213 $align = $wgContLang->isRtl() ? 'left' : 'right';
2215 wfDebug( "Article::confirmDelete\n" );
2217 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2218 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2219 $wgOut->addWikiMsg( 'confirmdeletetext' );
2221 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2222 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2223 $suppress .= Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2224 $suppress .= "</td></tr>";
2225 } else {
2226 $suppress = '';
2229 $form = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2230 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2231 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2232 Xml::openElement( 'table' ) .
2233 "<tr id=\"wpDeleteReasonListRow\">
2234 <td align='$align'>" .
2235 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2236 "</td>
2237 <td>" .
2238 Xml::listDropDown( 'wpDeleteReasonList',
2239 wfMsgForContent( 'deletereason-dropdown' ),
2240 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2241 "</td>
2242 </tr>
2243 <tr id=\"wpDeleteReasonRow\">
2244 <td align='$align'>" .
2245 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2246 "</td>
2247 <td>" .
2248 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2249 "</td>
2250 </tr>
2251 <tr>
2252 <td></td>
2253 <td>" .
2254 Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '3' ) ) .
2255 "</td>
2256 </tr>
2257 $suppress
2258 <tr>
2259 <td></td>
2260 <td>" .
2261 Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2262 "</td>
2263 </tr>" .
2264 Xml::closeElement( 'table' ) .
2265 Xml::closeElement( 'fieldset' ) .
2266 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2267 Xml::closeElement( 'form' );
2269 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2270 $skin = $wgUser->getSkin();
2271 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2272 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2275 $wgOut->addHTML( $form );
2276 $this->showLogExtract( $wgOut );
2281 * Show relevant lines from the deletion log
2283 function showLogExtract( $out ) {
2284 $out->addHtml( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2285 LogEventsList::showLogExtract( $out, 'delete', $this->mTitle->getPrefixedText() );
2290 * Perform a deletion and output success or failure messages
2292 function doDelete( $reason, $suppress = false ) {
2293 global $wgOut, $wgUser;
2294 wfDebug( __METHOD__."\n" );
2296 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2298 $error = '';
2300 if ( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2301 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2302 $deleted = $this->mTitle->getPrefixedText();
2304 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2305 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2307 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2309 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2310 $wgOut->returnToMain( false );
2311 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2312 } else {
2313 if ($error = '')
2314 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2315 else
2316 $wgOut->showFatalError( $error );
2322 * Back-end article deletion
2323 * Deletes the article with database consistency, writes logs, purges caches
2324 * Returns success
2326 function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2327 global $wgUseSquid, $wgDeferredUpdateList;
2328 global $wgUseTrackbacks;
2330 wfDebug( __METHOD__."\n" );
2332 $dbw = wfGetDB( DB_MASTER );
2333 $ns = $this->mTitle->getNamespace();
2334 $t = $this->mTitle->getDBkey();
2335 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2337 if ( $t == '' || $id == 0 ) {
2338 return false;
2341 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2342 array_push( $wgDeferredUpdateList, $u );
2344 // Bitfields to further suppress the content
2345 if ( $suppress ) {
2346 $bitfield = 0;
2347 // This should be 15...
2348 $bitfield |= Revision::DELETED_TEXT;
2349 $bitfield |= Revision::DELETED_COMMENT;
2350 $bitfield |= Revision::DELETED_USER;
2351 $bitfield |= Revision::DELETED_RESTRICTED;
2352 } else {
2353 $bitfield = 'rev_deleted';
2356 $dbw->begin();
2357 // For now, shunt the revision data into the archive table.
2358 // Text is *not* removed from the text table; bulk storage
2359 // is left intact to avoid breaking block-compression or
2360 // immutable storage schemes.
2362 // For backwards compatibility, note that some older archive
2363 // table entries will have ar_text and ar_flags fields still.
2365 // In the future, we may keep revisions and mark them with
2366 // the rev_deleted field, which is reserved for this purpose.
2367 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2368 array(
2369 'ar_namespace' => 'page_namespace',
2370 'ar_title' => 'page_title',
2371 'ar_comment' => 'rev_comment',
2372 'ar_user' => 'rev_user',
2373 'ar_user_text' => 'rev_user_text',
2374 'ar_timestamp' => 'rev_timestamp',
2375 'ar_minor_edit' => 'rev_minor_edit',
2376 'ar_rev_id' => 'rev_id',
2377 'ar_text_id' => 'rev_text_id',
2378 'ar_text' => '\'\'', // Be explicit to appease
2379 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2380 'ar_len' => 'rev_len',
2381 'ar_page_id' => 'page_id',
2382 'ar_deleted' => $bitfield
2383 ), array(
2384 'page_id' => $id,
2385 'page_id = rev_page'
2386 ), __METHOD__
2389 # Delete restrictions for it
2390 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2392 # Now that it's safely backed up, delete it
2393 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2394 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2395 if( !$ok ) {
2396 $dbw->rollback();
2397 return false;
2400 # If using cascading deletes, we can skip some explicit deletes
2401 if ( !$dbw->cascadingDeletes() ) {
2402 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2404 if ($wgUseTrackbacks)
2405 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2407 # Delete outgoing links
2408 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2409 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2410 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2411 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2412 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2413 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2414 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2417 # If using cleanup triggers, we can skip some manual deletes
2418 if ( !$dbw->cleanupTriggers() ) {
2419 # Clean up recentchanges entries...
2420 $dbw->delete( 'recentchanges',
2421 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2422 __METHOD__ );
2425 # Clear caches
2426 Article::onArticleDelete( $this->mTitle );
2428 # Fix category table counts
2429 $cats = array();
2430 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2431 foreach( $res as $row ) {
2432 $cats []= $row->cl_to;
2434 $this->updateCategoryCounts( array(), $cats );
2436 # Clear the cached article id so the interface doesn't act like we exist
2437 $this->mTitle->resetArticleID( 0 );
2438 $this->mTitle->mArticleID = 0;
2440 # Log the deletion, if the page was suppressed, log it at Oversight instead
2441 $logtype = $suppress ? 'suppress' : 'delete';
2442 $log = new LogPage( $logtype );
2444 # Make sure logging got through
2445 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2447 $dbw->commit();
2449 return true;
2453 * Roll back the most recent consecutive set of edits to a page
2454 * from the same user; fails if there are no eligible edits to
2455 * roll back to, e.g. user is the sole contributor. This function
2456 * performs permissions checks on $wgUser, then calls commitRollback()
2457 * to do the dirty work
2459 * @param string $fromP - Name of the user whose edits to rollback.
2460 * @param string $summary - Custom summary. Set to default summary if empty.
2461 * @param string $token - Rollback token.
2462 * @param bool $bot - If true, mark all reverted edits as bot.
2464 * @param array $resultDetails contains result-specific array of additional values
2465 * 'alreadyrolled' : 'current' (rev)
2466 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2468 * @return array of errors, each error formatted as
2469 * array(messagekey, param1, param2, ...).
2470 * On success, the array is empty. This array can also be passed to
2471 * OutputPage::showPermissionsErrorPage().
2473 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2474 global $wgUser;
2475 $resultDetails = null;
2477 # Check permissions
2478 $errors = array_merge( $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ),
2479 $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
2480 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2481 $errors[] = array( 'sessionfailure' );
2483 if ( $wgUser->pingLimiter('rollback') || $wgUser->pingLimiter() ) {
2484 $errors[] = array( 'actionthrottledtext' );
2486 # If there were errors, bail out now
2487 if(!empty($errors))
2488 return $errors;
2490 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2494 * Backend implementation of doRollback(), please refer there for parameter
2495 * and return value documentation
2497 * NOTE: This function does NOT check ANY permissions, it just commits the
2498 * rollback to the DB Therefore, you should only call this function direct-
2499 * ly if you want to use custom permissions checks. If you don't, use
2500 * doRollback() instead.
2502 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2503 global $wgUseRCPatrol, $wgUser, $wgLang;
2504 $dbw = wfGetDB( DB_MASTER );
2506 if( wfReadOnly() ) {
2507 return array( array( 'readonlytext' ) );
2510 # Get the last editor
2511 $current = Revision::newFromTitle( $this->mTitle );
2512 if( is_null( $current ) ) {
2513 # Something wrong... no page?
2514 return array(array('notanarticle'));
2517 $from = str_replace( '_', ' ', $fromP );
2518 if( $from != $current->getUserText() ) {
2519 $resultDetails = array( 'current' => $current );
2520 return array(array('alreadyrolled',
2521 htmlspecialchars($this->mTitle->getPrefixedText()),
2522 htmlspecialchars($fromP),
2523 htmlspecialchars($current->getUserText())
2527 # Get the last edit not by this guy
2528 $user = intval( $current->getUser() );
2529 $user_text = $dbw->addQuotes( $current->getUserText() );
2530 $s = $dbw->selectRow( 'revision',
2531 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2532 array( 'rev_page' => $current->getPage(),
2533 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2534 ), __METHOD__,
2535 array( 'USE INDEX' => 'page_timestamp',
2536 'ORDER BY' => 'rev_timestamp DESC' )
2538 if( $s === false ) {
2539 # No one else ever edited this page
2540 return array(array('cantrollback'));
2541 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2542 # Only admins can see this text
2543 return array(array('notvisiblerev'));
2546 $set = array();
2547 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2548 # Mark all reverted edits as bot
2549 $set['rc_bot'] = 1;
2551 if ( $wgUseRCPatrol ) {
2552 # Mark all reverted edits as patrolled
2553 $set['rc_patrolled'] = 1;
2556 if ( $set ) {
2557 $dbw->update( 'recentchanges', $set,
2558 array( /* WHERE */
2559 'rc_cur_id' => $current->getPage(),
2560 'rc_user_text' => $current->getUserText(),
2561 "rc_timestamp > '{$s->rev_timestamp}'",
2562 ), __METHOD__
2566 # Generate the edit summary if necessary
2567 $target = Revision::newFromId( $s->rev_id );
2568 if( empty( $summary ) ){
2569 $summary = wfMsgForContent( 'revertpage' );
2572 # Allow the custom summary to use the same args as the default message
2573 $args = array(
2574 $target->getUserText(), $from, $s->rev_id,
2575 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2576 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2578 $summary = wfMsgReplaceArgs( $summary, $args );
2580 # Save
2581 $flags = EDIT_UPDATE;
2583 if ($wgUser->isAllowed('minoredit'))
2584 $flags |= EDIT_MINOR;
2586 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2587 $flags |= EDIT_FORCE_BOT;
2588 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2590 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2592 $resultDetails = array(
2593 'summary' => $summary,
2594 'current' => $current,
2595 'target' => $target,
2597 return array();
2601 * User interface for rollback operations
2603 function rollback() {
2604 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2605 $details = null;
2607 $result = $this->doRollback(
2608 $wgRequest->getVal( 'from' ),
2609 $wgRequest->getText( 'summary' ),
2610 $wgRequest->getVal( 'token' ),
2611 $wgRequest->getBool( 'bot' ),
2612 $details
2615 if( in_array( array( 'blocked' ), $result ) ) {
2616 $wgOut->blockedPage();
2617 return;
2619 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2620 $wgOut->rateLimited();
2621 return;
2623 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ){
2624 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2625 $errArray = $result[0];
2626 $errMsg = array_shift( $errArray );
2627 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2628 if( isset( $details['current'] ) ){
2629 $current = $details['current'];
2630 if( $current->getComment() != '' ) {
2631 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2634 return;
2636 # Display permissions errors before read-only message -- there's no
2637 # point in misleading the user into thinking the inability to rollback
2638 # is only temporary.
2639 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2640 # array_diff is completely broken for arrays of arrays, sigh. Re-
2641 # move any 'readonlytext' error manually.
2642 $out = array();
2643 foreach( $result as $error ) {
2644 if( $error != array( 'readonlytext' ) ) {
2645 $out []= $error;
2648 $wgOut->showPermissionsErrorPage( $out );
2649 return;
2651 if( $result == array( array('readonlytext') ) ) {
2652 $wgOut->readOnlyPage();
2653 return;
2656 $current = $details['current'];
2657 $target = $details['target'];
2658 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2659 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2660 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2661 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2662 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2663 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2664 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2665 $wgOut->returnToMain( false, $this->mTitle );
2667 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2668 $de = new DifferenceEngine( $this->mTitle, $current->getId(), 'next', false, true );
2669 $de->showDiff( '', '' );
2675 * Do standard deferred updates after page view
2676 * @private
2678 function viewUpdates() {
2679 global $wgDeferredUpdateList, $wgUser;
2681 if ( 0 != $this->getID() ) {
2682 # Don't update page view counters on views from bot users (bug 14044)
2683 global $wgDisableCounters;
2684 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2685 Article::incViewCount( $this->getID() );
2686 $u = new SiteStatsUpdate( 1, 0, 0 );
2687 array_push( $wgDeferredUpdateList, $u );
2691 # Update newtalk / watchlist notification status
2692 $wgUser->clearNotification( $this->mTitle );
2696 * Prepare text which is about to be saved.
2697 * Returns a stdclass with source, pst and output members
2699 function prepareTextForEdit( $text, $revid=null ) {
2700 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2701 // Already prepared
2702 return $this->mPreparedEdit;
2704 global $wgParser;
2705 $edit = (object)array();
2706 $edit->revid = $revid;
2707 $edit->newText = $text;
2708 $edit->pst = $this->preSaveTransform( $text );
2709 $options = new ParserOptions;
2710 $options->setTidy( true );
2711 $options->enableLimitReport();
2712 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2713 $edit->oldText = $this->getContent();
2714 $this->mPreparedEdit = $edit;
2715 return $edit;
2719 * Do standard deferred updates after page edit.
2720 * Update links tables, site stats, search index and message cache.
2721 * Purges pages that include this page if the text was changed here.
2722 * Every 100th edit, prune the recent changes table.
2724 * @private
2725 * @param $text New text of the article
2726 * @param $summary Edit summary
2727 * @param $minoredit Minor edit
2728 * @param $timestamp_of_pagechange Timestamp associated with the page change
2729 * @param $newid rev_id value of the new revision
2730 * @param $changed Whether or not the content actually changed
2732 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2733 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2735 wfProfileIn( __METHOD__ );
2737 # Parse the text
2738 # Be careful not to double-PST: $text is usually already PST-ed once
2739 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2740 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2741 $editInfo = $this->prepareTextForEdit( $text, $newid );
2742 } else {
2743 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2744 $editInfo = $this->mPreparedEdit;
2747 # Save it to the parser cache
2748 if ( $wgEnableParserCache ) {
2749 $parserCache = ParserCache::singleton();
2750 $parserCache->save( $editInfo->output, $this, $wgUser );
2753 # Update the links tables
2754 $u = new LinksUpdate( $this->mTitle, $editInfo->output, false );
2755 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2756 $u->doUpdate();
2758 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2759 if ( 0 == mt_rand( 0, 99 ) ) {
2760 // Flush old entries from the `recentchanges` table; we do this on
2761 // random requests so as to avoid an increase in writes for no good reason
2762 global $wgRCMaxAge;
2763 $dbw = wfGetDB( DB_MASTER );
2764 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2765 $recentchanges = $dbw->tableName( 'recentchanges' );
2766 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2767 $dbw->query( $sql );
2771 $id = $this->getID();
2772 $title = $this->mTitle->getPrefixedDBkey();
2773 $shortTitle = $this->mTitle->getDBkey();
2775 if ( 0 == $id ) {
2776 wfProfileOut( __METHOD__ );
2777 return;
2780 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2781 array_push( $wgDeferredUpdateList, $u );
2782 $u = new SearchUpdate( $id, $title, $text );
2783 array_push( $wgDeferredUpdateList, $u );
2785 # If this is another user's talk page, update newtalk
2786 # Don't do this if $changed = false otherwise some idiot can null-edit a
2787 # load of user talk pages and piss people off, nor if it's a minor edit
2788 # by a properly-flagged bot.
2789 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2790 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2791 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2792 $other = User::newFromName( $shortTitle, false );
2793 if ( !$other ) {
2794 wfDebug( __METHOD__.": invalid username\n" );
2795 } elseif( User::isIP( $shortTitle ) ) {
2796 // An anonymous user
2797 $other->setNewtalk( true );
2798 } elseif( $other->isLoggedIn() ) {
2799 $other->setNewtalk( true );
2800 } else {
2801 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
2806 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2807 $wgMessageCache->replace( $shortTitle, $text );
2810 wfProfileOut( __METHOD__ );
2814 * Perform article updates on a special page creation.
2816 * @param Revision $rev
2818 * @todo This is a shitty interface function. Kill it and replace the
2819 * other shitty functions like editUpdates and such so it's not needed
2820 * anymore.
2822 function createUpdates( $rev ) {
2823 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2824 $this->mTotalAdjustment = 1;
2825 $this->editUpdates( $rev->getText(), $rev->getComment(),
2826 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2830 * Generate the navigation links when browsing through an article revisions
2831 * It shows the information as:
2832 * Revision as of \<date\>; view current revision
2833 * \<- Previous version | Next Version -\>
2835 * @private
2836 * @param string $oldid Revision ID of this article revision
2838 function setOldSubtitle( $oldid=0 ) {
2839 global $wgLang, $wgOut, $wgUser;
2841 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2842 return;
2845 $revision = Revision::newFromId( $oldid );
2847 $current = ( $oldid == $this->mLatest );
2848 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2849 $sk = $wgUser->getSkin();
2850 $lnk = $current
2851 ? wfMsg( 'currentrevisionlink' )
2852 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2853 $curdiff = $current
2854 ? wfMsg( 'diff' )
2855 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2856 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2857 $prevlink = $prev
2858 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2859 : wfMsg( 'previousrevision' );
2860 $prevdiff = $prev
2861 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2862 : wfMsg( 'diff' );
2863 $nextlink = $current
2864 ? wfMsg( 'nextrevision' )
2865 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2866 $nextdiff = $current
2867 ? wfMsg( 'diff' )
2868 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2870 $cdel='';
2871 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2872 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2873 if( $revision->isCurrent() ) {
2874 // We don't handle top deleted edits too well
2875 $cdel = wfMsgHtml('rev-delundel');
2876 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2877 // If revision was hidden from sysops
2878 $cdel = wfMsgHtml('rev-delundel');
2879 } else {
2880 $cdel = $sk->makeKnownLinkObj( $revdel,
2881 wfMsgHtml('rev-delundel'),
2882 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2883 '&oldid=' . urlencode( $oldid ) );
2884 // Bolden oversighted content
2885 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2886 $cdel = "<strong>$cdel</strong>";
2888 $cdel = "(<small>$cdel</small>) ";
2890 # Show user links if allowed to see them. Normally they
2891 # are hidden regardless, but since we can already see the text here...
2892 $userlinks = $sk->revUserTools( $revision, false );
2894 $m = wfMsg( 'revision-info-current' );
2895 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2896 ? 'revision-info-current'
2897 : 'revision-info';
2899 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2901 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff,
2902 $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2903 $wgOut->setSubtitle( $r );
2907 * This function is called right before saving the wikitext,
2908 * so we can do things like signatures and links-in-context.
2910 * @param string $text
2912 function preSaveTransform( $text ) {
2913 global $wgParser, $wgUser;
2914 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2917 /* Caching functions */
2920 * checkLastModified returns true if it has taken care of all
2921 * output to the client that is necessary for this request.
2922 * (that is, it has sent a cached version of the page)
2924 function tryFileCache() {
2925 static $called = false;
2926 if( $called ) {
2927 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2928 return;
2930 $called = true;
2931 if($this->isFileCacheable()) {
2932 $touched = $this->mTouched;
2933 $cache = new HTMLFileCache( $this->mTitle );
2934 if($cache->isFileCacheGood( $touched )) {
2935 wfDebug( "Article::tryFileCache(): about to load file\n" );
2936 $cache->loadFromFileCache();
2937 return true;
2938 } else {
2939 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2940 ob_start( array(&$cache, 'saveToFileCache' ) );
2942 } else {
2943 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2948 * Check if the page can be cached
2949 * @return bool
2951 function isFileCacheable() {
2952 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2953 $action = $wgRequest->getVal( 'action' );
2954 $oldid = $wgRequest->getVal( 'oldid' );
2955 $diff = $wgRequest->getVal( 'diff' );
2956 $redirect = $wgRequest->getVal( 'redirect' );
2957 $printable = $wgRequest->getVal( 'printable' );
2958 $page = $wgRequest->getVal( 'page' );
2959 $useskin = $wgRequest->getVal( 'useskin' );
2961 //check for non-standard user language; this covers uselang,
2962 //and extensions for auto-detecting user language.
2963 $ulang = $wgLang->getCode();
2964 $clang = $wgContLang->getCode();
2966 $cacheable = $wgUseFileCache
2967 && (!$wgShowIPinHeader)
2968 && ($this->getID() != 0)
2969 && ($wgUser->isAnon())
2970 && (!$wgUser->getNewtalk())
2971 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2972 && (!isset($useskin))
2973 && (empty( $action ) || $action == 'view')
2974 && (!isset($oldid))
2975 && (!isset($diff))
2976 && (!isset($redirect))
2977 && (!isset($printable))
2978 && !isset($page)
2979 && (!$this->mRedirectedFrom)
2980 && ($ulang === $clang);
2982 if ( $cacheable ) {
2983 //extension may have reason to disable file caching on some pages.
2984 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
2987 return $cacheable;
2991 * Loads page_touched and returns a value indicating if it should be used
2994 function checkTouched() {
2995 if( !$this->mDataLoaded ) {
2996 $this->loadPageData();
2998 return !$this->mIsRedirect;
3002 * Get the page_touched field
3004 function getTouched() {
3005 # Ensure that page data has been loaded
3006 if( !$this->mDataLoaded ) {
3007 $this->loadPageData();
3009 return $this->mTouched;
3013 * Get the page_latest field
3015 function getLatest() {
3016 if ( !$this->mDataLoaded ) {
3017 $this->loadPageData();
3019 return $this->mLatest;
3023 * Edit an article without doing all that other stuff
3024 * The article must already exist; link tables etc
3025 * are not updated, caches are not flushed.
3027 * @param string $text text submitted
3028 * @param string $comment comment submitted
3029 * @param bool $minor whereas it's a minor modification
3031 function quickEdit( $text, $comment = '', $minor = 0 ) {
3032 wfProfileIn( __METHOD__ );
3034 $dbw = wfGetDB( DB_MASTER );
3035 $revision = new Revision( array(
3036 'page' => $this->getId(),
3037 'text' => $text,
3038 'comment' => $comment,
3039 'minor_edit' => $minor ? 1 : 0,
3040 ) );
3041 $revision->insertOn( $dbw );
3042 $this->updateRevisionOn( $dbw, $revision );
3044 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
3046 wfProfileOut( __METHOD__ );
3050 * Used to increment the view counter
3052 * @static
3053 * @param integer $id article id
3055 function incViewCount( $id ) {
3056 $id = intval( $id );
3057 global $wgHitcounterUpdateFreq, $wgDBtype;
3059 $dbw = wfGetDB( DB_MASTER );
3060 $pageTable = $dbw->tableName( 'page' );
3061 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3062 $acchitsTable = $dbw->tableName( 'acchits' );
3064 if( $wgHitcounterUpdateFreq <= 1 ) {
3065 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3066 return;
3069 # Not important enough to warrant an error page in case of failure
3070 $oldignore = $dbw->ignoreErrors( true );
3072 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3074 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3075 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3076 # Most of the time (or on SQL errors), skip row count check
3077 $dbw->ignoreErrors( $oldignore );
3078 return;
3081 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3082 $row = $dbw->fetchObject( $res );
3083 $rown = intval( $row->n );
3084 if( $rown >= $wgHitcounterUpdateFreq ){
3085 wfProfileIn( 'Article::incViewCount-collect' );
3086 $old_user_abort = ignore_user_abort( true );
3088 if ($wgDBtype == 'mysql')
3089 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3090 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3091 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3092 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3093 'GROUP BY hc_id');
3094 $dbw->query("DELETE FROM $hitcounterTable");
3095 if ($wgDBtype == 'mysql') {
3096 $dbw->query('UNLOCK TABLES');
3097 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3098 'WHERE page_id = hc_id');
3100 else {
3101 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3102 "FROM $acchitsTable WHERE page_id = hc_id");
3104 $dbw->query("DROP TABLE $acchitsTable");
3106 ignore_user_abort( $old_user_abort );
3107 wfProfileOut( 'Article::incViewCount-collect' );
3109 $dbw->ignoreErrors( $oldignore );
3112 /**#@+
3113 * The onArticle*() functions are supposed to be a kind of hooks
3114 * which should be called whenever any of the specified actions
3115 * are done.
3117 * This is a good place to put code to clear caches, for instance.
3119 * This is called on page move and undelete, as well as edit
3120 * @static
3121 * @param $title_obj a title object
3124 public static function onArticleCreate( $title ) {
3125 # Update existence markers on article/talk tabs...
3126 if ( $title->isTalkPage() ) {
3127 $other = $title->getSubjectPage();
3128 } else {
3129 $other = $title->getTalkPage();
3131 $other->invalidateCache();
3132 $other->purgeSquid();
3134 $title->touchLinks();
3135 $title->purgeSquid();
3136 $title->deleteTitleProtection();
3139 public static function onArticleDelete( $title ) {
3140 global $wgUseFileCache, $wgMessageCache;
3141 # Update existence markers on article/talk tabs...
3142 if( $title->isTalkPage() ) {
3143 $other = $title->getSubjectPage();
3144 } else {
3145 $other = $title->getTalkPage();
3147 $other->invalidateCache();
3148 $other->purgeSquid();
3150 $title->touchLinks();
3151 $title->purgeSquid();
3153 # File cache
3154 if ( $wgUseFileCache ) {
3155 $cm = new HTMLFileCache( $title );
3156 @unlink( $cm->fileCacheName() );
3159 # Messages
3160 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3161 $wgMessageCache->replace( $title->getDBkey(), false );
3163 # Images
3164 if( $title->getNamespace() == NS_IMAGE ) {
3165 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3166 $update->doUpdate();
3168 # User talk pages
3169 if( $title->getNamespace() == NS_USER_TALK ) {
3170 $user = User::newFromName( $title->getText(), false );
3171 $user->setNewtalk( false );
3176 * Purge caches on page update etc
3178 public static function onArticleEdit( $title, $touchTemplates = true ) {
3179 global $wgDeferredUpdateList, $wgUseFileCache;
3181 // Invalidate caches of articles which include this page
3182 if( $touchTemplates )
3183 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3185 // Invalidate the caches of all pages which redirect here
3186 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3188 # Purge squid for this page only
3189 $title->purgeSquid();
3191 # Clear file cache for this page only
3192 if ( $wgUseFileCache ) {
3193 $cm = new HTMLFileCache( $title );
3194 @unlink( $cm->fileCacheName() );
3198 /**#@-*/
3201 * Overriden by ImagePage class, only present here to avoid a fatal error
3202 * Called for ?action=revert
3204 public function revert(){
3205 global $wgOut;
3206 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3210 * Info about this page
3211 * Called for ?action=info when $wgAllowPageInfo is on.
3213 * @public
3215 function info() {
3216 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3218 if ( !$wgAllowPageInfo ) {
3219 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3220 return;
3223 $page = $this->mTitle->getSubjectPage();
3225 $wgOut->setPagetitle( $page->getPrefixedText() );
3226 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3227 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3229 if( !$this->mTitle->exists() ) {
3230 $wgOut->addHtml( '<div class="noarticletext">' );
3231 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3232 // This doesn't quite make sense; the user is asking for
3233 // information about the _page_, not the message... -- RC
3234 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3235 } else {
3236 $msg = $wgUser->isLoggedIn()
3237 ? 'noarticletext'
3238 : 'noarticletextanon';
3239 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3241 $wgOut->addHtml( '</div>' );
3242 } else {
3243 $dbr = wfGetDB( DB_SLAVE );
3244 $wl_clause = array(
3245 'wl_title' => $page->getDBkey(),
3246 'wl_namespace' => $page->getNamespace() );
3247 $numwatchers = $dbr->selectField(
3248 'watchlist',
3249 'COUNT(*)',
3250 $wl_clause,
3251 __METHOD__,
3252 $this->getSelectOptions() );
3254 $pageInfo = $this->pageCountInfo( $page );
3255 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3257 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3258 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3259 if( $talkInfo ) {
3260 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3262 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3263 if( $talkInfo ) {
3264 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3266 $wgOut->addHTML( '</ul>' );
3272 * Return the total number of edits and number of unique editors
3273 * on a given page. If page does not exist, returns false.
3275 * @param Title $title
3276 * @return array
3277 * @private
3279 function pageCountInfo( $title ) {
3280 $id = $title->getArticleId();
3281 if( $id == 0 ) {
3282 return false;
3285 $dbr = wfGetDB( DB_SLAVE );
3287 $rev_clause = array( 'rev_page' => $id );
3289 $edits = $dbr->selectField(
3290 'revision',
3291 'COUNT(rev_page)',
3292 $rev_clause,
3293 __METHOD__,
3294 $this->getSelectOptions() );
3296 $authors = $dbr->selectField(
3297 'revision',
3298 'COUNT(DISTINCT rev_user_text)',
3299 $rev_clause,
3300 __METHOD__,
3301 $this->getSelectOptions() );
3303 return array( 'edits' => $edits, 'authors' => $authors );
3307 * Return a list of templates used by this article.
3308 * Uses the templatelinks table
3310 * @return array Array of Title objects
3312 public function getUsedTemplates() {
3313 $result = array();
3314 $id = $this->mTitle->getArticleID();
3315 if( $id == 0 ) {
3316 return array();
3319 $dbr = wfGetDB( DB_SLAVE );
3320 $res = $dbr->select( array( 'templatelinks' ),
3321 array( 'tl_namespace', 'tl_title' ),
3322 array( 'tl_from' => $id ),
3323 __METHOD__ );
3324 if( false !== $res ) {
3325 foreach( $res as $row ) {
3326 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3329 $dbr->freeResult( $res );
3330 return $result;
3334 * Returns a list of hidden categories this page is a member of.
3335 * Uses the page_props and categorylinks tables.
3337 * @return array Array of Title objects
3339 public function getHiddenCategories() {
3340 $result = array();
3341 $id = $this->mTitle->getArticleID();
3342 if( $id == 0 ) {
3343 return array();
3346 $dbr = wfGetDB( DB_SLAVE );
3347 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3348 array( 'cl_to' ),
3349 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3350 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3351 __METHOD__ );
3352 if ( false !== $res ) {
3353 foreach( $res as $row ) {
3354 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3357 $dbr->freeResult( $res );
3358 return $result;
3362 * Return an applicable autosummary if one exists for the given edit.
3363 * @param string $oldtext The previous text of the page.
3364 * @param string $newtext The submitted text of the page.
3365 * @param bitmask $flags A bitmask of flags submitted for the edit.
3366 * @return string An appropriate autosummary, or an empty string.
3368 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3369 # Decide what kind of autosummary is needed.
3371 # Redirect autosummaries
3372 $rt = Title::newFromRedirect( $newtext );
3373 if( is_object( $rt ) ) {
3374 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3377 # New page autosummaries
3378 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3379 # If they're making a new article, give its text, truncated, in the summary.
3380 global $wgContLang;
3381 $truncatedtext = $wgContLang->truncate(
3382 str_replace("\n", ' ', $newtext),
3383 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3384 '...' );
3385 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3388 # Blanking autosummaries
3389 if( $oldtext != '' && $newtext == '' ) {
3390 return wfMsgForContent('autosumm-blank');
3391 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3392 # Removing more than 90% of the article
3393 global $wgContLang;
3394 $truncatedtext = $wgContLang->truncate(
3395 $newtext,
3396 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3397 '...'
3399 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3402 # If we reach this point, there's no applicable autosummary for our case, so our
3403 # autosummary is empty.
3404 return '';
3408 * Add the primary page-view wikitext to the output buffer
3409 * Saves the text into the parser cache if possible.
3410 * Updates templatelinks if it is out of date.
3412 * @param string $text
3413 * @param bool $cache
3415 public function outputWikiText( $text, $cache = true ) {
3416 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3418 $popts = $wgOut->parserOptions();
3419 $popts->setTidy(true);
3420 $popts->enableLimitReport();
3421 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3422 $popts, true, true, $this->getRevIdFetched() );
3423 $popts->setTidy(false);
3424 $popts->enableLimitReport( false );
3425 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3426 $parserCache = ParserCache::singleton();
3427 $parserCache->save( $parserOutput, $this, $wgUser );
3430 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3431 // templatelinks table may have become out of sync,
3432 // especially if using variable-based transclusions.
3433 // For paranoia, check if things have changed and if
3434 // so apply updates to the database. This will ensure
3435 // that cascaded protections apply as soon as the changes
3436 // are visible.
3438 # Get templates from templatelinks
3439 $id = $this->mTitle->getArticleID();
3441 $tlTemplates = array();
3443 $dbr = wfGetDB( DB_SLAVE );
3444 $res = $dbr->select( array( 'templatelinks' ),
3445 array( 'tl_namespace', 'tl_title' ),
3446 array( 'tl_from' => $id ),
3447 __METHOD__ );
3449 global $wgContLang;
3451 if ( false !== $res ) {
3452 foreach( $res as $row ) {
3453 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3457 # Get templates from parser output.
3458 $poTemplates_allns = $parserOutput->getTemplates();
3460 $poTemplates = array ();
3461 foreach ( $poTemplates_allns as $ns_templates ) {
3462 $poTemplates = array_merge( $poTemplates, $ns_templates );
3465 # Get the diff
3466 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3468 if ( count( $templates_diff ) > 0 ) {
3469 # Whee, link updates time.
3470 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3471 $u->doUpdate();
3475 $wgOut->addParserOutput( $parserOutput );
3479 * Update all the appropriate counts in the category table, given that
3480 * we've added the categories $added and deleted the categories $deleted.
3482 * @param $added array The names of categories that were added
3483 * @param $deleted array The names of categories that were deleted
3484 * @return null
3486 public function updateCategoryCounts( $added, $deleted ) {
3487 $ns = $this->mTitle->getNamespace();
3488 $dbw = wfGetDB( DB_MASTER );
3490 # First make sure the rows exist. If one of the "deleted" ones didn't
3491 # exist, we might legitimately not create it, but it's simpler to just
3492 # create it and then give it a negative value, since the value is bogus
3493 # anyway.
3495 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3496 $insertCats = array_merge( $added, $deleted );
3497 if( !$insertCats ) {
3498 # Okay, nothing to do
3499 return;
3501 $insertRows = array();
3502 foreach( $insertCats as $cat ) {
3503 $insertRows[] = array( 'cat_title' => $cat );
3505 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3507 $addFields = array( 'cat_pages = cat_pages + 1' );
3508 $removeFields = array( 'cat_pages = cat_pages - 1' );
3509 if( $ns == NS_CATEGORY ) {
3510 $addFields[] = 'cat_subcats = cat_subcats + 1';
3511 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3512 } elseif( $ns == NS_IMAGE ) {
3513 $addFields[] = 'cat_files = cat_files + 1';
3514 $removeFields[] = 'cat_files = cat_files - 1';
3517 if ( $added ) {
3518 $dbw->update(
3519 'category',
3520 $addFields,
3521 array( 'cat_title' => $added ),
3522 __METHOD__
3525 if ( $deleted ) {
3526 $dbw->update(
3527 'category',
3528 $removeFields,
3529 array( 'cat_title' => $deleted ),
3530 __METHOD__