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