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