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