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