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