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