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