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