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