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