(bug 672) Add MathAfterTexvc hook
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
6
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11
12 /**
13 * Class representing a MediaWiki article and history.
14 *
15 * See design.txt for an overview.
16 * Note: edit user interface and cache support functions have been
17 * moved to separate EditPage and CacheManager classes.
18 *
19 * @package MediaWiki
20 */
21 class Article {
22 /**@{{
23 * @private
24 */
25 var $mComment; //!<
26 var $mContent; //!<
27 var $mContentLoaded; //!<
28 var $mCounter; //!<
29 var $mForUpdate; //!<
30 var $mGoodAdjustment; //!<
31 var $mLatest; //!<
32 var $mMinorEdit; //!<
33 var $mOldId; //!<
34 var $mRedirectedFrom; //!<
35 var $mRedirectUrl; //!<
36 var $mRevIdFetched; //!<
37 var $mRevision; //!<
38 var $mTimestamp; //!<
39 var $mTitle; //!<
40 var $mTotalAdjustment; //!<
41 var $mTouched; //!<
42 var $mUser; //!<
43 var $mUserText; //!<
44 /**@}}*/
45
46 /**
47 * Constructor and clear the article
48 * @param $title Reference to a Title object.
49 * @param $oldId Integer revision ID, null to fetch from request, zero for current
50 */
51 function Article( &$title, $oldId = null ) {
52 $this->mTitle =& $title;
53 $this->mOldId = $oldId;
54 $this->clear();
55 }
56
57 /**
58 * Tell the page view functions that this view was redirected
59 * from another page on the wiki.
60 * @param $from Title object.
61 */
62 function setRedirectedFrom( $from ) {
63 $this->mRedirectedFrom = $from;
64 }
65
66 /**
67 * @return mixed false, Title of in-wiki target, or string with URL
68 */
69 function followRedirect() {
70 $text = $this->getContent();
71 $rt = Title::newFromRedirect( $text );
72
73 # process if title object is valid and not special:userlogout
74 if( $rt ) {
75 if( $rt->getInterwiki() != '' ) {
76 if( $rt->isLocal() ) {
77 // Offsite wikis need an HTTP redirect.
78 //
79 // This can be hard to reverse and may produce loops,
80 // so they may be disabled in the site configuration.
81
82 $source = $this->mTitle->getFullURL( 'redirect=no' );
83 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
84 }
85 } else {
86 if( $rt->getNamespace() == NS_SPECIAL ) {
87 // Gotta hand redirects to special pages differently:
88 // Fill the HTTP response "Location" header and ignore
89 // the rest of the page we're on.
90 //
91 // This can be hard to reverse, so they may be disabled.
92
93 if( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) {
94 // rolleyes
95 } else {
96 return $rt->getFullURL();
97 }
98 }
99 return $rt;
100 }
101 }
102
103 // No or invalid redirect
104 return false;
105 }
106
107 /**
108 * get the title object of the article
109 */
110 function getTitle() {
111 return $this->mTitle;
112 }
113
114 /**
115 * Clear the object
116 * @private
117 */
118 function clear() {
119 $this->mDataLoaded = false;
120 $this->mContentLoaded = false;
121
122 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
123 $this->mRedirectedFrom = null; # Title object if set
124 $this->mUserText =
125 $this->mTimestamp = $this->mComment = '';
126 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
127 $this->mTouched = '19700101000000';
128 $this->mForUpdate = false;
129 $this->mIsRedirect = false;
130 $this->mRevIdFetched = 0;
131 $this->mRedirectUrl = false;
132 $this->mLatest = false;
133 }
134
135 /**
136 * Note that getContent/loadContent do not follow redirects anymore.
137 * If you need to fetch redirectable content easily, try
138 * the shortcut in Article::followContent()
139 * FIXME
140 * @todo There are still side-effects in this!
141 * In general, you should use the Revision class, not Article,
142 * to fetch text for purposes other than page views.
143 *
144 * @return Return the text of this revision
145 */
146 function getContent() {
147 global $wgRequest, $wgUser, $wgOut;
148
149 # Get variables from query string :P
150 $action = $wgRequest->getText( 'action', 'view' );
151 $section = $wgRequest->getText( 'section' );
152 $preload = $wgRequest->getText( 'preload' );
153
154 wfProfileIn( __METHOD__ );
155
156 if ( 0 == $this->getID() ) {
157 if ( 'edit' == $action ) {
158 wfProfileOut( __METHOD__ );
159
160 # If requested, preload some text.
161 $text=$this->getPreloadedText($preload);
162
163 # We used to put MediaWiki:Newarticletext here if
164 # $text was empty at this point.
165 # This is now shown above the edit box instead.
166 return $text;
167 }
168 wfProfileOut( __METHOD__ );
169 $wgOut->setRobotpolicy( 'noindex,nofollow' );
170
171 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
172 $ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
173 } else {
174 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
175 }
176
177 return "<div class='noarticletext'>$ret</div>";
178 } else {
179 $this->loadContent();
180 if($action=='edit') {
181 if($section!='') {
182 if($section=='new') {
183 wfProfileOut( __METHOD__ );
184 $text=$this->getPreloadedText($preload);
185 return $text;
186 }
187
188 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
189 # comments to be stripped as well)
190 $rv=$this->getSection($this->mContent,$section);
191 wfProfileOut( __METHOD__ );
192 return $rv;
193 }
194 }
195 wfProfileOut( __METHOD__ );
196 return $this->mContent;
197 }
198 }
199
200 /**
201 * Get the contents of a page from its title and remove includeonly tags
202 *
203 * @param $preload String: the title of the page.
204 * @return string The contents of the page.
205 */
206 function getPreloadedText($preload) {
207 if ( $preload === '' )
208 return '';
209 else {
210 $preloadTitle = Title::newFromText( $preload );
211 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
212 $rev=Revision::newFromTitle($preloadTitle);
213 if ( is_object( $rev ) ) {
214 $text = $rev->getText();
215 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
216 // its own mini-parser! -ævar
217 $text = preg_replace( '~</?includeonly>~', '', $text );
218 return $text;
219 } else
220 return '';
221 }
222 }
223 }
224
225 /**
226 * This function returns the text of a section, specified by a number ($section).
227 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
228 * the first section before any such heading (section 0).
229 *
230 * If a section contains subsections, these are also returned.
231 *
232 * @param $text String: text to look in
233 * @param $section Integer: section number
234 * @return string text of the requested section
235 */
236 function getSection($text,$section) {
237 global $wgParser;
238 return $wgParser->getSection( $text, $section );
239 }
240
241 /**
242 * @return int The oldid of the article that is to be shown, 0 for the
243 * current revision
244 */
245 function getOldID() {
246 if ( is_null( $this->mOldId ) ) {
247 $this->mOldId = $this->getOldIDFromRequest();
248 }
249 return $this->mOldId;
250 }
251
252 /**
253 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
254 *
255 * @return int The old id for the request
256 */
257 function getOldIDFromRequest() {
258 global $wgRequest;
259 $this->mRedirectUrl = false;
260 $oldid = $wgRequest->getVal( 'oldid' );
261 if ( isset( $oldid ) ) {
262 $oldid = intval( $oldid );
263 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
264 $nextid = $this->mTitle->getNextRevisionID( $oldid );
265 if ( $nextid ) {
266 $oldid = $nextid;
267 } else {
268 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
269 }
270 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
271 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
272 if ( $previd ) {
273 $oldid = $previd;
274 } else {
275 # TODO
276 }
277 }
278 # unused:
279 # $lastid = $oldid;
280 }
281 if ( !$oldid ) {
282 $oldid = 0;
283 }
284 return $oldid;
285 }
286
287 /**
288 * Load the revision (including text) into this object
289 */
290 function loadContent() {
291 if ( $this->mContentLoaded ) return;
292
293 # Query variables :P
294 $oldid = $this->getOldID();
295
296 # Pre-fill content with error message so that if something
297 # fails we'll have something telling us what we intended.
298
299 $t = $this->mTitle->getPrefixedText();
300
301 $this->mOldId = $oldid;
302 $this->fetchContent( $oldid );
303 }
304
305
306 /**
307 * Fetch a page record with the given conditions
308 * @param Database $dbr
309 * @param array $conditions
310 * @private
311 */
312 function pageData( &$dbr, $conditions ) {
313 $fields = array(
314 'page_id',
315 'page_namespace',
316 'page_title',
317 'page_restrictions',
318 'page_counter',
319 'page_is_redirect',
320 'page_is_new',
321 'page_random',
322 'page_touched',
323 'page_latest',
324 'page_len' ) ;
325 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
326 $row = $dbr->selectRow( 'page',
327 $fields,
328 $conditions,
329 'Article::pageData' );
330 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
331 return $row ;
332 }
333
334 /**
335 * @param Database $dbr
336 * @param Title $title
337 */
338 function pageDataFromTitle( &$dbr, $title ) {
339 return $this->pageData( $dbr, array(
340 'page_namespace' => $title->getNamespace(),
341 'page_title' => $title->getDBkey() ) );
342 }
343
344 /**
345 * @param Database $dbr
346 * @param int $id
347 */
348 function pageDataFromId( &$dbr, $id ) {
349 return $this->pageData( $dbr, array( 'page_id' => $id ) );
350 }
351
352 /**
353 * Set the general counter, title etc data loaded from
354 * some source.
355 *
356 * @param object $data
357 * @private
358 */
359 function loadPageData( $data = 'fromdb' ) {
360 if ( $data === 'fromdb' ) {
361 $dbr =& $this->getDB();
362 $data = $this->pageDataFromId( $dbr, $this->getId() );
363 }
364
365 $lc =& LinkCache::singleton();
366 if ( $data ) {
367 $lc->addGoodLinkObj( $data->page_id, $this->mTitle );
368
369 $this->mTitle->mArticleID = $data->page_id;
370 $this->mTitle->loadRestrictions( $data->page_restrictions );
371 $this->mTitle->mRestrictionsLoaded = true;
372
373 $this->mCounter = $data->page_counter;
374 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
375 $this->mIsRedirect = $data->page_is_redirect;
376 $this->mLatest = $data->page_latest;
377 } else {
378 if ( is_object( $this->mTitle ) ) {
379 $lc->addBadLinkObj( $this->mTitle );
380 }
381 $this->mTitle->mArticleID = 0;
382 }
383
384 $this->mDataLoaded = true;
385 }
386
387 /**
388 * Get text of an article from database
389 * Does *NOT* follow redirects.
390 * @param int $oldid 0 for whatever the latest revision is
391 * @return string
392 */
393 function fetchContent( $oldid = 0 ) {
394 if ( $this->mContentLoaded ) {
395 return $this->mContent;
396 }
397
398 $dbr =& $this->getDB();
399
400 # Pre-fill content with error message so that if something
401 # fails we'll have something telling us what we intended.
402 $t = $this->mTitle->getPrefixedText();
403 if( $oldid ) {
404 $t .= ',oldid='.$oldid;
405 }
406 $this->mContent = wfMsg( 'missingarticle', $t ) ;
407
408 if( $oldid ) {
409 $revision = Revision::newFromId( $oldid );
410 if( is_null( $revision ) ) {
411 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
412 return false;
413 }
414 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
415 if( !$data ) {
416 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
417 return false;
418 }
419 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
420 $this->loadPageData( $data );
421 } else {
422 if( !$this->mDataLoaded ) {
423 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
424 if( !$data ) {
425 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
426 return false;
427 }
428 $this->loadPageData( $data );
429 }
430 $revision = Revision::newFromId( $this->mLatest );
431 if( is_null( $revision ) ) {
432 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$data->page_latest}\n" );
433 return false;
434 }
435 }
436
437 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
438 // We should instead work with the Revision object when we need it...
439 $this->mContent = $revision->userCan( Revision::DELETED_TEXT ) ? $revision->getRawText() : "";
440 //$this->mContent = $revision->getText();
441
442 $this->mUser = $revision->getUser();
443 $this->mUserText = $revision->getUserText();
444 $this->mComment = $revision->getComment();
445 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
446
447 $this->mRevIdFetched = $revision->getID();
448 $this->mContentLoaded = true;
449 $this->mRevision =& $revision;
450
451 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
452
453 return $this->mContent;
454 }
455
456 /**
457 * Read/write accessor to select FOR UPDATE
458 *
459 * @param $x Mixed: FIXME
460 */
461 function forUpdate( $x = NULL ) {
462 return wfSetVar( $this->mForUpdate, $x );
463 }
464
465 /**
466 * Get the database which should be used for reads
467 *
468 * @return Database
469 */
470 function &getDB() {
471 $ret =& wfGetDB( DB_MASTER );
472 return $ret;
473 }
474
475 /**
476 * Get options for all SELECT statements
477 *
478 * @param $options Array: an optional options array which'll be appended to
479 * the default
480 * @return Array: options
481 */
482 function getSelectOptions( $options = '' ) {
483 if ( $this->mForUpdate ) {
484 if ( is_array( $options ) ) {
485 $options[] = 'FOR UPDATE';
486 } else {
487 $options = 'FOR UPDATE';
488 }
489 }
490 return $options;
491 }
492
493 /**
494 * @return int Page ID
495 */
496 function getID() {
497 if( $this->mTitle ) {
498 return $this->mTitle->getArticleID();
499 } else {
500 return 0;
501 }
502 }
503
504 /**
505 * @return bool Whether or not the page exists in the database
506 */
507 function exists() {
508 return $this->getId() != 0;
509 }
510
511 /**
512 * @return int The view count for the page
513 */
514 function getCount() {
515 if ( -1 == $this->mCounter ) {
516 $id = $this->getID();
517 if ( $id == 0 ) {
518 $this->mCounter = 0;
519 } else {
520 $dbr =& wfGetDB( DB_SLAVE );
521 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
522 'Article::getCount', $this->getSelectOptions() );
523 }
524 }
525 return $this->mCounter;
526 }
527
528 /**
529 * Determine whether a page would be suitable for being counted as an
530 * article in the site_stats table based on the title & its content
531 *
532 * @param $text String: text to analyze
533 * @return bool
534 */
535 function isCountable( $text ) {
536 global $wgUseCommaCount, $wgContentNamespaces;
537
538 $token = $wgUseCommaCount ? ',' : '[[';
539 return
540 array_search( $this->mTitle->getNamespace(), $wgContentNamespaces ) !== false
541 && ! $this->isRedirect( $text )
542 && in_string( $token, $text );
543 }
544
545 /**
546 * Tests if the article text represents a redirect
547 *
548 * @param $text String: FIXME
549 * @return bool
550 */
551 function isRedirect( $text = false ) {
552 if ( $text === false ) {
553 $this->loadContent();
554 $titleObj = Title::newFromRedirect( $this->fetchContent() );
555 } else {
556 $titleObj = Title::newFromRedirect( $text );
557 }
558 return $titleObj !== NULL;
559 }
560
561 /**
562 * Returns true if the currently-referenced revision is the current edit
563 * to this page (and it exists).
564 * @return bool
565 */
566 function isCurrent() {
567 return $this->exists() &&
568 isset( $this->mRevision ) &&
569 $this->mRevision->isCurrent();
570 }
571
572 /**
573 * Loads everything except the text
574 * This isn't necessary for all uses, so it's only done if needed.
575 * @private
576 */
577 function loadLastEdit() {
578 if ( -1 != $this->mUser )
579 return;
580
581 # New or non-existent articles have no user information
582 $id = $this->getID();
583 if ( 0 == $id ) return;
584
585 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
586 if( !is_null( $this->mLastRevision ) ) {
587 $this->mUser = $this->mLastRevision->getUser();
588 $this->mUserText = $this->mLastRevision->getUserText();
589 $this->mTimestamp = $this->mLastRevision->getTimestamp();
590 $this->mComment = $this->mLastRevision->getComment();
591 $this->mMinorEdit = $this->mLastRevision->isMinor();
592 $this->mRevIdFetched = $this->mLastRevision->getID();
593 }
594 }
595
596 function getTimestamp() {
597 // Check if the field has been filled by ParserCache::get()
598 if ( !$this->mTimestamp ) {
599 $this->loadLastEdit();
600 }
601 return wfTimestamp(TS_MW, $this->mTimestamp);
602 }
603
604 function getUser() {
605 $this->loadLastEdit();
606 return $this->mUser;
607 }
608
609 function getUserText() {
610 $this->loadLastEdit();
611 return $this->mUserText;
612 }
613
614 function getComment() {
615 $this->loadLastEdit();
616 return $this->mComment;
617 }
618
619 function getMinorEdit() {
620 $this->loadLastEdit();
621 return $this->mMinorEdit;
622 }
623
624 function getRevIdFetched() {
625 $this->loadLastEdit();
626 return $this->mRevIdFetched;
627 }
628
629 /**
630 * @todo Document, fixme $offset never used.
631 * @param $limit Integer: default 0.
632 * @param $offset Integer: default 0.
633 */
634 function getContributors($limit = 0, $offset = 0) {
635 # XXX: this is expensive; cache this info somewhere.
636
637 $title = $this->mTitle;
638 $contribs = array();
639 $dbr =& wfGetDB( DB_SLAVE );
640 $revTable = $dbr->tableName( 'revision' );
641 $userTable = $dbr->tableName( 'user' );
642 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
643 $ns = $title->getNamespace();
644 $user = $this->getUser();
645 $pageId = $this->getId();
646
647 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
648 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
649 WHERE rev_page = $pageId
650 AND rev_user != $user
651 GROUP BY rev_user, rev_user_text, user_real_name
652 ORDER BY timestamp DESC";
653
654 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
655 $sql .= ' '. $this->getSelectOptions();
656
657 $res = $dbr->query($sql, __METHOD__);
658
659 while ( $line = $dbr->fetchObject( $res ) ) {
660 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
661 }
662
663 $dbr->freeResult($res);
664 return $contribs;
665 }
666
667 /**
668 * This is the default action of the script: just view the page of
669 * the given title.
670 */
671 function view() {
672 global $wgUser, $wgOut, $wgRequest, $wgContLang;
673 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
674 global $wgUseTrackbacks, $wgNamespaceRobotPolicies;
675 $sk = $wgUser->getSkin();
676
677 wfProfileIn( __METHOD__ );
678
679 $parserCache =& ParserCache::singleton();
680 $ns = $this->mTitle->getNamespace(); # shortcut
681
682 # Get variables from query string
683 $oldid = $this->getOldID();
684
685 # getOldID may want us to redirect somewhere else
686 if ( $this->mRedirectUrl ) {
687 $wgOut->redirect( $this->mRedirectUrl );
688 wfProfileOut( __METHOD__ );
689 return;
690 }
691
692 $diff = $wgRequest->getVal( 'diff' );
693 $rcid = $wgRequest->getVal( 'rcid' );
694 $rdfrom = $wgRequest->getVal( 'rdfrom' );
695
696 $wgOut->setArticleFlag( true );
697 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
698 $policy = $wgNamespaceRobotPolicies[$ns];
699 } else {
700 $policy = 'index,follow';
701 }
702 $wgOut->setRobotpolicy( $policy );
703
704 # If we got diff and oldid in the query, we want to see a
705 # diff page instead of the article.
706
707 if ( !is_null( $diff ) ) {
708 require_once( 'DifferenceEngine.php' );
709 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
710
711 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid );
712 // DifferenceEngine directly fetched the revision:
713 $this->mRevIdFetched = $de->mNewid;
714 $de->showDiffPage();
715
716 if( $diff == 0 ) {
717 # Run view updates for current revision only
718 $this->viewUpdates();
719 }
720 wfProfileOut( __METHOD__ );
721 return;
722 }
723
724 if ( empty( $oldid ) && $this->checkTouched() ) {
725 $wgOut->setETag($parserCache->getETag($this, $wgUser));
726
727 if( $wgOut->checkLastModified( $this->mTouched ) ){
728 wfProfileOut( __METHOD__ );
729 return;
730 } else if ( $this->tryFileCache() ) {
731 # tell wgOut that output is taken care of
732 $wgOut->disable();
733 $this->viewUpdates();
734 wfProfileOut( __METHOD__ );
735 return;
736 }
737 }
738 # Should the parser cache be used?
739 $pcache = $wgEnableParserCache &&
740 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
741 $this->exists() &&
742 empty( $oldid );
743 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
744 if ( $wgUser->getOption( 'stubthreshold' ) ) {
745 wfIncrStats( 'pcache_miss_stub' );
746 }
747
748 $wasRedirected = false;
749 if ( isset( $this->mRedirectedFrom ) ) {
750 // This is an internally redirected page view.
751 // We'll need a backlink to the source page for navigation.
752 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
753 $sk = $wgUser->getSkin();
754 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
755 $s = wfMsg( 'redirectedfrom', $redir );
756 $wgOut->setSubtitle( $s );
757 $wasRedirected = true;
758 }
759 } elseif ( !empty( $rdfrom ) ) {
760 // This is an externally redirected view, from some other wiki.
761 // If it was reported from a trusted site, supply a backlink.
762 global $wgRedirectSources;
763 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
764 $sk = $wgUser->getSkin();
765 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
766 $s = wfMsg( 'redirectedfrom', $redir );
767 $wgOut->setSubtitle( $s );
768 $wasRedirected = true;
769 }
770 }
771
772 $outputDone = false;
773 if ( $pcache ) {
774 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
775 $outputDone = true;
776 }
777 }
778 if ( !$outputDone ) {
779 $text = $this->getContent();
780 if ( $text === false ) {
781 # Failed to load, replace text with error message
782 $t = $this->mTitle->getPrefixedText();
783 if( $oldid ) {
784 $t .= ',oldid='.$oldid;
785 $text = wfMsg( 'missingarticle', $t );
786 } else {
787 $text = wfMsg( 'noarticletext', $t );
788 }
789 }
790
791 # Another whitelist check in case oldid is altering the title
792 if ( !$this->mTitle->userCanRead() ) {
793 $wgOut->loginToUse();
794 $wgOut->output();
795 exit;
796 }
797
798 # We're looking at an old revision
799
800 if ( !empty( $oldid ) ) {
801 $wgOut->setRobotpolicy( 'noindex,nofollow' );
802 if( is_null( $this->mRevision ) ) {
803 // FIXME: This would be a nice place to load the 'no such page' text.
804 } else {
805 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
806 if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
807 if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
808 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
809 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
810 return;
811 } else {
812 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
813 // and we are allowed to see...
814 }
815 }
816 }
817
818 }
819 }
820 if( !$outputDone ) {
821 /**
822 * @fixme: this hook doesn't work most of the time, as it doesn't
823 * trigger when the parser cache is used.
824 */
825 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
826 $wgOut->setRevisionId( $this->getRevIdFetched() );
827 # wrap user css and user js in pre and don't parse
828 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
829 if (
830 $ns == NS_USER &&
831 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
832 ) {
833 $wgOut->addWikiText( wfMsg('clearyourcache'));
834 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
835 } else if ( $rt = Title::newFromRedirect( $text ) ) {
836 # Display redirect
837 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
838 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
839 # Don't overwrite the subtitle if this was an old revision
840 if( !$wasRedirected && $this->isCurrent() ) {
841 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
842 }
843 $targetUrl = $rt->escapeLocalURL();
844 # fixme unused $titleText :
845 $titleText = htmlspecialchars( $rt->getPrefixedText() );
846 $link = $sk->makeLinkObj( $rt );
847
848 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
849 '<span class="redirectText">'.$link.'</span>' );
850
851 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
852 $wgOut->addParserOutputNoText( $parseout );
853 } else if ( $pcache ) {
854 # Display content and save to parser cache
855 $wgOut->addPrimaryWikiText( $text, $this );
856 } else {
857 # Display content, don't attempt to save to parser cache
858 # Don't show section-edit links on old revisions... this way lies madness.
859 if( !$this->isCurrent() ) {
860 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
861 }
862 # Display content and don't save to parser cache
863 $wgOut->addPrimaryWikiText( $text, $this, false );
864
865 if( !$this->isCurrent() ) {
866 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
867 }
868 }
869 }
870 /* title may have been set from the cache */
871 $t = $wgOut->getPageTitle();
872 if( empty( $t ) ) {
873 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
874 }
875
876 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
877 if( $ns == NS_USER_TALK &&
878 User::isIP( $this->mTitle->getText() ) ) {
879 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
880 }
881
882 # If we have been passed an &rcid= parameter, we want to give the user a
883 # chance to mark this new article as patrolled.
884 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
885 $wgOut->addHTML(
886 "<div class='patrollink'>" .
887 wfMsg ( 'markaspatrolledlink',
888 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
889 ) .
890 '</div>'
891 );
892 }
893
894 # Trackbacks
895 if ($wgUseTrackbacks)
896 $this->addTrackbacks();
897
898 $this->viewUpdates();
899 wfProfileOut( __METHOD__ );
900 }
901
902 function addTrackbacks() {
903 global $wgOut, $wgUser;
904
905 $dbr =& wfGetDB(DB_SLAVE);
906 $tbs = $dbr->select(
907 /* FROM */ 'trackbacks',
908 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
909 /* WHERE */ array('tb_page' => $this->getID())
910 );
911
912 if (!$dbr->numrows($tbs))
913 return;
914
915 $tbtext = "";
916 while ($o = $dbr->fetchObject($tbs)) {
917 $rmvtxt = "";
918 if ($wgUser->isAllowed( 'trackback' )) {
919 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
920 . $o->tb_id . "&token=" . $wgUser->editToken());
921 $rmvtxt = wfMsg('trackbackremove', $delurl);
922 }
923 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
924 $o->tb_title,
925 $o->tb_url,
926 $o->tb_ex,
927 $o->tb_name,
928 $rmvtxt);
929 }
930 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
931 }
932
933 function deletetrackback() {
934 global $wgUser, $wgRequest, $wgOut, $wgTitle;
935
936 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
937 $wgOut->addWikitext(wfMsg('sessionfailure'));
938 return;
939 }
940
941 if ((!$wgUser->isAllowed('delete'))) {
942 $wgOut->sysopRequired();
943 return;
944 }
945
946 if (wfReadOnly()) {
947 $wgOut->readOnlyPage();
948 return;
949 }
950
951 $db =& wfGetDB(DB_MASTER);
952 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
953 $wgTitle->invalidateCache();
954 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
955 }
956
957 function render() {
958 global $wgOut;
959
960 $wgOut->setArticleBodyOnly(true);
961 $this->view();
962 }
963
964 /**
965 * Handle action=purge
966 */
967 function purge() {
968 global $wgUser, $wgRequest, $wgOut;
969
970 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
971 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
972 $this->doPurge();
973 }
974 } else {
975 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
976 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
977 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
978 $msg = str_replace( '$1',
979 "<form method=\"post\" action=\"$action\">\n" .
980 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
981 "</form>\n", $msg );
982
983 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
984 $wgOut->setRobotpolicy( 'noindex,nofollow' );
985 $wgOut->addHTML( $msg );
986 }
987 }
988
989 /**
990 * Perform the actions of a page purging
991 */
992 function doPurge() {
993 global $wgUseSquid;
994 // Invalidate the cache
995 $this->mTitle->invalidateCache();
996
997 if ( $wgUseSquid ) {
998 // Commit the transaction before the purge is sent
999 $dbw = wfGetDB( DB_MASTER );
1000 $dbw->immediateCommit();
1001
1002 // Send purge
1003 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1004 $update->doUpdate();
1005 }
1006 $this->view();
1007 }
1008
1009 /**
1010 * Insert a new empty page record for this article.
1011 * This *must* be followed up by creating a revision
1012 * and running $this->updateToLatest( $rev_id );
1013 * or else the record will be left in a funky state.
1014 * Best if all done inside a transaction.
1015 *
1016 * @param Database $dbw
1017 * @param string $restrictions
1018 * @return int The newly created page_id key
1019 * @private
1020 */
1021 function insertOn( &$dbw, $restrictions = '' ) {
1022 wfProfileIn( __METHOD__ );
1023
1024 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1025 $dbw->insert( 'page', array(
1026 'page_id' => $page_id,
1027 'page_namespace' => $this->mTitle->getNamespace(),
1028 'page_title' => $this->mTitle->getDBkey(),
1029 'page_counter' => 0,
1030 'page_restrictions' => $restrictions,
1031 'page_is_redirect' => 0, # Will set this shortly...
1032 'page_is_new' => 1,
1033 'page_random' => wfRandom(),
1034 'page_touched' => $dbw->timestamp(),
1035 'page_latest' => 0, # Fill this in shortly...
1036 'page_len' => 0, # Fill this in shortly...
1037 ), __METHOD__ );
1038 $newid = $dbw->insertId();
1039
1040 $this->mTitle->resetArticleId( $newid );
1041
1042 wfProfileOut( __METHOD__ );
1043 return $newid;
1044 }
1045
1046 /**
1047 * Update the page record to point to a newly saved revision.
1048 *
1049 * @param Database $dbw
1050 * @param Revision $revision For ID number, and text used to set
1051 length and redirect status fields
1052 * @param int $lastRevision If given, will not overwrite the page field
1053 * when different from the currently set value.
1054 * Giving 0 indicates the new page flag should
1055 * be set on.
1056 * @return bool true on success, false on failure
1057 * @private
1058 */
1059 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1060 wfProfileIn( __METHOD__ );
1061
1062 $conditions = array( 'page_id' => $this->getId() );
1063 if( !is_null( $lastRevision ) ) {
1064 # An extra check against threads stepping on each other
1065 $conditions['page_latest'] = $lastRevision;
1066 }
1067
1068 $text = $revision->getText();
1069 $dbw->update( 'page',
1070 array( /* SET */
1071 'page_latest' => $revision->getId(),
1072 'page_touched' => $dbw->timestamp(),
1073 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1074 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1075 'page_len' => strlen( $text ),
1076 ),
1077 $conditions,
1078 __METHOD__ );
1079
1080 wfProfileOut( __METHOD__ );
1081 return ( $dbw->affectedRows() != 0 );
1082 }
1083
1084 /**
1085 * If the given revision is newer than the currently set page_latest,
1086 * update the page record. Otherwise, do nothing.
1087 *
1088 * @param Database $dbw
1089 * @param Revision $revision
1090 */
1091 function updateIfNewerOn( &$dbw, $revision ) {
1092 wfProfileIn( __METHOD__ );
1093
1094 $row = $dbw->selectRow(
1095 array( 'revision', 'page' ),
1096 array( 'rev_id', 'rev_timestamp' ),
1097 array(
1098 'page_id' => $this->getId(),
1099 'page_latest=rev_id' ),
1100 __METHOD__ );
1101 if( $row ) {
1102 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1103 wfProfileOut( __METHOD__ );
1104 return false;
1105 }
1106 $prev = $row->rev_id;
1107 } else {
1108 # No or missing previous revision; mark the page as new
1109 $prev = 0;
1110 }
1111
1112 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1113 wfProfileOut( __METHOD__ );
1114 return $ret;
1115 }
1116
1117 /**
1118 * @return string Complete article text, or null if error
1119 */
1120 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1121 wfProfileIn( __METHOD__ );
1122
1123 if( $section == '' ) {
1124 // Whole-page edit; let the text through unmolested.
1125 } else {
1126 if( is_null( $edittime ) ) {
1127 $rev = Revision::newFromTitle( $this->mTitle );
1128 } else {
1129 $dbw =& wfGetDB( DB_MASTER );
1130 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1131 }
1132 if( is_null( $rev ) ) {
1133 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1134 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1135 return null;
1136 }
1137 $oldtext = $rev->getText();
1138
1139 if($section=='new') {
1140 if($summary) $subject="== {$summary} ==\n\n";
1141 $text=$oldtext."\n\n".$subject.$text;
1142 } else {
1143 global $wgParser;
1144 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1145 }
1146 }
1147
1148 wfProfileOut( __METHOD__ );
1149 return $text;
1150 }
1151
1152 /**
1153 * @deprecated use Article::doEdit()
1154 */
1155 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1156 $flags = EDIT_NEW | EDIT_DEFER_UPDATES |
1157 ( $isminor ? EDIT_MINOR : 0 ) |
1158 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 );
1159
1160 # If this is a comment, add the summary as headline
1161 if ( $comment && $summary != "" ) {
1162 $text = "== {$summary} ==\n\n".$text;
1163 }
1164
1165 $this->doEdit( $text, $summary, $flags );
1166
1167 $dbw =& wfGetDB( DB_MASTER );
1168 if ($watchthis) {
1169 if (!$this->mTitle->userIsWatching()) {
1170 $dbw->begin();
1171 $this->doWatch();
1172 $dbw->commit();
1173 }
1174 } else {
1175 if ( $this->mTitle->userIsWatching() ) {
1176 $dbw->begin();
1177 $this->doUnwatch();
1178 $dbw->commit();
1179 }
1180 }
1181 $this->doRedirect( $this->isRedirect( $text ) );
1182 }
1183
1184 /**
1185 * @deprecated use Article::doEdit()
1186 */
1187 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1188 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES |
1189 ( $minor ? EDIT_MINOR : 0 ) |
1190 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1191
1192 $good = $this->doEdit( $text, $summary, $flags );
1193 if ( $good ) {
1194 $dbw =& wfGetDB( DB_MASTER );
1195 if ($watchthis) {
1196 if (!$this->mTitle->userIsWatching()) {
1197 $dbw->begin();
1198 $this->doWatch();
1199 $dbw->commit();
1200 }
1201 } else {
1202 if ( $this->mTitle->userIsWatching() ) {
1203 $dbw->begin();
1204 $this->doUnwatch();
1205 $dbw->commit();
1206 }
1207 }
1208
1209 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1210 }
1211 return $good;
1212 }
1213
1214 /**
1215 * Article::doEdit()
1216 *
1217 * Change an existing article or create a new article. Updates RC and all necessary caches,
1218 * optionally via the deferred update array.
1219 *
1220 * $wgUser must be set before calling this function.
1221 *
1222 * @param string $text New text
1223 * @param string $summary Edit summary
1224 * @param integer $flags bitfield:
1225 * EDIT_NEW
1226 * Article is known or assumed to be non-existent, create a new one
1227 * EDIT_UPDATE
1228 * Article is known or assumed to be pre-existing, update it
1229 * EDIT_MINOR
1230 * Mark this edit minor, if the user is allowed to do so
1231 * EDIT_SUPPRESS_RC
1232 * Do not log the change in recentchanges
1233 * EDIT_FORCE_BOT
1234 * Mark the edit a "bot" edit regardless of user rights
1235 * EDIT_DEFER_UPDATES
1236 * Defer some of the updates until the end of index.php
1237 *
1238 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1239 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1240 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1241 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1242 * to MediaWiki's performance-optimised locking strategy.
1243 *
1244 * @return bool success
1245 */
1246 function doEdit( $text, $summary, $flags = 0 ) {
1247 global $wgUser, $wgDBtransactions;
1248
1249 wfProfileIn( __METHOD__ );
1250 $good = true;
1251
1252 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1253 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1254 if ( $aid ) {
1255 $flags |= EDIT_UPDATE;
1256 } else {
1257 $flags |= EDIT_NEW;
1258 }
1259 }
1260
1261 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1262 &$summary, $flags & EDIT_MINOR,
1263 null, null, &$flags ) ) )
1264 {
1265 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1266 wfProfileOut( __METHOD__ );
1267 return false;
1268 }
1269
1270 # Silently ignore EDIT_MINOR if not allowed
1271 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1272 $bot = $wgUser->isBot() || ( $flags & EDIT_FORCE_BOT );
1273
1274 $text = $this->preSaveTransform( $text );
1275
1276 $dbw =& wfGetDB( DB_MASTER );
1277 $now = wfTimestampNow();
1278
1279 if ( $flags & EDIT_UPDATE ) {
1280 # Update article, but only if changed.
1281
1282 # Make sure the revision is either completely inserted or not inserted at all
1283 if( !$wgDBtransactions ) {
1284 $userAbort = ignore_user_abort( true );
1285 }
1286
1287 $oldtext = $this->getContent();
1288 $oldsize = strlen( $oldtext );
1289 $newsize = strlen( $text );
1290 $lastRevision = 0;
1291 $revisionId = 0;
1292
1293 if ( 0 != strcmp( $text, $oldtext ) ) {
1294 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1295 - (int)$this->isCountable( $oldtext );
1296 $this->mTotalAdjustment = 0;
1297
1298 $lastRevision = $dbw->selectField(
1299 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1300
1301 if ( !$lastRevision ) {
1302 # Article gone missing
1303 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1304 wfProfileOut( __METHOD__ );
1305 return false;
1306 }
1307
1308 $revision = new Revision( array(
1309 'page' => $this->getId(),
1310 'comment' => $summary,
1311 'minor_edit' => $isminor,
1312 'text' => $text
1313 ) );
1314
1315 $dbw->begin();
1316 $revisionId = $revision->insertOn( $dbw );
1317
1318 # Update page
1319 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1320
1321 if( !$ok ) {
1322 /* Belated edit conflict! Run away!! */
1323 $good = false;
1324 $dbw->rollback();
1325 } else {
1326 # Update recentchanges
1327 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1328 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1329 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1330 $revisionId );
1331
1332 # Mark as patrolled if the user can do so and has it set in their options
1333 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1334 RecentChange::markPatrolled( $rcid );
1335 }
1336 }
1337 $dbw->commit();
1338 }
1339 } else {
1340 // Keep the same revision ID, but do some updates on it
1341 $revisionId = $this->getRevIdFetched();
1342 // Update page_touched, this is usually implicit in the page update
1343 // Other cache updates are done in onArticleEdit()
1344 $this->mTitle->invalidateCache();
1345 }
1346
1347 if( !$wgDBtransactions ) {
1348 ignore_user_abort( $userAbort );
1349 }
1350
1351 if ( $good ) {
1352 # Invalidate cache of this article and all pages using this article
1353 # as a template. Partly deferred.
1354 Article::onArticleEdit( $this->mTitle );
1355
1356 # Update links tables, site stats, etc.
1357 $changed = ( strcmp( $oldtext, $text ) != 0 );
1358 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1359 }
1360 } else {
1361 # Create new article
1362
1363 # Set statistics members
1364 # We work out if it's countable after PST to avoid counter drift
1365 # when articles are created with {{subst:}}
1366 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1367 $this->mTotalAdjustment = 1;
1368
1369 $dbw->begin();
1370
1371 # Add the page record; stake our claim on this title!
1372 # This will fail with a database query exception if the article already exists
1373 $newid = $this->insertOn( $dbw );
1374
1375 # Save the revision text...
1376 $revision = new Revision( array(
1377 'page' => $newid,
1378 'comment' => $summary,
1379 'minor_edit' => $isminor,
1380 'text' => $text
1381 ) );
1382 $revisionId = $revision->insertOn( $dbw );
1383
1384 $this->mTitle->resetArticleID( $newid );
1385
1386 # Update the page record with revision data
1387 $this->updateRevisionOn( $dbw, $revision, 0 );
1388
1389 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1390 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1391 '', strlen( $text ), $revisionId );
1392 # Mark as patrolled if the user can and has the option set
1393 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1394 RecentChange::markPatrolled( $rcid );
1395 }
1396 }
1397 $dbw->commit();
1398
1399 # Update links, etc.
1400 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1401
1402 # Clear caches
1403 Article::onArticleCreate( $this->mTitle );
1404
1405 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1406 $summary, $flags & EDIT_MINOR,
1407 null, null, &$flags ) );
1408 }
1409
1410 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1411 wfDoUpdates();
1412 }
1413
1414 wfRunHooks( 'ArticleSaveComplete',
1415 array( &$this, &$wgUser, $text,
1416 $summary, $flags & EDIT_MINOR,
1417 null, null, &$flags ) );
1418
1419 wfProfileOut( __METHOD__ );
1420 return $good;
1421 }
1422
1423 /**
1424 * @deprecated wrapper for doRedirect
1425 */
1426 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1427 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1428 }
1429
1430 /**
1431 * Output a redirect back to the article.
1432 * This is typically used after an edit.
1433 *
1434 * @param boolean $noRedir Add redirect=no
1435 * @param string $sectionAnchor section to redirect to, including "#"
1436 */
1437 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1438 global $wgOut;
1439 if ( $noRedir ) {
1440 $query = 'redirect=no';
1441 } else {
1442 $query = '';
1443 }
1444 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1445 }
1446
1447 /**
1448 * Mark this particular edit as patrolled
1449 */
1450 function markpatrolled() {
1451 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1452 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1453
1454 # Check RC patrol config. option
1455 if( !$wgUseRCPatrol ) {
1456 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1457 return;
1458 }
1459
1460 # Check permissions
1461 if( !$wgUser->isAllowed( 'patrol' ) ) {
1462 $wgOut->permissionRequired( 'patrol' );
1463 return;
1464 }
1465
1466 $rcid = $wgRequest->getVal( 'rcid' );
1467 if ( !is_null ( $rcid ) ) {
1468 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1469 RecentChange::markPatrolled( $rcid );
1470 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1471 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1472 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1473 }
1474 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1475 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1476 }
1477 else {
1478 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1479 }
1480 }
1481
1482 /**
1483 * User-interface handler for the "watch" action
1484 */
1485
1486 function watch() {
1487
1488 global $wgUser, $wgOut;
1489
1490 if ( $wgUser->isAnon() ) {
1491 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1492 return;
1493 }
1494 if ( wfReadOnly() ) {
1495 $wgOut->readOnlyPage();
1496 return;
1497 }
1498
1499 if( $this->doWatch() ) {
1500 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1501 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1502
1503 $link = $this->mTitle->getPrefixedText();
1504 $text = wfMsg( 'addedwatchtext', $link );
1505 $wgOut->addWikiText( $text );
1506 }
1507
1508 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1509 }
1510
1511 /**
1512 * Add this page to $wgUser's watchlist
1513 * @return bool true on successful watch operation
1514 */
1515 function doWatch() {
1516 global $wgUser;
1517 if( $wgUser->isAnon() ) {
1518 return false;
1519 }
1520
1521 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1522 $wgUser->addWatch( $this->mTitle );
1523 $wgUser->saveSettings();
1524
1525 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1526 }
1527
1528 return false;
1529 }
1530
1531 /**
1532 * User interface handler for the "unwatch" action.
1533 */
1534 function unwatch() {
1535
1536 global $wgUser, $wgOut;
1537
1538 if ( $wgUser->isAnon() ) {
1539 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1540 return;
1541 }
1542 if ( wfReadOnly() ) {
1543 $wgOut->readOnlyPage();
1544 return;
1545 }
1546
1547 if( $this->doUnwatch() ) {
1548 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1549 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1550
1551 $link = $this->mTitle->getPrefixedText();
1552 $text = wfMsg( 'removedwatchtext', $link );
1553 $wgOut->addWikiText( $text );
1554 }
1555
1556 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1557 }
1558
1559 /**
1560 * Stop watching a page
1561 * @return bool true on successful unwatch
1562 */
1563 function doUnwatch() {
1564 global $wgUser;
1565 if( $wgUser->isAnon() ) {
1566 return false;
1567 }
1568
1569 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1570 $wgUser->removeWatch( $this->mTitle );
1571 $wgUser->saveSettings();
1572
1573 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1574 }
1575
1576 return false;
1577 }
1578
1579 /**
1580 * action=protect handler
1581 */
1582 function protect() {
1583 require_once 'ProtectionForm.php';
1584 $form = new ProtectionForm( $this );
1585 $form->show();
1586 }
1587
1588 /**
1589 * action=unprotect handler (alias)
1590 */
1591 function unprotect() {
1592 $this->protect();
1593 }
1594
1595 /**
1596 * Update the article's restriction field, and leave a log entry.
1597 *
1598 * @param array $limit set of restriction keys
1599 * @param string $reason
1600 * @return bool true on success
1601 */
1602 function updateRestrictions( $limit = array(), $reason = '' ) {
1603 global $wgUser, $wgRestrictionTypes, $wgContLang;
1604
1605 $id = $this->mTitle->getArticleID();
1606 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1607 return false;
1608 }
1609
1610 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1611 # we expect a single selection, but the schema allows otherwise.
1612 $current = array();
1613 foreach( $wgRestrictionTypes as $action )
1614 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1615
1616 $current = Article::flattenRestrictions( $current );
1617 $updated = Article::flattenRestrictions( $limit );
1618
1619 $changed = ( $current != $updated );
1620 $protect = ( $updated != '' );
1621
1622 # If nothing's changed, do nothing
1623 if( $changed ) {
1624 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1625
1626 $dbw =& wfGetDB( DB_MASTER );
1627
1628 # Prepare a null revision to be added to the history
1629 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1630 if( $reason )
1631 $comment .= ": $reason";
1632 if( $protect )
1633 $comment .= " [$updated]";
1634 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1635 $nullRevId = $nullRevision->insertOn( $dbw );
1636
1637 # Update page record
1638 $dbw->update( 'page',
1639 array( /* SET */
1640 'page_touched' => $dbw->timestamp(),
1641 'page_restrictions' => $updated,
1642 'page_latest' => $nullRevId
1643 ), array( /* WHERE */
1644 'page_id' => $id
1645 ), 'Article::protect'
1646 );
1647 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1648
1649 # Update the protection log
1650 $log = new LogPage( 'protect' );
1651 if( $protect ) {
1652 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]" ) );
1653 } else {
1654 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1655 }
1656
1657 } # End hook
1658 } # End "changed" check
1659
1660 return true;
1661 }
1662
1663 /**
1664 * Take an array of page restrictions and flatten it to a string
1665 * suitable for insertion into the page_restrictions field.
1666 * @param array $limit
1667 * @return string
1668 * @private
1669 */
1670 function flattenRestrictions( $limit ) {
1671 if( !is_array( $limit ) ) {
1672 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1673 }
1674 $bits = array();
1675 ksort( $limit );
1676 foreach( $limit as $action => $restrictions ) {
1677 if( $restrictions != '' ) {
1678 $bits[] = "$action=$restrictions";
1679 }
1680 }
1681 return implode( ':', $bits );
1682 }
1683
1684 /*
1685 * UI entry point for page deletion
1686 */
1687 function delete() {
1688 global $wgUser, $wgOut, $wgRequest;
1689 $confirm = $wgRequest->wasPosted() &&
1690 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1691 $reason = $wgRequest->getText( 'wpReason' );
1692
1693 # This code desperately needs to be totally rewritten
1694
1695 # Check permissions
1696 if( $wgUser->isAllowed( 'delete' ) ) {
1697 if( $wgUser->isBlocked() ) {
1698 $wgOut->blockedPage();
1699 return;
1700 }
1701 } else {
1702 $wgOut->permissionRequired( 'delete' );
1703 return;
1704 }
1705
1706 if( wfReadOnly() ) {
1707 $wgOut->readOnlyPage();
1708 return;
1709 }
1710
1711 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1712
1713 # Better double-check that it hasn't been deleted yet!
1714 $dbw =& wfGetDB( DB_MASTER );
1715 $conds = $this->mTitle->pageCond();
1716 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1717 if ( $latest === false ) {
1718 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1719 return;
1720 }
1721
1722 if( $confirm ) {
1723 $this->doDelete( $reason );
1724 return;
1725 }
1726
1727 # determine whether this page has earlier revisions
1728 # and insert a warning if it does
1729 $maxRevisions = 20;
1730 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1731
1732 if( count( $authors ) > 1 && !$confirm ) {
1733 $skin=$wgUser->getSkin();
1734 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1735 }
1736
1737 # If a single user is responsible for all revisions, find out who they are
1738 if ( count( $authors ) == $maxRevisions ) {
1739 // Query bailed out, too many revisions to find out if they're all the same
1740 $authorOfAll = false;
1741 } else {
1742 $authorOfAll = reset( $authors );
1743 foreach ( $authors as $author ) {
1744 if ( $authorOfAll != $author ) {
1745 $authorOfAll = false;
1746 break;
1747 }
1748 }
1749 }
1750 # Fetch article text
1751 $rev = Revision::newFromTitle( $this->mTitle );
1752
1753 if( !is_null( $rev ) ) {
1754 # if this is a mini-text, we can paste part of it into the deletion reason
1755 $text = $rev->getText();
1756
1757 #if this is empty, an earlier revision may contain "useful" text
1758 $blanked = false;
1759 if( $text == '' ) {
1760 $prev = $rev->getPrevious();
1761 if( $prev ) {
1762 $text = $prev->getText();
1763 $blanked = true;
1764 }
1765 }
1766
1767 $length = strlen( $text );
1768
1769 # this should not happen, since it is not possible to store an empty, new
1770 # page. Let's insert a standard text in case it does, though
1771 if( $length == 0 && $reason === '' ) {
1772 $reason = wfMsgForContent( 'exblank' );
1773 }
1774
1775 if( $length < 500 && $reason === '' ) {
1776 # comment field=255, let's grep the first 150 to have some user
1777 # space left
1778 global $wgContLang;
1779 $text = $wgContLang->truncate( $text, 150, '...' );
1780
1781 # let's strip out newlines
1782 $text = preg_replace( "/[\n\r]/", '', $text );
1783
1784 if( !$blanked ) {
1785 if( $authorOfAll === false ) {
1786 $reason = wfMsgForContent( 'excontent', $text );
1787 } else {
1788 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1789 }
1790 } else {
1791 $reason = wfMsgForContent( 'exbeforeblank', $text );
1792 }
1793 }
1794 }
1795
1796 return $this->confirmDelete( '', $reason );
1797 }
1798
1799 /**
1800 * Get the last N authors
1801 * @param int $num Number of revisions to get
1802 * @param string $revLatest The latest rev_id, selected from the master (optional)
1803 * @return array Array of authors, duplicates not removed
1804 */
1805 function getLastNAuthors( $num, $revLatest = 0 ) {
1806 wfProfileIn( __METHOD__ );
1807
1808 // First try the slave
1809 // If that doesn't have the latest revision, try the master
1810 $continue = 2;
1811 $db =& wfGetDB( DB_SLAVE );
1812 do {
1813 $res = $db->select( array( 'page', 'revision' ),
1814 array( 'rev_id', 'rev_user_text' ),
1815 array(
1816 'page_namespace' => $this->mTitle->getNamespace(),
1817 'page_title' => $this->mTitle->getDBkey(),
1818 'rev_page = page_id'
1819 ), __METHOD__, $this->getSelectOptions( array(
1820 'ORDER BY' => 'rev_timestamp DESC',
1821 'LIMIT' => $num
1822 ) )
1823 );
1824 if ( !$res ) {
1825 wfProfileOut( __METHOD__ );
1826 return array();
1827 }
1828 $row = $db->fetchObject( $res );
1829 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1830 $db =& wfGetDB( DB_MASTER );
1831 $continue--;
1832 } else {
1833 $continue = 0;
1834 }
1835 } while ( $continue );
1836
1837 $authors = array( $row->rev_user_text );
1838 while ( $row = $db->fetchObject( $res ) ) {
1839 $authors[] = $row->rev_user_text;
1840 }
1841 wfProfileOut( __METHOD__ );
1842 return $authors;
1843 }
1844
1845 /**
1846 * Output deletion confirmation dialog
1847 */
1848 function confirmDelete( $par, $reason ) {
1849 global $wgOut, $wgUser;
1850
1851 wfDebug( "Article::confirmDelete\n" );
1852
1853 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1854 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1855 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1856 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1857
1858 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1859
1860 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1861 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1862 $token = htmlspecialchars( $wgUser->editToken() );
1863
1864 $wgOut->addHTML( "
1865 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1866 <table border='0'>
1867 <tr>
1868 <td align='right'>
1869 <label for='wpReason'>{$delcom}:</label>
1870 </td>
1871 <td align='left'>
1872 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1873 </td>
1874 </tr>
1875 <tr>
1876 <td>&nbsp;</td>
1877 <td>
1878 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1879 </td>
1880 </tr>
1881 </table>
1882 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1883 </form>\n" );
1884
1885 $wgOut->returnToMain( false );
1886 }
1887
1888
1889 /**
1890 * Perform a deletion and output success or failure messages
1891 */
1892 function doDelete( $reason ) {
1893 global $wgOut, $wgUser;
1894 wfDebug( __METHOD__."\n" );
1895
1896 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1897 if ( $this->doDeleteArticle( $reason ) ) {
1898 $deleted = $this->mTitle->getPrefixedText();
1899
1900 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1901 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1902
1903 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1904 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1905
1906 $wgOut->addWikiText( $text );
1907 $wgOut->returnToMain( false );
1908 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1909 } else {
1910 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1911 }
1912 }
1913 }
1914
1915 /**
1916 * Back-end article deletion
1917 * Deletes the article with database consistency, writes logs, purges caches
1918 * Returns success
1919 */
1920 function doDeleteArticle( $reason ) {
1921 global $wgUseSquid, $wgDeferredUpdateList;
1922 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1923
1924 wfDebug( __METHOD__."\n" );
1925
1926 $dbw =& wfGetDB( DB_MASTER );
1927 $ns = $this->mTitle->getNamespace();
1928 $t = $this->mTitle->getDBkey();
1929 $id = $this->mTitle->getArticleID();
1930
1931 if ( $t == '' || $id == 0 ) {
1932 return false;
1933 }
1934
1935 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1936 array_push( $wgDeferredUpdateList, $u );
1937
1938 // For now, shunt the revision data into the archive table.
1939 // Text is *not* removed from the text table; bulk storage
1940 // is left intact to avoid breaking block-compression or
1941 // immutable storage schemes.
1942 //
1943 // For backwards compatibility, note that some older archive
1944 // table entries will have ar_text and ar_flags fields still.
1945 //
1946 // In the future, we may keep revisions and mark them with
1947 // the rev_deleted field, which is reserved for this purpose.
1948 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1949 array(
1950 'ar_namespace' => 'page_namespace',
1951 'ar_title' => 'page_title',
1952 'ar_comment' => 'rev_comment',
1953 'ar_user' => 'rev_user',
1954 'ar_user_text' => 'rev_user_text',
1955 'ar_timestamp' => 'rev_timestamp',
1956 'ar_minor_edit' => 'rev_minor_edit',
1957 'ar_rev_id' => 'rev_id',
1958 'ar_text_id' => 'rev_text_id',
1959 ), array(
1960 'page_id' => $id,
1961 'page_id = rev_page'
1962 ), __METHOD__
1963 );
1964
1965 # Now that it's safely backed up, delete it
1966 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
1967 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
1968
1969 if ($wgUseTrackbacks)
1970 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
1971
1972 # Clean up recentchanges entries...
1973 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
1974
1975 # Finally, clean up the link tables
1976 $t = $this->mTitle->getPrefixedDBkey();
1977
1978 # Clear caches
1979 Article::onArticleDelete( $this->mTitle );
1980
1981 # Delete outgoing links
1982 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1983 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1984 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1985 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1986 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1987 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1988
1989 # Log the deletion
1990 $log = new LogPage( 'delete' );
1991 $log->addEntry( 'delete', $this->mTitle, $reason );
1992
1993 # Clear the cached article id so the interface doesn't act like we exist
1994 $this->mTitle->resetArticleID( 0 );
1995 $this->mTitle->mArticleID = 0;
1996 return true;
1997 }
1998
1999 /**
2000 * Revert a modification
2001 */
2002 function rollback() {
2003 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2004
2005 if( $wgUser->isAllowed( 'rollback' ) ) {
2006 if( $wgUser->isBlocked() ) {
2007 $wgOut->blockedPage();
2008 return;
2009 }
2010 } else {
2011 $wgOut->permissionRequired( 'rollback' );
2012 return;
2013 }
2014
2015 if ( wfReadOnly() ) {
2016 $wgOut->readOnlyPage( $this->getContent() );
2017 return;
2018 }
2019 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2020 array( $this->mTitle->getPrefixedText(),
2021 $wgRequest->getVal( 'from' ) ) ) ) {
2022 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2023 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2024 return;
2025 }
2026 $dbw =& wfGetDB( DB_MASTER );
2027
2028 # Enhanced rollback, marks edits rc_bot=1
2029 $bot = $wgRequest->getBool( 'bot' );
2030
2031 # Replace all this user's current edits with the next one down
2032 $tt = $this->mTitle->getDBKey();
2033 $n = $this->mTitle->getNamespace();
2034
2035 # Get the last editor
2036 $current = Revision::newFromTitle( $this->mTitle );
2037 if( is_null( $current ) ) {
2038 # Something wrong... no page?
2039 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2040 return;
2041 }
2042
2043 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2044 if( $from != $current->getUserText() ) {
2045 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2046 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2047 htmlspecialchars( $this->mTitle->getPrefixedText()),
2048 htmlspecialchars( $from ),
2049 htmlspecialchars( $current->getUserText() ) ) );
2050 if( $current->getComment() != '') {
2051 $wgOut->addHTML(
2052 wfMsg( 'editcomment',
2053 htmlspecialchars( $current->getComment() ) ) );
2054 }
2055 return;
2056 }
2057
2058 # Get the last edit not by this guy
2059 $user = intval( $current->getUser() );
2060 $user_text = $dbw->addQuotes( $current->getUserText() );
2061 $s = $dbw->selectRow( 'revision',
2062 array( 'rev_id', 'rev_timestamp' ),
2063 array(
2064 'rev_page' => $current->getPage(),
2065 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2066 ), __METHOD__,
2067 array(
2068 'USE INDEX' => 'page_timestamp',
2069 'ORDER BY' => 'rev_timestamp DESC' )
2070 );
2071 if( $s === false ) {
2072 # Something wrong
2073 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2074 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2075 return;
2076 }
2077
2078 $set = array();
2079 if ( $bot ) {
2080 # Mark all reverted edits as bot
2081 $set['rc_bot'] = 1;
2082 }
2083 if ( $wgUseRCPatrol ) {
2084 # Mark all reverted edits as patrolled
2085 $set['rc_patrolled'] = 1;
2086 }
2087
2088 if ( $set ) {
2089 $dbw->update( 'recentchanges', $set,
2090 array( /* WHERE */
2091 'rc_cur_id' => $current->getPage(),
2092 'rc_user_text' => $current->getUserText(),
2093 "rc_timestamp > '{$s->rev_timestamp}'",
2094 ), __METHOD__
2095 );
2096 }
2097
2098 # Get the edit summary
2099 $target = Revision::newFromId( $s->rev_id );
2100 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2101 $newComment = $wgRequest->getText( 'summary', $newComment );
2102
2103 # Save it!
2104 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2105 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2106 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2107
2108 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2109
2110 $wgOut->returnToMain( false );
2111 }
2112
2113
2114 /**
2115 * Do standard deferred updates after page view
2116 * @private
2117 */
2118 function viewUpdates() {
2119 global $wgDeferredUpdateList;
2120
2121 if ( 0 != $this->getID() ) {
2122 global $wgDisableCounters;
2123 if( !$wgDisableCounters ) {
2124 Article::incViewCount( $this->getID() );
2125 $u = new SiteStatsUpdate( 1, 0, 0 );
2126 array_push( $wgDeferredUpdateList, $u );
2127 }
2128 }
2129
2130 # Update newtalk / watchlist notification status
2131 global $wgUser;
2132 $wgUser->clearNotification( $this->mTitle );
2133 }
2134
2135 /**
2136 * Do standard deferred updates after page edit.
2137 * Update links tables, site stats, search index and message cache.
2138 * Every 1000th edit, prune the recent changes table.
2139 *
2140 * @private
2141 * @param $text New text of the article
2142 * @param $summary Edit summary
2143 * @param $minoredit Minor edit
2144 * @param $timestamp_of_pagechange Timestamp associated with the page change
2145 * @param $newid rev_id value of the new revision
2146 * @param $changed Whether or not the content actually changed
2147 */
2148 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2149 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2150
2151 wfProfileIn( __METHOD__ );
2152
2153 # Parse the text
2154 $options = new ParserOptions;
2155 $options->setTidy(true);
2156 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2157
2158 # Save it to the parser cache
2159 $parserCache =& ParserCache::singleton();
2160 $parserCache->save( $poutput, $this, $wgUser );
2161
2162 # Update the links tables
2163 $u = new LinksUpdate( $this->mTitle, $poutput );
2164 $u->doUpdate();
2165
2166 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2167 wfSeedRandom();
2168 if ( 0 == mt_rand( 0, 999 ) ) {
2169 # Periodically flush old entries from the recentchanges table.
2170 global $wgRCMaxAge;
2171
2172 $dbw =& wfGetDB( DB_MASTER );
2173 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2174 $recentchanges = $dbw->tableName( 'recentchanges' );
2175 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2176 $dbw->query( $sql );
2177 }
2178 }
2179
2180 $id = $this->getID();
2181 $title = $this->mTitle->getPrefixedDBkey();
2182 $shortTitle = $this->mTitle->getDBkey();
2183
2184 if ( 0 == $id ) {
2185 wfProfileOut( __METHOD__ );
2186 return;
2187 }
2188
2189 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2190 array_push( $wgDeferredUpdateList, $u );
2191 $u = new SearchUpdate( $id, $title, $text );
2192 array_push( $wgDeferredUpdateList, $u );
2193
2194 # If this is another user's talk page, update newtalk
2195 # Don't do this if $changed = false otherwise some idiot can null-edit a
2196 # load of user talk pages and piss people off
2197 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName() && $changed ) {
2198 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2199 $other = User::newFromName( $shortTitle );
2200 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2201 // An anonymous user
2202 $other = new User();
2203 $other->setName( $shortTitle );
2204 }
2205 if( $other ) {
2206 $other->setNewtalk( true );
2207 }
2208 }
2209 }
2210
2211 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2212 $wgMessageCache->replace( $shortTitle, $text );
2213 }
2214
2215 wfProfileOut( __METHOD__ );
2216 }
2217
2218 /**
2219 * Generate the navigation links when browsing through an article revisions
2220 * It shows the information as:
2221 * Revision as of \<date\>; view current revision
2222 * \<- Previous version | Next Version -\>
2223 *
2224 * @private
2225 * @param string $oldid Revision ID of this article revision
2226 */
2227 function setOldSubtitle( $oldid=0 ) {
2228 global $wgLang, $wgOut, $wgUser;
2229
2230 $revision = Revision::newFromId( $oldid );
2231
2232 $current = ( $oldid == $this->mLatest );
2233 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2234 $sk = $wgUser->getSkin();
2235 $lnk = $current
2236 ? wfMsg( 'currentrevisionlink' )
2237 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2238 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2239 $prevlink = $prev
2240 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2241 : wfMsg( 'previousrevision' );
2242 $nextlink = $current
2243 ? wfMsg( 'nextrevision' )
2244 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2245
2246 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2247 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2248
2249 $r = wfMsg( 'oldrevisionnavigation', $td, $lnk, $prevlink, $nextlink, $userlinks );
2250 $wgOut->setSubtitle( $r );
2251 }
2252
2253 /**
2254 * This function is called right before saving the wikitext,
2255 * so we can do things like signatures and links-in-context.
2256 *
2257 * @param string $text
2258 */
2259 function preSaveTransform( $text ) {
2260 global $wgParser, $wgUser;
2261 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2262 }
2263
2264 /* Caching functions */
2265
2266 /**
2267 * checkLastModified returns true if it has taken care of all
2268 * output to the client that is necessary for this request.
2269 * (that is, it has sent a cached version of the page)
2270 */
2271 function tryFileCache() {
2272 static $called = false;
2273 if( $called ) {
2274 wfDebug( " tryFileCache() -- called twice!?\n" );
2275 return;
2276 }
2277 $called = true;
2278 if($this->isFileCacheable()) {
2279 $touched = $this->mTouched;
2280 $cache = new CacheManager( $this->mTitle );
2281 if($cache->isFileCacheGood( $touched )) {
2282 wfDebug( " tryFileCache() - about to load\n" );
2283 $cache->loadFromFileCache();
2284 return true;
2285 } else {
2286 wfDebug( " tryFileCache() - starting buffer\n" );
2287 ob_start( array(&$cache, 'saveToFileCache' ) );
2288 }
2289 } else {
2290 wfDebug( " tryFileCache() - not cacheable\n" );
2291 }
2292 }
2293
2294 /**
2295 * Check if the page can be cached
2296 * @return bool
2297 */
2298 function isFileCacheable() {
2299 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2300 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2301
2302 return $wgUseFileCache
2303 and (!$wgShowIPinHeader)
2304 and ($this->getID() != 0)
2305 and ($wgUser->isAnon())
2306 and (!$wgUser->getNewtalk())
2307 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2308 and (empty( $action ) || $action == 'view')
2309 and (!isset($oldid))
2310 and (!isset($diff))
2311 and (!isset($redirect))
2312 and (!isset($printable))
2313 and (!$this->mRedirectedFrom);
2314 }
2315
2316 /**
2317 * Loads page_touched and returns a value indicating if it should be used
2318 *
2319 */
2320 function checkTouched() {
2321 if( !$this->mDataLoaded ) {
2322 $this->loadPageData();
2323 }
2324 return !$this->mIsRedirect;
2325 }
2326
2327 /**
2328 * Get the page_touched field
2329 */
2330 function getTouched() {
2331 # Ensure that page data has been loaded
2332 if( !$this->mDataLoaded ) {
2333 $this->loadPageData();
2334 }
2335 return $this->mTouched;
2336 }
2337
2338 /**
2339 * Get the page_latest field
2340 */
2341 function getLatest() {
2342 if ( !$this->mDataLoaded ) {
2343 $this->loadPageData();
2344 }
2345 return $this->mLatest;
2346 }
2347
2348 /**
2349 * Edit an article without doing all that other stuff
2350 * The article must already exist; link tables etc
2351 * are not updated, caches are not flushed.
2352 *
2353 * @param string $text text submitted
2354 * @param string $comment comment submitted
2355 * @param bool $minor whereas it's a minor modification
2356 */
2357 function quickEdit( $text, $comment = '', $minor = 0 ) {
2358 wfProfileIn( __METHOD__ );
2359
2360 $dbw =& wfGetDB( DB_MASTER );
2361 $dbw->begin();
2362 $revision = new Revision( array(
2363 'page' => $this->getId(),
2364 'text' => $text,
2365 'comment' => $comment,
2366 'minor_edit' => $minor ? 1 : 0,
2367 ) );
2368 # fixme : $revisionId never used
2369 $revisionId = $revision->insertOn( $dbw );
2370 $this->updateRevisionOn( $dbw, $revision );
2371 $dbw->commit();
2372
2373 wfProfileOut( __METHOD__ );
2374 }
2375
2376 /**
2377 * Used to increment the view counter
2378 *
2379 * @static
2380 * @param integer $id article id
2381 */
2382 function incViewCount( $id ) {
2383 $id = intval( $id );
2384 global $wgHitcounterUpdateFreq, $wgDBtype;
2385
2386 $dbw =& wfGetDB( DB_MASTER );
2387 $pageTable = $dbw->tableName( 'page' );
2388 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2389 $acchitsTable = $dbw->tableName( 'acchits' );
2390
2391 if( $wgHitcounterUpdateFreq <= 1 ){ //
2392 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2393 return;
2394 }
2395
2396 # Not important enough to warrant an error page in case of failure
2397 $oldignore = $dbw->ignoreErrors( true );
2398
2399 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2400
2401 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2402 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2403 # Most of the time (or on SQL errors), skip row count check
2404 $dbw->ignoreErrors( $oldignore );
2405 return;
2406 }
2407
2408 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2409 $row = $dbw->fetchObject( $res );
2410 $rown = intval( $row->n );
2411 if( $rown >= $wgHitcounterUpdateFreq ){
2412 wfProfileIn( 'Article::incViewCount-collect' );
2413 $old_user_abort = ignore_user_abort( true );
2414
2415 if ($wgDBtype == 'mysql')
2416 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2417 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2418 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2419 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2420 'GROUP BY hc_id');
2421 $dbw->query("DELETE FROM $hitcounterTable");
2422 if ($wgDBtype == 'mysql')
2423 $dbw->query('UNLOCK TABLES');
2424 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2425 'WHERE page_id = hc_id');
2426 $dbw->query("DROP TABLE $acchitsTable");
2427
2428 ignore_user_abort( $old_user_abort );
2429 wfProfileOut( 'Article::incViewCount-collect' );
2430 }
2431 $dbw->ignoreErrors( $oldignore );
2432 }
2433
2434 /**#@+
2435 * The onArticle*() functions are supposed to be a kind of hooks
2436 * which should be called whenever any of the specified actions
2437 * are done.
2438 *
2439 * This is a good place to put code to clear caches, for instance.
2440 *
2441 * This is called on page move and undelete, as well as edit
2442 * @static
2443 * @param $title_obj a title object
2444 */
2445
2446 static function onArticleCreate($title) {
2447 # The talk page isn't in the regular link tables, so we need to update manually:
2448 if ( $title->isTalkPage() ) {
2449 $other = $title->getSubjectPage();
2450 } else {
2451 $other = $title->getTalkPage();
2452 }
2453 $other->invalidateCache();
2454 $other->purgeSquid();
2455
2456 $title->touchLinks();
2457 $title->purgeSquid();
2458 }
2459
2460 static function onArticleDelete( $title ) {
2461 global $wgUseFileCache, $wgMessageCache;
2462
2463 $title->touchLinks();
2464 $title->purgeSquid();
2465
2466 # File cache
2467 if ( $wgUseFileCache ) {
2468 $cm = new CacheManager( $title );
2469 @unlink( $cm->fileCacheName() );
2470 }
2471
2472 if( $title->getNamespace() == NS_MEDIAWIKI) {
2473 $wgMessageCache->replace( $title->getDBkey(), false );
2474 }
2475 }
2476
2477 /**
2478 * Purge caches on page update etc
2479 */
2480 static function onArticleEdit( $title ) {
2481 global $wgDeferredUpdateList, $wgUseFileCache;
2482
2483 $urls = array();
2484
2485 // Invalidate caches of articles which include this page
2486 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2487 $wgDeferredUpdateList[] = $update;
2488
2489 # Purge squid for this page only
2490 $title->purgeSquid();
2491
2492 # Clear file cache
2493 if ( $wgUseFileCache ) {
2494 $cm = new CacheManager( $title );
2495 @unlink( $cm->fileCacheName() );
2496 }
2497 }
2498
2499 /**#@-*/
2500
2501 /**
2502 * Info about this page
2503 * Called for ?action=info when $wgAllowPageInfo is on.
2504 *
2505 * @public
2506 */
2507 function info() {
2508 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2509
2510 if ( !$wgAllowPageInfo ) {
2511 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2512 return;
2513 }
2514
2515 $page = $this->mTitle->getSubjectPage();
2516
2517 $wgOut->setPagetitle( $page->getPrefixedText() );
2518 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2519
2520 # first, see if the page exists at all.
2521 $exists = $page->getArticleId() != 0;
2522 if( !$exists ) {
2523 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2524 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2525 } else {
2526 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2527 }
2528 } else {
2529 $dbr =& wfGetDB( DB_SLAVE );
2530 $wl_clause = array(
2531 'wl_title' => $page->getDBkey(),
2532 'wl_namespace' => $page->getNamespace() );
2533 $numwatchers = $dbr->selectField(
2534 'watchlist',
2535 'COUNT(*)',
2536 $wl_clause,
2537 __METHOD__,
2538 $this->getSelectOptions() );
2539
2540 $pageInfo = $this->pageCountInfo( $page );
2541 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2542
2543 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2544 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2545 if( $talkInfo ) {
2546 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2547 }
2548 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2549 if( $talkInfo ) {
2550 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2551 }
2552 $wgOut->addHTML( '</ul>' );
2553
2554 }
2555 }
2556
2557 /**
2558 * Return the total number of edits and number of unique editors
2559 * on a given page. If page does not exist, returns false.
2560 *
2561 * @param Title $title
2562 * @return array
2563 * @private
2564 */
2565 function pageCountInfo( $title ) {
2566 $id = $title->getArticleId();
2567 if( $id == 0 ) {
2568 return false;
2569 }
2570
2571 $dbr =& wfGetDB( DB_SLAVE );
2572
2573 $rev_clause = array( 'rev_page' => $id );
2574
2575 $edits = $dbr->selectField(
2576 'revision',
2577 'COUNT(rev_page)',
2578 $rev_clause,
2579 __METHOD__,
2580 $this->getSelectOptions() );
2581
2582 $authors = $dbr->selectField(
2583 'revision',
2584 'COUNT(DISTINCT rev_user_text)',
2585 $rev_clause,
2586 __METHOD__,
2587 $this->getSelectOptions() );
2588
2589 return array( 'edits' => $edits, 'authors' => $authors );
2590 }
2591
2592 /**
2593 * Return a list of templates used by this article.
2594 * Uses the templatelinks table
2595 *
2596 * @return array Array of Title objects
2597 */
2598 function getUsedTemplates() {
2599 $result = array();
2600 $id = $this->mTitle->getArticleID();
2601 if( $id == 0 ) {
2602 return array();
2603 }
2604
2605 $dbr =& wfGetDB( DB_SLAVE );
2606 $res = $dbr->select( array( 'templatelinks' ),
2607 array( 'tl_namespace', 'tl_title' ),
2608 array( 'tl_from' => $id ),
2609 'Article:getUsedTemplates' );
2610 if ( false !== $res ) {
2611 if ( $dbr->numRows( $res ) ) {
2612 while ( $row = $dbr->fetchObject( $res ) ) {
2613 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2614 }
2615 }
2616 }
2617 $dbr->freeResult( $res );
2618 return $result;
2619 }
2620 }
2621
2622 ?>