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