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