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