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