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