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