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