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