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