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