Add page_latest to the LinkCache.
[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::followRedirect()
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, $data->page_latest );
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->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
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 * @param $setNewFlag Boolean: Set to true if a page flag should be set
1794 * Needed when $lastRevision has to be set to sth. !=0
1795 * @return bool true on success, false on failure
1796 * @private
1797 */
1798 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null, $setNewFlag = false ) {
1799 wfProfileIn( __METHOD__ );
1800
1801 $text = $revision->getText();
1802 $rt = Title::newFromRedirect( $text );
1803
1804 $conditions = array( 'page_id' => $this->getId() );
1805
1806 if ( !is_null( $lastRevision ) ) {
1807 # An extra check against threads stepping on each other
1808 $conditions['page_latest'] = $lastRevision;
1809 }
1810
1811 if ( !$setNewFlag ) {
1812 $setNewFlag = ( $lastRevision === 0 );
1813 }
1814
1815 $dbw->update( 'page',
1816 array( /* SET */
1817 'page_latest' => $revision->getId(),
1818 'page_touched' => $dbw->timestamp(),
1819 'page_is_new' => $setNewFlag,
1820 'page_is_redirect' => $rt !== null ? 1 : 0,
1821 'page_len' => strlen( $text ),
1822 ),
1823 $conditions,
1824 __METHOD__ );
1825
1826 $result = $dbw->affectedRows() != 0;
1827 if ( $result ) {
1828 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1829 }
1830
1831 wfProfileOut( __METHOD__ );
1832 return $result;
1833 }
1834
1835 /**
1836 * Add row to the redirect table if this is a redirect, remove otherwise.
1837 *
1838 * @param $dbw Database
1839 * @param $redirectTitle a title object pointing to the redirect target,
1840 * or NULL if this is not a redirect
1841 * @param $lastRevIsRedirect If given, will optimize adding and
1842 * removing rows in redirect table.
1843 * @return bool true on success, false on failure
1844 * @private
1845 */
1846 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1847 // Always update redirects (target link might have changed)
1848 // Update/Insert if we don't know if the last revision was a redirect or not
1849 // Delete if changing from redirect to non-redirect
1850 $isRedirect = !is_null( $redirectTitle );
1851
1852 if ( $isRedirect || is_null( $lastRevIsRedirect ) || $lastRevIsRedirect !== $isRedirect ) {
1853 wfProfileIn( __METHOD__ );
1854 if ( $isRedirect ) {
1855 // This title is a redirect, Add/Update row in the redirect table
1856 $set = array( /* SET */
1857 'rd_namespace' => $redirectTitle->getNamespace(),
1858 'rd_title' => $redirectTitle->getDBkey(),
1859 'rd_from' => $this->getId(),
1860 );
1861 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1862 } else {
1863 // This is not a redirect, remove row from redirect table
1864 $where = array( 'rd_from' => $this->getId() );
1865 $dbw->delete( 'redirect', $where, __METHOD__ );
1866 }
1867
1868 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1869 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1870 }
1871 wfProfileOut( __METHOD__ );
1872
1873 return ( $dbw->affectedRows() != 0 );
1874 }
1875
1876 return true;
1877 }
1878
1879 /**
1880 * If the given revision is newer than the currently set page_latest,
1881 * update the page record. Otherwise, do nothing.
1882 *
1883 * @param $dbw Database object
1884 * @param $revision Revision object
1885 * @return mixed
1886 */
1887 public function updateIfNewerOn( &$dbw, $revision ) {
1888 wfProfileIn( __METHOD__ );
1889
1890 $row = $dbw->selectRow(
1891 array( 'revision', 'page' ),
1892 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1893 array(
1894 'page_id' => $this->getId(),
1895 'page_latest=rev_id' ),
1896 __METHOD__ );
1897
1898 if ( $row ) {
1899 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1900 wfProfileOut( __METHOD__ );
1901 return false;
1902 }
1903 $prev = $row->rev_id;
1904 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1905 } else {
1906 # No or missing previous revision; mark the page as new
1907 $prev = 0;
1908 $lastRevIsRedirect = null;
1909 }
1910
1911 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1912
1913 wfProfileOut( __METHOD__ );
1914 return $ret;
1915 }
1916
1917 /**
1918 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1919 * @param $text String: new text of the section
1920 * @param $summary String: new section's subject, only if $section is 'new'
1921 * @param $edittime String: revision timestamp or null to use the current revision
1922 * @return string Complete article text, or null if error
1923 */
1924 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1925 wfProfileIn( __METHOD__ );
1926
1927 if ( strval( $section ) == '' ) {
1928 // Whole-page edit; let the whole text through
1929 } else {
1930 if ( is_null( $edittime ) ) {
1931 $rev = Revision::newFromTitle( $this->mTitle );
1932 } else {
1933 $dbw = wfGetDB( DB_MASTER );
1934 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1935 }
1936
1937 if ( !$rev ) {
1938 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1939 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1940 return null;
1941 }
1942
1943 $oldtext = $rev->getText();
1944
1945 if ( $section == 'new' ) {
1946 # Inserting a new section
1947 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1948 $text = strlen( trim( $oldtext ) ) > 0
1949 ? "{$oldtext}\n\n{$subject}{$text}"
1950 : "{$subject}{$text}";
1951 } else {
1952 # Replacing an existing section; roll out the big guns
1953 global $wgParser;
1954
1955 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1956 }
1957 }
1958
1959 wfProfileOut( __METHOD__ );
1960 return $text;
1961 }
1962
1963 /**
1964 * This function is not deprecated until somebody fixes the core not to use
1965 * it. Nevertheless, use Article::doEdit() instead.
1966 */
1967 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1968 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1969 ( $isminor ? EDIT_MINOR : 0 ) |
1970 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1971 ( $bot ? EDIT_FORCE_BOT : 0 );
1972
1973 $this->doEdit( $text, $summary, $flags, false, null, $watchthis, $comment, '', true );
1974 }
1975
1976 /**
1977 * @deprecated use Article::doEdit()
1978 */
1979 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1980 wfDeprecated( __METHOD__ );
1981 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1982 ( $minor ? EDIT_MINOR : 0 ) |
1983 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1984
1985 $status = $this->doEdit( $text, $summary, $flags, false, null, $watchthis, false, $sectionanchor, true );
1986
1987 if ( !$status->isOK() ) {
1988 return false;
1989 }
1990
1991 return true;
1992 }
1993
1994 /**
1995 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1996 * @param $flags Int
1997 * @return Int updated $flags
1998 */
1999 function checkFlags( $flags ) {
2000 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
2001 if ( $this->mTitle->getArticleID() ) {
2002 $flags |= EDIT_UPDATE;
2003 } else {
2004 $flags |= EDIT_NEW;
2005 }
2006 }
2007
2008 return $flags;
2009 }
2010
2011 /**
2012 * Article::doEdit()
2013 *
2014 * Change an existing article or create a new article. Updates RC and all necessary caches,
2015 * optionally via the deferred update array.
2016 *
2017 * $wgUser must be set before calling this function.
2018 *
2019 * @param $text String: new text
2020 * @param $summary String: edit summary
2021 * @param $flags Integer bitfield:
2022 * EDIT_NEW
2023 * Article is known or assumed to be non-existent, create a new one
2024 * EDIT_UPDATE
2025 * Article is known or assumed to be pre-existing, update it
2026 * EDIT_MINOR
2027 * Mark this edit minor, if the user is allowed to do so
2028 * EDIT_SUPPRESS_RC
2029 * Do not log the change in recentchanges
2030 * EDIT_FORCE_BOT
2031 * Mark the edit a "bot" edit regardless of user rights
2032 * EDIT_DEFER_UPDATES
2033 * Defer some of the updates until the end of index.php
2034 * EDIT_AUTOSUMMARY
2035 * Fill in blank summaries with generated text where possible
2036 *
2037 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2038 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2039 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2040 * edit-already-exists error will be returned. These two conditions are also possible with
2041 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2042 *
2043 * @param $baseRevId the revision ID this edit was based off, if any
2044 * @param $user Optional user object, $wgUser will be used if not passed
2045 * @param $watchthis Watch the page if true, unwatch the page if false, do nothing if null
2046 * @param $sectionanchor The section anchor for the page; used for redirecting the user back to the page
2047 * after the edit is successfully committed
2048 * @param $redirect If true, redirect the user back to the page after the edit is successfully committed
2049 *
2050 * @return Status object. Possible errors:
2051 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2052 * edit-gone-missing: In update mode, but the article didn't exist
2053 * edit-conflict: In update mode, the article changed unexpectedly
2054 * edit-no-change: Warning that the text was the same as before
2055 * edit-already-exists: In creation mode, but the article already exists
2056 *
2057 * Extensions may define additional errors.
2058 *
2059 * $return->value will contain an associative array with members as follows:
2060 * new: Boolean indicating if the function attempted to create a new article
2061 * revision: The revision object for the inserted revision, or null
2062 *
2063 * Compatibility note: this function previously returned a boolean value indicating success/failure
2064 */
2065 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null , $watchthis = null,
2066 $comment = false, $sectionanchor = '', $redirect = false) {
2067 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2068
2069 # Low-level sanity check
2070 if ( $this->mTitle->getText() == '' ) {
2071 throw new MWException( 'Something is trying to edit an article with an empty title' );
2072 }
2073
2074 wfProfileIn( __METHOD__ );
2075
2076 $user = is_null( $user ) ? $wgUser : $user;
2077 $status = Status::newGood( array() );
2078
2079 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2080 $this->loadPageData();
2081
2082 $flags = $this->checkFlags( $flags );
2083
2084 # If this is a comment, add the summary as headline
2085 if ( $comment && $summary != "" ) {
2086 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
2087 }
2088
2089 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2090 $flags & EDIT_MINOR, &$watchthis, null, &$flags, &$status) ) )
2091 {
2092 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
2093 wfProfileOut( __METHOD__ );
2094
2095 if ( $status->isOK() ) {
2096 $status->fatal( 'edit-hook-aborted' );
2097 }
2098
2099 return $status;
2100 }
2101
2102 # Silently ignore EDIT_MINOR if not allowed
2103 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
2104 $bot = $flags & EDIT_FORCE_BOT;
2105
2106 $oldtext = $this->getRawText(); // current revision
2107 $oldsize = strlen( $oldtext );
2108
2109 # Provide autosummaries if one is not provided and autosummaries are enabled.
2110 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
2111 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2112 }
2113
2114 $editInfo = $this->prepareTextForEdit( $text );
2115 $text = $editInfo->pst;
2116 $newsize = strlen( $text );
2117
2118 $dbw = wfGetDB( DB_MASTER );
2119 $now = wfTimestampNow();
2120 $this->mTimestamp = $now;
2121
2122 if ( $flags & EDIT_UPDATE ) {
2123 # Update article, but only if changed.
2124 $status->value['new'] = false;
2125
2126 # Make sure the revision is either completely inserted or not inserted at all
2127 if ( !$wgDBtransactions ) {
2128 $userAbort = ignore_user_abort( true );
2129 }
2130
2131 $revisionId = 0;
2132
2133 $changed = ( strcmp( $text, $oldtext ) != 0 );
2134
2135 if ( $changed ) {
2136 $this->mGoodAdjustment = (int)$this->isCountable( $text )
2137 - (int)$this->isCountable( $oldtext );
2138 $this->mTotalAdjustment = 0;
2139
2140 if ( !$this->mLatest ) {
2141 # Article gone missing
2142 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
2143 $status->fatal( 'edit-gone-missing' );
2144
2145 wfProfileOut( __METHOD__ );
2146 return $status;
2147 }
2148
2149 $revision = new Revision( array(
2150 'page' => $this->getId(),
2151 'comment' => $summary,
2152 'minor_edit' => $isminor,
2153 'text' => $text,
2154 'parent_id' => $this->mLatest,
2155 'user' => $user->getId(),
2156 'user_text' => $user->getName(),
2157 ) );
2158
2159 $dbw->begin();
2160 $revisionId = $revision->insertOn( $dbw );
2161
2162 # Update page
2163 #
2164 # Note that we use $this->mLatest instead of fetching a value from the master DB
2165 # during the course of this function. This makes sure that EditPage can detect
2166 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2167 # before this function is called. A previous function used a separate query, this
2168 # creates a window where concurrent edits can cause an ignored edit conflict.
2169 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
2170
2171 if ( !$ok ) {
2172 /* Belated edit conflict! Run away!! */
2173 $status->fatal( 'edit-conflict' );
2174
2175 # Delete the invalid revision if the DB is not transactional
2176 if ( !$wgDBtransactions ) {
2177 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
2178 }
2179
2180 $revisionId = 0;
2181 $dbw->rollback();
2182 } else {
2183 global $wgUseRCPatrol;
2184 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2185 # Update recentchanges
2186 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2187 # Mark as patrolled if the user can do so
2188 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan( 'autopatrol' );
2189 # Add RC row to the DB
2190 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
2191 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2192 $revisionId, $patrolled
2193 );
2194
2195 # Log auto-patrolled edits
2196 if ( $patrolled ) {
2197 PatrolLog::record( $rc, true );
2198 }
2199 }
2200 $user->incEditCount();
2201 $dbw->commit();
2202 }
2203 } else {
2204 $status->warning( 'edit-no-change' );
2205 $revision = null;
2206 // Keep the same revision ID, but do some updates on it
2207 $revisionId = $this->getRevIdFetched();
2208 // Update page_touched, this is usually implicit in the page update
2209 // Other cache updates are done in onArticleEdit()
2210 $this->mTitle->invalidateCache();
2211 }
2212
2213 if ( !$wgDBtransactions ) {
2214 ignore_user_abort( $userAbort );
2215 }
2216
2217 // Now that ignore_user_abort is restored, we can respond to fatal errors
2218 if ( !$status->isOK() ) {
2219 wfProfileOut( __METHOD__ );
2220 return $status;
2221 }
2222
2223 # Invalidate cache of this article and all pages using this article
2224 # as a template. Partly deferred.
2225 Article::onArticleEdit( $this->mTitle );
2226 # Update links tables, site stats, etc.
2227 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2228 } else {
2229 # Create new article
2230 $status->value['new'] = true;
2231
2232 # Set statistics members
2233 # We work out if it's countable after PST to avoid counter drift
2234 # when articles are created with {{subst:}}
2235 $this->mGoodAdjustment = (int)$this->isCountable( $text );
2236 $this->mTotalAdjustment = 1;
2237
2238 $dbw->begin();
2239
2240 # Add the page record; stake our claim on this title!
2241 # This will return false if the article already exists
2242 $newid = $this->insertOn( $dbw );
2243
2244 if ( $newid === false ) {
2245 $dbw->rollback();
2246 $status->fatal( 'edit-already-exists' );
2247
2248 wfProfileOut( __METHOD__ );
2249 return $status;
2250 }
2251
2252 # Save the revision text...
2253 $revision = new Revision( array(
2254 'page' => $newid,
2255 'comment' => $summary,
2256 'minor_edit' => $isminor,
2257 'text' => $text,
2258 'user' => $user->getId(),
2259 'user_text' => $user->getName(),
2260 ) );
2261 $revisionId = $revision->insertOn( $dbw );
2262
2263 $this->mTitle->resetArticleID( $newid );
2264
2265 # Update the page record with revision data
2266 $this->updateRevisionOn( $dbw, $revision, 0 );
2267
2268 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2269
2270 # Update recentchanges
2271 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2272 global $wgUseRCPatrol, $wgUseNPPatrol;
2273
2274 # Mark as patrolled if the user can do so
2275 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && $this->mTitle->userCan( 'autopatrol' );
2276 # Add RC row to the DB
2277 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2278 '', strlen( $text ), $revisionId, $patrolled );
2279
2280 # Log auto-patrolled edits
2281 if ( $patrolled ) {
2282 PatrolLog::record( $rc, true );
2283 }
2284 }
2285 $user->incEditCount();
2286 $dbw->commit();
2287
2288 # Update links, etc.
2289 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2290
2291 # Clear caches
2292 Article::onArticleCreate( $this->mTitle );
2293
2294 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2295 $flags & EDIT_MINOR, &$watchthis, null, &$flags, $revision ) );
2296 }
2297
2298 # Do updates right now unless deferral was requested
2299 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
2300 wfDoUpdates();
2301 }
2302
2303 // Return the new revision (or null) to the caller
2304 $status->value['revision'] = $revision;
2305
2306 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2307 $flags & EDIT_MINOR, &$watchthis, null, &$flags, $revision, &$status, $baseRevId,
2308 &$redirect) );
2309
2310 # Watch or unwatch the page
2311 if ( $watchthis === true ) {
2312 if ( !$this->mTitle->userIsWatching() ) {
2313 $dbw->begin();
2314 $this->doWatch();
2315 $dbw->commit();
2316 }
2317 } elseif ( $watchthis === false ) {
2318 if ( $this->mTitle->userIsWatching() ) {
2319 $dbw->begin();
2320 $this->doUnwatch();
2321 $dbw->commit();
2322 }
2323 }
2324
2325 # Give extensions a chance to modify URL query on update
2326 $extraQuery = '';
2327
2328 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
2329
2330 if ( $redirect ) {
2331 if ( $sectionanchor || $extraQuery ) {
2332 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
2333 } else {
2334 $this->doRedirect( $this->isRedirect( $text ) );
2335 }
2336 }
2337
2338 wfProfileOut( __METHOD__ );
2339
2340 return $status;
2341 }
2342
2343 /**
2344 * @deprecated wrapper for doRedirect
2345 */
2346 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2347 wfDeprecated( __METHOD__ );
2348 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2349 }
2350
2351 /**
2352 * Output a redirect back to the article.
2353 * This is typically used after an edit.
2354 *
2355 * @param $noRedir Boolean: add redirect=no
2356 * @param $sectionAnchor String: section to redirect to, including "#"
2357 * @param $extraQuery String: extra query params
2358 */
2359 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2360 global $wgOut;
2361
2362 if ( $noRedir ) {
2363 $query = 'redirect=no';
2364 if ( $extraQuery )
2365 $query .= "&$extraQuery";
2366 } else {
2367 $query = $extraQuery;
2368 }
2369
2370 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2371 }
2372
2373 /**
2374 * Mark this particular edit/page as patrolled
2375 */
2376 public function markpatrolled() {
2377 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2378
2379 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2380
2381 # If we haven't been given an rc_id value, we can't do anything
2382 $rcid = (int) $wgRequest->getVal( 'rcid' );
2383 $rc = RecentChange::newFromId( $rcid );
2384
2385 if ( is_null( $rc ) ) {
2386 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2387 return;
2388 }
2389
2390 # It would be nice to see where the user had actually come from, but for now just guess
2391 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2392 $return = SpecialPage::getTitleFor( $returnto );
2393
2394 $dbw = wfGetDB( DB_MASTER );
2395 $errors = $rc->doMarkPatrolled();
2396
2397 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2398 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2399
2400 return;
2401 }
2402
2403 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2404 // The hook itself has handled any output
2405 return;
2406 }
2407
2408 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2409 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2410 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2411 $wgOut->returnToMain( false, $return );
2412
2413 return;
2414 }
2415
2416 if ( !empty( $errors ) ) {
2417 $wgOut->showPermissionsErrorPage( $errors );
2418
2419 return;
2420 }
2421
2422 # Inform the user
2423 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2424 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2425 $wgOut->returnToMain( false, $return );
2426 }
2427
2428 /**
2429 * User-interface handler for the "watch" action
2430 */
2431 public function watch() {
2432 global $wgUser, $wgOut;
2433
2434 if ( $wgUser->isAnon() ) {
2435 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2436 return;
2437 }
2438
2439 if ( wfReadOnly() ) {
2440 $wgOut->readOnlyPage();
2441 return;
2442 }
2443
2444 if ( $this->doWatch() ) {
2445 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2446 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2447 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2448 }
2449
2450 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2451 }
2452
2453 /**
2454 * Add this page to $wgUser's watchlist
2455 * @return bool true on successful watch operation
2456 */
2457 public function doWatch() {
2458 global $wgUser;
2459
2460 if ( $wgUser->isAnon() ) {
2461 return false;
2462 }
2463
2464 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2465 $wgUser->addWatch( $this->mTitle );
2466 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2467 }
2468
2469 return false;
2470 }
2471
2472 /**
2473 * User interface handler for the "unwatch" action.
2474 */
2475 public function unwatch() {
2476 global $wgUser, $wgOut;
2477
2478 if ( $wgUser->isAnon() ) {
2479 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2480 return;
2481 }
2482
2483 if ( wfReadOnly() ) {
2484 $wgOut->readOnlyPage();
2485 return;
2486 }
2487
2488 if ( $this->doUnwatch() ) {
2489 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2490 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2491 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2492 }
2493
2494 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2495 }
2496
2497 /**
2498 * Stop watching a page
2499 * @return bool true on successful unwatch
2500 */
2501 public function doUnwatch() {
2502 global $wgUser;
2503
2504 if ( $wgUser->isAnon() ) {
2505 return false;
2506 }
2507
2508 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2509 $wgUser->removeWatch( $this->mTitle );
2510 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2511 }
2512
2513 return false;
2514 }
2515
2516 /**
2517 * action=protect handler
2518 */
2519 public function protect() {
2520 $form = new ProtectionForm( $this );
2521 $form->execute();
2522 }
2523
2524 /**
2525 * action=unprotect handler (alias)
2526 */
2527 public function unprotect() {
2528 $this->protect();
2529 }
2530
2531 /**
2532 * Update the article's restriction field, and leave a log entry.
2533 *
2534 * @param $limit Array: set of restriction keys
2535 * @param $reason String
2536 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2537 * @param $expiry Array: per restriction type expiration
2538 * @return bool true on success
2539 */
2540 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2541 global $wgUser, $wgContLang;
2542
2543 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2544
2545 $id = $this->mTitle->getArticleID();
2546
2547 if ( $id <= 0 ) {
2548 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2549 return false;
2550 }
2551
2552 if ( wfReadOnly() ) {
2553 wfDebug( "updateRestrictions failed: read-only\n" );
2554 return false;
2555 }
2556
2557 if ( !$this->mTitle->userCan( 'protect' ) ) {
2558 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2559 return false;
2560 }
2561
2562 if ( !$cascade ) {
2563 $cascade = false;
2564 }
2565
2566 // Take this opportunity to purge out expired restrictions
2567 Title::purgeExpiredRestrictions();
2568
2569 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2570 # we expect a single selection, but the schema allows otherwise.
2571 $current = array();
2572 $updated = Article::flattenRestrictions( $limit );
2573 $changed = false;
2574
2575 foreach ( $restrictionTypes as $action ) {
2576 if ( isset( $expiry[$action] ) ) {
2577 # Get current restrictions on $action
2578 $aLimits = $this->mTitle->getRestrictions( $action );
2579 $current[$action] = implode( '', $aLimits );
2580 # Are any actual restrictions being dealt with here?
2581 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
2582
2583 # If something changed, we need to log it. Checking $aRChanged
2584 # assures that "unprotecting" a page that is not protected does
2585 # not log just because the expiry was "changed".
2586 if ( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2587 $changed = true;
2588 }
2589 }
2590 }
2591
2592 $current = Article::flattenRestrictions( $current );
2593
2594 $changed = ( $changed || $current != $updated );
2595 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
2596 $protect = ( $updated != '' );
2597
2598 # If nothing's changed, do nothing
2599 if ( $changed ) {
2600 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2601 $dbw = wfGetDB( DB_MASTER );
2602
2603 # Prepare a null revision to be added to the history
2604 $modified = $current != '' && $protect;
2605
2606 if ( $protect ) {
2607 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2608 } else {
2609 $comment_type = 'unprotectedarticle';
2610 }
2611
2612 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2613
2614 # Only restrictions with the 'protect' right can cascade...
2615 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2616 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2617
2618 # The schema allows multiple restrictions
2619 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2620 $cascade = false;
2621 }
2622
2623 $cascade_description = '';
2624
2625 if ( $cascade ) {
2626 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2627 }
2628
2629 if ( $reason ) {
2630 $comment .= ": $reason";
2631 }
2632
2633 $editComment = $comment;
2634 $encodedExpiry = array();
2635 $protect_description = '';
2636 foreach ( $limit as $action => $restrictions ) {
2637 if ( !isset( $expiry[$action] ) )
2638 $expiry[$action] = 'infinite';
2639
2640 $encodedExpiry[$action] = Block::encodeExpiry( $expiry[$action], $dbw );
2641 if ( $restrictions != '' ) {
2642 $protect_description .= "[$action=$restrictions] (";
2643 if ( $encodedExpiry[$action] != 'infinity' ) {
2644 $protect_description .= wfMsgForContent( 'protect-expiring',
2645 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2646 $wgContLang->date( $expiry[$action], false, false ) ,
2647 $wgContLang->time( $expiry[$action], false, false ) );
2648 } else {
2649 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2650 }
2651
2652 $protect_description .= ') ';
2653 }
2654 }
2655 $protect_description = trim( $protect_description );
2656
2657 if ( $protect_description && $protect ) {
2658 $editComment .= " ($protect_description)";
2659 }
2660
2661 if ( $cascade ) {
2662 $editComment .= "$cascade_description";
2663 }
2664
2665 # Update restrictions table
2666 foreach ( $limit as $action => $restrictions ) {
2667 if ( $restrictions != '' ) {
2668 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2669 array( 'pr_page' => $id,
2670 'pr_type' => $action,
2671 'pr_level' => $restrictions,
2672 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2673 'pr_expiry' => $encodedExpiry[$action]
2674 ),
2675 __METHOD__
2676 );
2677 } else {
2678 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2679 'pr_type' => $action ), __METHOD__ );
2680 }
2681 }
2682
2683 # Insert a null revision
2684 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2685 $nullRevId = $nullRevision->insertOn( $dbw );
2686
2687 $latest = $this->getLatest();
2688 # Update page record
2689 $dbw->update( 'page',
2690 array( /* SET */
2691 'page_touched' => $dbw->timestamp(),
2692 'page_restrictions' => '',
2693 'page_latest' => $nullRevId
2694 ), array( /* WHERE */
2695 'page_id' => $id
2696 ), 'Article::protect'
2697 );
2698
2699 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2700 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2701
2702 # Update the protection log
2703 $log = new LogPage( 'protect' );
2704 if ( $protect ) {
2705 $params = array( $protect_description, $cascade ? 'cascade' : '' );
2706 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
2707 } else {
2708 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2709 }
2710 } # End hook
2711 } # End "changed" check
2712
2713 return true;
2714 }
2715
2716 /**
2717 * Take an array of page restrictions and flatten it to a string
2718 * suitable for insertion into the page_restrictions field.
2719 * @param $limit Array
2720 * @return String
2721 */
2722 protected static function flattenRestrictions( $limit ) {
2723 if ( !is_array( $limit ) ) {
2724 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2725 }
2726
2727 $bits = array();
2728 ksort( $limit );
2729
2730 foreach ( $limit as $action => $restrictions ) {
2731 if ( $restrictions != '' ) {
2732 $bits[] = "$action=$restrictions";
2733 }
2734 }
2735
2736 return implode( ':', $bits );
2737 }
2738
2739 /**
2740 * Auto-generates a deletion reason
2741 *
2742 * @param &$hasHistory Boolean: whether the page has a history
2743 * @return mixed String containing deletion reason or empty string, or boolean false
2744 * if no revision occurred
2745 */
2746 public function generateReason( &$hasHistory ) {
2747 global $wgContLang;
2748
2749 $dbw = wfGetDB( DB_MASTER );
2750 // Get the last revision
2751 $rev = Revision::newFromTitle( $this->mTitle );
2752
2753 if ( is_null( $rev ) ) {
2754 return false;
2755 }
2756
2757 // Get the article's contents
2758 $contents = $rev->getText();
2759 $blank = false;
2760
2761 // If the page is blank, use the text from the previous revision,
2762 // which can only be blank if there's a move/import/protect dummy revision involved
2763 if ( $contents == '' ) {
2764 $prev = $rev->getPrevious();
2765
2766 if ( $prev ) {
2767 $contents = $prev->getText();
2768 $blank = true;
2769 }
2770 }
2771
2772 // Find out if there was only one contributor
2773 // Only scan the last 20 revisions
2774 $res = $dbw->select( 'revision', 'rev_user_text',
2775 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2776 __METHOD__,
2777 array( 'LIMIT' => 20 )
2778 );
2779
2780 if ( $res === false ) {
2781 // This page has no revisions, which is very weird
2782 return false;
2783 }
2784
2785 $hasHistory = ( $res->numRows() > 1 );
2786 $row = $dbw->fetchObject( $res );
2787
2788 if ( $row ) { // $row is false if the only contributor is hidden
2789 $onlyAuthor = $row->rev_user_text;
2790 // Try to find a second contributor
2791 foreach ( $res as $row ) {
2792 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2793 $onlyAuthor = false;
2794 break;
2795 }
2796 }
2797 } else {
2798 $onlyAuthor = false;
2799 }
2800
2801 $dbw->freeResult( $res );
2802
2803 // Generate the summary with a '$1' placeholder
2804 if ( $blank ) {
2805 // The current revision is blank and the one before is also
2806 // blank. It's just not our lucky day
2807 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2808 } else {
2809 if ( $onlyAuthor ) {
2810 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2811 } else {
2812 $reason = wfMsgForContent( 'excontent', '$1' );
2813 }
2814 }
2815
2816 if ( $reason == '-' ) {
2817 // Allow these UI messages to be blanked out cleanly
2818 return '';
2819 }
2820
2821 // Replace newlines with spaces to prevent uglyness
2822 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2823 // Calculate the maximum amount of chars to get
2824 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2825 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2826 $contents = $wgContLang->truncate( $contents, $maxLength );
2827 // Remove possible unfinished links
2828 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2829 // Now replace the '$1' placeholder
2830 $reason = str_replace( '$1', $contents, $reason );
2831
2832 return $reason;
2833 }
2834
2835
2836 /*
2837 * UI entry point for page deletion
2838 */
2839 public function delete() {
2840 global $wgUser, $wgOut, $wgRequest;
2841
2842 $confirm = $wgRequest->wasPosted() &&
2843 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2844
2845 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2846 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2847
2848 $reason = $this->DeleteReasonList;
2849
2850 if ( $reason != 'other' && $this->DeleteReason != '' ) {
2851 // Entry from drop down menu + additional comment
2852 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2853 } elseif ( $reason == 'other' ) {
2854 $reason = $this->DeleteReason;
2855 }
2856
2857 # Flag to hide all contents of the archived revisions
2858 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2859
2860 # This code desperately needs to be totally rewritten
2861
2862 # Read-only check...
2863 if ( wfReadOnly() ) {
2864 $wgOut->readOnlyPage();
2865
2866 return;
2867 }
2868
2869 # Check permissions
2870 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2871
2872 if ( count( $permission_errors ) > 0 ) {
2873 $wgOut->showPermissionsErrorPage( $permission_errors );
2874
2875 return;
2876 }
2877
2878 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2879
2880 # Better double-check that it hasn't been deleted yet!
2881 $dbw = wfGetDB( DB_MASTER );
2882 $conds = $this->mTitle->pageCond();
2883 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2884 if ( $latest === false ) {
2885 $wgOut->showFatalError(
2886 Html::rawElement(
2887 'div',
2888 array( 'class' => 'error mw-error-cannotdelete' ),
2889 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2890 )
2891 );
2892 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2893 LogEventsList::showLogExtract(
2894 $wgOut,
2895 'delete',
2896 $this->mTitle->getPrefixedText()
2897 );
2898
2899 return;
2900 }
2901
2902 # Hack for big sites
2903 $bigHistory = $this->isBigDeletion();
2904 if ( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2905 global $wgLang, $wgDeleteRevisionsLimit;
2906
2907 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2908 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2909
2910 return;
2911 }
2912
2913 if ( $confirm ) {
2914 $this->doDelete( $reason, $suppress );
2915
2916 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2917 $this->doWatch();
2918 } elseif ( $this->mTitle->userIsWatching() ) {
2919 $this->doUnwatch();
2920 }
2921
2922 return;
2923 }
2924
2925 // Generate deletion reason
2926 $hasHistory = false;
2927 if ( !$reason ) {
2928 $reason = $this->generateReason( $hasHistory );
2929 }
2930
2931 // If the page has a history, insert a warning
2932 if ( $hasHistory && !$confirm ) {
2933 global $wgLang;
2934
2935 $skin = $wgUser->getSkin();
2936 $revisions = $this->estimateRevisionCount();
2937 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2938 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2939 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2940 '</strong>'
2941 );
2942
2943 if ( $bigHistory ) {
2944 global $wgDeleteRevisionsLimit;
2945
2946 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2947 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2948 }
2949 }
2950
2951 return $this->confirmDelete( $reason );
2952 }
2953
2954 /**
2955 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2956 */
2957 public function isBigDeletion() {
2958 global $wgDeleteRevisionsLimit;
2959
2960 if ( $wgDeleteRevisionsLimit ) {
2961 $revCount = $this->estimateRevisionCount();
2962
2963 return $revCount > $wgDeleteRevisionsLimit;
2964 }
2965
2966 return false;
2967 }
2968
2969 /**
2970 * @return int approximate revision count
2971 */
2972 public function estimateRevisionCount() {
2973 $dbr = wfGetDB( DB_SLAVE );
2974
2975 // For an exact count...
2976 // return $dbr->selectField( 'revision', 'COUNT(*)',
2977 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2978 return $dbr->estimateRowCount( 'revision', '*',
2979 array( 'rev_page' => $this->getId() ), __METHOD__ );
2980 }
2981
2982 /**
2983 * Get the last N authors
2984 * @param $num Integer: number of revisions to get
2985 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2986 * @return array Array of authors, duplicates not removed
2987 */
2988 public function getLastNAuthors( $num, $revLatest = 0 ) {
2989 wfProfileIn( __METHOD__ );
2990 // First try the slave
2991 // If that doesn't have the latest revision, try the master
2992 $continue = 2;
2993 $db = wfGetDB( DB_SLAVE );
2994
2995 do {
2996 $res = $db->select( array( 'page', 'revision' ),
2997 array( 'rev_id', 'rev_user_text' ),
2998 array(
2999 'page_namespace' => $this->mTitle->getNamespace(),
3000 'page_title' => $this->mTitle->getDBkey(),
3001 'rev_page = page_id'
3002 ), __METHOD__, $this->getSelectOptions( array(
3003 'ORDER BY' => 'rev_timestamp DESC',
3004 'LIMIT' => $num
3005 ) )
3006 );
3007
3008 if ( !$res ) {
3009 wfProfileOut( __METHOD__ );
3010 return array();
3011 }
3012
3013 $row = $db->fetchObject( $res );
3014
3015 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
3016 $db = wfGetDB( DB_MASTER );
3017 $continue--;
3018 } else {
3019 $continue = 0;
3020 }
3021 } while ( $continue );
3022
3023 $authors = array( $row->rev_user_text );
3024
3025 while ( $row = $db->fetchObject( $res ) ) {
3026 $authors[] = $row->rev_user_text;
3027 }
3028
3029 wfProfileOut( __METHOD__ );
3030 return $authors;
3031 }
3032
3033 /**
3034 * Output deletion confirmation dialog
3035 * @param $reason String: prefilled reason
3036 */
3037 public function confirmDelete( $reason ) {
3038 global $wgOut, $wgUser;
3039
3040 wfDebug( "Article::confirmDelete\n" );
3041
3042 $deleteBackLink = $wgUser->getSkin()->link(
3043 $this->mTitle,
3044 null,
3045 array(),
3046 array(),
3047 array( 'known', 'noclasses' )
3048 );
3049 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
3050 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3051 $wgOut->addWikiMsg( 'confirmdeletetext' );
3052
3053 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
3054
3055 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
3056 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
3057 <td></td>
3058 <td class='mw-input'><strong>" .
3059 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
3060 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
3061 "</strong></td>
3062 </tr>";
3063 } else {
3064 $suppress = '';
3065 }
3066 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
3067
3068 $form = Xml::openElement( 'form', array( 'method' => 'post',
3069 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
3070 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
3071 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
3072 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
3073 "<tr id=\"wpDeleteReasonListRow\">
3074 <td class='mw-label'>" .
3075 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
3076 "</td>
3077 <td class='mw-input'>" .
3078 Xml::listDropDown( 'wpDeleteReasonList',
3079 wfMsgForContent( 'deletereason-dropdown' ),
3080 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
3081 "</td>
3082 </tr>
3083 <tr id=\"wpDeleteReasonRow\">
3084 <td class='mw-label'>" .
3085 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
3086 "</td>
3087 <td class='mw-input'>" .
3088 Html::input( 'wpReason', $reason, 'text', array(
3089 'size' => '60',
3090 'maxlength' => '255',
3091 'tabindex' => '2',
3092 'id' => 'wpReason',
3093 'autofocus'
3094 ) ) .
3095 "</td>
3096 </tr>";
3097
3098 # Disallow watching if user is not logged in
3099 if ( $wgUser->isLoggedIn() ) {
3100 $form .= "
3101 <tr>
3102 <td></td>
3103 <td class='mw-input'>" .
3104 Xml::checkLabel( wfMsg( 'watchthis' ),
3105 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
3106 "</td>
3107 </tr>";
3108 }
3109
3110 $form .= "
3111 $suppress
3112 <tr>
3113 <td></td>
3114 <td class='mw-submit'>" .
3115 Xml::submitButton( wfMsg( 'deletepage' ),
3116 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
3117 "</td>
3118 </tr>" .
3119 Xml::closeElement( 'table' ) .
3120 Xml::closeElement( 'fieldset' ) .
3121 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
3122 Xml::closeElement( 'form' );
3123
3124 if ( $wgUser->isAllowed( 'editinterface' ) ) {
3125 $skin = $wgUser->getSkin();
3126 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
3127 $link = $skin->link(
3128 $title,
3129 wfMsgHtml( 'delete-edit-reasonlist' ),
3130 array(),
3131 array( 'action' => 'edit' )
3132 );
3133 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3134 }
3135
3136 $wgOut->addHTML( $form );
3137 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3138 LogEventsList::showLogExtract(
3139 $wgOut,
3140 'delete',
3141 $this->mTitle->getPrefixedText()
3142 );
3143 }
3144
3145 /**
3146 * Perform a deletion and output success or failure messages
3147 */
3148 public function doDelete( $reason, $suppress = false ) {
3149 global $wgOut, $wgUser;
3150
3151 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
3152
3153 $error = '';
3154 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3155 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
3156 $deleted = $this->mTitle->getPrefixedText();
3157
3158 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3159 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3160
3161 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3162
3163 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3164 $wgOut->returnToMain( false );
3165 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3166 }
3167 } else {
3168 if ( $error == '' ) {
3169 $wgOut->showFatalError(
3170 Html::rawElement(
3171 'div',
3172 array( 'class' => 'error mw-error-cannotdelete' ),
3173 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
3174 )
3175 );
3176
3177 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3178
3179 LogEventsList::showLogExtract(
3180 $wgOut,
3181 'delete',
3182 $this->mTitle->getPrefixedText()
3183 );
3184 } else {
3185 $wgOut->showFatalError( $error );
3186 }
3187 }
3188 }
3189
3190 /**
3191 * Back-end article deletion
3192 * Deletes the article with database consistency, writes logs, purges caches
3193 *
3194 * @param $reason string delete reason for deletion log
3195 * @param suppress bitfield
3196 * Revision::DELETED_TEXT
3197 * Revision::DELETED_COMMENT
3198 * Revision::DELETED_USER
3199 * Revision::DELETED_RESTRICTED
3200 * @param $id int article ID
3201 * @param $commit boolean defaults to true, triggers transaction end
3202 * @return boolean true if successful
3203 */
3204 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
3205 global $wgUseSquid, $wgDeferredUpdateList;
3206 global $wgUseTrackbacks;
3207
3208 wfDebug( __METHOD__ . "\n" );
3209
3210 $dbw = wfGetDB( DB_MASTER );
3211 $ns = $this->mTitle->getNamespace();
3212 $t = $this->mTitle->getDBkey();
3213 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
3214
3215 if ( $t == '' || $id == 0 ) {
3216 return false;
3217 }
3218
3219 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3220 array_push( $wgDeferredUpdateList, $u );
3221
3222 // Bitfields to further suppress the content
3223 if ( $suppress ) {
3224 $bitfield = 0;
3225 // This should be 15...
3226 $bitfield |= Revision::DELETED_TEXT;
3227 $bitfield |= Revision::DELETED_COMMENT;
3228 $bitfield |= Revision::DELETED_USER;
3229 $bitfield |= Revision::DELETED_RESTRICTED;
3230 } else {
3231 $bitfield = 'rev_deleted';
3232 }
3233
3234 $dbw->begin();
3235 // For now, shunt the revision data into the archive table.
3236 // Text is *not* removed from the text table; bulk storage
3237 // is left intact to avoid breaking block-compression or
3238 // immutable storage schemes.
3239 //
3240 // For backwards compatibility, note that some older archive
3241 // table entries will have ar_text and ar_flags fields still.
3242 //
3243 // In the future, we may keep revisions and mark them with
3244 // the rev_deleted field, which is reserved for this purpose.
3245 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3246 array(
3247 'ar_namespace' => 'page_namespace',
3248 'ar_title' => 'page_title',
3249 'ar_comment' => 'rev_comment',
3250 'ar_user' => 'rev_user',
3251 'ar_user_text' => 'rev_user_text',
3252 'ar_timestamp' => 'rev_timestamp',
3253 'ar_minor_edit' => 'rev_minor_edit',
3254 'ar_rev_id' => 'rev_id',
3255 'ar_text_id' => 'rev_text_id',
3256 'ar_text' => '\'\'', // Be explicit to appease
3257 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3258 'ar_len' => 'rev_len',
3259 'ar_page_id' => 'page_id',
3260 'ar_deleted' => $bitfield
3261 ), array(
3262 'page_id' => $id,
3263 'page_id = rev_page'
3264 ), __METHOD__
3265 );
3266
3267 # Delete restrictions for it
3268 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
3269
3270 # Now that it's safely backed up, delete it
3271 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
3272 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3273
3274 if ( !$ok ) {
3275 $dbw->rollback();
3276 return false;
3277 }
3278
3279 # Fix category table counts
3280 $cats = array();
3281 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
3282
3283 foreach ( $res as $row ) {
3284 $cats [] = $row->cl_to;
3285 }
3286
3287 $this->updateCategoryCounts( array(), $cats );
3288
3289 # If using cascading deletes, we can skip some explicit deletes
3290 if ( !$dbw->cascadingDeletes() ) {
3291 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
3292
3293 if ( $wgUseTrackbacks )
3294 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
3295
3296 # Delete outgoing links
3297 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3298 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3299 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3300 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3301 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3302 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3303 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3304 }
3305
3306 # If using cleanup triggers, we can skip some manual deletes
3307 if ( !$dbw->cleanupTriggers() ) {
3308 # Clean up recentchanges entries...
3309 $dbw->delete( 'recentchanges',
3310 array( 'rc_type != ' . RC_LOG,
3311 'rc_namespace' => $this->mTitle->getNamespace(),
3312 'rc_title' => $this->mTitle->getDBkey() ),
3313 __METHOD__ );
3314 $dbw->delete( 'recentchanges',
3315 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
3316 __METHOD__ );
3317 }
3318
3319 # Clear caches
3320 Article::onArticleDelete( $this->mTitle );
3321
3322 # Clear the cached article id so the interface doesn't act like we exist
3323 $this->mTitle->resetArticleID( 0 );
3324
3325 # Log the deletion, if the page was suppressed, log it at Oversight instead
3326 $logtype = $suppress ? 'suppress' : 'delete';
3327 $log = new LogPage( $logtype );
3328
3329 # Make sure logging got through
3330 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
3331
3332 if ( $commit ) {
3333 $dbw->commit();
3334 }
3335
3336 return true;
3337 }
3338
3339 /**
3340 * Roll back the most recent consecutive set of edits to a page
3341 * from the same user; fails if there are no eligible edits to
3342 * roll back to, e.g. user is the sole contributor. This function
3343 * performs permissions checks on $wgUser, then calls commitRollback()
3344 * to do the dirty work
3345 *
3346 * @param $fromP String: Name of the user whose edits to rollback.
3347 * @param $summary String: Custom summary. Set to default summary if empty.
3348 * @param $token String: Rollback token.
3349 * @param $bot Boolean: If true, mark all reverted edits as bot.
3350 *
3351 * @param $resultDetails Array: contains result-specific array of additional values
3352 * 'alreadyrolled' : 'current' (rev)
3353 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3354 *
3355 * @return array of errors, each error formatted as
3356 * array(messagekey, param1, param2, ...).
3357 * On success, the array is empty. This array can also be passed to
3358 * OutputPage::showPermissionsErrorPage().
3359 */
3360 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3361 global $wgUser;
3362
3363 $resultDetails = null;
3364
3365 # Check permissions
3366 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
3367 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
3368 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3369
3370 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
3371 $errors[] = array( 'sessionfailure' );
3372 }
3373
3374 if ( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
3375 $errors[] = array( 'actionthrottledtext' );
3376 }
3377
3378 # If there were errors, bail out now
3379 if ( !empty( $errors ) ) {
3380 return $errors;
3381 }
3382
3383 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3384 }
3385
3386 /**
3387 * Backend implementation of doRollback(), please refer there for parameter
3388 * and return value documentation
3389 *
3390 * NOTE: This function does NOT check ANY permissions, it just commits the
3391 * rollback to the DB Therefore, you should only call this function direct-
3392 * ly if you want to use custom permissions checks. If you don't, use
3393 * doRollback() instead.
3394 */
3395 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3396 global $wgUseRCPatrol, $wgUser, $wgLang;
3397
3398 $dbw = wfGetDB( DB_MASTER );
3399
3400 if ( wfReadOnly() ) {
3401 return array( array( 'readonlytext' ) );
3402 }
3403
3404 # Get the last editor
3405 $current = Revision::newFromTitle( $this->mTitle );
3406 if ( is_null( $current ) ) {
3407 # Something wrong... no page?
3408 return array( array( 'notanarticle' ) );
3409 }
3410
3411 $from = str_replace( '_', ' ', $fromP );
3412 # User name given should match up with the top revision.
3413 # If the user was deleted then $from should be empty.
3414 if ( $from != $current->getUserText() ) {
3415 $resultDetails = array( 'current' => $current );
3416 return array( array( 'alreadyrolled',
3417 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3418 htmlspecialchars( $fromP ),
3419 htmlspecialchars( $current->getUserText() )
3420 ) );
3421 }
3422
3423 # Get the last edit not by this guy...
3424 # Note: these may not be public values
3425 $user = intval( $current->getRawUser() );
3426 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3427 $s = $dbw->selectRow( 'revision',
3428 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3429 array( 'rev_page' => $current->getPage(),
3430 "rev_user != {$user} OR rev_user_text != {$user_text}"
3431 ), __METHOD__,
3432 array( 'USE INDEX' => 'page_timestamp',
3433 'ORDER BY' => 'rev_timestamp DESC' )
3434 );
3435 if ( $s === false ) {
3436 # No one else ever edited this page
3437 return array( array( 'cantrollback' ) );
3438 } else if ( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
3439 # Only admins can see this text
3440 return array( array( 'notvisiblerev' ) );
3441 }
3442
3443 $set = array();
3444 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3445 # Mark all reverted edits as bot
3446 $set['rc_bot'] = 1;
3447 }
3448
3449 if ( $wgUseRCPatrol ) {
3450 # Mark all reverted edits as patrolled
3451 $set['rc_patrolled'] = 1;
3452 }
3453
3454 if ( count( $set ) ) {
3455 $dbw->update( 'recentchanges', $set,
3456 array( /* WHERE */
3457 'rc_cur_id' => $current->getPage(),
3458 'rc_user_text' => $current->getUserText(),
3459 "rc_timestamp > '{$s->rev_timestamp}'",
3460 ), __METHOD__
3461 );
3462 }
3463
3464 # Generate the edit summary if necessary
3465 $target = Revision::newFromId( $s->rev_id );
3466 if ( empty( $summary ) ) {
3467 if ( $from == '' ) { // no public user name
3468 $summary = wfMsgForContent( 'revertpage-nouser' );
3469 } else {
3470 $summary = wfMsgForContent( 'revertpage' );
3471 }
3472 }
3473
3474 # Allow the custom summary to use the same args as the default message
3475 $args = array(
3476 $target->getUserText(), $from, $s->rev_id,
3477 $wgLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ), true ),
3478 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3479 );
3480 $summary = wfMsgReplaceArgs( $summary, $args );
3481
3482 # Save
3483 $flags = EDIT_UPDATE;
3484
3485 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3486 $flags |= EDIT_MINOR;
3487 }
3488
3489 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) || $wgUser->isAllowed( 'bot' ) ) ) {
3490 $flags |= EDIT_FORCE_BOT;
3491 }
3492
3493 # Actually store the edit
3494 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3495 if ( !empty( $status->value['revision'] ) ) {
3496 $revId = $status->value['revision']->getId();
3497 } else {
3498 $revId = false;
3499 }
3500
3501 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3502
3503 $resultDetails = array(
3504 'summary' => $summary,
3505 'current' => $current,
3506 'target' => $target,
3507 'newid' => $revId
3508 );
3509
3510 return array();
3511 }
3512
3513 /**
3514 * User interface for rollback operations
3515 */
3516 public function rollback() {
3517 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3518
3519 $details = null;
3520
3521 $result = $this->doRollback(
3522 $wgRequest->getVal( 'from' ),
3523 $wgRequest->getText( 'summary' ),
3524 $wgRequest->getVal( 'token' ),
3525 $wgRequest->getBool( 'bot' ),
3526 $details
3527 );
3528
3529 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3530 $wgOut->rateLimited();
3531 return;
3532 }
3533
3534 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3535 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3536 $errArray = $result[0];
3537 $errMsg = array_shift( $errArray );
3538 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3539
3540 if ( isset( $details['current'] ) ) {
3541 $current = $details['current'];
3542
3543 if ( $current->getComment() != '' ) {
3544 $wgOut->addWikiMsgArray( 'editcomment', array(
3545 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3546 }
3547 }
3548
3549 return;
3550 }
3551
3552 # Display permissions errors before read-only message -- there's no
3553 # point in misleading the user into thinking the inability to rollback
3554 # is only temporary.
3555 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3556 # array_diff is completely broken for arrays of arrays, sigh.
3557 # Remove any 'readonlytext' error manually.
3558 $out = array();
3559 foreach ( $result as $error ) {
3560 if ( $error != array( 'readonlytext' ) ) {
3561 $out [] = $error;
3562 }
3563 }
3564 $wgOut->showPermissionsErrorPage( $out );
3565
3566 return;
3567 }
3568
3569 if ( $result == array( array( 'readonlytext' ) ) ) {
3570 $wgOut->readOnlyPage();
3571
3572 return;
3573 }
3574
3575 $current = $details['current'];
3576 $target = $details['target'];
3577 $newId = $details['newid'];
3578 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3579 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3580
3581 if ( $current->getUserText() === '' ) {
3582 $old = wfMsg( 'rev-deleted-user' );
3583 } else {
3584 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3585 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3586 }
3587
3588 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3589 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3590 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3591 $wgOut->returnToMain( false, $this->mTitle );
3592
3593 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3594 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3595 $de->showDiff( '', '' );
3596 }
3597 }
3598
3599 /**
3600 * Do standard deferred updates after page view
3601 */
3602 public function viewUpdates() {
3603 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3604 if ( wfReadOnly() ) {
3605 return;
3606 }
3607
3608 # Don't update page view counters on views from bot users (bug 14044)
3609 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3610 Article::incViewCount( $this->getID() );
3611 $u = new SiteStatsUpdate( 1, 0, 0 );
3612 array_push( $wgDeferredUpdateList, $u );
3613 }
3614
3615 # Update newtalk / watchlist notification status
3616 $wgUser->clearNotification( $this->mTitle );
3617 }
3618
3619 /**
3620 * Prepare text which is about to be saved.
3621 * Returns a stdclass with source, pst and output members
3622 */
3623 public function prepareTextForEdit( $text, $revid = null ) {
3624 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid ) {
3625 // Already prepared
3626 return $this->mPreparedEdit;
3627 }
3628
3629 global $wgParser;
3630
3631 $edit = (object)array();
3632 $edit->revid = $revid;
3633 $edit->newText = $text;
3634 $edit->pst = $this->preSaveTransform( $text );
3635 $options = $this->getParserOptions();
3636 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3637 $edit->oldText = $this->getContent();
3638
3639 $this->mPreparedEdit = $edit;
3640
3641 return $edit;
3642 }
3643
3644 /**
3645 * Do standard deferred updates after page edit.
3646 * Update links tables, site stats, search index and message cache.
3647 * Purges pages that include this page if the text was changed here.
3648 * Every 100th edit, prune the recent changes table.
3649 *
3650 * @private
3651 * @param $text New text of the article
3652 * @param $summary Edit summary
3653 * @param $minoredit Minor edit
3654 * @param $timestamp_of_pagechange Timestamp associated with the page change
3655 * @param $newid rev_id value of the new revision
3656 * @param $changed Whether or not the content actually changed
3657 */
3658 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3659 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3660
3661 wfProfileIn( __METHOD__ );
3662
3663 # Parse the text
3664 # Be careful not to double-PST: $text is usually already PST-ed once
3665 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3666 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3667 $editInfo = $this->prepareTextForEdit( $text, $newid );
3668 } else {
3669 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3670 $editInfo = $this->mPreparedEdit;
3671 }
3672
3673 # Save it to the parser cache
3674 if ( $wgEnableParserCache ) {
3675 $popts = $this->getParserOptions();
3676 $parserCache = ParserCache::singleton();
3677 $parserCache->save( $editInfo->output, $this, $popts );
3678 }
3679
3680 # Update the links tables
3681 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3682 $u->doUpdate();
3683
3684 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3685
3686 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3687 if ( 0 == mt_rand( 0, 99 ) ) {
3688 // Flush old entries from the `recentchanges` table; we do this on
3689 // random requests so as to avoid an increase in writes for no good reason
3690 global $wgRCMaxAge;
3691
3692 $dbw = wfGetDB( DB_MASTER );
3693 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3694 $recentchanges = $dbw->tableName( 'recentchanges' );
3695 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3696
3697 $dbw->query( $sql );
3698 }
3699 }
3700
3701 $id = $this->getID();
3702 $title = $this->mTitle->getPrefixedDBkey();
3703 $shortTitle = $this->mTitle->getDBkey();
3704
3705 if ( 0 == $id ) {
3706 wfProfileOut( __METHOD__ );
3707 return;
3708 }
3709
3710 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3711 array_push( $wgDeferredUpdateList, $u );
3712 $u = new SearchUpdate( $id, $title, $text );
3713 array_push( $wgDeferredUpdateList, $u );
3714
3715 # If this is another user's talk page, update newtalk
3716 # Don't do this if $changed = false otherwise some idiot can null-edit a
3717 # load of user talk pages and piss people off, nor if it's a minor edit
3718 # by a properly-flagged bot.
3719 if ( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3720 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3721 ) {
3722 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3723 $other = User::newFromName( $shortTitle, false );
3724 if ( !$other ) {
3725 wfDebug( __METHOD__ . ": invalid username\n" );
3726 } elseif ( User::isIP( $shortTitle ) ) {
3727 // An anonymous user
3728 $other->setNewtalk( true );
3729 } elseif ( $other->isLoggedIn() ) {
3730 $other->setNewtalk( true );
3731 } else {
3732 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
3733 }
3734 }
3735 }
3736
3737 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3738 $wgMessageCache->replace( $shortTitle, $text );
3739 }
3740
3741 wfProfileOut( __METHOD__ );
3742 }
3743
3744 /**
3745 * Perform article updates on a special page creation.
3746 *
3747 * @param $rev Revision object
3748 *
3749 * @todo This is a shitty interface function. Kill it and replace the
3750 * other shitty functions like editUpdates and such so it's not needed
3751 * anymore.
3752 */
3753 public function createUpdates( $rev ) {
3754 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3755 $this->mTotalAdjustment = 1;
3756 $this->editUpdates( $rev->getText(), $rev->getComment(),
3757 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3758 }
3759
3760 /**
3761 * Generate the navigation links when browsing through an article revisions
3762 * It shows the information as:
3763 * Revision as of \<date\>; view current revision
3764 * \<- Previous version | Next Version -\>
3765 *
3766 * @param $oldid String: revision ID of this article revision
3767 */
3768 public function setOldSubtitle( $oldid = 0 ) {
3769 global $wgLang, $wgOut, $wgUser, $wgRequest;
3770
3771 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3772 return;
3773 }
3774
3775 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3776
3777 # Cascade unhide param in links for easy deletion browsing
3778 $extraParams = array();
3779 if ( $wgRequest->getVal( 'unhide' ) ) {
3780 $extraParams['unhide'] = 1;
3781 }
3782
3783 $revision = Revision::newFromId( $oldid );
3784
3785 $current = ( $oldid == $this->mLatest );
3786 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3787 $tddate = $wgLang->date( $this->mTimestamp, true );
3788 $tdtime = $wgLang->time( $this->mTimestamp, true );
3789 $sk = $wgUser->getSkin();
3790 $lnk = $current
3791 ? wfMsgHtml( 'currentrevisionlink' )
3792 : $sk->link(
3793 $this->mTitle,
3794 wfMsgHtml( 'currentrevisionlink' ),
3795 array(),
3796 $extraParams,
3797 array( 'known', 'noclasses' )
3798 );
3799 $curdiff = $current
3800 ? wfMsgHtml( 'diff' )
3801 : $sk->link(
3802 $this->mTitle,
3803 wfMsgHtml( 'diff' ),
3804 array(),
3805 array(
3806 'diff' => 'cur',
3807 'oldid' => $oldid
3808 ) + $extraParams,
3809 array( 'known', 'noclasses' )
3810 );
3811 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3812 $prevlink = $prev
3813 ? $sk->link(
3814 $this->mTitle,
3815 wfMsgHtml( 'previousrevision' ),
3816 array(),
3817 array(
3818 'direction' => 'prev',
3819 'oldid' => $oldid
3820 ) + $extraParams,
3821 array( 'known', 'noclasses' )
3822 )
3823 : wfMsgHtml( 'previousrevision' );
3824 $prevdiff = $prev
3825 ? $sk->link(
3826 $this->mTitle,
3827 wfMsgHtml( 'diff' ),
3828 array(),
3829 array(
3830 'diff' => 'prev',
3831 'oldid' => $oldid
3832 ) + $extraParams,
3833 array( 'known', 'noclasses' )
3834 )
3835 : wfMsgHtml( 'diff' );
3836 $nextlink = $current
3837 ? wfMsgHtml( 'nextrevision' )
3838 : $sk->link(
3839 $this->mTitle,
3840 wfMsgHtml( 'nextrevision' ),
3841 array(),
3842 array(
3843 'direction' => 'next',
3844 'oldid' => $oldid
3845 ) + $extraParams,
3846 array( 'known', 'noclasses' )
3847 );
3848 $nextdiff = $current
3849 ? wfMsgHtml( 'diff' )
3850 : $sk->link(
3851 $this->mTitle,
3852 wfMsgHtml( 'diff' ),
3853 array(),
3854 array(
3855 'diff' => 'next',
3856 'oldid' => $oldid
3857 ) + $extraParams,
3858 array( 'known', 'noclasses' )
3859 );
3860
3861 $cdel = '';
3862
3863 // User can delete revisions or view deleted revisions...
3864 $canHide = $wgUser->isAllowed( 'deleterevision' );
3865 if ( $canHide || ( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3866 if ( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3867 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3868 } else {
3869 $query = array(
3870 'type' => 'revision',
3871 'target' => $this->mTitle->getPrefixedDbkey(),
3872 'ids' => $oldid
3873 );
3874 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
3875 }
3876 $cdel .= ' ';
3877 }
3878
3879 # Show user links if allowed to see them. If hidden, then show them only if requested...
3880 $userlinks = $sk->revUserTools( $revision, !$unhide );
3881
3882 $m = wfMsg( 'revision-info-current' );
3883 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3884 ? 'revision-info-current'
3885 : 'revision-info';
3886
3887 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3888 wfMsgExt(
3889 $infomsg,
3890 array( 'parseinline', 'replaceafter' ),
3891 $td,
3892 $userlinks,
3893 $revision->getID(),
3894 $tddate,
3895 $tdtime,
3896 $revision->getUser()
3897 ) .
3898 "</div>\n" .
3899 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3900 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3901
3902 $wgOut->setSubtitle( $r );
3903 }
3904
3905 /**
3906 * This function is called right before saving the wikitext,
3907 * so we can do things like signatures and links-in-context.
3908 *
3909 * @param $text String article contents
3910 * @return string article contents with altered wikitext markup (signatures
3911 * converted, {{subst:}}, templates, etc.)
3912 */
3913 public function preSaveTransform( $text ) {
3914 global $wgParser, $wgUser;
3915
3916 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3917 }
3918
3919 /* Caching functions */
3920
3921 /**
3922 * checkLastModified returns true if it has taken care of all
3923 * output to the client that is necessary for this request.
3924 * (that is, it has sent a cached version of the page)
3925 *
3926 * @return boolean true if cached version send, false otherwise
3927 */
3928 protected function tryFileCache() {
3929 static $called = false;
3930
3931 if ( $called ) {
3932 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3933 return false;
3934 }
3935
3936 $called = true;
3937 if ( $this->isFileCacheable() ) {
3938 $cache = new HTMLFileCache( $this->mTitle );
3939 if ( $cache->isFileCacheGood( $this->mTouched ) ) {
3940 wfDebug( "Article::tryFileCache(): about to load file\n" );
3941 $cache->loadFromFileCache();
3942 return true;
3943 } else {
3944 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3945 ob_start( array( &$cache, 'saveToFileCache' ) );
3946 }
3947 } else {
3948 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3949 }
3950
3951 return false;
3952 }
3953
3954 /**
3955 * Check if the page can be cached
3956 * @return bool
3957 */
3958 public function isFileCacheable() {
3959 $cacheable = false;
3960
3961 if ( HTMLFileCache::useFileCache() ) {
3962 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3963 // Extension may have reason to disable file caching on some pages.
3964 if ( $cacheable ) {
3965 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3966 }
3967 }
3968
3969 return $cacheable;
3970 }
3971
3972 /**
3973 * Loads page_touched and returns a value indicating if it should be used
3974 * @return boolean true if not a redirect
3975 */
3976 public function checkTouched() {
3977 if ( !$this->mDataLoaded ) {
3978 $this->loadPageData();
3979 }
3980
3981 return !$this->mIsRedirect;
3982 }
3983
3984 /**
3985 * Get the page_touched field
3986 * @return string containing GMT timestamp
3987 */
3988 public function getTouched() {
3989 # Ensure that page data has been loaded
3990 if ( !$this->mDataLoaded ) {
3991 $this->loadPageData();
3992 }
3993
3994 return $this->mTouched;
3995 }
3996
3997 /**
3998 * Get the page_latest field
3999 * @return integer rev_id of current revision
4000 */
4001 public function getLatest() {
4002 if ( !$this->mDataLoaded ) {
4003 $this->loadPageData();
4004 }
4005
4006 return (int)$this->mLatest;
4007 }
4008
4009 /**
4010 * Edit an article without doing all that other stuff
4011 * The article must already exist; link tables etc
4012 * are not updated, caches are not flushed.
4013 *
4014 * @param $text String: text submitted
4015 * @param $comment String: comment submitted
4016 * @param $minor Boolean: whereas it's a minor modification
4017 */
4018 public function quickEdit( $text, $comment = '', $minor = 0 ) {
4019 wfProfileIn( __METHOD__ );
4020
4021 $dbw = wfGetDB( DB_MASTER );
4022 $revision = new Revision( array(
4023 'page' => $this->getId(),
4024 'text' => $text,
4025 'comment' => $comment,
4026 'minor_edit' => $minor ? 1 : 0,
4027 ) );
4028 $revision->insertOn( $dbw );
4029 $this->updateRevisionOn( $dbw, $revision );
4030
4031 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
4032
4033 wfProfileOut( __METHOD__ );
4034 }
4035
4036 /**
4037 * Used to increment the view counter
4038 *
4039 * @param $id Integer: article id
4040 */
4041 public static function incViewCount( $id ) {
4042 $id = intval( $id );
4043
4044 global $wgHitcounterUpdateFreq;
4045
4046 $dbw = wfGetDB( DB_MASTER );
4047 $pageTable = $dbw->tableName( 'page' );
4048 $hitcounterTable = $dbw->tableName( 'hitcounter' );
4049 $acchitsTable = $dbw->tableName( 'acchits' );
4050
4051 if ( $wgHitcounterUpdateFreq <= 1 ) {
4052 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
4053
4054 return;
4055 }
4056
4057 # Not important enough to warrant an error page in case of failure
4058 $oldignore = $dbw->ignoreErrors( true );
4059
4060 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
4061
4062 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 + 1 );
4063 if ( ( rand() % $checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
4064 # Most of the time (or on SQL errors), skip row count check
4065 $dbw->ignoreErrors( $oldignore );
4066
4067 return;
4068 }
4069
4070 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
4071 $row = $dbw->fetchObject( $res );
4072 $rown = intval( $row->n );
4073
4074 if ( $rown >= $wgHitcounterUpdateFreq ) {
4075 wfProfileIn( 'Article::incViewCount-collect' );
4076 $old_user_abort = ignore_user_abort( true );
4077
4078 $dbType = $dbw->getType();
4079 $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__, false );
4080 $tabletype = $dbType == 'mysql' ? "ENGINE=HEAP " : '';
4081 $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
4082 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
4083 'GROUP BY hc_id', __METHOD__ );
4084 $dbw->delete( 'hitcounter', '*', __METHOD__ );
4085 $dbw->unlockTables( __METHOD__ );
4086
4087 if ( $dbType == 'mysql' ) {
4088 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
4089 'WHERE page_id = hc_id', __METHOD__ );
4090 } else {
4091 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
4092 "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__ );
4093 }
4094 $dbw->query( "DROP TABLE $acchitsTable", __METHOD__ );
4095
4096 ignore_user_abort( $old_user_abort );
4097 wfProfileOut( 'Article::incViewCount-collect' );
4098 }
4099
4100 $dbw->ignoreErrors( $oldignore );
4101 }
4102
4103 /**#@+
4104 * The onArticle*() functions are supposed to be a kind of hooks
4105 * which should be called whenever any of the specified actions
4106 * are done.
4107 *
4108 * This is a good place to put code to clear caches, for instance.
4109 *
4110 * This is called on page move and undelete, as well as edit
4111 *
4112 * @param $title a title object
4113 */
4114 public static function onArticleCreate( $title ) {
4115 # Update existence markers on article/talk tabs...
4116 if ( $title->isTalkPage() ) {
4117 $other = $title->getSubjectPage();
4118 } else {
4119 $other = $title->getTalkPage();
4120 }
4121
4122 $other->invalidateCache();
4123 $other->purgeSquid();
4124
4125 $title->touchLinks();
4126 $title->purgeSquid();
4127 $title->deleteTitleProtection();
4128 }
4129
4130 /**
4131 * Clears caches when article is deleted
4132 */
4133 public static function onArticleDelete( $title ) {
4134 global $wgMessageCache;
4135
4136 # Update existence markers on article/talk tabs...
4137 if ( $title->isTalkPage() ) {
4138 $other = $title->getSubjectPage();
4139 } else {
4140 $other = $title->getTalkPage();
4141 }
4142
4143 $other->invalidateCache();
4144 $other->purgeSquid();
4145
4146 $title->touchLinks();
4147 $title->purgeSquid();
4148
4149 # File cache
4150 HTMLFileCache::clearFileCache( $title );
4151
4152 # Messages
4153 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
4154 $wgMessageCache->replace( $title->getDBkey(), false );
4155 }
4156
4157 # Images
4158 if ( $title->getNamespace() == NS_FILE ) {
4159 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
4160 $update->doUpdate();
4161 }
4162
4163 # User talk pages
4164 if ( $title->getNamespace() == NS_USER_TALK ) {
4165 $user = User::newFromName( $title->getText(), false );
4166 $user->setNewtalk( false );
4167 }
4168
4169 # Image redirects
4170 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4171 }
4172
4173 /**
4174 * Purge caches on page update etc
4175 *
4176 * @param $title Title object
4177 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4178 */
4179 public static function onArticleEdit( $title ) {
4180 global $wgDeferredUpdateList;
4181
4182 // Invalidate caches of articles which include this page
4183 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4184
4185 // Invalidate the caches of all pages which redirect here
4186 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4187
4188 # Purge squid for this page only
4189 $title->purgeSquid();
4190
4191 # Clear file cache for this page only
4192 HTMLFileCache::clearFileCache( $title );
4193 }
4194
4195 /**#@-*/
4196
4197 /**
4198 * Overriden by ImagePage class, only present here to avoid a fatal error
4199 * Called for ?action=revert
4200 */
4201 public function revert() {
4202 global $wgOut;
4203
4204 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4205 }
4206
4207 /**
4208 * Info about this page
4209 * Called for ?action=info when $wgAllowPageInfo is on.
4210 */
4211 public function info() {
4212 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4213
4214 if ( !$wgAllowPageInfo ) {
4215 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4216 return;
4217 }
4218
4219 $page = $this->mTitle->getSubjectPage();
4220
4221 $wgOut->setPagetitle( $page->getPrefixedText() );
4222 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4223 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4224
4225 if ( !$this->mTitle->exists() ) {
4226 $wgOut->addHTML( '<div class="noarticletext">' );
4227 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
4228 // This doesn't quite make sense; the user is asking for
4229 // information about the _page_, not the message... -- RC
4230 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
4231 } else {
4232 $msg = $wgUser->isLoggedIn()
4233 ? 'noarticletext'
4234 : 'noarticletextanon';
4235 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
4236 }
4237
4238 $wgOut->addHTML( '</div>' );
4239 } else {
4240 $dbr = wfGetDB( DB_SLAVE );
4241 $wl_clause = array(
4242 'wl_title' => $page->getDBkey(),
4243 'wl_namespace' => $page->getNamespace() );
4244 $numwatchers = $dbr->selectField(
4245 'watchlist',
4246 'COUNT(*)',
4247 $wl_clause,
4248 __METHOD__,
4249 $this->getSelectOptions() );
4250
4251 $pageInfo = $this->pageCountInfo( $page );
4252 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4253
4254 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4255 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4256
4257 if ( $talkInfo ) {
4258 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4259 }
4260
4261 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4262
4263 if ( $talkInfo ) {
4264 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4265 }
4266
4267 $wgOut->addHTML( '</ul>' );
4268 }
4269 }
4270
4271 /**
4272 * Return the total number of edits and number of unique editors
4273 * on a given page. If page does not exist, returns false.
4274 *
4275 * @param $title Title object
4276 * @return mixed array or boolean false
4277 */
4278 public function pageCountInfo( $title ) {
4279 $id = $title->getArticleId();
4280
4281 if ( $id == 0 ) {
4282 return false;
4283 }
4284
4285 $dbr = wfGetDB( DB_SLAVE );
4286 $rev_clause = array( 'rev_page' => $id );
4287 $edits = $dbr->selectField(
4288 'revision',
4289 'COUNT(rev_page)',
4290 $rev_clause,
4291 __METHOD__,
4292 $this->getSelectOptions()
4293 );
4294 $authors = $dbr->selectField(
4295 'revision',
4296 'COUNT(DISTINCT rev_user_text)',
4297 $rev_clause,
4298 __METHOD__,
4299 $this->getSelectOptions()
4300 );
4301
4302 return array( 'edits' => $edits, 'authors' => $authors );
4303 }
4304
4305 /**
4306 * Return a list of templates used by this article.
4307 * Uses the templatelinks table
4308 *
4309 * @return Array of Title objects
4310 */
4311 public function getUsedTemplates() {
4312 $result = array();
4313 $id = $this->mTitle->getArticleID();
4314
4315 if ( $id == 0 ) {
4316 return array();
4317 }
4318
4319 $dbr = wfGetDB( DB_SLAVE );
4320 $res = $dbr->select( array( 'templatelinks' ),
4321 array( 'tl_namespace', 'tl_title' ),
4322 array( 'tl_from' => $id ),
4323 __METHOD__ );
4324
4325 if ( $res !== false ) {
4326 foreach ( $res as $row ) {
4327 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
4328 }
4329 }
4330
4331 $dbr->freeResult( $res );
4332
4333 return $result;
4334 }
4335
4336 /**
4337 * Returns a list of hidden categories this page is a member of.
4338 * Uses the page_props and categorylinks tables.
4339 *
4340 * @return Array of Title objects
4341 */
4342 public function getHiddenCategories() {
4343 $result = array();
4344 $id = $this->mTitle->getArticleID();
4345
4346 if ( $id == 0 ) {
4347 return array();
4348 }
4349
4350 $dbr = wfGetDB( DB_SLAVE );
4351 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4352 array( 'cl_to' ),
4353 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4354 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
4355 __METHOD__ );
4356
4357 if ( $res !== false ) {
4358 foreach ( $res as $row ) {
4359 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
4360 }
4361 }
4362
4363 $dbr->freeResult( $res );
4364
4365 return $result;
4366 }
4367
4368 /**
4369 * Return an applicable autosummary if one exists for the given edit.
4370 * @param $oldtext String: the previous text of the page.
4371 * @param $newtext String: The submitted text of the page.
4372 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
4373 * @return string An appropriate autosummary, or an empty string.
4374 */
4375 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4376 # Decide what kind of autosummary is needed.
4377
4378 # Redirect autosummaries
4379 $ot = Title::newFromRedirect( $oldtext );
4380 $rt = Title::newFromRedirect( $newtext );
4381
4382 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
4383 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4384 }
4385
4386 # New page autosummaries
4387 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
4388 # If they're making a new article, give its text, truncated, in the summary.
4389 global $wgContLang;
4390
4391 $truncatedtext = $wgContLang->truncate(
4392 str_replace( "\n", ' ', $newtext ),
4393 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4394
4395 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4396 }
4397
4398 # Blanking autosummaries
4399 if ( $oldtext != '' && $newtext == '' ) {
4400 return wfMsgForContent( 'autosumm-blank' );
4401 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4402 # Removing more than 90% of the article
4403 global $wgContLang;
4404
4405 $truncatedtext = $wgContLang->truncate(
4406 $newtext,
4407 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4408
4409 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4410 }
4411
4412 # If we reach this point, there's no applicable autosummary for our case, so our
4413 # autosummary is empty.
4414 return '';
4415 }
4416
4417 /**
4418 * Add the primary page-view wikitext to the output buffer
4419 * Saves the text into the parser cache if possible.
4420 * Updates templatelinks if it is out of date.
4421 *
4422 * @param $text String
4423 * @param $cache Boolean
4424 * @param $parserOptions mixed ParserOptions object, or boolean false
4425 */
4426 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4427 global $wgOut;
4428
4429 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4430 $wgOut->addParserOutput( $this->mParserOutput );
4431 }
4432
4433 /**
4434 * This does all the heavy lifting for outputWikitext, except it returns the parser
4435 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4436 * say, embedding thread pages within a discussion system (LiquidThreads)
4437 *
4438 * @param $text string
4439 * @param $cache boolean
4440 * @param $parserOptions parsing options, defaults to false
4441 * @return string containing parsed output
4442 */
4443 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4444 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
4445
4446 if ( !$parserOptions ) {
4447 $parserOptions = $this->getParserOptions();
4448 }
4449
4450 $time = - wfTime();
4451 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
4452 $parserOptions, true, true, $this->getRevIdFetched() );
4453 $time += wfTime();
4454
4455 # Timing hack
4456 if ( $time > 3 ) {
4457 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4458 $this->mTitle->getPrefixedDBkey() ) );
4459 }
4460
4461 if ( $wgEnableParserCache && $cache && $this->mParserOutput->isCacheable() ) {
4462 $parserCache = ParserCache::singleton();
4463 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
4464 }
4465
4466 // Make sure file cache is not used on uncacheable content.
4467 // Output that has magic words in it can still use the parser cache
4468 // (if enabled), though it will generally expire sooner.
4469 if ( !$this->mParserOutput->isCacheable() || $this->mParserOutput->containsOldMagic() ) {
4470 $wgUseFileCache = false;
4471 }
4472
4473 $this->doCascadeProtectionUpdates( $this->mParserOutput );
4474
4475 return $this->mParserOutput;
4476 }
4477
4478 /**
4479 * Get parser options suitable for rendering the primary article wikitext
4480 * @return mixed ParserOptions object or boolean false
4481 */
4482 public function getParserOptions() {
4483 global $wgUser;
4484
4485 if ( !$this->mParserOptions ) {
4486 $this->mParserOptions = new ParserOptions( $wgUser );
4487 $this->mParserOptions->setTidy( true );
4488 $this->mParserOptions->enableLimitReport();
4489 }
4490
4491 return $this->mParserOptions;
4492 }
4493
4494 /**
4495 * Updates cascading protections
4496 *
4497 * @param $parserOutput mixed ParserOptions object, or boolean false
4498 **/
4499
4500 protected function doCascadeProtectionUpdates( $parserOutput ) {
4501 if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4502 return;
4503 }
4504
4505 // templatelinks table may have become out of sync,
4506 // especially if using variable-based transclusions.
4507 // For paranoia, check if things have changed and if
4508 // so apply updates to the database. This will ensure
4509 // that cascaded protections apply as soon as the changes
4510 // are visible.
4511
4512 # Get templates from templatelinks
4513 $id = $this->mTitle->getArticleID();
4514
4515 $tlTemplates = array();
4516
4517 $dbr = wfGetDB( DB_SLAVE );
4518 $res = $dbr->select( array( 'templatelinks' ),
4519 array( 'tl_namespace', 'tl_title' ),
4520 array( 'tl_from' => $id ),
4521 __METHOD__
4522 );
4523
4524 global $wgContLang;
4525
4526 foreach ( $res as $row ) {
4527 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4528 }
4529
4530 # Get templates from parser output.
4531 $poTemplates = array();
4532 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4533 foreach ( $templates as $dbk => $id ) {
4534 $poTemplates["$ns:$dbk"] = true;
4535 }
4536 }
4537
4538 # Get the diff
4539 # Note that we simulate array_diff_key in PHP <5.0.x
4540 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4541
4542 if ( count( $templates_diff ) > 0 ) {
4543 # Whee, link updates time.
4544 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4545 $u->doUpdate();
4546 }
4547 }
4548
4549 /**
4550 * Update all the appropriate counts in the category table, given that
4551 * we've added the categories $added and deleted the categories $deleted.
4552 *
4553 * @param $added array The names of categories that were added
4554 * @param $deleted array The names of categories that were deleted
4555 */
4556 public function updateCategoryCounts( $added, $deleted ) {
4557 $ns = $this->mTitle->getNamespace();
4558 $dbw = wfGetDB( DB_MASTER );
4559
4560 # First make sure the rows exist. If one of the "deleted" ones didn't
4561 # exist, we might legitimately not create it, but it's simpler to just
4562 # create it and then give it a negative value, since the value is bogus
4563 # anyway.
4564 #
4565 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4566 $insertCats = array_merge( $added, $deleted );
4567 if ( !$insertCats ) {
4568 # Okay, nothing to do
4569 return;
4570 }
4571
4572 $insertRows = array();
4573
4574 foreach ( $insertCats as $cat ) {
4575 $insertRows[] = array(
4576 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4577 'cat_title' => $cat
4578 );
4579 }
4580 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4581
4582 $addFields = array( 'cat_pages = cat_pages + 1' );
4583 $removeFields = array( 'cat_pages = cat_pages - 1' );
4584
4585 if ( $ns == NS_CATEGORY ) {
4586 $addFields[] = 'cat_subcats = cat_subcats + 1';
4587 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4588 } elseif ( $ns == NS_FILE ) {
4589 $addFields[] = 'cat_files = cat_files + 1';
4590 $removeFields[] = 'cat_files = cat_files - 1';
4591 }
4592
4593 if ( $added ) {
4594 $dbw->update(
4595 'category',
4596 $addFields,
4597 array( 'cat_title' => $added ),
4598 __METHOD__
4599 );
4600 }
4601
4602 if ( $deleted ) {
4603 $dbw->update(
4604 'category',
4605 $removeFields,
4606 array( 'cat_title' => $deleted ),
4607 __METHOD__
4608 );
4609 }
4610 }
4611
4612 /**
4613 * Lightweight method to get the parser output for a page, checking the parser cache
4614 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4615 * consider, so it's not appropriate to use there.
4616 *
4617 * @param $oldid mixed integer Revision ID or null
4618 */
4619 public function getParserOutput( $oldid = null ) {
4620 global $wgEnableParserCache, $wgUser, $wgOut;
4621
4622 // Should the parser cache be used?
4623 $useParserCache = $wgEnableParserCache &&
4624 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4625 $this->exists() &&
4626 $oldid === null;
4627
4628 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4629
4630 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4631 wfIncrStats( 'pcache_miss_stub' );
4632 }
4633
4634 $parserOutput = false;
4635 if ( $useParserCache ) {
4636 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4637 }
4638
4639 if ( $parserOutput === false ) {
4640 // Cache miss; parse and output it.
4641 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4642
4643 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4644 } else {
4645 return $parserOutput;
4646 }
4647 }
4648 }