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