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