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