(bug 28978) jquery.autoEllipsis cache doesn't take position into account, leads to...
[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 // 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 # 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 * 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 // 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 # 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 (FIXME?)
2217 LinkCache::singleton()->addGoodLinkObj( $newid, $this->mTitle, strlen( $text ), (bool)Title::newFromRedirect( $text ), $revisionId );
2218
2219 # Update the page record with revision data
2220 $this->updateRevisionOn( $dbw, $revision, 0 );
2221
2222 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2223
2224 # Update recentchanges
2225 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2226 global $wgUseRCPatrol, $wgUseNPPatrol;
2227
2228 # Mark as patrolled if the user can do so
2229 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
2230 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
2231 # Add RC row to the DB
2232 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2233 '', strlen( $text ), $revisionId, $patrolled );
2234
2235 # Log auto-patrolled edits
2236 if ( $patrolled ) {
2237 PatrolLog::record( $rc, true );
2238 }
2239 }
2240 $user->incEditCount();
2241 $dbw->commit();
2242
2243 # Update links, etc.
2244 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user, true );
2245
2246 # Clear caches
2247 Article::onArticleCreate( $this->mTitle );
2248
2249 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2250 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
2251 }
2252
2253 # Do updates right now unless deferral was requested
2254 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
2255 wfDoUpdates();
2256 }
2257
2258 // Return the new revision (or null) to the caller
2259 $status->value['revision'] = $revision;
2260
2261 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2262 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
2263
2264 wfProfileOut( __METHOD__ );
2265 return $status;
2266 }
2267
2268 /**
2269 * Output a redirect back to the article.
2270 * This is typically used after an edit.
2271 *
2272 * @param $noRedir Boolean: add redirect=no
2273 * @param $sectionAnchor String: section to redirect to, including "#"
2274 * @param $extraQuery String: extra query params
2275 */
2276 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2277 global $wgOut;
2278
2279 if ( $noRedir ) {
2280 $query = 'redirect=no';
2281 if ( $extraQuery )
2282 $query .= "&$extraQuery";
2283 } else {
2284 $query = $extraQuery;
2285 }
2286
2287 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2288 }
2289
2290 /**
2291 * Mark this particular edit/page as patrolled
2292 */
2293 public function markpatrolled() {
2294 global $wgOut, $wgRequest;
2295
2296 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2297
2298 # If we haven't been given an rc_id value, we can't do anything
2299 $rcid = (int) $wgRequest->getVal( 'rcid' );
2300
2301 if ( !$wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2302 $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2303 return;
2304 }
2305
2306 $rc = RecentChange::newFromId( $rcid );
2307
2308 if ( is_null( $rc ) ) {
2309 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2310 return;
2311 }
2312
2313 # It would be nice to see where the user had actually come from, but for now just guess
2314 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2315 $return = SpecialPage::getTitleFor( $returnto );
2316
2317 $errors = $rc->doMarkPatrolled();
2318
2319 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2320 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2321
2322 return;
2323 }
2324
2325 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2326 // The hook itself has handled any output
2327 return;
2328 }
2329
2330 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2331 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2332 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2333 $wgOut->returnToMain( null, $return );
2334
2335 return;
2336 }
2337
2338 if ( !empty( $errors ) ) {
2339 $wgOut->showPermissionsErrorPage( $errors );
2340
2341 return;
2342 }
2343
2344 # Inform the user
2345 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2346 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2347 $wgOut->returnToMain( null, $return );
2348 }
2349
2350 /**
2351 * User-interface handler for the "watch" action
2352 * @deprecated since 1.18
2353 */
2354 public function watch() {
2355 Action::factory( 'watch', $this )->show();
2356 }
2357
2358 /**
2359 * Add this page to $wgUser's watchlist
2360 *
2361 * This is safe to be called multiple times
2362 *
2363 * @return bool true on successful watch operation
2364 * @deprecated since 1.18
2365 */
2366 public function doWatch() {
2367 return Action::factory( 'watch', $this )->execute();
2368 }
2369
2370 /**
2371 * User interface handler for the "unwatch" action.
2372 * @deprecated since 1.18
2373 */
2374 public function unwatch() {
2375 Action::factory( 'unwatch', $this )->show();
2376 }
2377
2378 /**
2379 * Stop watching a page
2380 * @return bool true on successful unwatch
2381 * @deprecated since 1.18
2382 */
2383 public function doUnwatch() {
2384 return Action::factory( 'unwatch', $this )->execute();
2385 }
2386
2387 /**
2388 * action=protect handler
2389 */
2390 public function protect() {
2391 $form = new ProtectionForm( $this );
2392 $form->execute();
2393 }
2394
2395 /**
2396 * action=unprotect handler (alias)
2397 */
2398 public function unprotect() {
2399 $this->protect();
2400 }
2401
2402 /**
2403 * Update the article's restriction field, and leave a log entry.
2404 *
2405 * @param $limit Array: set of restriction keys
2406 * @param $reason String
2407 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2408 * @param $expiry Array: per restriction type expiration
2409 * @return bool true on success
2410 */
2411 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2412 global $wgUser, $wgContLang;
2413
2414 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2415
2416 $id = $this->mTitle->getArticleID();
2417
2418 if ( $id <= 0 ) {
2419 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2420 return false;
2421 }
2422
2423 if ( wfReadOnly() ) {
2424 wfDebug( "updateRestrictions failed: read-only\n" );
2425 return false;
2426 }
2427
2428 if ( !$this->mTitle->userCan( 'protect' ) ) {
2429 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2430 return false;
2431 }
2432
2433 if ( !$cascade ) {
2434 $cascade = false;
2435 }
2436
2437 // Take this opportunity to purge out expired restrictions
2438 Title::purgeExpiredRestrictions();
2439
2440 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2441 # we expect a single selection, but the schema allows otherwise.
2442 $current = array();
2443 $updated = Article::flattenRestrictions( $limit );
2444 $changed = false;
2445
2446 foreach ( $restrictionTypes as $action ) {
2447 if ( isset( $expiry[$action] ) ) {
2448 # Get current restrictions on $action
2449 $aLimits = $this->mTitle->getRestrictions( $action );
2450 $current[$action] = implode( '', $aLimits );
2451 # Are any actual restrictions being dealt with here?
2452 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
2453
2454 # If something changed, we need to log it. Checking $aRChanged
2455 # assures that "unprotecting" a page that is not protected does
2456 # not log just because the expiry was "changed".
2457 if ( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2458 $changed = true;
2459 }
2460 }
2461 }
2462
2463 $current = Article::flattenRestrictions( $current );
2464
2465 $changed = ( $changed || $current != $updated );
2466 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
2467 $protect = ( $updated != '' );
2468
2469 # If nothing's changed, do nothing
2470 if ( $changed ) {
2471 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2472 $dbw = wfGetDB( DB_MASTER );
2473
2474 # Prepare a null revision to be added to the history
2475 $modified = $current != '' && $protect;
2476
2477 if ( $protect ) {
2478 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2479 } else {
2480 $comment_type = 'unprotectedarticle';
2481 }
2482
2483 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2484
2485 # Only restrictions with the 'protect' right can cascade...
2486 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2487 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2488
2489 # The schema allows multiple restrictions
2490 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2491 $cascade = false;
2492 }
2493
2494 $cascade_description = '';
2495
2496 if ( $cascade ) {
2497 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2498 }
2499
2500 if ( $reason ) {
2501 $comment .= ": $reason";
2502 }
2503
2504 $editComment = $comment;
2505 $encodedExpiry = array();
2506 $protect_description = '';
2507 foreach ( $limit as $action => $restrictions ) {
2508 if ( !isset( $expiry[$action] ) )
2509 $expiry[$action] = $dbw->getInfinity();
2510
2511 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2512 if ( $restrictions != '' ) {
2513 $protect_description .= "[$action=$restrictions] (";
2514 if ( $encodedExpiry[$action] != 'infinity' ) {
2515 $protect_description .= wfMsgForContent( 'protect-expiring',
2516 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2517 $wgContLang->date( $expiry[$action], false, false ) ,
2518 $wgContLang->time( $expiry[$action], false, false ) );
2519 } else {
2520 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2521 }
2522
2523 $protect_description .= ') ';
2524 }
2525 }
2526 $protect_description = trim( $protect_description );
2527
2528 if ( $protect_description && $protect ) {
2529 $editComment .= " ($protect_description)";
2530 }
2531
2532 if ( $cascade ) {
2533 $editComment .= "$cascade_description";
2534 }
2535
2536 # Update restrictions table
2537 foreach ( $limit as $action => $restrictions ) {
2538 if ( $restrictions != '' ) {
2539 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2540 array( 'pr_page' => $id,
2541 'pr_type' => $action,
2542 'pr_level' => $restrictions,
2543 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2544 'pr_expiry' => $encodedExpiry[$action]
2545 ),
2546 __METHOD__
2547 );
2548 } else {
2549 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2550 'pr_type' => $action ), __METHOD__ );
2551 }
2552 }
2553
2554 # Insert a null revision
2555 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2556 $nullRevId = $nullRevision->insertOn( $dbw );
2557
2558 $latest = $this->getLatest();
2559 # Update page record
2560 $dbw->update( 'page',
2561 array( /* SET */
2562 'page_touched' => $dbw->timestamp(),
2563 'page_restrictions' => '',
2564 'page_latest' => $nullRevId
2565 ), array( /* WHERE */
2566 'page_id' => $id
2567 ), 'Article::protect'
2568 );
2569
2570 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2571 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2572
2573 # Update the protection log
2574 $log = new LogPage( 'protect' );
2575 if ( $protect ) {
2576 $params = array( $protect_description, $cascade ? 'cascade' : '' );
2577 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
2578 } else {
2579 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2580 }
2581 } # End hook
2582 } # End "changed" check
2583
2584 return true;
2585 }
2586
2587 /**
2588 * Take an array of page restrictions and flatten it to a string
2589 * suitable for insertion into the page_restrictions field.
2590 * @param $limit Array
2591 * @return String
2592 */
2593 protected static function flattenRestrictions( $limit ) {
2594 if ( !is_array( $limit ) ) {
2595 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2596 }
2597
2598 $bits = array();
2599 ksort( $limit );
2600
2601 foreach ( $limit as $action => $restrictions ) {
2602 if ( $restrictions != '' ) {
2603 $bits[] = "$action=$restrictions";
2604 }
2605 }
2606
2607 return implode( ':', $bits );
2608 }
2609
2610 /**
2611 * Auto-generates a deletion reason
2612 *
2613 * @param &$hasHistory Boolean: whether the page has a history
2614 * @return mixed String containing deletion reason or empty string, or boolean false
2615 * if no revision occurred
2616 */
2617 public function generateReason( &$hasHistory ) {
2618 global $wgContLang;
2619
2620 $dbw = wfGetDB( DB_MASTER );
2621 // Get the last revision
2622 $rev = Revision::newFromTitle( $this->mTitle );
2623
2624 if ( is_null( $rev ) ) {
2625 return false;
2626 }
2627
2628 // Get the article's contents
2629 $contents = $rev->getText();
2630 $blank = false;
2631
2632 // If the page is blank, use the text from the previous revision,
2633 // which can only be blank if there's a move/import/protect dummy revision involved
2634 if ( $contents == '' ) {
2635 $prev = $rev->getPrevious();
2636
2637 if ( $prev ) {
2638 $contents = $prev->getText();
2639 $blank = true;
2640 }
2641 }
2642
2643 // Find out if there was only one contributor
2644 // Only scan the last 20 revisions
2645 $res = $dbw->select( 'revision', 'rev_user_text',
2646 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2647 __METHOD__,
2648 array( 'LIMIT' => 20 )
2649 );
2650
2651 if ( $res === false ) {
2652 // This page has no revisions, which is very weird
2653 return false;
2654 }
2655
2656 $hasHistory = ( $res->numRows() > 1 );
2657 $row = $dbw->fetchObject( $res );
2658
2659 if ( $row ) { // $row is false if the only contributor is hidden
2660 $onlyAuthor = $row->rev_user_text;
2661 // Try to find a second contributor
2662 foreach ( $res as $row ) {
2663 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2664 $onlyAuthor = false;
2665 break;
2666 }
2667 }
2668 } else {
2669 $onlyAuthor = false;
2670 }
2671
2672 // Generate the summary with a '$1' placeholder
2673 if ( $blank ) {
2674 // The current revision is blank and the one before is also
2675 // blank. It's just not our lucky day
2676 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2677 } else {
2678 if ( $onlyAuthor ) {
2679 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2680 } else {
2681 $reason = wfMsgForContent( 'excontent', '$1' );
2682 }
2683 }
2684
2685 if ( $reason == '-' ) {
2686 // Allow these UI messages to be blanked out cleanly
2687 return '';
2688 }
2689
2690 // Replace newlines with spaces to prevent uglyness
2691 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2692 // Calculate the maximum amount of chars to get
2693 // Max content length = max comment length - length of the comment (excl. $1)
2694 $maxLength = 255 - ( strlen( $reason ) - 2 );
2695 $contents = $wgContLang->truncate( $contents, $maxLength );
2696 // Remove possible unfinished links
2697 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2698 // Now replace the '$1' placeholder
2699 $reason = str_replace( '$1', $contents, $reason );
2700
2701 return $reason;
2702 }
2703
2704
2705 /*
2706 * UI entry point for page deletion
2707 */
2708 public function delete() {
2709 global $wgOut, $wgRequest;
2710
2711 $confirm = $wgRequest->wasPosted() &&
2712 $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2713
2714 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2715 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2716
2717 $reason = $this->DeleteReasonList;
2718
2719 if ( $reason != 'other' && $this->DeleteReason != '' ) {
2720 // Entry from drop down menu + additional comment
2721 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2722 } elseif ( $reason == 'other' ) {
2723 $reason = $this->DeleteReason;
2724 }
2725
2726 # Flag to hide all contents of the archived revisions
2727 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
2728
2729 # This code desperately needs to be totally rewritten
2730
2731 # Read-only check...
2732 if ( wfReadOnly() ) {
2733 $wgOut->readOnlyPage();
2734
2735 return;
2736 }
2737
2738 # Check permissions
2739 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
2740
2741 if ( count( $permission_errors ) > 0 ) {
2742 $wgOut->showPermissionsErrorPage( $permission_errors );
2743
2744 return;
2745 }
2746
2747 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2748
2749 # Better double-check that it hasn't been deleted yet!
2750 $dbw = wfGetDB( DB_MASTER );
2751 $conds = $this->mTitle->pageCond();
2752 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2753 if ( $latest === false ) {
2754 $wgOut->showFatalError(
2755 Html::rawElement(
2756 'div',
2757 array( 'class' => 'error mw-error-cannotdelete' ),
2758 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2759 )
2760 );
2761 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2762 LogEventsList::showLogExtract(
2763 $wgOut,
2764 'delete',
2765 $this->mTitle->getPrefixedText()
2766 );
2767
2768 return;
2769 }
2770
2771 # Hack for big sites
2772 $bigHistory = $this->isBigDeletion();
2773 if ( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2774 global $wgLang, $wgDeleteRevisionsLimit;
2775
2776 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2777 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2778
2779 return;
2780 }
2781
2782 if ( $confirm ) {
2783 $this->doDelete( $reason, $suppress );
2784
2785 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
2786 $this->doWatch();
2787 } elseif ( $this->mTitle->userIsWatching() ) {
2788 $this->doUnwatch();
2789 }
2790
2791 return;
2792 }
2793
2794 // Generate deletion reason
2795 $hasHistory = false;
2796 if ( !$reason ) {
2797 $reason = $this->generateReason( $hasHistory );
2798 }
2799
2800 // If the page has a history, insert a warning
2801 if ( $hasHistory && !$confirm ) {
2802 global $wgLang;
2803
2804 $revisions = $this->estimateRevisionCount();
2805 //FIXME: lego
2806 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2807 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2808 wfMsgHtml( 'word-separator' ) . Linker::link( $this->mTitle,
2809 wfMsgHtml( 'history' ),
2810 array( 'rel' => 'archives' ),
2811 array( 'action' => 'history' ) ) .
2812 '</strong>'
2813 );
2814
2815 if ( $bigHistory ) {
2816 global $wgDeleteRevisionsLimit;
2817 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2818 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2819 }
2820 }
2821
2822 return $this->confirmDelete( $reason );
2823 }
2824
2825 /**
2826 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2827 */
2828 public function isBigDeletion() {
2829 global $wgDeleteRevisionsLimit;
2830
2831 if ( $wgDeleteRevisionsLimit ) {
2832 $revCount = $this->estimateRevisionCount();
2833
2834 return $revCount > $wgDeleteRevisionsLimit;
2835 }
2836
2837 return false;
2838 }
2839
2840 /**
2841 * @return int approximate revision count
2842 */
2843 public function estimateRevisionCount() {
2844 $dbr = wfGetDB( DB_SLAVE );
2845
2846 // For an exact count...
2847 // return $dbr->selectField( 'revision', 'COUNT(*)',
2848 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2849 return $dbr->estimateRowCount( 'revision', '*',
2850 array( 'rev_page' => $this->getId() ), __METHOD__ );
2851 }
2852
2853 /**
2854 * Get the last N authors
2855 * @param $num Integer: number of revisions to get
2856 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2857 * @return array Array of authors, duplicates not removed
2858 */
2859 public function getLastNAuthors( $num, $revLatest = 0 ) {
2860 wfProfileIn( __METHOD__ );
2861 // First try the slave
2862 // If that doesn't have the latest revision, try the master
2863 $continue = 2;
2864 $db = wfGetDB( DB_SLAVE );
2865
2866 do {
2867 $res = $db->select( array( 'page', 'revision' ),
2868 array( 'rev_id', 'rev_user_text' ),
2869 array(
2870 'page_namespace' => $this->mTitle->getNamespace(),
2871 'page_title' => $this->mTitle->getDBkey(),
2872 'rev_page = page_id'
2873 ), __METHOD__,
2874 array(
2875 'ORDER BY' => 'rev_timestamp DESC',
2876 'LIMIT' => $num
2877 )
2878 );
2879
2880 if ( !$res ) {
2881 wfProfileOut( __METHOD__ );
2882 return array();
2883 }
2884
2885 $row = $db->fetchObject( $res );
2886
2887 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2888 $db = wfGetDB( DB_MASTER );
2889 $continue--;
2890 } else {
2891 $continue = 0;
2892 }
2893 } while ( $continue );
2894
2895 $authors = array( $row->rev_user_text );
2896
2897 foreach ( $res as $row ) {
2898 $authors[] = $row->rev_user_text;
2899 }
2900
2901 wfProfileOut( __METHOD__ );
2902 return $authors;
2903 }
2904
2905 /**
2906 * Output deletion confirmation dialog
2907 * FIXME: Move to another file?
2908 * @param $reason String: prefilled reason
2909 */
2910 public function confirmDelete( $reason ) {
2911 global $wgOut;
2912
2913 wfDebug( "Article::confirmDelete\n" );
2914
2915 $deleteBackLink = Linker::linkKnown( $this->mTitle );
2916 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2917 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2918 $wgOut->addWikiMsg( 'confirmdeletetext' );
2919
2920 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2921
2922 if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
2923 $suppress = "<tr id=\"wpDeleteSuppressRow\">
2924 <td></td>
2925 <td class='mw-input'><strong>" .
2926 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2927 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2928 "</strong></td>
2929 </tr>";
2930 } else {
2931 $suppress = '';
2932 }
2933 $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2934
2935 $form = Xml::openElement( 'form', array( 'method' => 'post',
2936 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2937 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2938 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2939 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2940 "<tr id=\"wpDeleteReasonListRow\">
2941 <td class='mw-label'>" .
2942 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2943 "</td>
2944 <td class='mw-input'>" .
2945 Xml::listDropDown( 'wpDeleteReasonList',
2946 wfMsgForContent( 'deletereason-dropdown' ),
2947 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2948 "</td>
2949 </tr>
2950 <tr id=\"wpDeleteReasonRow\">
2951 <td class='mw-label'>" .
2952 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2953 "</td>
2954 <td class='mw-input'>" .
2955 Html::input( 'wpReason', $reason, 'text', array(
2956 'size' => '60',
2957 'maxlength' => '255',
2958 'tabindex' => '2',
2959 'id' => 'wpReason',
2960 'autofocus'
2961 ) ) .
2962 "</td>
2963 </tr>";
2964
2965 # Disallow watching if user is not logged in
2966 if ( $wgOut->getUser()->isLoggedIn() ) {
2967 $form .= "
2968 <tr>
2969 <td></td>
2970 <td class='mw-input'>" .
2971 Xml::checkLabel( wfMsg( 'watchthis' ),
2972 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2973 "</td>
2974 </tr>";
2975 }
2976
2977 $form .= "
2978 $suppress
2979 <tr>
2980 <td></td>
2981 <td class='mw-submit'>" .
2982 Xml::submitButton( wfMsg( 'deletepage' ),
2983 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2984 "</td>
2985 </tr>" .
2986 Xml::closeElement( 'table' ) .
2987 Xml::closeElement( 'fieldset' ) .
2988 Html::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
2989 Xml::closeElement( 'form' );
2990
2991 if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
2992 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2993 $link = Linker::link(
2994 $title,
2995 wfMsgHtml( 'delete-edit-reasonlist' ),
2996 array(),
2997 array( 'action' => 'edit' )
2998 );
2999 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3000 }
3001
3002 $wgOut->addHTML( $form );
3003 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3004 LogEventsList::showLogExtract( $wgOut, 'delete',
3005 $this->mTitle->getPrefixedText()
3006 );
3007 }
3008
3009 /**
3010 * Perform a deletion and output success or failure messages
3011 */
3012 public function doDelete( $reason, $suppress = false ) {
3013 global $wgOut;
3014
3015 $id = $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
3016
3017 $error = '';
3018 if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
3019 $deleted = $this->mTitle->getPrefixedText();
3020
3021 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3022 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3023
3024 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3025
3026 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3027 $wgOut->returnToMain( false );
3028 } else {
3029 if ( $error == '' ) {
3030 $wgOut->showFatalError(
3031 Html::rawElement(
3032 'div',
3033 array( 'class' => 'error mw-error-cannotdelete' ),
3034 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
3035 )
3036 );
3037
3038 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3039
3040 LogEventsList::showLogExtract(
3041 $wgOut,
3042 'delete',
3043 $this->mTitle->getPrefixedText()
3044 );
3045 } else {
3046 $wgOut->showFatalError( $error );
3047 }
3048 }
3049 }
3050
3051 /**
3052 * Back-end article deletion
3053 * Deletes the article with database consistency, writes logs, purges caches
3054 *
3055 * @param $reason string delete reason for deletion log
3056 * @param suppress bitfield
3057 * Revision::DELETED_TEXT
3058 * Revision::DELETED_COMMENT
3059 * Revision::DELETED_USER
3060 * Revision::DELETED_RESTRICTED
3061 * @param $id int article ID
3062 * @param $commit boolean defaults to true, triggers transaction end
3063 * @return boolean true if successful
3064 */
3065 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
3066 global $wgDeferredUpdateList, $wgUseTrackbacks;
3067 global $wgUser;
3068
3069 wfDebug( __METHOD__ . "\n" );
3070
3071 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3072 return false;
3073 }
3074 $dbw = wfGetDB( DB_MASTER );
3075 $t = $this->mTitle->getDBkey();
3076 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
3077
3078 if ( $t === '' || $id == 0 ) {
3079 return false;
3080 }
3081
3082 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
3083 array_push( $wgDeferredUpdateList, $u );
3084
3085 // Bitfields to further suppress the content
3086 if ( $suppress ) {
3087 $bitfield = 0;
3088 // This should be 15...
3089 $bitfield |= Revision::DELETED_TEXT;
3090 $bitfield |= Revision::DELETED_COMMENT;
3091 $bitfield |= Revision::DELETED_USER;
3092 $bitfield |= Revision::DELETED_RESTRICTED;
3093 } else {
3094 $bitfield = 'rev_deleted';
3095 }
3096
3097 $dbw->begin();
3098 // For now, shunt the revision data into the archive table.
3099 // Text is *not* removed from the text table; bulk storage
3100 // is left intact to avoid breaking block-compression or
3101 // immutable storage schemes.
3102 //
3103 // For backwards compatibility, note that some older archive
3104 // table entries will have ar_text and ar_flags fields still.
3105 //
3106 // In the future, we may keep revisions and mark them with
3107 // the rev_deleted field, which is reserved for this purpose.
3108 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3109 array(
3110 'ar_namespace' => 'page_namespace',
3111 'ar_title' => 'page_title',
3112 'ar_comment' => 'rev_comment',
3113 'ar_user' => 'rev_user',
3114 'ar_user_text' => 'rev_user_text',
3115 'ar_timestamp' => 'rev_timestamp',
3116 'ar_minor_edit' => 'rev_minor_edit',
3117 'ar_rev_id' => 'rev_id',
3118 'ar_text_id' => 'rev_text_id',
3119 'ar_text' => '\'\'', // Be explicit to appease
3120 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3121 'ar_len' => 'rev_len',
3122 'ar_page_id' => 'page_id',
3123 'ar_deleted' => $bitfield
3124 ), array(
3125 'page_id' => $id,
3126 'page_id = rev_page'
3127 ), __METHOD__
3128 );
3129
3130 # Delete restrictions for it
3131 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
3132
3133 # Now that it's safely backed up, delete it
3134 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
3135 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3136
3137 if ( !$ok ) {
3138 $dbw->rollback();
3139 return false;
3140 }
3141
3142 # Fix category table counts
3143 $cats = array();
3144 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
3145
3146 foreach ( $res as $row ) {
3147 $cats [] = $row->cl_to;
3148 }
3149
3150 $this->updateCategoryCounts( array(), $cats );
3151
3152 # If using cascading deletes, we can skip some explicit deletes
3153 if ( !$dbw->cascadingDeletes() ) {
3154 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
3155
3156 if ( $wgUseTrackbacks )
3157 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
3158
3159 # Delete outgoing links
3160 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3161 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3162 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3163 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3164 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3165 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3166 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3167 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3168 }
3169
3170 # If using cleanup triggers, we can skip some manual deletes
3171 if ( !$dbw->cleanupTriggers() ) {
3172 # Clean up recentchanges entries...
3173 $dbw->delete( 'recentchanges',
3174 array( 'rc_type != ' . RC_LOG,
3175 'rc_namespace' => $this->mTitle->getNamespace(),
3176 'rc_title' => $this->mTitle->getDBkey() ),
3177 __METHOD__ );
3178 $dbw->delete( 'recentchanges',
3179 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
3180 __METHOD__ );
3181 }
3182
3183 # Clear caches
3184 Article::onArticleDelete( $this->mTitle );
3185
3186 # Clear the cached article id so the interface doesn't act like we exist
3187 $this->mTitle->resetArticleID( 0 );
3188
3189 # Log the deletion, if the page was suppressed, log it at Oversight instead
3190 $logtype = $suppress ? 'suppress' : 'delete';
3191 $log = new LogPage( $logtype );
3192
3193 # Make sure logging got through
3194 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
3195
3196 if ( $commit ) {
3197 $dbw->commit();
3198 }
3199
3200 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3201 return true;
3202 }
3203
3204 /**
3205 * Roll back the most recent consecutive set of edits to a page
3206 * from the same user; fails if there are no eligible edits to
3207 * roll back to, e.g. user is the sole contributor. This function
3208 * performs permissions checks on $wgUser, then calls commitRollback()
3209 * to do the dirty work
3210 *
3211 * @param $fromP String: Name of the user whose edits to rollback.
3212 * @param $summary String: Custom summary. Set to default summary if empty.
3213 * @param $token String: Rollback token.
3214 * @param $bot Boolean: If true, mark all reverted edits as bot.
3215 *
3216 * @param $resultDetails Array: contains result-specific array of additional values
3217 * 'alreadyrolled' : 'current' (rev)
3218 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3219 *
3220 * @return array of errors, each error formatted as
3221 * array(messagekey, param1, param2, ...).
3222 * On success, the array is empty. This array can also be passed to
3223 * OutputPage::showPermissionsErrorPage().
3224 */
3225 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3226 global $wgUser;
3227
3228 $resultDetails = null;
3229
3230 # Check permissions
3231 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
3232 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
3233 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3234
3235 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
3236 $errors[] = array( 'sessionfailure' );
3237 }
3238
3239 if ( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
3240 $errors[] = array( 'actionthrottledtext' );
3241 }
3242
3243 # If there were errors, bail out now
3244 if ( !empty( $errors ) ) {
3245 return $errors;
3246 }
3247
3248 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3249 }
3250
3251 /**
3252 * Backend implementation of doRollback(), please refer there for parameter
3253 * and return value documentation
3254 *
3255 * NOTE: This function does NOT check ANY permissions, it just commits the
3256 * rollback to the DB Therefore, you should only call this function direct-
3257 * ly if you want to use custom permissions checks. If you don't, use
3258 * doRollback() instead.
3259 */
3260 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3261 global $wgUseRCPatrol, $wgUser, $wgLang;
3262
3263 $dbw = wfGetDB( DB_MASTER );
3264
3265 if ( wfReadOnly() ) {
3266 return array( array( 'readonlytext' ) );
3267 }
3268
3269 # Get the last editor
3270 $current = Revision::newFromTitle( $this->mTitle );
3271 if ( is_null( $current ) ) {
3272 # Something wrong... no page?
3273 return array( array( 'notanarticle' ) );
3274 }
3275
3276 $from = str_replace( '_', ' ', $fromP );
3277 # User name given should match up with the top revision.
3278 # If the user was deleted then $from should be empty.
3279 if ( $from != $current->getUserText() ) {
3280 $resultDetails = array( 'current' => $current );
3281 return array( array( 'alreadyrolled',
3282 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3283 htmlspecialchars( $fromP ),
3284 htmlspecialchars( $current->getUserText() )
3285 ) );
3286 }
3287
3288 # Get the last edit not by this guy...
3289 # Note: these may not be public values
3290 $user = intval( $current->getRawUser() );
3291 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3292 $s = $dbw->selectRow( 'revision',
3293 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3294 array( 'rev_page' => $current->getPage(),
3295 "rev_user != {$user} OR rev_user_text != {$user_text}"
3296 ), __METHOD__,
3297 array( 'USE INDEX' => 'page_timestamp',
3298 'ORDER BY' => 'rev_timestamp DESC' )
3299 );
3300 if ( $s === false ) {
3301 # No one else ever edited this page
3302 return array( array( 'cantrollback' ) );
3303 } else if ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
3304 # Only admins can see this text
3305 return array( array( 'notvisiblerev' ) );
3306 }
3307
3308 $set = array();
3309 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3310 # Mark all reverted edits as bot
3311 $set['rc_bot'] = 1;
3312 }
3313
3314 if ( $wgUseRCPatrol ) {
3315 # Mark all reverted edits as patrolled
3316 $set['rc_patrolled'] = 1;
3317 }
3318
3319 if ( count( $set ) ) {
3320 $dbw->update( 'recentchanges', $set,
3321 array( /* WHERE */
3322 'rc_cur_id' => $current->getPage(),
3323 'rc_user_text' => $current->getUserText(),
3324 "rc_timestamp > '{$s->rev_timestamp}'",
3325 ), __METHOD__
3326 );
3327 }
3328
3329 # Generate the edit summary if necessary
3330 $target = Revision::newFromId( $s->rev_id );
3331 if ( empty( $summary ) ) {
3332 if ( $from == '' ) { // no public user name
3333 $summary = wfMsgForContent( 'revertpage-nouser' );
3334 } else {
3335 $summary = wfMsgForContent( 'revertpage' );
3336 }
3337 }
3338
3339 # Allow the custom summary to use the same args as the default message
3340 $args = array(
3341 $target->getUserText(), $from, $s->rev_id,
3342 $wgLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ), true ),
3343 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3344 );
3345 $summary = wfMsgReplaceArgs( $summary, $args );
3346
3347 # Save
3348 $flags = EDIT_UPDATE;
3349
3350 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3351 $flags |= EDIT_MINOR;
3352 }
3353
3354 if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3355 $flags |= EDIT_FORCE_BOT;
3356 }
3357
3358 # Actually store the edit
3359 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3360 if ( !empty( $status->value['revision'] ) ) {
3361 $revId = $status->value['revision']->getId();
3362 } else {
3363 $revId = false;
3364 }
3365
3366 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3367
3368 $resultDetails = array(
3369 'summary' => $summary,
3370 'current' => $current,
3371 'target' => $target,
3372 'newid' => $revId
3373 );
3374
3375 return array();
3376 }
3377
3378 /**
3379 * User interface for rollback operations
3380 */
3381 public function rollback() {
3382 global $wgUser, $wgOut, $wgRequest;
3383
3384 $details = null;
3385
3386 $result = $this->doRollback(
3387 $wgRequest->getVal( 'from' ),
3388 $wgRequest->getText( 'summary' ),
3389 $wgRequest->getVal( 'token' ),
3390 $wgRequest->getBool( 'bot' ),
3391 $details
3392 );
3393
3394 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3395 $wgOut->rateLimited();
3396 return;
3397 }
3398
3399 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3400 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3401 $errArray = $result[0];
3402 $errMsg = array_shift( $errArray );
3403 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3404
3405 if ( isset( $details['current'] ) ) {
3406 $current = $details['current'];
3407
3408 if ( $current->getComment() != '' ) {
3409 $wgOut->addWikiMsgArray( 'editcomment', array(
3410 Linker::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3411 }
3412 }
3413
3414 return;
3415 }
3416
3417 # Display permissions errors before read-only message -- there's no
3418 # point in misleading the user into thinking the inability to rollback
3419 # is only temporary.
3420 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3421 # array_diff is completely broken for arrays of arrays, sigh.
3422 # Remove any 'readonlytext' error manually.
3423 $out = array();
3424 foreach ( $result as $error ) {
3425 if ( $error != array( 'readonlytext' ) ) {
3426 $out [] = $error;
3427 }
3428 }
3429 $wgOut->showPermissionsErrorPage( $out );
3430
3431 return;
3432 }
3433
3434 if ( $result == array( array( 'readonlytext' ) ) ) {
3435 $wgOut->readOnlyPage();
3436
3437 return;
3438 }
3439
3440 $current = $details['current'];
3441 $target = $details['target'];
3442 $newId = $details['newid'];
3443 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3444 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3445
3446 if ( $current->getUserText() === '' ) {
3447 $old = wfMsg( 'rev-deleted-user' );
3448 } else {
3449 $old = Linker::userLink( $current->getUser(), $current->getUserText() )
3450 . Linker::userToolLinks( $current->getUser(), $current->getUserText() );
3451 }
3452
3453 $new = Linker::userLink( $target->getUser(), $target->getUserText() )
3454 . Linker::userToolLinks( $target->getUser(), $target->getUserText() );
3455 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3456 $wgOut->returnToMain( false, $this->mTitle );
3457
3458 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3459 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3460 $de->showDiff( '', '' );
3461 }
3462 }
3463
3464 /**
3465 * Do standard deferred updates after page view
3466 */
3467 public function viewUpdates() {
3468 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3469 if ( wfReadOnly() ) {
3470 return;
3471 }
3472
3473 # Don't update page view counters on views from bot users (bug 14044)
3474 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3475 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
3476 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
3477 }
3478
3479 # Update newtalk / watchlist notification status
3480 $wgUser->clearNotification( $this->mTitle );
3481 }
3482
3483 /**
3484 * Prepare text which is about to be saved.
3485 * Returns a stdclass with source, pst and output members
3486 */
3487 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
3488 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid ) {
3489 // Already prepared
3490 return $this->mPreparedEdit;
3491 }
3492
3493 global $wgParser;
3494
3495 if( $user === null ) {
3496 global $wgUser;
3497 $user = $wgUser;
3498 }
3499 $popts = ParserOptions::newFromUser( $user );
3500 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
3501
3502 $edit = (object)array();
3503 $edit->revid = $revid;
3504 $edit->newText = $text;
3505 $edit->pst = $this->preSaveTransform( $text, $user, $popts );
3506 $edit->popts = $this->getParserOptions();
3507 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
3508 $edit->oldText = $this->getRawText();
3509
3510 $this->mPreparedEdit = $edit;
3511
3512 return $edit;
3513 }
3514
3515 /**
3516 * Do standard deferred updates after page edit.
3517 * Update links tables, site stats, search index and message cache.
3518 * Purges pages that include this page if the text was changed here.
3519 * Every 100th edit, prune the recent changes table.
3520 *
3521 * @private
3522 * @param $text String: New text of the article
3523 * @param $summary String: Edit summary
3524 * @param $minoredit Boolean: Minor edit
3525 * @param $timestamp_of_pagechange String timestamp associated with the page change
3526 * @param $newid Integer: rev_id value of the new revision
3527 * @param $changed Boolean: Whether or not the content actually changed
3528 * @param $user User object: User doing the edit
3529 * @param $created Boolean: Whether the edit created the page
3530 */
3531 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
3532 $changed = true, User $user = null, $created = false )
3533 {
3534 global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
3535
3536 wfProfileIn( __METHOD__ );
3537
3538 # Parse the text
3539 # Be careful not to double-PST: $text is usually already PST-ed once
3540 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3541 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3542 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
3543 } else {
3544 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3545 $editInfo = $this->mPreparedEdit;
3546 }
3547
3548 # Save it to the parser cache
3549 if ( $wgEnableParserCache ) {
3550 $parserCache = ParserCache::singleton();
3551 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
3552 }
3553
3554 # Update the links tables
3555 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3556 $u->doUpdate();
3557
3558 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3559
3560 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3561 if ( 0 == mt_rand( 0, 99 ) ) {
3562 // Flush old entries from the `recentchanges` table; we do this on
3563 // random requests so as to avoid an increase in writes for no good reason
3564 global $wgRCMaxAge;
3565
3566 $dbw = wfGetDB( DB_MASTER );
3567 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3568 $dbw->delete(
3569 'recentchanges',
3570 array( "rc_timestamp < '$cutoff'" ),
3571 __METHOD__
3572 );
3573 }
3574 }
3575
3576 $id = $this->getID();
3577 $title = $this->mTitle->getPrefixedDBkey();
3578 $shortTitle = $this->mTitle->getDBkey();
3579
3580 if ( 0 == $id ) {
3581 wfProfileOut( __METHOD__ );
3582 return;
3583 }
3584
3585 if ( !$changed ) {
3586 $good = 0;
3587 $total = 0;
3588 } elseif ( $created ) {
3589 $good = (int)$this->isCountable( $editInfo );
3590 $total = 1;
3591 } else {
3592 $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
3593 $total = 0;
3594 }
3595
3596 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
3597 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
3598
3599 # If this is another user's talk page, update newtalk
3600 # Don't do this if $changed = false otherwise some idiot can null-edit a
3601 # load of user talk pages and piss people off, nor if it's a minor edit
3602 # by a properly-flagged bot.
3603 if ( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3604 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3605 ) {
3606 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3607 $other = User::newFromName( $shortTitle, false );
3608 if ( !$other ) {
3609 wfDebug( __METHOD__ . ": invalid username\n" );
3610 } elseif ( User::isIP( $shortTitle ) ) {
3611 // An anonymous user
3612 $other->setNewtalk( true );
3613 } elseif ( $other->isLoggedIn() ) {
3614 $other->setNewtalk( true );
3615 } else {
3616 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
3617 }
3618 }
3619 }
3620
3621 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3622 MessageCache::singleton()->replace( $shortTitle, $text );
3623 }
3624
3625 wfProfileOut( __METHOD__ );
3626 }
3627
3628 /**
3629 * Perform article updates on a special page creation.
3630 *
3631 * @param $rev Revision object
3632 *
3633 * @todo This is a shitty interface function. Kill it and replace the
3634 * other shitty functions like editUpdates and such so it's not needed
3635 * anymore.
3636 */
3637 public function createUpdates( $rev ) {
3638 $this->editUpdates( $rev->getText(), $rev->getComment(),
3639 $rev->isMinor(), wfTimestamp(), $rev->getId(), true, null, true );
3640 }
3641
3642 /**
3643 * Generate the navigation links when browsing through an article revisions
3644 * It shows the information as:
3645 * Revision as of \<date\>; view current revision
3646 * \<- Previous version | Next Version -\>
3647 *
3648 * @param $oldid String: revision ID of this article revision
3649 */
3650 public function setOldSubtitle( $oldid = 0 ) {
3651 global $wgLang, $wgOut, $wgUser, $wgRequest;
3652
3653 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3654 return;
3655 }
3656
3657 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3658
3659 # Cascade unhide param in links for easy deletion browsing
3660 $extraParams = array();
3661 if ( $wgRequest->getVal( 'unhide' ) ) {
3662 $extraParams['unhide'] = 1;
3663 }
3664
3665 $revision = Revision::newFromId( $oldid );
3666 $timestamp = $revision->getTimestamp();
3667
3668 $current = ( $oldid == $this->mLatest );
3669 $td = $wgLang->timeanddate( $timestamp, true );
3670 $tddate = $wgLang->date( $timestamp, true );
3671 $tdtime = $wgLang->time( $timestamp, true );
3672
3673 $lnk = $current
3674 ? wfMsgHtml( 'currentrevisionlink' )
3675 : Linker::link(
3676 $this->mTitle,
3677 wfMsgHtml( 'currentrevisionlink' ),
3678 array(),
3679 $extraParams,
3680 array( 'known', 'noclasses' )
3681 );
3682 $curdiff = $current
3683 ? wfMsgHtml( 'diff' )
3684 : Linker::link(
3685 $this->mTitle,
3686 wfMsgHtml( 'diff' ),
3687 array(),
3688 array(
3689 'diff' => 'cur',
3690 'oldid' => $oldid
3691 ) + $extraParams,
3692 array( 'known', 'noclasses' )
3693 );
3694 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3695 $prevlink = $prev
3696 ? Linker::link(
3697 $this->mTitle,
3698 wfMsgHtml( 'previousrevision' ),
3699 array(),
3700 array(
3701 'direction' => 'prev',
3702 'oldid' => $oldid
3703 ) + $extraParams,
3704 array( 'known', 'noclasses' )
3705 )
3706 : wfMsgHtml( 'previousrevision' );
3707 $prevdiff = $prev
3708 ? Linker::link(
3709 $this->mTitle,
3710 wfMsgHtml( 'diff' ),
3711 array(),
3712 array(
3713 'diff' => 'prev',
3714 'oldid' => $oldid
3715 ) + $extraParams,
3716 array( 'known', 'noclasses' )
3717 )
3718 : wfMsgHtml( 'diff' );
3719 $nextlink = $current
3720 ? wfMsgHtml( 'nextrevision' )
3721 : Linker::link(
3722 $this->mTitle,
3723 wfMsgHtml( 'nextrevision' ),
3724 array(),
3725 array(
3726 'direction' => 'next',
3727 'oldid' => $oldid
3728 ) + $extraParams,
3729 array( 'known', 'noclasses' )
3730 );
3731 $nextdiff = $current
3732 ? wfMsgHtml( 'diff' )
3733 : Linker::link(
3734 $this->mTitle,
3735 wfMsgHtml( 'diff' ),
3736 array(),
3737 array(
3738 'diff' => 'next',
3739 'oldid' => $oldid
3740 ) + $extraParams,
3741 array( 'known', 'noclasses' )
3742 );
3743
3744 $cdel = '';
3745
3746 // User can delete revisions or view deleted revisions...
3747 $canHide = $wgUser->isAllowed( 'deleterevision' );
3748 if ( $canHide || ( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3749 if ( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3750 $cdel = Linker::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3751 } else {
3752 $query = array(
3753 'type' => 'revision',
3754 'target' => $this->mTitle->getPrefixedDbkey(),
3755 'ids' => $oldid
3756 );
3757 $cdel = Linker::revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
3758 }
3759 $cdel .= ' ';
3760 }
3761
3762 # Show user links if allowed to see them. If hidden, then show them only if requested...
3763 $userlinks = Linker::revUserTools( $revision, !$unhide );
3764
3765 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
3766 ? 'revision-info-current'
3767 : 'revision-info';
3768
3769 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3770 wfMsgExt(
3771 $infomsg,
3772 array( 'parseinline', 'replaceafter' ),
3773 $td,
3774 $userlinks,
3775 $revision->getID(),
3776 $tddate,
3777 $tdtime,
3778 $revision->getUser()
3779 ) .
3780 "</div>\n" .
3781 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3782 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3783
3784 $wgOut->addHTML( $r );
3785 }
3786
3787 /**
3788 * This function is called right before saving the wikitext,
3789 * so we can do things like signatures and links-in-context.
3790 *
3791 * @param $text String article contents
3792 * @param $user User object: user doing the edit, $wgUser will be used if
3793 * null is given
3794 * @param $popts ParserOptions object: parser options, default options for
3795 * the user loaded if null given
3796 * @return string article contents with altered wikitext markup (signatures
3797 * converted, {{subst:}}, templates, etc.)
3798 */
3799 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3800 global $wgParser;
3801
3802 if ( $user === null ) {
3803 global $wgUser;
3804 $user = $wgUser;
3805 }
3806
3807 if ( $popts === null ) {
3808 $popts = ParserOptions::newFromUser( $user );
3809 }
3810
3811 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3812 }
3813
3814 /* Caching functions */
3815
3816 /**
3817 * checkLastModified returns true if it has taken care of all
3818 * output to the client that is necessary for this request.
3819 * (that is, it has sent a cached version of the page)
3820 *
3821 * @return boolean true if cached version send, false otherwise
3822 */
3823 protected function tryFileCache() {
3824 static $called = false;
3825
3826 if ( $called ) {
3827 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3828 return false;
3829 }
3830
3831 $called = true;
3832 if ( $this->isFileCacheable() ) {
3833 $cache = new HTMLFileCache( $this->mTitle );
3834 if ( $cache->isFileCacheGood( $this->mTouched ) ) {
3835 wfDebug( "Article::tryFileCache(): about to load file\n" );
3836 $cache->loadFromFileCache();
3837 return true;
3838 } else {
3839 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3840 ob_start( array( &$cache, 'saveToFileCache' ) );
3841 }
3842 } else {
3843 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3844 }
3845
3846 return false;
3847 }
3848
3849 /**
3850 * Check if the page can be cached
3851 * @return bool
3852 */
3853 public function isFileCacheable() {
3854 $cacheable = false;
3855
3856 if ( HTMLFileCache::useFileCache() ) {
3857 $cacheable = $this->getID() && !$this->mRedirectedFrom && !$this->mTitle->isRedirect();
3858 // Extension may have reason to disable file caching on some pages.
3859 if ( $cacheable ) {
3860 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3861 }
3862 }
3863
3864 return $cacheable;
3865 }
3866
3867 /**
3868 * Loads page_touched and returns a value indicating if it should be used
3869 * @return boolean true if not a redirect
3870 */
3871 public function checkTouched() {
3872 if ( !$this->mDataLoaded ) {
3873 $this->loadPageData();
3874 }
3875
3876 return !$this->mIsRedirect;
3877 }
3878
3879 /**
3880 * Get the page_touched field
3881 * @return string containing GMT timestamp
3882 */
3883 public function getTouched() {
3884 if ( !$this->mDataLoaded ) {
3885 $this->loadPageData();
3886 }
3887
3888 return $this->mTouched;
3889 }
3890
3891 /**
3892 * Get the page_latest field
3893 * @return integer rev_id of current revision
3894 */
3895 public function getLatest() {
3896 if ( !$this->mDataLoaded ) {
3897 $this->loadPageData();
3898 }
3899
3900 return (int)$this->mLatest;
3901 }
3902
3903 /**
3904 * Edit an article without doing all that other stuff
3905 * The article must already exist; link tables etc
3906 * are not updated, caches are not flushed.
3907 *
3908 * @param $text String: text submitted
3909 * @param $comment String: comment submitted
3910 * @param $minor Boolean: whereas it's a minor modification
3911 */
3912 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3913 wfProfileIn( __METHOD__ );
3914
3915 $dbw = wfGetDB( DB_MASTER );
3916 $revision = new Revision( array(
3917 'page' => $this->getId(),
3918 'text' => $text,
3919 'comment' => $comment,
3920 'minor_edit' => $minor ? 1 : 0,
3921 ) );
3922 $revision->insertOn( $dbw );
3923 $this->updateRevisionOn( $dbw, $revision );
3924
3925 global $wgUser;
3926 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3927
3928 wfProfileOut( __METHOD__ );
3929 }
3930
3931 /**
3932 * The onArticle*() functions are supposed to be a kind of hooks
3933 * which should be called whenever any of the specified actions
3934 * are done.
3935 *
3936 * This is a good place to put code to clear caches, for instance.
3937 *
3938 * This is called on page move and undelete, as well as edit
3939 *
3940 * @param $title Title object
3941 */
3942 public static function onArticleCreate( $title ) {
3943 # Update existence markers on article/talk tabs...
3944 if ( $title->isTalkPage() ) {
3945 $other = $title->getSubjectPage();
3946 } else {
3947 $other = $title->getTalkPage();
3948 }
3949
3950 $other->invalidateCache();
3951 $other->purgeSquid();
3952
3953 $title->touchLinks();
3954 $title->purgeSquid();
3955 $title->deleteTitleProtection();
3956 }
3957
3958 /**
3959 * Clears caches when article is deleted
3960 *
3961 * @param $title Title
3962 */
3963 public static function onArticleDelete( $title ) {
3964 # Update existence markers on article/talk tabs...
3965 if ( $title->isTalkPage() ) {
3966 $other = $title->getSubjectPage();
3967 } else {
3968 $other = $title->getTalkPage();
3969 }
3970
3971 $other->invalidateCache();
3972 $other->purgeSquid();
3973
3974 $title->touchLinks();
3975 $title->purgeSquid();
3976
3977 # File cache
3978 HTMLFileCache::clearFileCache( $title );
3979
3980 # Messages
3981 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3982 MessageCache::singleton()->replace( $title->getDBkey(), false );
3983 }
3984
3985 # Images
3986 if ( $title->getNamespace() == NS_FILE ) {
3987 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3988 $update->doUpdate();
3989 }
3990
3991 # User talk pages
3992 if ( $title->getNamespace() == NS_USER_TALK ) {
3993 $user = User::newFromName( $title->getText(), false );
3994 $user->setNewtalk( false );
3995 }
3996
3997 # Image redirects
3998 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3999 }
4000
4001 /**
4002 * Purge caches on page update etc
4003 *
4004 * @param $title Title object
4005 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4006 */
4007 public static function onArticleEdit( $title ) {
4008 global $wgDeferredUpdateList;
4009
4010 // Invalidate caches of articles which include this page
4011 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4012
4013 // Invalidate the caches of all pages which redirect here
4014 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4015
4016 # Purge squid for this page only
4017 $title->purgeSquid();
4018
4019 # Clear file cache for this page only
4020 HTMLFileCache::clearFileCache( $title );
4021 }
4022
4023 /**#@-*/
4024
4025 /**
4026 * Overriden by ImagePage class, only present here to avoid a fatal error
4027 * Called for ?action=revert
4028 */
4029 public function revert() {
4030 global $wgOut;
4031 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4032 }
4033
4034 /**
4035 * Info about this page
4036 * Called for ?action=info when $wgAllowPageInfo is on.
4037 */
4038 public function info() {
4039 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4040
4041 if ( !$wgAllowPageInfo ) {
4042 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4043 return;
4044 }
4045
4046 $page = $this->mTitle->getSubjectPage();
4047
4048 $wgOut->setPagetitle( $page->getPrefixedText() );
4049 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4050 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4051
4052 if ( !$this->mTitle->exists() ) {
4053 $wgOut->addHTML( '<div class="noarticletext">' );
4054 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
4055 // This doesn't quite make sense; the user is asking for
4056 // information about the _page_, not the message... -- RC
4057 $wgOut->addHTML( htmlspecialchars( $this->mTitle->getDefaultMessageText() ) );
4058 } else {
4059 $msg = $wgUser->isLoggedIn()
4060 ? 'noarticletext'
4061 : 'noarticletextanon';
4062 $wgOut->addWikiMsg( $msg );
4063 }
4064
4065 $wgOut->addHTML( '</div>' );
4066 } else {
4067 $dbr = wfGetDB( DB_SLAVE );
4068 $wl_clause = array(
4069 'wl_title' => $page->getDBkey(),
4070 'wl_namespace' => $page->getNamespace() );
4071 $numwatchers = $dbr->selectField(
4072 'watchlist',
4073 'COUNT(*)',
4074 $wl_clause,
4075 __METHOD__ );
4076
4077 $pageInfo = $this->pageCountInfo( $page );
4078 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4079
4080
4081 //FIXME: unescaped messages
4082 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4083 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4084
4085 if ( $talkInfo ) {
4086 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4087 }
4088
4089 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4090
4091 if ( $talkInfo ) {
4092 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4093 }
4094
4095 $wgOut->addHTML( '</ul>' );
4096 }
4097 }
4098
4099 /**
4100 * Return the total number of edits and number of unique editors
4101 * on a given page. If page does not exist, returns false.
4102 *
4103 * @param $title Title object
4104 * @return mixed array or boolean false
4105 */
4106 public function pageCountInfo( $title ) {
4107 $id = $title->getArticleId();
4108
4109 if ( $id == 0 ) {
4110 return false;
4111 }
4112
4113 $dbr = wfGetDB( DB_SLAVE );
4114 $rev_clause = array( 'rev_page' => $id );
4115 $edits = $dbr->selectField(
4116 'revision',
4117 'COUNT(rev_page)',
4118 $rev_clause,
4119 __METHOD__
4120 );
4121 $authors = $dbr->selectField(
4122 'revision',
4123 'COUNT(DISTINCT rev_user_text)',
4124 $rev_clause,
4125 __METHOD__
4126 );
4127
4128 return array( 'edits' => $edits, 'authors' => $authors );
4129 }
4130
4131 /**
4132 * Return a list of templates used by this article.
4133 * Uses the templatelinks table
4134 *
4135 * @return Array of Title objects
4136 */
4137 public function getUsedTemplates() {
4138 $result = array();
4139 $id = $this->mTitle->getArticleID();
4140
4141 if ( $id == 0 ) {
4142 return array();
4143 }
4144
4145 $dbr = wfGetDB( DB_SLAVE );
4146 $res = $dbr->select( array( 'templatelinks' ),
4147 array( 'tl_namespace', 'tl_title' ),
4148 array( 'tl_from' => $id ),
4149 __METHOD__ );
4150
4151 if ( $res !== false ) {
4152 foreach ( $res as $row ) {
4153 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
4154 }
4155 }
4156
4157 return $result;
4158 }
4159
4160 /**
4161 * Returns a list of hidden categories this page is a member of.
4162 * Uses the page_props and categorylinks tables.
4163 *
4164 * @return Array of Title objects
4165 */
4166 public function getHiddenCategories() {
4167 $result = array();
4168 $id = $this->mTitle->getArticleID();
4169
4170 if ( $id == 0 ) {
4171 return array();
4172 }
4173
4174 $dbr = wfGetDB( DB_SLAVE );
4175 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4176 array( 'cl_to' ),
4177 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4178 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
4179 __METHOD__ );
4180
4181 if ( $res !== false ) {
4182 foreach ( $res as $row ) {
4183 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
4184 }
4185 }
4186
4187 return $result;
4188 }
4189
4190 /**
4191 * Return an applicable autosummary if one exists for the given edit.
4192 * @param $oldtext String: the previous text of the page.
4193 * @param $newtext String: The submitted text of the page.
4194 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
4195 * @return string An appropriate autosummary, or an empty string.
4196 */
4197 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4198 global $wgContLang;
4199
4200 # Decide what kind of autosummary is needed.
4201
4202 # Redirect autosummaries
4203 $ot = Title::newFromRedirect( $oldtext );
4204 $rt = Title::newFromRedirect( $newtext );
4205
4206 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
4207 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4208 }
4209
4210 # New page autosummaries
4211 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
4212 # If they're making a new article, give its text, truncated, in the summary.
4213
4214 $truncatedtext = $wgContLang->truncate(
4215 str_replace( "\n", ' ', $newtext ),
4216 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4217
4218 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4219 }
4220
4221 # Blanking autosummaries
4222 if ( $oldtext != '' && $newtext == '' ) {
4223 return wfMsgForContent( 'autosumm-blank' );
4224 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4225 # Removing more than 90% of the article
4226
4227 $truncatedtext = $wgContLang->truncate(
4228 $newtext,
4229 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4230
4231 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4232 }
4233
4234 # If we reach this point, there's no applicable autosummary for our case, so our
4235 # autosummary is empty.
4236 return '';
4237 }
4238
4239 /**
4240 * Add the primary page-view wikitext to the output buffer
4241 * Saves the text into the parser cache if possible.
4242 * Updates templatelinks if it is out of date.
4243 *
4244 * @param $text String
4245 * @param $cache Boolean
4246 * @param $parserOptions mixed ParserOptions object, or boolean false
4247 */
4248 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4249 global $wgOut;
4250
4251 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4252 $wgOut->addParserOutput( $this->mParserOutput );
4253 }
4254
4255 /**
4256 * This does all the heavy lifting for outputWikitext, except it returns the parser
4257 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4258 * say, embedding thread pages within a discussion system (LiquidThreads)
4259 *
4260 * @param $text string
4261 * @param $cache boolean
4262 * @param $parserOptions parsing options, defaults to false
4263 * @return string containing parsed output
4264 */
4265 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4266 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4267
4268 if ( !$parserOptions ) {
4269 $parserOptions = $this->getParserOptions();
4270 }
4271
4272 $time = - wfTime();
4273 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
4274 $parserOptions, true, true, $this->getRevIdFetched() );
4275 $time += wfTime();
4276
4277 # Timing hack
4278 if ( $time > 3 ) {
4279 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4280 $this->mTitle->getPrefixedDBkey() ) );
4281 }
4282
4283 if ( $wgEnableParserCache && $cache && $this->mParserOutput->isCacheable() ) {
4284 $parserCache = ParserCache::singleton();
4285 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
4286 }
4287
4288 // Make sure file cache is not used on uncacheable content.
4289 // Output that has magic words in it can still use the parser cache
4290 // (if enabled), though it will generally expire sooner.
4291 if ( !$this->mParserOutput->isCacheable() || $this->mParserOutput->containsOldMagic() ) {
4292 $wgUseFileCache = false;
4293 }
4294
4295 $this->doCascadeProtectionUpdates( $this->mParserOutput );
4296
4297 return $this->mParserOutput;
4298 }
4299
4300 /**
4301 * Get parser options suitable for rendering the primary article wikitext
4302 * @return ParserOptions object
4303 */
4304 public function getParserOptions() {
4305 global $wgUser;
4306 if ( !$this->mParserOptions ) {
4307 $this->mParserOptions = $this->makeParserOptions( $wgUser );
4308 }
4309 // Clone to allow modifications of the return value without affecting cache
4310 return clone $this->mParserOptions;
4311 }
4312
4313 /**
4314 * Get parser options suitable for rendering the primary article wikitext
4315 * @param User $user
4316 * @return ParserOptions
4317 */
4318 public function makeParserOptions( User $user ) {
4319 $options = ParserOptions::newFromUser( $user );
4320 $options->enableLimitReport(); // show inclusion/loop reports
4321 $options->setTidy( true ); // fix bad HTML
4322 return $options;
4323 }
4324
4325 /**
4326 * Updates cascading protections
4327 *
4328 * @param $parserOutput ParserOutput object, or boolean false
4329 **/
4330 protected function doCascadeProtectionUpdates( $parserOutput ) {
4331 if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4332 return;
4333 }
4334
4335 // templatelinks table may have become out of sync,
4336 // especially if using variable-based transclusions.
4337 // For paranoia, check if things have changed and if
4338 // so apply updates to the database. This will ensure
4339 // that cascaded protections apply as soon as the changes
4340 // are visible.
4341
4342 # Get templates from templatelinks
4343 $id = $this->mTitle->getArticleID();
4344
4345 $tlTemplates = array();
4346
4347 $dbr = wfGetDB( DB_SLAVE );
4348 $res = $dbr->select( array( 'templatelinks' ),
4349 array( 'tl_namespace', 'tl_title' ),
4350 array( 'tl_from' => $id ),
4351 __METHOD__
4352 );
4353
4354 foreach ( $res as $row ) {
4355 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4356 }
4357
4358 # Get templates from parser output.
4359 $poTemplates = array();
4360 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4361 foreach ( $templates as $dbk => $id ) {
4362 $poTemplates["$ns:$dbk"] = true;
4363 }
4364 }
4365
4366 # Get the diff
4367 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4368
4369 if ( count( $templates_diff ) > 0 ) {
4370 # Whee, link updates time.
4371 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4372 $u->doUpdate();
4373 }
4374 }
4375
4376 /**
4377 * Update all the appropriate counts in the category table, given that
4378 * we've added the categories $added and deleted the categories $deleted.
4379 *
4380 * @param $added array The names of categories that were added
4381 * @param $deleted array The names of categories that were deleted
4382 */
4383 public function updateCategoryCounts( $added, $deleted ) {
4384 $ns = $this->mTitle->getNamespace();
4385 $dbw = wfGetDB( DB_MASTER );
4386
4387 # First make sure the rows exist. If one of the "deleted" ones didn't
4388 # exist, we might legitimately not create it, but it's simpler to just
4389 # create it and then give it a negative value, since the value is bogus
4390 # anyway.
4391 #
4392 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4393 $insertCats = array_merge( $added, $deleted );
4394 if ( !$insertCats ) {
4395 # Okay, nothing to do
4396 return;
4397 }
4398
4399 $insertRows = array();
4400
4401 foreach ( $insertCats as $cat ) {
4402 $insertRows[] = array(
4403 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4404 'cat_title' => $cat
4405 );
4406 }
4407 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4408
4409 $addFields = array( 'cat_pages = cat_pages + 1' );
4410 $removeFields = array( 'cat_pages = cat_pages - 1' );
4411
4412 if ( $ns == NS_CATEGORY ) {
4413 $addFields[] = 'cat_subcats = cat_subcats + 1';
4414 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4415 } elseif ( $ns == NS_FILE ) {
4416 $addFields[] = 'cat_files = cat_files + 1';
4417 $removeFields[] = 'cat_files = cat_files - 1';
4418 }
4419
4420 if ( $added ) {
4421 $dbw->update(
4422 'category',
4423 $addFields,
4424 array( 'cat_title' => $added ),
4425 __METHOD__
4426 );
4427 }
4428
4429 if ( $deleted ) {
4430 $dbw->update(
4431 'category',
4432 $removeFields,
4433 array( 'cat_title' => $deleted ),
4434 __METHOD__
4435 );
4436 }
4437 }
4438
4439 /**
4440 * Lightweight method to get the parser output for a page, checking the parser cache
4441 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4442 * consider, so it's not appropriate to use there.
4443 *
4444 * @since 1.16 (r52326) for LiquidThreads
4445 *
4446 * @param $oldid mixed integer Revision ID or null
4447 * @return ParserOutput or false if the given revsion ID is not found
4448 */
4449 public function getParserOutput( $oldid = null ) {
4450 global $wgEnableParserCache, $wgUser;
4451
4452 // Should the parser cache be used?
4453 $useParserCache = $wgEnableParserCache &&
4454 $wgUser->getStubThreshold() == 0 &&
4455 $this->exists() &&
4456 $oldid === null;
4457
4458 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4459
4460 if ( $wgUser->getStubThreshold() ) {
4461 wfIncrStats( 'pcache_miss_stub' );
4462 }
4463
4464 if ( $useParserCache ) {
4465 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4466 if ( $parserOutput !== false ) {
4467 return $parserOutput;
4468 }
4469 }
4470
4471 // Cache miss; parse and output it.
4472 if ( $oldid === null ) {
4473 $text = $this->getRawText();
4474 } else {
4475 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4476 if ( $rev === null ) {
4477 return false;
4478 }
4479 $text = $rev->getText();
4480 }
4481
4482 return $this->getOutputFromWikitext( $text, $useParserCache );
4483 }
4484
4485 /**
4486 * Sets the context this Article is executed in
4487 *
4488 * @param $context RequestContext
4489 * @since 1.18
4490 */
4491 public function setContext( $context ) {
4492 $this->mContext = $context;
4493 }
4494
4495 /**
4496 * Gets the context this Article is executed in
4497 *
4498 * @return RequestContext
4499 * @since 1.18
4500 */
4501 public function getContext() {
4502 if ( $this->mContext instanceof RequestContext ) {
4503 return $this->mContext;
4504 } else {
4505 wfDebug( __METHOD__ . " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
4506 return RequestContext::getMain();
4507 }
4508 }
4509
4510 }
4511
4512 class PoolWorkArticleView extends PoolCounterWork {
4513
4514 /**
4515 * @var Article
4516 */
4517 private $mArticle;
4518
4519 function __construct( $article, $key, $useParserCache, $parserOptions ) {
4520 parent::__construct( 'ArticleView', $key );
4521 $this->mArticle = $article;
4522 $this->cacheable = $useParserCache;
4523 $this->parserOptions = $parserOptions;
4524 }
4525
4526 function doWork() {
4527 return $this->mArticle->doViewParse();
4528 }
4529
4530 function getCachedWork() {
4531 global $wgOut;
4532
4533 $parserCache = ParserCache::singleton();
4534 $this->mArticle->mParserOutput = $parserCache->get( $this->mArticle, $this->parserOptions );
4535
4536 if ( $this->mArticle->mParserOutput !== false ) {
4537 wfDebug( __METHOD__ . ": showing contents parsed by someone else\n" );
4538 $wgOut->addParserOutput( $this->mArticle->mParserOutput );
4539 # Ensure that UI elements requiring revision ID have
4540 # the correct version information.
4541 $wgOut->setRevisionId( $this->mArticle->getLatest() );
4542 return true;
4543 }
4544 return false;
4545 }
4546
4547 function fallback() {
4548 return $this->mArticle->tryDirtyCache();
4549 }
4550
4551 /**
4552 * @param $status Status
4553 */
4554 function error( $status ) {
4555 global $wgOut;
4556
4557 $wgOut->clearHTML(); // for release() errors
4558 $wgOut->enableClientCache( false );
4559 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4560
4561 $errortext = $status->getWikiText( false, 'view-pool-error' );
4562 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );
4563
4564 return false;
4565 }
4566 }