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