Localisation updates for core messages from translatewiki.net (2009-09-10 22:35 UTC)
[mediawiki.git] / includes / Article.php
blobefc3961066cbb920d49a506959d4302e44269ee2
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 var $mParserOptions; //!<
44 var $mParserOutput; //!<
45 /**@}}*/
47 /**
48 * Constructor and clear the article
49 * @param $title Reference to a Title object.
50 * @param $oldId Integer revision ID, null to fetch from request, zero for current
52 public function __construct( Title $title, $oldId = null ) {
53 $this->mTitle =& $title;
54 $this->mOldId = $oldId;
57 /**
58 * Constructor from an article article
59 * @param $id The article ID to load
61 public static function newFromID( $id ) {
62 $t = Title::newFromID( $id );
63 return $t == null ? null : new Article( $t );
66 /**
67 * Tell the page view functions that this view was redirected
68 * from another page on the wiki.
69 * @param $from Title object.
71 public function setRedirectedFrom( $from ) {
72 $this->mRedirectedFrom = $from;
75 /**
76 * If this page is a redirect, get its target
78 * The target will be fetched from the redirect table if possible.
79 * If this page doesn't have an entry there, call insertRedirect()
80 * @return mixed Title object, or null if this page is not a redirect
82 public function getRedirectTarget() {
83 if( !$this->mTitle || !$this->mTitle->isRedirect() )
84 return null;
85 if( !is_null($this->mRedirectTarget) )
86 return $this->mRedirectTarget;
87 # Query the redirect table
88 $dbr = wfGetDB( DB_SLAVE );
89 $row = $dbr->selectRow( 'redirect',
90 array('rd_namespace', 'rd_title'),
91 array('rd_from' => $this->getID() ),
92 __METHOD__
94 if( $row ) {
95 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
97 # This page doesn't have an entry in the redirect table
98 return $this->mRedirectTarget = $this->insertRedirect();
102 * Insert an entry for this page into the redirect table.
104 * Don't call this function directly unless you know what you're doing.
105 * @return Title object
107 public function insertRedirect() {
108 $retval = Title::newFromRedirect( $this->getContent() );
109 if( !$retval ) {
110 return null;
112 $dbw = wfGetDB( DB_MASTER );
113 $dbw->replace( 'redirect', array('rd_from'),
114 array(
115 'rd_from' => $this->getID(),
116 'rd_namespace' => $retval->getNamespace(),
117 'rd_title' => $retval->getDBkey()
119 __METHOD__
121 return $retval;
125 * Get the Title object this page redirects to
127 * @return mixed false, Title of in-wiki target, or string with URL
129 public function followRedirect() {
130 $text = $this->getContent();
131 return $this->followRedirectText( $text );
135 * Get the Title object this text redirects to
137 * @return mixed false, Title of in-wiki target, or string with URL
139 public function followRedirectText( $text ) {
140 $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
141 # process if title object is valid and not special:userlogout
142 if( $rt ) {
143 if( $rt->getInterwiki() != '' ) {
144 if( $rt->isLocal() ) {
145 // Offsite wikis need an HTTP redirect.
147 // This can be hard to reverse and may produce loops,
148 // so they may be disabled in the site configuration.
149 $source = $this->mTitle->getFullURL( 'redirect=no' );
150 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
152 } else {
153 if( $rt->getNamespace() == NS_SPECIAL ) {
154 // Gotta handle redirects to special pages differently:
155 // Fill the HTTP response "Location" header and ignore
156 // the rest of the page we're on.
158 // This can be hard to reverse, so they may be disabled.
159 if( $rt->isSpecial( 'Userlogout' ) ) {
160 // rolleyes
161 } else {
162 return $rt->getFullURL();
165 return $rt;
168 // No or invalid redirect
169 return false;
173 * get the title object of the article
175 public function getTitle() {
176 return $this->mTitle;
180 * Clear the object
181 * @private
183 public function clear() {
184 $this->mDataLoaded = false;
185 $this->mContentLoaded = false;
187 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
188 $this->mRedirectedFrom = null; # Title object if set
189 $this->mRedirectTarget = null; # Title object if set
190 $this->mUserText =
191 $this->mTimestamp = $this->mComment = '';
192 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
193 $this->mTouched = '19700101000000';
194 $this->mForUpdate = false;
195 $this->mIsRedirect = false;
196 $this->mRevIdFetched = 0;
197 $this->mRedirectUrl = false;
198 $this->mLatest = false;
199 $this->mPreparedEdit = false;
203 * Note that getContent/loadContent do not follow redirects anymore.
204 * If you need to fetch redirectable content easily, try
205 * the shortcut in Article::followContent()
207 * @return Return the text of this revision
209 public function getContent() {
210 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
211 wfProfileIn( __METHOD__ );
212 if( $this->getID() === 0 ) {
213 # If this is a MediaWiki:x message, then load the messages
214 # and return the message value for x.
215 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
216 # If this is a system message, get the default text.
217 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
218 $wgMessageCache->loadAllMessages( $lang );
219 $text = wfMsgGetKey( $message, false, $lang, false );
220 if( wfEmptyMsg( $message, $text ) )
221 $text = '';
222 } else {
223 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
225 wfProfileOut( __METHOD__ );
226 return $text;
227 } else {
228 $this->loadContent();
229 wfProfileOut( __METHOD__ );
230 return $this->mContent;
235 * Get the text of the current revision. No side-effects...
237 * @return Return the text of the current revision
239 public function getRawText() {
240 // Check process cache for current revision
241 if( $this->mContentLoaded && $this->mOldId == 0 ) {
242 return $this->mContent;
244 $rev = Revision::newFromTitle( $this->mTitle );
245 $text = $rev ? $rev->getRawText() : false;
246 return $text;
250 * This function returns the text of a section, specified by a number ($section).
251 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
252 * the first section before any such heading (section 0).
254 * If a section contains subsections, these are also returned.
256 * @param $text String: text to look in
257 * @param $section Integer: section number
258 * @return string text of the requested section
259 * @deprecated
261 public function getSection( $text, $section ) {
262 global $wgParser;
263 return $wgParser->getSection( $text, $section );
267 * Get the text that needs to be saved in order to undo all revisions
268 * between $undo and $undoafter. Revisions must belong to the same page,
269 * must exist and must not be deleted
270 * @param $undo Revision
271 * @param $undoafter Revision Must be an earlier revision than $undo
272 * @return mixed string on success, false on failure
274 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
275 $undo_text = $undo->getText();
276 $undoafter_text = $undoafter->getText();
277 $cur_text = $this->getContent();
278 if ( $cur_text == $undo_text ) {
279 # No use doing a merge if it's just a straight revert.
280 return $undoafter_text;
282 $undone_text = '';
283 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
284 return false;
285 return $undone_text;
289 * @return int The oldid of the article that is to be shown, 0 for the
290 * current revision
292 public function getOldID() {
293 if( is_null( $this->mOldId ) ) {
294 $this->mOldId = $this->getOldIDFromRequest();
296 return $this->mOldId;
300 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
302 * @return int The old id for the request
304 public function getOldIDFromRequest() {
305 global $wgRequest;
306 $this->mRedirectUrl = false;
307 $oldid = $wgRequest->getVal( 'oldid' );
308 if( isset( $oldid ) ) {
309 $oldid = intval( $oldid );
310 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
311 $nextid = $this->mTitle->getNextRevisionID( $oldid );
312 if( $nextid ) {
313 $oldid = $nextid;
314 } else {
315 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
317 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
318 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
319 if( $previd ) {
320 $oldid = $previd;
324 if( !$oldid ) {
325 $oldid = 0;
327 return $oldid;
331 * Load the revision (including text) into this object
333 function loadContent() {
334 if( $this->mContentLoaded ) return;
335 wfProfileIn( __METHOD__ );
336 # Query variables :P
337 $oldid = $this->getOldID();
338 # Pre-fill content with error message so that if something
339 # fails we'll have something telling us what we intended.
340 $this->mOldId = $oldid;
341 $this->fetchContent( $oldid );
342 wfProfileOut( __METHOD__ );
347 * Fetch a page record with the given conditions
348 * @param $dbr Database object
349 * @param $conditions Array
351 protected function pageData( $dbr, $conditions ) {
352 $fields = array(
353 'page_id',
354 'page_namespace',
355 'page_title',
356 'page_restrictions',
357 'page_counter',
358 'page_is_redirect',
359 'page_is_new',
360 'page_random',
361 'page_touched',
362 'page_latest',
363 'page_len',
365 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
366 $row = $dbr->selectRow(
367 'page',
368 $fields,
369 $conditions,
370 __METHOD__
372 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
373 return $row ;
377 * @param $dbr Database object
378 * @param $title Title object
380 public function pageDataFromTitle( $dbr, $title ) {
381 return $this->pageData( $dbr, array(
382 'page_namespace' => $title->getNamespace(),
383 'page_title' => $title->getDBkey() ) );
387 * @param $dbr Database
388 * @param $id Integer
390 protected function pageDataFromId( $dbr, $id ) {
391 return $this->pageData( $dbr, array( 'page_id' => $id ) );
395 * Set the general counter, title etc data loaded from
396 * some source.
398 * @param $data Database row object or "fromdb"
400 public function loadPageData( $data = 'fromdb' ) {
401 if( $data === 'fromdb' ) {
402 $dbr = wfGetDB( DB_MASTER );
403 $data = $this->pageDataFromId( $dbr, $this->getId() );
406 $lc = LinkCache::singleton();
407 if( $data ) {
408 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
410 $this->mTitle->mArticleID = intval( $data->page_id );
412 # Old-fashioned restrictions
413 $this->mTitle->loadRestrictions( $data->page_restrictions );
415 $this->mCounter = intval( $data->page_counter );
416 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
417 $this->mIsRedirect = intval( $data->page_is_redirect );
418 $this->mLatest = intval( $data->page_latest );
419 } else {
420 if( is_object( $this->mTitle ) ) {
421 $lc->addBadLinkObj( $this->mTitle );
423 $this->mTitle->mArticleID = 0;
426 $this->mDataLoaded = true;
430 * Get text of an article from database
431 * Does *NOT* follow redirects.
432 * @param $oldid Int: 0 for whatever the latest revision is
433 * @return string
435 function fetchContent( $oldid = 0 ) {
436 if( $this->mContentLoaded ) {
437 return $this->mContent;
440 $dbr = wfGetDB( DB_MASTER );
442 # Pre-fill content with error message so that if something
443 # fails we'll have something telling us what we intended.
444 $t = $this->mTitle->getPrefixedText();
445 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
446 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
448 if( $oldid ) {
449 $revision = Revision::newFromId( $oldid );
450 if( is_null( $revision ) ) {
451 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
452 return false;
454 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
455 if( !$data ) {
456 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
457 return false;
459 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
460 $this->loadPageData( $data );
461 } else {
462 if( !$this->mDataLoaded ) {
463 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
464 if( !$data ) {
465 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
466 return false;
468 $this->loadPageData( $data );
470 $revision = Revision::newFromId( $this->mLatest );
471 if( is_null( $revision ) ) {
472 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
473 return false;
477 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
478 // We should instead work with the Revision object when we need it...
479 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
481 $this->mUser = $revision->getUser();
482 $this->mUserText = $revision->getUserText();
483 $this->mComment = $revision->getComment();
484 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
486 $this->mRevIdFetched = $revision->getId();
487 $this->mContentLoaded = true;
488 $this->mRevision =& $revision;
490 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
492 return $this->mContent;
496 * Read/write accessor to select FOR UPDATE
498 * @param $x Mixed: FIXME
500 public function forUpdate( $x = NULL ) {
501 return wfSetVar( $this->mForUpdate, $x );
505 * Get the database which should be used for reads
507 * @return Database
508 * @deprecated - just call wfGetDB( DB_MASTER ) instead
510 function getDB() {
511 wfDeprecated( __METHOD__ );
512 return wfGetDB( DB_MASTER );
516 * Get options for all SELECT statements
518 * @param $options Array: an optional options array which'll be appended to
519 * the default
520 * @return Array: options
522 protected function getSelectOptions( $options = '' ) {
523 if( $this->mForUpdate ) {
524 if( is_array( $options ) ) {
525 $options[] = 'FOR UPDATE';
526 } else {
527 $options = 'FOR UPDATE';
530 return $options;
534 * @return int Page ID
536 public function getID() {
537 if( $this->mTitle ) {
538 return $this->mTitle->getArticleID();
539 } else {
540 return 0;
545 * @return bool Whether or not the page exists in the database
547 public function exists() {
548 return $this->getId() > 0;
552 * Check if this page is something we're going to be showing
553 * some sort of sensible content for. If we return false, page
554 * views (plain action=view) will return an HTTP 404 response,
555 * so spiders and robots can know they're following a bad link.
557 * @return bool
559 public function hasViewableContent() {
560 return $this->exists() || $this->mTitle->isAlwaysKnown();
564 * @return int The view count for the page
566 public function getCount() {
567 if( -1 == $this->mCounter ) {
568 $id = $this->getID();
569 if( $id == 0 ) {
570 $this->mCounter = 0;
571 } else {
572 $dbr = wfGetDB( DB_SLAVE );
573 $this->mCounter = $dbr->selectField( 'page',
574 'page_counter',
575 array( 'page_id' => $id ),
576 __METHOD__,
577 $this->getSelectOptions()
581 return $this->mCounter;
585 * Determine whether a page would be suitable for being counted as an
586 * article in the site_stats table based on the title & its content
588 * @param $text String: text to analyze
589 * @return bool
591 public function isCountable( $text ) {
592 global $wgUseCommaCount;
594 $token = $wgUseCommaCount ? ',' : '[[';
595 return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
599 * Tests if the article text represents a redirect
601 * @param $text String: FIXME
602 * @return bool
604 public function isRedirect( $text = false ) {
605 if( $text === false ) {
606 if( $this->mDataLoaded ) {
607 return $this->mIsRedirect;
609 // Apparently loadPageData was never called
610 $this->loadContent();
611 $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
612 } else {
613 $titleObj = Title::newFromRedirect( $text );
615 return $titleObj !== NULL;
619 * Returns true if the currently-referenced revision is the current edit
620 * to this page (and it exists).
621 * @return bool
623 public function isCurrent() {
624 # If no oldid, this is the current version.
625 if( $this->getOldID() == 0 ) {
626 return true;
628 return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
632 * Loads everything except the text
633 * This isn't necessary for all uses, so it's only done if needed.
635 protected function loadLastEdit() {
636 if( -1 != $this->mUser )
637 return;
639 # New or non-existent articles have no user information
640 $id = $this->getID();
641 if( 0 == $id ) return;
643 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
644 if( !is_null( $this->mLastRevision ) ) {
645 $this->mUser = $this->mLastRevision->getUser();
646 $this->mUserText = $this->mLastRevision->getUserText();
647 $this->mTimestamp = $this->mLastRevision->getTimestamp();
648 $this->mComment = $this->mLastRevision->getComment();
649 $this->mMinorEdit = $this->mLastRevision->isMinor();
650 $this->mRevIdFetched = $this->mLastRevision->getId();
654 public function getTimestamp() {
655 // Check if the field has been filled by ParserCache::get()
656 if( !$this->mTimestamp ) {
657 $this->loadLastEdit();
659 return wfTimestamp(TS_MW, $this->mTimestamp);
662 public function getUser() {
663 $this->loadLastEdit();
664 return $this->mUser;
667 public function getUserText() {
668 $this->loadLastEdit();
669 return $this->mUserText;
672 public function getComment() {
673 $this->loadLastEdit();
674 return $this->mComment;
677 public function getMinorEdit() {
678 $this->loadLastEdit();
679 return $this->mMinorEdit;
682 /* Use this to fetch the rev ID used on page views */
683 public function getRevIdFetched() {
684 $this->loadLastEdit();
685 return $this->mRevIdFetched;
689 * @param $limit Integer: default 0.
690 * @param $offset Integer: default 0.
692 public function getContributors($limit = 0, $offset = 0) {
693 # XXX: this is expensive; cache this info somewhere.
695 $contribs = array();
696 $dbr = wfGetDB( DB_SLAVE );
697 $revTable = $dbr->tableName( 'revision' );
698 $userTable = $dbr->tableName( 'user' );
699 $user = $this->getUser();
700 $pageId = $this->getId();
702 $deletedBit = $dbr->bitAnd('rev_deleted', Revision::DELETED_USER); // username hidden?
704 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
705 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
706 WHERE rev_page = $pageId
707 AND rev_user != $user
708 AND $deletedBit = 0
709 GROUP BY rev_user, rev_user_text, user_real_name
710 ORDER BY timestamp DESC";
712 if($limit > 0)
713 $sql = $dbr->limitResult($sql, $limit, $offset);
715 $sql .= ' '. $this->getSelectOptions();
717 $res = $dbr->query($sql, __METHOD__ );
719 return new UserArrayFromResult( $res );
723 * This is the default action of the index.php entry point: just view the
724 * page of the given title.
726 public function view() {
727 global $wgUser, $wgOut, $wgRequest, $wgContLang;
728 global $wgEnableParserCache, $wgStylePath, $wgParser;
729 global $wgUseTrackbacks, $wgUseFileCache;
731 wfProfileIn( __METHOD__ );
733 # Get variables from query string
734 $oldid = $this->getOldID();
735 $parserCache = ParserCache::singleton();
737 $parserOptions = clone $this->getParserOptions();
738 # Render printable version, use printable version cache
739 if ( $wgOut->isPrintable() ) {
740 $parserOptions->setIsPrintable( true );
743 # Try client and file cache
744 if( $oldid === 0 && $this->checkTouched() ) {
745 global $wgUseETag;
746 if( $wgUseETag ) {
747 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
749 # Is is client cached?
750 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
751 wfDebug( __METHOD__.": done 304\n" );
752 wfProfileOut( __METHOD__ );
753 return;
754 # Try file cache
755 } else if( $wgUseFileCache && $this->tryFileCache() ) {
756 wfDebug( __METHOD__.": done file cache\n" );
757 # tell wgOut that output is taken care of
758 $wgOut->disable();
759 $this->viewUpdates();
760 wfProfileOut( __METHOD__ );
761 return;
765 $sk = $wgUser->getSkin();
767 # getOldID may want us to redirect somewhere else
768 if( $this->mRedirectUrl ) {
769 $wgOut->redirect( $this->mRedirectUrl );
770 wfDebug( __METHOD__.": redirecting due to oldid\n" );
771 wfProfileOut( __METHOD__ );
772 return;
775 $wgOut->setArticleFlag( true );
776 # Set page title (may be overridden by DISPLAYTITLE)
777 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
779 # If we got diff in the query, we want to see a diff page instead of the article.
780 if( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
781 wfDebug( __METHOD__.": showing diff page\n" );
782 $this->showDiffPage();
783 wfProfileOut( __METHOD__ );
784 return;
787 # Should the parser cache be used?
788 $useParserCache = $this->useParserCache( $oldid );
789 wfDebug( 'Article::view using parser cache: ' . ($useParserCache ? 'yes' : 'no' ) . "\n" );
790 if( $wgUser->getOption( 'stubthreshold' ) ) {
791 wfIncrStats( 'pcache_miss_stub' );
794 # For the main page, overwrite the <title> element with the con-
795 # tents of 'pagetitle-view-mainpage' instead of the default (if
796 # that's not empty).
797 if( $this->mTitle->equals( Title::newMainPage() )
798 && ($m=wfMsgForContent( 'pagetitle-view-mainpage' )) !== '' )
800 $wgOut->setHTMLTitle( $m );
803 $wasRedirected = $this->showRedirectedFromHeader();
804 $this->showNamespaceHeader();
806 # Iterate through the possible ways of constructing the output text.
807 # Keep going until $outputDone is set, or we run out of things to do.
808 $pass = 0;
809 $outputDone = false;
810 while( !$outputDone && ++$pass ){
811 switch( $pass ){
812 case 1:
813 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
814 break;
816 case 2:
817 # Try the parser cache
818 if( $useParserCache ) {
819 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
820 if ( $this->mParserOutput !== false ) {
821 wfDebug( __METHOD__.": showing parser cache contents\n" );
822 $wgOut->addParserOutput( $this->mParserOutput );
823 # Ensure that UI elements requiring revision ID have
824 # the correct version information.
825 $wgOut->setRevisionId( $this->mLatest );
826 $outputDone = true;
829 break;
831 case 3:
832 $text = $this->getContent();
833 if( $text === false || $this->getID() == 0 ) {
834 wfDebug( __METHOD__.": showing missing article\n" );
835 $this->showMissingArticle();
836 wfProfileOut( __METHOD__ );
837 return;
840 # Another whitelist check in case oldid is altering the title
841 if( !$this->mTitle->userCanRead() ) {
842 wfDebug( __METHOD__.": denied on secondary read check\n" );
843 $wgOut->loginToUse();
844 $wgOut->output();
845 $wgOut->disable();
846 wfProfileOut( __METHOD__ );
847 return;
850 # Are we looking at an old revision
851 if( $oldid && !is_null( $this->mRevision ) ) {
852 $this->setOldSubtitle( $oldid );
853 if ( !$this->showDeletedRevisionHeader() ) {
854 wfDebug( __METHOD__.": cannot view deleted revision\n" );
855 wfProfileOut( __METHOD__ );
856 return;
858 # If this "old" version is the current, then try the parser cache...
859 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
860 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
861 if ( $this->mParserOutput ) {
862 wfDebug( __METHOD__.": showing parser cache for current rev permalink\n" );
863 $wgOut->addParserOutput( $this->mParserOutput );
864 $wgOut->setRevisionId( $this->mLatest );
865 $this->showViewFooter();
866 $this->viewUpdates();
867 wfProfileOut( __METHOD__ );
868 return;
873 # Ensure that UI elements requiring revision ID have
874 # the correct version information.
875 $wgOut->setRevisionId( $this->getRevIdFetched() );
877 # Pages containing custom CSS or JavaScript get special treatment
878 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
879 wfDebug( __METHOD__.": showing CSS/JS source\n" );
880 $this->showCssOrJsPage();
881 $outputDone = true;
882 } else if( $rt = Title::newFromRedirectArray( $text ) ) {
883 wfDebug( __METHOD__.": showing redirect=no page\n" );
884 # Viewing a redirect page (e.g. with parameter redirect=no)
885 # Don't append the subtitle if this was an old revision
886 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
887 # Parse just to get categories, displaytitle, etc.
888 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
889 $wgOut->addParserOutputNoText( $this->mParserOutput );
890 $outputDone = true;
892 break;
894 case 4:
895 # Run the parse, protected by a pool counter
896 wfDebug( __METHOD__.": doing uncached parse\n" );
897 $key = $parserCache->getKey( $this, $parserOptions );
898 $poolCounter = PoolCounter::factory( 'Article::view', $key );
899 $dirtyCallback = $useParserCache ? array( $this, 'tryDirtyCache' ) : false;
900 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
902 if ( !$status->isOK() ) {
903 # Connection or timeout error
904 $this->showPoolError( $status );
905 wfProfileOut( __METHOD__ );
906 return;
907 } else {
908 $outputDone = true;
910 break;
912 # Should be unreachable, but just in case...
913 default:
914 break 2;
918 # Now that we've filled $this->mParserOutput, we know whether
919 # there are any __NOINDEX__ tags on the page
920 $policy = $this->getRobotPolicy( 'view' );
921 $wgOut->setIndexPolicy( $policy['index'] );
922 $wgOut->setFollowPolicy( $policy['follow'] );
924 $this->showViewFooter();
925 $this->viewUpdates();
926 wfProfileOut( __METHOD__ );
930 * Show a diff page according to current request variables. For use within
931 * Article::view() only, other callers should use the DifferenceEngine class.
933 public function showDiffPage() {
934 global $wgOut, $wgRequest, $wgUser;
936 $diff = $wgRequest->getVal( 'diff' );
937 $rcid = $wgRequest->getVal( 'rcid' );
938 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
939 $purge = $wgRequest->getVal( 'action' ) == 'purge';
940 $htmldiff = $wgRequest->getBool( 'htmldiff' );
941 $unhide = $wgRequest->getInt('unhide') == 1;
942 $oldid = $this->getOldID();
944 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
945 // DifferenceEngine directly fetched the revision:
946 $this->mRevIdFetched = $de->mNewid;
947 $de->showDiffPage( $diffOnly );
949 // Needed to get the page's current revision
950 $this->loadPageData();
951 if( $diff == 0 || $diff == $this->mLatest ) {
952 # Run view updates for current revision only
953 $this->viewUpdates();
958 * Show a page view for a page formatted as CSS or JavaScript. To be called by
959 * Article::view() only.
961 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
962 * page views.
964 public function showCssOrJsPage() {
965 global $wgOut;
966 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
967 // Give hooks a chance to customise the output
968 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
969 // Wrap the whole lot in a <pre> and don't parse
970 $m = array();
971 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
972 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
973 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
974 $wgOut->addHTML( "\n</pre>\n" );
979 * Get the robot policy to be used for the current action=view request.
980 * @return String the policy that should be set
981 * @deprecated use getRobotPolicy() instead, which returns an associative
982 * array
984 public function getRobotPolicyForView() {
985 wfDeprecated( __FUNC__ );
986 $policy = $this->getRobotPolicy( 'view' );
987 return $policy['index'] . ',' . $policy['follow'];
991 * Get the robot policy to be used for the current view
992 * @param $action String the action= GET parameter
993 * @return Array the policy that should be set
994 * TODO: actions other than 'view'
996 public function getRobotPolicy( $action ){
998 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
999 global $wgDefaultRobotPolicy, $wgRequest;
1001 $ns = $this->mTitle->getNamespace();
1002 if( $ns == NS_USER || $ns == NS_USER_TALK ) {
1003 # Don't index user and user talk pages for blocked users (bug 11443)
1004 if( !$this->mTitle->isSubpage() ) {
1005 $block = new Block();
1006 if( $block->load( $this->mTitle->getText() ) ) {
1007 return array( 'index' => 'noindex',
1008 'follow' => 'nofollow' );
1013 if( $this->getID() === 0 || $this->getOldID() ) {
1014 # Non-articles (special pages etc), and old revisions
1015 return array( 'index' => 'noindex',
1016 'follow' => 'nofollow' );
1017 } elseif( $wgOut->isPrintable() ) {
1018 # Discourage indexing of printable versions, but encourage following
1019 return array( 'index' => 'noindex',
1020 'follow' => 'follow' );
1021 } elseif( $wgRequest->getInt('curid') ) {
1022 # For ?curid=x urls, disallow indexing
1023 return array( 'index' => 'noindex',
1024 'follow' => 'follow' );
1027 # Otherwise, construct the policy based on the various config variables.
1028 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
1030 if( isset( $wgNamespaceRobotPolicies[$ns] ) ){
1031 # Honour customised robot policies for this namespace
1032 $policy = array_merge( $policy,
1033 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] ) );
1035 if( $this->mTitle->canUseNoindex() && is_object( $this->mParserOutput ) && $this->mParserOutput->getIndexPolicy() ){
1036 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1037 # a final sanity check that we have really got the parser output.
1038 $policy = array_merge( $policy,
1039 array( 'index' => $this->mParserOutput->getIndexPolicy() ) );
1042 if( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ){
1043 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1044 $policy = array_merge( $policy,
1045 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) );
1048 return $policy;
1053 * Converts a String robot policy into an associative array, to allow
1054 * merging of several policies using array_merge().
1055 * @param $policy Mixed, returns empty array on null/false/'', transparent
1056 * to already-converted arrays, converts String.
1057 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1059 public static function formatRobotPolicy( $policy ){
1060 if( is_array( $policy ) ){
1061 return $policy;
1062 } elseif( !$policy ){
1063 return array();
1066 $policy = explode( ',', $policy );
1067 $policy = array_map( 'trim', $policy );
1069 $arr = array();
1070 foreach( $policy as $var ){
1071 if( in_array( $var, array('index','noindex') ) ){
1072 $arr['index'] = $var;
1073 } elseif( in_array( $var, array('follow','nofollow') ) ){
1074 $arr['follow'] = $var;
1077 return $arr;
1081 * If this request is a redirect view, send "redirected from" subtitle to
1082 * $wgOut. Returns true if the header was needed, false if this is not a
1083 * redirect view. Handles both local and remote redirects.
1085 public function showRedirectedFromHeader() {
1086 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1088 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1089 $sk = $wgUser->getSkin();
1090 if( isset( $this->mRedirectedFrom ) ) {
1091 // This is an internally redirected page view.
1092 // We'll need a backlink to the source page for navigation.
1093 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1094 $redir = $sk->link(
1095 $this->mRedirectedFrom,
1096 null,
1097 array(),
1098 array( 'redirect' => 'no' ),
1099 array( 'known', 'noclasses' )
1101 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1102 $wgOut->setSubtitle( $s );
1104 // Set the fragment if one was specified in the redirect
1105 if( strval( $this->mTitle->getFragment() ) != '' ) {
1106 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
1107 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1110 // Add a <link rel="canonical"> tag
1111 $wgOut->addLink( array( 'rel' => 'canonical',
1112 'href' => $this->mTitle->getLocalURL() )
1114 return true;
1116 } elseif( $rdfrom ) {
1117 // This is an externally redirected view, from some other wiki.
1118 // If it was reported from a trusted site, supply a backlink.
1119 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1120 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1121 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1122 $wgOut->setSubtitle( $s );
1123 return true;
1126 return false;
1130 * Show a header specific to the namespace currently being viewed, like
1131 * [[MediaWiki:Talkpagetext]]. For Article::view().
1133 public function showNamespaceHeader() {
1134 global $wgOut;
1135 if( $this->mTitle->isTalkPage() ) {
1136 $msg = wfMsgNoTrans( 'talkpageheader' );
1137 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1138 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1144 * Show the footer section of an ordinary page view
1146 public function showViewFooter() {
1147 global $wgOut, $wgUseTrackbacks, $wgRequest;
1148 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1149 if( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1150 $wgOut->addWikiMsg('anontalkpagetext');
1153 # If we have been passed an &rcid= parameter, we want to give the user a
1154 # chance to mark this new article as patrolled.
1155 $this->showPatrolFooter();
1157 # Trackbacks
1158 if( $wgUseTrackbacks ) {
1159 $this->addTrackbacks();
1164 * If patrol is possible, output a patrol UI box. This is called from the
1165 * footer section of ordinary page views. If patrol is not possible or not
1166 * desired, does nothing.
1168 public function showPatrolFooter() {
1169 global $wgOut, $wgRequest, $wgUser;
1170 $rcid = $wgRequest->getVal( 'rcid' );
1172 if( !$rcid || !$this->mTitle->exists() || !$this->mTitle->quickUserCan( 'patrol' ) ) {
1173 return;
1176 $sk = $wgUser->getSkin();
1178 $wgOut->addHTML(
1179 "<div class='patrollink'>" .
1180 wfMsgHtml(
1181 'markaspatrolledlink',
1182 $sk->link(
1183 $this->mTitle,
1184 wfMsgHtml( 'markaspatrolledtext' ),
1185 array(),
1186 array(
1187 'action' => 'markpatrolled',
1188 'rcid' => $rcid
1190 array( 'known', 'noclasses' )
1193 '</div>'
1198 * Show the error text for a missing article. For articles in the MediaWiki
1199 * namespace, show the default message text. To be called from Article::view().
1201 public function showMissingArticle() {
1202 global $wgOut, $wgRequest, $wgUser;
1203 # Show delete and move logs
1204 $this->showLogs();
1206 # Show error message
1207 $oldid = $this->getOldID();
1208 if( $oldid ) {
1209 $text = wfMsgNoTrans( 'missing-article',
1210 $this->mTitle->getPrefixedText(),
1211 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1212 } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1213 // Use the default message text
1214 $text = $this->getContent();
1215 } else {
1216 $createErrors = $this->mTitle->getUserPermissionsErrors( 'create', $wgUser );
1217 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
1218 $errors = array_merge( $createErrors, $editErrors );
1220 if ( !count($errors) )
1221 $text = wfMsgNoTrans( 'noarticletext' );
1222 else
1223 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1225 $text = "<div class='noarticletext'>\n$text\n</div>";
1226 if( !$this->hasViewableContent() ) {
1227 // If there's no backing content, send a 404 Not Found
1228 // for better machine handling of broken links.
1229 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1231 $wgOut->addWikiText( $text );
1235 * If the revision requested for view is deleted, check permissions.
1236 * Send either an error message or a warning header to $wgOut.
1237 * Returns true if the view is allowed, false if not.
1239 public function showDeletedRevisionHeader() {
1240 global $wgOut, $wgRequest;
1241 if( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1242 // Not deleted
1243 return true;
1245 // If the user is not allowed to see it...
1246 if( !$this->mRevision->userCan(Revision::DELETED_TEXT) ) {
1247 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1248 'rev-deleted-text-permission' );
1249 return false;
1250 // If the user needs to confirm that they want to see it...
1251 } else if( $wgRequest->getInt('unhide') != 1 ) {
1252 # Give explanation and add a link to view the revision...
1253 $oldid = intval( $this->getOldID() );
1254 $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
1255 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1256 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1257 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1258 array($msg,$link) );
1259 return false;
1260 // We are allowed to see...
1261 } else {
1262 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1263 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1264 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", $msg );
1265 return true;
1270 * Show an excerpt from the deletion and move logs. To be called from the
1271 * header section on page views of missing pages.
1273 public function showLogs() {
1274 global $wgUser, $wgOut;
1275 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1276 $pager = new LogPager( $loglist, array('move', 'delete'), false,
1277 $this->mTitle->getPrefixedText(), '', array( "log_action != 'revision'" ) );
1278 if( $pager->getNumRows() > 0 ) {
1279 $pager->mLimit = 10;
1280 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1281 $wgOut->addWikiMsg( 'moveddeleted-notice' );
1282 $wgOut->addHTML(
1283 $loglist->beginLogEventsList() .
1284 $pager->getBody() .
1285 $loglist->endLogEventsList()
1287 if( $pager->getNumRows() > 10 ) {
1288 $wgOut->addHTML( $wgUser->getSkin()->link(
1289 SpecialPage::getTitleFor( 'Log' ),
1290 wfMsgHtml( 'log-fulllog' ),
1291 array(),
1292 array( 'page' => $this->mTitle->getPrefixedText() )
1293 ) );
1295 $wgOut->addHTML( '</div>' );
1300 * Should the parser cache be used?
1302 public function useParserCache( $oldid ) {
1303 global $wgUser, $wgEnableParserCache;
1305 return $wgEnableParserCache
1306 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1307 && $this->exists()
1308 && empty( $oldid )
1309 && !$this->mTitle->isCssOrJsPage()
1310 && !$this->mTitle->isCssJsSubpage();
1314 * Execute the uncached parse for action=view
1316 public function doViewParse() {
1317 global $wgOut;
1318 $oldid = $this->getOldID();
1319 $useParserCache = $this->useParserCache( $oldid );
1320 $parserOptions = clone $this->getParserOptions();
1321 # Render printable version, use printable version cache
1322 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1323 # Don't show section-edit links on old revisions... this way lies madness.
1324 $parserOptions->setEditSection( $this->isCurrent() );
1325 $useParserCache = $this->useParserCache( $oldid );
1326 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1330 * Try to fetch an expired entry from the parser cache. If it is present,
1331 * output it and return true. If it is not present, output nothing and
1332 * return false. This is used as a callback function for
1333 * PoolCounter::executeProtected().
1335 public function tryDirtyCache() {
1336 global $wgOut;
1337 $parserCache = ParserCache::singleton();
1338 $options = $this->getParserOptions();
1339 $options->setIsPrintable( $wgOut->isPrintable() );
1340 $output = $parserCache->getDirty( $this, $options );
1341 if ( $output ) {
1342 wfDebug( __METHOD__.": sending dirty output\n" );
1343 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1344 $wgOut->setSquidMaxage( 0 );
1345 $this->mParserOutput = $output;
1346 $wgOut->addParserOutput( $output );
1347 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1348 return true;
1349 } else {
1350 wfDebugLog( 'dirty', "dirty missing\n" );
1351 wfDebug( __METHOD__.": no dirty cache\n" );
1352 return false;
1357 * Show an error page for an error from the pool counter.
1358 * @param $status Status
1360 public function showPoolError( $status ) {
1361 global $wgOut;
1362 $wgOut->clearHTML(); // for release() errors
1363 $wgOut->enableClientCache( false );
1364 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1365 $wgOut->addWikiText(
1366 '<div class="errorbox">' .
1367 $status->getWikiText( false, 'view-pool-error' ) .
1368 '</div>'
1373 * View redirect
1374 * @param $target Title object or Array of destination(s) to redirect
1375 * @param $appendSubtitle Boolean [optional]
1376 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1378 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1379 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1380 # Display redirect
1381 if( !is_array( $target ) ) {
1382 $target = array( $target );
1384 $imageDir = $wgContLang->getDir();
1385 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1386 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1387 $alt2 = $wgContLang->isRTL() ? '&larr;' : '&rarr;'; // should -> and <- be used instead of entities?
1389 if( $appendSubtitle ) {
1390 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1392 $sk = $wgUser->getSkin();
1393 // the loop prepends the arrow image before the link, so the first case needs to be outside
1394 $title = array_shift( $target );
1395 if( $forceKnown ) {
1396 $link = $sk->link(
1397 $title,
1398 htmlspecialchars( $title->getFullText() ),
1399 array(),
1400 array(),
1401 array( 'known', 'noclasses' )
1403 } else {
1404 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1406 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1407 foreach( $target as $rt ) {
1408 if( $forceKnown ) {
1409 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1410 . $sk->link(
1411 $rt,
1412 htmlspecialchars( $rt->getFullText() ),
1413 array(),
1414 array(),
1415 array( 'known', 'noclasses' )
1417 } else {
1418 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1419 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1422 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1423 '<span class="redirectText">'.$link.'</span>';
1427 public function addTrackbacks() {
1428 global $wgOut, $wgUser;
1429 $dbr = wfGetDB( DB_SLAVE );
1430 $tbs = $dbr->select( 'trackbacks',
1431 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1432 array('tb_page' => $this->getID() )
1434 if( !$dbr->numRows($tbs) ) return;
1436 $tbtext = "";
1437 while( $o = $dbr->fetchObject($tbs) ) {
1438 $rmvtxt = "";
1439 if( $wgUser->isAllowed( 'trackback' ) ) {
1440 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" .
1441 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1442 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1444 $tbtext .= "\n";
1445 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1446 $o->tb_title,
1447 $o->tb_url,
1448 $o->tb_ex,
1449 $o->tb_name,
1450 $rmvtxt);
1452 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1453 $this->mTitle->invalidateCache();
1456 public function deletetrackback() {
1457 global $wgUser, $wgRequest, $wgOut;
1458 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1459 $wgOut->addWikiMsg( 'sessionfailure' );
1460 return;
1463 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1464 if( count($permission_errors) ) {
1465 $wgOut->showPermissionsErrorPage( $permission_errors );
1466 return;
1469 $db = wfGetDB( DB_MASTER );
1470 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1472 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1473 $this->mTitle->invalidateCache();
1476 public function render() {
1477 global $wgOut;
1478 $wgOut->setArticleBodyOnly(true);
1479 $this->view();
1483 * Handle action=purge
1485 public function purge() {
1486 global $wgUser, $wgRequest, $wgOut;
1487 if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1488 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1489 $this->doPurge();
1490 $this->view();
1492 } else {
1493 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1494 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1495 $form = "<form method=\"post\" action=\"$action\">\n" .
1496 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1497 "</form>\n";
1498 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1499 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1500 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1501 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1502 $wgOut->addHTML( $top . $form . $bottom );
1507 * Perform the actions of a page purging
1509 public function doPurge() {
1510 global $wgUseSquid;
1511 // Invalidate the cache
1512 $this->mTitle->invalidateCache();
1514 if( $wgUseSquid ) {
1515 // Commit the transaction before the purge is sent
1516 $dbw = wfGetDB( DB_MASTER );
1517 $dbw->immediateCommit();
1519 // Send purge
1520 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1521 $update->doUpdate();
1523 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1524 global $wgMessageCache;
1525 if( $this->getID() == 0 ) {
1526 $text = false;
1527 } else {
1528 $text = $this->getRawText();
1530 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1535 * Insert a new empty page record for this article.
1536 * This *must* be followed up by creating a revision
1537 * and running $this->updateToLatest( $rev_id );
1538 * or else the record will be left in a funky state.
1539 * Best if all done inside a transaction.
1541 * @param $dbw Database
1542 * @return int The newly created page_id key, or false if the title already existed
1543 * @private
1545 public function insertOn( $dbw ) {
1546 wfProfileIn( __METHOD__ );
1548 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1549 $dbw->insert( 'page', array(
1550 'page_id' => $page_id,
1551 'page_namespace' => $this->mTitle->getNamespace(),
1552 'page_title' => $this->mTitle->getDBkey(),
1553 'page_counter' => 0,
1554 'page_restrictions' => '',
1555 'page_is_redirect' => 0, # Will set this shortly...
1556 'page_is_new' => 1,
1557 'page_random' => wfRandom(),
1558 'page_touched' => $dbw->timestamp(),
1559 'page_latest' => 0, # Fill this in shortly...
1560 'page_len' => 0, # Fill this in shortly...
1561 ), __METHOD__, 'IGNORE' );
1563 $affected = $dbw->affectedRows();
1564 if( $affected ) {
1565 $newid = $dbw->insertId();
1566 $this->mTitle->resetArticleId( $newid );
1568 wfProfileOut( __METHOD__ );
1569 return $affected ? $newid : false;
1573 * Update the page record to point to a newly saved revision.
1575 * @param $dbw Database object
1576 * @param $revision Revision: For ID number, and text used to set
1577 length and redirect status fields
1578 * @param $lastRevision Integer: if given, will not overwrite the page field
1579 * when different from the currently set value.
1580 * Giving 0 indicates the new page flag should be set
1581 * on.
1582 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1583 * removing rows in redirect table.
1584 * @return bool true on success, false on failure
1585 * @private
1587 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1588 wfProfileIn( __METHOD__ );
1590 $text = $revision->getText();
1591 $rt = Title::newFromRedirect( $text );
1593 $conditions = array( 'page_id' => $this->getId() );
1594 if( !is_null( $lastRevision ) ) {
1595 # An extra check against threads stepping on each other
1596 $conditions['page_latest'] = $lastRevision;
1599 $dbw->update( 'page',
1600 array( /* SET */
1601 'page_latest' => $revision->getId(),
1602 'page_touched' => $dbw->timestamp(),
1603 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1604 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1605 'page_len' => strlen( $text ),
1607 $conditions,
1608 __METHOD__ );
1610 $result = $dbw->affectedRows() != 0;
1611 if( $result ) {
1612 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1615 wfProfileOut( __METHOD__ );
1616 return $result;
1620 * Add row to the redirect table if this is a redirect, remove otherwise.
1622 * @param $dbw Database
1623 * @param $redirectTitle a title object pointing to the redirect target,
1624 * or NULL if this is not a redirect
1625 * @param $lastRevIsRedirect If given, will optimize adding and
1626 * removing rows in redirect table.
1627 * @return bool true on success, false on failure
1628 * @private
1630 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1631 // Always update redirects (target link might have changed)
1632 // Update/Insert if we don't know if the last revision was a redirect or not
1633 // Delete if changing from redirect to non-redirect
1634 $isRedirect = !is_null($redirectTitle);
1635 if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1636 wfProfileIn( __METHOD__ );
1637 if( $isRedirect ) {
1638 // This title is a redirect, Add/Update row in the redirect table
1639 $set = array( /* SET */
1640 'rd_namespace' => $redirectTitle->getNamespace(),
1641 'rd_title' => $redirectTitle->getDBkey(),
1642 'rd_from' => $this->getId(),
1644 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1645 } else {
1646 // This is not a redirect, remove row from redirect table
1647 $where = array( 'rd_from' => $this->getId() );
1648 $dbw->delete( 'redirect', $where, __METHOD__);
1650 if( $this->getTitle()->getNamespace() == NS_FILE ) {
1651 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1653 wfProfileOut( __METHOD__ );
1654 return ( $dbw->affectedRows() != 0 );
1656 return true;
1660 * If the given revision is newer than the currently set page_latest,
1661 * update the page record. Otherwise, do nothing.
1663 * @param $dbw Database object
1664 * @param $revision Revision object
1666 public function updateIfNewerOn( &$dbw, $revision ) {
1667 wfProfileIn( __METHOD__ );
1668 $row = $dbw->selectRow(
1669 array( 'revision', 'page' ),
1670 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1671 array(
1672 'page_id' => $this->getId(),
1673 'page_latest=rev_id' ),
1674 __METHOD__ );
1675 if( $row ) {
1676 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1677 wfProfileOut( __METHOD__ );
1678 return false;
1680 $prev = $row->rev_id;
1681 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1682 } else {
1683 # No or missing previous revision; mark the page as new
1684 $prev = 0;
1685 $lastRevIsRedirect = null;
1687 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1688 wfProfileOut( __METHOD__ );
1689 return $ret;
1693 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1694 * @return string Complete article text, or null if error
1696 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1697 wfProfileIn( __METHOD__ );
1698 if( strval( $section ) == '' ) {
1699 // Whole-page edit; let the whole text through
1700 } else {
1701 if( is_null($edittime) ) {
1702 $rev = Revision::newFromTitle( $this->mTitle );
1703 } else {
1704 $dbw = wfGetDB( DB_MASTER );
1705 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1707 if( !$rev ) {
1708 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1709 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1710 return null;
1712 $oldtext = $rev->getText();
1714 if( $section == 'new' ) {
1715 # Inserting a new section
1716 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1717 $text = strlen( trim( $oldtext ) ) > 0
1718 ? "{$oldtext}\n\n{$subject}{$text}"
1719 : "{$subject}{$text}";
1720 } else {
1721 # Replacing an existing section; roll out the big guns
1722 global $wgParser;
1723 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1726 wfProfileOut( __METHOD__ );
1727 return $text;
1731 * This function is not deprecated until somebody fixes the core not to use
1732 * it. Nevertheless, use Article::doEdit() instead.
1734 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1735 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1736 ( $isminor ? EDIT_MINOR : 0 ) |
1737 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1738 ( $bot ? EDIT_FORCE_BOT : 0 );
1740 # If this is a comment, add the summary as headline
1741 if( $comment && $summary != "" ) {
1742 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1745 $this->doEdit( $text, $summary, $flags );
1747 $dbw = wfGetDB( DB_MASTER );
1748 if($watchthis) {
1749 if(!$this->mTitle->userIsWatching()) {
1750 $dbw->begin();
1751 $this->doWatch();
1752 $dbw->commit();
1754 } else {
1755 if( $this->mTitle->userIsWatching() ) {
1756 $dbw->begin();
1757 $this->doUnwatch();
1758 $dbw->commit();
1761 $this->doRedirect( $this->isRedirect( $text ) );
1765 * @deprecated use Article::doEdit()
1767 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1768 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1769 ( $minor ? EDIT_MINOR : 0 ) |
1770 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1772 $status = $this->doEdit( $text, $summary, $flags );
1773 if( !$status->isOK() ) {
1774 return false;
1777 $dbw = wfGetDB( DB_MASTER );
1778 if( $watchthis ) {
1779 if(!$this->mTitle->userIsWatching()) {
1780 $dbw->begin();
1781 $this->doWatch();
1782 $dbw->commit();
1784 } else {
1785 if( $this->mTitle->userIsWatching() ) {
1786 $dbw->begin();
1787 $this->doUnwatch();
1788 $dbw->commit();
1792 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1793 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1795 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1796 return true;
1800 * Article::doEdit()
1802 * Change an existing article or create a new article. Updates RC and all necessary caches,
1803 * optionally via the deferred update array.
1805 * $wgUser must be set before calling this function.
1807 * @param $text String: new text
1808 * @param $summary String: edit summary
1809 * @param $flags Integer bitfield:
1810 * EDIT_NEW
1811 * Article is known or assumed to be non-existent, create a new one
1812 * EDIT_UPDATE
1813 * Article is known or assumed to be pre-existing, update it
1814 * EDIT_MINOR
1815 * Mark this edit minor, if the user is allowed to do so
1816 * EDIT_SUPPRESS_RC
1817 * Do not log the change in recentchanges
1818 * EDIT_FORCE_BOT
1819 * Mark the edit a "bot" edit regardless of user rights
1820 * EDIT_DEFER_UPDATES
1821 * Defer some of the updates until the end of index.php
1822 * EDIT_AUTOSUMMARY
1823 * Fill in blank summaries with generated text where possible
1825 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1826 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1827 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1828 * edit-already-exists error will be returned. These two conditions are also possible with
1829 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1831 * @param $baseRevId the revision ID this edit was based off, if any
1832 * @param $user Optional user object, $wgUser will be used if not passed
1834 * @return Status object. Possible errors:
1835 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1836 * edit-gone-missing: In update mode, but the article didn't exist
1837 * edit-conflict: In update mode, the article changed unexpectedly
1838 * edit-no-change: Warning that the text was the same as before
1839 * edit-already-exists: In creation mode, but the article already exists
1841 * Extensions may define additional errors.
1843 * $return->value will contain an associative array with members as follows:
1844 * new: Boolean indicating if the function attempted to create a new article
1845 * revision: The revision object for the inserted revision, or null
1847 * Compatibility note: this function previously returned a boolean value indicating success/failure
1849 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1850 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1852 # Low-level sanity check
1853 if( $this->mTitle->getText() == '' ) {
1854 throw new MWException( 'Something is trying to edit an article with an empty title' );
1857 wfProfileIn( __METHOD__ );
1859 $user = is_null($user) ? $wgUser : $user;
1860 $status = Status::newGood( array() );
1862 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1863 $this->loadPageData();
1865 if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1866 $aid = $this->mTitle->getArticleID();
1867 if( $aid ) {
1868 $flags |= EDIT_UPDATE;
1869 } else {
1870 $flags |= EDIT_NEW;
1874 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1875 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1877 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1878 wfProfileOut( __METHOD__ );
1879 if( $status->isOK() ) {
1880 $status->fatal( 'edit-hook-aborted');
1882 return $status;
1885 # Silently ignore EDIT_MINOR if not allowed
1886 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1887 $bot = $flags & EDIT_FORCE_BOT;
1889 $oldtext = $this->getRawText(); // current revision
1890 $oldsize = strlen( $oldtext );
1892 # Provide autosummaries if one is not provided and autosummaries are enabled.
1893 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1894 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1897 $editInfo = $this->prepareTextForEdit( $text );
1898 $text = $editInfo->pst;
1899 $newsize = strlen( $text );
1901 $dbw = wfGetDB( DB_MASTER );
1902 $now = wfTimestampNow();
1903 $this->mTimestamp=$now;
1905 if( $flags & EDIT_UPDATE ) {
1906 # Update article, but only if changed.
1907 $status->value['new'] = false;
1908 # Make sure the revision is either completely inserted or not inserted at all
1909 if( !$wgDBtransactions ) {
1910 $userAbort = ignore_user_abort( true );
1913 $revisionId = 0;
1915 $changed = ( strcmp( $text, $oldtext ) != 0 );
1917 if( $changed ) {
1918 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1919 - (int)$this->isCountable( $oldtext );
1920 $this->mTotalAdjustment = 0;
1922 if( !$this->mLatest ) {
1923 # Article gone missing
1924 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1925 $status->fatal( 'edit-gone-missing' );
1926 wfProfileOut( __METHOD__ );
1927 return $status;
1930 $revision = new Revision( array(
1931 'page' => $this->getId(),
1932 'comment' => $summary,
1933 'minor_edit' => $isminor,
1934 'text' => $text,
1935 'parent_id' => $this->mLatest,
1936 'user' => $user->getId(),
1937 'user_text' => $user->getName(),
1938 ) );
1940 $dbw->begin();
1941 $revisionId = $revision->insertOn( $dbw );
1943 # Update page
1945 # Note that we use $this->mLatest instead of fetching a value from the master DB
1946 # during the course of this function. This makes sure that EditPage can detect
1947 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1948 # before this function is called. A previous function used a separate query, this
1949 # creates a window where concurrent edits can cause an ignored edit conflict.
1950 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1952 if( !$ok ) {
1953 /* Belated edit conflict! Run away!! */
1954 $status->fatal( 'edit-conflict' );
1955 # Delete the invalid revision if the DB is not transactional
1956 if( !$wgDBtransactions ) {
1957 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1959 $revisionId = 0;
1960 $dbw->rollback();
1961 } else {
1962 global $wgUseRCPatrol;
1963 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1964 # Update recentchanges
1965 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1966 # Mark as patrolled if the user can do so
1967 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
1968 # Add RC row to the DB
1969 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1970 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1971 $revisionId, $patrolled
1973 # Log auto-patrolled edits
1974 if( $patrolled ) {
1975 PatrolLog::record( $rc, true );
1978 $user->incEditCount();
1979 $dbw->commit();
1981 } else {
1982 $status->warning( 'edit-no-change' );
1983 $revision = null;
1984 // Keep the same revision ID, but do some updates on it
1985 $revisionId = $this->getRevIdFetched();
1986 // Update page_touched, this is usually implicit in the page update
1987 // Other cache updates are done in onArticleEdit()
1988 $this->mTitle->invalidateCache();
1991 if( !$wgDBtransactions ) {
1992 ignore_user_abort( $userAbort );
1994 // Now that ignore_user_abort is restored, we can respond to fatal errors
1995 if( !$status->isOK() ) {
1996 wfProfileOut( __METHOD__ );
1997 return $status;
2000 # Invalidate cache of this article and all pages using this article
2001 # as a template. Partly deferred.
2002 Article::onArticleEdit( $this->mTitle );
2003 # Update links tables, site stats, etc.
2004 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2005 } else {
2006 # Create new article
2007 $status->value['new'] = true;
2009 # Set statistics members
2010 # We work out if it's countable after PST to avoid counter drift
2011 # when articles are created with {{subst:}}
2012 $this->mGoodAdjustment = (int)$this->isCountable( $text );
2013 $this->mTotalAdjustment = 1;
2015 $dbw->begin();
2017 # Add the page record; stake our claim on this title!
2018 # This will return false if the article already exists
2019 $newid = $this->insertOn( $dbw );
2021 if( $newid === false ) {
2022 $dbw->rollback();
2023 $status->fatal( 'edit-already-exists' );
2024 wfProfileOut( __METHOD__ );
2025 return $status;
2028 # Save the revision text...
2029 $revision = new Revision( array(
2030 'page' => $newid,
2031 'comment' => $summary,
2032 'minor_edit' => $isminor,
2033 'text' => $text,
2034 'user' => $user->getId(),
2035 'user_text' => $user->getName(),
2036 ) );
2037 $revisionId = $revision->insertOn( $dbw );
2039 $this->mTitle->resetArticleID( $newid );
2041 # Update the page record with revision data
2042 $this->updateRevisionOn( $dbw, $revision, 0 );
2044 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
2045 # Update recentchanges
2046 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
2047 global $wgUseRCPatrol, $wgUseNPPatrol;
2048 # Mark as patrolled if the user can do so
2049 $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
2050 # Add RC row to the DB
2051 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2052 '', strlen($text), $revisionId, $patrolled );
2053 # Log auto-patrolled edits
2054 if( $patrolled ) {
2055 PatrolLog::record( $rc, true );
2058 $user->incEditCount();
2059 $dbw->commit();
2061 # Update links, etc.
2062 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2064 # Clear caches
2065 Article::onArticleCreate( $this->mTitle );
2067 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2068 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
2071 # Do updates right now unless deferral was requested
2072 if( !( $flags & EDIT_DEFER_UPDATES ) ) {
2073 wfDoUpdates();
2076 // Return the new revision (or null) to the caller
2077 $status->value['revision'] = $revision;
2079 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2080 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
2082 wfProfileOut( __METHOD__ );
2083 return $status;
2087 * @deprecated wrapper for doRedirect
2089 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2090 wfDeprecated( __METHOD__ );
2091 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2095 * Output a redirect back to the article.
2096 * This is typically used after an edit.
2098 * @param $noRedir Boolean: add redirect=no
2099 * @param $sectionAnchor String: section to redirect to, including "#"
2100 * @param $extraQuery String: extra query params
2102 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2103 global $wgOut;
2104 if( $noRedir ) {
2105 $query = 'redirect=no';
2106 if( $extraQuery )
2107 $query .= "&$query";
2108 } else {
2109 $query = $extraQuery;
2111 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2115 * Mark this particular edit/page as patrolled
2117 public function markpatrolled() {
2118 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2119 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2121 # If we haven't been given an rc_id value, we can't do anything
2122 $rcid = (int) $wgRequest->getVal('rcid');
2123 $rc = RecentChange::newFromId($rcid);
2124 if( is_null($rc) ) {
2125 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2126 return;
2129 #It would be nice to see where the user had actually come from, but for now just guess
2130 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2131 $return = SpecialPage::getTitleFor( $returnto );
2133 $dbw = wfGetDB( DB_MASTER );
2134 $errors = $rc->doMarkPatrolled();
2136 if( in_array(array('rcpatroldisabled'), $errors) ) {
2137 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2138 return;
2141 if( in_array(array('hookaborted'), $errors) ) {
2142 // The hook itself has handled any output
2143 return;
2146 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
2147 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2148 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2149 $wgOut->returnToMain( false, $return );
2150 return;
2153 if( !empty($errors) ) {
2154 $wgOut->showPermissionsErrorPage( $errors );
2155 return;
2158 # Inform the user
2159 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2160 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
2161 $wgOut->returnToMain( false, $return );
2165 * User-interface handler for the "watch" action
2168 public function watch() {
2169 global $wgUser, $wgOut;
2170 if( $wgUser->isAnon() ) {
2171 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2172 return;
2174 if( wfReadOnly() ) {
2175 $wgOut->readOnlyPage();
2176 return;
2178 if( $this->doWatch() ) {
2179 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2180 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2181 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2183 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2187 * Add this page to $wgUser's watchlist
2188 * @return bool true on successful watch operation
2190 public function doWatch() {
2191 global $wgUser;
2192 if( $wgUser->isAnon() ) {
2193 return false;
2195 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
2196 $wgUser->addWatch( $this->mTitle );
2197 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
2199 return false;
2203 * User interface handler for the "unwatch" action.
2205 public function unwatch() {
2206 global $wgUser, $wgOut;
2207 if( $wgUser->isAnon() ) {
2208 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2209 return;
2211 if( wfReadOnly() ) {
2212 $wgOut->readOnlyPage();
2213 return;
2215 if( $this->doUnwatch() ) {
2216 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2217 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2218 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2220 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2224 * Stop watching a page
2225 * @return bool true on successful unwatch
2227 public function doUnwatch() {
2228 global $wgUser;
2229 if( $wgUser->isAnon() ) {
2230 return false;
2232 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
2233 $wgUser->removeWatch( $this->mTitle );
2234 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
2236 return false;
2240 * action=protect handler
2242 public function protect() {
2243 $form = new ProtectionForm( $this );
2244 $form->execute();
2248 * action=unprotect handler (alias)
2250 public function unprotect() {
2251 $this->protect();
2255 * Update the article's restriction field, and leave a log entry.
2257 * @param $limit Array: set of restriction keys
2258 * @param $reason String
2259 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2260 * @param $expiry Array: per restriction type expiration
2261 * @return bool true on success
2263 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2264 global $wgUser, $wgRestrictionTypes, $wgContLang;
2266 $id = $this->mTitle->getArticleID();
2267 if ( $id <= 0 ) {
2268 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2269 return false;
2272 if ( wfReadOnly() ) {
2273 wfDebug( "updateRestrictions failed: read-only\n" );
2274 return false;
2277 if ( !$this->mTitle->userCan( 'protect' ) ) {
2278 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2279 return false;
2282 if( !$cascade ) {
2283 $cascade = false;
2286 // Take this opportunity to purge out expired restrictions
2287 Title::purgeExpiredRestrictions();
2289 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2290 # we expect a single selection, but the schema allows otherwise.
2291 $current = array();
2292 $updated = Article::flattenRestrictions( $limit );
2293 $changed = false;
2294 foreach( $wgRestrictionTypes as $action ) {
2295 if( isset( $expiry[$action] ) ) {
2296 # Get current restrictions on $action
2297 $aLimits = $this->mTitle->getRestrictions( $action );
2298 $current[$action] = implode( '', $aLimits );
2299 # Are any actual restrictions being dealt with here?
2300 $aRChanged = count($aLimits) || !empty($limit[$action]);
2301 # If something changed, we need to log it. Checking $aRChanged
2302 # assures that "unprotecting" a page that is not protected does
2303 # not log just because the expiry was "changed".
2304 if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2305 $changed = true;
2310 $current = Article::flattenRestrictions( $current );
2312 $changed = ($changed || $current != $updated );
2313 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
2314 $protect = ( $updated != '' );
2316 # If nothing's changed, do nothing
2317 if( $changed ) {
2318 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2320 $dbw = wfGetDB( DB_MASTER );
2322 # Prepare a null revision to be added to the history
2323 $modified = $current != '' && $protect;
2324 if( $protect ) {
2325 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2326 } else {
2327 $comment_type = 'unprotectedarticle';
2329 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2331 # Only restrictions with the 'protect' right can cascade...
2332 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2333 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2334 # The schema allows multiple restrictions
2335 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2336 $cascade = false;
2337 $cascade_description = '';
2338 if( $cascade ) {
2339 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2342 if( $reason )
2343 $comment .= ": $reason";
2345 $editComment = $comment;
2346 $encodedExpiry = array();
2347 $protect_description = '';
2348 foreach( $limit as $action => $restrictions ) {
2349 if ( !isset($expiry[$action]) )
2350 $expiry[$action] = 'infinite';
2352 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
2353 if( $restrictions != '' ) {
2354 $protect_description .= "[$action=$restrictions] (";
2355 if( $encodedExpiry[$action] != 'infinity' ) {
2356 $protect_description .= wfMsgForContent( 'protect-expiring',
2357 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2358 $wgContLang->date( $expiry[$action], false, false ) ,
2359 $wgContLang->time( $expiry[$action], false, false ) );
2360 } else {
2361 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2363 $protect_description .= ') ';
2366 $protect_description = trim($protect_description);
2368 if( $protect_description && $protect )
2369 $editComment .= " ($protect_description)";
2370 if( $cascade )
2371 $editComment .= "$cascade_description";
2372 # Update restrictions table
2373 foreach( $limit as $action => $restrictions ) {
2374 if($restrictions != '' ) {
2375 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2376 array( 'pr_page' => $id,
2377 'pr_type' => $action,
2378 'pr_level' => $restrictions,
2379 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
2380 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
2381 } else {
2382 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2383 'pr_type' => $action ), __METHOD__ );
2387 # Insert a null revision
2388 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2389 $nullRevId = $nullRevision->insertOn( $dbw );
2391 $latest = $this->getLatest();
2392 # Update page record
2393 $dbw->update( 'page',
2394 array( /* SET */
2395 'page_touched' => $dbw->timestamp(),
2396 'page_restrictions' => '',
2397 'page_latest' => $nullRevId
2398 ), array( /* WHERE */
2399 'page_id' => $id
2400 ), 'Article::protect'
2403 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2404 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2406 # Update the protection log
2407 $log = new LogPage( 'protect' );
2408 if( $protect ) {
2409 $params = array($protect_description,$cascade ? 'cascade' : '');
2410 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
2411 } else {
2412 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2415 } # End hook
2416 } # End "changed" check
2418 return true;
2422 * Take an array of page restrictions and flatten it to a string
2423 * suitable for insertion into the page_restrictions field.
2424 * @param $limit Array
2425 * @return String
2427 protected static function flattenRestrictions( $limit ) {
2428 if( !is_array( $limit ) ) {
2429 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2431 $bits = array();
2432 ksort( $limit );
2433 foreach( $limit as $action => $restrictions ) {
2434 if( $restrictions != '' ) {
2435 $bits[] = "$action=$restrictions";
2438 return implode( ':', $bits );
2442 * Auto-generates a deletion reason
2443 * @param &$hasHistory Boolean: whether the page has a history
2445 public function generateReason( &$hasHistory ) {
2446 global $wgContLang;
2447 $dbw = wfGetDB( DB_MASTER );
2448 // Get the last revision
2449 $rev = Revision::newFromTitle( $this->mTitle );
2450 if( is_null( $rev ) )
2451 return false;
2453 // Get the article's contents
2454 $contents = $rev->getText();
2455 $blank = false;
2456 // If the page is blank, use the text from the previous revision,
2457 // which can only be blank if there's a move/import/protect dummy revision involved
2458 if( $contents == '' ) {
2459 $prev = $rev->getPrevious();
2460 if( $prev ) {
2461 $contents = $prev->getText();
2462 $blank = true;
2466 // Find out if there was only one contributor
2467 // Only scan the last 20 revisions
2468 $res = $dbw->select( 'revision', 'rev_user_text',
2469 array( 'rev_page' => $this->getID(), $dbw->bitAnd('rev_deleted', Revision::DELETED_USER) . ' = 0' ),
2470 __METHOD__,
2471 array( 'LIMIT' => 20 )
2473 if( $res === false )
2474 // This page has no revisions, which is very weird
2475 return false;
2477 $hasHistory = ( $res->numRows() > 1 );
2478 $row = $dbw->fetchObject( $res );
2479 $onlyAuthor = $row->rev_user_text;
2480 // Try to find a second contributor
2481 foreach( $res as $row ) {
2482 if( $row->rev_user_text != $onlyAuthor ) {
2483 $onlyAuthor = false;
2484 break;
2487 $dbw->freeResult( $res );
2489 // Generate the summary with a '$1' placeholder
2490 if( $blank ) {
2491 // The current revision is blank and the one before is also
2492 // blank. It's just not our lucky day
2493 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2494 } else {
2495 if( $onlyAuthor )
2496 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2497 else
2498 $reason = wfMsgForContent( 'excontent', '$1' );
2501 if( $reason == '-' ) {
2502 // Allow these UI messages to be blanked out cleanly
2503 return '';
2506 // Replace newlines with spaces to prevent uglyness
2507 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2508 // Calculate the maximum amount of chars to get
2509 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2510 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2511 $contents = $wgContLang->truncate( $contents, $maxLength );
2512 // Remove possible unfinished links
2513 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2514 // Now replace the '$1' placeholder
2515 $reason = str_replace( '$1', $contents, $reason );
2516 return $reason;
2521 * UI entry point for page deletion
2523 public function delete() {
2524 global $wgUser, $wgOut, $wgRequest;
2526 $confirm = $wgRequest->wasPosted() &&
2527 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2529 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2530 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2532 $reason = $this->DeleteReasonList;
2534 if( $reason != 'other' && $this->DeleteReason != '' ) {
2535 // Entry from drop down menu + additional comment
2536 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2537 } elseif( $reason == 'other' ) {
2538 $reason = $this->DeleteReason;
2540 # Flag to hide all contents of the archived revisions
2541 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2543 # This code desperately needs to be totally rewritten
2545 # Read-only check...
2546 if( wfReadOnly() ) {
2547 $wgOut->readOnlyPage();
2548 return;
2551 # Check permissions
2552 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2554 if( count( $permission_errors ) > 0 ) {
2555 $wgOut->showPermissionsErrorPage( $permission_errors );
2556 return;
2559 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2561 # Better double-check that it hasn't been deleted yet!
2562 $dbw = wfGetDB( DB_MASTER );
2563 $conds = $this->mTitle->pageCond();
2564 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2565 if( $latest === false ) {
2566 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2567 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2568 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2569 return;
2572 # Hack for big sites
2573 $bigHistory = $this->isBigDeletion();
2574 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2575 global $wgLang, $wgDeleteRevisionsLimit;
2576 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2577 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2578 return;
2581 if( $confirm ) {
2582 $this->doDelete( $reason, $suppress );
2583 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2584 $this->doWatch();
2585 } elseif( $this->mTitle->userIsWatching() ) {
2586 $this->doUnwatch();
2588 return;
2591 // Generate deletion reason
2592 $hasHistory = false;
2593 if( !$reason ) $reason = $this->generateReason($hasHistory);
2595 // If the page has a history, insert a warning
2596 if( $hasHistory && !$confirm ) {
2597 $skin = $wgUser->getSkin();
2598 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2599 if( $bigHistory ) {
2600 global $wgLang, $wgDeleteRevisionsLimit;
2601 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2602 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2606 return $this->confirmDelete( $reason );
2610 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2612 public function isBigDeletion() {
2613 global $wgDeleteRevisionsLimit;
2614 if( $wgDeleteRevisionsLimit ) {
2615 $revCount = $this->estimateRevisionCount();
2616 return $revCount > $wgDeleteRevisionsLimit;
2618 return false;
2622 * @return int approximate revision count
2624 public function estimateRevisionCount() {
2625 $dbr = wfGetDB( DB_SLAVE );
2626 // For an exact count...
2627 //return $dbr->selectField( 'revision', 'COUNT(*)',
2628 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2629 return $dbr->estimateRowCount( 'revision', '*',
2630 array( 'rev_page' => $this->getId() ), __METHOD__ );
2634 * Get the last N authors
2635 * @param $num Integer: number of revisions to get
2636 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2637 * @return array Array of authors, duplicates not removed
2639 public function getLastNAuthors( $num, $revLatest = 0 ) {
2640 wfProfileIn( __METHOD__ );
2641 // First try the slave
2642 // If that doesn't have the latest revision, try the master
2643 $continue = 2;
2644 $db = wfGetDB( DB_SLAVE );
2645 do {
2646 $res = $db->select( array( 'page', 'revision' ),
2647 array( 'rev_id', 'rev_user_text' ),
2648 array(
2649 'page_namespace' => $this->mTitle->getNamespace(),
2650 'page_title' => $this->mTitle->getDBkey(),
2651 'rev_page = page_id'
2652 ), __METHOD__, $this->getSelectOptions( array(
2653 'ORDER BY' => 'rev_timestamp DESC',
2654 'LIMIT' => $num
2657 if( !$res ) {
2658 wfProfileOut( __METHOD__ );
2659 return array();
2661 $row = $db->fetchObject( $res );
2662 if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2663 $db = wfGetDB( DB_MASTER );
2664 $continue--;
2665 } else {
2666 $continue = 0;
2668 } while ( $continue );
2670 $authors = array( $row->rev_user_text );
2671 while ( $row = $db->fetchObject( $res ) ) {
2672 $authors[] = $row->rev_user_text;
2674 wfProfileOut( __METHOD__ );
2675 return $authors;
2679 * Output deletion confirmation dialog
2680 * @param $reason String: prefilled reason
2682 public function confirmDelete( $reason ) {
2683 global $wgOut, $wgUser;
2685 wfDebug( "Article::confirmDelete\n" );
2687 $deleteBackLink = $wgUser->getSkin()->link(
2688 $this->mTitle,
2689 null,
2690 array(),
2691 array(),
2692 array( 'known', 'noclasses' )
2694 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2695 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2696 $wgOut->addWikiMsg( 'confirmdeletetext' );
2698 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2700 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2701 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2702 <td></td>
2703 <td class='mw-input'><strong>" .
2704 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2705 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2706 "</strong></td>
2707 </tr>";
2708 } else {
2709 $suppress = '';
2711 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2713 $form = Xml::openElement( 'form', array( 'method' => 'post',
2714 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2715 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2716 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2717 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2718 "<tr id=\"wpDeleteReasonListRow\">
2719 <td class='mw-label'>" .
2720 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2721 "</td>
2722 <td class='mw-input'>" .
2723 Xml::listDropDown( 'wpDeleteReasonList',
2724 wfMsgForContent( 'deletereason-dropdown' ),
2725 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2726 "</td>
2727 </tr>
2728 <tr id=\"wpDeleteReasonRow\">
2729 <td class='mw-label'>" .
2730 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2731 "</td>
2732 <td class='mw-input'>" .
2733 Html::input( 'wpReason', $reason, 'text', array(
2734 'size' => '60',
2735 'maxlength' => '255',
2736 'tabindex' => '2',
2737 'id' => 'wpReason',
2738 'autofocus'
2739 ) ) .
2740 "</td>
2741 </tr>
2742 <tr>
2743 <td></td>
2744 <td class='mw-input'>" .
2745 Xml::checkLabel( wfMsg( 'watchthis' ),
2746 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2747 "</td>
2748 </tr>
2749 $suppress
2750 <tr>
2751 <td></td>
2752 <td class='mw-submit'>" .
2753 Xml::submitButton( wfMsg( 'deletepage' ),
2754 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2755 "</td>
2756 </tr>" .
2757 Xml::closeElement( 'table' ) .
2758 Xml::closeElement( 'fieldset' ) .
2759 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2760 Xml::closeElement( 'form' );
2762 if( $wgUser->isAllowed( 'editinterface' ) ) {
2763 $skin = $wgUser->getSkin();
2764 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2765 $link = $skin->link(
2766 $title,
2767 wfMsgHtml( 'delete-edit-reasonlist' ),
2768 array(),
2769 array( 'action' => 'edit' )
2771 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2774 $wgOut->addHTML( $form );
2775 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2776 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2780 * Perform a deletion and output success or failure messages
2782 public function doDelete( $reason, $suppress = false ) {
2783 global $wgOut, $wgUser;
2784 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2786 $error = '';
2787 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2788 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2789 $deleted = $this->mTitle->getPrefixedText();
2791 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2792 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2794 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2796 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2797 $wgOut->returnToMain( false );
2798 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2800 } else {
2801 if( $error == '' ) {
2802 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2803 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2804 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2805 } else {
2806 $wgOut->showFatalError( $error );
2812 * Back-end article deletion
2813 * Deletes the article with database consistency, writes logs, purges caches
2814 * Returns success
2816 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2817 global $wgUseSquid, $wgDeferredUpdateList;
2818 global $wgUseTrackbacks;
2820 wfDebug( __METHOD__."\n" );
2822 $dbw = wfGetDB( DB_MASTER );
2823 $ns = $this->mTitle->getNamespace();
2824 $t = $this->mTitle->getDBkey();
2825 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2827 if( $t == '' || $id == 0 ) {
2828 return false;
2831 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2832 array_push( $wgDeferredUpdateList, $u );
2834 // Bitfields to further suppress the content
2835 if( $suppress ) {
2836 $bitfield = 0;
2837 // This should be 15...
2838 $bitfield |= Revision::DELETED_TEXT;
2839 $bitfield |= Revision::DELETED_COMMENT;
2840 $bitfield |= Revision::DELETED_USER;
2841 $bitfield |= Revision::DELETED_RESTRICTED;
2842 } else {
2843 $bitfield = 'rev_deleted';
2846 $dbw->begin();
2847 // For now, shunt the revision data into the archive table.
2848 // Text is *not* removed from the text table; bulk storage
2849 // is left intact to avoid breaking block-compression or
2850 // immutable storage schemes.
2852 // For backwards compatibility, note that some older archive
2853 // table entries will have ar_text and ar_flags fields still.
2855 // In the future, we may keep revisions and mark them with
2856 // the rev_deleted field, which is reserved for this purpose.
2857 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2858 array(
2859 'ar_namespace' => 'page_namespace',
2860 'ar_title' => 'page_title',
2861 'ar_comment' => 'rev_comment',
2862 'ar_user' => 'rev_user',
2863 'ar_user_text' => 'rev_user_text',
2864 'ar_timestamp' => 'rev_timestamp',
2865 'ar_minor_edit' => 'rev_minor_edit',
2866 'ar_rev_id' => 'rev_id',
2867 'ar_text_id' => 'rev_text_id',
2868 'ar_text' => '\'\'', // Be explicit to appease
2869 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2870 'ar_len' => 'rev_len',
2871 'ar_page_id' => 'page_id',
2872 'ar_deleted' => $bitfield
2873 ), array(
2874 'page_id' => $id,
2875 'page_id = rev_page'
2876 ), __METHOD__
2879 # Delete restrictions for it
2880 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2882 # Now that it's safely backed up, delete it
2883 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2884 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2885 if( !$ok ) {
2886 $dbw->rollback();
2887 return false;
2890 # Fix category table counts
2891 $cats = array();
2892 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2893 foreach( $res as $row ) {
2894 $cats []= $row->cl_to;
2896 $this->updateCategoryCounts( array(), $cats );
2898 # If using cascading deletes, we can skip some explicit deletes
2899 if( !$dbw->cascadingDeletes() ) {
2900 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2902 if($wgUseTrackbacks)
2903 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2905 # Delete outgoing links
2906 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2907 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2908 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2909 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2910 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2911 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2912 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2915 # If using cleanup triggers, we can skip some manual deletes
2916 if( !$dbw->cleanupTriggers() ) {
2917 # Clean up recentchanges entries...
2918 $dbw->delete( 'recentchanges',
2919 array( 'rc_type != '.RC_LOG,
2920 'rc_namespace' => $this->mTitle->getNamespace(),
2921 'rc_title' => $this->mTitle->getDBkey() ),
2922 __METHOD__ );
2923 $dbw->delete( 'recentchanges',
2924 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2925 __METHOD__ );
2928 # Clear caches
2929 Article::onArticleDelete( $this->mTitle );
2931 # Clear the cached article id so the interface doesn't act like we exist
2932 $this->mTitle->resetArticleID( 0 );
2934 # Log the deletion, if the page was suppressed, log it at Oversight instead
2935 $logtype = $suppress ? 'suppress' : 'delete';
2936 $log = new LogPage( $logtype );
2938 # Make sure logging got through
2939 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2941 $dbw->commit();
2943 return true;
2947 * Roll back the most recent consecutive set of edits to a page
2948 * from the same user; fails if there are no eligible edits to
2949 * roll back to, e.g. user is the sole contributor. This function
2950 * performs permissions checks on $wgUser, then calls commitRollback()
2951 * to do the dirty work
2953 * @param $fromP String: Name of the user whose edits to rollback.
2954 * @param $summary String: Custom summary. Set to default summary if empty.
2955 * @param $token String: Rollback token.
2956 * @param $bot Boolean: If true, mark all reverted edits as bot.
2958 * @param $resultDetails Array: contains result-specific array of additional values
2959 * 'alreadyrolled' : 'current' (rev)
2960 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2962 * @return array of errors, each error formatted as
2963 * array(messagekey, param1, param2, ...).
2964 * On success, the array is empty. This array can also be passed to
2965 * OutputPage::showPermissionsErrorPage().
2967 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2968 global $wgUser;
2969 $resultDetails = null;
2971 # Check permissions
2972 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
2973 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
2974 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2976 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2977 $errors[] = array( 'sessionfailure' );
2979 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2980 $errors[] = array( 'actionthrottledtext' );
2982 # If there were errors, bail out now
2983 if( !empty( $errors ) )
2984 return $errors;
2986 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2990 * Backend implementation of doRollback(), please refer there for parameter
2991 * and return value documentation
2993 * NOTE: This function does NOT check ANY permissions, it just commits the
2994 * rollback to the DB Therefore, you should only call this function direct-
2995 * ly if you want to use custom permissions checks. If you don't, use
2996 * doRollback() instead.
2998 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2999 global $wgUseRCPatrol, $wgUser, $wgLang;
3000 $dbw = wfGetDB( DB_MASTER );
3002 if( wfReadOnly() ) {
3003 return array( array( 'readonlytext' ) );
3006 # Get the last editor
3007 $current = Revision::newFromTitle( $this->mTitle );
3008 if( is_null( $current ) ) {
3009 # Something wrong... no page?
3010 return array(array('notanarticle'));
3013 $from = str_replace( '_', ' ', $fromP );
3014 # User name given should match up with the top revision.
3015 # If the user was deleted then $from should be empty.
3016 if( $from != $current->getUserText() ) {
3017 $resultDetails = array( 'current' => $current );
3018 return array(array('alreadyrolled',
3019 htmlspecialchars($this->mTitle->getPrefixedText()),
3020 htmlspecialchars($fromP),
3021 htmlspecialchars($current->getUserText())
3025 # Get the last edit not by this guy...
3026 # Note: these may not be public values
3027 $user = intval( $current->getRawUser() );
3028 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3029 $s = $dbw->selectRow( 'revision',
3030 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3031 array( 'rev_page' => $current->getPage(),
3032 "rev_user != {$user} OR rev_user_text != {$user_text}"
3033 ), __METHOD__,
3034 array( 'USE INDEX' => 'page_timestamp',
3035 'ORDER BY' => 'rev_timestamp DESC' )
3037 if( $s === false ) {
3038 # No one else ever edited this page
3039 return array(array('cantrollback'));
3040 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
3041 # Only admins can see this text
3042 return array(array('notvisiblerev'));
3045 $set = array();
3046 if( $bot && $wgUser->isAllowed('markbotedits') ) {
3047 # Mark all reverted edits as bot
3048 $set['rc_bot'] = 1;
3050 if( $wgUseRCPatrol ) {
3051 # Mark all reverted edits as patrolled
3052 $set['rc_patrolled'] = 1;
3055 if( count($set) ) {
3056 $dbw->update( 'recentchanges', $set,
3057 array( /* WHERE */
3058 'rc_cur_id' => $current->getPage(),
3059 'rc_user_text' => $current->getUserText(),
3060 "rc_timestamp > '{$s->rev_timestamp}'",
3061 ), __METHOD__
3065 # Generate the edit summary if necessary
3066 $target = Revision::newFromId( $s->rev_id );
3067 if( empty( $summary ) ) {
3068 if( $from == '' ) { // no public user name
3069 $summary = wfMsgForContent( 'revertpage-nouser' );
3070 } else {
3071 $summary = wfMsgForContent( 'revertpage' );
3075 # Allow the custom summary to use the same args as the default message
3076 $args = array(
3077 $target->getUserText(), $from, $s->rev_id,
3078 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
3079 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
3081 $summary = wfMsgReplaceArgs( $summary, $args );
3083 # Save
3084 $flags = EDIT_UPDATE;
3086 if( $wgUser->isAllowed('minoredit') )
3087 $flags |= EDIT_MINOR;
3089 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
3090 $flags |= EDIT_FORCE_BOT;
3091 # Actually store the edit
3092 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3093 if( !empty( $status->value['revision'] ) ) {
3094 $revId = $status->value['revision']->getId();
3095 } else {
3096 $revId = false;
3099 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3101 $resultDetails = array(
3102 'summary' => $summary,
3103 'current' => $current,
3104 'target' => $target,
3105 'newid' => $revId
3107 return array();
3111 * User interface for rollback operations
3113 public function rollback() {
3114 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3115 $details = null;
3117 $result = $this->doRollback(
3118 $wgRequest->getVal( 'from' ),
3119 $wgRequest->getText( 'summary' ),
3120 $wgRequest->getVal( 'token' ),
3121 $wgRequest->getBool( 'bot' ),
3122 $details
3125 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
3126 $wgOut->rateLimited();
3127 return;
3129 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3130 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3131 $errArray = $result[0];
3132 $errMsg = array_shift( $errArray );
3133 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3134 if( isset( $details['current'] ) ){
3135 $current = $details['current'];
3136 if( $current->getComment() != '' ) {
3137 $wgOut->addWikiMsgArray( 'editcomment', array(
3138 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3141 return;
3143 # Display permissions errors before read-only message -- there's no
3144 # point in misleading the user into thinking the inability to rollback
3145 # is only temporary.
3146 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3147 # array_diff is completely broken for arrays of arrays, sigh. Re-
3148 # move any 'readonlytext' error manually.
3149 $out = array();
3150 foreach( $result as $error ) {
3151 if( $error != array( 'readonlytext' ) ) {
3152 $out []= $error;
3155 $wgOut->showPermissionsErrorPage( $out );
3156 return;
3158 if( $result == array( array( 'readonlytext' ) ) ) {
3159 $wgOut->readOnlyPage();
3160 return;
3163 $current = $details['current'];
3164 $target = $details['target'];
3165 $newId = $details['newid'];
3166 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3167 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3168 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3169 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3170 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3171 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3172 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3173 $wgOut->returnToMain( false, $this->mTitle );
3175 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3176 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3177 $de->showDiff( '', '' );
3183 * Do standard deferred updates after page view
3185 public function viewUpdates() {
3186 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3187 if ( wfReadOnly() ) {
3188 return;
3190 # Don't update page view counters on views from bot users (bug 14044)
3191 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
3192 Article::incViewCount( $this->getID() );
3193 $u = new SiteStatsUpdate( 1, 0, 0 );
3194 array_push( $wgDeferredUpdateList, $u );
3196 # Update newtalk / watchlist notification status
3197 $wgUser->clearNotification( $this->mTitle );
3201 * Prepare text which is about to be saved.
3202 * Returns a stdclass with source, pst and output members
3204 public function prepareTextForEdit( $text, $revid=null ) {
3205 if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
3206 // Already prepared
3207 return $this->mPreparedEdit;
3209 global $wgParser;
3210 $edit = (object)array();
3211 $edit->revid = $revid;
3212 $edit->newText = $text;
3213 $edit->pst = $this->preSaveTransform( $text );
3214 $options = $this->getParserOptions();
3215 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3216 $edit->oldText = $this->getContent();
3217 $this->mPreparedEdit = $edit;
3218 return $edit;
3222 * Do standard deferred updates after page edit.
3223 * Update links tables, site stats, search index and message cache.
3224 * Purges pages that include this page if the text was changed here.
3225 * Every 100th edit, prune the recent changes table.
3227 * @private
3228 * @param $text New text of the article
3229 * @param $summary Edit summary
3230 * @param $minoredit Minor edit
3231 * @param $timestamp_of_pagechange Timestamp associated with the page change
3232 * @param $newid rev_id value of the new revision
3233 * @param $changed Whether or not the content actually changed
3235 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3236 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
3238 wfProfileIn( __METHOD__ );
3240 # Parse the text
3241 # Be careful not to double-PST: $text is usually already PST-ed once
3242 if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3243 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3244 $editInfo = $this->prepareTextForEdit( $text, $newid );
3245 } else {
3246 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3247 $editInfo = $this->mPreparedEdit;
3250 # Save it to the parser cache
3251 if( $wgEnableParserCache ) {
3252 $popts = $this->getParserOptions();
3253 $parserCache = ParserCache::singleton();
3254 $parserCache->save( $editInfo->output, $this, $popts );
3257 # Update the links tables
3258 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3259 $u->doUpdate();
3261 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3263 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3264 if( 0 == mt_rand( 0, 99 ) ) {
3265 // Flush old entries from the `recentchanges` table; we do this on
3266 // random requests so as to avoid an increase in writes for no good reason
3267 global $wgRCMaxAge;
3268 $dbw = wfGetDB( DB_MASTER );
3269 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3270 $recentchanges = $dbw->tableName( 'recentchanges' );
3271 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3272 $dbw->query( $sql );
3276 $id = $this->getID();
3277 $title = $this->mTitle->getPrefixedDBkey();
3278 $shortTitle = $this->mTitle->getDBkey();
3280 if( 0 == $id ) {
3281 wfProfileOut( __METHOD__ );
3282 return;
3285 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3286 array_push( $wgDeferredUpdateList, $u );
3287 $u = new SearchUpdate( $id, $title, $text );
3288 array_push( $wgDeferredUpdateList, $u );
3290 # If this is another user's talk page, update newtalk
3291 # Don't do this if $changed = false otherwise some idiot can null-edit a
3292 # load of user talk pages and piss people off, nor if it's a minor edit
3293 # by a properly-flagged bot.
3294 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3295 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3296 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3297 $other = User::newFromName( $shortTitle, false );
3298 if( !$other ) {
3299 wfDebug( __METHOD__.": invalid username\n" );
3300 } elseif( User::isIP( $shortTitle ) ) {
3301 // An anonymous user
3302 $other->setNewtalk( true );
3303 } elseif( $other->isLoggedIn() ) {
3304 $other->setNewtalk( true );
3305 } else {
3306 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
3311 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3312 $wgMessageCache->replace( $shortTitle, $text );
3315 wfProfileOut( __METHOD__ );
3319 * Perform article updates on a special page creation.
3321 * @param $rev Revision object
3323 * @todo This is a shitty interface function. Kill it and replace the
3324 * other shitty functions like editUpdates and such so it's not needed
3325 * anymore.
3327 public function createUpdates( $rev ) {
3328 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3329 $this->mTotalAdjustment = 1;
3330 $this->editUpdates( $rev->getText(), $rev->getComment(),
3331 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3335 * Generate the navigation links when browsing through an article revisions
3336 * It shows the information as:
3337 * Revision as of \<date\>; view current revision
3338 * \<- Previous version | Next Version -\>
3340 * @param $oldid String: revision ID of this article revision
3342 public function setOldSubtitle( $oldid = 0 ) {
3343 global $wgLang, $wgOut, $wgUser, $wgRequest;
3345 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3346 return;
3349 $revision = Revision::newFromId( $oldid );
3351 $current = ( $oldid == $this->mLatest );
3352 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3353 $tddate = $wgLang->date( $this->mTimestamp, true );
3354 $tdtime = $wgLang->time( $this->mTimestamp, true );
3355 $sk = $wgUser->getSkin();
3356 $lnk = $current
3357 ? wfMsgHtml( 'currentrevisionlink' )
3358 : $sk->link(
3359 $this->mTitle,
3360 wfMsgHtml( 'currentrevisionlink' ),
3361 array(),
3362 array(),
3363 array( 'known', 'noclasses' )
3365 $curdiff = $current
3366 ? wfMsgHtml( 'diff' )
3367 : $sk->link(
3368 $this->mTitle,
3369 wfMsgHtml( 'diff' ),
3370 array(),
3371 array(
3372 'diff' => 'cur',
3373 'oldid' => $oldid
3375 array( 'known', 'noclasses' )
3377 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3378 $prevlink = $prev
3379 ? $sk->link(
3380 $this->mTitle,
3381 wfMsgHtml( 'previousrevision' ),
3382 array(),
3383 array(
3384 'direction' => 'prev',
3385 'oldid' => $oldid
3387 array( 'known', 'noclasses' )
3389 : wfMsgHtml( 'previousrevision' );
3390 $prevdiff = $prev
3391 ? $sk->link(
3392 $this->mTitle,
3393 wfMsgHtml( 'diff' ),
3394 array(),
3395 array(
3396 'diff' => 'prev',
3397 'oldid' => $oldid
3399 array( 'known', 'noclasses' )
3401 : wfMsgHtml( 'diff' );
3402 $nextlink = $current
3403 ? wfMsgHtml( 'nextrevision' )
3404 : $sk->link(
3405 $this->mTitle,
3406 wfMsgHtml( 'nextrevision' ),
3407 array(),
3408 array(
3409 'direction' => 'next',
3410 'oldid' => $oldid
3412 array( 'known', 'noclasses' )
3414 $nextdiff = $current
3415 ? wfMsgHtml( 'diff' )
3416 : $sk->link(
3417 $this->mTitle,
3418 wfMsgHtml( 'diff' ),
3419 array(),
3420 array(
3421 'diff' => 'next',
3422 'oldid' => $oldid
3424 array( 'known', 'noclasses' )
3427 $cdel='';
3428 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3429 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
3430 if( $revision->isCurrent() ) {
3431 // We don't handle top deleted edits too well
3432 $cdel = wfMsgHtml( 'rev-delundel' );
3433 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3434 // If revision was hidden from sysops
3435 $cdel = wfMsgHtml( 'rev-delundel' );
3436 } else {
3437 $cdel = $sk->link(
3438 $revdel,
3439 wfMsgHtml('rev-delundel'),
3440 array(),
3441 array(
3442 'type' => 'revision',
3443 'target' => urlencode( $this->mTitle->getPrefixedDbkey() ),
3444 'ids' => urlencode( $oldid )
3446 array( 'known', 'noclasses' )
3448 // Bolden oversighted content
3449 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
3450 $cdel = "<strong>$cdel</strong>";
3452 $cdel = "(<small>$cdel</small>) ";
3454 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3455 # Show user links if allowed to see them. If hidden, then show them only if requested...
3456 $userlinks = $sk->revUserTools( $revision, !$unhide );
3458 $m = wfMsg( 'revision-info-current' );
3459 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3460 ? 'revision-info-current'
3461 : 'revision-info';
3463 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3464 wfMsgExt(
3465 $infomsg,
3466 array( 'parseinline', 'replaceafter' ),
3467 $td,
3468 $userlinks,
3469 $revision->getID(),
3470 $tddate,
3471 $tdtime,
3472 $revision->getUser()
3474 "</div>\n" .
3475 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3476 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3477 $wgOut->setSubtitle( $r );
3481 * This function is called right before saving the wikitext,
3482 * so we can do things like signatures and links-in-context.
3484 * @param $text String
3486 public function preSaveTransform( $text ) {
3487 global $wgParser, $wgUser;
3488 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3491 /* Caching functions */
3494 * checkLastModified returns true if it has taken care of all
3495 * output to the client that is necessary for this request.
3496 * (that is, it has sent a cached version of the page)
3498 protected function tryFileCache() {
3499 static $called = false;
3500 if( $called ) {
3501 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3502 return false;
3504 $called = true;
3505 if( $this->isFileCacheable() ) {
3506 $cache = new HTMLFileCache( $this->mTitle );
3507 if( $cache->isFileCacheGood( $this->mTouched ) ) {
3508 wfDebug( "Article::tryFileCache(): about to load file\n" );
3509 $cache->loadFromFileCache();
3510 return true;
3511 } else {
3512 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3513 ob_start( array(&$cache, 'saveToFileCache' ) );
3515 } else {
3516 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3518 return false;
3522 * Check if the page can be cached
3523 * @return bool
3525 public function isFileCacheable() {
3526 $cacheable = false;
3527 if( HTMLFileCache::useFileCache() ) {
3528 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3529 // Extension may have reason to disable file caching on some pages.
3530 if( $cacheable ) {
3531 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3534 return $cacheable;
3538 * Loads page_touched and returns a value indicating if it should be used
3541 public function checkTouched() {
3542 if( !$this->mDataLoaded ) {
3543 $this->loadPageData();
3545 return !$this->mIsRedirect;
3549 * Get the page_touched field
3551 public function getTouched() {
3552 # Ensure that page data has been loaded
3553 if( !$this->mDataLoaded ) {
3554 $this->loadPageData();
3556 return $this->mTouched;
3560 * Get the page_latest field
3562 public function getLatest() {
3563 if( !$this->mDataLoaded ) {
3564 $this->loadPageData();
3566 return (int)$this->mLatest;
3570 * Edit an article without doing all that other stuff
3571 * The article must already exist; link tables etc
3572 * are not updated, caches are not flushed.
3574 * @param $text String: text submitted
3575 * @param $comment String: comment submitted
3576 * @param $minor Boolean: whereas it's a minor modification
3578 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3579 wfProfileIn( __METHOD__ );
3581 $dbw = wfGetDB( DB_MASTER );
3582 $revision = new Revision( array(
3583 'page' => $this->getId(),
3584 'text' => $text,
3585 'comment' => $comment,
3586 'minor_edit' => $minor ? 1 : 0,
3587 ) );
3588 $revision->insertOn( $dbw );
3589 $this->updateRevisionOn( $dbw, $revision );
3591 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3593 wfProfileOut( __METHOD__ );
3597 * Used to increment the view counter
3599 * @param $id Integer: article id
3601 public static function incViewCount( $id ) {
3602 $id = intval( $id );
3603 global $wgHitcounterUpdateFreq, $wgDBtype;
3605 $dbw = wfGetDB( DB_MASTER );
3606 $pageTable = $dbw->tableName( 'page' );
3607 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3608 $acchitsTable = $dbw->tableName( 'acchits' );
3610 if( $wgHitcounterUpdateFreq <= 1 ) {
3611 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3612 return;
3615 # Not important enough to warrant an error page in case of failure
3616 $oldignore = $dbw->ignoreErrors( true );
3618 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3620 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3621 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3622 # Most of the time (or on SQL errors), skip row count check
3623 $dbw->ignoreErrors( $oldignore );
3624 return;
3627 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3628 $row = $dbw->fetchObject( $res );
3629 $rown = intval( $row->n );
3630 if( $rown >= $wgHitcounterUpdateFreq ){
3631 wfProfileIn( 'Article::incViewCount-collect' );
3632 $old_user_abort = ignore_user_abort( true );
3634 if($wgDBtype == 'mysql')
3635 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3636 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3637 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3638 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3639 'GROUP BY hc_id');
3640 $dbw->query("DELETE FROM $hitcounterTable");
3641 if($wgDBtype == 'mysql') {
3642 $dbw->query('UNLOCK TABLES');
3643 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3644 'WHERE page_id = hc_id');
3646 else {
3647 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3648 "FROM $acchitsTable WHERE page_id = hc_id");
3650 $dbw->query("DROP TABLE $acchitsTable");
3652 ignore_user_abort( $old_user_abort );
3653 wfProfileOut( 'Article::incViewCount-collect' );
3655 $dbw->ignoreErrors( $oldignore );
3658 /**#@+
3659 * The onArticle*() functions are supposed to be a kind of hooks
3660 * which should be called whenever any of the specified actions
3661 * are done.
3663 * This is a good place to put code to clear caches, for instance.
3665 * This is called on page move and undelete, as well as edit
3667 * @param $title a title object
3670 public static function onArticleCreate( $title ) {
3671 # Update existence markers on article/talk tabs...
3672 if( $title->isTalkPage() ) {
3673 $other = $title->getSubjectPage();
3674 } else {
3675 $other = $title->getTalkPage();
3677 $other->invalidateCache();
3678 $other->purgeSquid();
3680 $title->touchLinks();
3681 $title->purgeSquid();
3682 $title->deleteTitleProtection();
3685 public static function onArticleDelete( $title ) {
3686 global $wgMessageCache;
3687 # Update existence markers on article/talk tabs...
3688 if( $title->isTalkPage() ) {
3689 $other = $title->getSubjectPage();
3690 } else {
3691 $other = $title->getTalkPage();
3693 $other->invalidateCache();
3694 $other->purgeSquid();
3696 $title->touchLinks();
3697 $title->purgeSquid();
3699 # File cache
3700 HTMLFileCache::clearFileCache( $title );
3702 # Messages
3703 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3704 $wgMessageCache->replace( $title->getDBkey(), false );
3706 # Images
3707 if( $title->getNamespace() == NS_FILE ) {
3708 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3709 $update->doUpdate();
3711 # User talk pages
3712 if( $title->getNamespace() == NS_USER_TALK ) {
3713 $user = User::newFromName( $title->getText(), false );
3714 $user->setNewtalk( false );
3716 # Image redirects
3717 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3721 * Purge caches on page update etc
3723 public static function onArticleEdit( $title, $flags = '' ) {
3724 global $wgDeferredUpdateList;
3726 // Invalidate caches of articles which include this page
3727 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3729 // Invalidate the caches of all pages which redirect here
3730 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3732 # Purge squid for this page only
3733 $title->purgeSquid();
3735 # Clear file cache for this page only
3736 HTMLFileCache::clearFileCache( $title );
3739 /**#@-*/
3742 * Overriden by ImagePage class, only present here to avoid a fatal error
3743 * Called for ?action=revert
3745 public function revert() {
3746 global $wgOut;
3747 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3751 * Info about this page
3752 * Called for ?action=info when $wgAllowPageInfo is on.
3754 public function info() {
3755 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3757 if( !$wgAllowPageInfo ) {
3758 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3759 return;
3762 $page = $this->mTitle->getSubjectPage();
3764 $wgOut->setPagetitle( $page->getPrefixedText() );
3765 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3766 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3768 if( !$this->mTitle->exists() ) {
3769 $wgOut->addHTML( '<div class="noarticletext">' );
3770 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3771 // This doesn't quite make sense; the user is asking for
3772 // information about the _page_, not the message... -- RC
3773 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3774 } else {
3775 $msg = $wgUser->isLoggedIn()
3776 ? 'noarticletext'
3777 : 'noarticletextanon';
3778 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3780 $wgOut->addHTML( '</div>' );
3781 } else {
3782 $dbr = wfGetDB( DB_SLAVE );
3783 $wl_clause = array(
3784 'wl_title' => $page->getDBkey(),
3785 'wl_namespace' => $page->getNamespace() );
3786 $numwatchers = $dbr->selectField(
3787 'watchlist',
3788 'COUNT(*)',
3789 $wl_clause,
3790 __METHOD__,
3791 $this->getSelectOptions() );
3793 $pageInfo = $this->pageCountInfo( $page );
3794 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3796 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3797 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3798 if( $talkInfo ) {
3799 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3801 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3802 if( $talkInfo ) {
3803 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3805 $wgOut->addHTML( '</ul>' );
3810 * Return the total number of edits and number of unique editors
3811 * on a given page. If page does not exist, returns false.
3813 * @param $title Title object
3814 * @return array
3816 public function pageCountInfo( $title ) {
3817 $id = $title->getArticleId();
3818 if( $id == 0 ) {
3819 return false;
3821 $dbr = wfGetDB( DB_SLAVE );
3822 $rev_clause = array( 'rev_page' => $id );
3823 $edits = $dbr->selectField(
3824 'revision',
3825 'COUNT(rev_page)',
3826 $rev_clause,
3827 __METHOD__,
3828 $this->getSelectOptions()
3830 $authors = $dbr->selectField(
3831 'revision',
3832 'COUNT(DISTINCT rev_user_text)',
3833 $rev_clause,
3834 __METHOD__,
3835 $this->getSelectOptions()
3837 return array( 'edits' => $edits, 'authors' => $authors );
3841 * Return a list of templates used by this article.
3842 * Uses the templatelinks table
3844 * @return Array of Title objects
3846 public function getUsedTemplates() {
3847 $result = array();
3848 $id = $this->mTitle->getArticleID();
3849 if( $id == 0 ) {
3850 return array();
3852 $dbr = wfGetDB( DB_SLAVE );
3853 $res = $dbr->select( array( 'templatelinks' ),
3854 array( 'tl_namespace', 'tl_title' ),
3855 array( 'tl_from' => $id ),
3856 __METHOD__ );
3857 if( $res !== false ) {
3858 foreach( $res as $row ) {
3859 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3862 $dbr->freeResult( $res );
3863 return $result;
3867 * Returns a list of hidden categories this page is a member of.
3868 * Uses the page_props and categorylinks tables.
3870 * @return Array of Title objects
3872 public function getHiddenCategories() {
3873 $result = array();
3874 $id = $this->mTitle->getArticleID();
3875 if( $id == 0 ) {
3876 return array();
3878 $dbr = wfGetDB( DB_SLAVE );
3879 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3880 array( 'cl_to' ),
3881 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3882 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3883 __METHOD__ );
3884 if( $res !== false ) {
3885 foreach( $res as $row ) {
3886 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3889 $dbr->freeResult( $res );
3890 return $result;
3894 * Return an applicable autosummary if one exists for the given edit.
3895 * @param $oldtext String: the previous text of the page.
3896 * @param $newtext String: The submitted text of the page.
3897 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3898 * @return string An appropriate autosummary, or an empty string.
3900 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3901 # Decide what kind of autosummary is needed.
3903 # Redirect autosummaries
3904 $ot = Title::newFromRedirect( $oldtext );
3905 $rt = Title::newFromRedirect( $newtext );
3906 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3907 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3910 # New page autosummaries
3911 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3912 # If they're making a new article, give its text, truncated, in the summary.
3913 global $wgContLang;
3914 $truncatedtext = $wgContLang->truncate(
3915 str_replace("\n", ' ', $newtext),
3916 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3917 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3920 # Blanking autosummaries
3921 if( $oldtext != '' && $newtext == '' ) {
3922 return wfMsgForContent( 'autosumm-blank' );
3923 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3924 # Removing more than 90% of the article
3925 global $wgContLang;
3926 $truncatedtext = $wgContLang->truncate(
3927 $newtext,
3928 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3929 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3932 # If we reach this point, there's no applicable autosummary for our case, so our
3933 # autosummary is empty.
3934 return '';
3938 * Add the primary page-view wikitext to the output buffer
3939 * Saves the text into the parser cache if possible.
3940 * Updates templatelinks if it is out of date.
3942 * @param $text String
3943 * @param $cache Boolean
3945 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
3946 global $wgOut;
3948 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
3949 $wgOut->addParserOutput( $this->mParserOutput );
3953 * This does all the heavy lifting for outputWikitext, except it returns the parser
3954 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
3955 * say, embedding thread pages within a discussion system (LiquidThreads)
3957 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
3958 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3960 if ( !$parserOptions ) {
3961 $parserOptions = $this->getParserOptions();
3964 $time = -wfTime();
3965 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
3966 $parserOptions, true, true, $this->getRevIdFetched() );
3967 $time += wfTime();
3969 # Timing hack
3970 if( $time > 3 ) {
3971 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3972 $this->mTitle->getPrefixedDBkey()));
3975 if( $wgEnableParserCache && $cache && $this && $this->mParserOutput->getCacheTime() != -1 ) {
3976 $parserCache = ParserCache::singleton();
3977 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
3979 // Make sure file cache is not used on uncacheable content.
3980 // Output that has magic words in it can still use the parser cache
3981 // (if enabled), though it will generally expire sooner.
3982 if( $this->mParserOutput->getCacheTime() == -1 || $this->mParserOutput->containsOldMagic() ) {
3983 $wgUseFileCache = false;
3985 $this->doCascadeProtectionUpdates( $this->mParserOutput );
3986 return $this->mParserOutput;
3990 * Get parser options suitable for rendering the primary article wikitext
3992 public function getParserOptions() {
3993 global $wgUser;
3994 if ( !$this->mParserOptions ) {
3995 $this->mParserOptions = new ParserOptions( $wgUser );
3996 $this->mParserOptions->setTidy( true );
3997 $this->mParserOptions->enableLimitReport();
3999 return $this->mParserOptions;
4002 protected function doCascadeProtectionUpdates( $parserOutput ) {
4003 if( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4004 return;
4007 // templatelinks table may have become out of sync,
4008 // especially if using variable-based transclusions.
4009 // For paranoia, check if things have changed and if
4010 // so apply updates to the database. This will ensure
4011 // that cascaded protections apply as soon as the changes
4012 // are visible.
4014 # Get templates from templatelinks
4015 $id = $this->mTitle->getArticleID();
4017 $tlTemplates = array();
4019 $dbr = wfGetDB( DB_SLAVE );
4020 $res = $dbr->select( array( 'templatelinks' ),
4021 array( 'tl_namespace', 'tl_title' ),
4022 array( 'tl_from' => $id ),
4023 __METHOD__ );
4025 global $wgContLang;
4026 foreach( $res as $row ) {
4027 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4030 # Get templates from parser output.
4031 $poTemplates = array();
4032 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4033 foreach ( $templates as $dbk => $id ) {
4034 $poTemplates["$ns:$dbk"] = true;
4038 # Get the diff
4039 # Note that we simulate array_diff_key in PHP <5.0.x
4040 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4042 if( count( $templates_diff ) > 0 ) {
4043 # Whee, link updates time.
4044 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4045 $u->doUpdate();
4050 * Update all the appropriate counts in the category table, given that
4051 * we've added the categories $added and deleted the categories $deleted.
4053 * @param $added array The names of categories that were added
4054 * @param $deleted array The names of categories that were deleted
4055 * @return null
4057 public function updateCategoryCounts( $added, $deleted ) {
4058 $ns = $this->mTitle->getNamespace();
4059 $dbw = wfGetDB( DB_MASTER );
4061 # First make sure the rows exist. If one of the "deleted" ones didn't
4062 # exist, we might legitimately not create it, but it's simpler to just
4063 # create it and then give it a negative value, since the value is bogus
4064 # anyway.
4066 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4067 $insertCats = array_merge( $added, $deleted );
4068 if( !$insertCats ) {
4069 # Okay, nothing to do
4070 return;
4072 $insertRows = array();
4073 foreach( $insertCats as $cat ) {
4074 $insertRows[] = array( 'cat_title' => $cat );
4076 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4078 $addFields = array( 'cat_pages = cat_pages + 1' );
4079 $removeFields = array( 'cat_pages = cat_pages - 1' );
4080 if( $ns == NS_CATEGORY ) {
4081 $addFields[] = 'cat_subcats = cat_subcats + 1';
4082 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4083 } elseif( $ns == NS_FILE ) {
4084 $addFields[] = 'cat_files = cat_files + 1';
4085 $removeFields[] = 'cat_files = cat_files - 1';
4088 if( $added ) {
4089 $dbw->update(
4090 'category',
4091 $addFields,
4092 array( 'cat_title' => $added ),
4093 __METHOD__
4096 if( $deleted ) {
4097 $dbw->update(
4098 'category',
4099 $removeFields,
4100 array( 'cat_title' => $deleted ),
4101 __METHOD__
4106 /** Lightweight method to get the parser output for a page, checking the parser cache
4107 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4108 * consider, so it's not appropriate to use there. */
4109 function getParserOutput( $oldid = null ) {
4110 global $wgEnableParserCache, $wgUser, $wgOut;
4112 // Should the parser cache be used?
4113 $useParserCache = $wgEnableParserCache &&
4114 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4115 $this->exists() &&
4116 $oldid === null;
4118 wfDebug( __METHOD__.': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4119 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4120 wfIncrStats( 'pcache_miss_stub' );
4123 $parserOutput = false;
4124 if ( $useParserCache ) {
4125 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4128 if ( $parserOutput === false ) {
4129 // Cache miss; parse and output it.
4130 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4132 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4133 } else {
4134 return $parserOutput;