ea1d7f940794488875ab908b00f9dd3cead4406c
[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::MW_REV_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::MW_REV_DELETED_TEXT ) ) {
807 if( !$this->mRevision->userCan( Revision::MW_REV_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 * It is possible to call this function from a command-line script, but note that you should
1221 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1222 *
1223 * $wgUser must be set before calling this function.
1224 *
1225 * @param string $text New text
1226 * @param string $summary Edit summary
1227 * @param integer $flags bitfield:
1228 * EDIT_NEW
1229 * Article is known or assumed to be non-existent, create a new one
1230 * EDIT_UPDATE
1231 * Article is known or assumed to be pre-existing, update it
1232 * EDIT_MINOR
1233 * Mark this edit minor, if the user is allowed to do so
1234 * EDIT_SUPPRESS_RC
1235 * Do not log the change in recentchanges
1236 * EDIT_FORCE_BOT
1237 * Mark the edit a "bot" edit regardless of user rights
1238 * EDIT_DEFER_UPDATES
1239 * Defer some of the updates until the end of index.php
1240 *
1241 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1242 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1243 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1244 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1245 * to MediaWiki's performance-optimised locking strategy.
1246 *
1247 * @return bool success
1248 */
1249 function doEdit( $text, $summary, $flags = 0 ) {
1250 global $wgUser, $wgDBtransactions;
1251
1252 wfProfileIn( __METHOD__ );
1253 $good = true;
1254
1255 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1256 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1257 if ( $aid ) {
1258 $flags |= EDIT_UPDATE;
1259 } else {
1260 $flags |= EDIT_NEW;
1261 }
1262 }
1263
1264 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1265 &$summary, $flags & EDIT_MINOR,
1266 null, null, &$flags ) ) )
1267 {
1268 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1269 wfProfileOut( __METHOD__ );
1270 return false;
1271 }
1272
1273 # Silently ignore EDIT_MINOR if not allowed
1274 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1275 $bot = $wgUser->isBot() || ( $flags & EDIT_FORCE_BOT );
1276
1277 $text = $this->preSaveTransform( $text );
1278
1279 $dbw =& wfGetDB( DB_MASTER );
1280 $now = wfTimestampNow();
1281
1282 if ( $flags & EDIT_UPDATE ) {
1283 # Update article, but only if changed.
1284
1285 # Make sure the revision is either completely inserted or not inserted at all
1286 if( !$wgDBtransactions ) {
1287 $userAbort = ignore_user_abort( true );
1288 }
1289
1290 $oldtext = $this->getContent();
1291 $oldsize = strlen( $oldtext );
1292 $newsize = strlen( $text );
1293 $lastRevision = 0;
1294 $revisionId = 0;
1295
1296 if ( 0 != strcmp( $text, $oldtext ) ) {
1297 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1298 - (int)$this->isCountable( $oldtext );
1299 $this->mTotalAdjustment = 0;
1300
1301 $lastRevision = $dbw->selectField(
1302 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1303
1304 if ( !$lastRevision ) {
1305 # Article gone missing
1306 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1307 wfProfileOut( __METHOD__ );
1308 return false;
1309 }
1310
1311 $revision = new Revision( array(
1312 'page' => $this->getId(),
1313 'comment' => $summary,
1314 'minor_edit' => $isminor,
1315 'text' => $text
1316 ) );
1317
1318 $dbw->begin();
1319 $revisionId = $revision->insertOn( $dbw );
1320
1321 # Update page
1322 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1323
1324 if( !$ok ) {
1325 /* Belated edit conflict! Run away!! */
1326 $good = false;
1327 $dbw->rollback();
1328 } else {
1329 # Update recentchanges
1330 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1331 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1332 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1333 $revisionId );
1334
1335 # Mark as patrolled if the user can do so and has it set in their options
1336 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1337 RecentChange::markPatrolled( $rcid );
1338 }
1339 }
1340 $dbw->commit();
1341 }
1342 } else {
1343 // Keep the same revision ID, but do some updates on it
1344 $revisionId = $this->getRevIdFetched();
1345 // Update page_touched, this is usually implicit in the page update
1346 // Other cache updates are done in onArticleEdit()
1347 $this->mTitle->invalidateCache();
1348 }
1349
1350 if( !$wgDBtransactions ) {
1351 ignore_user_abort( $userAbort );
1352 }
1353
1354 if ( $good ) {
1355 # Invalidate cache of this article and all pages using this article
1356 # as a template. Partly deferred.
1357 Article::onArticleEdit( $this->mTitle );
1358
1359 # Update links tables, site stats, etc.
1360 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1361 }
1362 } else {
1363 # Create new article
1364
1365 # Set statistics members
1366 # We work out if it's countable after PST to avoid counter drift
1367 # when articles are created with {{subst:}}
1368 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1369 $this->mTotalAdjustment = 1;
1370
1371 $dbw->begin();
1372
1373 # Add the page record; stake our claim on this title!
1374 # This will fail with a database query exception if the article already exists
1375 $newid = $this->insertOn( $dbw );
1376
1377 # Save the revision text...
1378 $revision = new Revision( array(
1379 'page' => $newid,
1380 'comment' => $summary,
1381 'minor_edit' => $isminor,
1382 'text' => $text
1383 ) );
1384 $revisionId = $revision->insertOn( $dbw );
1385
1386 $this->mTitle->resetArticleID( $newid );
1387
1388 # Update the page record with revision data
1389 $this->updateRevisionOn( $dbw, $revision, 0 );
1390
1391 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1392 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1393 '', strlen( $text ), $revisionId );
1394 # Mark as patrolled if the user can and has the option set
1395 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1396 RecentChange::markPatrolled( $rcid );
1397 }
1398 }
1399 $dbw->commit();
1400
1401 # Update links, etc.
1402 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1403
1404 # Clear caches
1405 Article::onArticleCreate( $this->mTitle );
1406
1407 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1408 $summary, $flags & EDIT_MINOR,
1409 null, null, &$flags ) );
1410 }
1411
1412 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1413 wfDoUpdates();
1414 }
1415
1416 wfRunHooks( 'ArticleSaveComplete',
1417 array( &$this, &$wgUser, $text,
1418 $summary, $flags & EDIT_MINOR,
1419 null, null, &$flags ) );
1420
1421 wfProfileOut( __METHOD__ );
1422 return $good;
1423 }
1424
1425 /**
1426 * @deprecated wrapper for doRedirect
1427 */
1428 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1429 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1430 }
1431
1432 /**
1433 * Output a redirect back to the article.
1434 * This is typically used after an edit.
1435 *
1436 * @param boolean $noRedir Add redirect=no
1437 * @param string $sectionAnchor section to redirect to, including "#"
1438 */
1439 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1440 global $wgOut;
1441 if ( $noRedir ) {
1442 $query = 'redirect=no';
1443 } else {
1444 $query = '';
1445 }
1446 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1447 }
1448
1449 /**
1450 * Mark this particular edit as patrolled
1451 */
1452 function markpatrolled() {
1453 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1454 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1455
1456 # Check RC patrol config. option
1457 if( !$wgUseRCPatrol ) {
1458 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1459 return;
1460 }
1461
1462 # Check permissions
1463 if( !$wgUser->isAllowed( 'patrol' ) ) {
1464 $wgOut->permissionRequired( 'patrol' );
1465 return;
1466 }
1467
1468 $rcid = $wgRequest->getVal( 'rcid' );
1469 if ( !is_null ( $rcid ) ) {
1470 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1471 RecentChange::markPatrolled( $rcid );
1472 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1473 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1474 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1475 }
1476 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1477 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1478 }
1479 else {
1480 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1481 }
1482 }
1483
1484 /**
1485 * User-interface handler for the "watch" action
1486 */
1487
1488 function watch() {
1489
1490 global $wgUser, $wgOut;
1491
1492 if ( $wgUser->isAnon() ) {
1493 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1494 return;
1495 }
1496 if ( wfReadOnly() ) {
1497 $wgOut->readOnlyPage();
1498 return;
1499 }
1500
1501 if( $this->doWatch() ) {
1502 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1503 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1504
1505 $link = $this->mTitle->getPrefixedText();
1506 $text = wfMsg( 'addedwatchtext', $link );
1507 $wgOut->addWikiText( $text );
1508 }
1509
1510 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1511 }
1512
1513 /**
1514 * Add this page to $wgUser's watchlist
1515 * @return bool true on successful watch operation
1516 */
1517 function doWatch() {
1518 global $wgUser;
1519 if( $wgUser->isAnon() ) {
1520 return false;
1521 }
1522
1523 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1524 $wgUser->addWatch( $this->mTitle );
1525 $wgUser->saveSettings();
1526
1527 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1528 }
1529
1530 return false;
1531 }
1532
1533 /**
1534 * User interface handler for the "unwatch" action.
1535 */
1536 function unwatch() {
1537
1538 global $wgUser, $wgOut;
1539
1540 if ( $wgUser->isAnon() ) {
1541 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1542 return;
1543 }
1544 if ( wfReadOnly() ) {
1545 $wgOut->readOnlyPage();
1546 return;
1547 }
1548
1549 if( $this->doUnwatch() ) {
1550 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1551 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1552
1553 $link = $this->mTitle->getPrefixedText();
1554 $text = wfMsg( 'removedwatchtext', $link );
1555 $wgOut->addWikiText( $text );
1556 }
1557
1558 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1559 }
1560
1561 /**
1562 * Stop watching a page
1563 * @return bool true on successful unwatch
1564 */
1565 function doUnwatch() {
1566 global $wgUser;
1567 if( $wgUser->isAnon() ) {
1568 return false;
1569 }
1570
1571 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1572 $wgUser->removeWatch( $this->mTitle );
1573 $wgUser->saveSettings();
1574
1575 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1576 }
1577
1578 return false;
1579 }
1580
1581 /**
1582 * action=protect handler
1583 */
1584 function protect() {
1585 require_once 'ProtectionForm.php';
1586 $form = new ProtectionForm( $this );
1587 $form->show();
1588 }
1589
1590 /**
1591 * action=unprotect handler (alias)
1592 */
1593 function unprotect() {
1594 $this->protect();
1595 }
1596
1597 /**
1598 * Update the article's restriction field, and leave a log entry.
1599 *
1600 * @param array $limit set of restriction keys
1601 * @param string $reason
1602 * @return bool true on success
1603 */
1604 function updateRestrictions( $limit = array(), $reason = '' ) {
1605 global $wgUser, $wgRestrictionTypes, $wgContLang;
1606
1607 $id = $this->mTitle->getArticleID();
1608 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1609 return false;
1610 }
1611
1612 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1613 # we expect a single selection, but the schema allows otherwise.
1614 $current = array();
1615 foreach( $wgRestrictionTypes as $action )
1616 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1617
1618 $current = Article::flattenRestrictions( $current );
1619 $updated = Article::flattenRestrictions( $limit );
1620
1621 $changed = ( $current != $updated );
1622 $protect = ( $updated != '' );
1623
1624 # If nothing's changed, do nothing
1625 if( $changed ) {
1626 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1627
1628 $dbw =& wfGetDB( DB_MASTER );
1629
1630 # Prepare a null revision to be added to the history
1631 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1632 if( $reason )
1633 $comment .= ": $reason";
1634 if( $protect )
1635 $comment .= " [$updated]";
1636 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1637 $nullRevId = $nullRevision->insertOn( $dbw );
1638
1639 # Update page record
1640 $dbw->update( 'page',
1641 array( /* SET */
1642 'page_touched' => $dbw->timestamp(),
1643 'page_restrictions' => $updated,
1644 'page_latest' => $nullRevId
1645 ), array( /* WHERE */
1646 'page_id' => $id
1647 ), 'Article::protect'
1648 );
1649 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1650
1651 # Update the protection log
1652 $log = new LogPage( 'protect' );
1653 if( $protect ) {
1654 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]" ) );
1655 } else {
1656 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1657 }
1658
1659 } # End hook
1660 } # End "changed" check
1661
1662 return true;
1663 }
1664
1665 /**
1666 * Take an array of page restrictions and flatten it to a string
1667 * suitable for insertion into the page_restrictions field.
1668 * @param array $limit
1669 * @return string
1670 * @private
1671 */
1672 function flattenRestrictions( $limit ) {
1673 if( !is_array( $limit ) ) {
1674 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1675 }
1676 $bits = array();
1677 ksort( $limit );
1678 foreach( $limit as $action => $restrictions ) {
1679 if( $restrictions != '' ) {
1680 $bits[] = "$action=$restrictions";
1681 }
1682 }
1683 return implode( ':', $bits );
1684 }
1685
1686 /*
1687 * UI entry point for page deletion
1688 */
1689 function delete() {
1690 global $wgUser, $wgOut, $wgRequest;
1691 $confirm = $wgRequest->wasPosted() &&
1692 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1693 $reason = $wgRequest->getText( 'wpReason' );
1694
1695 # This code desperately needs to be totally rewritten
1696
1697 # Check permissions
1698 if( $wgUser->isAllowed( 'delete' ) ) {
1699 if( $wgUser->isBlocked() ) {
1700 $wgOut->blockedPage();
1701 return;
1702 }
1703 } else {
1704 $wgOut->permissionRequired( 'delete' );
1705 return;
1706 }
1707
1708 if( wfReadOnly() ) {
1709 $wgOut->readOnlyPage();
1710 return;
1711 }
1712
1713 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1714
1715 # Better double-check that it hasn't been deleted yet!
1716 $dbw =& wfGetDB( DB_MASTER );
1717 $conds = $this->mTitle->pageCond();
1718 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1719 if ( $latest === false ) {
1720 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1721 return;
1722 }
1723
1724 if( $confirm ) {
1725 $this->doDelete( $reason );
1726 return;
1727 }
1728
1729 # determine whether this page has earlier revisions
1730 # and insert a warning if it does
1731 $maxRevisions = 20;
1732 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1733
1734 if( count( $authors ) > 1 && !$confirm ) {
1735 $skin=$wgUser->getSkin();
1736 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1737 }
1738
1739 # If a single user is responsible for all revisions, find out who they are
1740 if ( count( $authors ) == $maxRevisions ) {
1741 // Query bailed out, too many revisions to find out if they're all the same
1742 $authorOfAll = false;
1743 } else {
1744 $authorOfAll = reset( $authors );
1745 foreach ( $authors as $author ) {
1746 if ( $authorOfAll != $author ) {
1747 $authorOfAll = false;
1748 break;
1749 }
1750 }
1751 }
1752 # Fetch article text
1753 $rev = Revision::newFromTitle( $this->mTitle );
1754
1755 if( !is_null( $rev ) ) {
1756 # if this is a mini-text, we can paste part of it into the deletion reason
1757 $text = $rev->getText();
1758
1759 #if this is empty, an earlier revision may contain "useful" text
1760 $blanked = false;
1761 if( $text == '' ) {
1762 $prev = $rev->getPrevious();
1763 if( $prev ) {
1764 $text = $prev->getText();
1765 $blanked = true;
1766 }
1767 }
1768
1769 $length = strlen( $text );
1770
1771 # this should not happen, since it is not possible to store an empty, new
1772 # page. Let's insert a standard text in case it does, though
1773 if( $length == 0 && $reason === '' ) {
1774 $reason = wfMsgForContent( 'exblank' );
1775 }
1776
1777 if( $length < 500 && $reason === '' ) {
1778 # comment field=255, let's grep the first 150 to have some user
1779 # space left
1780 global $wgContLang;
1781 $text = $wgContLang->truncate( $text, 150, '...' );
1782
1783 # let's strip out newlines
1784 $text = preg_replace( "/[\n\r]/", '', $text );
1785
1786 if( !$blanked ) {
1787 if( $authorOfAll === false ) {
1788 $reason = wfMsgForContent( 'excontent', $text );
1789 } else {
1790 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1791 }
1792 } else {
1793 $reason = wfMsgForContent( 'exbeforeblank', $text );
1794 }
1795 }
1796 }
1797
1798 return $this->confirmDelete( '', $reason );
1799 }
1800
1801 /**
1802 * Get the last N authors
1803 * @param int $num Number of revisions to get
1804 * @param string $revLatest The latest rev_id, selected from the master (optional)
1805 * @return array Array of authors, duplicates not removed
1806 */
1807 function getLastNAuthors( $num, $revLatest = 0 ) {
1808 wfProfileIn( __METHOD__ );
1809
1810 // First try the slave
1811 // If that doesn't have the latest revision, try the master
1812 $continue = 2;
1813 $db =& wfGetDB( DB_SLAVE );
1814 do {
1815 $res = $db->select( array( 'page', 'revision' ),
1816 array( 'rev_id', 'rev_user_text' ),
1817 array(
1818 'page_namespace' => $this->mTitle->getNamespace(),
1819 'page_title' => $this->mTitle->getDBkey(),
1820 'rev_page = page_id'
1821 ), __METHOD__, $this->getSelectOptions( array(
1822 'ORDER BY' => 'rev_timestamp DESC',
1823 'LIMIT' => $num
1824 ) )
1825 );
1826 if ( !$res ) {
1827 wfProfileOut( __METHOD__ );
1828 return array();
1829 }
1830 $row = $db->fetchObject( $res );
1831 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1832 $db =& wfGetDB( DB_MASTER );
1833 $continue--;
1834 } else {
1835 $continue = 0;
1836 }
1837 } while ( $continue );
1838
1839 $authors = array( $row->rev_user_text );
1840 while ( $row = $db->fetchObject( $res ) ) {
1841 $authors[] = $row->rev_user_text;
1842 }
1843 wfProfileOut( __METHOD__ );
1844 return $authors;
1845 }
1846
1847 /**
1848 * Output deletion confirmation dialog
1849 */
1850 function confirmDelete( $par, $reason ) {
1851 global $wgOut, $wgUser;
1852
1853 wfDebug( "Article::confirmDelete\n" );
1854
1855 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1856 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1857 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1858 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1859
1860 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1861
1862 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1863 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1864 $token = htmlspecialchars( $wgUser->editToken() );
1865
1866 $wgOut->addHTML( "
1867 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1868 <table border='0'>
1869 <tr>
1870 <td align='right'>
1871 <label for='wpReason'>{$delcom}:</label>
1872 </td>
1873 <td align='left'>
1874 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1875 </td>
1876 </tr>
1877 <tr>
1878 <td>&nbsp;</td>
1879 <td>
1880 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1881 </td>
1882 </tr>
1883 </table>
1884 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1885 </form>\n" );
1886
1887 $wgOut->returnToMain( false );
1888 }
1889
1890
1891 /**
1892 * Perform a deletion and output success or failure messages
1893 */
1894 function doDelete( $reason ) {
1895 global $wgOut, $wgUser;
1896 wfDebug( __METHOD__."\n" );
1897
1898 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1899 if ( $this->doDeleteArticle( $reason ) ) {
1900 $deleted = $this->mTitle->getPrefixedText();
1901
1902 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1903 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1904
1905 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1906 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1907
1908 $wgOut->addWikiText( $text );
1909 $wgOut->returnToMain( false );
1910 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1911 } else {
1912 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1913 }
1914 }
1915 }
1916
1917 /**
1918 * Back-end article deletion
1919 * Deletes the article with database consistency, writes logs, purges caches
1920 * Returns success
1921 */
1922 function doDeleteArticle( $reason ) {
1923 global $wgUseSquid, $wgDeferredUpdateList;
1924 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1925
1926 wfDebug( __METHOD__."\n" );
1927
1928 $dbw =& wfGetDB( DB_MASTER );
1929 $ns = $this->mTitle->getNamespace();
1930 $t = $this->mTitle->getDBkey();
1931 $id = $this->mTitle->getArticleID();
1932
1933 if ( $t == '' || $id == 0 ) {
1934 return false;
1935 }
1936
1937 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1938 array_push( $wgDeferredUpdateList, $u );
1939
1940 // For now, shunt the revision data into the archive table.
1941 // Text is *not* removed from the text table; bulk storage
1942 // is left intact to avoid breaking block-compression or
1943 // immutable storage schemes.
1944 //
1945 // For backwards compatibility, note that some older archive
1946 // table entries will have ar_text and ar_flags fields still.
1947 //
1948 // In the future, we may keep revisions and mark them with
1949 // the rev_deleted field, which is reserved for this purpose.
1950 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1951 array(
1952 'ar_namespace' => 'page_namespace',
1953 'ar_title' => 'page_title',
1954 'ar_comment' => 'rev_comment',
1955 'ar_user' => 'rev_user',
1956 'ar_user_text' => 'rev_user_text',
1957 'ar_timestamp' => 'rev_timestamp',
1958 'ar_minor_edit' => 'rev_minor_edit',
1959 'ar_rev_id' => 'rev_id',
1960 'ar_text_id' => 'rev_text_id',
1961 ), array(
1962 'page_id' => $id,
1963 'page_id = rev_page'
1964 ), __METHOD__
1965 );
1966
1967 # Now that it's safely backed up, delete it
1968 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
1969 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
1970
1971 if ($wgUseTrackbacks)
1972 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
1973
1974 # Clean up recentchanges entries...
1975 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
1976
1977 # Finally, clean up the link tables
1978 $t = $this->mTitle->getPrefixedDBkey();
1979
1980 # Clear caches
1981 Article::onArticleDelete( $this->mTitle );
1982
1983 # Delete outgoing links
1984 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1985 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1986 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1987 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1988 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1989 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1990
1991 # Log the deletion
1992 $log = new LogPage( 'delete' );
1993 $log->addEntry( 'delete', $this->mTitle, $reason );
1994
1995 # Clear the cached article id so the interface doesn't act like we exist
1996 $this->mTitle->resetArticleID( 0 );
1997 $this->mTitle->mArticleID = 0;
1998 return true;
1999 }
2000
2001 /**
2002 * Revert a modification
2003 */
2004 function rollback() {
2005 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2006
2007 if( $wgUser->isAllowed( 'rollback' ) ) {
2008 if( $wgUser->isBlocked() ) {
2009 $wgOut->blockedPage();
2010 return;
2011 }
2012 } else {
2013 $wgOut->permissionRequired( 'rollback' );
2014 return;
2015 }
2016
2017 if ( wfReadOnly() ) {
2018 $wgOut->readOnlyPage( $this->getContent() );
2019 return;
2020 }
2021 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2022 array( $this->mTitle->getPrefixedText(),
2023 $wgRequest->getVal( 'from' ) ) ) ) {
2024 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2025 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2026 return;
2027 }
2028 $dbw =& wfGetDB( DB_MASTER );
2029
2030 # Enhanced rollback, marks edits rc_bot=1
2031 $bot = $wgRequest->getBool( 'bot' );
2032
2033 # Replace all this user's current edits with the next one down
2034 $tt = $this->mTitle->getDBKey();
2035 $n = $this->mTitle->getNamespace();
2036
2037 # Get the last editor
2038 $current = Revision::newFromTitle( $this->mTitle );
2039 if( is_null( $current ) ) {
2040 # Something wrong... no page?
2041 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2042 return;
2043 }
2044
2045 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2046 if( $from != $current->getUserText() ) {
2047 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2048 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2049 htmlspecialchars( $this->mTitle->getPrefixedText()),
2050 htmlspecialchars( $from ),
2051 htmlspecialchars( $current->getUserText() ) ) );
2052 if( $current->getComment() != '') {
2053 $wgOut->addHTML(
2054 wfMsg( 'editcomment',
2055 htmlspecialchars( $current->getComment() ) ) );
2056 }
2057 return;
2058 }
2059
2060 # Get the last edit not by this guy
2061 $user = intval( $current->getUser() );
2062 $user_text = $dbw->addQuotes( $current->getUserText() );
2063 $s = $dbw->selectRow( 'revision',
2064 array( 'rev_id', 'rev_timestamp' ),
2065 array(
2066 'rev_page' => $current->getPage(),
2067 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2068 ), __METHOD__,
2069 array(
2070 'USE INDEX' => 'page_timestamp',
2071 'ORDER BY' => 'rev_timestamp DESC' )
2072 );
2073 if( $s === false ) {
2074 # Something wrong
2075 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2076 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2077 return;
2078 }
2079
2080 $set = array();
2081 if ( $bot ) {
2082 # Mark all reverted edits as bot
2083 $set['rc_bot'] = 1;
2084 }
2085 if ( $wgUseRCPatrol ) {
2086 # Mark all reverted edits as patrolled
2087 $set['rc_patrolled'] = 1;
2088 }
2089
2090 if ( $set ) {
2091 $dbw->update( 'recentchanges', $set,
2092 array( /* WHERE */
2093 'rc_cur_id' => $current->getPage(),
2094 'rc_user_text' => $current->getUserText(),
2095 "rc_timestamp > '{$s->rev_timestamp}'",
2096 ), __METHOD__
2097 );
2098 }
2099
2100 # Get the edit summary
2101 $target = Revision::newFromId( $s->rev_id );
2102 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2103 $newComment = $wgRequest->getText( 'summary', $newComment );
2104
2105 # Save it!
2106 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2107 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2108 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2109
2110 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2111
2112 $wgOut->returnToMain( false );
2113 }
2114
2115
2116 /**
2117 * Do standard deferred updates after page view
2118 * @private
2119 */
2120 function viewUpdates() {
2121 global $wgDeferredUpdateList;
2122
2123 if ( 0 != $this->getID() ) {
2124 global $wgDisableCounters;
2125 if( !$wgDisableCounters ) {
2126 Article::incViewCount( $this->getID() );
2127 $u = new SiteStatsUpdate( 1, 0, 0 );
2128 array_push( $wgDeferredUpdateList, $u );
2129 }
2130 }
2131
2132 # Update newtalk / watchlist notification status
2133 global $wgUser;
2134 $wgUser->clearNotification( $this->mTitle );
2135 }
2136
2137 /**
2138 * Do standard deferred updates after page edit.
2139 * Update links tables, site stats, search index and message cache.
2140 * Every 1000th edit, prune the recent changes table.
2141 *
2142 * @private
2143 * @param string $text
2144 */
2145 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2146 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2147
2148 wfProfileIn( __METHOD__ );
2149
2150 # Parse the text
2151 $options = new ParserOptions;
2152 $options->setTidy(true);
2153 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2154
2155 # Save it to the parser cache
2156 $parserCache =& ParserCache::singleton();
2157 $parserCache->save( $poutput, $this, $wgUser );
2158
2159 # Update the links tables
2160 $u = new LinksUpdate( $this->mTitle, $poutput );
2161 $u->doUpdate();
2162
2163 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2164 wfSeedRandom();
2165 if ( 0 == mt_rand( 0, 999 ) ) {
2166 # Periodically flush old entries from the recentchanges table.
2167 global $wgRCMaxAge;
2168
2169 $dbw =& wfGetDB( DB_MASTER );
2170 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2171 $recentchanges = $dbw->tableName( 'recentchanges' );
2172 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2173 $dbw->query( $sql );
2174 }
2175 }
2176
2177 $id = $this->getID();
2178 $title = $this->mTitle->getPrefixedDBkey();
2179 $shortTitle = $this->mTitle->getDBkey();
2180
2181 if ( 0 == $id ) {
2182 wfProfileOut( __METHOD__ );
2183 return;
2184 }
2185
2186 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2187 array_push( $wgDeferredUpdateList, $u );
2188 $u = new SearchUpdate( $id, $title, $text );
2189 array_push( $wgDeferredUpdateList, $u );
2190
2191 # If this is another user's talk page, update newtalk
2192
2193 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2194 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2195 $other = User::newFromName( $shortTitle );
2196 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2197 // An anonymous user
2198 $other = new User();
2199 $other->setName( $shortTitle );
2200 }
2201 if( $other ) {
2202 $other->setNewtalk( true );
2203 }
2204 }
2205 }
2206
2207 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2208 $wgMessageCache->replace( $shortTitle, $text );
2209 }
2210
2211 wfProfileOut( __METHOD__ );
2212 }
2213
2214 /**
2215 * Generate the navigation links when browsing through an article revisions
2216 * It shows the information as:
2217 * Revision as of \<date\>; view current revision
2218 * \<- Previous version | Next Version -\>
2219 *
2220 * @private
2221 * @param string $oldid Revision ID of this article revision
2222 */
2223 function setOldSubtitle( $oldid=0 ) {
2224 global $wgLang, $wgOut, $wgUser;
2225
2226 $current = ( $oldid == $this->mLatest );
2227 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2228 $sk = $wgUser->getSkin();
2229 $lnk = $current
2230 ? wfMsg( 'currentrevisionlink' )
2231 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2232 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2233 $prevlink = $prev
2234 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2235 : wfMsg( 'previousrevision' );
2236 $nextlink = $current
2237 ? wfMsg( 'nextrevision' )
2238 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2239 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2240 $wgOut->setSubtitle( $r );
2241 }
2242
2243 /**
2244 * This function is called right before saving the wikitext,
2245 * so we can do things like signatures and links-in-context.
2246 *
2247 * @param string $text
2248 */
2249 function preSaveTransform( $text ) {
2250 global $wgParser, $wgUser;
2251 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2252 }
2253
2254 /* Caching functions */
2255
2256 /**
2257 * checkLastModified returns true if it has taken care of all
2258 * output to the client that is necessary for this request.
2259 * (that is, it has sent a cached version of the page)
2260 */
2261 function tryFileCache() {
2262 static $called = false;
2263 if( $called ) {
2264 wfDebug( " tryFileCache() -- called twice!?\n" );
2265 return;
2266 }
2267 $called = true;
2268 if($this->isFileCacheable()) {
2269 $touched = $this->mTouched;
2270 $cache = new CacheManager( $this->mTitle );
2271 if($cache->isFileCacheGood( $touched )) {
2272 wfDebug( " tryFileCache() - about to load\n" );
2273 $cache->loadFromFileCache();
2274 return true;
2275 } else {
2276 wfDebug( " tryFileCache() - starting buffer\n" );
2277 ob_start( array(&$cache, 'saveToFileCache' ) );
2278 }
2279 } else {
2280 wfDebug( " tryFileCache() - not cacheable\n" );
2281 }
2282 }
2283
2284 /**
2285 * Check if the page can be cached
2286 * @return bool
2287 */
2288 function isFileCacheable() {
2289 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2290 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2291
2292 return $wgUseFileCache
2293 and (!$wgShowIPinHeader)
2294 and ($this->getID() != 0)
2295 and ($wgUser->isAnon())
2296 and (!$wgUser->getNewtalk())
2297 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2298 and (empty( $action ) || $action == 'view')
2299 and (!isset($oldid))
2300 and (!isset($diff))
2301 and (!isset($redirect))
2302 and (!isset($printable))
2303 and (!$this->mRedirectedFrom);
2304 }
2305
2306 /**
2307 * Loads page_touched and returns a value indicating if it should be used
2308 *
2309 */
2310 function checkTouched() {
2311 if( !$this->mDataLoaded ) {
2312 $this->loadPageData();
2313 }
2314 return !$this->mIsRedirect;
2315 }
2316
2317 /**
2318 * Get the page_touched field
2319 */
2320 function getTouched() {
2321 # Ensure that page data has been loaded
2322 if( !$this->mDataLoaded ) {
2323 $this->loadPageData();
2324 }
2325 return $this->mTouched;
2326 }
2327
2328 /**
2329 * Get the page_latest field
2330 */
2331 function getLatest() {
2332 if ( !$this->mDataLoaded ) {
2333 $this->loadPageData();
2334 }
2335 return $this->mLatest;
2336 }
2337
2338 /**
2339 * Edit an article without doing all that other stuff
2340 * The article must already exist; link tables etc
2341 * are not updated, caches are not flushed.
2342 *
2343 * @param string $text text submitted
2344 * @param string $comment comment submitted
2345 * @param bool $minor whereas it's a minor modification
2346 */
2347 function quickEdit( $text, $comment = '', $minor = 0 ) {
2348 wfProfileIn( __METHOD__ );
2349
2350 $dbw =& wfGetDB( DB_MASTER );
2351 $dbw->begin();
2352 $revision = new Revision( array(
2353 'page' => $this->getId(),
2354 'text' => $text,
2355 'comment' => $comment,
2356 'minor_edit' => $minor ? 1 : 0,
2357 ) );
2358 # fixme : $revisionId never used
2359 $revisionId = $revision->insertOn( $dbw );
2360 $this->updateRevisionOn( $dbw, $revision );
2361 $dbw->commit();
2362
2363 wfProfileOut( __METHOD__ );
2364 }
2365
2366 /**
2367 * Used to increment the view counter
2368 *
2369 * @static
2370 * @param integer $id article id
2371 */
2372 function incViewCount( $id ) {
2373 $id = intval( $id );
2374 global $wgHitcounterUpdateFreq, $wgDBtype;
2375
2376 $dbw =& wfGetDB( DB_MASTER );
2377 $pageTable = $dbw->tableName( 'page' );
2378 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2379 $acchitsTable = $dbw->tableName( 'acchits' );
2380
2381 if( $wgHitcounterUpdateFreq <= 1 ){ //
2382 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2383 return;
2384 }
2385
2386 # Not important enough to warrant an error page in case of failure
2387 $oldignore = $dbw->ignoreErrors( true );
2388
2389 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2390
2391 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2392 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2393 # Most of the time (or on SQL errors), skip row count check
2394 $dbw->ignoreErrors( $oldignore );
2395 return;
2396 }
2397
2398 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2399 $row = $dbw->fetchObject( $res );
2400 $rown = intval( $row->n );
2401 if( $rown >= $wgHitcounterUpdateFreq ){
2402 wfProfileIn( 'Article::incViewCount-collect' );
2403 $old_user_abort = ignore_user_abort( true );
2404
2405 if ($wgDBtype == 'mysql')
2406 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2407 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2408 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2409 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2410 'GROUP BY hc_id');
2411 $dbw->query("DELETE FROM $hitcounterTable");
2412 if ($wgDBtype == 'mysql')
2413 $dbw->query('UNLOCK TABLES');
2414 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2415 'WHERE page_id = hc_id');
2416 $dbw->query("DROP TABLE $acchitsTable");
2417
2418 ignore_user_abort( $old_user_abort );
2419 wfProfileOut( 'Article::incViewCount-collect' );
2420 }
2421 $dbw->ignoreErrors( $oldignore );
2422 }
2423
2424 /**#@+
2425 * The onArticle*() functions are supposed to be a kind of hooks
2426 * which should be called whenever any of the specified actions
2427 * are done.
2428 *
2429 * This is a good place to put code to clear caches, for instance.
2430 *
2431 * This is called on page move and undelete, as well as edit
2432 * @static
2433 * @param $title_obj a title object
2434 */
2435
2436 static function onArticleCreate($title) {
2437 # The talk page isn't in the regular link tables, so we need to update manually:
2438 if ( $title->isTalkPage() ) {
2439 $other = $title->getSubjectPage();
2440 } else {
2441 $other = $title->getTalkPage();
2442 }
2443 $other->invalidateCache();
2444 $other->purgeSquid();
2445
2446 $title->touchLinks();
2447 $title->purgeSquid();
2448 }
2449
2450 static function onArticleDelete( $title ) {
2451 global $wgUseFileCache, $wgMessageCache;
2452
2453 $title->touchLinks();
2454 $title->purgeSquid();
2455
2456 # File cache
2457 if ( $wgUseFileCache ) {
2458 $cm = new CacheManager( $title );
2459 @unlink( $cm->fileCacheName() );
2460 }
2461
2462 if( $title->getNamespace() == NS_MEDIAWIKI) {
2463 $wgMessageCache->replace( $title->getDBkey(), false );
2464 }
2465 }
2466
2467 /**
2468 * Purge caches on page update etc
2469 */
2470 static function onArticleEdit( $title ) {
2471 global $wgDeferredUpdateList, $wgUseFileCache;
2472
2473 $urls = array();
2474
2475 // Invalidate caches of articles which include this page
2476 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2477 $wgDeferredUpdateList[] = $update;
2478
2479 # Purge squid for this page only
2480 $title->purgeSquid();
2481
2482 # Clear file cache
2483 if ( $wgUseFileCache ) {
2484 $cm = new CacheManager( $title );
2485 @unlink( $cm->fileCacheName() );
2486 }
2487 }
2488
2489 /**#@-*/
2490
2491 /**
2492 * Info about this page
2493 * Called for ?action=info when $wgAllowPageInfo is on.
2494 *
2495 * @public
2496 */
2497 function info() {
2498 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2499
2500 if ( !$wgAllowPageInfo ) {
2501 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2502 return;
2503 }
2504
2505 $page = $this->mTitle->getSubjectPage();
2506
2507 $wgOut->setPagetitle( $page->getPrefixedText() );
2508 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2509
2510 # first, see if the page exists at all.
2511 $exists = $page->getArticleId() != 0;
2512 if( !$exists ) {
2513 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2514 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2515 } else {
2516 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2517 }
2518 } else {
2519 $dbr =& wfGetDB( DB_SLAVE );
2520 $wl_clause = array(
2521 'wl_title' => $page->getDBkey(),
2522 'wl_namespace' => $page->getNamespace() );
2523 $numwatchers = $dbr->selectField(
2524 'watchlist',
2525 'COUNT(*)',
2526 $wl_clause,
2527 __METHOD__,
2528 $this->getSelectOptions() );
2529
2530 $pageInfo = $this->pageCountInfo( $page );
2531 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2532
2533 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2534 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2535 if( $talkInfo ) {
2536 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2537 }
2538 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2539 if( $talkInfo ) {
2540 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2541 }
2542 $wgOut->addHTML( '</ul>' );
2543
2544 }
2545 }
2546
2547 /**
2548 * Return the total number of edits and number of unique editors
2549 * on a given page. If page does not exist, returns false.
2550 *
2551 * @param Title $title
2552 * @return array
2553 * @private
2554 */
2555 function pageCountInfo( $title ) {
2556 $id = $title->getArticleId();
2557 if( $id == 0 ) {
2558 return false;
2559 }
2560
2561 $dbr =& wfGetDB( DB_SLAVE );
2562
2563 $rev_clause = array( 'rev_page' => $id );
2564
2565 $edits = $dbr->selectField(
2566 'revision',
2567 'COUNT(rev_page)',
2568 $rev_clause,
2569 __METHOD__,
2570 $this->getSelectOptions() );
2571
2572 $authors = $dbr->selectField(
2573 'revision',
2574 'COUNT(DISTINCT rev_user_text)',
2575 $rev_clause,
2576 __METHOD__,
2577 $this->getSelectOptions() );
2578
2579 return array( 'edits' => $edits, 'authors' => $authors );
2580 }
2581
2582 /**
2583 * Return a list of templates used by this article.
2584 * Uses the templatelinks table
2585 *
2586 * @return array Array of Title objects
2587 */
2588 function getUsedTemplates() {
2589 $result = array();
2590 $id = $this->mTitle->getArticleID();
2591 if( $id == 0 ) {
2592 return array();
2593 }
2594
2595 $dbr =& wfGetDB( DB_SLAVE );
2596 $res = $dbr->select( array( 'templatelinks' ),
2597 array( 'tl_namespace', 'tl_title' ),
2598 array( 'tl_from' => $id ),
2599 'Article:getUsedTemplates' );
2600 if ( false !== $res ) {
2601 if ( $dbr->numRows( $res ) ) {
2602 while ( $row = $dbr->fetchObject( $res ) ) {
2603 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2604 }
2605 }
2606 }
2607 $dbr->freeResult( $res );
2608 return $result;
2609 }
2610 }
2611
2612 ?>