13dc5a0b1d4e4a35dd2e512ed7d0a239dee7972d
[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, $wgContentNamespaces;
542
543 $token = $wgUseCommaCount ? ',' : '[[';
544 return
545 array_search( $this->mTitle->getNamespace(), $wgContentNamespaces ) !== false
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 # Don't show section-edit links on old revisions... this way lies madness.
867 if( !$this->isCurrent() ) {
868 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
869 }
870 # Display content and don't save to parser cache
871 $wgOut->addPrimaryWikiText( $text, $this, false );
872
873 if( !$this->isCurrent() ) {
874 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
875 }
876 }
877 }
878 /* title may have been set from the cache */
879 $t = $wgOut->getPageTitle();
880 if( empty( $t ) ) {
881 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
882 }
883
884 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
885 if( $ns == NS_USER_TALK &&
886 User::isIP( $this->mTitle->getText() ) ) {
887 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
888 }
889
890 # If we have been passed an &rcid= parameter, we want to give the user a
891 # chance to mark this new article as patrolled.
892 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
893 $wgOut->addHTML(
894 "<div class='patrollink'>" .
895 wfMsg ( 'markaspatrolledlink',
896 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
897 ) .
898 '</div>'
899 );
900 }
901
902 # Trackbacks
903 if ($wgUseTrackbacks)
904 $this->addTrackbacks();
905
906 $this->viewUpdates();
907 wfProfileOut( $fname );
908 }
909
910 function addTrackbacks() {
911 global $wgOut, $wgUser;
912
913 $dbr =& wfGetDB(DB_SLAVE);
914 $tbs = $dbr->select(
915 /* FROM */ 'trackbacks',
916 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
917 /* WHERE */ array('tb_page' => $this->getID())
918 );
919
920 if (!$dbr->numrows($tbs))
921 return;
922
923 $tbtext = "";
924 while ($o = $dbr->fetchObject($tbs)) {
925 $rmvtxt = "";
926 if ($wgUser->isAllowed( 'trackback' )) {
927 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
928 . $o->tb_id . "&token=" . $wgUser->editToken());
929 $rmvtxt = wfMsg('trackbackremove', $delurl);
930 }
931 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
932 $o->tb_title,
933 $o->tb_url,
934 $o->tb_ex,
935 $o->tb_name,
936 $rmvtxt);
937 }
938 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
939 }
940
941 function deletetrackback() {
942 global $wgUser, $wgRequest, $wgOut, $wgTitle;
943
944 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
945 $wgOut->addWikitext(wfMsg('sessionfailure'));
946 return;
947 }
948
949 if ((!$wgUser->isAllowed('delete'))) {
950 $wgOut->sysopRequired();
951 return;
952 }
953
954 if (wfReadOnly()) {
955 $wgOut->readOnlyPage();
956 return;
957 }
958
959 $db =& wfGetDB(DB_MASTER);
960 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
961 $wgTitle->invalidateCache();
962 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
963 }
964
965 function render() {
966 global $wgOut;
967
968 $wgOut->setArticleBodyOnly(true);
969 $this->view();
970 }
971
972 /**
973 * Handle action=purge
974 */
975 function purge() {
976 global $wgUser, $wgRequest, $wgOut;
977
978 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
979 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
980 $this->doPurge();
981 }
982 } else {
983 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
984 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
985 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
986 $msg = str_replace( '$1',
987 "<form method=\"post\" action=\"$action\">\n" .
988 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
989 "</form>\n", $msg );
990
991 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
992 $wgOut->setRobotpolicy( 'noindex,nofollow' );
993 $wgOut->addHTML( $msg );
994 }
995 }
996
997 /**
998 * Perform the actions of a page purging
999 */
1000 function doPurge() {
1001 global $wgUseSquid;
1002 // Invalidate the cache
1003 $this->mTitle->invalidateCache();
1004
1005 if ( $wgUseSquid ) {
1006 // Commit the transaction before the purge is sent
1007 $dbw = wfGetDB( DB_MASTER );
1008 $dbw->immediateCommit();
1009
1010 // Send purge
1011 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1012 $update->doUpdate();
1013 }
1014 $this->view();
1015 }
1016
1017 /**
1018 * Insert a new empty page record for this article.
1019 * This *must* be followed up by creating a revision
1020 * and running $this->updateToLatest( $rev_id );
1021 * or else the record will be left in a funky state.
1022 * Best if all done inside a transaction.
1023 *
1024 * @param Database $dbw
1025 * @param string $restrictions
1026 * @return int The newly created page_id key
1027 * @private
1028 */
1029 function insertOn( &$dbw, $restrictions = '' ) {
1030 $fname = 'Article::insertOn';
1031 wfProfileIn( $fname );
1032
1033 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1034 $dbw->insert( 'page', array(
1035 'page_id' => $page_id,
1036 'page_namespace' => $this->mTitle->getNamespace(),
1037 'page_title' => $this->mTitle->getDBkey(),
1038 'page_counter' => 0,
1039 'page_restrictions' => $restrictions,
1040 'page_is_redirect' => 0, # Will set this shortly...
1041 'page_is_new' => 1,
1042 'page_random' => wfRandom(),
1043 'page_touched' => $dbw->timestamp(),
1044 'page_latest' => 0, # Fill this in shortly...
1045 'page_len' => 0, # Fill this in shortly...
1046 ), $fname );
1047 $newid = $dbw->insertId();
1048
1049 $this->mTitle->resetArticleId( $newid );
1050
1051 wfProfileOut( $fname );
1052 return $newid;
1053 }
1054
1055 /**
1056 * Update the page record to point to a newly saved revision.
1057 *
1058 * @param Database $dbw
1059 * @param Revision $revision For ID number, and text used to set
1060 length and redirect status fields
1061 * @param int $lastRevision If given, will not overwrite the page field
1062 * when different from the currently set value.
1063 * Giving 0 indicates the new page flag should
1064 * be set on.
1065 * @return bool true on success, false on failure
1066 * @private
1067 */
1068 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1069 $fname = 'Article::updateToRevision';
1070 wfProfileIn( $fname );
1071
1072 $conditions = array( 'page_id' => $this->getId() );
1073 if( !is_null( $lastRevision ) ) {
1074 # An extra check against threads stepping on each other
1075 $conditions['page_latest'] = $lastRevision;
1076 }
1077
1078 $text = $revision->getText();
1079 $dbw->update( 'page',
1080 array( /* SET */
1081 'page_latest' => $revision->getId(),
1082 'page_touched' => $dbw->timestamp(),
1083 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1084 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1085 'page_len' => strlen( $text ),
1086 ),
1087 $conditions,
1088 $fname );
1089
1090 wfProfileOut( $fname );
1091 return ( $dbw->affectedRows() != 0 );
1092 }
1093
1094 /**
1095 * If the given revision is newer than the currently set page_latest,
1096 * update the page record. Otherwise, do nothing.
1097 *
1098 * @param Database $dbw
1099 * @param Revision $revision
1100 */
1101 function updateIfNewerOn( &$dbw, $revision ) {
1102 $fname = 'Article::updateIfNewerOn';
1103 wfProfileIn( $fname );
1104
1105 $row = $dbw->selectRow(
1106 array( 'revision', 'page' ),
1107 array( 'rev_id', 'rev_timestamp' ),
1108 array(
1109 'page_id' => $this->getId(),
1110 'page_latest=rev_id' ),
1111 $fname );
1112 if( $row ) {
1113 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1114 wfProfileOut( $fname );
1115 return false;
1116 }
1117 $prev = $row->rev_id;
1118 } else {
1119 # No or missing previous revision; mark the page as new
1120 $prev = 0;
1121 }
1122
1123 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1124 wfProfileOut( $fname );
1125 return $ret;
1126 }
1127
1128 /**
1129 * Insert a new article into the database
1130 * @private
1131 */
1132 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1133 global $wgUser;
1134
1135 $fname = 'Article::insertNewArticle';
1136 wfProfileIn( $fname );
1137
1138 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1139 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1140 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1141 wfProfileOut( $fname );
1142 return false;
1143 }
1144
1145 $ns = $this->mTitle->getNamespace();
1146 $ttl = $this->mTitle->getDBkey();
1147
1148 # If this is a comment, add the summary as headline
1149 if($comment && $summary!="") {
1150 $text="== {$summary} ==\n\n".$text;
1151 }
1152 $text = $this->preSaveTransform( $text );
1153
1154
1155 # Set statistics members
1156 # We work out if it's countable after PST to avoid counter drift
1157 # when articles are created with {{subst:}}
1158 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1159 $this->mTotalAdjustment = 1;
1160
1161 /* Silently ignore minoredit if not allowed */
1162 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1163 $now = wfTimestampNow();
1164
1165 $dbw =& wfGetDB( DB_MASTER );
1166
1167 # Add the page record; stake our claim on this title!
1168 $newid = $this->insertOn( $dbw );
1169
1170 # Save the revision text...
1171 $revision = new Revision( array(
1172 'page' => $newid,
1173 'comment' => $summary,
1174 'minor_edit' => $isminor,
1175 'text' => $text
1176 ) );
1177 $revisionId = $revision->insertOn( $dbw );
1178
1179 $this->mTitle->resetArticleID( $newid );
1180
1181 # Update the page record with revision data
1182 $this->updateRevisionOn( $dbw, $revision, 0 );
1183
1184 if(!$suppressRC) {
1185 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1186 '', strlen( $text ), $revisionId );
1187 # Mark as patrolled if the user can and has the option set
1188 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1189 RecentChange::markPatrolled( $rcid );
1190 }
1191 }
1192
1193 if ($watchthis) {
1194 if(!$this->mTitle->userIsWatching()) $this->doWatch();
1195 } else {
1196 if ( $this->mTitle->userIsWatching() ) {
1197 $this->doUnwatch();
1198 }
1199 }
1200
1201 # The talk page isn't in the regular link tables, so we need to update manually:
1202 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1203 $dbw->update( 'page',
1204 array( 'page_touched' => $dbw->timestamp($now) ),
1205 array( 'page_namespace' => $talkns,
1206 'page_title' => $ttl ),
1207 $fname );
1208
1209 # Update links, etc.
1210 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1211
1212 # Clear caches
1213 Article::onArticleCreate( $this->mTitle );
1214
1215 # Output a redirect back to the article
1216 $this->doRedirect( $this->isRedirect( $text ) );
1217
1218 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1219 $summary, $isminor,
1220 $watchthis, NULL ) );
1221 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1222 $summary, $isminor,
1223 $watchthis, NULL ) );
1224 wfProfileOut( $fname );
1225 }
1226
1227 /**
1228 * @return string Complete article text, or null if error
1229 */
1230 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1231 $fname = 'Article::replaceSection';
1232 wfProfileIn( $fname );
1233
1234 if( $section == '' ) {
1235 // Whole-page edit; let the text through unmolested.
1236 } else {
1237 if( is_null( $edittime ) ) {
1238 $rev = Revision::newFromTitle( $this->mTitle );
1239 } else {
1240 $dbw =& wfGetDB( DB_MASTER );
1241 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1242 }
1243 if( is_null( $rev ) ) {
1244 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1245 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1246 return null;
1247 }
1248 $oldtext = $rev->getText();
1249
1250 if($section=='new') {
1251 if($summary) $subject="== {$summary} ==\n\n";
1252 $text=$oldtext."\n\n".$subject.$text;
1253 } else {
1254 global $wgParser;
1255 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1256 }
1257 }
1258
1259 wfProfileOut( $fname );
1260 return $text;
1261 }
1262
1263 /**
1264 * Change an existing article. Puts the previous version back into the old table, updates RC
1265 * and all necessary caches, mostly via the deferred update array.
1266 *
1267 * It is possible to call this function from a command-line script, but note that you should
1268 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1269 */
1270 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1271 global $wgUser, $wgDBtransactions, $wgUseSquid;
1272 global $wgPostCommitUpdateList, $wgUseFileCache;
1273
1274 $fname = 'Article::updateArticle';
1275 wfProfileIn( $fname );
1276 $good = true;
1277
1278 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1279 &$summary, &$minor,
1280 &$watchthis, &$sectionanchor ) ) ) {
1281 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1282 wfProfileOut( $fname );
1283 return false;
1284 }
1285
1286 $isminor = $minor && $wgUser->isAllowed('minoredit');
1287
1288 $text = $this->preSaveTransform( $text );
1289 $dbw =& wfGetDB( DB_MASTER );
1290 $now = wfTimestampNow();
1291
1292 # Update article, but only if changed.
1293
1294 # It's important that we either rollback or complete, otherwise an attacker could
1295 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1296 # could conceivably have the same effect, especially if cur is locked for long periods.
1297 if( !$wgDBtransactions ) {
1298 $userAbort = ignore_user_abort( true );
1299 }
1300
1301 $oldtext = $this->getContent();
1302 $oldsize = strlen( $oldtext );
1303 $newsize = strlen( $text );
1304 $lastRevision = 0;
1305 $revisionId = 0;
1306
1307 if ( 0 != strcmp( $text, $oldtext ) ) {
1308 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1309 - (int)$this->isCountable( $oldtext );
1310 $this->mTotalAdjustment = 0;
1311 $now = wfTimestampNow();
1312
1313 $lastRevision = $dbw->selectField(
1314 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1315
1316 $revision = new Revision( array(
1317 'page' => $this->getId(),
1318 'comment' => $summary,
1319 'minor_edit' => $isminor,
1320 'text' => $text
1321 ) );
1322
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
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 } else {
1348 // Keep the same revision ID, but do some updates on it
1349 $revisionId = $this->getRevIdFetched();
1350 }
1351
1352 if( !$wgDBtransactions ) {
1353 ignore_user_abort( $userAbort );
1354 }
1355
1356 if ( $good ) {
1357 # Invalidate cache of this article and all pages using this article
1358 # as a template. Partly deferred.
1359 Article::onArticleEdit( $this->mTitle );
1360
1361 if ($watchthis) {
1362 if (!$this->mTitle->userIsWatching()) {
1363 $dbw->begin();
1364 $this->doWatch();
1365 $dbw->commit();
1366 }
1367 } else {
1368 if ( $this->mTitle->userIsWatching() ) {
1369 $dbw->begin();
1370 $this->doUnwatch();
1371 $dbw->commit();
1372 }
1373 }
1374 # Update links tables, site stats, etc.
1375 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1376
1377 # Output a redirect back to the article
1378 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1379 }
1380 wfRunHooks( 'ArticleSaveComplete',
1381 array( &$this, &$wgUser, $text,
1382 $summary, $minor,
1383 $watchthis, $sectionanchor ) );
1384 wfProfileOut( $fname );
1385 return $good;
1386 }
1387
1388 /**
1389 * @deprecated wrapper for doRedirect
1390 */
1391 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1392 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1393 }
1394
1395 /**
1396 * Output a redirect back to the article.
1397 * This is typically used after an edit.
1398 *
1399 * @param boolean $noRedir Add redirect=no
1400 * @param string $sectionAnchor section to redirect to, including "#"
1401 */
1402 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1403 global $wgOut;
1404 if ( $noRedir ) {
1405 $query = 'redirect=no';
1406 } else {
1407 $query = '';
1408 }
1409 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1410 }
1411
1412 /**
1413 * Mark this particular edit as patrolled
1414 */
1415 function markpatrolled() {
1416 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1417 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1418
1419 # Check RC patrol config. option
1420 if( !$wgUseRCPatrol ) {
1421 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1422 return;
1423 }
1424
1425 # Check permissions
1426 if( !$wgUser->isAllowed( 'patrol' ) ) {
1427 $wgOut->permissionRequired( 'patrol' );
1428 return;
1429 }
1430
1431 $rcid = $wgRequest->getVal( 'rcid' );
1432 if ( !is_null ( $rcid ) ) {
1433 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1434 RecentChange::markPatrolled( $rcid );
1435 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1436 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1437 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1438 }
1439 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1440 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1441 }
1442 else {
1443 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1444 }
1445 }
1446
1447 /**
1448 * User-interface handler for the "watch" action
1449 */
1450
1451 function watch() {
1452
1453 global $wgUser, $wgOut;
1454
1455 if ( $wgUser->isAnon() ) {
1456 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1457 return;
1458 }
1459 if ( wfReadOnly() ) {
1460 $wgOut->readOnlyPage();
1461 return;
1462 }
1463
1464 if( $this->doWatch() ) {
1465 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1466 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1467
1468 $link = $this->mTitle->getPrefixedText();
1469 $text = wfMsg( 'addedwatchtext', $link );
1470 $wgOut->addWikiText( $text );
1471 }
1472
1473 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1474 }
1475
1476 /**
1477 * Add this page to $wgUser's watchlist
1478 * @return bool true on successful watch operation
1479 */
1480 function doWatch() {
1481 global $wgUser;
1482 if( $wgUser->isAnon() ) {
1483 return false;
1484 }
1485
1486 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1487 $wgUser->addWatch( $this->mTitle );
1488 $wgUser->saveSettings();
1489
1490 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1491 }
1492
1493 return false;
1494 }
1495
1496 /**
1497 * User interface handler for the "unwatch" action.
1498 */
1499 function unwatch() {
1500
1501 global $wgUser, $wgOut;
1502
1503 if ( $wgUser->isAnon() ) {
1504 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1505 return;
1506 }
1507 if ( wfReadOnly() ) {
1508 $wgOut->readOnlyPage();
1509 return;
1510 }
1511
1512 if( $this->doUnwatch() ) {
1513 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1514 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1515
1516 $link = $this->mTitle->getPrefixedText();
1517 $text = wfMsg( 'removedwatchtext', $link );
1518 $wgOut->addWikiText( $text );
1519 }
1520
1521 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1522 }
1523
1524 /**
1525 * Stop watching a page
1526 * @return bool true on successful unwatch
1527 */
1528 function doUnwatch() {
1529 global $wgUser;
1530 if( $wgUser->isAnon() ) {
1531 return false;
1532 }
1533
1534 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1535 $wgUser->removeWatch( $this->mTitle );
1536 $wgUser->saveSettings();
1537
1538 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1539 }
1540
1541 return false;
1542 }
1543
1544 /**
1545 * action=protect handler
1546 */
1547 function protect() {
1548 require_once 'ProtectionForm.php';
1549 $form = new ProtectionForm( $this );
1550 $form->show();
1551 }
1552
1553 /**
1554 * action=unprotect handler (alias)
1555 */
1556 function unprotect() {
1557 $this->protect();
1558 }
1559
1560 /**
1561 * Update the article's restriction field, and leave a log entry.
1562 *
1563 * @param array $limit set of restriction keys
1564 * @param string $reason
1565 * @return bool true on success
1566 */
1567 function updateRestrictions( $limit = array(), $reason = '' ) {
1568 global $wgUser, $wgRestrictionTypes, $wgContLang;
1569
1570 $id = $this->mTitle->getArticleID();
1571 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1572 return false;
1573 }
1574
1575 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1576 # we expect a single selection, but the schema allows otherwise.
1577 $current = array();
1578 foreach( $wgRestrictionTypes as $action )
1579 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1580
1581 $current = Article::flattenRestrictions( $current );
1582 $updated = Article::flattenRestrictions( $limit );
1583
1584 $changed = ( $current != $updated );
1585 $protect = ( $updated != '' );
1586
1587 # If nothing's changed, do nothing
1588 if( $changed ) {
1589 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1590
1591 $dbw =& wfGetDB( DB_MASTER );
1592
1593 # Prepare a null revision to be added to the history
1594 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1595 if( $reason )
1596 $comment .= ": $reason";
1597 if( $protect )
1598 $comment .= " [$updated]";
1599 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1600 $nullRevId = $nullRevision->insertOn( $dbw );
1601
1602 # Update page record
1603 $dbw->update( 'page',
1604 array( /* SET */
1605 'page_touched' => $dbw->timestamp(),
1606 'page_restrictions' => $updated,
1607 'page_latest' => $nullRevId
1608 ), array( /* WHERE */
1609 'page_id' => $id
1610 ), 'Article::protect'
1611 );
1612 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1613
1614 # Update the protection log
1615 $log = new LogPage( 'protect' );
1616 if( $protect ) {
1617 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]" ) );
1618 } else {
1619 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1620 }
1621
1622 } # End hook
1623 } # End "changed" check
1624
1625 return true;
1626 }
1627
1628 /**
1629 * Take an array of page restrictions and flatten it to a string
1630 * suitable for insertion into the page_restrictions field.
1631 * @param array $limit
1632 * @return string
1633 * @private
1634 */
1635 function flattenRestrictions( $limit ) {
1636 if( !is_array( $limit ) ) {
1637 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1638 }
1639 $bits = array();
1640 ksort( $limit );
1641 foreach( $limit as $action => $restrictions ) {
1642 if( $restrictions != '' ) {
1643 $bits[] = "$action=$restrictions";
1644 }
1645 }
1646 return implode( ':', $bits );
1647 }
1648
1649 /*
1650 * UI entry point for page deletion
1651 */
1652 function delete() {
1653 global $wgUser, $wgOut, $wgRequest;
1654 $fname = 'Article::delete';
1655 $confirm = $wgRequest->wasPosted() &&
1656 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1657 $reason = $wgRequest->getText( 'wpReason' );
1658
1659 # This code desperately needs to be totally rewritten
1660
1661 # Check permissions
1662 if( $wgUser->isAllowed( 'delete' ) ) {
1663 if( $wgUser->isBlocked() ) {
1664 $wgOut->blockedPage();
1665 return;
1666 }
1667 } else {
1668 $wgOut->permissionRequired( 'delete' );
1669 return;
1670 }
1671
1672 if( wfReadOnly() ) {
1673 $wgOut->readOnlyPage();
1674 return;
1675 }
1676
1677 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1678
1679 # Better double-check that it hasn't been deleted yet!
1680 $dbw =& wfGetDB( DB_MASTER );
1681 $conds = $this->mTitle->pageCond();
1682 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1683 if ( $latest === false ) {
1684 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1685 return;
1686 }
1687
1688 if( $confirm ) {
1689 $this->doDelete( $reason );
1690 return;
1691 }
1692
1693 # determine whether this page has earlier revisions
1694 # and insert a warning if it does
1695 $maxRevisions = 20;
1696 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1697
1698 if( count( $authors ) > 1 && !$confirm ) {
1699 $skin=$wgUser->getSkin();
1700 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1701 }
1702
1703 # If a single user is responsible for all revisions, find out who they are
1704 if ( count( $authors ) == $maxRevisions ) {
1705 // Query bailed out, too many revisions to find out if they're all the same
1706 $authorOfAll = false;
1707 } else {
1708 $authorOfAll = reset( $authors );
1709 foreach ( $authors as $author ) {
1710 if ( $authorOfAll != $author ) {
1711 $authorOfAll = false;
1712 break;
1713 }
1714 }
1715 }
1716 # Fetch article text
1717 $rev = Revision::newFromTitle( $this->mTitle );
1718
1719 if( !is_null( $rev ) ) {
1720 # if this is a mini-text, we can paste part of it into the deletion reason
1721 $text = $rev->getText();
1722
1723 #if this is empty, an earlier revision may contain "useful" text
1724 $blanked = false;
1725 if( $text == '' ) {
1726 $prev = $rev->getPrevious();
1727 if( $prev ) {
1728 $text = $prev->getText();
1729 $blanked = true;
1730 }
1731 }
1732
1733 $length = strlen( $text );
1734
1735 # this should not happen, since it is not possible to store an empty, new
1736 # page. Let's insert a standard text in case it does, though
1737 if( $length == 0 && $reason === '' ) {
1738 $reason = wfMsgForContent( 'exblank' );
1739 }
1740
1741 if( $length < 500 && $reason === '' ) {
1742 # comment field=255, let's grep the first 150 to have some user
1743 # space left
1744 global $wgContLang;
1745 $text = $wgContLang->truncate( $text, 150, '...' );
1746
1747 # let's strip out newlines
1748 $text = preg_replace( "/[\n\r]/", '', $text );
1749
1750 if( !$blanked ) {
1751 if( $authorOfAll === false ) {
1752 $reason = wfMsgForContent( 'excontent', $text );
1753 } else {
1754 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1755 }
1756 } else {
1757 $reason = wfMsgForContent( 'exbeforeblank', $text );
1758 }
1759 }
1760 }
1761
1762 return $this->confirmDelete( '', $reason );
1763 }
1764
1765 /**
1766 * Get the last N authors
1767 * @param int $num Number of revisions to get
1768 * @param string $revLatest The latest rev_id, selected from the master (optional)
1769 * @return array Array of authors, duplicates not removed
1770 */
1771 function getLastNAuthors( $num, $revLatest = 0 ) {
1772 $fname = 'Article::getLastNAuthors';
1773 wfProfileIn( $fname );
1774
1775 // First try the slave
1776 // If that doesn't have the latest revision, try the master
1777 $continue = 2;
1778 $db =& wfGetDB( DB_SLAVE );
1779 do {
1780 $res = $db->select( array( 'page', 'revision' ),
1781 array( 'rev_id', 'rev_user_text' ),
1782 array(
1783 'page_namespace' => $this->mTitle->getNamespace(),
1784 'page_title' => $this->mTitle->getDBkey(),
1785 'rev_page = page_id'
1786 ), $fname, $this->getSelectOptions( array(
1787 'ORDER BY' => 'rev_timestamp DESC',
1788 'LIMIT' => $num
1789 ) )
1790 );
1791 if ( !$res ) {
1792 wfProfileOut( $fname );
1793 return array();
1794 }
1795 $row = $db->fetchObject( $res );
1796 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1797 $db =& wfGetDB( DB_MASTER );
1798 $continue--;
1799 } else {
1800 $continue = 0;
1801 }
1802 } while ( $continue );
1803
1804 $authors = array( $row->rev_user_text );
1805 while ( $row = $db->fetchObject( $res ) ) {
1806 $authors[] = $row->rev_user_text;
1807 }
1808 wfProfileOut( $fname );
1809 return $authors;
1810 }
1811
1812 /**
1813 * Output deletion confirmation dialog
1814 */
1815 function confirmDelete( $par, $reason ) {
1816 global $wgOut, $wgUser;
1817
1818 wfDebug( "Article::confirmDelete\n" );
1819
1820 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1821 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1822 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1823 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1824
1825 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1826
1827 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1828 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1829 $token = htmlspecialchars( $wgUser->editToken() );
1830
1831 $wgOut->addHTML( "
1832 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1833 <table border='0'>
1834 <tr>
1835 <td align='right'>
1836 <label for='wpReason'>{$delcom}:</label>
1837 </td>
1838 <td align='left'>
1839 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1840 </td>
1841 </tr>
1842 <tr>
1843 <td>&nbsp;</td>
1844 <td>
1845 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1846 </td>
1847 </tr>
1848 </table>
1849 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1850 </form>\n" );
1851
1852 $wgOut->returnToMain( false );
1853 }
1854
1855
1856 /**
1857 * Perform a deletion and output success or failure messages
1858 */
1859 function doDelete( $reason ) {
1860 global $wgOut, $wgUser;
1861 $fname = 'Article::doDelete';
1862 wfDebug( $fname."\n" );
1863
1864 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1865 if ( $this->doDeleteArticle( $reason ) ) {
1866 $deleted = $this->mTitle->getPrefixedText();
1867
1868 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1869 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1870
1871 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1872 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1873
1874 $wgOut->addWikiText( $text );
1875 $wgOut->returnToMain( false );
1876 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1877 } else {
1878 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1879 }
1880 }
1881 }
1882
1883 /**
1884 * Back-end article deletion
1885 * Deletes the article with database consistency, writes logs, purges caches
1886 * Returns success
1887 */
1888 function doDeleteArticle( $reason ) {
1889 global $wgUseSquid, $wgDeferredUpdateList;
1890 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1891
1892 $fname = 'Article::doDeleteArticle';
1893 wfDebug( $fname."\n" );
1894
1895 $dbw =& wfGetDB( DB_MASTER );
1896 $ns = $this->mTitle->getNamespace();
1897 $t = $this->mTitle->getDBkey();
1898 $id = $this->mTitle->getArticleID();
1899
1900 if ( $t == '' || $id == 0 ) {
1901 return false;
1902 }
1903
1904 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1905 array_push( $wgDeferredUpdateList, $u );
1906
1907 // For now, shunt the revision data into the archive table.
1908 // Text is *not* removed from the text table; bulk storage
1909 // is left intact to avoid breaking block-compression or
1910 // immutable storage schemes.
1911 //
1912 // For backwards compatibility, note that some older archive
1913 // table entries will have ar_text and ar_flags fields still.
1914 //
1915 // In the future, we may keep revisions and mark them with
1916 // the rev_deleted field, which is reserved for this purpose.
1917 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1918 array(
1919 'ar_namespace' => 'page_namespace',
1920 'ar_title' => 'page_title',
1921 'ar_comment' => 'rev_comment',
1922 'ar_user' => 'rev_user',
1923 'ar_user_text' => 'rev_user_text',
1924 'ar_timestamp' => 'rev_timestamp',
1925 'ar_minor_edit' => 'rev_minor_edit',
1926 'ar_rev_id' => 'rev_id',
1927 'ar_text_id' => 'rev_text_id',
1928 ), array(
1929 'page_id' => $id,
1930 'page_id = rev_page'
1931 ), $fname
1932 );
1933
1934 # Now that it's safely backed up, delete it
1935 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1936 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1937
1938 if ($wgUseTrackbacks)
1939 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
1940
1941 # Clean up recentchanges entries...
1942 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1943
1944 # Finally, clean up the link tables
1945 $t = $this->mTitle->getPrefixedDBkey();
1946
1947 # Clear caches
1948 Article::onArticleDelete( $this->mTitle );
1949
1950 # Delete outgoing links
1951 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1952 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1953 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1954 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1955 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1956 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1957
1958 # Log the deletion
1959 $log = new LogPage( 'delete' );
1960 $log->addEntry( 'delete', $this->mTitle, $reason );
1961
1962 # Clear the cached article id so the interface doesn't act like we exist
1963 $this->mTitle->resetArticleID( 0 );
1964 $this->mTitle->mArticleID = 0;
1965 return true;
1966 }
1967
1968 /**
1969 * Revert a modification
1970 */
1971 function rollback() {
1972 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
1973 $fname = 'Article::rollback';
1974
1975 if( $wgUser->isAllowed( 'rollback' ) ) {
1976 if( $wgUser->isBlocked() ) {
1977 $wgOut->blockedPage();
1978 return;
1979 }
1980 } else {
1981 $wgOut->permissionRequired( 'rollback' );
1982 return;
1983 }
1984
1985 if ( wfReadOnly() ) {
1986 $wgOut->readOnlyPage( $this->getContent() );
1987 return;
1988 }
1989 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1990 array( $this->mTitle->getPrefixedText(),
1991 $wgRequest->getVal( 'from' ) ) ) ) {
1992 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1993 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1994 return;
1995 }
1996 $dbw =& wfGetDB( DB_MASTER );
1997
1998 # Enhanced rollback, marks edits rc_bot=1
1999 $bot = $wgRequest->getBool( 'bot' );
2000
2001 # Replace all this user's current edits with the next one down
2002 $tt = $this->mTitle->getDBKey();
2003 $n = $this->mTitle->getNamespace();
2004
2005 # Get the last editor
2006 $current = Revision::newFromTitle( $this->mTitle );
2007 if( is_null( $current ) ) {
2008 # Something wrong... no page?
2009 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2010 return;
2011 }
2012
2013 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2014 if( $from != $current->getUserText() ) {
2015 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2016 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2017 htmlspecialchars( $this->mTitle->getPrefixedText()),
2018 htmlspecialchars( $from ),
2019 htmlspecialchars( $current->getUserText() ) ) );
2020 if( $current->getComment() != '') {
2021 $wgOut->addHTML(
2022 wfMsg( 'editcomment',
2023 htmlspecialchars( $current->getComment() ) ) );
2024 }
2025 return;
2026 }
2027
2028 # Get the last edit not by this guy
2029 $user = intval( $current->getUser() );
2030 $user_text = $dbw->addQuotes( $current->getUserText() );
2031 $s = $dbw->selectRow( 'revision',
2032 array( 'rev_id', 'rev_timestamp' ),
2033 array(
2034 'rev_page' => $current->getPage(),
2035 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2036 ), $fname,
2037 array(
2038 'USE INDEX' => 'page_timestamp',
2039 'ORDER BY' => 'rev_timestamp DESC' )
2040 );
2041 if( $s === false ) {
2042 # Something wrong
2043 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2044 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2045 return;
2046 }
2047
2048 $set = array();
2049 if ( $bot ) {
2050 # Mark all reverted edits as bot
2051 $set['rc_bot'] = 1;
2052 }
2053 if ( $wgUseRCPatrol ) {
2054 # Mark all reverted edits as patrolled
2055 $set['rc_patrolled'] = 1;
2056 }
2057
2058 if ( $set ) {
2059 $dbw->update( 'recentchanges', $set,
2060 array( /* WHERE */
2061 'rc_cur_id' => $current->getPage(),
2062 'rc_user_text' => $current->getUserText(),
2063 "rc_timestamp > '{$s->rev_timestamp}'",
2064 ), $fname
2065 );
2066 }
2067
2068 # Get the edit summary
2069 $target = Revision::newFromId( $s->rev_id );
2070 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2071 $newComment = $wgRequest->getText( 'summary', $newComment );
2072
2073 # Save it!
2074 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2075 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2076 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2077
2078 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2079
2080 $wgOut->returnToMain( false );
2081 }
2082
2083
2084 /**
2085 * Do standard deferred updates after page view
2086 * @private
2087 */
2088 function viewUpdates() {
2089 global $wgDeferredUpdateList;
2090
2091 if ( 0 != $this->getID() ) {
2092 global $wgDisableCounters;
2093 if( !$wgDisableCounters ) {
2094 Article::incViewCount( $this->getID() );
2095 $u = new SiteStatsUpdate( 1, 0, 0 );
2096 array_push( $wgDeferredUpdateList, $u );
2097 }
2098 }
2099
2100 # Update newtalk / watchlist notification status
2101 global $wgUser;
2102 $wgUser->clearNotification( $this->mTitle );
2103 }
2104
2105 /**
2106 * Do standard deferred updates after page edit.
2107 * Update links tables, site stats, search index and message cache.
2108 * Every 1000th edit, prune the recent changes table.
2109 *
2110 * @private
2111 * @param string $text
2112 */
2113 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2114 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2115
2116 $fname = 'Article::editUpdates';
2117 wfProfileIn( $fname );
2118
2119 # Parse the text
2120 $options = new ParserOptions;
2121 $options->setTidy(true);
2122 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2123
2124 # Save it to the parser cache
2125 $parserCache =& ParserCache::singleton();
2126 $parserCache->save( $poutput, $this, $wgUser );
2127
2128 # Update the links tables
2129 $u = new LinksUpdate( $this->mTitle, $poutput );
2130 $u->doUpdate();
2131
2132 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2133 wfSeedRandom();
2134 if ( 0 == mt_rand( 0, 999 ) ) {
2135 # Periodically flush old entries from the recentchanges table.
2136 global $wgRCMaxAge;
2137
2138 $dbw =& wfGetDB( DB_MASTER );
2139 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2140 $recentchanges = $dbw->tableName( 'recentchanges' );
2141 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2142 $dbw->query( $sql );
2143 }
2144 }
2145
2146 $id = $this->getID();
2147 $title = $this->mTitle->getPrefixedDBkey();
2148 $shortTitle = $this->mTitle->getDBkey();
2149
2150 if ( 0 == $id ) {
2151 wfProfileOut( $fname );
2152 return;
2153 }
2154
2155 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2156 array_push( $wgDeferredUpdateList, $u );
2157 $u = new SearchUpdate( $id, $title, $text );
2158 array_push( $wgDeferredUpdateList, $u );
2159
2160 # If this is another user's talk page, update newtalk
2161
2162 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2163 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2164 $other = User::newFromName( $shortTitle );
2165 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2166 // An anonymous user
2167 $other = new User();
2168 $other->setName( $shortTitle );
2169 }
2170 if( $other ) {
2171 $other->setNewtalk( true );
2172 }
2173 }
2174 }
2175
2176 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2177 $wgMessageCache->replace( $shortTitle, $text );
2178 }
2179
2180 wfProfileOut( $fname );
2181 }
2182
2183 /**
2184 * Generate the navigation links when browsing through an article revisions
2185 * It shows the information as:
2186 * Revision as of \<date\>; view current revision
2187 * \<- Previous version | Next Version -\>
2188 *
2189 * @private
2190 * @param string $oldid Revision ID of this article revision
2191 */
2192 function setOldSubtitle( $oldid=0 ) {
2193 global $wgLang, $wgOut, $wgUser;
2194
2195 $current = ( $oldid == $this->mLatest );
2196 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2197 $sk = $wgUser->getSkin();
2198 $lnk = $current
2199 ? wfMsg( 'currentrevisionlink' )
2200 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2201 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2202 $prevlink = $prev
2203 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2204 : wfMsg( 'previousrevision' );
2205 $nextlink = $current
2206 ? wfMsg( 'nextrevision' )
2207 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2208 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2209 $wgOut->setSubtitle( $r );
2210 }
2211
2212 /**
2213 * This function is called right before saving the wikitext,
2214 * so we can do things like signatures and links-in-context.
2215 *
2216 * @param string $text
2217 */
2218 function preSaveTransform( $text ) {
2219 global $wgParser, $wgUser;
2220 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2221 }
2222
2223 /* Caching functions */
2224
2225 /**
2226 * checkLastModified returns true if it has taken care of all
2227 * output to the client that is necessary for this request.
2228 * (that is, it has sent a cached version of the page)
2229 */
2230 function tryFileCache() {
2231 static $called = false;
2232 if( $called ) {
2233 wfDebug( " tryFileCache() -- called twice!?\n" );
2234 return;
2235 }
2236 $called = true;
2237 if($this->isFileCacheable()) {
2238 $touched = $this->mTouched;
2239 $cache = new CacheManager( $this->mTitle );
2240 if($cache->isFileCacheGood( $touched )) {
2241 wfDebug( " tryFileCache() - about to load\n" );
2242 $cache->loadFromFileCache();
2243 return true;
2244 } else {
2245 wfDebug( " tryFileCache() - starting buffer\n" );
2246 ob_start( array(&$cache, 'saveToFileCache' ) );
2247 }
2248 } else {
2249 wfDebug( " tryFileCache() - not cacheable\n" );
2250 }
2251 }
2252
2253 /**
2254 * Check if the page can be cached
2255 * @return bool
2256 */
2257 function isFileCacheable() {
2258 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2259 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2260
2261 return $wgUseFileCache
2262 and (!$wgShowIPinHeader)
2263 and ($this->getID() != 0)
2264 and ($wgUser->isAnon())
2265 and (!$wgUser->getNewtalk())
2266 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2267 and (empty( $action ) || $action == 'view')
2268 and (!isset($oldid))
2269 and (!isset($diff))
2270 and (!isset($redirect))
2271 and (!isset($printable))
2272 and (!$this->mRedirectedFrom);
2273 }
2274
2275 /**
2276 * Loads page_touched and returns a value indicating if it should be used
2277 *
2278 */
2279 function checkTouched() {
2280 $fname = 'Article::checkTouched';
2281 if( !$this->mDataLoaded ) {
2282 $this->loadPageData();
2283 }
2284 return !$this->mIsRedirect;
2285 }
2286
2287 /**
2288 * Get the page_touched field
2289 */
2290 function getTouched() {
2291 # Ensure that page data has been loaded
2292 if( !$this->mDataLoaded ) {
2293 $this->loadPageData();
2294 }
2295 return $this->mTouched;
2296 }
2297
2298 /**
2299 * Get the page_latest field
2300 */
2301 function getLatest() {
2302 if ( !$this->mDataLoaded ) {
2303 $this->loadPageData();
2304 }
2305 return $this->mLatest;
2306 }
2307
2308 /**
2309 * Edit an article without doing all that other stuff
2310 * The article must already exist; link tables etc
2311 * are not updated, caches are not flushed.
2312 *
2313 * @param string $text text submitted
2314 * @param string $comment comment submitted
2315 * @param bool $minor whereas it's a minor modification
2316 */
2317 function quickEdit( $text, $comment = '', $minor = 0 ) {
2318 $fname = 'Article::quickEdit';
2319 wfProfileIn( $fname );
2320
2321 $dbw =& wfGetDB( DB_MASTER );
2322 $dbw->begin();
2323 $revision = new Revision( array(
2324 'page' => $this->getId(),
2325 'text' => $text,
2326 'comment' => $comment,
2327 'minor_edit' => $minor ? 1 : 0,
2328 ) );
2329 # fixme : $revisionId never used
2330 $revisionId = $revision->insertOn( $dbw );
2331 $this->updateRevisionOn( $dbw, $revision );
2332 $dbw->commit();
2333
2334 wfProfileOut( $fname );
2335 }
2336
2337 /**
2338 * Used to increment the view counter
2339 *
2340 * @static
2341 * @param integer $id article id
2342 */
2343 function incViewCount( $id ) {
2344 $id = intval( $id );
2345 global $wgHitcounterUpdateFreq, $wgDBtype;
2346
2347 $dbw =& wfGetDB( DB_MASTER );
2348 $pageTable = $dbw->tableName( 'page' );
2349 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2350 $acchitsTable = $dbw->tableName( 'acchits' );
2351
2352 if( $wgHitcounterUpdateFreq <= 1 ){ //
2353 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2354 return;
2355 }
2356
2357 # Not important enough to warrant an error page in case of failure
2358 $oldignore = $dbw->ignoreErrors( true );
2359
2360 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2361
2362 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2363 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2364 # Most of the time (or on SQL errors), skip row count check
2365 $dbw->ignoreErrors( $oldignore );
2366 return;
2367 }
2368
2369 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2370 $row = $dbw->fetchObject( $res );
2371 $rown = intval( $row->n );
2372 if( $rown >= $wgHitcounterUpdateFreq ){
2373 wfProfileIn( 'Article::incViewCount-collect' );
2374 $old_user_abort = ignore_user_abort( true );
2375
2376 if ($wgDBtype == 'mysql')
2377 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2378 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2379 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2380 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2381 'GROUP BY hc_id');
2382 $dbw->query("DELETE FROM $hitcounterTable");
2383 if ($wgDBtype == 'mysql')
2384 $dbw->query('UNLOCK TABLES');
2385 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2386 'WHERE page_id = hc_id');
2387 $dbw->query("DROP TABLE $acchitsTable");
2388
2389 ignore_user_abort( $old_user_abort );
2390 wfProfileOut( 'Article::incViewCount-collect' );
2391 }
2392 $dbw->ignoreErrors( $oldignore );
2393 }
2394
2395 /**#@+
2396 * The onArticle*() functions are supposed to be a kind of hooks
2397 * which should be called whenever any of the specified actions
2398 * are done.
2399 *
2400 * This is a good place to put code to clear caches, for instance.
2401 *
2402 * This is called on page move and undelete, as well as edit
2403 * @static
2404 * @param $title_obj a title object
2405 */
2406
2407 static function onArticleCreate($title) {
2408 $title->touchLinks();
2409 $title->purgeSquid();
2410 }
2411
2412 static function onArticleDelete( $title ) {
2413 global $wgUseFileCache, $wgMessageCache;
2414
2415 $title->touchLinks();
2416 $title->purgeSquid();
2417
2418 # File cache
2419 if ( $wgUseFileCache ) {
2420 $cm = new CacheManager( $title );
2421 @unlink( $cm->fileCacheName() );
2422 }
2423
2424 if( $title->getNamespace() == NS_MEDIAWIKI) {
2425 $wgMessageCache->replace( $title->getDBkey(), false );
2426 }
2427 }
2428
2429 /**
2430 * Purge caches on page update etc
2431 */
2432 static function onArticleEdit( $title ) {
2433 global $wgDeferredUpdateList, $wgUseFileCache;
2434
2435 $urls = array();
2436
2437 // Invalidate caches of articles which include this page
2438 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2439 $wgDeferredUpdateList[] = $update;
2440
2441 # Purge squid for this page only
2442 $title->purgeSquid();
2443
2444 # Clear file cache
2445 if ( $wgUseFileCache ) {
2446 $cm = new CacheManager( $title );
2447 @unlink( $cm->fileCacheName() );
2448 }
2449 }
2450
2451 /**#@-*/
2452
2453 /**
2454 * Info about this page
2455 * Called for ?action=info when $wgAllowPageInfo is on.
2456 *
2457 * @public
2458 */
2459 function info() {
2460 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2461 $fname = 'Article::info';
2462
2463 if ( !$wgAllowPageInfo ) {
2464 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2465 return;
2466 }
2467
2468 $page = $this->mTitle->getSubjectPage();
2469
2470 $wgOut->setPagetitle( $page->getPrefixedText() );
2471 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2472
2473 # first, see if the page exists at all.
2474 $exists = $page->getArticleId() != 0;
2475 if( !$exists ) {
2476 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2477 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2478 } else {
2479 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2480 }
2481 } else {
2482 $dbr =& wfGetDB( DB_SLAVE );
2483 $wl_clause = array(
2484 'wl_title' => $page->getDBkey(),
2485 'wl_namespace' => $page->getNamespace() );
2486 $numwatchers = $dbr->selectField(
2487 'watchlist',
2488 'COUNT(*)',
2489 $wl_clause,
2490 $fname,
2491 $this->getSelectOptions() );
2492
2493 $pageInfo = $this->pageCountInfo( $page );
2494 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2495
2496 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2497 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2498 if( $talkInfo ) {
2499 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2500 }
2501 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2502 if( $talkInfo ) {
2503 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2504 }
2505 $wgOut->addHTML( '</ul>' );
2506
2507 }
2508 }
2509
2510 /**
2511 * Return the total number of edits and number of unique editors
2512 * on a given page. If page does not exist, returns false.
2513 *
2514 * @param Title $title
2515 * @return array
2516 * @private
2517 */
2518 function pageCountInfo( $title ) {
2519 $id = $title->getArticleId();
2520 if( $id == 0 ) {
2521 return false;
2522 }
2523
2524 $dbr =& wfGetDB( DB_SLAVE );
2525
2526 $rev_clause = array( 'rev_page' => $id );
2527 $fname = 'Article::pageCountInfo';
2528
2529 $edits = $dbr->selectField(
2530 'revision',
2531 'COUNT(rev_page)',
2532 $rev_clause,
2533 $fname,
2534 $this->getSelectOptions() );
2535
2536 $authors = $dbr->selectField(
2537 'revision',
2538 'COUNT(DISTINCT rev_user_text)',
2539 $rev_clause,
2540 $fname,
2541 $this->getSelectOptions() );
2542
2543 return array( 'edits' => $edits, 'authors' => $authors );
2544 }
2545
2546 /**
2547 * Return a list of templates used by this article.
2548 * Uses the templatelinks table
2549 *
2550 * @return array Array of Title objects
2551 */
2552 function getUsedTemplates() {
2553 $result = array();
2554 $id = $this->mTitle->getArticleID();
2555 if( $id == 0 ) {
2556 return array();
2557 }
2558
2559 $dbr =& wfGetDB( DB_SLAVE );
2560 $res = $dbr->select( array( 'templatelinks' ),
2561 array( 'tl_namespace', 'tl_title' ),
2562 array( 'tl_from' => $id ),
2563 'Article:getUsedTemplates' );
2564 if ( false !== $res ) {
2565 if ( $dbr->numRows( $res ) ) {
2566 while ( $row = $dbr->fetchObject( $res ) ) {
2567 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2568 }
2569 }
2570 }
2571 $dbr->freeResult( $res );
2572 return $result;
2573 }
2574 }
2575
2576 ?>