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