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