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