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