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