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