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