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