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