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