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