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