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