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