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