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