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