Update the Chinese conversion tables
[mediawiki.git] / includes / Article.php
blobad45b44e2dcac9332aec1b23809b2875f50850f1
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 * Tell the page view functions that this view was redirected
57 * from another page on the wiki.
58 * @param $from Title object.
60 function setRedirectedFrom( $from ) {
61 $this->mRedirectedFrom = $from;
64 /**
65 * If this page is a redirect, get its target
67 * The target will be fetched from the redirect table if possible.
68 * If this page doesn't have an entry there, call insertRedirect()
69 * @return mixed Title object, or null if this page is not a redirect
71 public function getRedirectTarget() {
72 if(!$this->mTitle || !$this->mTitle->isRedirect())
73 return null;
74 if(!is_null($this->mRedirectTarget))
75 return $this->mRedirectTarget;
77 # Query the redirect table
78 $dbr = wfGetDB(DB_SLAVE);
79 $res = $dbr->select('redirect',
80 array('rd_namespace', 'rd_title'),
81 array('rd_from' => $this->getID()),
82 __METHOD__
84 $row = $dbr->fetchObject($res);
85 if($row)
86 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
88 # This page doesn't have an entry in the redirect table
89 return $this->mRedirectTarget = $this->insertRedirect();
92 /**
93 * Insert an entry for this page into the redirect table.
95 * Don't call this function directly unless you know what you're doing.
96 * @return Title object
98 public function insertRedirect() {
99 $retval = Title::newFromRedirect($this->getContent());
100 if(!$retval)
101 return null;
102 $dbw = wfGetDB(DB_MASTER);
103 $dbw->replace('redirect', array('rd_from'), array(
104 'rd_from' => $this->getID(),
105 'rd_namespace' => $retval->getNamespace(),
106 'rd_title' => $retval->getDBKey()
107 ), __METHOD__);
108 return $retval;
112 * Get the Title object this page redirects to
114 * @return mixed false, Title of in-wiki target, or string with URL
116 public function followRedirect() {
117 $text = $this->getContent();
118 return self::followRedirectText( $text );
122 * Get the Title object this text redirects to
124 * @return mixed false, Title of in-wiki target, or string with URL
126 public function followRedirectText( $text ) {
127 $rt = Title::newFromRedirect( $text );
128 # process if title object is valid and not special:userlogout
129 if( $rt ) {
130 if( $rt->getInterwiki() != '' ) {
131 if( $rt->isLocal() ) {
132 // Offsite wikis need an HTTP redirect.
134 // This can be hard to reverse and may produce loops,
135 // so they may be disabled in the site configuration.
137 $source = $this->mTitle->getFullURL( 'redirect=no' );
138 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
140 } else {
141 if( $rt->getNamespace() == NS_SPECIAL ) {
142 // Gotta handle redirects to special pages differently:
143 // Fill the HTTP response "Location" header and ignore
144 // the rest of the page we're on.
146 // This can be hard to reverse, so they may be disabled.
148 if( $rt->isSpecial( 'Userlogout' ) ) {
149 // rolleyes
150 } else {
151 return $rt->getFullURL();
154 return $rt;
157 // No or invalid redirect
158 return false;
162 * get the title object of the article
164 function getTitle() {
165 return $this->mTitle;
169 * Clear the object
170 * @private
172 function clear() {
173 $this->mDataLoaded = false;
174 $this->mContentLoaded = false;
176 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
177 $this->mRedirectedFrom = null; # Title object if set
178 $this->mRedirectTarget = null; # Title object if set
179 $this->mUserText =
180 $this->mTimestamp = $this->mComment = '';
181 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
182 $this->mTouched = '19700101000000';
183 $this->mForUpdate = false;
184 $this->mIsRedirect = false;
185 $this->mRevIdFetched = 0;
186 $this->mRedirectUrl = false;
187 $this->mLatest = false;
188 $this->mPreparedEdit = false;
192 * Note that getContent/loadContent do not follow redirects anymore.
193 * If you need to fetch redirectable content easily, try
194 * the shortcut in Article::followContent()
195 * FIXME
196 * @todo There are still side-effects in this!
197 * In general, you should use the Revision class, not Article,
198 * to fetch text for purposes other than page views.
200 * @return Return the text of this revision
202 function getContent() {
203 global $wgUser, $wgOut, $wgMessageCache;
205 wfProfileIn( __METHOD__ );
207 if ( 0 == $this->getID() ) {
208 wfProfileOut( __METHOD__ );
209 $wgOut->setRobotPolicy( 'noindex,nofollow' );
211 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
212 $wgMessageCache->loadAllMessages();
213 $ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
214 } else {
215 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
218 return "<div class='noarticletext'>\n$ret\n</div>";
219 } else {
220 $this->loadContent();
221 wfProfileOut( __METHOD__ );
222 return $this->mContent;
227 * This function returns the text of a section, specified by a number ($section).
228 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
229 * the first section before any such heading (section 0).
231 * If a section contains subsections, these are also returned.
233 * @param $text String: text to look in
234 * @param $section Integer: section number
235 * @return string text of the requested section
236 * @deprecated
238 function getSection($text,$section) {
239 global $wgParser;
240 return $wgParser->getSection( $text, $section );
244 * @return int The oldid of the article that is to be shown, 0 for the
245 * current revision
247 function getOldID() {
248 if ( is_null( $this->mOldId ) ) {
249 $this->mOldId = $this->getOldIDFromRequest();
251 return $this->mOldId;
255 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
257 * @return int The old id for the request
259 function getOldIDFromRequest() {
260 global $wgRequest;
261 $this->mRedirectUrl = false;
262 $oldid = $wgRequest->getVal( 'oldid' );
263 if ( isset( $oldid ) ) {
264 $oldid = intval( $oldid );
265 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
266 $nextid = $this->mTitle->getNextRevisionID( $oldid );
267 if ( $nextid ) {
268 $oldid = $nextid;
269 } else {
270 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
272 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
273 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
274 if ( $previd ) {
275 $oldid = $previd;
276 } else {
277 # TODO
280 # unused:
281 # $lastid = $oldid;
284 if ( !$oldid ) {
285 $oldid = 0;
287 return $oldid;
291 * Load the revision (including text) into this object
293 function loadContent() {
294 if ( $this->mContentLoaded ) return;
296 # Query variables :P
297 $oldid = $this->getOldID();
299 # Pre-fill content with error message so that if something
300 # fails we'll have something telling us what we intended.
301 $this->mOldId = $oldid;
302 $this->fetchContent( $oldid );
307 * Fetch a page record with the given conditions
308 * @param Database $dbr
309 * @param array $conditions
310 * @private
312 function pageData( $dbr, $conditions ) {
313 $fields = array(
314 'page_id',
315 'page_namespace',
316 'page_title',
317 'page_restrictions',
318 'page_counter',
319 'page_is_redirect',
320 'page_is_new',
321 'page_random',
322 'page_touched',
323 'page_latest',
324 'page_len',
326 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
327 $row = $dbr->selectRow(
328 'page',
329 $fields,
330 $conditions,
331 __METHOD__
333 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
334 return $row ;
338 * @param Database $dbr
339 * @param Title $title
341 function pageDataFromTitle( $dbr, $title ) {
342 return $this->pageData( $dbr, array(
343 'page_namespace' => $title->getNamespace(),
344 'page_title' => $title->getDBkey() ) );
348 * @param Database $dbr
349 * @param int $id
351 function pageDataFromId( $dbr, $id ) {
352 return $this->pageData( $dbr, array( 'page_id' => $id ) );
356 * Set the general counter, title etc data loaded from
357 * some source.
359 * @param object $data
360 * @private
362 function loadPageData( $data = 'fromdb' ) {
363 if ( $data === 'fromdb' ) {
364 $dbr = wfGetDB( DB_MASTER );
365 $data = $this->pageDataFromId( $dbr, $this->getId() );
368 $lc = LinkCache::singleton();
369 if ( $data ) {
370 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
372 $this->mTitle->mArticleID = $data->page_id;
374 # Old-fashioned restrictions.
375 $this->mTitle->loadRestrictions( $data->page_restrictions );
377 $this->mCounter = $data->page_counter;
378 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
379 $this->mIsRedirect = $data->page_is_redirect;
380 $this->mLatest = $data->page_latest;
381 } else {
382 if ( is_object( $this->mTitle ) ) {
383 $lc->addBadLinkObj( $this->mTitle );
385 $this->mTitle->mArticleID = 0;
388 $this->mDataLoaded = true;
392 * Get text of an article from database
393 * Does *NOT* follow redirects.
394 * @param int $oldid 0 for whatever the latest revision is
395 * @return string
397 function fetchContent( $oldid = 0 ) {
398 if ( $this->mContentLoaded ) {
399 return $this->mContent;
402 $dbr = wfGetDB( DB_MASTER );
404 # Pre-fill content with error message so that if something
405 # fails we'll have something telling us what we intended.
406 $t = $this->mTitle->getPrefixedText();
407 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
408 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
410 if( $oldid ) {
411 $revision = Revision::newFromId( $oldid );
412 if( is_null( $revision ) ) {
413 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
414 return false;
416 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
417 if( !$data ) {
418 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
419 return false;
421 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
422 $this->loadPageData( $data );
423 } else {
424 if( !$this->mDataLoaded ) {
425 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
426 if( !$data ) {
427 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
428 return false;
430 $this->loadPageData( $data );
432 $revision = Revision::newFromId( $this->mLatest );
433 if( is_null( $revision ) ) {
434 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$data->page_latest}\n" );
435 return false;
439 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
440 // We should instead work with the Revision object when we need it...
441 $this->mContent = $revision->revText(); // Loads if user is allowed
443 $this->mUser = $revision->getUser();
444 $this->mUserText = $revision->getUserText();
445 $this->mComment = $revision->getComment();
446 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
448 $this->mRevIdFetched = $revision->getId();
449 $this->mContentLoaded = true;
450 $this->mRevision =& $revision;
452 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
454 return $this->mContent;
458 * Read/write accessor to select FOR UPDATE
460 * @param $x Mixed: FIXME
462 function forUpdate( $x = NULL ) {
463 return wfSetVar( $this->mForUpdate, $x );
467 * Get the database which should be used for reads
469 * @return Database
470 * @deprecated - just call wfGetDB( DB_MASTER ) instead
472 function getDB() {
473 wfDeprecated( __METHOD__ );
474 return wfGetDB( DB_MASTER );
478 * Get options for all SELECT statements
480 * @param $options Array: an optional options array which'll be appended to
481 * the default
482 * @return Array: options
484 function getSelectOptions( $options = '' ) {
485 if ( $this->mForUpdate ) {
486 if ( is_array( $options ) ) {
487 $options[] = 'FOR UPDATE';
488 } else {
489 $options = 'FOR UPDATE';
492 return $options;
496 * @return int Page ID
498 function getID() {
499 if( $this->mTitle ) {
500 return $this->mTitle->getArticleID();
501 } else {
502 return 0;
507 * @return bool Whether or not the page exists in the database
509 function exists() {
510 return $this->getId() != 0;
514 * @return int The view count for the page
516 function getCount() {
517 if ( -1 == $this->mCounter ) {
518 $id = $this->getID();
519 if ( $id == 0 ) {
520 $this->mCounter = 0;
521 } else {
522 $dbr = wfGetDB( DB_SLAVE );
523 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
524 'Article::getCount', $this->getSelectOptions() );
527 return $this->mCounter;
531 * Determine whether a page would be suitable for being counted as an
532 * article in the site_stats table based on the title & its content
534 * @param $text String: text to analyze
535 * @return bool
537 function isCountable( $text ) {
538 global $wgUseCommaCount;
540 $token = $wgUseCommaCount ? ',' : '[[';
541 return
542 $this->mTitle->isContentPage()
543 && !$this->isRedirect( $text )
544 && in_string( $token, $text );
548 * Tests if the article text represents a redirect
550 * @param $text String: FIXME
551 * @return bool
553 function isRedirect( $text = false ) {
554 if ( $text === false ) {
555 if ( $this->mDataLoaded )
556 return $this->mIsRedirect;
558 // Apparently loadPageData was never called
559 $this->loadContent();
560 $titleObj = Title::newFromRedirect( $this->fetchContent() );
561 } else {
562 $titleObj = Title::newFromRedirect( $text );
564 return $titleObj !== NULL;
568 * Returns true if the currently-referenced revision is the current edit
569 * to this page (and it exists).
570 * @return bool
572 function isCurrent() {
573 # If no oldid, this is the current version.
574 if ($this->getOldID() == 0)
575 return true;
577 return $this->exists() &&
578 isset( $this->mRevision ) &&
579 $this->mRevision->isCurrent();
583 * Loads everything except the text
584 * This isn't necessary for all uses, so it's only done if needed.
585 * @private
587 function loadLastEdit() {
588 if ( -1 != $this->mUser )
589 return;
591 # New or non-existent articles have no user information
592 $id = $this->getID();
593 if ( 0 == $id ) return;
595 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
596 if( !is_null( $this->mLastRevision ) ) {
597 $this->mUser = $this->mLastRevision->getUser();
598 $this->mUserText = $this->mLastRevision->getUserText();
599 $this->mTimestamp = $this->mLastRevision->getTimestamp();
600 $this->mComment = $this->mLastRevision->getComment();
601 $this->mMinorEdit = $this->mLastRevision->isMinor();
602 $this->mRevIdFetched = $this->mLastRevision->getId();
606 function getTimestamp() {
607 // Check if the field has been filled by ParserCache::get()
608 if ( !$this->mTimestamp ) {
609 $this->loadLastEdit();
611 return wfTimestamp(TS_MW, $this->mTimestamp);
614 function getUser() {
615 $this->loadLastEdit();
616 return $this->mUser;
619 function getUserText() {
620 $this->loadLastEdit();
621 return $this->mUserText;
624 function getComment() {
625 $this->loadLastEdit();
626 return $this->mComment;
629 function getMinorEdit() {
630 $this->loadLastEdit();
631 return $this->mMinorEdit;
634 function getRevIdFetched() {
635 $this->loadLastEdit();
636 return $this->mRevIdFetched;
640 * @param $limit Integer: default 0.
641 * @param $offset Integer: default 0.
643 function getContributors($limit = 0, $offset = 0) {
644 # XXX: this is expensive; cache this info somewhere.
646 $contribs = array();
647 $dbr = wfGetDB( DB_SLAVE );
648 $revTable = $dbr->tableName( 'revision' );
649 $userTable = $dbr->tableName( 'user' );
650 $user = $this->getUser();
651 $pageId = $this->getId();
653 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
654 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
655 WHERE rev_page = $pageId
656 AND rev_user != $user
657 GROUP BY rev_user, rev_user_text, user_real_name
658 ORDER BY timestamp DESC";
660 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
661 if ($offset > 0) { $sql .= ' OFFSET '.$offset; }
663 $sql .= ' '. $this->getSelectOptions();
665 $res = $dbr->query($sql, __METHOD__);
667 while ( $line = $dbr->fetchObject( $res ) ) {
668 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
671 $dbr->freeResult($res);
672 return $contribs;
676 * This is the default action of the script: just view the page of
677 * the given title.
679 function view() {
680 global $wgUser, $wgOut, $wgRequest, $wgContLang;
681 global $wgEnableParserCache, $wgStylePath, $wgParser;
682 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
683 global $wgDefaultRobotPolicy;
684 $sk = $wgUser->getSkin();
686 wfProfileIn( __METHOD__ );
688 $parserCache = ParserCache::singleton();
689 $ns = $this->mTitle->getNamespace(); # shortcut
691 # Get variables from query string
692 $oldid = $this->getOldID();
694 # getOldID may want us to redirect somewhere else
695 if ( $this->mRedirectUrl ) {
696 $wgOut->redirect( $this->mRedirectUrl );
697 wfProfileOut( __METHOD__ );
698 return;
701 $diff = $wgRequest->getVal( 'diff' );
702 $rcid = $wgRequest->getVal( 'rcid' );
703 $rdfrom = $wgRequest->getVal( 'rdfrom' );
704 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
705 $purge = $wgRequest->getVal( 'action' ) == 'purge';
707 $wgOut->setArticleFlag( true );
709 # Discourage indexing of printable versions, but encourage following
710 if( $wgOut->isPrintable() ) {
711 $policy = 'noindex,follow';
712 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
713 $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
714 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
715 # Honour customised robot policies for this namespace
716 $policy = $wgNamespaceRobotPolicies[$ns];
717 } else {
718 $policy = $wgDefaultRobotPolicy;
720 $wgOut->setRobotPolicy( $policy );
722 # If we got diff and oldid in the query, we want to see a
723 # diff page instead of the article.
725 if ( !is_null( $diff ) ) {
726 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
728 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge );
729 // DifferenceEngine directly fetched the revision:
730 $this->mRevIdFetched = $de->mNewid;
731 $de->showDiffPage( $diffOnly );
733 // Needed to get the page's current revision
734 $this->loadPageData();
735 if( $diff == 0 || $diff == $this->mLatest ) {
736 # Run view updates for current revision only
737 $this->viewUpdates();
739 wfProfileOut( __METHOD__ );
740 return;
743 if ( empty( $oldid ) && $this->checkTouched() ) {
744 $wgOut->setETag($parserCache->getETag($this, $wgUser));
746 if( $wgOut->checkLastModified( $this->mTouched ) ){
747 wfProfileOut( __METHOD__ );
748 return;
749 } else if ( $this->tryFileCache() ) {
750 # tell wgOut that output is taken care of
751 $wgOut->disable();
752 $this->viewUpdates();
753 wfProfileOut( __METHOD__ );
754 return;
758 # Should the parser cache be used?
759 $pcache = $this->useParserCache( $oldid );
760 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
761 if ( $wgUser->getOption( 'stubthreshold' ) ) {
762 wfIncrStats( 'pcache_miss_stub' );
765 $wasRedirected = false;
766 if ( isset( $this->mRedirectedFrom ) ) {
767 // This is an internally redirected page view.
768 // We'll need a backlink to the source page for navigation.
769 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
770 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
771 $s = wfMsg( 'redirectedfrom', $redir );
772 $wgOut->setSubtitle( $s );
774 // Set the fragment if one was specified in the redirect
775 if ( strval( $this->mTitle->getFragment() ) != '' ) {
776 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
777 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
779 $wasRedirected = true;
781 } elseif ( !empty( $rdfrom ) ) {
782 // This is an externally redirected view, from some other wiki.
783 // If it was reported from a trusted site, supply a backlink.
784 global $wgRedirectSources;
785 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
786 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
787 $s = wfMsg( 'redirectedfrom', $redir );
788 $wgOut->setSubtitle( $s );
789 $wasRedirected = true;
793 $outputDone = false;
794 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
795 if ( $pcache ) {
796 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
797 // Ensure that UI elements requiring revision ID have
798 // the correct version information.
799 $wgOut->setRevisionId( $this->mLatest );
800 $outputDone = true;
803 # Fetch content and check for errors
804 if ( !$outputDone ) {
805 $text = $this->getContent();
806 if ( $text === false ) {
807 # Failed to load, replace text with error message
808 $t = $this->mTitle->getPrefixedText();
809 if( $oldid ) {
810 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
811 $text = wfMsg( 'missing-article', $t, $d );
812 } else {
813 $text = wfMsg( 'noarticletext' );
817 # Another whitelist check in case oldid is altering the title
818 if ( !$this->mTitle->userCanRead() ) {
819 $wgOut->loginToUse();
820 $wgOut->output();
821 wfProfileOut( __METHOD__ );
822 exit;
825 # We're looking at an old revision
826 if ( !empty( $oldid ) ) {
827 $wgOut->setRobotPolicy( 'noindex,nofollow' );
828 if( is_null( $this->mRevision ) ) {
829 // FIXME: This would be a nice place to load the 'no such page' text.
830 } else {
831 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
832 if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
833 if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
834 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
835 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
836 wfProfileOut( __METHOD__ );
837 return;
838 } else {
839 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
840 // and we are allowed to see...
846 $wgOut->setRevisionId( $this->getRevIdFetched() );
848 // Pages containing custom CSS or JavaScript get special treatment
849 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
850 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
851 // Give hooks a chance to customise the output
852 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
853 // Wrap the whole lot in a <pre> and don't parse
854 $m = array();
855 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
856 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
857 $wgOut->addHtml( htmlspecialchars( $this->mContent ) );
858 $wgOut->addHtml( "\n</pre>\n" );
860 } else if ( $rt = Title::newFromRedirect( $text ) ) {
861 # Don't append the subtitle if this was an old revision
862 $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() );
863 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
864 $wgOut->addParserOutputNoText( $parseout );
865 } else if ( $pcache ) {
866 # Display content and save to parser cache
867 $this->outputWikiText( $text );
868 } else {
869 # Display content, don't attempt to save to parser cache
870 # Don't show section-edit links on old revisions... this way lies madness.
871 if( !$this->isCurrent() ) {
872 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
874 # Display content and don't save to parser cache
875 # With timing hack -- TS 2006-07-26
876 $time = -wfTime();
877 $this->outputWikiText( $text, false );
878 $time += wfTime();
880 # Timing hack
881 if ( $time > 3 ) {
882 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
883 $this->mTitle->getPrefixedDBkey()));
886 if( !$this->isCurrent() ) {
887 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
891 /* title may have been set from the cache */
892 $t = $wgOut->getPageTitle();
893 if( empty( $t ) ) {
894 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
897 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
898 if( $ns == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
899 $wgOut->addWikiMsg('anontalkpagetext');
902 # If we have been passed an &rcid= parameter, we want to give the user a
903 # chance to mark this new article as patrolled.
904 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle->exists() ) {
905 $wgOut->addHTML(
906 "<div class='patrollink'>" .
907 wfMsgHtml( 'markaspatrolledlink',
908 $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
909 "action=markpatrolled&rcid=$rcid" )
911 '</div>'
915 # Trackbacks
916 if ($wgUseTrackbacks)
917 $this->addTrackbacks();
919 $this->viewUpdates();
920 wfProfileOut( __METHOD__ );
924 * Should the parser cache be used?
926 protected function useParserCache( $oldid ) {
927 global $wgUser, $wgEnableParserCache;
929 return $wgEnableParserCache
930 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
931 && $this->exists()
932 && empty( $oldid )
933 && !$this->mTitle->isCssOrJsPage()
934 && !$this->mTitle->isCssJsSubpage();
937 protected function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
938 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
940 # Display redirect
941 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
942 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
944 if( $appendSubtitle ) {
945 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
947 $sk = $wgUser->getSkin();
948 if ( $forceKnown )
949 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
950 else
951 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
953 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
954 '<span class="redirectText">'.$link.'</span>' );
958 function addTrackbacks() {
959 global $wgOut, $wgUser;
961 $dbr = wfGetDB(DB_SLAVE);
962 $tbs = $dbr->select(
963 /* FROM */ 'trackbacks',
964 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
965 /* WHERE */ array('tb_page' => $this->getID())
968 if (!$dbr->numrows($tbs))
969 return;
971 $tbtext = "";
972 while ($o = $dbr->fetchObject($tbs)) {
973 $rmvtxt = "";
974 if ($wgUser->isAllowed( 'trackback' )) {
975 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
976 . $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
977 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
979 $tbtext .= "\n";
980 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
981 $o->tb_title,
982 $o->tb_url,
983 $o->tb_ex,
984 $o->tb_name,
985 $rmvtxt);
987 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
990 function deletetrackback() {
991 global $wgUser, $wgRequest, $wgOut, $wgTitle;
993 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
994 $wgOut->addWikiMsg( 'sessionfailure' );
995 return;
998 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1000 if (count($permission_errors)>0)
1002 $wgOut->showPermissionsErrorPage( $permission_errors );
1003 return;
1006 $db = wfGetDB(DB_MASTER);
1007 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1008 $wgTitle->invalidateCache();
1009 $wgOut->addWikiMsg('trackbackdeleteok');
1012 function render() {
1013 global $wgOut;
1015 $wgOut->setArticleBodyOnly(true);
1016 $this->view();
1020 * Handle action=purge
1022 function purge() {
1023 global $wgUser, $wgRequest, $wgOut;
1025 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1026 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1027 $this->doPurge();
1029 } else {
1030 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1031 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1032 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1033 $msg = str_replace( '$1',
1034 "<form method=\"post\" action=\"$action\">\n" .
1035 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1036 "</form>\n", $msg );
1038 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1039 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1040 $wgOut->addHTML( $msg );
1045 * Perform the actions of a page purging
1047 function doPurge() {
1048 global $wgUseSquid;
1049 // Invalidate the cache
1050 $this->mTitle->invalidateCache();
1052 if ( $wgUseSquid ) {
1053 // Commit the transaction before the purge is sent
1054 $dbw = wfGetDB( DB_MASTER );
1055 $dbw->immediateCommit();
1057 // Send purge
1058 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1059 $update->doUpdate();
1061 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1062 global $wgMessageCache;
1063 if ( $this->getID() == 0 ) {
1064 $text = false;
1065 } else {
1066 $text = $this->getContent();
1068 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1070 $this->view();
1074 * Insert a new empty page record for this article.
1075 * This *must* be followed up by creating a revision
1076 * and running $this->updateToLatest( $rev_id );
1077 * or else the record will be left in a funky state.
1078 * Best if all done inside a transaction.
1080 * @param Database $dbw
1081 * @return int The newly created page_id key
1082 * @private
1084 function insertOn( $dbw ) {
1085 wfProfileIn( __METHOD__ );
1087 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1088 $dbw->insert( 'page', array(
1089 'page_id' => $page_id,
1090 'page_namespace' => $this->mTitle->getNamespace(),
1091 'page_title' => $this->mTitle->getDBkey(),
1092 'page_counter' => 0,
1093 'page_restrictions' => '',
1094 'page_is_redirect' => 0, # Will set this shortly...
1095 'page_is_new' => 1,
1096 'page_random' => wfRandom(),
1097 'page_touched' => $dbw->timestamp(),
1098 'page_latest' => 0, # Fill this in shortly...
1099 'page_len' => 0, # Fill this in shortly...
1100 ), __METHOD__ );
1101 $newid = $dbw->insertId();
1103 $this->mTitle->resetArticleId( $newid );
1105 wfProfileOut( __METHOD__ );
1106 return $newid;
1110 * Update the page record to point to a newly saved revision.
1112 * @param Database $dbw
1113 * @param Revision $revision For ID number, and text used to set
1114 length and redirect status fields
1115 * @param int $lastRevision If given, will not overwrite the page field
1116 * when different from the currently set value.
1117 * Giving 0 indicates the new page flag should
1118 * be set on.
1119 * @param bool $lastRevIsRedirect If given, will optimize adding and
1120 * removing rows in redirect table.
1121 * @return bool true on success, false on failure
1122 * @private
1124 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1125 wfProfileIn( __METHOD__ );
1127 $text = $revision->getText();
1128 $rt = Title::newFromRedirect( $text );
1130 $conditions = array( 'page_id' => $this->getId() );
1131 if( !is_null( $lastRevision ) ) {
1132 # An extra check against threads stepping on each other
1133 $conditions['page_latest'] = $lastRevision;
1136 $dbw->update( 'page',
1137 array( /* SET */
1138 'page_latest' => $revision->getId(),
1139 'page_touched' => $dbw->timestamp(),
1140 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1141 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1142 'page_len' => strlen( $text ),
1144 $conditions,
1145 __METHOD__ );
1147 $result = $dbw->affectedRows() != 0;
1149 if ($result) {
1150 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1153 wfProfileOut( __METHOD__ );
1154 return $result;
1158 * Add row to the redirect table if this is a redirect, remove otherwise.
1160 * @param Database $dbw
1161 * @param $redirectTitle a title object pointing to the redirect target,
1162 * or NULL if this is not a redirect
1163 * @param bool $lastRevIsRedirect If given, will optimize adding and
1164 * removing rows in redirect table.
1165 * @return bool true on success, false on failure
1166 * @private
1168 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1170 // Always update redirects (target link might have changed)
1171 // Update/Insert if we don't know if the last revision was a redirect or not
1172 // Delete if changing from redirect to non-redirect
1173 $isRedirect = !is_null($redirectTitle);
1174 if ($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1176 wfProfileIn( __METHOD__ );
1178 if ($isRedirect) {
1180 // This title is a redirect, Add/Update row in the redirect table
1181 $set = array( /* SET */
1182 'rd_namespace' => $redirectTitle->getNamespace(),
1183 'rd_title' => $redirectTitle->getDBkey(),
1184 'rd_from' => $this->getId(),
1187 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1188 } else {
1189 // This is not a redirect, remove row from redirect table
1190 $where = array( 'rd_from' => $this->getId() );
1191 $dbw->delete( 'redirect', $where, __METHOD__);
1194 if( $this->getTitle()->getNamespace() == NS_IMAGE )
1195 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1196 wfProfileOut( __METHOD__ );
1197 return ( $dbw->affectedRows() != 0 );
1200 return true;
1204 * If the given revision is newer than the currently set page_latest,
1205 * update the page record. Otherwise, do nothing.
1207 * @param Database $dbw
1208 * @param Revision $revision
1210 function updateIfNewerOn( &$dbw, $revision ) {
1211 wfProfileIn( __METHOD__ );
1213 $row = $dbw->selectRow(
1214 array( 'revision', 'page' ),
1215 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1216 array(
1217 'page_id' => $this->getId(),
1218 'page_latest=rev_id' ),
1219 __METHOD__ );
1220 if( $row ) {
1221 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1222 wfProfileOut( __METHOD__ );
1223 return false;
1225 $prev = $row->rev_id;
1226 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1227 } else {
1228 # No or missing previous revision; mark the page as new
1229 $prev = 0;
1230 $lastRevIsRedirect = null;
1233 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1234 wfProfileOut( __METHOD__ );
1235 return $ret;
1239 * @return string Complete article text, or null if error
1241 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1242 wfProfileIn( __METHOD__ );
1244 if( $section == '' ) {
1245 // Whole-page edit; let the text through unmolested.
1246 } else {
1247 if( is_null( $edittime ) ) {
1248 $rev = Revision::newFromTitle( $this->mTitle );
1249 } else {
1250 $dbw = wfGetDB( DB_MASTER );
1251 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1253 if( is_null( $rev ) ) {
1254 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1255 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1256 return null;
1258 $oldtext = $rev->getText();
1260 if( $section == 'new' ) {
1261 # Inserting a new section
1262 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1263 $text = strlen( trim( $oldtext ) ) > 0
1264 ? "{$oldtext}\n\n{$subject}{$text}"
1265 : "{$subject}{$text}";
1266 } else {
1267 # Replacing an existing section; roll out the big guns
1268 global $wgParser;
1269 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1274 wfProfileOut( __METHOD__ );
1275 return $text;
1279 * @deprecated use Article::doEdit()
1281 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1282 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1283 ( $isminor ? EDIT_MINOR : 0 ) |
1284 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1285 ( $bot ? EDIT_FORCE_BOT : 0 );
1287 # If this is a comment, add the summary as headline
1288 if ( $comment && $summary != "" ) {
1289 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1292 $this->doEdit( $text, $summary, $flags );
1294 $dbw = wfGetDB( DB_MASTER );
1295 if ($watchthis) {
1296 if (!$this->mTitle->userIsWatching()) {
1297 $dbw->begin();
1298 $this->doWatch();
1299 $dbw->commit();
1301 } else {
1302 if ( $this->mTitle->userIsWatching() ) {
1303 $dbw->begin();
1304 $this->doUnwatch();
1305 $dbw->commit();
1308 $this->doRedirect( $this->isRedirect( $text ) );
1312 * @deprecated use Article::doEdit()
1314 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1315 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1316 ( $minor ? EDIT_MINOR : 0 ) |
1317 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1319 $good = $this->doEdit( $text, $summary, $flags );
1320 if ( $good ) {
1321 $dbw = wfGetDB( DB_MASTER );
1322 if ($watchthis) {
1323 if (!$this->mTitle->userIsWatching()) {
1324 $dbw->begin();
1325 $this->doWatch();
1326 $dbw->commit();
1328 } else {
1329 if ( $this->mTitle->userIsWatching() ) {
1330 $dbw->begin();
1331 $this->doUnwatch();
1332 $dbw->commit();
1336 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1337 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1339 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1341 return $good;
1345 * Article::doEdit()
1347 * Change an existing article or create a new article. Updates RC and all necessary caches,
1348 * optionally via the deferred update array.
1350 * $wgUser must be set before calling this function.
1352 * @param string $text New text
1353 * @param string $summary Edit summary
1354 * @param integer $flags bitfield:
1355 * EDIT_NEW
1356 * Article is known or assumed to be non-existent, create a new one
1357 * EDIT_UPDATE
1358 * Article is known or assumed to be pre-existing, update it
1359 * EDIT_MINOR
1360 * Mark this edit minor, if the user is allowed to do so
1361 * EDIT_SUPPRESS_RC
1362 * Do not log the change in recentchanges
1363 * EDIT_FORCE_BOT
1364 * Mark the edit a "bot" edit regardless of user rights
1365 * EDIT_DEFER_UPDATES
1366 * Defer some of the updates until the end of index.php
1367 * EDIT_AUTOSUMMARY
1368 * Fill in blank summaries with generated text where possible
1370 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1371 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1372 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1373 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1374 * to MediaWiki's performance-optimised locking strategy.
1375 * @param $baseRevId, the revision ID this edit was based off, if any
1377 * @return bool success
1379 function doEdit( $text, $summary, $flags = 0, $baseRevId = false ) {
1380 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1382 wfProfileIn( __METHOD__ );
1383 $good = true;
1385 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1386 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1387 if ( $aid ) {
1388 $flags |= EDIT_UPDATE;
1389 } else {
1390 $flags |= EDIT_NEW;
1394 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1395 &$summary, $flags & EDIT_MINOR,
1396 null, null, &$flags ) ) )
1398 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1399 wfProfileOut( __METHOD__ );
1400 return false;
1403 # Silently ignore EDIT_MINOR if not allowed
1404 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1405 $bot = $flags & EDIT_FORCE_BOT;
1407 $oldtext = $this->getContent();
1408 $oldsize = strlen( $oldtext );
1410 # Provide autosummaries if one is not provided and autosummaries are enabled.
1411 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1412 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1415 $editInfo = $this->prepareTextForEdit( $text );
1416 $text = $editInfo->pst;
1417 $newsize = strlen( $text );
1419 $dbw = wfGetDB( DB_MASTER );
1420 $now = wfTimestampNow();
1422 if ( $flags & EDIT_UPDATE ) {
1423 # Update article, but only if changed.
1425 # Make sure the revision is either completely inserted or not inserted at all
1426 if( !$wgDBtransactions ) {
1427 $userAbort = ignore_user_abort( true );
1430 $lastRevision = 0;
1431 $revisionId = 0;
1433 $changed = ( strcmp( $text, $oldtext ) != 0 );
1435 if ( $changed ) {
1436 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1437 - (int)$this->isCountable( $oldtext );
1438 $this->mTotalAdjustment = 0;
1440 $lastRevision = $dbw->selectField(
1441 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1443 if ( !$lastRevision ) {
1444 # Article gone missing
1445 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1446 wfProfileOut( __METHOD__ );
1447 return false;
1450 $revision = new Revision( array(
1451 'page' => $this->getId(),
1452 'comment' => $summary,
1453 'minor_edit' => $isminor,
1454 'text' => $text,
1455 'parent_id' => $lastRevision
1456 ) );
1458 $dbw->begin();
1459 $revisionId = $revision->insertOn( $dbw );
1461 # Update page
1462 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1464 if( !$ok ) {
1465 /* Belated edit conflict! Run away!! */
1466 $good = false;
1467 $dbw->rollback();
1468 } else {
1469 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
1471 # Update recentchanges
1472 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1473 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1474 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1475 $revisionId );
1477 # Mark as patrolled if the user can do so
1478 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1479 RecentChange::markPatrolled( $rcid );
1480 PatrolLog::record( $rcid, true );
1483 $wgUser->incEditCount();
1484 $dbw->commit();
1486 } else {
1487 $revision = null;
1488 // Keep the same revision ID, but do some updates on it
1489 $revisionId = $this->getRevIdFetched();
1490 // Update page_touched, this is usually implicit in the page update
1491 // Other cache updates are done in onArticleEdit()
1492 $this->mTitle->invalidateCache();
1495 if( !$wgDBtransactions ) {
1496 ignore_user_abort( $userAbort );
1499 if ( $good ) {
1500 # Invalidate cache of this article and all pages using this article
1501 # as a template. Partly deferred.
1502 Article::onArticleEdit( $this->mTitle );
1504 # Update links tables, site stats, etc.
1505 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1507 } else {
1508 # Create new article
1510 # Set statistics members
1511 # We work out if it's countable after PST to avoid counter drift
1512 # when articles are created with {{subst:}}
1513 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1514 $this->mTotalAdjustment = 1;
1516 $dbw->begin();
1518 # Add the page record; stake our claim on this title!
1519 # This will fail with a database query exception if the article already exists
1520 $newid = $this->insertOn( $dbw );
1522 # Save the revision text...
1523 $revision = new Revision( array(
1524 'page' => $newid,
1525 'comment' => $summary,
1526 'minor_edit' => $isminor,
1527 'text' => $text
1528 ) );
1529 $revisionId = $revision->insertOn( $dbw );
1531 $this->mTitle->resetArticleID( $newid );
1533 # Update the page record with revision data
1534 $this->updateRevisionOn( $dbw, $revision, 0 );
1536 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1538 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1539 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1540 '', strlen( $text ), $revisionId );
1541 # Mark as patrolled if the user can
1542 if( ($GLOBALS['wgUseRCPatrol'] || $GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1543 RecentChange::markPatrolled( $rcid );
1544 PatrolLog::record( $rcid, true );
1547 $wgUser->incEditCount();
1548 $dbw->commit();
1550 # Update links, etc.
1551 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1553 # Clear caches
1554 Article::onArticleCreate( $this->mTitle );
1556 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1557 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1560 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1561 wfDoUpdates();
1564 if ( $good ) {
1565 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1566 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1569 wfProfileOut( __METHOD__ );
1570 return $good;
1574 * @deprecated wrapper for doRedirect
1576 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1577 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1581 * Output a redirect back to the article.
1582 * This is typically used after an edit.
1584 * @param boolean $noRedir Add redirect=no
1585 * @param string $sectionAnchor section to redirect to, including "#"
1586 * @param string $extraQuery, extra query params
1588 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1589 global $wgOut;
1590 if ( $noRedir ) {
1591 $query = 'redirect=no';
1592 if( $extraQuery )
1593 $query .= "&$query";
1594 } else {
1595 $query = $extraQuery;
1597 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1601 * Mark this particular edit/page as patrolled
1603 function markpatrolled() {
1604 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1605 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1607 # Check patrol config options
1609 if ( !($wgUseNPPatrol || $wgUseRCPatrol)) {
1610 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1611 return;
1614 # If we haven't been given an rc_id value, we can't do anything
1615 $rcid = (int) $wgRequest->getVal('rcid');
1616 $rc = $rcid ? RecentChange::newFromId($rcid) : null;
1617 if ( is_null ( $rc ) )
1619 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1620 return;
1623 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW) {
1624 // Only new pages can be patrolled if the general patrolling is off....???
1625 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1626 // front end here?
1627 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1628 return;
1631 # Check permissions
1632 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'patrol', $wgUser );
1634 if (count($permission_errors)>0)
1636 $wgOut->showPermissionsErrorPage( $permission_errors );
1637 return;
1640 # Handle the 'MarkPatrolled' hook
1641 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1642 return;
1645 #It would be nice to see where the user had actually come from, but for now just guess
1646 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1647 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1649 # If it's left up to us, check that the user is allowed to patrol this edit
1650 # If the user has the "autopatrol" right, then we'll assume there are no
1651 # other conditions stopping them doing so
1652 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1653 $rc = RecentChange::newFromId( $rcid );
1654 # Graceful error handling, as we've done before here...
1655 # (If the recent change doesn't exist, then it doesn't matter whether
1656 # the user is allowed to patrol it or not; nothing is going to happen
1657 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1658 # The user made this edit, and can't patrol it
1659 # Tell them so, and then back off
1660 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1661 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1662 $wgOut->returnToMain( false, $return );
1663 return;
1667 # Check that the revision isn't patrolled already
1668 # Prevents duplicate log entries
1669 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1670 # Mark the edit as patrolled
1671 RecentChange::markPatrolled( $rcid );
1672 PatrolLog::record( $rcid );
1673 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1676 # Inform the user
1677 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1678 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1679 $wgOut->returnToMain( false, $return );
1683 * User-interface handler for the "watch" action
1686 function watch() {
1688 global $wgUser, $wgOut;
1690 if ( $wgUser->isAnon() ) {
1691 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1692 return;
1694 if ( wfReadOnly() ) {
1695 $wgOut->readOnlyPage();
1696 return;
1699 if( $this->doWatch() ) {
1700 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1701 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1703 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1706 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1710 * Add this page to $wgUser's watchlist
1711 * @return bool true on successful watch operation
1713 function doWatch() {
1714 global $wgUser;
1715 if( $wgUser->isAnon() ) {
1716 return false;
1719 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1720 $wgUser->addWatch( $this->mTitle );
1722 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1725 return false;
1729 * User interface handler for the "unwatch" action.
1731 function unwatch() {
1733 global $wgUser, $wgOut;
1735 if ( $wgUser->isAnon() ) {
1736 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1737 return;
1739 if ( wfReadOnly() ) {
1740 $wgOut->readOnlyPage();
1741 return;
1744 if( $this->doUnwatch() ) {
1745 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1746 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1748 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1751 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1755 * Stop watching a page
1756 * @return bool true on successful unwatch
1758 function doUnwatch() {
1759 global $wgUser;
1760 if( $wgUser->isAnon() ) {
1761 return false;
1764 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1765 $wgUser->removeWatch( $this->mTitle );
1767 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1770 return false;
1774 * action=protect handler
1776 function protect() {
1777 $form = new ProtectionForm( $this );
1778 $form->execute();
1782 * action=unprotect handler (alias)
1784 function unprotect() {
1785 $this->protect();
1789 * Update the article's restriction field, and leave a log entry.
1791 * @param array $limit set of restriction keys
1792 * @param string $reason
1793 * @return bool true on success
1795 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1796 global $wgUser, $wgRestrictionTypes, $wgContLang;
1798 $id = $this->mTitle->getArticleID();
1799 if( array() != $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser ) || wfReadOnly() || $id == 0 ) {
1800 return false;
1803 if (!$cascade) {
1804 $cascade = false;
1807 // Take this opportunity to purge out expired restrictions
1808 Title::purgeExpiredRestrictions();
1810 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1811 # we expect a single selection, but the schema allows otherwise.
1812 $current = array();
1813 foreach( $wgRestrictionTypes as $action )
1814 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1816 $current = Article::flattenRestrictions( $current );
1817 $updated = Article::flattenRestrictions( $limit );
1819 $changed = ( $current != $updated );
1820 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
1821 $changed = $changed || ($updated && $this->mTitle->mRestrictionsExpiry != $expiry);
1822 $protect = ( $updated != '' );
1824 # If nothing's changed, do nothing
1825 if( $changed ) {
1826 global $wgGroupPermissions;
1827 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1829 $dbw = wfGetDB( DB_MASTER );
1831 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1833 $expiry_description = '';
1834 if ( $encodedExpiry != 'infinity' ) {
1835 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1838 # Prepare a null revision to be added to the history
1839 $modified = $current != '' && $protect;
1840 if ( $protect ) {
1841 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1842 } else {
1843 $comment_type = 'unprotectedarticle';
1845 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1847 # Only restrictions with the 'protect' right can cascade...
1848 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1849 foreach( $limit as $action => $restriction ) {
1850 # FIXME: can $restriction be an array or what? (same as fixme above)
1851 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1852 $cascade = false;
1853 break;
1857 $cascade_description = '';
1858 if ($cascade) {
1859 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1862 if( $reason )
1863 $comment .= ": $reason";
1864 if( $protect )
1865 $comment .= " [$updated]";
1866 if ( $expiry_description && $protect )
1867 $comment .= "$expiry_description";
1868 if ( $cascade )
1869 $comment .= "$cascade_description";
1871 # Update restrictions table
1872 foreach( $limit as $action => $restrictions ) {
1873 if ($restrictions != '' ) {
1874 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1875 array( 'pr_page' => $id, 'pr_type' => $action
1876 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
1877 , 'pr_expiry' => $encodedExpiry ), __METHOD__ );
1878 } else {
1879 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1880 'pr_type' => $action ), __METHOD__ );
1884 # Insert a null revision
1885 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1886 $nullRevId = $nullRevision->insertOn( $dbw );
1888 # Update page record
1889 $dbw->update( 'page',
1890 array( /* SET */
1891 'page_touched' => $dbw->timestamp(),
1892 'page_restrictions' => '',
1893 'page_latest' => $nullRevId
1894 ), array( /* WHERE */
1895 'page_id' => $id
1896 ), 'Article::protect'
1899 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, false) );
1900 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1902 # Update the protection log
1903 $log = new LogPage( 'protect' );
1904 if( $protect ) {
1905 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle,
1906 trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1907 } else {
1908 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1911 } # End hook
1912 } # End "changed" check
1914 return true;
1918 * Take an array of page restrictions and flatten it to a string
1919 * suitable for insertion into the page_restrictions field.
1920 * @param array $limit
1921 * @return string
1922 * @private
1924 function flattenRestrictions( $limit ) {
1925 if( !is_array( $limit ) ) {
1926 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1928 $bits = array();
1929 ksort( $limit );
1930 foreach( $limit as $action => $restrictions ) {
1931 if( $restrictions != '' ) {
1932 $bits[] = "$action=$restrictions";
1935 return implode( ':', $bits );
1939 * Auto-generates a deletion reason
1940 * @param bool &$hasHistory Whether the page has a history
1942 public function generateReason(&$hasHistory)
1944 global $wgContLang;
1945 $dbw = wfGetDB(DB_MASTER);
1946 // Get the last revision
1947 $rev = Revision::newFromTitle($this->mTitle);
1948 if(is_null($rev))
1949 return false;
1950 // Get the article's contents
1951 $contents = $rev->getText();
1952 $blank = false;
1953 // If the page is blank, use the text from the previous revision,
1954 // which can only be blank if there's a move/import/protect dummy revision involved
1955 if($contents == '')
1957 $prev = $rev->getPrevious();
1958 if($prev)
1960 $contents = $prev->getText();
1961 $blank = true;
1965 // Find out if there was only one contributor
1966 // Only scan the last 20 revisions
1967 $limit = 20;
1968 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__,
1969 array('LIMIT' => $limit));
1970 if($res === false)
1971 // This page has no revisions, which is very weird
1972 return false;
1973 if($res->numRows() > 1)
1974 $hasHistory = true;
1975 else
1976 $hasHistory = false;
1977 $row = $dbw->fetchObject($res);
1978 $onlyAuthor = $row->rev_user_text;
1979 // Try to find a second contributor
1980 while( $row = $dbw->fetchObject($res) ) {
1981 if($row->rev_user_text != $onlyAuthor) {
1982 $onlyAuthor = false;
1983 break;
1986 $dbw->freeResult($res);
1988 // Generate the summary with a '$1' placeholder
1989 if($blank) {
1990 // The current revision is blank and the one before is also
1991 // blank. It's just not our lucky day
1992 $reason = wfMsgForContent('exbeforeblank', '$1');
1993 } else {
1994 if($onlyAuthor)
1995 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1996 else
1997 $reason = wfMsgForContent('excontent', '$1');
2000 // Replace newlines with spaces to prevent uglyness
2001 $contents = preg_replace("/[\n\r]/", ' ', $contents);
2002 // Calculate the maximum amount of chars to get
2003 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2004 $maxLength = 255 - (strlen($reason) - 2) - 3;
2005 $contents = $wgContLang->truncate($contents, $maxLength, '...');
2006 // Remove possible unfinished links
2007 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2008 // Now replace the '$1' placeholder
2009 $reason = str_replace( '$1', $contents, $reason );
2010 return $reason;
2015 * UI entry point for page deletion
2017 function delete() {
2018 global $wgUser, $wgOut, $wgRequest;
2020 $confirm = $wgRequest->wasPosted() &&
2021 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2023 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2024 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2026 $reason = $this->DeleteReasonList;
2028 if ( $reason != 'other' && $this->DeleteReason != '') {
2029 // Entry from drop down menu + additional comment
2030 $reason .= ': ' . $this->DeleteReason;
2031 } elseif ( $reason == 'other' ) {
2032 $reason = $this->DeleteReason;
2034 # Flag to hide all contents of the archived revisions
2035 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2037 # This code desperately needs to be totally rewritten
2039 # Read-only check...
2040 if ( wfReadOnly() ) {
2041 $wgOut->readOnlyPage();
2042 return;
2045 # Check permissions
2046 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2048 if (count($permission_errors)>0) {
2049 $wgOut->showPermissionsErrorPage( $permission_errors );
2050 return;
2053 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2055 # Better double-check that it hasn't been deleted yet!
2056 $dbw = wfGetDB( DB_MASTER );
2057 $conds = $this->mTitle->pageCond();
2058 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2059 if ( $latest === false ) {
2060 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2061 return;
2064 # Hack for big sites
2065 $bigHistory = $this->isBigDeletion();
2066 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2067 global $wgLang, $wgDeleteRevisionsLimit;
2068 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2069 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2070 return;
2073 if( $confirm ) {
2074 $this->doDelete( $reason, $suppress );
2075 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2076 $this->doWatch();
2077 } elseif( $this->mTitle->userIsWatching() ) {
2078 $this->doUnwatch();
2080 return;
2083 // Generate deletion reason
2084 $hasHistory = false;
2085 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2087 // If the page has a history, insert a warning
2088 if( $hasHistory && !$confirm ) {
2089 $skin=$wgUser->getSkin();
2090 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2091 if( $bigHistory ) {
2092 global $wgLang, $wgDeleteRevisionsLimit;
2093 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2094 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2098 return $this->confirmDelete( $reason );
2102 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2104 function isBigDeletion() {
2105 global $wgDeleteRevisionsLimit;
2106 if( $wgDeleteRevisionsLimit ) {
2107 $revCount = $this->estimateRevisionCount();
2108 return $revCount > $wgDeleteRevisionsLimit;
2110 return false;
2114 * @return int approximate revision count
2116 function estimateRevisionCount() {
2117 $dbr = wfGetDB();
2118 // For an exact count...
2119 //return $dbr->selectField( 'revision', 'COUNT(*)',
2120 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2121 return $dbr->estimateRowCount( 'revision', '*',
2122 array( 'rev_page' => $this->getId() ), __METHOD__ );
2126 * Get the last N authors
2127 * @param int $num Number of revisions to get
2128 * @param string $revLatest The latest rev_id, selected from the master (optional)
2129 * @return array Array of authors, duplicates not removed
2131 function getLastNAuthors( $num, $revLatest = 0 ) {
2132 wfProfileIn( __METHOD__ );
2134 // First try the slave
2135 // If that doesn't have the latest revision, try the master
2136 $continue = 2;
2137 $db = wfGetDB( DB_SLAVE );
2138 do {
2139 $res = $db->select( array( 'page', 'revision' ),
2140 array( 'rev_id', 'rev_user_text' ),
2141 array(
2142 'page_namespace' => $this->mTitle->getNamespace(),
2143 'page_title' => $this->mTitle->getDBkey(),
2144 'rev_page = page_id'
2145 ), __METHOD__, $this->getSelectOptions( array(
2146 'ORDER BY' => 'rev_timestamp DESC',
2147 'LIMIT' => $num
2150 if ( !$res ) {
2151 wfProfileOut( __METHOD__ );
2152 return array();
2154 $row = $db->fetchObject( $res );
2155 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2156 $db = wfGetDB( DB_MASTER );
2157 $continue--;
2158 } else {
2159 $continue = 0;
2161 } while ( $continue );
2163 $authors = array( $row->rev_user_text );
2164 while ( $row = $db->fetchObject( $res ) ) {
2165 $authors[] = $row->rev_user_text;
2167 wfProfileOut( __METHOD__ );
2168 return $authors;
2172 * Output deletion confirmation dialog
2173 * @param $reason string Prefilled reason
2175 function confirmDelete( $reason ) {
2176 global $wgOut, $wgUser, $wgContLang;
2177 $align = $wgContLang->isRtl() ? 'left' : 'right';
2179 wfDebug( "Article::confirmDelete\n" );
2181 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2182 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2183 $wgOut->addWikiMsg( 'confirmdeletetext' );
2185 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2186 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2187 $suppress .= Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2188 $suppress .= "</td></tr>";
2189 } else {
2190 $suppress = '';
2193 $form = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2194 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2195 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2196 Xml::openElement( 'table' ) .
2197 "<tr id=\"wpDeleteReasonListRow\">
2198 <td align='$align'>" .
2199 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2200 "</td>
2201 <td>" .
2202 Xml::listDropDown( 'wpDeleteReasonList',
2203 wfMsgForContent( 'deletereason-dropdown' ),
2204 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2205 "</td>
2206 </tr>
2207 <tr id=\"wpDeleteReasonRow\">
2208 <td align='$align'>" .
2209 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2210 "</td>
2211 <td>" .
2212 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2213 "</td>
2214 </tr>
2215 <tr>
2216 <td></td>
2217 <td>" .
2218 Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '3' ) ) .
2219 "</td>
2220 </tr>
2221 $suppress
2222 <tr>
2223 <td></td>
2224 <td>" .
2225 Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2226 "</td>
2227 </tr>" .
2228 Xml::closeElement( 'table' ) .
2229 Xml::closeElement( 'fieldset' ) .
2230 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2231 Xml::closeElement( 'form' );
2233 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2234 $skin = $wgUser->getSkin();
2235 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2236 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2239 $wgOut->addHTML( $form );
2240 $this->showLogExtract( $wgOut );
2245 * Show relevant lines from the deletion log
2247 function showLogExtract( $out ) {
2248 $out->addHtml( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2249 LogEventsList::showLogExtract( $out, 'delete', $this->mTitle->getPrefixedText() );
2254 * Perform a deletion and output success or failure messages
2256 function doDelete( $reason, $suppress = false ) {
2257 global $wgOut, $wgUser;
2258 wfDebug( __METHOD__."\n" );
2260 $id = $this->getId();
2262 $error = '';
2264 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error))) {
2265 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2266 $deleted = $this->mTitle->getPrefixedText();
2268 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2269 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2271 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2273 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2274 $wgOut->returnToMain( false );
2275 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2276 } else {
2277 if ($error = '')
2278 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2279 else
2280 $wgOut->showFatalError( $error );
2286 * Back-end article deletion
2287 * Deletes the article with database consistency, writes logs, purges caches
2288 * Returns success
2290 function doDeleteArticle( $reason, $suppress = false ) {
2291 global $wgUseSquid, $wgDeferredUpdateList;
2292 global $wgUseTrackbacks;
2294 wfDebug( __METHOD__."\n" );
2296 $dbw = wfGetDB( DB_MASTER );
2297 $ns = $this->mTitle->getNamespace();
2298 $t = $this->mTitle->getDBkey();
2299 $id = $this->mTitle->getArticleID();
2301 if ( $t == '' || $id == 0 ) {
2302 return false;
2305 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2306 array_push( $wgDeferredUpdateList, $u );
2308 // Bitfields to further suppress the content
2309 if ( $suppress ) {
2310 $bitfield = 0;
2311 // This should be 15...
2312 $bitfield |= Revision::DELETED_TEXT;
2313 $bitfield |= Revision::DELETED_COMMENT;
2314 $bitfield |= Revision::DELETED_USER;
2315 $bitfield |= Revision::DELETED_RESTRICTED;
2316 } else {
2317 $bitfield = 'rev_deleted';
2320 $dbw->begin();
2321 // For now, shunt the revision data into the archive table.
2322 // Text is *not* removed from the text table; bulk storage
2323 // is left intact to avoid breaking block-compression or
2324 // immutable storage schemes.
2326 // For backwards compatibility, note that some older archive
2327 // table entries will have ar_text and ar_flags fields still.
2329 // In the future, we may keep revisions and mark them with
2330 // the rev_deleted field, which is reserved for this purpose.
2331 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2332 array(
2333 'ar_namespace' => 'page_namespace',
2334 'ar_title' => 'page_title',
2335 'ar_comment' => 'rev_comment',
2336 'ar_user' => 'rev_user',
2337 'ar_user_text' => 'rev_user_text',
2338 'ar_timestamp' => 'rev_timestamp',
2339 'ar_minor_edit' => 'rev_minor_edit',
2340 'ar_rev_id' => 'rev_id',
2341 'ar_text_id' => 'rev_text_id',
2342 'ar_text' => '\'\'', // Be explicit to appease
2343 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2344 'ar_len' => 'rev_len',
2345 'ar_page_id' => 'page_id',
2346 'ar_deleted' => $bitfield
2347 ), array(
2348 'page_id' => $id,
2349 'page_id = rev_page'
2350 ), __METHOD__
2353 # Delete restrictions for it
2354 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2356 # Fix category table counts
2357 $cats = array();
2358 $res = $dbw->select( 'categorylinks', 'cl_to',
2359 array( 'cl_from' => $id ), __METHOD__ );
2360 foreach( $res as $row ) {
2361 $cats []= $row->cl_to;
2363 $this->updateCategoryCounts( array(), $cats );
2365 # Now that it's safely backed up, delete it
2366 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2367 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2368 if( !$ok ) {
2369 $dbw->rollback();
2370 return false;
2373 # If using cascading deletes, we can skip some explicit deletes
2374 if ( !$dbw->cascadingDeletes() ) {
2375 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2377 if ($wgUseTrackbacks)
2378 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2380 # Delete outgoing links
2381 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2382 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2383 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2384 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2385 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2386 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2387 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2390 # If using cleanup triggers, we can skip some manual deletes
2391 if ( !$dbw->cleanupTriggers() ) {
2393 # Clean up recentchanges entries...
2394 $dbw->delete( 'recentchanges',
2395 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG ),
2396 __METHOD__ );
2398 $dbw->commit();
2400 # Clear caches
2401 Article::onArticleDelete( $this->mTitle );
2403 # Clear the cached article id so the interface doesn't act like we exist
2404 $this->mTitle->resetArticleID( 0 );
2405 $this->mTitle->mArticleID = 0;
2407 # Log the deletion, if the page was suppressed, log it at Oversight instead
2408 $logtype = $suppress ? 'suppress' : 'delete';
2409 $log = new LogPage( $logtype );
2411 # Make sure logging got through
2412 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2414 return true;
2418 * Roll back the most recent consecutive set of edits to a page
2419 * from the same user; fails if there are no eligible edits to
2420 * roll back to, e.g. user is the sole contributor. This function
2421 * performs permissions checks on $wgUser, then calls commitRollback()
2422 * to do the dirty work
2424 * @param string $fromP - Name of the user whose edits to rollback.
2425 * @param string $summary - Custom summary. Set to default summary if empty.
2426 * @param string $token - Rollback token.
2427 * @param bool $bot - If true, mark all reverted edits as bot.
2429 * @param array $resultDetails contains result-specific array of additional values
2430 * 'alreadyrolled' : 'current' (rev)
2431 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2433 * @return array of errors, each error formatted as
2434 * array(messagekey, param1, param2, ...).
2435 * On success, the array is empty. This array can also be passed to
2436 * OutputPage::showPermissionsErrorPage().
2438 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2439 global $wgUser;
2440 $resultDetails = null;
2442 # Check permissions
2443 $errors = array_merge( $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ),
2444 $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
2445 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2446 $errors[] = array( 'sessionfailure' );
2448 if ( $wgUser->pingLimiter('rollback') || $wgUser->pingLimiter() ) {
2449 $errors[] = array( 'actionthrottledtext' );
2451 # If there were errors, bail out now
2452 if(!empty($errors))
2453 return $errors;
2455 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2459 * Backend implementation of doRollback(), please refer there for parameter
2460 * and return value documentation
2462 * NOTE: This function does NOT check ANY permissions, it just commits the
2463 * rollback to the DB Therefore, you should only call this function direct-
2464 * ly if you want to use custom permissions checks. If you don't, use
2465 * doRollback() instead.
2467 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2468 global $wgUseRCPatrol, $wgUser, $wgLang;
2469 $dbw = wfGetDB( DB_MASTER );
2471 if( wfReadOnly() ) {
2472 return array( array( 'readonlytext' ) );
2475 # Get the last editor
2476 $current = Revision::newFromTitle( $this->mTitle );
2477 if( is_null( $current ) ) {
2478 # Something wrong... no page?
2479 return array(array('notanarticle'));
2482 $from = str_replace( '_', ' ', $fromP );
2483 if( $from != $current->getUserText() ) {
2484 $resultDetails = array( 'current' => $current );
2485 return array(array('alreadyrolled',
2486 htmlspecialchars($this->mTitle->getPrefixedText()),
2487 htmlspecialchars($fromP),
2488 htmlspecialchars($current->getUserText())
2492 # Get the last edit not by this guy
2493 $user = intval( $current->getUser() );
2494 $user_text = $dbw->addQuotes( $current->getUserText() );
2495 $s = $dbw->selectRow( 'revision',
2496 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2497 array( 'rev_page' => $current->getPage(),
2498 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2499 ), __METHOD__,
2500 array( 'USE INDEX' => 'page_timestamp',
2501 'ORDER BY' => 'rev_timestamp DESC' )
2503 if( $s === false ) {
2504 # No one else ever edited this page
2505 return array(array('cantrollback'));
2506 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2507 # Only admins can see this text
2508 return array(array('notvisiblerev'));
2511 $set = array();
2512 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2513 # Mark all reverted edits as bot
2514 $set['rc_bot'] = 1;
2516 if ( $wgUseRCPatrol ) {
2517 # Mark all reverted edits as patrolled
2518 $set['rc_patrolled'] = 1;
2521 if ( $set ) {
2522 $dbw->update( 'recentchanges', $set,
2523 array( /* WHERE */
2524 'rc_cur_id' => $current->getPage(),
2525 'rc_user_text' => $current->getUserText(),
2526 "rc_timestamp > '{$s->rev_timestamp}'",
2527 ), __METHOD__
2531 # Generate the edit summary if necessary
2532 $target = Revision::newFromId( $s->rev_id );
2533 if( empty( $summary ) ){
2534 $summary = wfMsgForContent( 'revertpage' );
2537 # Allow the custom summary to use the same args as the default message
2538 $args = array(
2539 $target->getUserText(), $from, $s->rev_id,
2540 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2541 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2543 $summary = wfMsgReplaceArgs( $summary, $args );
2545 # Save
2546 $flags = EDIT_UPDATE;
2548 if ($wgUser->isAllowed('minoredit'))
2549 $flags |= EDIT_MINOR;
2551 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2552 $flags |= EDIT_FORCE_BOT;
2553 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2555 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2557 $resultDetails = array(
2558 'summary' => $summary,
2559 'current' => $current,
2560 'target' => $target,
2562 return array();
2566 * User interface for rollback operations
2568 function rollback() {
2569 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2570 $details = null;
2572 $result = $this->doRollback(
2573 $wgRequest->getVal( 'from' ),
2574 $wgRequest->getText( 'summary' ),
2575 $wgRequest->getVal( 'token' ),
2576 $wgRequest->getBool( 'bot' ),
2577 $details
2580 if( in_array( array( 'blocked' ), $result ) ) {
2581 $wgOut->blockedPage();
2582 return;
2584 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2585 $wgOut->rateLimited();
2586 return;
2588 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ){
2589 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2590 $errArray = $result[0];
2591 $errMsg = array_shift( $errArray );
2592 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2593 if( isset( $details['current'] ) ){
2594 $current = $details['current'];
2595 if( $current->getComment() != '' ) {
2596 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2599 return;
2601 # Display permissions errors before read-only message -- there's no
2602 # point in misleading the user into thinking the inability to rollback
2603 # is only temporary.
2604 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2605 # array_diff is completely broken for arrays of arrays, sigh. Re-
2606 # move any 'readonlytext' error manually.
2607 $out = array();
2608 foreach( $result as $error ) {
2609 if( $error != array( 'readonlytext' ) ) {
2610 $out []= $error;
2613 $wgOut->showPermissionsErrorPage( $out );
2614 return;
2616 if( $result == array( array('readonlytext') ) ) {
2617 $wgOut->readOnlyPage();
2618 return;
2621 $current = $details['current'];
2622 $target = $details['target'];
2623 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2624 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2625 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2626 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2627 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2628 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2629 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2630 $wgOut->returnToMain( false, $this->mTitle );
2632 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2633 $de = new DifferenceEngine( $this->mTitle, $current->getId(), 'next', false, true );
2634 $de->showDiff( '', '' );
2640 * Do standard deferred updates after page view
2641 * @private
2643 function viewUpdates() {
2644 global $wgDeferredUpdateList, $wgUser;
2646 if ( 0 != $this->getID() ) {
2647 # Don't update page view counters on views from bot users (bug 14044)
2648 global $wgDisableCounters;
2649 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2650 Article::incViewCount( $this->getID() );
2651 $u = new SiteStatsUpdate( 1, 0, 0 );
2652 array_push( $wgDeferredUpdateList, $u );
2656 # Update newtalk / watchlist notification status
2657 $wgUser->clearNotification( $this->mTitle );
2661 * Prepare text which is about to be saved.
2662 * Returns a stdclass with source, pst and output members
2664 function prepareTextForEdit( $text, $revid=null ) {
2665 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2666 // Already prepared
2667 return $this->mPreparedEdit;
2669 global $wgParser;
2670 $edit = (object)array();
2671 $edit->revid = $revid;
2672 $edit->newText = $text;
2673 $edit->pst = $this->preSaveTransform( $text );
2674 $options = new ParserOptions;
2675 $options->setTidy( true );
2676 $options->enableLimitReport();
2677 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2678 $edit->oldText = $this->getContent();
2679 $this->mPreparedEdit = $edit;
2680 return $edit;
2684 * Do standard deferred updates after page edit.
2685 * Update links tables, site stats, search index and message cache.
2686 * Every 100th edit, prune the recent changes table.
2688 * @private
2689 * @param $text New text of the article
2690 * @param $summary Edit summary
2691 * @param $minoredit Minor edit
2692 * @param $timestamp_of_pagechange Timestamp associated with the page change
2693 * @param $newid rev_id value of the new revision
2694 * @param $changed Whether or not the content actually changed
2696 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2697 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2699 wfProfileIn( __METHOD__ );
2701 # Parse the text
2702 # Be careful not to double-PST: $text is usually already PST-ed once
2703 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2704 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2705 $editInfo = $this->prepareTextForEdit( $text, $newid );
2706 } else {
2707 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2708 $editInfo = $this->mPreparedEdit;
2711 # Save it to the parser cache
2712 if ( $wgEnableParserCache ) {
2713 $parserCache = ParserCache::singleton();
2714 $parserCache->save( $editInfo->output, $this, $wgUser );
2717 # Update the links tables
2718 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
2719 $u->doUpdate();
2721 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2722 if ( 0 == mt_rand( 0, 99 ) ) {
2723 // Flush old entries from the `recentchanges` table; we do this on
2724 // random requests so as to avoid an increase in writes for no good reason
2725 global $wgRCMaxAge;
2726 $dbw = wfGetDB( DB_MASTER );
2727 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2728 $recentchanges = $dbw->tableName( 'recentchanges' );
2729 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2730 $dbw->query( $sql );
2734 $id = $this->getID();
2735 $title = $this->mTitle->getPrefixedDBkey();
2736 $shortTitle = $this->mTitle->getDBkey();
2738 if ( 0 == $id ) {
2739 wfProfileOut( __METHOD__ );
2740 return;
2743 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2744 array_push( $wgDeferredUpdateList, $u );
2745 $u = new SearchUpdate( $id, $title, $text );
2746 array_push( $wgDeferredUpdateList, $u );
2748 # If this is another user's talk page, update newtalk
2749 # Don't do this if $changed = false otherwise some idiot can null-edit a
2750 # load of user talk pages and piss people off, nor if it's a minor edit
2751 # by a properly-flagged bot.
2752 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2753 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2754 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2755 $other = User::newFromName( $shortTitle );
2756 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2757 // An anonymous user
2758 $other = new User();
2759 $other->setName( $shortTitle );
2761 if( $other ) {
2762 $other->setNewtalk( true );
2767 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2768 $wgMessageCache->replace( $shortTitle, $text );
2771 wfProfileOut( __METHOD__ );
2775 * Perform article updates on a special page creation.
2777 * @param Revision $rev
2779 * @todo This is a shitty interface function. Kill it and replace the
2780 * other shitty functions like editUpdates and such so it's not needed
2781 * anymore.
2783 function createUpdates( $rev ) {
2784 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2785 $this->mTotalAdjustment = 1;
2786 $this->editUpdates( $rev->getText(), $rev->getComment(),
2787 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2791 * Generate the navigation links when browsing through an article revisions
2792 * It shows the information as:
2793 * Revision as of \<date\>; view current revision
2794 * \<- Previous version | Next Version -\>
2796 * @private
2797 * @param string $oldid Revision ID of this article revision
2799 function setOldSubtitle( $oldid=0 ) {
2800 global $wgLang, $wgOut, $wgUser;
2802 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2803 return;
2806 $revision = Revision::newFromId( $oldid );
2808 $current = ( $oldid == $this->mLatest );
2809 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2810 $sk = $wgUser->getSkin();
2811 $lnk = $current
2812 ? wfMsg( 'currentrevisionlink' )
2813 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2814 $curdiff = $current
2815 ? wfMsg( 'diff' )
2816 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2817 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2818 $prevlink = $prev
2819 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2820 : wfMsg( 'previousrevision' );
2821 $prevdiff = $prev
2822 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2823 : wfMsg( 'diff' );
2824 $nextlink = $current
2825 ? wfMsg( 'nextrevision' )
2826 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2827 $nextdiff = $current
2828 ? wfMsg( 'diff' )
2829 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2831 $cdel='';
2832 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2833 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2834 if( $revision->isCurrent() ) {
2835 // We don't handle top deleted edits too well
2836 $cdel = wfMsgHtml('rev-delundel');
2837 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2838 // If revision was hidden from sysops
2839 $cdel = wfMsgHtml('rev-delundel');
2840 } else {
2841 $cdel = $sk->makeKnownLinkObj( $revdel,
2842 wfMsgHtml('rev-delundel'),
2843 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2844 '&oldid=' . urlencode( $oldid ) );
2845 // Bolden oversighted content
2846 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2847 $cdel = "<strong>$cdel</strong>";
2849 $cdel = "(<small>$cdel</small>) ";
2851 # Show user links if allowed to see them. Normally they
2852 # are hidden regardless, but since we can already see the text here...
2853 $userlinks = $sk->revUserTools( $revision, false );
2855 $m = wfMsg( 'revision-info-current' );
2856 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2857 ? 'revision-info-current'
2858 : 'revision-info';
2860 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2862 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2863 $wgOut->setSubtitle( $r );
2867 * This function is called right before saving the wikitext,
2868 * so we can do things like signatures and links-in-context.
2870 * @param string $text
2872 function preSaveTransform( $text ) {
2873 global $wgParser, $wgUser;
2874 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2877 /* Caching functions */
2880 * checkLastModified returns true if it has taken care of all
2881 * output to the client that is necessary for this request.
2882 * (that is, it has sent a cached version of the page)
2884 function tryFileCache() {
2885 static $called = false;
2886 if( $called ) {
2887 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2888 return;
2890 $called = true;
2891 if($this->isFileCacheable()) {
2892 $touched = $this->mTouched;
2893 $cache = new HTMLFileCache( $this->mTitle );
2894 if($cache->isFileCacheGood( $touched )) {
2895 wfDebug( "Article::tryFileCache(): about to load file\n" );
2896 $cache->loadFromFileCache();
2897 return true;
2898 } else {
2899 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2900 ob_start( array(&$cache, 'saveToFileCache' ) );
2902 } else {
2903 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2908 * Check if the page can be cached
2909 * @return bool
2911 function isFileCacheable() {
2912 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2913 $action = $wgRequest->getVal( 'action' );
2914 $oldid = $wgRequest->getVal( 'oldid' );
2915 $diff = $wgRequest->getVal( 'diff' );
2916 $redirect = $wgRequest->getVal( 'redirect' );
2917 $printable = $wgRequest->getVal( 'printable' );
2918 $page = $wgRequest->getVal( 'page' );
2920 //check for non-standard user language; this covers uselang,
2921 //and extensions for auto-detecting user language.
2922 $ulang = $wgLang->getCode();
2923 $clang = $wgContLang->getCode();
2925 $cacheable = $wgUseFileCache
2926 && (!$wgShowIPinHeader)
2927 && ($this->getID() != 0)
2928 && ($wgUser->isAnon())
2929 && (!$wgUser->getNewtalk())
2930 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2931 && (empty( $action ) || $action == 'view')
2932 && (!isset($oldid))
2933 && (!isset($diff))
2934 && (!isset($redirect))
2935 && (!isset($printable))
2936 && !isset($page)
2937 && (!$this->mRedirectedFrom)
2938 && ($ulang === $clang);
2940 if ( $cacheable ) {
2941 //extension may have reason to disable file caching on some pages.
2942 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2945 return $cacheable;
2949 * Loads page_touched and returns a value indicating if it should be used
2952 function checkTouched() {
2953 if( !$this->mDataLoaded ) {
2954 $this->loadPageData();
2956 return !$this->mIsRedirect;
2960 * Get the page_touched field
2962 function getTouched() {
2963 # Ensure that page data has been loaded
2964 if( !$this->mDataLoaded ) {
2965 $this->loadPageData();
2967 return $this->mTouched;
2971 * Get the page_latest field
2973 function getLatest() {
2974 if ( !$this->mDataLoaded ) {
2975 $this->loadPageData();
2977 return $this->mLatest;
2981 * Edit an article without doing all that other stuff
2982 * The article must already exist; link tables etc
2983 * are not updated, caches are not flushed.
2985 * @param string $text text submitted
2986 * @param string $comment comment submitted
2987 * @param bool $minor whereas it's a minor modification
2989 function quickEdit( $text, $comment = '', $minor = 0 ) {
2990 wfProfileIn( __METHOD__ );
2992 $dbw = wfGetDB( DB_MASTER );
2993 $dbw->begin();
2994 $revision = new Revision( array(
2995 'page' => $this->getId(),
2996 'text' => $text,
2997 'comment' => $comment,
2998 'minor_edit' => $minor ? 1 : 0,
2999 ) );
3000 $revision->insertOn( $dbw );
3001 $this->updateRevisionOn( $dbw, $revision );
3002 $dbw->commit();
3004 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
3006 wfProfileOut( __METHOD__ );
3010 * Used to increment the view counter
3012 * @static
3013 * @param integer $id article id
3015 function incViewCount( $id ) {
3016 $id = intval( $id );
3017 global $wgHitcounterUpdateFreq, $wgDBtype;
3019 $dbw = wfGetDB( DB_MASTER );
3020 $pageTable = $dbw->tableName( 'page' );
3021 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3022 $acchitsTable = $dbw->tableName( 'acchits' );
3024 if( $wgHitcounterUpdateFreq <= 1 ) {
3025 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3026 return;
3029 # Not important enough to warrant an error page in case of failure
3030 $oldignore = $dbw->ignoreErrors( true );
3032 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3034 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3035 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3036 # Most of the time (or on SQL errors), skip row count check
3037 $dbw->ignoreErrors( $oldignore );
3038 return;
3041 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3042 $row = $dbw->fetchObject( $res );
3043 $rown = intval( $row->n );
3044 if( $rown >= $wgHitcounterUpdateFreq ){
3045 wfProfileIn( 'Article::incViewCount-collect' );
3046 $old_user_abort = ignore_user_abort( true );
3048 if ($wgDBtype == 'mysql')
3049 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3050 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3051 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3052 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3053 'GROUP BY hc_id');
3054 $dbw->query("DELETE FROM $hitcounterTable");
3055 if ($wgDBtype == 'mysql') {
3056 $dbw->query('UNLOCK TABLES');
3057 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3058 'WHERE page_id = hc_id');
3060 else {
3061 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3062 "FROM $acchitsTable WHERE page_id = hc_id");
3064 $dbw->query("DROP TABLE $acchitsTable");
3066 ignore_user_abort( $old_user_abort );
3067 wfProfileOut( 'Article::incViewCount-collect' );
3069 $dbw->ignoreErrors( $oldignore );
3072 /**#@+
3073 * The onArticle*() functions are supposed to be a kind of hooks
3074 * which should be called whenever any of the specified actions
3075 * are done.
3077 * This is a good place to put code to clear caches, for instance.
3079 * This is called on page move and undelete, as well as edit
3080 * @static
3081 * @param $title_obj a title object
3084 static function onArticleCreate($title) {
3085 # The talk page isn't in the regular link tables, so we need to update manually:
3086 if ( $title->isTalkPage() ) {
3087 $other = $title->getSubjectPage();
3088 } else {
3089 $other = $title->getTalkPage();
3091 $other->invalidateCache();
3092 $other->purgeSquid();
3094 $title->touchLinks();
3095 $title->purgeSquid();
3096 $title->deleteTitleProtection();
3099 static function onArticleDelete( $title ) {
3100 global $wgUseFileCache, $wgMessageCache;
3102 // Update existence markers on article/talk tabs...
3103 if( $title->isTalkPage() ) {
3104 $other = $title->getSubjectPage();
3105 } else {
3106 $other = $title->getTalkPage();
3108 $other->invalidateCache();
3109 $other->purgeSquid();
3111 $title->touchLinks();
3112 $title->purgeSquid();
3114 # File cache
3115 if ( $wgUseFileCache ) {
3116 $cm = new HTMLFileCache( $title );
3117 @unlink( $cm->fileCacheName() );
3120 # Messages
3121 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3122 $wgMessageCache->replace( $title->getDBkey(), false );
3124 # Images
3125 if( $title->getNamespace() == NS_IMAGE ) {
3126 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3127 $update->doUpdate();
3129 # User talk pages
3130 if( $title->getNamespace() == NS_USER_TALK ) {
3131 $user = User::newFromName( $title->getText(), false );
3132 $user->setNewtalk( false );
3137 * Purge caches on page update etc
3139 static function onArticleEdit( $title ) {
3140 global $wgDeferredUpdateList, $wgUseFileCache;
3142 // Invalidate caches of articles which include this page
3143 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3145 // Invalidate the caches of all pages which redirect here
3146 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3148 # Purge squid for this page only
3149 $title->purgeSquid();
3151 # Clear file cache
3152 if ( $wgUseFileCache ) {
3153 $cm = new HTMLFileCache( $title );
3154 @unlink( $cm->fileCacheName() );
3158 /**#@-*/
3161 * Overriden by ImagePage class, only present here to avoid a fatal error
3162 * Called for ?action=revert
3164 public function revert(){
3165 global $wgOut;
3166 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3170 * Info about this page
3171 * Called for ?action=info when $wgAllowPageInfo is on.
3173 * @public
3175 function info() {
3176 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3178 if ( !$wgAllowPageInfo ) {
3179 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3180 return;
3183 $page = $this->mTitle->getSubjectPage();
3185 $wgOut->setPagetitle( $page->getPrefixedText() );
3186 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3187 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3189 if( !$this->mTitle->exists() ) {
3190 $wgOut->addHtml( '<div class="noarticletext">' );
3191 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3192 // This doesn't quite make sense; the user is asking for
3193 // information about the _page_, not the message... -- RC
3194 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3195 } else {
3196 $msg = $wgUser->isLoggedIn()
3197 ? 'noarticletext'
3198 : 'noarticletextanon';
3199 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3201 $wgOut->addHtml( '</div>' );
3202 } else {
3203 $dbr = wfGetDB( DB_SLAVE );
3204 $wl_clause = array(
3205 'wl_title' => $page->getDBkey(),
3206 'wl_namespace' => $page->getNamespace() );
3207 $numwatchers = $dbr->selectField(
3208 'watchlist',
3209 'COUNT(*)',
3210 $wl_clause,
3211 __METHOD__,
3212 $this->getSelectOptions() );
3214 $pageInfo = $this->pageCountInfo( $page );
3215 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3217 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3218 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3219 if( $talkInfo ) {
3220 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3222 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3223 if( $talkInfo ) {
3224 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3226 $wgOut->addHTML( '</ul>' );
3232 * Return the total number of edits and number of unique editors
3233 * on a given page. If page does not exist, returns false.
3235 * @param Title $title
3236 * @return array
3237 * @private
3239 function pageCountInfo( $title ) {
3240 $id = $title->getArticleId();
3241 if( $id == 0 ) {
3242 return false;
3245 $dbr = wfGetDB( DB_SLAVE );
3247 $rev_clause = array( 'rev_page' => $id );
3249 $edits = $dbr->selectField(
3250 'revision',
3251 'COUNT(rev_page)',
3252 $rev_clause,
3253 __METHOD__,
3254 $this->getSelectOptions() );
3256 $authors = $dbr->selectField(
3257 'revision',
3258 'COUNT(DISTINCT rev_user_text)',
3259 $rev_clause,
3260 __METHOD__,
3261 $this->getSelectOptions() );
3263 return array( 'edits' => $edits, 'authors' => $authors );
3267 * Return a list of templates used by this article.
3268 * Uses the templatelinks table
3270 * @return array Array of Title objects
3272 function getUsedTemplates() {
3273 $result = array();
3274 $id = $this->mTitle->getArticleID();
3275 if( $id == 0 ) {
3276 return array();
3279 $dbr = wfGetDB( DB_SLAVE );
3280 $res = $dbr->select( array( 'templatelinks' ),
3281 array( 'tl_namespace', 'tl_title' ),
3282 array( 'tl_from' => $id ),
3283 __METHOD__ );
3284 if ( false !== $res ) {
3285 if ( $dbr->numRows( $res ) ) {
3286 while ( $row = $dbr->fetchObject( $res ) ) {
3287 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3291 $dbr->freeResult( $res );
3292 return $result;
3296 * Returns a list of hidden categories this page is a member of.
3297 * Uses the page_props and categorylinks tables.
3299 * @return array Array of Title objects
3301 function getHiddenCategories() {
3302 $result = array();
3303 $id = $this->mTitle->getArticleID();
3304 if( $id == 0 ) {
3305 return array();
3308 $dbr = wfGetDB( DB_SLAVE );
3309 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3310 array( 'cl_to' ),
3311 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3312 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3313 __METHOD__ );
3314 if ( false !== $res ) {
3315 if ( $dbr->numRows( $res ) ) {
3316 while ( $row = $dbr->fetchObject( $res ) ) {
3317 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3321 $dbr->freeResult( $res );
3322 return $result;
3326 * Return an applicable autosummary if one exists for the given edit.
3327 * @param string $oldtext The previous text of the page.
3328 * @param string $newtext The submitted text of the page.
3329 * @param bitmask $flags A bitmask of flags submitted for the edit.
3330 * @return string An appropriate autosummary, or an empty string.
3332 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3333 # Decide what kind of autosummary is needed.
3335 # Redirect autosummaries
3336 $rt = Title::newFromRedirect( $newtext );
3337 if( is_object( $rt ) ) {
3338 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3341 # New page autosummaries
3342 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3343 # If they're making a new article, give its text, truncated, in the summary.
3344 global $wgContLang;
3345 $truncatedtext = $wgContLang->truncate(
3346 str_replace("\n", ' ', $newtext),
3347 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3348 '...' );
3349 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3352 # Blanking autosummaries
3353 if( $oldtext != '' && $newtext == '' ) {
3354 return wfMsgForContent('autosumm-blank');
3355 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3356 # Removing more than 90% of the article
3357 global $wgContLang;
3358 $truncatedtext = $wgContLang->truncate(
3359 $newtext,
3360 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3361 '...'
3363 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3366 # If we reach this point, there's no applicable autosummary for our case, so our
3367 # autosummary is empty.
3368 return '';
3372 * Add the primary page-view wikitext to the output buffer
3373 * Saves the text into the parser cache if possible.
3374 * Updates templatelinks if it is out of date.
3376 * @param string $text
3377 * @param bool $cache
3379 public function outputWikiText( $text, $cache = true ) {
3380 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3382 $popts = $wgOut->parserOptions();
3383 $popts->setTidy(true);
3384 $popts->enableLimitReport();
3385 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3386 $popts, true, true, $this->getRevIdFetched() );
3387 $popts->setTidy(false);
3388 $popts->enableLimitReport( false );
3389 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3390 $parserCache = ParserCache::singleton();
3391 $parserCache->save( $parserOutput, $this, $wgUser );
3394 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3395 // templatelinks table may have become out of sync,
3396 // especially if using variable-based transclusions.
3397 // For paranoia, check if things have changed and if
3398 // so apply updates to the database. This will ensure
3399 // that cascaded protections apply as soon as the changes
3400 // are visible.
3402 # Get templates from templatelinks
3403 $id = $this->mTitle->getArticleID();
3405 $tlTemplates = array();
3407 $dbr = wfGetDB( DB_SLAVE );
3408 $res = $dbr->select( array( 'templatelinks' ),
3409 array( 'tl_namespace', 'tl_title' ),
3410 array( 'tl_from' => $id ),
3411 __METHOD__ );
3413 global $wgContLang;
3415 if ( false !== $res ) {
3416 if ( $dbr->numRows( $res ) ) {
3417 while ( $row = $dbr->fetchObject( $res ) ) {
3418 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3423 # Get templates from parser output.
3424 $poTemplates_allns = $parserOutput->getTemplates();
3426 $poTemplates = array ();
3427 foreach ( $poTemplates_allns as $ns_templates ) {
3428 $poTemplates = array_merge( $poTemplates, $ns_templates );
3431 # Get the diff
3432 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3434 if ( count( $templates_diff ) > 0 ) {
3435 # Whee, link updates time.
3436 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3438 $dbw = wfGetDb( DB_MASTER );
3439 $dbw->begin();
3441 $u->doUpdate();
3443 $dbw->commit();
3447 $wgOut->addParserOutput( $parserOutput );
3451 * Update all the appropriate counts in the category table, given that
3452 * we've added the categories $added and deleted the categories $deleted.
3454 * @param $added array The names of categories that were added
3455 * @param $deleted array The names of categories that were deleted
3456 * @return null
3458 public function updateCategoryCounts( $added, $deleted ) {
3459 $ns = $this->mTitle->getNamespace();
3460 $dbw = wfGetDB( DB_MASTER );
3462 # First make sure the rows exist. If one of the "deleted" ones didn't
3463 # exist, we might legitimately not create it, but it's simpler to just
3464 # create it and then give it a negative value, since the value is bogus
3465 # anyway.
3467 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3468 $insertCats = array_merge( $added, $deleted );
3469 if( !$insertCats ) {
3470 # Okay, nothing to do
3471 return;
3473 $insertRows = array();
3474 foreach( $insertCats as $cat ) {
3475 $insertRows[] = array( 'cat_title' => $cat );
3477 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3479 $addFields = array( 'cat_pages = cat_pages + 1' );
3480 $removeFields = array( 'cat_pages = cat_pages - 1' );
3481 if( $ns == NS_CATEGORY ) {
3482 $addFields[] = 'cat_subcats = cat_subcats + 1';
3483 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3484 } elseif( $ns == NS_IMAGE ) {
3485 $addFields[] = 'cat_files = cat_files + 1';
3486 $removeFields[] = 'cat_files = cat_files - 1';
3489 if ( $added ) {
3490 $dbw->update(
3491 'category',
3492 $addFields,
3493 array( 'cat_title' => $added ),
3494 __METHOD__
3497 if ( $deleted ) {
3498 $dbw->update(
3499 'category',
3500 $removeFields,
3501 array( 'cat_title' => $deleted ),
3502 __METHOD__