Remove all calls to $wgMessageCache->loadAllMessages()
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class representing a MediaWiki article and history.
9 *
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.
13 *
14 * @internal documentation reviewed 15 Mar 2010
15 */
16 class Article {
17 /**@{{
18 * @private
19 */
20 var $mComment = ''; // !<
21 var $mContent; // !<
22 var $mContentLoaded = false; // !<
23 var $mCounter = -1; // !< Not loaded
24 var $mCurID = -1; // !< Not loaded
25 var $mDataLoaded = false; // !<
26 var $mForUpdate = false; // !<
27 var $mGoodAdjustment = 0; // !<
28 var $mIsRedirect = false; // !<
29 var $mLatest = false; // !<
30 var $mMinorEdit; // !<
31 var $mOldId; // !<
32 var $mPreparedEdit = false; // !< Title object if set
33 var $mRedirectedFrom = null; // !< Title object if set
34 var $mRedirectTarget = null; // !< Title object if set
35 var $mRedirectUrl = false; // !<
36 var $mRevIdFetched = 0; // !<
37 var $mRevision; // !< Revision object if set
38 var $mTimestamp = ''; // !<
39 var $mTitle; // !< Title object
40 var $mTotalAdjustment = 0; // !<
41 var $mTouched = '19700101000000'; // !<
42 var $mUser = -1; // !< Not loaded
43 var $mUserText = ''; // !< username from Revision if set
44 var $mParserOptions; // !< ParserOptions object
45 var $mParserOutput; // !< ParserCache object if set
46 /**@}}*/
47
48 /**
49 * Constructor and clear the article
50 * @param $title Reference to a Title object.
51 * @param $oldId Integer revision ID, null to fetch from request, zero for current
52 */
53 public function __construct( Title $title, $oldId = null ) {
54 // FIXME: does the reference play any role here?
55 $this->mTitle =& $title;
56 $this->mOldId = $oldId;
57 }
58
59 /**
60 * Constructor from an page id
61 * @param $id The article ID to load
62 */
63 public static function newFromID( $id ) {
64 $t = Title::newFromID( $id );
65 # FIXME: doesn't inherit right
66 return $t == null ? null : new self( $t );
67 # return $t == null ? null : new static( $t ); // PHP 5.3
68 }
69
70 /**
71 * Tell the page view functions that this view was redirected
72 * from another page on the wiki.
73 * @param $from Title object.
74 */
75 public function setRedirectedFrom( Title $from ) {
76 $this->mRedirectedFrom = $from;
77 }
78
79 /**
80 * If this page is a redirect, get its target
81 *
82 * The target will be fetched from the redirect table if possible.
83 * If this page doesn't have an entry there, call insertRedirect()
84 * @return mixed Title object, or null if this page is not a redirect
85 */
86 public function getRedirectTarget() {
87 if ( !$this->mTitle->isRedirect() ) {
88 return null;
89 }
90
91 if ( $this->mRedirectTarget !== null ) {
92 return $this->mRedirectTarget;
93 }
94
95 # Query the redirect table
96 $dbr = wfGetDB( DB_SLAVE );
97 $row = $dbr->selectRow( 'redirect',
98 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
99 array( 'rd_from' => $this->getID() ),
100 __METHOD__
101 );
102
103 // rd_fragment and rd_interwiki were added later, populate them if empty
104 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
105 return $this->mRedirectTarget = Title::makeTitle(
106 $row->rd_namespace, $row->rd_title,
107 $row->rd_fragment, $row->rd_interwiki );
108 }
109
110 # This page doesn't have an entry in the redirect table
111 return $this->mRedirectTarget = $this->insertRedirect();
112 }
113
114 /**
115 * Insert an entry for this page into the redirect table.
116 *
117 * Don't call this function directly unless you know what you're doing.
118 * @return Title object or null if not a redirect
119 */
120 public function insertRedirect() {
121 // recurse through to only get the final target
122 $retval = Title::newFromRedirectRecurse( $this->getContent() );
123 if ( !$retval ) {
124 return null;
125 }
126 $this->insertRedirectEntry( $retval );
127 return $retval;
128 }
129
130 /**
131 * Insert or update the redirect table entry for this page to indicate
132 * it redirects to $rt .
133 * @param $rt Title redirect target
134 */
135 public function insertRedirectEntry( $rt ) {
136 $dbw = wfGetDB( DB_MASTER );
137 $dbw->replace( 'redirect', array( 'rd_from' ),
138 array(
139 'rd_from' => $this->getID(),
140 'rd_namespace' => $rt->getNamespace(),
141 'rd_title' => $rt->getDBkey(),
142 'rd_fragment' => $rt->getFragment(),
143 'rd_interwiki' => $rt->getInterwiki(),
144 ),
145 __METHOD__
146 );
147 }
148
149 /**
150 * Get the Title object or URL this page redirects to
151 *
152 * @return mixed false, Title of in-wiki target, or string with URL
153 */
154 public function followRedirect() {
155 return $this->getRedirectURL( $this->getRedirectTarget() );
156 }
157
158 /**
159 * Get the Title object this text redirects to
160 *
161 * @param $text string article content containing redirect info
162 * @return mixed false, Title of in-wiki target, or string with URL
163 * @deprecated
164 */
165 public function followRedirectText( $text ) {
166 // recurse through to only get the final target
167 return $this->getRedirectURL( Title::newFromRedirectRecurse( $text ) );
168 }
169
170 /**
171 * Get the Title object or URL to use for a redirect. We use Title
172 * objects for same-wiki, non-special redirects and URLs for everything
173 * else.
174 * @param $rt Title Redirect target
175 * @return mixed false, Title object of local target, or string with URL
176 */
177 public function getRedirectURL( $rt ) {
178 if ( $rt ) {
179 if ( $rt->getInterwiki() != '' ) {
180 if ( $rt->isLocal() ) {
181 // Offsite wikis need an HTTP redirect.
182 //
183 // This can be hard to reverse and may produce loops,
184 // so they may be disabled in the site configuration.
185 $source = $this->mTitle->getFullURL( 'redirect=no' );
186 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
187 }
188 } else {
189 if ( $rt->getNamespace() == NS_SPECIAL ) {
190 // Gotta handle redirects to special pages differently:
191 // Fill the HTTP response "Location" header and ignore
192 // the rest of the page we're on.
193 //
194 // This can be hard to reverse, so they may be disabled.
195 if ( $rt->isSpecial( 'Userlogout' ) ) {
196 // rolleyes
197 } else {
198 return $rt->getFullURL();
199 }
200 }
201
202 return $rt;
203 }
204 }
205
206 // No or invalid redirect
207 return false;
208 }
209
210 /**
211 * Get the title object of the article
212 * @return Title object of this page
213 */
214 public function getTitle() {
215 return $this->mTitle;
216 }
217
218 /**
219 * Clear the object
220 * FIXME: shouldn't this be public?
221 * @private
222 */
223 public function clear() {
224 $this->mDataLoaded = false;
225 $this->mContentLoaded = false;
226
227 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
228 $this->mRedirectedFrom = null; # Title object if set
229 $this->mRedirectTarget = null; # Title object if set
230 $this->mUserText =
231 $this->mTimestamp = $this->mComment = '';
232 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
233 $this->mTouched = '19700101000000';
234 $this->mForUpdate = false;
235 $this->mIsRedirect = false;
236 $this->mRevIdFetched = 0;
237 $this->mRedirectUrl = false;
238 $this->mLatest = false;
239 $this->mPreparedEdit = false;
240 }
241
242 /**
243 * Note that getContent/loadContent do not follow redirects anymore.
244 * If you need to fetch redirectable content easily, try
245 * the shortcut in Article::followRedirect()
246 *
247 * This function has side effects! Do not use this function if you
248 * only want the real revision text if any.
249 *
250 * @return Return the text of this revision
251 */
252 public function getContent() {
253 global $wgUser, $wgContLang, $wgMessageCache;
254
255 wfProfileIn( __METHOD__ );
256
257 if ( $this->getID() === 0 ) {
258 # If this is a MediaWiki:x message, then load the messages
259 # and return the message value for x.
260 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
261 # If this is a system message, get the default text.
262 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
263 $text = wfMsgGetKey( $message, false, $lang, false );
264
265 if ( wfEmptyMsg( $message, $text ) )
266 $text = '';
267 } else {
268 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
269 }
270 wfProfileOut( __METHOD__ );
271
272 return $text;
273 } else {
274 $this->loadContent();
275 wfProfileOut( __METHOD__ );
276
277 return $this->mContent;
278 }
279 }
280
281 /**
282 * Get the text of the current revision. No side-effects...
283 *
284 * @return Return the text of the current revision
285 */
286 public function getRawText() {
287 // Check process cache for current revision
288 if ( $this->mContentLoaded && $this->mOldId == 0 ) {
289 return $this->mContent;
290 }
291
292 $rev = Revision::newFromTitle( $this->mTitle );
293 $text = $rev ? $rev->getRawText() : false;
294
295 return $text;
296 }
297
298 /**
299 * This function returns the text of a section, specified by a number ($section).
300 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
301 * the first section before any such heading (section 0).
302 *
303 * If a section contains subsections, these are also returned.
304 *
305 * @param $text String: text to look in
306 * @param $section Integer: section number
307 * @return string text of the requested section
308 * @deprecated
309 */
310 public function getSection( $text, $section ) {
311 global $wgParser;
312 return $wgParser->getSection( $text, $section );
313 }
314
315 /**
316 * Get the text that needs to be saved in order to undo all revisions
317 * between $undo and $undoafter. Revisions must belong to the same page,
318 * must exist and must not be deleted
319 * @param $undo Revision
320 * @param $undoafter Revision Must be an earlier revision than $undo
321 * @return mixed string on success, false on failure
322 */
323 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
324 $undo_text = $undo->getText();
325 $undoafter_text = $undoafter->getText();
326 $cur_text = $this->getContent();
327
328 if ( $cur_text == $undo_text ) {
329 # No use doing a merge if it's just a straight revert.
330 return $undoafter_text;
331 }
332
333 $undone_text = '';
334
335 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
336 return false;
337 }
338
339 return $undone_text;
340 }
341
342 /**
343 * @return int The oldid of the article that is to be shown, 0 for the
344 * current revision
345 */
346 public function getOldID() {
347 if ( is_null( $this->mOldId ) ) {
348 $this->mOldId = $this->getOldIDFromRequest();
349 }
350
351 return $this->mOldId;
352 }
353
354 /**
355 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
356 *
357 * @return int The old id for the request
358 */
359 public function getOldIDFromRequest() {
360 global $wgRequest;
361
362 $this->mRedirectUrl = false;
363
364 $oldid = $wgRequest->getVal( 'oldid' );
365
366 if ( isset( $oldid ) ) {
367 $oldid = intval( $oldid );
368 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
369 $nextid = $this->mTitle->getNextRevisionID( $oldid );
370 if ( $nextid ) {
371 $oldid = $nextid;
372 } else {
373 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
374 }
375 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
376 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
377 if ( $previd ) {
378 $oldid = $previd;
379 }
380 }
381 }
382
383 if ( !$oldid ) {
384 $oldid = 0;
385 }
386
387 return $oldid;
388 }
389
390 /**
391 * Load the revision (including text) into this object
392 */
393 function loadContent() {
394 if ( $this->mContentLoaded ) {
395 return;
396 }
397
398 wfProfileIn( __METHOD__ );
399
400 $oldid = $this->getOldID();
401 $this->mOldId = $oldid;
402 $this->fetchContent( $oldid );
403
404 wfProfileOut( __METHOD__ );
405 }
406
407 /**
408 * Fetch a page record with the given conditions
409 * @param $dbr Database object
410 * @param $conditions Array
411 * @return mixed Database result resource, or false on failure
412 */
413 protected function pageData( $dbr, $conditions ) {
414 $fields = array(
415 'page_id',
416 'page_namespace',
417 'page_title',
418 'page_restrictions',
419 'page_counter',
420 'page_is_redirect',
421 'page_is_new',
422 'page_random',
423 'page_touched',
424 'page_latest',
425 'page_len',
426 );
427
428 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
429
430 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__ );
431
432 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
433
434 return $row;
435 }
436
437 /**
438 * Fetch a page record matching the Title object's namespace and title
439 * using a sanitized title string
440 *
441 * @param $dbr Database object
442 * @param $title Title object
443 * @return mixed Database result resource, or false on failure
444 */
445 public function pageDataFromTitle( $dbr, $title ) {
446 return $this->pageData( $dbr, array(
447 'page_namespace' => $title->getNamespace(),
448 'page_title' => $title->getDBkey() ) );
449 }
450
451 /**
452 * Fetch a page record matching the requested ID
453 *
454 * @param $dbr Database
455 * @param $id Integer
456 */
457 protected function pageDataFromId( $dbr, $id ) {
458 return $this->pageData( $dbr, array( 'page_id' => $id ) );
459 }
460
461 /**
462 * Set the general counter, title etc data loaded from
463 * some source.
464 *
465 * @param $data Database row object or "fromdb"
466 */
467 public function loadPageData( $data = 'fromdb' ) {
468 if ( $data === 'fromdb' ) {
469 $dbr = wfGetDB( DB_MASTER );
470 $data = $this->pageDataFromId( $dbr, $this->getId() );
471 }
472
473 $lc = LinkCache::singleton();
474
475 if ( $data ) {
476 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect, $data->page_latest );
477
478 $this->mTitle->mArticleID = intval( $data->page_id );
479
480 # Old-fashioned restrictions
481 $this->mTitle->loadRestrictions( $data->page_restrictions );
482
483 $this->mCounter = intval( $data->page_counter );
484 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
485 $this->mIsRedirect = intval( $data->page_is_redirect );
486 $this->mLatest = intval( $data->page_latest );
487 } else {
488 $lc->addBadLinkObj( $this->mTitle );
489 $this->mTitle->mArticleID = 0;
490 }
491
492 $this->mDataLoaded = true;
493 }
494
495 /**
496 * Get text of an article from database
497 * Does *NOT* follow redirects.
498 *
499 * @param $oldid Int: 0 for whatever the latest revision is
500 * @return mixed string containing article contents, or false if null
501 */
502 function fetchContent( $oldid = 0 ) {
503 if ( $this->mContentLoaded ) {
504 return $this->mContent;
505 }
506
507 $dbr = wfGetDB( DB_MASTER );
508
509 # Pre-fill content with error message so that if something
510 # fails we'll have something telling us what we intended.
511 $t = $this->mTitle->getPrefixedText();
512 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
513 $this->mContent = wfMsgNoTrans( 'missing-article', $t, $d ) ;
514
515 if ( $oldid ) {
516 $revision = Revision::newFromId( $oldid );
517 if ( $revision === null ) {
518 wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
519 return false;
520 }
521
522 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
523
524 if ( !$data ) {
525 wfDebug( __METHOD__ . " failed to get page data linked to revision id $oldid\n" );
526 return false;
527 }
528
529 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
530 $this->loadPageData( $data );
531 } else {
532 if ( !$this->mDataLoaded ) {
533 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
534
535 if ( !$data ) {
536 wfDebug( __METHOD__ . " failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
537 return false;
538 }
539
540 $this->loadPageData( $data );
541 }
542 $revision = Revision::newFromId( $this->mLatest );
543 if ( $revision === null ) {
544 wfDebug( __METHOD__ . " failed to retrieve current page, rev_id {$this->mLatest}\n" );
545 return false;
546 }
547 }
548
549 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
550 // We should instead work with the Revision object when we need it...
551 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
552
553 $this->mUser = $revision->getUser();
554 $this->mUserText = $revision->getUserText();
555 $this->mComment = $revision->getComment();
556 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
557
558 $this->mRevIdFetched = $revision->getId();
559 $this->mContentLoaded = true;
560 $this->mRevision =& $revision;
561
562 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) );
563
564 return $this->mContent;
565 }
566
567 /**
568 * Read/write accessor to select FOR UPDATE
569 *
570 * @param $x Mixed: FIXME
571 * @return mixed value of $x, or value stored in Article::mForUpdate
572 */
573 public function forUpdate( $x = null ) {
574 return wfSetVar( $this->mForUpdate, $x );
575 }
576
577 /**
578 * Get options for all SELECT statements
579 *
580 * @param $options Array: an optional options array which'll be appended to
581 * the default
582 * @return Array: options
583 */
584 protected function getSelectOptions( $options = '' ) {
585 if ( $this->mForUpdate ) {
586 if ( is_array( $options ) ) {
587 $options[] = 'FOR UPDATE';
588 } else {
589 $options = 'FOR UPDATE';
590 }
591 }
592
593 return $options;
594 }
595
596 /**
597 * @return int Page ID
598 */
599 public function getID() {
600 return $this->mTitle->getArticleID();
601 }
602
603 /**
604 * @return bool Whether or not the page exists in the database
605 */
606 public function exists() {
607 return $this->getId() > 0;
608 }
609
610 /**
611 * Check if this page is something we're going to be showing
612 * some sort of sensible content for. If we return false, page
613 * views (plain action=view) will return an HTTP 404 response,
614 * so spiders and robots can know they're following a bad link.
615 *
616 * @return bool
617 */
618 public function hasViewableContent() {
619 return $this->exists() || $this->mTitle->isAlwaysKnown();
620 }
621
622 /**
623 * @return int The view count for the page
624 */
625 public function getCount() {
626 if ( -1 == $this->mCounter ) {
627 $id = $this->getID();
628
629 if ( $id == 0 ) {
630 $this->mCounter = 0;
631 } else {
632 $dbr = wfGetDB( DB_SLAVE );
633 $this->mCounter = $dbr->selectField( 'page',
634 'page_counter',
635 array( 'page_id' => $id ),
636 __METHOD__,
637 $this->getSelectOptions()
638 );
639 }
640 }
641
642 return $this->mCounter;
643 }
644
645 /**
646 * Determine whether a page would be suitable for being counted as an
647 * article in the site_stats table based on the title & its content
648 *
649 * @param $text String: text to analyze
650 * @return bool
651 */
652 public function isCountable( $text ) {
653 global $wgUseCommaCount;
654
655 $token = $wgUseCommaCount ? ',' : '[[';
656
657 return $this->mTitle->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
658 }
659
660 /**
661 * Tests if the article text represents a redirect
662 *
663 * @param $text mixed string containing article contents, or boolean
664 * @return bool
665 */
666 public function isRedirect( $text = false ) {
667 if ( $text === false ) {
668 if ( $this->mDataLoaded ) {
669 return $this->mIsRedirect;
670 }
671
672 // Apparently loadPageData was never called
673 $this->loadContent();
674 $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
675 } else {
676 $titleObj = Title::newFromRedirect( $text );
677 }
678
679 return $titleObj !== null;
680 }
681
682 /**
683 * Returns true if the currently-referenced revision is the current edit
684 * to this page (and it exists).
685 * @return bool
686 */
687 public function isCurrent() {
688 # If no oldid, this is the current version.
689 if ( $this->getOldID() == 0 ) {
690 return true;
691 }
692
693 return $this->exists() && isset( $this->mRevision ) && $this->mRevision->isCurrent();
694 }
695
696 /**
697 * Loads everything except the text
698 * This isn't necessary for all uses, so it's only done if needed.
699 */
700 protected function loadLastEdit() {
701 if ( -1 != $this->mUser ) {
702 return;
703 }
704
705 # New or non-existent articles have no user information
706 $id = $this->getID();
707 if ( 0 == $id ) {
708 return;
709 }
710
711 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
712 if ( !is_null( $this->mLastRevision ) ) {
713 $this->mUser = $this->mLastRevision->getUser();
714 $this->mUserText = $this->mLastRevision->getUserText();
715 $this->mTimestamp = $this->mLastRevision->getTimestamp();
716 $this->mComment = $this->mLastRevision->getComment();
717 $this->mMinorEdit = $this->mLastRevision->isMinor();
718 $this->mRevIdFetched = $this->mLastRevision->getId();
719 }
720 }
721
722 /**
723 * @return string GMT timestamp of last article revision
724 **/
725
726 public function getTimestamp() {
727 // Check if the field has been filled by ParserCache::get()
728 if ( !$this->mTimestamp ) {
729 $this->loadLastEdit();
730 }
731
732 return wfTimestamp( TS_MW, $this->mTimestamp );
733 }
734
735 /**
736 * @return int user ID for the user that made the last article revision
737 */
738 public function getUser() {
739 $this->loadLastEdit();
740 return $this->mUser;
741 }
742
743 /**
744 * @return string username of the user that made the last article revision
745 */
746 public function getUserText() {
747 $this->loadLastEdit();
748 return $this->mUserText;
749 }
750
751 /**
752 * @return string Comment stored for the last article revision
753 */
754 public function getComment() {
755 $this->loadLastEdit();
756 return $this->mComment;
757 }
758
759 /**
760 * Returns true if last revision was marked as "minor edit"
761 *
762 * @return boolean Minor edit indicator for the last article revision.
763 */
764 public function getMinorEdit() {
765 $this->loadLastEdit();
766 return $this->mMinorEdit;
767 }
768
769 /**
770 * Use this to fetch the rev ID used on page views
771 *
772 * @return int revision ID of last article revision
773 */
774 public function getRevIdFetched() {
775 $this->loadLastEdit();
776 return $this->mRevIdFetched;
777 }
778
779 /**
780 * FIXME: this does what?
781 * @param $limit Integer: default 0.
782 * @param $offset Integer: default 0.
783 * @return UserArrayFromResult object with User objects of article contributors for requested range
784 */
785 public function getContributors( $limit = 0, $offset = 0 ) {
786 # FIXME: this is expensive; cache this info somewhere.
787
788 $dbr = wfGetDB( DB_SLAVE );
789 $revTable = $dbr->tableName( 'revision' );
790 $userTable = $dbr->tableName( 'user' );
791
792 $pageId = $this->getId();
793
794 $user = $this->getUser();
795
796 if ( $user ) {
797 $excludeCond = "AND rev_user != $user";
798 } else {
799 $userText = $dbr->addQuotes( $this->getUserText() );
800 $excludeCond = "AND rev_user_text != $userText";
801 }
802
803 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER ); // username hidden?
804
805 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
806 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
807 WHERE rev_page = $pageId
808 $excludeCond
809 AND $deletedBit = 0
810 GROUP BY rev_user, rev_user_text
811 ORDER BY timestamp DESC";
812
813 if ( $limit > 0 ) {
814 $sql = $dbr->limitResult( $sql, $limit, $offset );
815 }
816
817 $sql .= ' ' . $this->getSelectOptions();
818 $res = $dbr->query( $sql, __METHOD__ );
819
820 return new UserArrayFromResult( $res );
821 }
822
823 /**
824 * This is the default action of the index.php entry point: just view the
825 * page of the given title.
826 */
827 public function view() {
828 global $wgUser, $wgOut, $wgRequest, $wgParser;
829 global $wgUseFileCache;
830
831 wfProfileIn( __METHOD__ );
832
833 # Get variables from query string
834 $oldid = $this->getOldID();
835 $parserCache = ParserCache::singleton();
836
837 $parserOptions = clone $this->getParserOptions();
838 # Render printable version, use printable version cache
839 if ( $wgOut->isPrintable() ) {
840 $parserOptions->setIsPrintable( true );
841 }
842
843 # Try client and file cache
844 if ( $oldid === 0 && $this->checkTouched() ) {
845 global $wgUseETag;
846
847 if ( $wgUseETag ) {
848 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
849 }
850
851 # Is is client cached?
852 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
853 wfDebug( __METHOD__ . ": done 304\n" );
854 wfProfileOut( __METHOD__ );
855
856 return;
857 # Try file cache
858 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
859 wfDebug( __METHOD__ . ": done file cache\n" );
860 # tell wgOut that output is taken care of
861 $wgOut->disable();
862 $this->viewUpdates();
863 wfProfileOut( __METHOD__ );
864
865 return;
866 }
867 }
868
869 # getOldID may want us to redirect somewhere else
870 if ( $this->mRedirectUrl ) {
871 $wgOut->redirect( $this->mRedirectUrl );
872 wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
873 wfProfileOut( __METHOD__ );
874
875 return;
876 }
877
878 $wgOut->setArticleFlag( true );
879 # Set page title (may be overridden by DISPLAYTITLE)
880 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
881
882 # If we got diff in the query, we want to see a diff page instead of the article.
883 if ( $wgRequest->getCheck( 'diff' ) ) {
884 wfDebug( __METHOD__ . ": showing diff page\n" );
885 $this->showDiffPage();
886 wfProfileOut( __METHOD__ );
887
888 return;
889 }
890
891 # Should the parser cache be used?
892 $useParserCache = $this->useParserCache( $oldid );
893 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
894 if ( $wgUser->getOption( 'stubthreshold' ) ) {
895 wfIncrStats( 'pcache_miss_stub' );
896 }
897
898 $wasRedirected = $this->showRedirectedFromHeader();
899 $this->showNamespaceHeader();
900
901 # Iterate through the possible ways of constructing the output text.
902 # Keep going until $outputDone is set, or we run out of things to do.
903 $pass = 0;
904 $outputDone = false;
905 $this->mParserOutput = false;
906
907 while ( !$outputDone && ++$pass ) {
908 switch( $pass ) {
909 case 1:
910 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
911 break;
912 case 2:
913 # Try the parser cache
914 if ( $useParserCache ) {
915 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
916
917 if ( $this->mParserOutput !== false ) {
918 wfDebug( __METHOD__ . ": showing parser cache contents\n" );
919 $wgOut->addParserOutput( $this->mParserOutput );
920 # Ensure that UI elements requiring revision ID have
921 # the correct version information.
922 $wgOut->setRevisionId( $this->mLatest );
923 $outputDone = true;
924 }
925 }
926 break;
927 case 3:
928 $text = $this->getContent();
929 if ( $text === false || $this->getID() == 0 ) {
930 wfDebug( __METHOD__ . ": showing missing article\n" );
931 $this->showMissingArticle();
932 wfProfileOut( __METHOD__ );
933 return;
934 }
935
936 # Another whitelist check in case oldid is altering the title
937 if ( !$this->mTitle->userCanRead() ) {
938 wfDebug( __METHOD__ . ": denied on secondary read check\n" );
939 $wgOut->loginToUse();
940 $wgOut->output();
941 $wgOut->disable();
942 wfProfileOut( __METHOD__ );
943 return;
944 }
945
946 # Are we looking at an old revision
947 if ( $oldid && !is_null( $this->mRevision ) ) {
948 $this->setOldSubtitle( $oldid );
949
950 if ( !$this->showDeletedRevisionHeader() ) {
951 wfDebug( __METHOD__ . ": cannot view deleted revision\n" );
952 wfProfileOut( __METHOD__ );
953 return;
954 }
955
956 # If this "old" version is the current, then try the parser cache...
957 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
958 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
959 if ( $this->mParserOutput ) {
960 wfDebug( __METHOD__ . ": showing parser cache for current rev permalink\n" );
961 $wgOut->addParserOutput( $this->mParserOutput );
962 $wgOut->setRevisionId( $this->mLatest );
963 $this->showViewFooter();
964 $this->viewUpdates();
965 wfProfileOut( __METHOD__ );
966 return;
967 }
968 }
969 }
970
971 # Ensure that UI elements requiring revision ID have
972 # the correct version information.
973 $wgOut->setRevisionId( $this->getRevIdFetched() );
974
975 # Pages containing custom CSS or JavaScript get special treatment
976 if ( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
977 wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
978 $this->showCssOrJsPage();
979 $outputDone = true;
980 } else if ( $rt = Title::newFromRedirectArray( $text ) ) {
981 wfDebug( __METHOD__ . ": showing redirect=no page\n" );
982 # Viewing a redirect page (e.g. with parameter redirect=no)
983 # Don't append the subtitle if this was an old revision
984 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
985 # Parse just to get categories, displaytitle, etc.
986 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
987 $wgOut->addParserOutputNoText( $this->mParserOutput );
988 $outputDone = true;
989 }
990 break;
991 case 4:
992 # Run the parse, protected by a pool counter
993 wfDebug( __METHOD__ . ": doing uncached parse\n" );
994 $key = $parserCache->getKey( $this, $parserOptions );
995 $poolCounter = PoolCounter::factory( 'Article::view', $key );
996 $dirtyCallback = $useParserCache ? array( $this, 'tryDirtyCache' ) : false;
997 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
998
999 if ( !$status->isOK() ) {
1000 # Connection or timeout error
1001 $this->showPoolError( $status );
1002 wfProfileOut( __METHOD__ );
1003 return;
1004 } else {
1005 $outputDone = true;
1006 }
1007 break;
1008 # Should be unreachable, but just in case...
1009 default:
1010 break 2;
1011 }
1012 }
1013
1014 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1015 if ( $this->mParserOutput ) {
1016 $titleText = $this->mParserOutput->getTitleText();
1017
1018 if ( strval( $titleText ) !== '' ) {
1019 $wgOut->setPageTitle( $titleText );
1020 }
1021 }
1022
1023 # For the main page, overwrite the <title> element with the con-
1024 # tents of 'pagetitle-view-mainpage' instead of the default (if
1025 # that's not empty).
1026 # This message always exists because it is in the i18n files
1027 if ( $this->mTitle->equals( Title::newMainPage() )
1028 && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
1029 {
1030 $wgOut->setHTMLTitle( $m );
1031 }
1032
1033 # Now that we've filled $this->mParserOutput, we know whether
1034 # there are any __NOINDEX__ tags on the page
1035 $policy = $this->getRobotPolicy( 'view' );
1036 $wgOut->setIndexPolicy( $policy['index'] );
1037 $wgOut->setFollowPolicy( $policy['follow'] );
1038
1039 $this->showViewFooter();
1040 $this->viewUpdates();
1041 wfProfileOut( __METHOD__ );
1042 }
1043
1044 /**
1045 * Show a diff page according to current request variables. For use within
1046 * Article::view() only, other callers should use the DifferenceEngine class.
1047 */
1048 public function showDiffPage() {
1049 global $wgRequest, $wgUser;
1050
1051 $diff = $wgRequest->getVal( 'diff' );
1052 $rcid = $wgRequest->getVal( 'rcid' );
1053 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1054 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1055 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1056 $oldid = $this->getOldID();
1057
1058 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $unhide );
1059 // DifferenceEngine directly fetched the revision:
1060 $this->mRevIdFetched = $de->mNewid;
1061 $de->showDiffPage( $diffOnly );
1062
1063 // Needed to get the page's current revision
1064 $this->loadPageData();
1065 if ( $diff == 0 || $diff == $this->mLatest ) {
1066 # Run view updates for current revision only
1067 $this->viewUpdates();
1068 }
1069 }
1070
1071 /**
1072 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1073 * Article::view() only.
1074 *
1075 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1076 * page views.
1077 */
1078 public function showCssOrJsPage() {
1079 global $wgOut;
1080
1081 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1082
1083 // Give hooks a chance to customise the output
1084 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
1085 // Wrap the whole lot in a <pre> and don't parse
1086 $m = array();
1087 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
1088 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1089 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
1090 $wgOut->addHTML( "\n</pre>\n" );
1091 }
1092 }
1093
1094 /**
1095 * Get the robot policy to be used for the current view
1096 * @param $action String the action= GET parameter
1097 * @return Array the policy that should be set
1098 * TODO: actions other than 'view'
1099 */
1100 public function getRobotPolicy( $action ) {
1101 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1102 global $wgDefaultRobotPolicy, $wgRequest;
1103
1104 $ns = $this->mTitle->getNamespace();
1105
1106 if ( $ns == NS_USER || $ns == NS_USER_TALK ) {
1107 # Don't index user and user talk pages for blocked users (bug 11443)
1108 if ( !$this->mTitle->isSubpage() ) {
1109 $block = new Block();
1110 if ( $block->load( $this->mTitle->getText() ) ) {
1111 return array(
1112 'index' => 'noindex',
1113 'follow' => 'nofollow'
1114 );
1115 }
1116 }
1117 }
1118
1119 if ( $this->getID() === 0 || $this->getOldID() ) {
1120 # Non-articles (special pages etc), and old revisions
1121 return array(
1122 'index' => 'noindex',
1123 'follow' => 'nofollow'
1124 );
1125 } elseif ( $wgOut->isPrintable() ) {
1126 # Discourage indexing of printable versions, but encourage following
1127 return array(
1128 'index' => 'noindex',
1129 'follow' => 'follow'
1130 );
1131 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1132 # For ?curid=x urls, disallow indexing
1133 return array(
1134 'index' => 'noindex',
1135 'follow' => 'follow'
1136 );
1137 }
1138
1139 # Otherwise, construct the policy based on the various config variables.
1140 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
1141
1142 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1143 # Honour customised robot policies for this namespace
1144 $policy = array_merge(
1145 $policy,
1146 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1147 );
1148 }
1149 if ( $this->mTitle->canUseNoindex() && is_object( $this->mParserOutput ) && $this->mParserOutput->getIndexPolicy() ) {
1150 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1151 # a final sanity check that we have really got the parser output.
1152 $policy = array_merge(
1153 $policy,
1154 array( 'index' => $this->mParserOutput->getIndexPolicy() )
1155 );
1156 }
1157
1158 if ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
1159 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1160 $policy = array_merge(
1161 $policy,
1162 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] )
1163 );
1164 }
1165
1166 return $policy;
1167 }
1168
1169 /**
1170 * Converts a String robot policy into an associative array, to allow
1171 * merging of several policies using array_merge().
1172 * @param $policy Mixed, returns empty array on null/false/'', transparent
1173 * to already-converted arrays, converts String.
1174 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1175 */
1176 public static function formatRobotPolicy( $policy ) {
1177 if ( is_array( $policy ) ) {
1178 return $policy;
1179 } elseif ( !$policy ) {
1180 return array();
1181 }
1182
1183 $policy = explode( ',', $policy );
1184 $policy = array_map( 'trim', $policy );
1185
1186 $arr = array();
1187 foreach ( $policy as $var ) {
1188 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1189 $arr['index'] = $var;
1190 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1191 $arr['follow'] = $var;
1192 }
1193 }
1194
1195 return $arr;
1196 }
1197
1198 /**
1199 * If this request is a redirect view, send "redirected from" subtitle to
1200 * $wgOut. Returns true if the header was needed, false if this is not a
1201 * redirect view. Handles both local and remote redirects.
1202 *
1203 * @return boolean
1204 */
1205 public function showRedirectedFromHeader() {
1206 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1207
1208 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1209 $sk = $wgUser->getSkin();
1210
1211 if ( isset( $this->mRedirectedFrom ) ) {
1212 // This is an internally redirected page view.
1213 // We'll need a backlink to the source page for navigation.
1214 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1215 $redir = $sk->link(
1216 $this->mRedirectedFrom,
1217 null,
1218 array(),
1219 array( 'redirect' => 'no' ),
1220 array( 'known', 'noclasses' )
1221 );
1222
1223 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1224 $wgOut->setSubtitle( $s );
1225
1226 // Set the fragment if one was specified in the redirect
1227 if ( strval( $this->mTitle->getFragment() ) != '' ) {
1228 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
1229 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1230 }
1231
1232 // Add a <link rel="canonical"> tag
1233 $wgOut->addLink( array( 'rel' => 'canonical',
1234 'href' => $this->mTitle->getLocalURL() )
1235 );
1236
1237 return true;
1238 }
1239 } elseif ( $rdfrom ) {
1240 // This is an externally redirected view, from some other wiki.
1241 // If it was reported from a trusted site, supply a backlink.
1242 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1243 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1244 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1245 $wgOut->setSubtitle( $s );
1246
1247 return true;
1248 }
1249 }
1250
1251 return false;
1252 }
1253
1254 /**
1255 * Show a header specific to the namespace currently being viewed, like
1256 * [[MediaWiki:Talkpagetext]]. For Article::view().
1257 */
1258 public function showNamespaceHeader() {
1259 global $wgOut;
1260
1261 if ( $this->mTitle->isTalkPage() ) {
1262 $msg = wfMsgNoTrans( 'talkpageheader' );
1263 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1264 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1265 }
1266 }
1267 }
1268
1269 /**
1270 * Show the footer section of an ordinary page view
1271 */
1272 public function showViewFooter() {
1273 global $wgOut, $wgUseTrackbacks;
1274
1275 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1276 if ( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1277 $wgOut->addWikiMsg( 'anontalkpagetext' );
1278 }
1279
1280 # If we have been passed an &rcid= parameter, we want to give the user a
1281 # chance to mark this new article as patrolled.
1282 $this->showPatrolFooter();
1283
1284 # Trackbacks
1285 if ( $wgUseTrackbacks ) {
1286 $this->addTrackbacks();
1287 }
1288 }
1289
1290 /**
1291 * If patrol is possible, output a patrol UI box. This is called from the
1292 * footer section of ordinary page views. If patrol is not possible or not
1293 * desired, does nothing.
1294 */
1295 public function showPatrolFooter() {
1296 global $wgOut, $wgRequest, $wgUser;
1297
1298 $rcid = $wgRequest->getVal( 'rcid' );
1299
1300 if ( !$rcid || !$this->mTitle->quickUserCan( 'patrol' ) ) {
1301 return;
1302 }
1303
1304 $sk = $wgUser->getSkin();
1305 $token = $wgUser->editToken( $rcid );
1306
1307 $wgOut->addHTML(
1308 "<div class='patrollink'>" .
1309 wfMsgHtml(
1310 'markaspatrolledlink',
1311 $sk->link(
1312 $this->mTitle,
1313 wfMsgHtml( 'markaspatrolledtext' ),
1314 array(),
1315 array(
1316 'action' => 'markpatrolled',
1317 'rcid' => $rcid,
1318 'token' => $token,
1319 ),
1320 array( 'known', 'noclasses' )
1321 )
1322 ) .
1323 '</div>'
1324 );
1325 }
1326
1327 /**
1328 * Show the error text for a missing article. For articles in the MediaWiki
1329 * namespace, show the default message text. To be called from Article::view().
1330 */
1331 public function showMissingArticle() {
1332 global $wgOut, $wgRequest, $wgUser;
1333
1334 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1335 if ( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
1336 $parts = explode( '/', $this->mTitle->getText() );
1337 $rootPart = $parts[0];
1338 $user = User::newFromName( $rootPart, false /* allow IP users*/ );
1339 $ip = User::isIP( $rootPart );
1340
1341 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1342 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1343 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1344 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1345 LogEventsList::showLogExtract(
1346 $wgOut,
1347 'block',
1348 $user->getUserPage()->getPrefixedText(),
1349 '',
1350 array(
1351 'lim' => 1,
1352 'showIfEmpty' => false,
1353 'msgKey' => array(
1354 'blocked-notice-logextract',
1355 $user->getName() # Support GENDER in notice
1356 )
1357 )
1358 );
1359 }
1360 }
1361
1362 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1363
1364 # Show delete and move logs
1365 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle->getPrefixedText(), '',
1366 array( 'lim' => 10,
1367 'conds' => array( "log_action != 'revision'" ),
1368 'showIfEmpty' => false,
1369 'msgKey' => array( 'moveddeleted-notice' ) )
1370 );
1371
1372 # Show error message
1373 $oldid = $this->getOldID();
1374 if ( $oldid ) {
1375 $text = wfMsgNoTrans( 'missing-article',
1376 $this->mTitle->getPrefixedText(),
1377 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1378 } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1379 // Use the default message text
1380 $text = $this->getContent();
1381 } else {
1382 $createErrors = $this->mTitle->getUserPermissionsErrors( 'create', $wgUser );
1383 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
1384 $errors = array_merge( $createErrors, $editErrors );
1385
1386 if ( !count( $errors ) ) {
1387 $text = wfMsgNoTrans( 'noarticletext' );
1388 } else {
1389 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1390 }
1391 }
1392 $text = "<div class='noarticletext'>\n$text\n</div>";
1393
1394 if ( !$this->hasViewableContent() ) {
1395 // If there's no backing content, send a 404 Not Found
1396 // for better machine handling of broken links.
1397 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1398 }
1399
1400 $wgOut->addWikiText( $text );
1401 }
1402
1403 /**
1404 * If the revision requested for view is deleted, check permissions.
1405 * Send either an error message or a warning header to $wgOut.
1406 *
1407 * @return boolean true if the view is allowed, false if not.
1408 */
1409 public function showDeletedRevisionHeader() {
1410 global $wgOut, $wgRequest;
1411
1412 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1413 // Not deleted
1414 return true;
1415 }
1416
1417 // If the user is not allowed to see it...
1418 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1419 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1420 'rev-deleted-text-permission' );
1421
1422 return false;
1423 // If the user needs to confirm that they want to see it...
1424 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1425 # Give explanation and add a link to view the revision...
1426 $oldid = intval( $this->getOldID() );
1427 $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
1428 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1429 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1430 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1431 array( $msg, $link ) );
1432
1433 return false;
1434 // We are allowed to see...
1435 } else {
1436 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1437 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1438 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1439
1440 return true;
1441 }
1442 }
1443
1444 /**
1445 * Should the parser cache be used?
1446 *
1447 * @return boolean
1448 */
1449 public function useParserCache( $oldid ) {
1450 global $wgUser, $wgEnableParserCache;
1451
1452 return $wgEnableParserCache
1453 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1454 && $this->exists()
1455 && empty( $oldid )
1456 && !$this->mTitle->isCssOrJsPage()
1457 && !$this->mTitle->isCssJsSubpage();
1458 }
1459
1460 /**
1461 * Execute the uncached parse for action=view
1462 */
1463 public function doViewParse() {
1464 global $wgOut;
1465
1466 $oldid = $this->getOldID();
1467 $useParserCache = $this->useParserCache( $oldid );
1468 $parserOptions = clone $this->getParserOptions();
1469
1470 # Render printable version, use printable version cache
1471 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1472
1473 # Don't show section-edit links on old revisions... this way lies madness.
1474 $parserOptions->setEditSection( $this->isCurrent() );
1475 $useParserCache = $this->useParserCache( $oldid );
1476 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1477 }
1478
1479 /**
1480 * Try to fetch an expired entry from the parser cache. If it is present,
1481 * output it and return true. If it is not present, output nothing and
1482 * return false. This is used as a callback function for
1483 * PoolCounter::executeProtected().
1484 *
1485 * @return boolean
1486 */
1487 public function tryDirtyCache() {
1488
1489 global $wgOut;
1490 $parserCache = ParserCache::singleton();
1491 $options = $this->getParserOptions();
1492 $options->setIsPrintable( $wgOut->isPrintable() );
1493 $output = $parserCache->getDirty( $this, $options );
1494
1495 if ( $output ) {
1496 wfDebug( __METHOD__ . ": sending dirty output\n" );
1497 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1498 $wgOut->setSquidMaxage( 0 );
1499 $this->mParserOutput = $output;
1500 $wgOut->addParserOutput( $output );
1501 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1502
1503 return true;
1504 } else {
1505 wfDebugLog( 'dirty', "dirty missing\n" );
1506 wfDebug( __METHOD__ . ": no dirty cache\n" );
1507
1508 return false;
1509 }
1510 }
1511
1512 /**
1513 * Show an error page for an error from the pool counter.
1514 * @param $status Status
1515 */
1516 public function showPoolError( $status ) {
1517 global $wgOut;
1518
1519 $wgOut->clearHTML(); // for release() errors
1520 $wgOut->enableClientCache( false );
1521 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1522 $wgOut->addWikiText(
1523 '<div class="errorbox">' .
1524 $status->getWikiText( false, 'view-pool-error' ) .
1525 '</div>'
1526 );
1527 }
1528
1529 /**
1530 * View redirect
1531 *
1532 * @param $target Title object or Array of destination(s) to redirect
1533 * @param $appendSubtitle Boolean [optional]
1534 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1535 * @return string containing HMTL with redirect link
1536 */
1537 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1538 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1539
1540 if ( !is_array( $target ) ) {
1541 $target = array( $target );
1542 }
1543
1544 $imageDir = $wgContLang->getDir();
1545
1546 if ( $appendSubtitle ) {
1547 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1548 }
1549
1550 $sk = $wgUser->getSkin();
1551 // the loop prepends the arrow image before the link, so the first case needs to be outside
1552 $title = array_shift( $target );
1553
1554 if ( $forceKnown ) {
1555 $link = $sk->linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1556 } else {
1557 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1558 }
1559
1560 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1561 $alt = $wgContLang->isRTL() ? '←' : '→';
1562 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1563 // FIXME: where this happens?
1564 foreach ( $target as $rt ) {
1565 $link .= Html::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1566 if ( $forceKnown ) {
1567 $link .= $sk->linkKnown( $rt, htmlspecialchars( $rt->getFullText() ) );
1568 } else {
1569 $link .= $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1570 }
1571 }
1572
1573 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1574 return Html::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1575 '<span class="redirectText">' . $link . '</span>';
1576 }
1577
1578 /**
1579 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1580 */
1581 public function addTrackbacks() {
1582 global $wgOut, $wgUser;
1583
1584 $dbr = wfGetDB( DB_SLAVE );
1585 $tbs = $dbr->select( 'trackbacks',
1586 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1587 array( 'tb_page' => $this->getID() )
1588 );
1589
1590 if ( !$dbr->numRows( $tbs ) ) {
1591 return;
1592 }
1593
1594 $tbtext = "";
1595 while ( $o = $dbr->fetchObject( $tbs ) ) {
1596 $rmvtxt = "";
1597
1598 if ( $wgUser->isAllowed( 'trackback' ) ) {
1599 $delurl = $this->mTitle->getFullURL( "action=deletetrackback&tbid=" .
1600 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1601 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1602 }
1603
1604 $tbtext .= "\n";
1605 $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex ) ? 'trackbackexcerpt' : 'trackback',
1606 $o->tb_title,
1607 $o->tb_url,
1608 $o->tb_ex,
1609 $o->tb_name,
1610 $rmvtxt );
1611 }
1612
1613 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1614 }
1615
1616 /**
1617 * Removes trackback record for current article from trackbacks table
1618 */
1619 public function deletetrackback() {
1620 global $wgUser, $wgRequest, $wgOut;
1621
1622 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1623 $wgOut->addWikiMsg( 'sessionfailure' );
1624
1625 return;
1626 }
1627
1628 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1629
1630 if ( count( $permission_errors ) ) {
1631 $wgOut->showPermissionsErrorPage( $permission_errors );
1632
1633 return;
1634 }
1635
1636 $db = wfGetDB( DB_MASTER );
1637 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1638
1639 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1640 $this->mTitle->invalidateCache();
1641 }
1642
1643 /**
1644 * Handle action=render
1645 */
1646
1647 public function render() {
1648 global $wgOut;
1649
1650 $wgOut->setArticleBodyOnly( true );
1651 $this->view();
1652 }
1653
1654 /**
1655 * Handle action=purge
1656 */
1657 public function purge() {
1658 global $wgUser, $wgRequest, $wgOut;
1659
1660 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1661 //FIXME: shouldn't this be in doPurge()?
1662 if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1663 $this->doPurge();
1664 $this->view();
1665 }
1666 } else {
1667 $formParams = array(
1668 'method' => 'post',
1669 'action' => $wgRequest->getRequestURL(),
1670 );
1671
1672 $wgOut->addWikiMsg( 'confirm-purge-top' );
1673
1674 $form = Html::openElement( 'form', $formParams );
1675 $form .= Xml::submitButton( wfMsg( 'confirm_purge_button' ) );
1676 $form .= Html::closeElement( 'form' );
1677
1678 $wgOut->addHTML( $form );
1679 $wgOut->addWikiMsg( 'confirm-purge-bottom' );
1680
1681 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1682 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1683 }
1684 }
1685
1686 /**
1687 * Perform the actions of a page purging
1688 */
1689 public function doPurge() {
1690 global $wgUseSquid;
1691
1692 // Invalidate the cache
1693 $this->mTitle->invalidateCache();
1694
1695 if ( $wgUseSquid ) {
1696 // Commit the transaction before the purge is sent
1697 $dbw = wfGetDB( DB_MASTER );
1698 $dbw->commit();
1699
1700 // Send purge
1701 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1702 $update->doUpdate();
1703 }
1704
1705 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1706 global $wgMessageCache;
1707
1708 if ( $this->getID() == 0 ) {
1709 $text = false;
1710 } else {
1711 $text = $this->getRawText();
1712 }
1713
1714 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1715 }
1716 }
1717
1718 /**
1719 * Insert a new empty page record for this article.
1720 * This *must* be followed up by creating a revision
1721 * and running $this->updateRevisionOn( ... );
1722 * or else the record will be left in a funky state.
1723 * Best if all done inside a transaction.
1724 *
1725 * @param $dbw Database
1726 * @return int The newly created page_id key, or false if the title already existed
1727 * @private
1728 */
1729 public function insertOn( $dbw ) {
1730 wfProfileIn( __METHOD__ );
1731
1732 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1733 $dbw->insert( 'page', array(
1734 'page_id' => $page_id,
1735 'page_namespace' => $this->mTitle->getNamespace(),
1736 'page_title' => $this->mTitle->getDBkey(),
1737 'page_counter' => 0,
1738 'page_restrictions' => '',
1739 'page_is_redirect' => 0, # Will set this shortly...
1740 'page_is_new' => 1,
1741 'page_random' => wfRandom(),
1742 'page_touched' => $dbw->timestamp(),
1743 'page_latest' => 0, # Fill this in shortly...
1744 'page_len' => 0, # Fill this in shortly...
1745 ), __METHOD__, 'IGNORE' );
1746
1747 $affected = $dbw->affectedRows();
1748
1749 if ( $affected ) {
1750 $newid = $dbw->insertId();
1751 $this->mTitle->resetArticleId( $newid );
1752 }
1753 wfProfileOut( __METHOD__ );
1754
1755 return $affected ? $newid : false;
1756 }
1757
1758 /**
1759 * Update the page record to point to a newly saved revision.
1760 *
1761 * @param $dbw Database object
1762 * @param $revision Revision: For ID number, and text used to set
1763 length and redirect status fields
1764 * @param $lastRevision Integer: if given, will not overwrite the page field
1765 * when different from the currently set value.
1766 * Giving 0 indicates the new page flag should be set
1767 * on.
1768 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1769 * removing rows in redirect table.
1770 * @param $setNewFlag Boolean: Set to true if a page flag should be set
1771 * Needed when $lastRevision has to be set to sth. !=0
1772 * @return bool true on success, false on failure
1773 * @private
1774 */
1775 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null, $setNewFlag = false ) {
1776 wfProfileIn( __METHOD__ );
1777
1778 $text = $revision->getText();
1779 $rt = Title::newFromRedirectRecurse( $text );
1780
1781 $conditions = array( 'page_id' => $this->getId() );
1782
1783 if ( !is_null( $lastRevision ) ) {
1784 # An extra check against threads stepping on each other
1785 $conditions['page_latest'] = $lastRevision;
1786 }
1787
1788 if ( !$setNewFlag ) {
1789 $setNewFlag = ( $lastRevision === 0 );
1790 }
1791
1792 $dbw->update( 'page',
1793 array( /* SET */
1794 'page_latest' => $revision->getId(),
1795 'page_touched' => $dbw->timestamp(),
1796 'page_is_new' => $setNewFlag,
1797 'page_is_redirect' => $rt !== null ? 1 : 0,
1798 'page_len' => strlen( $text ),
1799 ),
1800 $conditions,
1801 __METHOD__ );
1802
1803 $result = $dbw->affectedRows() != 0;
1804 if ( $result ) {
1805 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1806 }
1807
1808 wfProfileOut( __METHOD__ );
1809 return $result;
1810 }
1811
1812 /**
1813 * Add row to the redirect table if this is a redirect, remove otherwise.
1814 *
1815 * @param $dbw Database
1816 * @param $redirectTitle a title object pointing to the redirect target,
1817 * or NULL if this is not a redirect
1818 * @param $lastRevIsRedirect If given, will optimize adding and
1819 * removing rows in redirect table.
1820 * @return bool true on success, false on failure
1821 * @private
1822 */
1823 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1824 // Always update redirects (target link might have changed)
1825 // Update/Insert if we don't know if the last revision was a redirect or not
1826 // Delete if changing from redirect to non-redirect
1827 $isRedirect = !is_null( $redirectTitle );
1828
1829 if ( $isRedirect || is_null( $lastRevIsRedirect ) || $lastRevIsRedirect !== $isRedirect ) {
1830 wfProfileIn( __METHOD__ );
1831 if ( $isRedirect ) {
1832 $this->insertRedirectEntry( $redirectTitle );
1833 } else {
1834 // This is not a redirect, remove row from redirect table
1835 $where = array( 'rd_from' => $this->getId() );
1836 $dbw->delete( 'redirect', $where, __METHOD__ );
1837 }
1838
1839 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1840 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1841 }
1842 wfProfileOut( __METHOD__ );
1843
1844 return ( $dbw->affectedRows() != 0 );
1845 }
1846
1847 return true;
1848 }
1849
1850 /**
1851 * If the given revision is newer than the currently set page_latest,
1852 * update the page record. Otherwise, do nothing.
1853 *
1854 * @param $dbw Database object
1855 * @param $revision Revision object
1856 * @return mixed
1857 */
1858 public function updateIfNewerOn( &$dbw, $revision ) {
1859 wfProfileIn( __METHOD__ );
1860
1861 $row = $dbw->selectRow(
1862 array( 'revision', 'page' ),
1863 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1864 array(
1865 'page_id' => $this->getId(),
1866 'page_latest=rev_id' ),
1867 __METHOD__ );
1868
1869 if ( $row ) {
1870 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1871 wfProfileOut( __METHOD__ );
1872 return false;
1873 }
1874 $prev = $row->rev_id;
1875 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1876 } else {
1877 # No or missing previous revision; mark the page as new
1878 $prev = 0;
1879 $lastRevIsRedirect = null;
1880 }
1881
1882 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1883
1884 wfProfileOut( __METHOD__ );
1885 return $ret;
1886 }
1887
1888 /**
1889 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1890 * @param $text String: new text of the section
1891 * @param $summary String: new section's subject, only if $section is 'new'
1892 * @param $edittime String: revision timestamp or null to use the current revision
1893 * @return string Complete article text, or null if error
1894 */
1895 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1896 wfProfileIn( __METHOD__ );
1897
1898 if ( strval( $section ) == '' ) {
1899 // Whole-page edit; let the whole text through
1900 } else {
1901 if ( is_null( $edittime ) ) {
1902 $rev = Revision::newFromTitle( $this->mTitle );
1903 } else {
1904 $dbw = wfGetDB( DB_MASTER );
1905 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1906 }
1907
1908 if ( !$rev ) {
1909 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1910 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1911 return null;
1912 }
1913
1914 $oldtext = $rev->getText();
1915
1916 if ( $section == 'new' ) {
1917 # Inserting a new section
1918 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1919 $text = strlen( trim( $oldtext ) ) > 0
1920 ? "{$oldtext}\n\n{$subject}{$text}"
1921 : "{$subject}{$text}";
1922 } else {
1923 # Replacing an existing section; roll out the big guns
1924 global $wgParser;
1925
1926 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1927 }
1928 }
1929
1930 wfProfileOut( __METHOD__ );
1931 return $text;
1932 }
1933
1934 /**
1935 * @deprecated use Article::doEdit()
1936 */
1937 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1938 wfDeprecated( __METHOD__ );
1939 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1940 ( $isminor ? EDIT_MINOR : 0 ) |
1941 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1942 ( $bot ? EDIT_FORCE_BOT : 0 );
1943
1944 $this->doEdit( $text, $summary, $flags, false, null, $watchthis, $comment, '', true );
1945 }
1946
1947 /**
1948 * @deprecated use Article::doEdit()
1949 */
1950 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1951 wfDeprecated( __METHOD__ );
1952 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1953 ( $minor ? EDIT_MINOR : 0 ) |
1954 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1955
1956 $status = $this->doEdit( $text, $summary, $flags, false, null, $watchthis, false, $sectionanchor, true );
1957
1958 if ( !$status->isOK() ) {
1959 return false;
1960 }
1961
1962 return true;
1963 }
1964
1965 /**
1966 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1967 * @param $flags Int
1968 * @return Int updated $flags
1969 */
1970 function checkFlags( $flags ) {
1971 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1972 if ( $this->mTitle->getArticleID() ) {
1973 $flags |= EDIT_UPDATE;
1974 } else {
1975 $flags |= EDIT_NEW;
1976 }
1977 }
1978
1979 return $flags;
1980 }
1981
1982 /**
1983 * Article::doEdit()
1984 *
1985 * Change an existing article or create a new article. Updates RC and all necessary caches,
1986 * optionally via the deferred update array.
1987 *
1988 * $wgUser must be set before calling this function.
1989 *
1990 * @param $text String: new text
1991 * @param $summary String: edit summary
1992 * @param $flags Integer bitfield:
1993 * EDIT_NEW
1994 * Article is known or assumed to be non-existent, create a new one
1995 * EDIT_UPDATE
1996 * Article is known or assumed to be pre-existing, update it
1997 * EDIT_MINOR
1998 * Mark this edit minor, if the user is allowed to do so
1999 * EDIT_SUPPRESS_RC
2000 * Do not log the change in recentchanges
2001 * EDIT_FORCE_BOT
2002 * Mark the edit a "bot" edit regardless of user rights
2003 * EDIT_DEFER_UPDATES
2004 * Defer some of the updates until the end of index.php
2005 * EDIT_AUTOSUMMARY
2006 * Fill in blank summaries with generated text where possible
2007 *
2008 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2009 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2010 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2011 * edit-already-exists error will be returned. These two conditions are also possible with
2012 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2013 *
2014 * @param $baseRevId the revision ID this edit was based off, if any
2015 * @param $user Optional user object, $wgUser will be used if not passed
2016 * @param $watchthis Watch the page if true, unwatch the page if false, do nothing if null
2017 * @param $comment Boolean: whether the edit is a new section
2018 * @param $sectionanchor The section anchor for the page; used for redirecting the user back to the page
2019 * after the edit is successfully committed
2020 * @param $redirect If true, redirect the user back to the page after the edit is successfully committed
2021 *
2022 * @return Status object. Possible errors:
2023 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2024 * edit-gone-missing: In update mode, but the article didn't exist
2025 * edit-conflict: In update mode, the article changed unexpectedly
2026 * edit-no-change: Warning that the text was the same as before
2027 * edit-already-exists: In creation mode, but the article already exists
2028 *
2029 * Extensions may define additional errors.
2030 *
2031 * $return->value will contain an associative array with members as follows:
2032 * new: Boolean indicating if the function attempted to create a new article
2033 * revision: The revision object for the inserted revision, or null
2034 *
2035 * Compatibility note: this function previously returned a boolean value indicating success/failure
2036 */
2037 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null , $watchthis = null,
2038 $comment = false, $sectionanchor = '', $redirect = false) {
2039 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2040
2041 # Low-level sanity check
2042 if ( $this->mTitle->getText() === '' ) {
2043 throw new MWException( 'Something is trying to edit an article with an empty title' );
2044 }
2045
2046 wfProfileIn( __METHOD__ );
2047
2048 $user = is_null( $user ) ? $wgUser : $user;
2049 $status = Status::newGood( array() );
2050
2051 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2052 $this->loadPageData();
2053
2054 $flags = $this->checkFlags( $flags );
2055
2056 # If this is a comment, add the summary as headline
2057 if ( $comment && $summary != "" ) {
2058 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
2059 }
2060
2061 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2062 $flags & EDIT_MINOR, &$watchthis, null, &$flags, &$status) ) )
2063 {
2064 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
2065 wfProfileOut( __METHOD__ );
2066
2067 if ( $status->isOK() ) {
2068 $status->fatal( 'edit-hook-aborted' );
2069 }
2070
2071 return $status;
2072 }
2073
2074 # Silently ignore EDIT_MINOR if not allowed
2075 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
2076 $bot = $flags & EDIT_FORCE_BOT;
2077
2078 $oldtext = $this->getRawText(); // current revision
2079 $oldsize = strlen( $oldtext );
2080
2081 # Provide autosummaries if one is not provided and autosummaries are enabled.
2082 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
2083 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2084 }
2085
2086 $editInfo = $this->prepareTextForEdit( $text );
2087 $text = $editInfo->pst;
2088 $newsize = strlen( $text );
2089
2090 $dbw = wfGetDB( DB_MASTER );
2091 $now = wfTimestampNow();
2092 $this->mTimestamp = $now;
2093
2094 if ( $flags & EDIT_UPDATE ) {
2095 # Update article, but only if changed.
2096 $status->value['new'] = false;
2097
2098 # Make sure the revision is either completely inserted or not inserted at all
2099 if ( !$wgDBtransactions ) {
2100 $userAbort = ignore_user_abort( true );
2101 }
2102
2103 $revisionId = 0;
2104
2105 $changed = ( strcmp( $text, $oldtext ) != 0 );
2106
2107 if ( $changed ) {
2108 $this->mGoodAdjustment = (int)$this->isCountable( $text )
2109 - (int)$this->isCountable( $oldtext );
2110 $this->mTotalAdjustment = 0;
2111
2112 if ( !$this->mLatest ) {
2113 # Article gone missing
2114 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
2115 $status->fatal( 'edit-gone-missing' );
2116
2117 wfProfileOut( __METHOD__ );
2118 return $status;
2119 }
2120
2121 $revision = new Revision( array(
2122 'page' => $this->getId(),
2123 'comment' => $summary,
2124 'minor_edit' => $isminor,
2125 'text' => $text,
2126 'parent_id' => $this->mLatest,
2127 'user' => $user->getId(),
2128 'user_text' => $user->getName(),
2129 ) );
2130
2131 $dbw->begin();
2132 $revisionId = $revision->insertOn( $dbw );
2133
2134 # Update page
2135 #
2136 # Note that we use $this->mLatest instead of fetching a value from the master DB
2137 # during the course of this function. This makes sure that EditPage can detect
2138 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2139 # before this function is called. A previous function used a separate query, this
2140 # creates a window where concurrent edits can cause an ignored edit conflict.
2141 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
2142
2143 if ( !$ok ) {
2144 /* Belated edit conflict! Run away!! */
2145 $status->fatal( 'edit-conflict' );
2146
2147 # Delete the invalid revision if the DB is not transactional
2148 if ( !$wgDBtransactions ) {
2149 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
2150 }
2151
2152 $revisionId = 0;
2153 $dbw->rollback();
2154 } else {
2155 global $wgUseRCPatrol;
2156 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2157 # Update recentchanges
2158 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2159 # Mark as patrolled if the user can do so
2160 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan( 'autopatrol' );
2161 # Add RC row to the DB
2162 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
2163 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2164 $revisionId, $patrolled
2165 );
2166
2167 # Log auto-patrolled edits
2168 if ( $patrolled ) {
2169 PatrolLog::record( $rc, true );
2170 }
2171 }
2172 $user->incEditCount();
2173 $dbw->commit();
2174 }
2175 } else {
2176 $status->warning( 'edit-no-change' );
2177 $revision = null;
2178 // Keep the same revision ID, but do some updates on it
2179 $revisionId = $this->getRevIdFetched();
2180 // Update page_touched, this is usually implicit in the page update
2181 // Other cache updates are done in onArticleEdit()
2182 $this->mTitle->invalidateCache();
2183 }
2184
2185 if ( !$wgDBtransactions ) {
2186 ignore_user_abort( $userAbort );
2187 }
2188
2189 // Now that ignore_user_abort is restored, we can respond to fatal errors
2190 if ( !$status->isOK() ) {
2191 wfProfileOut( __METHOD__ );
2192 return $status;
2193 }
2194
2195 # Invalidate cache of this article and all pages using this article
2196 # as a template. Partly deferred.
2197 Article::onArticleEdit( $this->mTitle );
2198 # Update links tables, site stats, etc.
2199 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2200 } else {
2201 # Create new article
2202 $status->value['new'] = true;
2203
2204 # Set statistics members
2205 # We work out if it's countable after PST to avoid counter drift
2206 # when articles are created with {{subst:}}
2207 $this->mGoodAdjustment = (int)$this->isCountable( $text );
2208 $this->mTotalAdjustment = 1;
2209
2210 $dbw->begin();
2211
2212 # Add the page record; stake our claim on this title!
2213 # This will return false if the article already exists
2214 $newid = $this->insertOn( $dbw );
2215
2216 if ( $newid === false ) {
2217 $dbw->rollback();
2218 $status->fatal( 'edit-already-exists' );
2219
2220 wfProfileOut( __METHOD__ );
2221 return $status;
2222 }
2223
2224 # Save the revision text...
2225 $revision = new Revision( array(
2226 'page' => $newid,
2227 'comment' => $summary,
2228 'minor_edit' => $isminor,
2229 'text' => $text,
2230 'user' => $user->getId(),
2231 'user_text' => $user->getName(),
2232 ) );
2233 $revisionId = $revision->insertOn( $dbw );
2234
2235 $this->mTitle->resetArticleID( $newid );
2236
2237 # Update the page record with revision data
2238 $this->updateRevisionOn( $dbw, $revision, 0 );
2239
2240 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2241
2242 # Update recentchanges
2243 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2244 global $wgUseRCPatrol, $wgUseNPPatrol;
2245
2246 # Mark as patrolled if the user can do so
2247 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && $this->mTitle->userCan( 'autopatrol' );
2248 # Add RC row to the DB
2249 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2250 '', strlen( $text ), $revisionId, $patrolled );
2251
2252 # Log auto-patrolled edits
2253 if ( $patrolled ) {
2254 PatrolLog::record( $rc, true );
2255 }
2256 }
2257 $user->incEditCount();
2258 $dbw->commit();
2259
2260 # Update links, etc.
2261 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2262
2263 # Clear caches
2264 Article::onArticleCreate( $this->mTitle );
2265
2266 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2267 $flags & EDIT_MINOR, &$watchthis, null, &$flags, $revision ) );
2268 }
2269
2270 # Do updates right now unless deferral was requested
2271 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
2272 wfDoUpdates();
2273 }
2274
2275 // Return the new revision (or null) to the caller
2276 $status->value['revision'] = $revision;
2277
2278 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2279 $flags & EDIT_MINOR, &$watchthis, null, &$flags, $revision, &$status, $baseRevId,
2280 &$redirect) );
2281
2282 # Watch or unwatch the page
2283 if ( $watchthis === true ) {
2284 if ( !$this->mTitle->userIsWatching() ) {
2285 $dbw->begin();
2286 $this->doWatch();
2287 $dbw->commit();
2288 }
2289 } elseif ( $watchthis === false ) {
2290 if ( $this->mTitle->userIsWatching() ) {
2291 $dbw->begin();
2292 $this->doUnwatch();
2293 $dbw->commit();
2294 }
2295 }
2296
2297 # Give extensions a chance to modify URL query on update
2298 $extraQuery = '';
2299
2300 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
2301
2302 if ( $redirect ) {
2303 if ( $sectionanchor || $extraQuery ) {
2304 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
2305 } else {
2306 $this->doRedirect( $this->isRedirect( $text ) );
2307 }
2308 }
2309
2310 wfProfileOut( __METHOD__ );
2311
2312 return $status;
2313 }
2314
2315 /**
2316 * @deprecated wrapper for doRedirect
2317 */
2318 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2319 wfDeprecated( __METHOD__ );
2320 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2321 }
2322
2323 /**
2324 * Output a redirect back to the article.
2325 * This is typically used after an edit.
2326 *
2327 * @param $noRedir Boolean: add redirect=no
2328 * @param $sectionAnchor String: section to redirect to, including "#"
2329 * @param $extraQuery String: extra query params
2330 */
2331 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2332 global $wgOut;
2333
2334 if ( $noRedir ) {
2335 $query = 'redirect=no';
2336 if ( $extraQuery )
2337 $query .= "&$extraQuery";
2338 } else {
2339 $query = $extraQuery;
2340 }
2341
2342 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2343 }
2344
2345 /**
2346 * Mark this particular edit/page as patrolled
2347 */
2348 public function markpatrolled() {
2349 global $wgOut, $wgUser, $wgRequest;
2350
2351 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2352
2353 # If we haven't been given an rc_id value, we can't do anything
2354 $rcid = (int) $wgRequest->getVal( 'rcid' );
2355
2356 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2357 $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2358 return;
2359 }
2360
2361 $rc = RecentChange::newFromId( $rcid );
2362
2363 if ( is_null( $rc ) ) {
2364 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2365 return;
2366 }
2367
2368 # It would be nice to see where the user had actually come from, but for now just guess
2369 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2370 $return = SpecialPage::getTitleFor( $returnto );
2371
2372 $errors = $rc->doMarkPatrolled();
2373
2374 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2375 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2376
2377 return;
2378 }
2379
2380 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2381 // The hook itself has handled any output
2382 return;
2383 }
2384
2385 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2386 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2387 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2388 $wgOut->returnToMain( false, $return );
2389
2390 return;
2391 }
2392
2393 if ( !empty( $errors ) ) {
2394 $wgOut->showPermissionsErrorPage( $errors );
2395
2396 return;
2397 }
2398
2399 # Inform the user
2400 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2401 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2402 $wgOut->returnToMain( false, $return );
2403 }
2404
2405 /**
2406 * User-interface handler for the "watch" action
2407 */
2408 public function watch() {
2409 global $wgUser, $wgOut;
2410
2411 if ( $wgUser->isAnon() ) {
2412 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2413 return;
2414 }
2415
2416 if ( wfReadOnly() ) {
2417 $wgOut->readOnlyPage();
2418 return;
2419 }
2420
2421 if ( $this->doWatch() ) {
2422 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2423 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2424 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2425 }
2426
2427 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2428 }
2429
2430 /**
2431 * Add this page to $wgUser's watchlist
2432 * @return bool true on successful watch operation
2433 */
2434 public function doWatch() {
2435 global $wgUser;
2436
2437 if ( $wgUser->isAnon() ) {
2438 return false;
2439 }
2440
2441 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2442 $wgUser->addWatch( $this->mTitle );
2443 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2444 }
2445
2446 return false;
2447 }
2448
2449 /**
2450 * User interface handler for the "unwatch" action.
2451 */
2452 public function unwatch() {
2453 global $wgUser, $wgOut;
2454
2455 if ( $wgUser->isAnon() ) {
2456 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2457 return;
2458 }
2459
2460 if ( wfReadOnly() ) {
2461 $wgOut->readOnlyPage();
2462 return;
2463 }
2464
2465 if ( $this->doUnwatch() ) {
2466 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2467 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2468 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2469 }
2470
2471 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2472 }
2473
2474 /**
2475 * Stop watching a page
2476 * @return bool true on successful unwatch
2477 */
2478 public function doUnwatch() {
2479 global $wgUser;
2480
2481 if ( $wgUser->isAnon() ) {
2482 return false;
2483 }
2484
2485 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2486 $wgUser->removeWatch( $this->mTitle );
2487 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2488 }
2489
2490 return false;
2491 }
2492
2493 /**
2494 * action=protect handler
2495 */
2496 public function protect() {
2497 $form = new ProtectionForm( $this );
2498 $form->execute();
2499 }
2500
2501 /**
2502 * action=unprotect handler (alias)
2503 */
2504 public function unprotect() {
2505 $this->protect();
2506 }
2507
2508 /**
2509 * Update the article's restriction field, and leave a log entry.
2510 *
2511 * @param $limit Array: set of restriction keys
2512 * @param $reason String
2513 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2514 * @param $expiry Array: per restriction type expiration
2515 * @return bool true on success
2516 */
2517 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2518 global $wgUser, $wgContLang;
2519
2520 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2521
2522 $id = $this->mTitle->getArticleID();
2523
2524 if ( $id <= 0 ) {
2525 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2526 return false;
2527 }
2528
2529 if ( wfReadOnly() ) {
2530 wfDebug( "updateRestrictions failed: read-only\n" );
2531 return false;
2532 }
2533
2534 if ( !$this->mTitle->userCan( 'protect' ) ) {
2535 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2536 return false;
2537 }
2538
2539 if ( !$cascade ) {
2540 $cascade = false;
2541 }
2542
2543 // Take this opportunity to purge out expired restrictions
2544 Title::purgeExpiredRestrictions();
2545
2546 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2547 # we expect a single selection, but the schema allows otherwise.
2548 $current = array();
2549 $updated = Article::flattenRestrictions( $limit );
2550 $changed = false;
2551
2552 foreach ( $restrictionTypes as $action ) {
2553 if ( isset( $expiry[$action] ) ) {
2554 # Get current restrictions on $action
2555 $aLimits = $this->mTitle->getRestrictions( $action );
2556 $current[$action] = implode( '', $aLimits );
2557 # Are any actual restrictions being dealt with here?
2558 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
2559
2560 # If something changed, we need to log it. Checking $aRChanged
2561 # assures that "unprotecting" a page that is not protected does
2562 # not log just because the expiry was "changed".
2563 if ( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2564 $changed = true;
2565 }
2566 }
2567 }
2568
2569 $current = Article::flattenRestrictions( $current );
2570
2571 $changed = ( $changed || $current != $updated );
2572 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
2573 $protect = ( $updated != '' );
2574
2575 # If nothing's changed, do nothing
2576 if ( $changed ) {
2577 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2578 $dbw = wfGetDB( DB_MASTER );
2579
2580 # Prepare a null revision to be added to the history
2581 $modified = $current != '' && $protect;
2582
2583 if ( $protect ) {
2584 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2585 } else {
2586 $comment_type = 'unprotectedarticle';
2587 }
2588
2589 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2590
2591 # Only restrictions with the 'protect' right can cascade...
2592 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2593 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2594
2595 # The schema allows multiple restrictions
2596 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2597 $cascade = false;
2598 }
2599
2600 $cascade_description = '';
2601
2602 if ( $cascade ) {
2603 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2604 }
2605
2606 if ( $reason ) {
2607 $comment .= ": $reason";
2608 }
2609
2610 $editComment = $comment;
2611 $encodedExpiry = array();
2612 $protect_description = '';
2613 foreach ( $limit as $action => $restrictions ) {
2614 if ( !isset( $expiry[$action] ) )
2615 $expiry[$action] = 'infinite';
2616
2617 $encodedExpiry[$action] = Block::encodeExpiry( $expiry[$action], $dbw );
2618 if ( $restrictions != '' ) {
2619 $protect_description .= "[$action=$restrictions] (";
2620 if ( $encodedExpiry[$action] != 'infinity' ) {
2621 $protect_description .= wfMsgForContent( 'protect-expiring',
2622 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2623 $wgContLang->date( $expiry[$action], false, false ) ,
2624 $wgContLang->time( $expiry[$action], false, false ) );
2625 } else {
2626 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2627 }
2628
2629 $protect_description .= ') ';
2630 }
2631 }
2632 $protect_description = trim( $protect_description );
2633
2634 if ( $protect_description && $protect ) {
2635 $editComment .= " ($protect_description)";
2636 }
2637
2638 if ( $cascade ) {
2639 $editComment .= "$cascade_description";
2640 }
2641
2642 # Update restrictions table
2643 foreach ( $limit as $action => $restrictions ) {
2644 if ( $restrictions != '' ) {
2645 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2646 array( 'pr_page' => $id,
2647 'pr_type' => $action,
2648 'pr_level' => $restrictions,
2649 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2650 'pr_expiry' => $encodedExpiry[$action]
2651 ),
2652 __METHOD__
2653 );
2654 } else {
2655 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2656 'pr_type' => $action ), __METHOD__ );
2657 }
2658 }
2659
2660 # Insert a null revision
2661 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2662 $nullRevId = $nullRevision->insertOn( $dbw );
2663
2664 $latest = $this->getLatest();
2665 # Update page record
2666 $dbw->update( 'page',
2667 array( /* SET */
2668 'page_touched' => $dbw->timestamp(),
2669 'page_restrictions' => '',
2670 'page_latest' => $nullRevId
2671 ), array( /* WHERE */
2672 'page_id' => $id
2673 ), 'Article::protect'
2674 );
2675
2676 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2677 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2678
2679 # Update the protection log
2680 $log = new LogPage( 'protect' );
2681 if ( $protect ) {
2682 $params = array( $protect_description, $cascade ? 'cascade' : '' );
2683 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
2684 } else {
2685 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2686 }
2687 } # End hook
2688 } # End "changed" check
2689
2690 return true;
2691 }
2692
2693 /**
2694 * Take an array of page restrictions and flatten it to a string
2695 * suitable for insertion into the page_restrictions field.
2696 * @param $limit Array
2697 * @return String
2698 */
2699 protected static function flattenRestrictions( $limit ) {
2700 if ( !is_array( $limit ) ) {
2701 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2702 }
2703
2704 $bits = array();
2705 ksort( $limit );
2706
2707 foreach ( $limit as $action => $restrictions ) {
2708 if ( $restrictions != '' ) {
2709 $bits[] = "$action=$restrictions";
2710 }
2711 }
2712
2713 return implode( ':', $bits );
2714 }
2715
2716 /**
2717 * Auto-generates a deletion reason
2718 *
2719 * @param &$hasHistory Boolean: whether the page has a history
2720 * @return mixed String containing deletion reason or empty string, or boolean false
2721 * if no revision occurred
2722 */
2723 public function generateReason( &$hasHistory ) {
2724 global $wgContLang;
2725
2726 $dbw = wfGetDB( DB_MASTER );
2727 // Get the last revision
2728 $rev = Revision::newFromTitle( $this->mTitle );
2729
2730 if ( is_null( $rev ) ) {
2731 return false;
2732 }
2733
2734 // Get the article's contents
2735 $contents = $rev->getText();
2736 $blank = false;
2737
2738 // If the page is blank, use the text from the previous revision,
2739 // which can only be blank if there's a move/import/protect dummy revision involved
2740 if ( $contents == '' ) {
2741 $prev = $rev->getPrevious();
2742
2743 if ( $prev ) {
2744 $contents = $prev->getText();
2745 $blank = true;
2746 }
2747 }
2748
2749 // Find out if there was only one contributor
2750 // Only scan the last 20 revisions
2751 $res = $dbw->select( 'revision', 'rev_user_text',
2752 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2753 __METHOD__,
2754 array( 'LIMIT' => 20 )
2755 );
2756
2757 if ( $res === false ) {
2758 // This page has no revisions, which is very weird
2759 return false;
2760 }
2761
2762 $hasHistory = ( $res->numRows() > 1 );
2763 $row = $dbw->fetchObject( $res );
2764
2765 if ( $row ) { // $row is false if the only contributor is hidden
2766 $onlyAuthor = $row->rev_user_text;
2767 // Try to find a second contributor
2768 foreach ( $res as $row ) {
2769 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2770 $onlyAuthor = false;
2771 break;
2772 }
2773 }
2774 } else {
2775 $onlyAuthor = false;
2776 }
2777
2778 $dbw->freeResult( $res );
2779
2780 // Generate the summary with a '$1' placeholder
2781 if ( $blank ) {
2782 // The current revision is blank and the one before is also
2783 // blank. It's just not our lucky day
2784 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2785 } else {
2786 if ( $onlyAuthor ) {
2787 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2788 } else {
2789 $reason = wfMsgForContent( 'excontent', '$1' );
2790 }
2791 }
2792
2793 if ( $reason == '-' ) {
2794 // Allow these UI messages to be blanked out cleanly
2795 return '';
2796 }
2797
2798 // Replace newlines with spaces to prevent uglyness
2799 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2800 // Calculate the maximum amount of chars to get
2801 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2802 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2803 $contents = $wgContLang->truncate( $contents, $maxLength );
2804 // Remove possible unfinished links
2805 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2806 // Now replace the '$1' placeholder
2807 $reason = str_replace( '$1', $contents, $reason );
2808
2809 return $reason;
2810 }
2811
2812
2813 /*
2814 * UI entry point for page deletion
2815 */
2816 public function delete() {
2817 global $wgUser, $wgOut, $wgRequest;
2818
2819 $confirm = $wgRequest->wasPosted() &&
2820 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2821
2822 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2823 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2824
2825 $reason = $this->DeleteReasonList;
2826
2827 if ( $reason != 'other' && $this->DeleteReason != '' ) {
2828 // Entry from drop down menu + additional comment
2829 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2830 } elseif ( $reason == 'other' ) {
2831 $reason = $this->DeleteReason;
2832 }
2833
2834 # Flag to hide all contents of the archived revisions
2835 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2836
2837 # This code desperately needs to be totally rewritten
2838
2839 # Read-only check...
2840 if ( wfReadOnly() ) {
2841 $wgOut->readOnlyPage();
2842
2843 return;
2844 }
2845
2846 # Check permissions
2847 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2848
2849 if ( count( $permission_errors ) > 0 ) {
2850 $wgOut->showPermissionsErrorPage( $permission_errors );
2851
2852 return;
2853 }
2854
2855 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2856
2857 # Better double-check that it hasn't been deleted yet!
2858 $dbw = wfGetDB( DB_MASTER );
2859 $conds = $this->mTitle->pageCond();
2860 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2861 if ( $latest === false ) {
2862 $wgOut->showFatalError(
2863 Html::rawElement(
2864 'div',
2865 array( 'class' => 'error mw-error-cannotdelete' ),
2866 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2867 )
2868 );
2869 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2870 LogEventsList::showLogExtract(
2871 $wgOut,
2872 'delete',
2873 $this->mTitle->getPrefixedText()
2874 );
2875
2876 return;
2877 }
2878
2879 # Hack for big sites
2880 $bigHistory = $this->isBigDeletion();
2881 if ( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2882 global $wgLang, $wgDeleteRevisionsLimit;
2883
2884 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2885 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2886
2887 return;
2888 }
2889
2890 if ( $confirm ) {
2891 $this->doDelete( $reason, $suppress );
2892
2893 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2894 $this->doWatch();
2895 } elseif ( $this->mTitle->userIsWatching() ) {
2896 $this->doUnwatch();
2897 }
2898
2899 return;
2900 }
2901
2902 // Generate deletion reason
2903 $hasHistory = false;
2904 if ( !$reason ) {
2905 $reason = $this->generateReason( $hasHistory );
2906 }
2907
2908 // If the page has a history, insert a warning
2909 if ( $hasHistory && !$confirm ) {
2910 global $wgLang;
2911
2912 $skin = $wgUser->getSkin();
2913 $revisions = $this->estimateRevisionCount();
2914 //FIXME: lego
2915 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2916 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2917 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2918 '</strong>'
2919 );
2920
2921 if ( $bigHistory ) {
2922 global $wgDeleteRevisionsLimit;
2923 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2924 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2925 }
2926 }
2927
2928 return $this->confirmDelete( $reason );
2929 }
2930
2931 /**
2932 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2933 */
2934 public function isBigDeletion() {
2935 global $wgDeleteRevisionsLimit;
2936
2937 if ( $wgDeleteRevisionsLimit ) {
2938 $revCount = $this->estimateRevisionCount();
2939
2940 return $revCount > $wgDeleteRevisionsLimit;
2941 }
2942
2943 return false;
2944 }
2945
2946 /**
2947 * @return int approximate revision count
2948 */
2949 public function estimateRevisionCount() {
2950 $dbr = wfGetDB( DB_SLAVE );
2951
2952 // For an exact count...
2953 // return $dbr->selectField( 'revision', 'COUNT(*)',
2954 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2955 return $dbr->estimateRowCount( 'revision', '*',
2956 array( 'rev_page' => $this->getId() ), __METHOD__ );
2957 }
2958
2959 /**
2960 * Get the last N authors
2961 * @param $num Integer: number of revisions to get
2962 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2963 * @return array Array of authors, duplicates not removed
2964 */
2965 public function getLastNAuthors( $num, $revLatest = 0 ) {
2966 wfProfileIn( __METHOD__ );
2967 // First try the slave
2968 // If that doesn't have the latest revision, try the master
2969 $continue = 2;
2970 $db = wfGetDB( DB_SLAVE );
2971
2972 do {
2973 $res = $db->select( array( 'page', 'revision' ),
2974 array( 'rev_id', 'rev_user_text' ),
2975 array(
2976 'page_namespace' => $this->mTitle->getNamespace(),
2977 'page_title' => $this->mTitle->getDBkey(),
2978 'rev_page = page_id'
2979 ), __METHOD__, $this->getSelectOptions( array(
2980 'ORDER BY' => 'rev_timestamp DESC',
2981 'LIMIT' => $num
2982 ) )
2983 );
2984
2985 if ( !$res ) {
2986 wfProfileOut( __METHOD__ );
2987 return array();
2988 }
2989
2990 $row = $db->fetchObject( $res );
2991
2992 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2993 $db = wfGetDB( DB_MASTER );
2994 $continue--;
2995 } else {
2996 $continue = 0;
2997 }
2998 } while ( $continue );
2999
3000 $authors = array( $row->rev_user_text );
3001
3002 while ( $row = $db->fetchObject( $res ) ) {
3003 $authors[] = $row->rev_user_text;
3004 }
3005
3006 wfProfileOut( __METHOD__ );
3007 return $authors;
3008 }
3009
3010 /**
3011 * Output deletion confirmation dialog
3012 * FIXME: Move to another file?
3013 * @param $reason String: prefilled reason
3014 */
3015 public function confirmDelete( $reason ) {
3016 global $wgOut, $wgUser;
3017
3018 wfDebug( "Article::confirmDelete\n" );
3019
3020 $deleteBackLink = $wgUser->getSkin()->linkKnown( $this->mTitle );
3021 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
3022 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3023 $wgOut->addWikiMsg( 'confirmdeletetext' );
3024
3025 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
3026
3027 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
3028 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
3029 <td></td>
3030 <td class='mw-input'><strong>" .
3031 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
3032 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
3033 "</strong></td>
3034 </tr>";
3035 } else {
3036 $suppress = '';
3037 }
3038 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
3039
3040 $form = Xml::openElement( 'form', array( 'method' => 'post',
3041 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
3042 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
3043 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
3044 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
3045 "<tr id=\"wpDeleteReasonListRow\">
3046 <td class='mw-label'>" .
3047 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
3048 "</td>
3049 <td class='mw-input'>" .
3050 Xml::listDropDown( 'wpDeleteReasonList',
3051 wfMsgForContent( 'deletereason-dropdown' ),
3052 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
3053 "</td>
3054 </tr>
3055 <tr id=\"wpDeleteReasonRow\">
3056 <td class='mw-label'>" .
3057 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
3058 "</td>
3059 <td class='mw-input'>" .
3060 Html::input( 'wpReason', $reason, 'text', array(
3061 'size' => '60',
3062 'maxlength' => '255',
3063 'tabindex' => '2',
3064 'id' => 'wpReason',
3065 'autofocus'
3066 ) ) .
3067 "</td>
3068 </tr>";
3069
3070 # Disallow watching if user is not logged in
3071 if ( $wgUser->isLoggedIn() ) {
3072 $form .= "
3073 <tr>
3074 <td></td>
3075 <td class='mw-input'>" .
3076 Xml::checkLabel( wfMsg( 'watchthis' ),
3077 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
3078 "</td>
3079 </tr>";
3080 }
3081
3082 $form .= "
3083 $suppress
3084 <tr>
3085 <td></td>
3086 <td class='mw-submit'>" .
3087 Xml::submitButton( wfMsg( 'deletepage' ),
3088 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
3089 "</td>
3090 </tr>" .
3091 Xml::closeElement( 'table' ) .
3092 Xml::closeElement( 'fieldset' ) .
3093 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
3094 Xml::closeElement( 'form' );
3095
3096 if ( $wgUser->isAllowed( 'editinterface' ) ) {
3097 $skin = $wgUser->getSkin();
3098 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
3099 $link = $skin->link(
3100 $title,
3101 wfMsgHtml( 'delete-edit-reasonlist' ),
3102 array(),
3103 array( 'action' => 'edit' )
3104 );
3105 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3106 }
3107
3108 $wgOut->addHTML( $form );
3109 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3110 LogEventsList::showLogExtract( $wgOut, 'delete',
3111 $this->mTitle->getPrefixedText()
3112 );
3113 }
3114
3115 /**
3116 * Perform a deletion and output success or failure messages
3117 */
3118 public function doDelete( $reason, $suppress = false ) {
3119 global $wgOut, $wgUser;
3120
3121 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
3122
3123 $error = '';
3124 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3125 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
3126 $deleted = $this->mTitle->getPrefixedText();
3127
3128 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3129 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3130
3131 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3132
3133 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3134 $wgOut->returnToMain( false );
3135 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3136 }
3137 } else {
3138 if ( $error == '' ) {
3139 $wgOut->showFatalError(
3140 Html::rawElement(
3141 'div',
3142 array( 'class' => 'error mw-error-cannotdelete' ),
3143 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
3144 )
3145 );
3146
3147 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3148
3149 LogEventsList::showLogExtract(
3150 $wgOut,
3151 'delete',
3152 $this->mTitle->getPrefixedText()
3153 );
3154 } else {
3155 $wgOut->showFatalError( $error );
3156 }
3157 }
3158 }
3159
3160 /**
3161 * Back-end article deletion
3162 * Deletes the article with database consistency, writes logs, purges caches
3163 *
3164 * @param $reason string delete reason for deletion log
3165 * @param suppress bitfield
3166 * Revision::DELETED_TEXT
3167 * Revision::DELETED_COMMENT
3168 * Revision::DELETED_USER
3169 * Revision::DELETED_RESTRICTED
3170 * @param $id int article ID
3171 * @param $commit boolean defaults to true, triggers transaction end
3172 * @return boolean true if successful
3173 */
3174 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
3175 global $wgDeferredUpdateList, $wgUseTrackbacks;
3176
3177 wfDebug( __METHOD__ . "\n" );
3178
3179 $dbw = wfGetDB( DB_MASTER );
3180 $ns = $this->mTitle->getNamespace();
3181 $t = $this->mTitle->getDBkey();
3182 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
3183
3184 if ( $t === '' || $id == 0 ) {
3185 return false;
3186 }
3187
3188 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3189 array_push( $wgDeferredUpdateList, $u );
3190
3191 // Bitfields to further suppress the content
3192 if ( $suppress ) {
3193 $bitfield = 0;
3194 // This should be 15...
3195 $bitfield |= Revision::DELETED_TEXT;
3196 $bitfield |= Revision::DELETED_COMMENT;
3197 $bitfield |= Revision::DELETED_USER;
3198 $bitfield |= Revision::DELETED_RESTRICTED;
3199 } else {
3200 $bitfield = 'rev_deleted';
3201 }
3202
3203 $dbw->begin();
3204 // For now, shunt the revision data into the archive table.
3205 // Text is *not* removed from the text table; bulk storage
3206 // is left intact to avoid breaking block-compression or
3207 // immutable storage schemes.
3208 //
3209 // For backwards compatibility, note that some older archive
3210 // table entries will have ar_text and ar_flags fields still.
3211 //
3212 // In the future, we may keep revisions and mark them with
3213 // the rev_deleted field, which is reserved for this purpose.
3214 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3215 array(
3216 'ar_namespace' => 'page_namespace',
3217 'ar_title' => 'page_title',
3218 'ar_comment' => 'rev_comment',
3219 'ar_user' => 'rev_user',
3220 'ar_user_text' => 'rev_user_text',
3221 'ar_timestamp' => 'rev_timestamp',
3222 'ar_minor_edit' => 'rev_minor_edit',
3223 'ar_rev_id' => 'rev_id',
3224 'ar_text_id' => 'rev_text_id',
3225 'ar_text' => '\'\'', // Be explicit to appease
3226 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3227 'ar_len' => 'rev_len',
3228 'ar_page_id' => 'page_id',
3229 'ar_deleted' => $bitfield
3230 ), array(
3231 'page_id' => $id,
3232 'page_id = rev_page'
3233 ), __METHOD__
3234 );
3235
3236 # Delete restrictions for it
3237 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
3238
3239 # Now that it's safely backed up, delete it
3240 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
3241 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3242
3243 if ( !$ok ) {
3244 $dbw->rollback();
3245 return false;
3246 }
3247
3248 # Fix category table counts
3249 $cats = array();
3250 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
3251
3252 foreach ( $res as $row ) {
3253 $cats [] = $row->cl_to;
3254 }
3255
3256 $this->updateCategoryCounts( array(), $cats );
3257
3258 # If using cascading deletes, we can skip some explicit deletes
3259 if ( !$dbw->cascadingDeletes() ) {
3260 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
3261
3262 if ( $wgUseTrackbacks )
3263 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
3264
3265 # Delete outgoing links
3266 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3267 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3268 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3269 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3270 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3271 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3272 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3273 }
3274
3275 # If using cleanup triggers, we can skip some manual deletes
3276 if ( !$dbw->cleanupTriggers() ) {
3277 # Clean up recentchanges entries...
3278 $dbw->delete( 'recentchanges',
3279 array( 'rc_type != ' . RC_LOG,
3280 'rc_namespace' => $this->mTitle->getNamespace(),
3281 'rc_title' => $this->mTitle->getDBkey() ),
3282 __METHOD__ );
3283 $dbw->delete( 'recentchanges',
3284 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
3285 __METHOD__ );
3286 }
3287
3288 # Clear caches
3289 Article::onArticleDelete( $this->mTitle );
3290
3291 # Clear the cached article id so the interface doesn't act like we exist
3292 $this->mTitle->resetArticleID( 0 );
3293
3294 # Log the deletion, if the page was suppressed, log it at Oversight instead
3295 $logtype = $suppress ? 'suppress' : 'delete';
3296 $log = new LogPage( $logtype );
3297
3298 # Make sure logging got through
3299 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
3300
3301 if ( $commit ) {
3302 $dbw->commit();
3303 }
3304
3305 return true;
3306 }
3307
3308 /**
3309 * Roll back the most recent consecutive set of edits to a page
3310 * from the same user; fails if there are no eligible edits to
3311 * roll back to, e.g. user is the sole contributor. This function
3312 * performs permissions checks on $wgUser, then calls commitRollback()
3313 * to do the dirty work
3314 *
3315 * @param $fromP String: Name of the user whose edits to rollback.
3316 * @param $summary String: Custom summary. Set to default summary if empty.
3317 * @param $token String: Rollback token.
3318 * @param $bot Boolean: If true, mark all reverted edits as bot.
3319 *
3320 * @param $resultDetails Array: contains result-specific array of additional values
3321 * 'alreadyrolled' : 'current' (rev)
3322 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3323 *
3324 * @return array of errors, each error formatted as
3325 * array(messagekey, param1, param2, ...).
3326 * On success, the array is empty. This array can also be passed to
3327 * OutputPage::showPermissionsErrorPage().
3328 */
3329 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3330 global $wgUser;
3331
3332 $resultDetails = null;
3333
3334 # Check permissions
3335 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
3336 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
3337 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3338
3339 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
3340 $errors[] = array( 'sessionfailure' );
3341 }
3342
3343 if ( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
3344 $errors[] = array( 'actionthrottledtext' );
3345 }
3346
3347 # If there were errors, bail out now
3348 if ( !empty( $errors ) ) {
3349 return $errors;
3350 }
3351
3352 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3353 }
3354
3355 /**
3356 * Backend implementation of doRollback(), please refer there for parameter
3357 * and return value documentation
3358 *
3359 * NOTE: This function does NOT check ANY permissions, it just commits the
3360 * rollback to the DB Therefore, you should only call this function direct-
3361 * ly if you want to use custom permissions checks. If you don't, use
3362 * doRollback() instead.
3363 */
3364 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3365 global $wgUseRCPatrol, $wgUser, $wgLang;
3366
3367 $dbw = wfGetDB( DB_MASTER );
3368
3369 if ( wfReadOnly() ) {
3370 return array( array( 'readonlytext' ) );
3371 }
3372
3373 # Get the last editor
3374 $current = Revision::newFromTitle( $this->mTitle );
3375 if ( is_null( $current ) ) {
3376 # Something wrong... no page?
3377 return array( array( 'notanarticle' ) );
3378 }
3379
3380 $from = str_replace( '_', ' ', $fromP );
3381 # User name given should match up with the top revision.
3382 # If the user was deleted then $from should be empty.
3383 if ( $from != $current->getUserText() ) {
3384 $resultDetails = array( 'current' => $current );
3385 return array( array( 'alreadyrolled',
3386 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3387 htmlspecialchars( $fromP ),
3388 htmlspecialchars( $current->getUserText() )
3389 ) );
3390 }
3391
3392 # Get the last edit not by this guy...
3393 # Note: these may not be public values
3394 $user = intval( $current->getRawUser() );
3395 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3396 $s = $dbw->selectRow( 'revision',
3397 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3398 array( 'rev_page' => $current->getPage(),
3399 "rev_user != {$user} OR rev_user_text != {$user_text}"
3400 ), __METHOD__,
3401 array( 'USE INDEX' => 'page_timestamp',
3402 'ORDER BY' => 'rev_timestamp DESC' )
3403 );
3404 if ( $s === false ) {
3405 # No one else ever edited this page
3406 return array( array( 'cantrollback' ) );
3407 } else if ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
3408 # Only admins can see this text
3409 return array( array( 'notvisiblerev' ) );
3410 }
3411
3412 $set = array();
3413 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3414 # Mark all reverted edits as bot
3415 $set['rc_bot'] = 1;
3416 }
3417
3418 if ( $wgUseRCPatrol ) {
3419 # Mark all reverted edits as patrolled
3420 $set['rc_patrolled'] = 1;
3421 }
3422
3423 if ( count( $set ) ) {
3424 $dbw->update( 'recentchanges', $set,
3425 array( /* WHERE */
3426 'rc_cur_id' => $current->getPage(),
3427 'rc_user_text' => $current->getUserText(),
3428 "rc_timestamp > '{$s->rev_timestamp}'",
3429 ), __METHOD__
3430 );
3431 }
3432
3433 # Generate the edit summary if necessary
3434 $target = Revision::newFromId( $s->rev_id );
3435 if ( empty( $summary ) ) {
3436 if ( $from == '' ) { // no public user name
3437 $summary = wfMsgForContent( 'revertpage-nouser' );
3438 } else {
3439 $summary = wfMsgForContent( 'revertpage' );
3440 }
3441 }
3442
3443 # Allow the custom summary to use the same args as the default message
3444 $args = array(
3445 $target->getUserText(), $from, $s->rev_id,
3446 $wgLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ), true ),
3447 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3448 );
3449 $summary = wfMsgReplaceArgs( $summary, $args );
3450
3451 # Save
3452 $flags = EDIT_UPDATE;
3453
3454 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3455 $flags |= EDIT_MINOR;
3456 }
3457
3458 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) || $wgUser->isAllowed( 'bot' ) ) ) {
3459 $flags |= EDIT_FORCE_BOT;
3460 }
3461
3462 # Actually store the edit
3463 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3464 if ( !empty( $status->value['revision'] ) ) {
3465 $revId = $status->value['revision']->getId();
3466 } else {
3467 $revId = false;
3468 }
3469
3470 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3471
3472 $resultDetails = array(
3473 'summary' => $summary,
3474 'current' => $current,
3475 'target' => $target,
3476 'newid' => $revId
3477 );
3478
3479 return array();
3480 }
3481
3482 /**
3483 * User interface for rollback operations
3484 */
3485 public function rollback() {
3486 global $wgUser, $wgOut, $wgRequest;
3487
3488 $details = null;
3489
3490 $result = $this->doRollback(
3491 $wgRequest->getVal( 'from' ),
3492 $wgRequest->getText( 'summary' ),
3493 $wgRequest->getVal( 'token' ),
3494 $wgRequest->getBool( 'bot' ),
3495 $details
3496 );
3497
3498 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3499 $wgOut->rateLimited();
3500 return;
3501 }
3502
3503 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3504 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3505 $errArray = $result[0];
3506 $errMsg = array_shift( $errArray );
3507 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3508
3509 if ( isset( $details['current'] ) ) {
3510 $current = $details['current'];
3511
3512 if ( $current->getComment() != '' ) {
3513 $wgOut->addWikiMsgArray( 'editcomment', array(
3514 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3515 }
3516 }
3517
3518 return;
3519 }
3520
3521 # Display permissions errors before read-only message -- there's no
3522 # point in misleading the user into thinking the inability to rollback
3523 # is only temporary.
3524 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3525 # array_diff is completely broken for arrays of arrays, sigh.
3526 # Remove any 'readonlytext' error manually.
3527 $out = array();
3528 foreach ( $result as $error ) {
3529 if ( $error != array( 'readonlytext' ) ) {
3530 $out [] = $error;
3531 }
3532 }
3533 $wgOut->showPermissionsErrorPage( $out );
3534
3535 return;
3536 }
3537
3538 if ( $result == array( array( 'readonlytext' ) ) ) {
3539 $wgOut->readOnlyPage();
3540
3541 return;
3542 }
3543
3544 $current = $details['current'];
3545 $target = $details['target'];
3546 $newId = $details['newid'];
3547 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3548 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3549
3550 if ( $current->getUserText() === '' ) {
3551 $old = wfMsg( 'rev-deleted-user' );
3552 } else {
3553 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3554 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3555 }
3556
3557 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3558 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3559 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3560 $wgOut->returnToMain( false, $this->mTitle );
3561
3562 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3563 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3564 $de->showDiff( '', '' );
3565 }
3566 }
3567
3568 /**
3569 * Do standard deferred updates after page view
3570 */
3571 public function viewUpdates() {
3572 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3573 if ( wfReadOnly() ) {
3574 return;
3575 }
3576
3577 # Don't update page view counters on views from bot users (bug 14044)
3578 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3579 Article::incViewCount( $this->getID() );
3580 $u = new SiteStatsUpdate( 1, 0, 0 );
3581 array_push( $wgDeferredUpdateList, $u );
3582 }
3583
3584 # Update newtalk / watchlist notification status
3585 $wgUser->clearNotification( $this->mTitle );
3586 }
3587
3588 /**
3589 * Prepare text which is about to be saved.
3590 * Returns a stdclass with source, pst and output members
3591 */
3592 public function prepareTextForEdit( $text, $revid = null ) {
3593 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid ) {
3594 // Already prepared
3595 return $this->mPreparedEdit;
3596 }
3597
3598 global $wgParser;
3599
3600 $edit = (object)array();
3601 $edit->revid = $revid;
3602 $edit->newText = $text;
3603 $edit->pst = $this->preSaveTransform( $text );
3604 $options = $this->getParserOptions();
3605 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3606 $edit->oldText = $this->getContent();
3607
3608 $this->mPreparedEdit = $edit;
3609
3610 return $edit;
3611 }
3612
3613 /**
3614 * Do standard deferred updates after page edit.
3615 * Update links tables, site stats, search index and message cache.
3616 * Purges pages that include this page if the text was changed here.
3617 * Every 100th edit, prune the recent changes table.
3618 *
3619 * @private
3620 * @param $text New text of the article
3621 * @param $summary Edit summary
3622 * @param $minoredit Minor edit
3623 * @param $timestamp_of_pagechange Timestamp associated with the page change
3624 * @param $newid rev_id value of the new revision
3625 * @param $changed Whether or not the content actually changed
3626 */
3627 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3628 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3629
3630 wfProfileIn( __METHOD__ );
3631
3632 # Parse the text
3633 # Be careful not to double-PST: $text is usually already PST-ed once
3634 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3635 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3636 $editInfo = $this->prepareTextForEdit( $text, $newid );
3637 } else {
3638 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3639 $editInfo = $this->mPreparedEdit;
3640 }
3641
3642 # Save it to the parser cache
3643 if ( $wgEnableParserCache ) {
3644 $popts = $this->getParserOptions();
3645 $parserCache = ParserCache::singleton();
3646 $parserCache->save( $editInfo->output, $this, $popts );
3647 }
3648
3649 # Update the links tables
3650 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3651 $u->doUpdate();
3652
3653 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3654
3655 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3656 if ( 0 == mt_rand( 0, 99 ) ) {
3657 // Flush old entries from the `recentchanges` table; we do this on
3658 // random requests so as to avoid an increase in writes for no good reason
3659 global $wgRCMaxAge;
3660
3661 $dbw = wfGetDB( DB_MASTER );
3662 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3663 $recentchanges = $dbw->tableName( 'recentchanges' );
3664 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3665
3666 $dbw->query( $sql );
3667 }
3668 }
3669
3670 $id = $this->getID();
3671 $title = $this->mTitle->getPrefixedDBkey();
3672 $shortTitle = $this->mTitle->getDBkey();
3673
3674 if ( 0 == $id ) {
3675 wfProfileOut( __METHOD__ );
3676 return;
3677 }
3678
3679 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3680 array_push( $wgDeferredUpdateList, $u );
3681 $u = new SearchUpdate( $id, $title, $text );
3682 array_push( $wgDeferredUpdateList, $u );
3683
3684 # If this is another user's talk page, update newtalk
3685 # Don't do this if $changed = false otherwise some idiot can null-edit a
3686 # load of user talk pages and piss people off, nor if it's a minor edit
3687 # by a properly-flagged bot.
3688 if ( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3689 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3690 ) {
3691 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3692 $other = User::newFromName( $shortTitle, false );
3693 if ( !$other ) {
3694 wfDebug( __METHOD__ . ": invalid username\n" );
3695 } elseif ( User::isIP( $shortTitle ) ) {
3696 // An anonymous user
3697 $other->setNewtalk( true );
3698 } elseif ( $other->isLoggedIn() ) {
3699 $other->setNewtalk( true );
3700 } else {
3701 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
3702 }
3703 }
3704 }
3705
3706 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3707 $wgMessageCache->replace( $shortTitle, $text );
3708 }
3709
3710 wfProfileOut( __METHOD__ );
3711 }
3712
3713 /**
3714 * Perform article updates on a special page creation.
3715 *
3716 * @param $rev Revision object
3717 *
3718 * @todo This is a shitty interface function. Kill it and replace the
3719 * other shitty functions like editUpdates and such so it's not needed
3720 * anymore.
3721 */
3722 public function createUpdates( $rev ) {
3723 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3724 $this->mTotalAdjustment = 1;
3725 $this->editUpdates( $rev->getText(), $rev->getComment(),
3726 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3727 }
3728
3729 /**
3730 * Generate the navigation links when browsing through an article revisions
3731 * It shows the information as:
3732 * Revision as of \<date\>; view current revision
3733 * \<- Previous version | Next Version -\>
3734 *
3735 * @param $oldid String: revision ID of this article revision
3736 */
3737 public function setOldSubtitle( $oldid = 0 ) {
3738 global $wgLang, $wgOut, $wgUser, $wgRequest;
3739
3740 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3741 return;
3742 }
3743
3744 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3745
3746 # Cascade unhide param in links for easy deletion browsing
3747 $extraParams = array();
3748 if ( $wgRequest->getVal( 'unhide' ) ) {
3749 $extraParams['unhide'] = 1;
3750 }
3751
3752 $revision = Revision::newFromId( $oldid );
3753
3754 $current = ( $oldid == $this->mLatest );
3755 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3756 $tddate = $wgLang->date( $this->mTimestamp, true );
3757 $tdtime = $wgLang->time( $this->mTimestamp, true );
3758 $sk = $wgUser->getSkin();
3759 $lnk = $current
3760 ? wfMsgHtml( 'currentrevisionlink' )
3761 : $sk->link(
3762 $this->mTitle,
3763 wfMsgHtml( 'currentrevisionlink' ),
3764 array(),
3765 $extraParams,
3766 array( 'known', 'noclasses' )
3767 );
3768 $curdiff = $current
3769 ? wfMsgHtml( 'diff' )
3770 : $sk->link(
3771 $this->mTitle,
3772 wfMsgHtml( 'diff' ),
3773 array(),
3774 array(
3775 'diff' => 'cur',
3776 'oldid' => $oldid
3777 ) + $extraParams,
3778 array( 'known', 'noclasses' )
3779 );
3780 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3781 $prevlink = $prev
3782 ? $sk->link(
3783 $this->mTitle,
3784 wfMsgHtml( 'previousrevision' ),
3785 array(),
3786 array(
3787 'direction' => 'prev',
3788 'oldid' => $oldid
3789 ) + $extraParams,
3790 array( 'known', 'noclasses' )
3791 )
3792 : wfMsgHtml( 'previousrevision' );
3793 $prevdiff = $prev
3794 ? $sk->link(
3795 $this->mTitle,
3796 wfMsgHtml( 'diff' ),
3797 array(),
3798 array(
3799 'diff' => 'prev',
3800 'oldid' => $oldid
3801 ) + $extraParams,
3802 array( 'known', 'noclasses' )
3803 )
3804 : wfMsgHtml( 'diff' );
3805 $nextlink = $current
3806 ? wfMsgHtml( 'nextrevision' )
3807 : $sk->link(
3808 $this->mTitle,
3809 wfMsgHtml( 'nextrevision' ),
3810 array(),
3811 array(
3812 'direction' => 'next',
3813 'oldid' => $oldid
3814 ) + $extraParams,
3815 array( 'known', 'noclasses' )
3816 );
3817 $nextdiff = $current
3818 ? wfMsgHtml( 'diff' )
3819 : $sk->link(
3820 $this->mTitle,
3821 wfMsgHtml( 'diff' ),
3822 array(),
3823 array(
3824 'diff' => 'next',
3825 'oldid' => $oldid
3826 ) + $extraParams,
3827 array( 'known', 'noclasses' )
3828 );
3829
3830 $cdel = '';
3831
3832 // User can delete revisions or view deleted revisions...
3833 $canHide = $wgUser->isAllowed( 'deleterevision' );
3834 if ( $canHide || ( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3835 if ( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3836 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3837 } else {
3838 $query = array(
3839 'type' => 'revision',
3840 'target' => $this->mTitle->getPrefixedDbkey(),
3841 'ids' => $oldid
3842 );
3843 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
3844 }
3845 $cdel .= ' ';
3846 }
3847
3848 # Show user links if allowed to see them. If hidden, then show them only if requested...
3849 $userlinks = $sk->revUserTools( $revision, !$unhide );
3850
3851 $m = wfMsg( 'revision-info-current' );
3852 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3853 ? 'revision-info-current'
3854 : 'revision-info';
3855
3856 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3857 wfMsgExt(
3858 $infomsg,
3859 array( 'parseinline', 'replaceafter' ),
3860 $td,
3861 $userlinks,
3862 $revision->getID(),
3863 $tddate,
3864 $tdtime,
3865 $revision->getUser()
3866 ) .
3867 "</div>\n" .
3868 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3869 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3870
3871 $wgOut->setSubtitle( $r );
3872 }
3873
3874 /**
3875 * This function is called right before saving the wikitext,
3876 * so we can do things like signatures and links-in-context.
3877 *
3878 * @param $text String article contents
3879 * @return string article contents with altered wikitext markup (signatures
3880 * converted, {{subst:}}, templates, etc.)
3881 */
3882 public function preSaveTransform( $text ) {
3883 global $wgParser, $wgUser;
3884
3885 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3886 }
3887
3888 /* Caching functions */
3889
3890 /**
3891 * checkLastModified returns true if it has taken care of all
3892 * output to the client that is necessary for this request.
3893 * (that is, it has sent a cached version of the page)
3894 *
3895 * @return boolean true if cached version send, false otherwise
3896 */
3897 protected function tryFileCache() {
3898 static $called = false;
3899
3900 if ( $called ) {
3901 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3902 return false;
3903 }
3904
3905 $called = true;
3906 if ( $this->isFileCacheable() ) {
3907 $cache = new HTMLFileCache( $this->mTitle );
3908 if ( $cache->isFileCacheGood( $this->mTouched ) ) {
3909 wfDebug( "Article::tryFileCache(): about to load file\n" );
3910 $cache->loadFromFileCache();
3911 return true;
3912 } else {
3913 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3914 ob_start( array( &$cache, 'saveToFileCache' ) );
3915 }
3916 } else {
3917 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3918 }
3919
3920 return false;
3921 }
3922
3923 /**
3924 * Check if the page can be cached
3925 * @return bool
3926 */
3927 public function isFileCacheable() {
3928 $cacheable = false;
3929
3930 if ( HTMLFileCache::useFileCache() ) {
3931 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3932 // Extension may have reason to disable file caching on some pages.
3933 if ( $cacheable ) {
3934 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3935 }
3936 }
3937
3938 return $cacheable;
3939 }
3940
3941 /**
3942 * Loads page_touched and returns a value indicating if it should be used
3943 * @return boolean true if not a redirect
3944 */
3945 public function checkTouched() {
3946 if ( !$this->mDataLoaded ) {
3947 $this->loadPageData();
3948 }
3949
3950 return !$this->mIsRedirect;
3951 }
3952
3953 /**
3954 * Get the page_touched field
3955 * @return string containing GMT timestamp
3956 */
3957 public function getTouched() {
3958 if ( !$this->mDataLoaded ) {
3959 $this->loadPageData();
3960 }
3961
3962 return $this->mTouched;
3963 }
3964
3965 /**
3966 * Get the page_latest field
3967 * @return integer rev_id of current revision
3968 */
3969 public function getLatest() {
3970 if ( !$this->mDataLoaded ) {
3971 $this->loadPageData();
3972 }
3973
3974 return (int)$this->mLatest;
3975 }
3976
3977 /**
3978 * Edit an article without doing all that other stuff
3979 * The article must already exist; link tables etc
3980 * are not updated, caches are not flushed.
3981 *
3982 * @param $text String: text submitted
3983 * @param $comment String: comment submitted
3984 * @param $minor Boolean: whereas it's a minor modification
3985 */
3986 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3987 wfProfileIn( __METHOD__ );
3988
3989 $dbw = wfGetDB( DB_MASTER );
3990 $revision = new Revision( array(
3991 'page' => $this->getId(),
3992 'text' => $text,
3993 'comment' => $comment,
3994 'minor_edit' => $minor ? 1 : 0,
3995 ) );
3996 $revision->insertOn( $dbw );
3997 $this->updateRevisionOn( $dbw, $revision );
3998
3999 global $wgUser;
4000 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
4001
4002 wfProfileOut( __METHOD__ );
4003 }
4004
4005 /**
4006 * Used to increment the view counter
4007 *
4008 * @param $id Integer: article id
4009 */
4010 public static function incViewCount( $id ) {
4011 $id = intval( $id );
4012
4013 global $wgHitcounterUpdateFreq;
4014
4015 $dbw = wfGetDB( DB_MASTER );
4016 $pageTable = $dbw->tableName( 'page' );
4017 $hitcounterTable = $dbw->tableName( 'hitcounter' );
4018 $acchitsTable = $dbw->tableName( 'acchits' );
4019 $dbType = $dbw->getType();
4020
4021 if ( $wgHitcounterUpdateFreq <= 1 || $dbType == 'sqlite' ) {
4022 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
4023
4024 return;
4025 }
4026
4027 # Not important enough to warrant an error page in case of failure
4028 $oldignore = $dbw->ignoreErrors( true );
4029
4030 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
4031
4032 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 + 1 );
4033 if ( ( rand() % $checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
4034 # Most of the time (or on SQL errors), skip row count check
4035 $dbw->ignoreErrors( $oldignore );
4036
4037 return;
4038 }
4039
4040 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
4041 $row = $dbw->fetchObject( $res );
4042 $rown = intval( $row->n );
4043
4044 if ( $rown >= $wgHitcounterUpdateFreq ) {
4045 wfProfileIn( 'Article::incViewCount-collect' );
4046 $old_user_abort = ignore_user_abort( true );
4047
4048 $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__, false );
4049 $tabletype = $dbType == 'mysql' ? "ENGINE=HEAP " : '';
4050 $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
4051 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
4052 'GROUP BY hc_id', __METHOD__ );
4053 $dbw->delete( 'hitcounter', '*', __METHOD__ );
4054 $dbw->unlockTables( __METHOD__ );
4055
4056 if ( $dbType == 'mysql' ) {
4057 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
4058 'WHERE page_id = hc_id', __METHOD__ );
4059 } else {
4060 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
4061 "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__ );
4062 }
4063 $dbw->query( "DROP TABLE $acchitsTable", __METHOD__ );
4064
4065 ignore_user_abort( $old_user_abort );
4066 wfProfileOut( 'Article::incViewCount-collect' );
4067 }
4068
4069 $dbw->ignoreErrors( $oldignore );
4070 }
4071
4072 /**#@+
4073 * The onArticle*() functions are supposed to be a kind of hooks
4074 * which should be called whenever any of the specified actions
4075 * are done.
4076 *
4077 * This is a good place to put code to clear caches, for instance.
4078 *
4079 * This is called on page move and undelete, as well as edit
4080 *
4081 * @param $title a title object
4082 */
4083 public static function onArticleCreate( $title ) {
4084 # Update existence markers on article/talk tabs...
4085 if ( $title->isTalkPage() ) {
4086 $other = $title->getSubjectPage();
4087 } else {
4088 $other = $title->getTalkPage();
4089 }
4090
4091 $other->invalidateCache();
4092 $other->purgeSquid();
4093
4094 $title->touchLinks();
4095 $title->purgeSquid();
4096 $title->deleteTitleProtection();
4097 }
4098
4099 /**
4100 * Clears caches when article is deleted
4101 */
4102 public static function onArticleDelete( $title ) {
4103 global $wgMessageCache;
4104
4105 # Update existence markers on article/talk tabs...
4106 if ( $title->isTalkPage() ) {
4107 $other = $title->getSubjectPage();
4108 } else {
4109 $other = $title->getTalkPage();
4110 }
4111
4112 $other->invalidateCache();
4113 $other->purgeSquid();
4114
4115 $title->touchLinks();
4116 $title->purgeSquid();
4117
4118 # File cache
4119 HTMLFileCache::clearFileCache( $title );
4120
4121 # Messages
4122 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
4123 $wgMessageCache->replace( $title->getDBkey(), false );
4124 }
4125
4126 # Images
4127 if ( $title->getNamespace() == NS_FILE ) {
4128 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
4129 $update->doUpdate();
4130 }
4131
4132 # User talk pages
4133 if ( $title->getNamespace() == NS_USER_TALK ) {
4134 $user = User::newFromName( $title->getText(), false );
4135 $user->setNewtalk( false );
4136 }
4137
4138 # Image redirects
4139 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4140 }
4141
4142 /**
4143 * Purge caches on page update etc
4144 *
4145 * @param $title Title object
4146 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4147 */
4148 public static function onArticleEdit( $title ) {
4149 global $wgDeferredUpdateList;
4150
4151 // Invalidate caches of articles which include this page
4152 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4153
4154 // Invalidate the caches of all pages which redirect here
4155 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4156
4157 # Purge squid for this page only
4158 $title->purgeSquid();
4159
4160 # Clear file cache for this page only
4161 HTMLFileCache::clearFileCache( $title );
4162 }
4163
4164 /**#@-*/
4165
4166 /**
4167 * Overriden by ImagePage class, only present here to avoid a fatal error
4168 * Called for ?action=revert
4169 */
4170 public function revert() {
4171 global $wgOut;
4172 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4173 }
4174
4175 /**
4176 * Info about this page
4177 * Called for ?action=info when $wgAllowPageInfo is on.
4178 */
4179 public function info() {
4180 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4181
4182 if ( !$wgAllowPageInfo ) {
4183 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4184 return;
4185 }
4186
4187 $page = $this->mTitle->getSubjectPage();
4188
4189 $wgOut->setPagetitle( $page->getPrefixedText() );
4190 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4191 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4192
4193 if ( !$this->mTitle->exists() ) {
4194 $wgOut->addHTML( '<div class="noarticletext">' );
4195 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
4196 // This doesn't quite make sense; the user is asking for
4197 // information about the _page_, not the message... -- RC
4198 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
4199 } else {
4200 $msg = $wgUser->isLoggedIn()
4201 ? 'noarticletext'
4202 : 'noarticletextanon';
4203 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
4204 }
4205
4206 $wgOut->addHTML( '</div>' );
4207 } else {
4208 $dbr = wfGetDB( DB_SLAVE );
4209 $wl_clause = array(
4210 'wl_title' => $page->getDBkey(),
4211 'wl_namespace' => $page->getNamespace() );
4212 $numwatchers = $dbr->selectField(
4213 'watchlist',
4214 'COUNT(*)',
4215 $wl_clause,
4216 __METHOD__,
4217 $this->getSelectOptions() );
4218
4219 $pageInfo = $this->pageCountInfo( $page );
4220 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4221
4222
4223 //FIXME: unescaped messages
4224 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4225 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4226
4227 if ( $talkInfo ) {
4228 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4229 }
4230
4231 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4232
4233 if ( $talkInfo ) {
4234 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4235 }
4236
4237 $wgOut->addHTML( '</ul>' );
4238 }
4239 }
4240
4241 /**
4242 * Return the total number of edits and number of unique editors
4243 * on a given page. If page does not exist, returns false.
4244 *
4245 * @param $title Title object
4246 * @return mixed array or boolean false
4247 */
4248 public function pageCountInfo( $title ) {
4249 $id = $title->getArticleId();
4250
4251 if ( $id == 0 ) {
4252 return false;
4253 }
4254
4255 $dbr = wfGetDB( DB_SLAVE );
4256 $rev_clause = array( 'rev_page' => $id );
4257 $edits = $dbr->selectField(
4258 'revision',
4259 'COUNT(rev_page)',
4260 $rev_clause,
4261 __METHOD__,
4262 $this->getSelectOptions()
4263 );
4264 $authors = $dbr->selectField(
4265 'revision',
4266 'COUNT(DISTINCT rev_user_text)',
4267 $rev_clause,
4268 __METHOD__,
4269 $this->getSelectOptions()
4270 );
4271
4272 return array( 'edits' => $edits, 'authors' => $authors );
4273 }
4274
4275 /**
4276 * Return a list of templates used by this article.
4277 * Uses the templatelinks table
4278 *
4279 * @return Array of Title objects
4280 */
4281 public function getUsedTemplates() {
4282 $result = array();
4283 $id = $this->mTitle->getArticleID();
4284
4285 if ( $id == 0 ) {
4286 return array();
4287 }
4288
4289 $dbr = wfGetDB( DB_SLAVE );
4290 $res = $dbr->select( array( 'templatelinks' ),
4291 array( 'tl_namespace', 'tl_title' ),
4292 array( 'tl_from' => $id ),
4293 __METHOD__ );
4294
4295 if ( $res !== false ) {
4296 foreach ( $res as $row ) {
4297 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
4298 }
4299 }
4300
4301 $dbr->freeResult( $res );
4302
4303 return $result;
4304 }
4305
4306 /**
4307 * Returns a list of hidden categories this page is a member of.
4308 * Uses the page_props and categorylinks tables.
4309 *
4310 * @return Array of Title objects
4311 */
4312 public function getHiddenCategories() {
4313 $result = array();
4314 $id = $this->mTitle->getArticleID();
4315
4316 if ( $id == 0 ) {
4317 return array();
4318 }
4319
4320 $dbr = wfGetDB( DB_SLAVE );
4321 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4322 array( 'cl_to' ),
4323 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4324 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
4325 __METHOD__ );
4326
4327 if ( $res !== false ) {
4328 foreach ( $res as $row ) {
4329 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
4330 }
4331 }
4332
4333 $dbr->freeResult( $res );
4334
4335 return $result;
4336 }
4337
4338 /**
4339 * Return an applicable autosummary if one exists for the given edit.
4340 * @param $oldtext String: the previous text of the page.
4341 * @param $newtext String: The submitted text of the page.
4342 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
4343 * @return string An appropriate autosummary, or an empty string.
4344 */
4345 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4346 global $wgContLang;
4347
4348 # Decide what kind of autosummary is needed.
4349
4350 # Redirect autosummaries
4351 $ot = Title::newFromRedirect( $oldtext );
4352 $rt = Title::newFromRedirect( $newtext );
4353
4354 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
4355 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4356 }
4357
4358 # New page autosummaries
4359 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
4360 # If they're making a new article, give its text, truncated, in the summary.
4361
4362 $truncatedtext = $wgContLang->truncate(
4363 str_replace( "\n", ' ', $newtext ),
4364 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4365
4366 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4367 }
4368
4369 # Blanking autosummaries
4370 if ( $oldtext != '' && $newtext == '' ) {
4371 return wfMsgForContent( 'autosumm-blank' );
4372 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4373 # Removing more than 90% of the article
4374
4375 $truncatedtext = $wgContLang->truncate(
4376 $newtext,
4377 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4378
4379 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4380 }
4381
4382 # If we reach this point, there's no applicable autosummary for our case, so our
4383 # autosummary is empty.
4384 return '';
4385 }
4386
4387 /**
4388 * Add the primary page-view wikitext to the output buffer
4389 * Saves the text into the parser cache if possible.
4390 * Updates templatelinks if it is out of date.
4391 *
4392 * @param $text String
4393 * @param $cache Boolean
4394 * @param $parserOptions mixed ParserOptions object, or boolean false
4395 */
4396 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4397 global $wgOut;
4398
4399 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4400 $wgOut->addParserOutput( $this->mParserOutput );
4401 }
4402
4403 /**
4404 * This does all the heavy lifting for outputWikitext, except it returns the parser
4405 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4406 * say, embedding thread pages within a discussion system (LiquidThreads)
4407 *
4408 * @param $text string
4409 * @param $cache boolean
4410 * @param $parserOptions parsing options, defaults to false
4411 * @return string containing parsed output
4412 */
4413 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4414 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4415
4416 if ( !$parserOptions ) {
4417 $parserOptions = $this->getParserOptions();
4418 }
4419
4420 $time = - wfTime();
4421 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
4422 $parserOptions, true, true, $this->getRevIdFetched() );
4423 $time += wfTime();
4424
4425 # Timing hack
4426 if ( $time > 3 ) {
4427 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4428 $this->mTitle->getPrefixedDBkey() ) );
4429 }
4430
4431 if ( $wgEnableParserCache && $cache && $this->mParserOutput->isCacheable() ) {
4432 $parserCache = ParserCache::singleton();
4433 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
4434 }
4435
4436 // Make sure file cache is not used on uncacheable content.
4437 // Output that has magic words in it can still use the parser cache
4438 // (if enabled), though it will generally expire sooner.
4439 if ( !$this->mParserOutput->isCacheable() || $this->mParserOutput->containsOldMagic() ) {
4440 $wgUseFileCache = false;
4441 }
4442
4443 $this->doCascadeProtectionUpdates( $this->mParserOutput );
4444
4445 return $this->mParserOutput;
4446 }
4447
4448 /**
4449 * Get parser options suitable for rendering the primary article wikitext
4450 * @return mixed ParserOptions object or boolean false
4451 */
4452 public function getParserOptions() {
4453 global $wgUser;
4454
4455 if ( !$this->mParserOptions ) {
4456 $this->mParserOptions = new ParserOptions( $wgUser );
4457 $this->mParserOptions->setTidy( true );
4458 $this->mParserOptions->enableLimitReport();
4459 }
4460
4461 return $this->mParserOptions;
4462 }
4463
4464 /**
4465 * Updates cascading protections
4466 *
4467 * @param $parserOutput mixed ParserOptions object, or boolean false
4468 **/
4469
4470 protected function doCascadeProtectionUpdates( $parserOutput ) {
4471 if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4472 return;
4473 }
4474
4475 // templatelinks table may have become out of sync,
4476 // especially if using variable-based transclusions.
4477 // For paranoia, check if things have changed and if
4478 // so apply updates to the database. This will ensure
4479 // that cascaded protections apply as soon as the changes
4480 // are visible.
4481
4482 # Get templates from templatelinks
4483 $id = $this->mTitle->getArticleID();
4484
4485 $tlTemplates = array();
4486
4487 $dbr = wfGetDB( DB_SLAVE );
4488 $res = $dbr->select( array( 'templatelinks' ),
4489 array( 'tl_namespace', 'tl_title' ),
4490 array( 'tl_from' => $id ),
4491 __METHOD__
4492 );
4493
4494 foreach ( $res as $row ) {
4495 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4496 }
4497
4498 # Get templates from parser output.
4499 $poTemplates = array();
4500 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4501 foreach ( $templates as $dbk => $id ) {
4502 $poTemplates["$ns:$dbk"] = true;
4503 }
4504 }
4505
4506 # Get the diff
4507 # Note that we simulate array_diff_key in PHP <5.0.x
4508 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4509
4510 if ( count( $templates_diff ) > 0 ) {
4511 # Whee, link updates time.
4512 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4513 $u->doUpdate();
4514 }
4515 }
4516
4517 /**
4518 * Update all the appropriate counts in the category table, given that
4519 * we've added the categories $added and deleted the categories $deleted.
4520 *
4521 * @param $added array The names of categories that were added
4522 * @param $deleted array The names of categories that were deleted
4523 */
4524 public function updateCategoryCounts( $added, $deleted ) {
4525 $ns = $this->mTitle->getNamespace();
4526 $dbw = wfGetDB( DB_MASTER );
4527
4528 # First make sure the rows exist. If one of the "deleted" ones didn't
4529 # exist, we might legitimately not create it, but it's simpler to just
4530 # create it and then give it a negative value, since the value is bogus
4531 # anyway.
4532 #
4533 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4534 $insertCats = array_merge( $added, $deleted );
4535 if ( !$insertCats ) {
4536 # Okay, nothing to do
4537 return;
4538 }
4539
4540 $insertRows = array();
4541
4542 foreach ( $insertCats as $cat ) {
4543 $insertRows[] = array(
4544 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4545 'cat_title' => $cat
4546 );
4547 }
4548 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4549
4550 $addFields = array( 'cat_pages = cat_pages + 1' );
4551 $removeFields = array( 'cat_pages = cat_pages - 1' );
4552
4553 if ( $ns == NS_CATEGORY ) {
4554 $addFields[] = 'cat_subcats = cat_subcats + 1';
4555 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4556 } elseif ( $ns == NS_FILE ) {
4557 $addFields[] = 'cat_files = cat_files + 1';
4558 $removeFields[] = 'cat_files = cat_files - 1';
4559 }
4560
4561 if ( $added ) {
4562 $dbw->update(
4563 'category',
4564 $addFields,
4565 array( 'cat_title' => $added ),
4566 __METHOD__
4567 );
4568 }
4569
4570 if ( $deleted ) {
4571 $dbw->update(
4572 'category',
4573 $removeFields,
4574 array( 'cat_title' => $deleted ),
4575 __METHOD__
4576 );
4577 }
4578 }
4579
4580 /**
4581 * Lightweight method to get the parser output for a page, checking the parser cache
4582 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4583 * consider, so it's not appropriate to use there.
4584 *
4585 * @param $oldid mixed integer Revision ID or null
4586 */
4587 public function getParserOutput( $oldid = null ) {
4588 global $wgEnableParserCache, $wgUser;
4589
4590 // Should the parser cache be used?
4591 $useParserCache = $wgEnableParserCache &&
4592 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4593 $this->exists() &&
4594 $oldid === null;
4595
4596 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4597
4598 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4599 wfIncrStats( 'pcache_miss_stub' );
4600 }
4601
4602 $parserOutput = false;
4603 if ( $useParserCache ) {
4604 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4605 }
4606
4607 if ( $parserOutput === false ) {
4608 // Cache miss; parse and output it.
4609 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4610
4611 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4612 } else {
4613 return $parserOutput;
4614 }
4615 }
4616
4617 // Deprecated methods
4618 /**
4619 * Get the database which should be used for reads
4620 *
4621 * @return Database
4622 * @deprecated - just call wfGetDB( DB_MASTER ) instead
4623 */
4624 function getDB() {
4625 wfDeprecated( __METHOD__ );
4626 return wfGetDB( DB_MASTER );
4627 }
4628
4629 }