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