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