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