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