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