Follow-up r90749:
[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, $wgStylePath;
1628
1629 if ( !is_array( $target ) ) {
1630 $target = array( $target );
1631 }
1632
1633 $imageDir = wfUILang()->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 = wfUILang()->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 # Promote user to any groups they meet the criteria for
2351 $user->addAutopromoteOnceGroups( 'onEdit' );
2352
2353 wfProfileOut( __METHOD__ );
2354 return $status;
2355 }
2356
2357 /**
2358 * Output a redirect back to the article.
2359 * This is typically used after an edit.
2360 *
2361 * @deprecated in 1.19; call $wgOut->redirect() directly
2362 * @param $noRedir Boolean: add redirect=no
2363 * @param $sectionAnchor String: section to redirect to, including "#"
2364 * @param $extraQuery String: extra query params
2365 */
2366 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2367 wfDeprecated( __METHOD__ );
2368 global $wgOut;
2369
2370 if ( $noRedir ) {
2371 $query = 'redirect=no';
2372 if ( $extraQuery )
2373 $query .= "&$extraQuery";
2374 } else {
2375 $query = $extraQuery;
2376 }
2377
2378 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2379 }
2380
2381 /**
2382 * Update the article's restriction field, and leave a log entry.
2383 *
2384 * @param $limit Array: set of restriction keys
2385 * @param $reason String
2386 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2387 * @param $expiry Array: per restriction type expiration
2388 * @return bool true on success
2389 */
2390 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2391 global $wgUser, $wgContLang;
2392
2393 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2394
2395 $id = $this->mTitle->getArticleID();
2396
2397 if ( $id <= 0 ) {
2398 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2399 return false;
2400 }
2401
2402 if ( wfReadOnly() ) {
2403 wfDebug( "updateRestrictions failed: read-only\n" );
2404 return false;
2405 }
2406
2407 if ( !$this->mTitle->userCan( 'protect' ) ) {
2408 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2409 return false;
2410 }
2411
2412 if ( !$cascade ) {
2413 $cascade = false;
2414 }
2415
2416 // Take this opportunity to purge out expired restrictions
2417 Title::purgeExpiredRestrictions();
2418
2419 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2420 # we expect a single selection, but the schema allows otherwise.
2421 $current = array();
2422 $updated = Article::flattenRestrictions( $limit );
2423 $changed = false;
2424
2425 foreach ( $restrictionTypes as $action ) {
2426 if ( isset( $expiry[$action] ) ) {
2427 # Get current restrictions on $action
2428 $aLimits = $this->mTitle->getRestrictions( $action );
2429 $current[$action] = implode( '', $aLimits );
2430 # Are any actual restrictions being dealt with here?
2431 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
2432
2433 # If something changed, we need to log it. Checking $aRChanged
2434 # assures that "unprotecting" a page that is not protected does
2435 # not log just because the expiry was "changed".
2436 if ( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2437 $changed = true;
2438 }
2439 }
2440 }
2441
2442 $current = Article::flattenRestrictions( $current );
2443
2444 $changed = ( $changed || $current != $updated );
2445 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
2446 $protect = ( $updated != '' );
2447
2448 # If nothing's changed, do nothing
2449 if ( $changed ) {
2450 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2451 $dbw = wfGetDB( DB_MASTER );
2452
2453 # Prepare a null revision to be added to the history
2454 $modified = $current != '' && $protect;
2455
2456 if ( $protect ) {
2457 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2458 } else {
2459 $comment_type = 'unprotectedarticle';
2460 }
2461
2462 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2463
2464 # Only restrictions with the 'protect' right can cascade...
2465 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2466 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2467
2468 # The schema allows multiple restrictions
2469 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2470 $cascade = false;
2471 }
2472
2473 $cascade_description = '';
2474
2475 if ( $cascade ) {
2476 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2477 }
2478
2479 if ( $reason ) {
2480 $comment .= ": $reason";
2481 }
2482
2483 $editComment = $comment;
2484 $encodedExpiry = array();
2485 $protect_description = '';
2486 foreach ( $limit as $action => $restrictions ) {
2487 if ( !isset( $expiry[$action] ) )
2488 $expiry[$action] = $dbw->getInfinity();
2489
2490 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2491 if ( $restrictions != '' ) {
2492 $protect_description .= "[$action=$restrictions] (";
2493 if ( $encodedExpiry[$action] != 'infinity' ) {
2494 $protect_description .= wfMsgForContent( 'protect-expiring',
2495 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2496 $wgContLang->date( $expiry[$action], false, false ) ,
2497 $wgContLang->time( $expiry[$action], false, false ) );
2498 } else {
2499 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2500 }
2501
2502 $protect_description .= ') ';
2503 }
2504 }
2505 $protect_description = trim( $protect_description );
2506
2507 if ( $protect_description && $protect ) {
2508 $editComment .= " ($protect_description)";
2509 }
2510
2511 if ( $cascade ) {
2512 $editComment .= "$cascade_description";
2513 }
2514
2515 # Update restrictions table
2516 foreach ( $limit as $action => $restrictions ) {
2517 if ( $restrictions != '' ) {
2518 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2519 array( 'pr_page' => $id,
2520 'pr_type' => $action,
2521 'pr_level' => $restrictions,
2522 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2523 'pr_expiry' => $encodedExpiry[$action]
2524 ),
2525 __METHOD__
2526 );
2527 } else {
2528 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2529 'pr_type' => $action ), __METHOD__ );
2530 }
2531 }
2532
2533 # Insert a null revision
2534 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2535 $nullRevId = $nullRevision->insertOn( $dbw );
2536
2537 $latest = $this->getLatest();
2538 # Update page record
2539 $dbw->update( 'page',
2540 array( /* SET */
2541 'page_touched' => $dbw->timestamp(),
2542 'page_restrictions' => '',
2543 'page_latest' => $nullRevId
2544 ), array( /* WHERE */
2545 'page_id' => $id
2546 ), 'Article::protect'
2547 );
2548
2549 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2550 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2551
2552 # Update the protection log
2553 $log = new LogPage( 'protect' );
2554 if ( $protect ) {
2555 $params = array( $protect_description, $cascade ? 'cascade' : '' );
2556 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
2557 } else {
2558 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2559 }
2560 } # End hook
2561 } # End "changed" check
2562
2563 return true;
2564 }
2565
2566 /**
2567 * Take an array of page restrictions and flatten it to a string
2568 * suitable for insertion into the page_restrictions field.
2569 * @param $limit Array
2570 * @return String
2571 */
2572 protected static function flattenRestrictions( $limit ) {
2573 if ( !is_array( $limit ) ) {
2574 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2575 }
2576
2577 $bits = array();
2578 ksort( $limit );
2579
2580 foreach ( $limit as $action => $restrictions ) {
2581 if ( $restrictions != '' ) {
2582 $bits[] = "$action=$restrictions";
2583 }
2584 }
2585
2586 return implode( ':', $bits );
2587 }
2588
2589 /**
2590 * Auto-generates a deletion reason
2591 *
2592 * @param &$hasHistory Boolean: whether the page has a history
2593 * @return mixed String containing deletion reason or empty string, or boolean false
2594 * if no revision occurred
2595 */
2596 public function generateReason( &$hasHistory ) {
2597 global $wgContLang;
2598
2599 $dbw = wfGetDB( DB_MASTER );
2600 // Get the last revision
2601 $rev = Revision::newFromTitle( $this->mTitle );
2602
2603 if ( is_null( $rev ) ) {
2604 return false;
2605 }
2606
2607 // Get the article's contents
2608 $contents = $rev->getText();
2609 $blank = false;
2610
2611 // If the page is blank, use the text from the previous revision,
2612 // which can only be blank if there's a move/import/protect dummy revision involved
2613 if ( $contents == '' ) {
2614 $prev = $rev->getPrevious();
2615
2616 if ( $prev ) {
2617 $contents = $prev->getText();
2618 $blank = true;
2619 }
2620 }
2621
2622 // Find out if there was only one contributor
2623 // Only scan the last 20 revisions
2624 $res = $dbw->select( 'revision', 'rev_user_text',
2625 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2626 __METHOD__,
2627 array( 'LIMIT' => 20 )
2628 );
2629
2630 if ( $res === false ) {
2631 // This page has no revisions, which is very weird
2632 return false;
2633 }
2634
2635 $hasHistory = ( $res->numRows() > 1 );
2636 $row = $dbw->fetchObject( $res );
2637
2638 if ( $row ) { // $row is false if the only contributor is hidden
2639 $onlyAuthor = $row->rev_user_text;
2640 // Try to find a second contributor
2641 foreach ( $res as $row ) {
2642 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2643 $onlyAuthor = false;
2644 break;
2645 }
2646 }
2647 } else {
2648 $onlyAuthor = false;
2649 }
2650
2651 // Generate the summary with a '$1' placeholder
2652 if ( $blank ) {
2653 // The current revision is blank and the one before is also
2654 // blank. It's just not our lucky day
2655 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2656 } else {
2657 if ( $onlyAuthor ) {
2658 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2659 } else {
2660 $reason = wfMsgForContent( 'excontent', '$1' );
2661 }
2662 }
2663
2664 if ( $reason == '-' ) {
2665 // Allow these UI messages to be blanked out cleanly
2666 return '';
2667 }
2668
2669 // Replace newlines with spaces to prevent uglyness
2670 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2671 // Calculate the maximum amount of chars to get
2672 // Max content length = max comment length - length of the comment (excl. $1)
2673 $maxLength = 255 - ( strlen( $reason ) - 2 );
2674 $contents = $wgContLang->truncate( $contents, $maxLength );
2675 // Remove possible unfinished links
2676 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2677 // Now replace the '$1' placeholder
2678 $reason = str_replace( '$1', $contents, $reason );
2679
2680 return $reason;
2681 }
2682
2683
2684 /**
2685 * UI entry point for page deletion
2686 */
2687 public function delete() {
2688 global $wgOut, $wgRequest;
2689
2690 $confirm = $wgRequest->wasPosted() &&
2691 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2692
2693 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2694 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2695
2696 $reason = $this->DeleteReasonList;
2697
2698 if ( $reason != 'other' && $this->DeleteReason != '' ) {
2699 // Entry from drop down menu + additional comment
2700 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2701 } elseif ( $reason == 'other' ) {
2702 $reason = $this->DeleteReason;
2703 }
2704
2705 # Flag to hide all contents of the archived revisions
2706 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2707
2708 # This code desperately needs to be totally rewritten
2709
2710 # Read-only check...
2711 if ( wfReadOnly() ) {
2712 $wgOut->readOnlyPage();
2713
2714 return;
2715 }
2716
2717 # Check permissions
2718 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2719
2720 if ( count( $permission_errors ) > 0 ) {
2721 $wgOut->showPermissionsErrorPage( $permission_errors );
2722
2723 return;
2724 }
2725
2726 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2727
2728 # Better double-check that it hasn't been deleted yet!
2729 $dbw = wfGetDB( DB_MASTER );
2730 $conds = $this->mTitle->pageCond();
2731 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2732 if ( $latest === false ) {
2733 $wgOut->showFatalError(
2734 Html::rawElement(
2735 'div',
2736 array( 'class' => 'error mw-error-cannotdelete' ),
2737 wfMsgExt( 'cannotdelete', array( 'parse' ),
2738 wfEscapeWikiText( $this->mTitle->getPrefixedText() ) )
2739 )
2740 );
2741 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2742 LogEventsList::showLogExtract(
2743 $wgOut,
2744 'delete',
2745 $this->mTitle->getPrefixedText()
2746 );
2747
2748 return;
2749 }
2750
2751 # Hack for big sites
2752 $bigHistory = $this->isBigDeletion();
2753 if ( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2754 global $wgLang, $wgDeleteRevisionsLimit;
2755
2756 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2757 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2758
2759 return;
2760 }
2761
2762 if ( $confirm ) {
2763 $this->doDelete( $reason, $suppress );
2764
2765 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2766 $this->doWatch();
2767 } elseif ( $this->mTitle->userIsWatching() ) {
2768 $this->doUnwatch();
2769 }
2770
2771 return;
2772 }
2773
2774 // Generate deletion reason
2775 $hasHistory = false;
2776 if ( !$reason ) {
2777 $reason = $this->generateReason( $hasHistory );
2778 }
2779
2780 // If the page has a history, insert a warning
2781 if ( $hasHistory && !$confirm ) {
2782 global $wgLang;
2783
2784 $revisions = $this->estimateRevisionCount();
2785 // @todo FIXME: i18n issue/patchwork message
2786 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2787 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2788 wfMsgHtml( 'word-separator' ) . Linker::link( $this->mTitle,
2789 wfMsgHtml( 'history' ),
2790 array( 'rel' => 'archives' ),
2791 array( 'action' => 'history' ) ) .
2792 '</strong>'
2793 );
2794
2795 if ( $bigHistory ) {
2796 global $wgDeleteRevisionsLimit;
2797 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2798 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2799 }
2800 }
2801
2802 return $this->confirmDelete( $reason );
2803 }
2804
2805 /**
2806 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2807 */
2808 public function isBigDeletion() {
2809 global $wgDeleteRevisionsLimit;
2810
2811 if ( $wgDeleteRevisionsLimit ) {
2812 $revCount = $this->estimateRevisionCount();
2813
2814 return $revCount > $wgDeleteRevisionsLimit;
2815 }
2816
2817 return false;
2818 }
2819
2820 /**
2821 * @return int approximate revision count
2822 */
2823 public function estimateRevisionCount() {
2824 $dbr = wfGetDB( DB_SLAVE );
2825
2826 // For an exact count...
2827 // return $dbr->selectField( 'revision', 'COUNT(*)',
2828 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2829 return $dbr->estimateRowCount( 'revision', '*',
2830 array( 'rev_page' => $this->getId() ), __METHOD__ );
2831 }
2832
2833 /**
2834 * Get the last N authors
2835 * @param $num Integer: number of revisions to get
2836 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2837 * @return array Array of authors, duplicates not removed
2838 */
2839 public function getLastNAuthors( $num, $revLatest = 0 ) {
2840 wfProfileIn( __METHOD__ );
2841 // First try the slave
2842 // If that doesn't have the latest revision, try the master
2843 $continue = 2;
2844 $db = wfGetDB( DB_SLAVE );
2845
2846 do {
2847 $res = $db->select( array( 'page', 'revision' ),
2848 array( 'rev_id', 'rev_user_text' ),
2849 array(
2850 'page_namespace' => $this->mTitle->getNamespace(),
2851 'page_title' => $this->mTitle->getDBkey(),
2852 'rev_page = page_id'
2853 ), __METHOD__,
2854 array(
2855 'ORDER BY' => 'rev_timestamp DESC',
2856 'LIMIT' => $num
2857 )
2858 );
2859
2860 if ( !$res ) {
2861 wfProfileOut( __METHOD__ );
2862 return array();
2863 }
2864
2865 $row = $db->fetchObject( $res );
2866
2867 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2868 $db = wfGetDB( DB_MASTER );
2869 $continue--;
2870 } else {
2871 $continue = 0;
2872 }
2873 } while ( $continue );
2874
2875 $authors = array( $row->rev_user_text );
2876
2877 foreach ( $res as $row ) {
2878 $authors[] = $row->rev_user_text;
2879 }
2880
2881 wfProfileOut( __METHOD__ );
2882 return $authors;
2883 }
2884
2885 /**
2886 * Output deletion confirmation dialog
2887 * @todo FIXME: Move to another file?
2888 * @param $reason String: prefilled reason
2889 */
2890 public function confirmDelete( $reason ) {
2891 global $wgOut;
2892
2893 wfDebug( "Article::confirmDelete\n" );
2894
2895 $deleteBackLink = Linker::linkKnown( $this->mTitle );
2896 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2897 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2898 $wgOut->addWikiMsg( 'confirmdeletetext' );
2899
2900 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2901
2902 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2903 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2904 <td></td>
2905 <td class='mw-input'><strong>" .
2906 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2907 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2908 "</strong></td>
2909 </tr>";
2910 } else {
2911 $suppress = '';
2912 }
2913 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2914
2915 $form = Xml::openElement( 'form', array( 'method' => 'post',
2916 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2917 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2918 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2919 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2920 "<tr id=\"wpDeleteReasonListRow\">
2921 <td class='mw-label'>" .
2922 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2923 "</td>
2924 <td class='mw-input'>" .
2925 Xml::listDropDown( 'wpDeleteReasonList',
2926 wfMsgForContent( 'deletereason-dropdown' ),
2927 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2928 "</td>
2929 </tr>
2930 <tr id=\"wpDeleteReasonRow\">
2931 <td class='mw-label'>" .
2932 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2933 "</td>
2934 <td class='mw-input'>" .
2935 Html::input( 'wpReason', $reason, 'text', array(
2936 'size' => '60',
2937 'maxlength' => '255',
2938 'tabindex' => '2',
2939 'id' => 'wpReason',
2940 'autofocus'
2941 ) ) .
2942 "</td>
2943 </tr>";
2944
2945 # Disallow watching if user is not logged in
2946 if ( $wgOut->getUser()->isLoggedIn() ) {
2947 $form .= "
2948 <tr>
2949 <td></td>
2950 <td class='mw-input'>" .
2951 Xml::checkLabel( wfMsg( 'watchthis' ),
2952 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2953 "</td>
2954 </tr>";
2955 }
2956
2957 $form .= "
2958 $suppress
2959 <tr>
2960 <td></td>
2961 <td class='mw-submit'>" .
2962 Xml::submitButton( wfMsg( 'deletepage' ),
2963 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2964 "</td>
2965 </tr>" .
2966 Xml::closeElement( 'table' ) .
2967 Xml::closeElement( 'fieldset' ) .
2968 Html::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
2969 Xml::closeElement( 'form' );
2970
2971 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
2972 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2973 $link = Linker::link(
2974 $title,
2975 wfMsgHtml( 'delete-edit-reasonlist' ),
2976 array(),
2977 array( 'action' => 'edit' )
2978 );
2979 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2980 }
2981
2982 $wgOut->addHTML( $form );
2983 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2984 LogEventsList::showLogExtract( $wgOut, 'delete',
2985 $this->mTitle->getPrefixedText()
2986 );
2987 }
2988
2989 /**
2990 * Perform a deletion and output success or failure messages
2991 */
2992 public function doDelete( $reason, $suppress = false ) {
2993 global $wgOut;
2994
2995 $id = $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
2996
2997 $error = '';
2998 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
2999 $deleted = $this->mTitle->getPrefixedText();
3000
3001 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3002 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3003
3004 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3005
3006 $wgOut->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
3007 $wgOut->returnToMain( false );
3008 } else {
3009 if ( $error == '' ) {
3010 $wgOut->showFatalError(
3011 Html::rawElement(
3012 'div',
3013 array( 'class' => 'error mw-error-cannotdelete' ),
3014 wfMsgExt( 'cannotdelete', array( 'parse' ),
3015 wfEscapeWikiText( $this->mTitle->getPrefixedText() ) )
3016 )
3017 );
3018
3019 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3020
3021 LogEventsList::showLogExtract(
3022 $wgOut,
3023 'delete',
3024 $this->mTitle->getPrefixedText()
3025 );
3026 } else {
3027 $wgOut->showFatalError( $error );
3028 }
3029 }
3030 }
3031
3032 /**
3033 * Back-end article deletion
3034 * Deletes the article with database consistency, writes logs, purges caches
3035 *
3036 * @param $reason string delete reason for deletion log
3037 * @param suppress bitfield
3038 * Revision::DELETED_TEXT
3039 * Revision::DELETED_COMMENT
3040 * Revision::DELETED_USER
3041 * Revision::DELETED_RESTRICTED
3042 * @param $id int article ID
3043 * @param $commit boolean defaults to true, triggers transaction end
3044 * @return boolean true if successful
3045 */
3046 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3047 global $wgDeferredUpdateList, $wgUseTrackbacks;
3048 global $wgUser;
3049
3050 wfDebug( __METHOD__ . "\n" );
3051
3052 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3053 return false;
3054 }
3055 $dbw = wfGetDB( DB_MASTER );
3056 $t = $this->mTitle->getDBkey();
3057 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
3058
3059 if ( $t === '' || $id == 0 ) {
3060 return false;
3061 }
3062
3063 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
3064 array_push( $wgDeferredUpdateList, $u );
3065
3066 // Bitfields to further suppress the content
3067 if ( $suppress ) {
3068 $bitfield = 0;
3069 // This should be 15...
3070 $bitfield |= Revision::DELETED_TEXT;
3071 $bitfield |= Revision::DELETED_COMMENT;
3072 $bitfield |= Revision::DELETED_USER;
3073 $bitfield |= Revision::DELETED_RESTRICTED;
3074 } else {
3075 $bitfield = 'rev_deleted';
3076 }
3077
3078 $dbw->begin();
3079 // For now, shunt the revision data into the archive table.
3080 // Text is *not* removed from the text table; bulk storage
3081 // is left intact to avoid breaking block-compression or
3082 // immutable storage schemes.
3083 //
3084 // For backwards compatibility, note that some older archive
3085 // table entries will have ar_text and ar_flags fields still.
3086 //
3087 // In the future, we may keep revisions and mark them with
3088 // the rev_deleted field, which is reserved for this purpose.
3089 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3090 array(
3091 'ar_namespace' => 'page_namespace',
3092 'ar_title' => 'page_title',
3093 'ar_comment' => 'rev_comment',
3094 'ar_user' => 'rev_user',
3095 'ar_user_text' => 'rev_user_text',
3096 'ar_timestamp' => 'rev_timestamp',
3097 'ar_minor_edit' => 'rev_minor_edit',
3098 'ar_rev_id' => 'rev_id',
3099 'ar_text_id' => 'rev_text_id',
3100 'ar_text' => '\'\'', // Be explicit to appease
3101 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3102 'ar_len' => 'rev_len',
3103 'ar_page_id' => 'page_id',
3104 'ar_deleted' => $bitfield
3105 ), array(
3106 'page_id' => $id,
3107 'page_id = rev_page'
3108 ), __METHOD__
3109 );
3110
3111 # Delete restrictions for it
3112 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
3113
3114 # Now that it's safely backed up, delete it
3115 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
3116 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3117
3118 if ( !$ok ) {
3119 $dbw->rollback();
3120 return false;
3121 }
3122
3123 # Fix category table counts
3124 $cats = array();
3125 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
3126
3127 foreach ( $res as $row ) {
3128 $cats [] = $row->cl_to;
3129 }
3130
3131 $this->updateCategoryCounts( array(), $cats );
3132
3133 # If using cascading deletes, we can skip some explicit deletes
3134 if ( !$dbw->cascadingDeletes() ) {
3135 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
3136
3137 if ( $wgUseTrackbacks )
3138 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
3139
3140 # Delete outgoing links
3141 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3142 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3143 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3144 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3145 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3146 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3147 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3148 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3149 }
3150
3151 # If using cleanup triggers, we can skip some manual deletes
3152 if ( !$dbw->cleanupTriggers() ) {
3153 # Clean up recentchanges entries...
3154 $dbw->delete( 'recentchanges',
3155 array( 'rc_type != ' . RC_LOG,
3156 'rc_namespace' => $this->mTitle->getNamespace(),
3157 'rc_title' => $this->mTitle->getDBkey() ),
3158 __METHOD__ );
3159 $dbw->delete( 'recentchanges',
3160 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
3161 __METHOD__ );
3162 }
3163
3164 # Clear caches
3165 Article::onArticleDelete( $this->mTitle );
3166
3167 # Clear the cached article id so the interface doesn't act like we exist
3168 $this->mTitle->resetArticleID( 0 );
3169
3170 # Log the deletion, if the page was suppressed, log it at Oversight instead
3171 $logtype = $suppress ? 'suppress' : 'delete';
3172 $log = new LogPage( $logtype );
3173
3174 # Make sure logging got through
3175 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
3176
3177 if ( $commit ) {
3178 $dbw->commit();
3179 }
3180
3181 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3182 return true;
3183 }
3184
3185 /**
3186 * Roll back the most recent consecutive set of edits to a page
3187 * from the same user; fails if there are no eligible edits to
3188 * roll back to, e.g. user is the sole contributor. This function
3189 * performs permissions checks on $wgUser, then calls commitRollback()
3190 * to do the dirty work
3191 *
3192 * @param $fromP String: Name of the user whose edits to rollback.
3193 * @param $summary String: Custom summary. Set to default summary if empty.
3194 * @param $token String: Rollback token.
3195 * @param $bot Boolean: If true, mark all reverted edits as bot.
3196 *
3197 * @param $resultDetails Array: contains result-specific array of additional values
3198 * 'alreadyrolled' : 'current' (rev)
3199 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3200 *
3201 * @return array of errors, each error formatted as
3202 * array(messagekey, param1, param2, ...).
3203 * On success, the array is empty. This array can also be passed to
3204 * OutputPage::showPermissionsErrorPage().
3205 */
3206 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3207 global $wgUser;
3208
3209 $resultDetails = null;
3210
3211 # Check permissions
3212 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
3213 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
3214 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3215
3216 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
3217 $errors[] = array( 'sessionfailure' );
3218 }
3219
3220 if ( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
3221 $errors[] = array( 'actionthrottledtext' );
3222 }
3223
3224 # If there were errors, bail out now
3225 if ( !empty( $errors ) ) {
3226 return $errors;
3227 }
3228
3229 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3230 }
3231
3232 /**
3233 * Backend implementation of doRollback(), please refer there for parameter
3234 * and return value documentation
3235 *
3236 * NOTE: This function does NOT check ANY permissions, it just commits the
3237 * rollback to the DB Therefore, you should only call this function direct-
3238 * ly if you want to use custom permissions checks. If you don't, use
3239 * doRollback() instead.
3240 */
3241 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3242 global $wgUseRCPatrol, $wgUser, $wgLang;
3243
3244 $dbw = wfGetDB( DB_MASTER );
3245
3246 if ( wfReadOnly() ) {
3247 return array( array( 'readonlytext' ) );
3248 }
3249
3250 # Get the last editor
3251 $current = Revision::newFromTitle( $this->mTitle );
3252 if ( is_null( $current ) ) {
3253 # Something wrong... no page?
3254 return array( array( 'notanarticle' ) );
3255 }
3256
3257 $from = str_replace( '_', ' ', $fromP );
3258 # User name given should match up with the top revision.
3259 # If the user was deleted then $from should be empty.
3260 if ( $from != $current->getUserText() ) {
3261 $resultDetails = array( 'current' => $current );
3262 return array( array( 'alreadyrolled',
3263 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3264 htmlspecialchars( $fromP ),
3265 htmlspecialchars( $current->getUserText() )
3266 ) );
3267 }
3268
3269 # Get the last edit not by this guy...
3270 # Note: these may not be public values
3271 $user = intval( $current->getRawUser() );
3272 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3273 $s = $dbw->selectRow( 'revision',
3274 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3275 array( 'rev_page' => $current->getPage(),
3276 "rev_user != {$user} OR rev_user_text != {$user_text}"
3277 ), __METHOD__,
3278 array( 'USE INDEX' => 'page_timestamp',
3279 'ORDER BY' => 'rev_timestamp DESC' )
3280 );
3281 if ( $s === false ) {
3282 # No one else ever edited this page
3283 return array( array( 'cantrollback' ) );
3284 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
3285 # Only admins can see this text
3286 return array( array( 'notvisiblerev' ) );
3287 }
3288
3289 $set = array();
3290 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3291 # Mark all reverted edits as bot
3292 $set['rc_bot'] = 1;
3293 }
3294
3295 if ( $wgUseRCPatrol ) {
3296 # Mark all reverted edits as patrolled
3297 $set['rc_patrolled'] = 1;
3298 }
3299
3300 if ( count( $set ) ) {
3301 $dbw->update( 'recentchanges', $set,
3302 array( /* WHERE */
3303 'rc_cur_id' => $current->getPage(),
3304 'rc_user_text' => $current->getUserText(),
3305 "rc_timestamp > '{$s->rev_timestamp}'",
3306 ), __METHOD__
3307 );
3308 }
3309
3310 # Generate the edit summary if necessary
3311 $target = Revision::newFromId( $s->rev_id );
3312 if ( empty( $summary ) ) {
3313 if ( $from == '' ) { // no public user name
3314 $summary = wfMsgForContent( 'revertpage-nouser' );
3315 } else {
3316 $summary = wfMsgForContent( 'revertpage' );
3317 }
3318 }
3319
3320 # Allow the custom summary to use the same args as the default message
3321 $args = array(
3322 $target->getUserText(), $from, $s->rev_id,
3323 $wgLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ), true ),
3324 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3325 );
3326 $summary = wfMsgReplaceArgs( $summary, $args );
3327
3328 # Save
3329 $flags = EDIT_UPDATE;
3330
3331 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3332 $flags |= EDIT_MINOR;
3333 }
3334
3335 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3336 $flags |= EDIT_FORCE_BOT;
3337 }
3338
3339 # Actually store the edit
3340 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3341 if ( !empty( $status->value['revision'] ) ) {
3342 $revId = $status->value['revision']->getId();
3343 } else {
3344 $revId = false;
3345 }
3346
3347 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3348
3349 $resultDetails = array(
3350 'summary' => $summary,
3351 'current' => $current,
3352 'target' => $target,
3353 'newid' => $revId
3354 );
3355
3356 return array();
3357 }
3358
3359 /**
3360 * User interface for rollback operations
3361 */
3362 public function rollback() {
3363 global $wgUser, $wgOut, $wgRequest;
3364
3365 $details = null;
3366
3367 $result = $this->doRollback(
3368 $wgRequest->getVal( 'from' ),
3369 $wgRequest->getText( 'summary' ),
3370 $wgRequest->getVal( 'token' ),
3371 $wgRequest->getBool( 'bot' ),
3372 $details
3373 );
3374
3375 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3376 $wgOut->rateLimited();
3377 return;
3378 }
3379
3380 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3381 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3382 $errArray = $result[0];
3383 $errMsg = array_shift( $errArray );
3384 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3385
3386 if ( isset( $details['current'] ) ) {
3387 $current = $details['current'];
3388
3389 if ( $current->getComment() != '' ) {
3390 $wgOut->addWikiMsgArray( 'editcomment', array(
3391 Linker::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3392 }
3393 }
3394
3395 return;
3396 }
3397
3398 # Display permissions errors before read-only message -- there's no
3399 # point in misleading the user into thinking the inability to rollback
3400 # is only temporary.
3401 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3402 # array_diff is completely broken for arrays of arrays, sigh.
3403 # Remove any 'readonlytext' error manually.
3404 $out = array();
3405 foreach ( $result as $error ) {
3406 if ( $error != array( 'readonlytext' ) ) {
3407 $out [] = $error;
3408 }
3409 }
3410 $wgOut->showPermissionsErrorPage( $out );
3411
3412 return;
3413 }
3414
3415 if ( $result == array( array( 'readonlytext' ) ) ) {
3416 $wgOut->readOnlyPage();
3417
3418 return;
3419 }
3420
3421 $current = $details['current'];
3422 $target = $details['target'];
3423 $newId = $details['newid'];
3424 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3425 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3426
3427 if ( $current->getUserText() === '' ) {
3428 $old = wfMsg( 'rev-deleted-user' );
3429 } else {
3430 $old = Linker::userLink( $current->getUser(), $current->getUserText() )
3431 . Linker::userToolLinks( $current->getUser(), $current->getUserText() );
3432 }
3433
3434 $new = Linker::userLink( $target->getUser(), $target->getUserText() )
3435 . Linker::userToolLinks( $target->getUser(), $target->getUserText() );
3436 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3437 $wgOut->returnToMain( false, $this->mTitle );
3438
3439 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3440 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3441 $de->showDiff( '', '' );
3442 }
3443 }
3444
3445 /**
3446 * Do standard deferred updates after page view
3447 */
3448 public function viewUpdates() {
3449 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3450 if ( wfReadOnly() ) {
3451 return;
3452 }
3453
3454 # Don't update page view counters on views from bot users (bug 14044)
3455 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3456 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3457 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3458 }
3459
3460 # Update newtalk / watchlist notification status
3461 $wgUser->clearNotification( $this->mTitle );
3462 }
3463
3464 /**
3465 * Prepare text which is about to be saved.
3466 * Returns a stdclass with source, pst and output members
3467 */
3468 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
3469 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid ) {
3470 // Already prepared
3471 return $this->mPreparedEdit;
3472 }
3473
3474 global $wgParser;
3475
3476 if( $user === null ) {
3477 global $wgUser;
3478 $user = $wgUser;
3479 }
3480 $popts = ParserOptions::newFromUser( $user );
3481 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3482
3483 $edit = (object)array();
3484 $edit->revid = $revid;
3485 $edit->newText = $text;
3486 $edit->pst = $this->preSaveTransform( $text, $user, $popts );
3487 $edit->popts = $this->getParserOptions( true );
3488 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
3489 $edit->oldText = $this->getRawText();
3490
3491 $this->mPreparedEdit = $edit;
3492
3493 return $edit;
3494 }
3495
3496 /**
3497 * Do standard deferred updates after page edit.
3498 * Update links tables, site stats, search index and message cache.
3499 * Purges pages that include this page if the text was changed here.
3500 * Every 100th edit, prune the recent changes table.
3501 *
3502 * @private
3503 * @param $text String: New text of the article
3504 * @param $summary String: Edit summary
3505 * @param $minoredit Boolean: Minor edit
3506 * @param $timestamp_of_pagechange String timestamp associated with the page change
3507 * @param $newid Integer: rev_id value of the new revision
3508 * @param $changed Boolean: Whether or not the content actually changed
3509 * @param $user User object: User doing the edit
3510 * @param $created Boolean: Whether the edit created the page
3511 */
3512 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
3513 $changed = true, User $user = null, $created = false )
3514 {
3515 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3516
3517 wfProfileIn( __METHOD__ );
3518
3519 # Parse the text
3520 # Be careful not to double-PST: $text is usually already PST-ed once
3521 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3522 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3523 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3524 } else {
3525 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3526 $editInfo = $this->mPreparedEdit;
3527 }
3528
3529 # Save it to the parser cache
3530 if ( $wgEnableParserCache ) {
3531 $parserCache = ParserCache::singleton();
3532 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
3533 }
3534
3535 # Update the links tables
3536 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3537 $u->doUpdate();
3538
3539 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3540
3541 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3542 if ( 0 == mt_rand( 0, 99 ) ) {
3543 // Flush old entries from the `recentchanges` table; we do this on
3544 // random requests so as to avoid an increase in writes for no good reason
3545 global $wgRCMaxAge;
3546
3547 $dbw = wfGetDB( DB_MASTER );
3548 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3549 $dbw->delete(
3550 'recentchanges',
3551 array( "rc_timestamp < '$cutoff'" ),
3552 __METHOD__
3553 );
3554 }
3555 }
3556
3557 $id = $this->getID();
3558 $title = $this->mTitle->getPrefixedDBkey();
3559 $shortTitle = $this->mTitle->getDBkey();
3560
3561 if ( 0 == $id ) {
3562 wfProfileOut( __METHOD__ );
3563 return;
3564 }
3565
3566 if ( !$changed ) {
3567 $good = 0;
3568 $total = 0;
3569 } elseif ( $created ) {
3570 $good = (int)$this->isCountable( $editInfo );
3571 $total = 1;
3572 } else {
3573 $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
3574 $total = 0;
3575 }
3576
3577 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
3578 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
3579
3580 # If this is another user's talk page, update newtalk
3581 # Don't do this if $changed = false otherwise some idiot can null-edit a
3582 # load of user talk pages and piss people off, nor if it's a minor edit
3583 # by a properly-flagged bot.
3584 if ( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3585 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3586 ) {
3587 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3588 $other = User::newFromName( $shortTitle, false );
3589 if ( !$other ) {
3590 wfDebug( __METHOD__ . ": invalid username\n" );
3591 } elseif ( User::isIP( $shortTitle ) ) {
3592 // An anonymous user
3593 $other->setNewtalk( true );
3594 } elseif ( $other->isLoggedIn() ) {
3595 $other->setNewtalk( true );
3596 } else {
3597 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
3598 }
3599 }
3600 }
3601
3602 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3603 MessageCache::singleton()->replace( $shortTitle, $text );
3604 }
3605
3606 wfProfileOut( __METHOD__ );
3607 }
3608
3609 /**
3610 * Perform article updates on a special page creation.
3611 *
3612 * @param $rev Revision object
3613 *
3614 * @todo This is a shitty interface function. Kill it and replace the
3615 * other shitty functions like editUpdates and such so it's not needed
3616 * anymore.
3617 */
3618 public function createUpdates( $rev ) {
3619 $this->editUpdates( $rev->getText(), $rev->getComment(),
3620 $rev->isMinor(), wfTimestamp(), $rev->getId(), true, null, true );
3621 }
3622
3623 /**
3624 * Generate the navigation links when browsing through an article revisions
3625 * It shows the information as:
3626 * Revision as of \<date\>; view current revision
3627 * \<- Previous version | Next Version -\>
3628 *
3629 * @param $oldid String: revision ID of this article revision
3630 */
3631 public function setOldSubtitle( $oldid = 0 ) {
3632 global $wgLang, $wgOut, $wgUser, $wgRequest;
3633
3634 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3635 return;
3636 }
3637
3638 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3639
3640 # Cascade unhide param in links for easy deletion browsing
3641 $extraParams = array();
3642 if ( $wgRequest->getVal( 'unhide' ) ) {
3643 $extraParams['unhide'] = 1;
3644 }
3645
3646 $revision = Revision::newFromId( $oldid );
3647 $timestamp = $revision->getTimestamp();
3648
3649 $current = ( $oldid == $this->mLatest );
3650 $td = $wgLang->timeanddate( $timestamp, true );
3651 $tddate = $wgLang->date( $timestamp, true );
3652 $tdtime = $wgLang->time( $timestamp, true );
3653
3654 $lnk = $current
3655 ? wfMsgHtml( 'currentrevisionlink' )
3656 : Linker::link(
3657 $this->mTitle,
3658 wfMsgHtml( 'currentrevisionlink' ),
3659 array(),
3660 $extraParams,
3661 array( 'known', 'noclasses' )
3662 );
3663 $curdiff = $current
3664 ? wfMsgHtml( 'diff' )
3665 : Linker::link(
3666 $this->mTitle,
3667 wfMsgHtml( 'diff' ),
3668 array(),
3669 array(
3670 'diff' => 'cur',
3671 'oldid' => $oldid
3672 ) + $extraParams,
3673 array( 'known', 'noclasses' )
3674 );
3675 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3676 $prevlink = $prev
3677 ? Linker::link(
3678 $this->mTitle,
3679 wfMsgHtml( 'previousrevision' ),
3680 array(),
3681 array(
3682 'direction' => 'prev',
3683 'oldid' => $oldid
3684 ) + $extraParams,
3685 array( 'known', 'noclasses' )
3686 )
3687 : wfMsgHtml( 'previousrevision' );
3688 $prevdiff = $prev
3689 ? Linker::link(
3690 $this->mTitle,
3691 wfMsgHtml( 'diff' ),
3692 array(),
3693 array(
3694 'diff' => 'prev',
3695 'oldid' => $oldid
3696 ) + $extraParams,
3697 array( 'known', 'noclasses' )
3698 )
3699 : wfMsgHtml( 'diff' );
3700 $nextlink = $current
3701 ? wfMsgHtml( 'nextrevision' )
3702 : Linker::link(
3703 $this->mTitle,
3704 wfMsgHtml( 'nextrevision' ),
3705 array(),
3706 array(
3707 'direction' => 'next',
3708 'oldid' => $oldid
3709 ) + $extraParams,
3710 array( 'known', 'noclasses' )
3711 );
3712 $nextdiff = $current
3713 ? wfMsgHtml( 'diff' )
3714 : Linker::link(
3715 $this->mTitle,
3716 wfMsgHtml( 'diff' ),
3717 array(),
3718 array(
3719 'diff' => 'next',
3720 'oldid' => $oldid
3721 ) + $extraParams,
3722 array( 'known', 'noclasses' )
3723 );
3724
3725 $cdel = '';
3726
3727 // User can delete revisions or view deleted revisions...
3728 $canHide = $wgUser->isAllowed( 'deleterevision' );
3729 if ( $canHide || ( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3730 if ( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3731 $cdel = Linker::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3732 } else {
3733 $query = array(
3734 'type' => 'revision',
3735 'target' => $this->mTitle->getPrefixedDbkey(),
3736 'ids' => $oldid
3737 );
3738 $cdel = Linker::revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
3739 }
3740 $cdel .= ' ';
3741 }
3742
3743 # Show user links if allowed to see them. If hidden, then show them only if requested...
3744 $userlinks = Linker::revUserTools( $revision, !$unhide );
3745
3746 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3747 ? 'revision-info-current'
3748 : 'revision-info';
3749
3750 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3751 wfMsgExt(
3752 $infomsg,
3753 array( 'parseinline', 'replaceafter' ),
3754 $td,
3755 $userlinks,
3756 $revision->getID(),
3757 $tddate,
3758 $tdtime,
3759 $revision->getUser()
3760 ) .
3761 "</div>\n" .
3762 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3763 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3764
3765 $wgOut->addHTML( $r );
3766 }
3767
3768 /**
3769 * This function is called right before saving the wikitext,
3770 * so we can do things like signatures and links-in-context.
3771 *
3772 * @param $text String article contents
3773 * @param $user User object: user doing the edit, $wgUser will be used if
3774 * null is given
3775 * @param $popts ParserOptions object: parser options, default options for
3776 * the user loaded if null given
3777 * @return string article contents with altered wikitext markup (signatures
3778 * converted, {{subst:}}, templates, etc.)
3779 */
3780 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3781 global $wgParser;
3782
3783 if ( $user === null ) {
3784 global $wgUser;
3785 $user = $wgUser;
3786 }
3787
3788 if ( $popts === null ) {
3789 $popts = ParserOptions::newFromUser( $user );
3790 }
3791
3792 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3793 }
3794
3795 /* Caching functions */
3796
3797 /**
3798 * checkLastModified returns true if it has taken care of all
3799 * output to the client that is necessary for this request.
3800 * (that is, it has sent a cached version of the page)
3801 *
3802 * @return boolean true if cached version send, false otherwise
3803 */
3804 protected function tryFileCache() {
3805 static $called = false;
3806
3807 if ( $called ) {
3808 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3809 return false;
3810 }
3811
3812 $called = true;
3813 if ( $this->isFileCacheable() ) {
3814 $cache = new HTMLFileCache( $this->mTitle );
3815 if ( $cache->isFileCacheGood( $this->mTouched ) ) {
3816 wfDebug( "Article::tryFileCache(): about to load file\n" );
3817 $cache->loadFromFileCache();
3818 return true;
3819 } else {
3820 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3821 ob_start( array( &$cache, 'saveToFileCache' ) );
3822 }
3823 } else {
3824 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3825 }
3826
3827 return false;
3828 }
3829
3830 /**
3831 * Check if the page can be cached
3832 * @return bool
3833 */
3834 public function isFileCacheable() {
3835 $cacheable = false;
3836
3837 if ( HTMLFileCache::useFileCache() ) {
3838 $cacheable = $this->getID() && !$this->mRedirectedFrom && !$this->mTitle->isRedirect();
3839 // Extension may have reason to disable file caching on some pages.
3840 if ( $cacheable ) {
3841 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3842 }
3843 }
3844
3845 return $cacheable;
3846 }
3847
3848 /**
3849 * Loads page_touched and returns a value indicating if it should be used
3850 * @return boolean true if not a redirect
3851 */
3852 public function checkTouched() {
3853 if ( !$this->mDataLoaded ) {
3854 $this->loadPageData();
3855 }
3856
3857 return !$this->mIsRedirect;
3858 }
3859
3860 /**
3861 * Get the page_touched field
3862 * @return string containing GMT timestamp
3863 */
3864 public function getTouched() {
3865 if ( !$this->mDataLoaded ) {
3866 $this->loadPageData();
3867 }
3868
3869 return $this->mTouched;
3870 }
3871
3872 /**
3873 * Get the page_latest field
3874 * @return integer rev_id of current revision
3875 */
3876 public function getLatest() {
3877 if ( !$this->mDataLoaded ) {
3878 $this->loadPageData();
3879 }
3880
3881 return (int)$this->mLatest;
3882 }
3883
3884 /**
3885 * Edit an article without doing all that other stuff
3886 * The article must already exist; link tables etc
3887 * are not updated, caches are not flushed.
3888 *
3889 * @param $text String: text submitted
3890 * @param $comment String: comment submitted
3891 * @param $minor Boolean: whereas it's a minor modification
3892 */
3893 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3894 wfProfileIn( __METHOD__ );
3895
3896 $dbw = wfGetDB( DB_MASTER );
3897 $revision = new Revision( array(
3898 'page' => $this->getId(),
3899 'text' => $text,
3900 'comment' => $comment,
3901 'minor_edit' => $minor ? 1 : 0,
3902 ) );
3903 $revision->insertOn( $dbw );
3904 $this->updateRevisionOn( $dbw, $revision );
3905
3906 global $wgUser;
3907 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3908
3909 wfProfileOut( __METHOD__ );
3910 }
3911
3912 /**
3913 * The onArticle*() functions are supposed to be a kind of hooks
3914 * which should be called whenever any of the specified actions
3915 * are done.
3916 *
3917 * This is a good place to put code to clear caches, for instance.
3918 *
3919 * This is called on page move and undelete, as well as edit
3920 *
3921 * @param $title Title object
3922 */
3923 public static function onArticleCreate( $title ) {
3924 # Update existence markers on article/talk tabs...
3925 if ( $title->isTalkPage() ) {
3926 $other = $title->getSubjectPage();
3927 } else {
3928 $other = $title->getTalkPage();
3929 }
3930
3931 $other->invalidateCache();
3932 $other->purgeSquid();
3933
3934 $title->touchLinks();
3935 $title->purgeSquid();
3936 $title->deleteTitleProtection();
3937 }
3938
3939 /**
3940 * Clears caches when article is deleted
3941 *
3942 * @param $title Title
3943 */
3944 public static function onArticleDelete( $title ) {
3945 # Update existence markers on article/talk tabs...
3946 if ( $title->isTalkPage() ) {
3947 $other = $title->getSubjectPage();
3948 } else {
3949 $other = $title->getTalkPage();
3950 }
3951
3952 $other->invalidateCache();
3953 $other->purgeSquid();
3954
3955 $title->touchLinks();
3956 $title->purgeSquid();
3957
3958 # File cache
3959 HTMLFileCache::clearFileCache( $title );
3960
3961 # Messages
3962 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3963 MessageCache::singleton()->replace( $title->getDBkey(), false );
3964 }
3965
3966 # Images
3967 if ( $title->getNamespace() == NS_FILE ) {
3968 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3969 $update->doUpdate();
3970 }
3971
3972 # User talk pages
3973 if ( $title->getNamespace() == NS_USER_TALK ) {
3974 $user = User::newFromName( $title->getText(), false );
3975 $user->setNewtalk( false );
3976 }
3977
3978 # Image redirects
3979 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3980 }
3981
3982 /**
3983 * Purge caches on page update etc
3984 *
3985 * @param $title Title object
3986 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3987 */
3988 public static function onArticleEdit( $title ) {
3989 global $wgDeferredUpdateList;
3990
3991 // Invalidate caches of articles which include this page
3992 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3993
3994 // Invalidate the caches of all pages which redirect here
3995 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3996
3997 # Purge squid for this page only
3998 $title->purgeSquid();
3999
4000 # Clear file cache for this page only
4001 HTMLFileCache::clearFileCache( $title );
4002 }
4003
4004 /**#@-*/
4005
4006 /**
4007 * Overriden by ImagePage class, only present here to avoid a fatal error
4008 * Called for ?action=revert
4009 */
4010 public function revert() {
4011 global $wgOut;
4012 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4013 }
4014
4015 /**
4016 * Return a list of templates used by this article.
4017 * Uses the templatelinks table
4018 *
4019 * @return Array of Title objects
4020 */
4021 public function getUsedTemplates() {
4022 $result = array();
4023 $id = $this->mTitle->getArticleID();
4024
4025 if ( $id == 0 ) {
4026 return array();
4027 }
4028
4029 $dbr = wfGetDB( DB_SLAVE );
4030 $res = $dbr->select( array( 'templatelinks' ),
4031 array( 'tl_namespace', 'tl_title' ),
4032 array( 'tl_from' => $id ),
4033 __METHOD__ );
4034
4035 if ( $res !== false ) {
4036 foreach ( $res as $row ) {
4037 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
4038 }
4039 }
4040
4041 return $result;
4042 }
4043
4044 /**
4045 * Returns a list of hidden categories this page is a member of.
4046 * Uses the page_props and categorylinks tables.
4047 *
4048 * @return Array of Title objects
4049 */
4050 public function getHiddenCategories() {
4051 $result = array();
4052 $id = $this->mTitle->getArticleID();
4053
4054 if ( $id == 0 ) {
4055 return array();
4056 }
4057
4058 $dbr = wfGetDB( DB_SLAVE );
4059 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4060 array( 'cl_to' ),
4061 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4062 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
4063 __METHOD__ );
4064
4065 if ( $res !== false ) {
4066 foreach ( $res as $row ) {
4067 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
4068 }
4069 }
4070
4071 return $result;
4072 }
4073
4074 /**
4075 * Return an applicable autosummary if one exists for the given edit.
4076 * @param $oldtext String: the previous text of the page.
4077 * @param $newtext String: The submitted text of the page.
4078 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4079 * @return string An appropriate autosummary, or an empty string.
4080 */
4081 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4082 global $wgContLang;
4083
4084 # Decide what kind of autosummary is needed.
4085
4086 # Redirect autosummaries
4087 $ot = Title::newFromRedirect( $oldtext );
4088 $rt = Title::newFromRedirect( $newtext );
4089
4090 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
4091 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4092 }
4093
4094 # New page autosummaries
4095 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
4096 # If they're making a new article, give its text, truncated, in the summary.
4097
4098 $truncatedtext = $wgContLang->truncate(
4099 str_replace( "\n", ' ', $newtext ),
4100 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4101
4102 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4103 }
4104
4105 # Blanking autosummaries
4106 if ( $oldtext != '' && $newtext == '' ) {
4107 return wfMsgForContent( 'autosumm-blank' );
4108 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4109 # Removing more than 90% of the article
4110
4111 $truncatedtext = $wgContLang->truncate(
4112 $newtext,
4113 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4114
4115 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4116 }
4117
4118 # If we reach this point, there's no applicable autosummary for our case, so our
4119 # autosummary is empty.
4120 return '';
4121 }
4122
4123 /**
4124 * Add the primary page-view wikitext to the output buffer
4125 * Saves the text into the parser cache if possible.
4126 * Updates templatelinks if it is out of date.
4127 *
4128 * @param $text String
4129 * @param $cache Boolean
4130 * @param $parserOptions mixed ParserOptions object, or boolean false
4131 */
4132 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4133 global $wgOut;
4134
4135 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4136 $wgOut->addParserOutput( $this->mParserOutput );
4137 }
4138
4139 /**
4140 * This does all the heavy lifting for outputWikitext, except it returns the parser
4141 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4142 * say, embedding thread pages within a discussion system (LiquidThreads)
4143 *
4144 * @param $text string
4145 * @param $cache boolean
4146 * @param $parserOptions parsing options, defaults to false
4147 * @return string containing parsed output
4148 */
4149 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4150 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4151
4152 if ( !$parserOptions ) {
4153 $parserOptions = $this->getParserOptions();
4154 }
4155
4156 $time = - wfTime();
4157 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
4158 $parserOptions, true, true, $this->getRevIdFetched() );
4159 $time += wfTime();
4160
4161 # Timing hack
4162 if ( $time > 3 ) {
4163 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4164 $this->mTitle->getPrefixedDBkey() ) );
4165 }
4166
4167 if ( $wgEnableParserCache && $cache && $this->mParserOutput->isCacheable() ) {
4168 $parserCache = ParserCache::singleton();
4169 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
4170 }
4171
4172 // Make sure file cache is not used on uncacheable content.
4173 // Output that has magic words in it can still use the parser cache
4174 // (if enabled), though it will generally expire sooner.
4175 if ( !$this->mParserOutput->isCacheable() || $this->mParserOutput->containsOldMagic() ) {
4176 $wgUseFileCache = false;
4177 }
4178
4179 $this->doCascadeProtectionUpdates( $this->mParserOutput );
4180
4181 return $this->mParserOutput;
4182 }
4183
4184 /**
4185 * Get parser options suitable for rendering the primary article wikitext
4186 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
4187 * @return mixed ParserOptions object or boolean false
4188 */
4189 public function getParserOptions( $canonical = false ) {
4190 global $wgUser, $wgLanguageCode;
4191
4192 if ( !$this->mParserOptions || $canonical ) {
4193 $user = !$canonical ? $wgUser : new User;
4194 $parserOptions = new ParserOptions( $user );
4195 $parserOptions->setTidy( true );
4196 $parserOptions->enableLimitReport();
4197
4198 if ( $canonical ) {
4199 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
4200 return $parserOptions;
4201 }
4202 $this->mParserOptions = $parserOptions;
4203 }
4204 // Clone to allow modifications of the return value without affecting cache
4205 return clone $this->mParserOptions;
4206 }
4207
4208 /**
4209 * Get parser options suitable for rendering the primary article wikitext
4210 * @param User $user
4211 * @return ParserOptions
4212 */
4213 public function makeParserOptions( User $user ) {
4214 $options = ParserOptions::newFromUser( $user );
4215 $options->enableLimitReport(); // show inclusion/loop reports
4216 $options->setTidy( true ); // fix bad HTML
4217 return $options;
4218 }
4219
4220 /**
4221 * Updates cascading protections
4222 *
4223 * @param $parserOutput ParserOutput object, or boolean false
4224 **/
4225 protected function doCascadeProtectionUpdates( $parserOutput ) {
4226 if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4227 return;
4228 }
4229
4230 // templatelinks table may have become out of sync,
4231 // especially if using variable-based transclusions.
4232 // For paranoia, check if things have changed and if
4233 // so apply updates to the database. This will ensure
4234 // that cascaded protections apply as soon as the changes
4235 // are visible.
4236
4237 # Get templates from templatelinks
4238 $id = $this->mTitle->getArticleID();
4239
4240 $tlTemplates = array();
4241
4242 $dbr = wfGetDB( DB_SLAVE );
4243 $res = $dbr->select( array( 'templatelinks' ),
4244 array( 'tl_namespace', 'tl_title' ),
4245 array( 'tl_from' => $id ),
4246 __METHOD__
4247 );
4248
4249 foreach ( $res as $row ) {
4250 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4251 }
4252
4253 # Get templates from parser output.
4254 $poTemplates = array();
4255 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4256 foreach ( $templates as $dbk => $id ) {
4257 $poTemplates["$ns:$dbk"] = true;
4258 }
4259 }
4260
4261 # Get the diff
4262 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4263
4264 if ( count( $templates_diff ) > 0 ) {
4265 # Whee, link updates time.
4266 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4267 $u->doUpdate();
4268 }
4269 }
4270
4271 /**
4272 * Update all the appropriate counts in the category table, given that
4273 * we've added the categories $added and deleted the categories $deleted.
4274 *
4275 * @param $added array The names of categories that were added
4276 * @param $deleted array The names of categories that were deleted
4277 */
4278 public function updateCategoryCounts( $added, $deleted ) {
4279 $ns = $this->mTitle->getNamespace();
4280 $dbw = wfGetDB( DB_MASTER );
4281
4282 # First make sure the rows exist. If one of the "deleted" ones didn't
4283 # exist, we might legitimately not create it, but it's simpler to just
4284 # create it and then give it a negative value, since the value is bogus
4285 # anyway.
4286 #
4287 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4288 $insertCats = array_merge( $added, $deleted );
4289 if ( !$insertCats ) {
4290 # Okay, nothing to do
4291 return;
4292 }
4293
4294 $insertRows = array();
4295
4296 foreach ( $insertCats as $cat ) {
4297 $insertRows[] = array(
4298 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4299 'cat_title' => $cat
4300 );
4301 }
4302 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4303
4304 $addFields = array( 'cat_pages = cat_pages + 1' );
4305 $removeFields = array( 'cat_pages = cat_pages - 1' );
4306
4307 if ( $ns == NS_CATEGORY ) {
4308 $addFields[] = 'cat_subcats = cat_subcats + 1';
4309 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4310 } elseif ( $ns == NS_FILE ) {
4311 $addFields[] = 'cat_files = cat_files + 1';
4312 $removeFields[] = 'cat_files = cat_files - 1';
4313 }
4314
4315 if ( $added ) {
4316 $dbw->update(
4317 'category',
4318 $addFields,
4319 array( 'cat_title' => $added ),
4320 __METHOD__
4321 );
4322 }
4323
4324 if ( $deleted ) {
4325 $dbw->update(
4326 'category',
4327 $removeFields,
4328 array( 'cat_title' => $deleted ),
4329 __METHOD__
4330 );
4331 }
4332 }
4333
4334 /**
4335 * Lightweight method to get the parser output for a page, checking the parser cache
4336 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4337 * consider, so it's not appropriate to use there.
4338 *
4339 * @since 1.16 (r52326) for LiquidThreads
4340 *
4341 * @param $oldid mixed integer Revision ID or null
4342 * @return ParserOutput or false if the given revsion ID is not found
4343 */
4344 public function getParserOutput( $oldid = null ) {
4345 global $wgEnableParserCache, $wgUser;
4346
4347 // Should the parser cache be used?
4348 $useParserCache = $wgEnableParserCache &&
4349 $wgUser->getStubThreshold() == 0 &&
4350 $this->exists() &&
4351 $oldid === null;
4352
4353 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4354
4355 if ( $wgUser->getStubThreshold() ) {
4356 wfIncrStats( 'pcache_miss_stub' );
4357 }
4358
4359 if ( $useParserCache ) {
4360 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4361 if ( $parserOutput !== false ) {
4362 return $parserOutput;
4363 }
4364 }
4365
4366 // Cache miss; parse and output it.
4367 if ( $oldid === null ) {
4368 $text = $this->getRawText();
4369 } else {
4370 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4371 if ( $rev === null ) {
4372 return false;
4373 }
4374 $text = $rev->getText();
4375 }
4376
4377 return $this->getOutputFromWikitext( $text, $useParserCache );
4378 }
4379
4380 /**
4381 * Sets the context this Article is executed in
4382 *
4383 * @param $context RequestContext
4384 * @since 1.18
4385 */
4386 public function setContext( $context ) {
4387 $this->mContext = $context;
4388 }
4389
4390 /**
4391 * Gets the context this Article is executed in
4392 *
4393 * @return RequestContext
4394 * @since 1.18
4395 */
4396 public function getContext() {
4397 if ( $this->mContext instanceof RequestContext ) {
4398 return $this->mContext;
4399 } else {
4400 wfDebug( __METHOD__ . " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4401 return RequestContext::getMain();
4402 }
4403 }
4404
4405 }
4406
4407 class PoolWorkArticleView extends PoolCounterWork {
4408
4409 /**
4410 * @var Article
4411 */
4412 private $mArticle;
4413
4414 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4415 parent::__construct( 'ArticleView', $key );
4416 $this->mArticle = $article;
4417 $this->cacheable = $useParserCache;
4418 $this->parserOptions = $parserOptions;
4419 }
4420
4421 function doWork() {
4422 return $this->mArticle->doViewParse();
4423 }
4424
4425 function getCachedWork() {
4426 global $wgOut;
4427
4428 $parserCache = ParserCache::singleton();
4429 $this->mArticle->mParserOutput = $parserCache->get( $this->mArticle, $this->parserOptions );
4430
4431 if ( $this->mArticle->mParserOutput !== false ) {
4432 wfDebug( __METHOD__ . ": showing contents parsed by someone else\n" );
4433 $wgOut->addParserOutput( $this->mArticle->mParserOutput );
4434 # Ensure that UI elements requiring revision ID have
4435 # the correct version information.
4436 $wgOut->setRevisionId( $this->mArticle->getLatest() );
4437 return true;
4438 }
4439 return false;
4440 }
4441
4442 function fallback() {
4443 return $this->mArticle->tryDirtyCache();
4444 }
4445
4446 /**
4447 * @param $status Status
4448 */
4449 function error( $status ) {
4450 global $wgOut;
4451
4452 $wgOut->clearHTML(); // for release() errors
4453 $wgOut->enableClientCache( false );
4454 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4455
4456 $errortext = $status->getWikiText( false, 'view-pool-error' );
4457 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );
4458
4459 return false;
4460 }
4461 }