* Bug 4456: Add hook for marking article patrolled
[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 $wgOut->setRevisionId( $this->getRevIdFetched() );
837 # wrap user css and user js in pre and don't parse
838 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
839 if (
840 $this->mTitle->getNamespace() == NS_USER &&
841 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
842 ) {
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->addPrimaryWikiText( $text, $this );
864 } else {
865 # Display content, don't attempt to save to parser cache
866
867 # Don't show section-edit links on old revisions... this way lies madness.
868 if( !$this->isCurrent() ) {
869 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
870 }
871 $wgOut->addWikiText( $text );
872
873 if( !$this->isCurrent() ) {
874 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
875 }
876 }
877 }
878 /* title may have been set from the cache */
879 $t = $wgOut->getPageTitle();
880 if( empty( $t ) ) {
881 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
882 }
883
884 # If we have been passed an &rcid= parameter, we want to give the user a
885 # chance to mark this new article as patrolled.
886 if ( $wgUseRCPatrol
887 && !is_null($rcid)
888 && $rcid != 0
889 && $wgUser->isLoggedIn()
890 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
891 {
892 $wgOut->addHTML(
893 "<div class='patrollink'>" .
894 wfMsg ( 'markaspatrolledlink',
895 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
896 ) .
897 '</div>'
898 );
899 }
900
901 # Trackbacks
902 if ($wgUseTrackbacks)
903 $this->addTrackbacks();
904
905 $this->viewUpdates();
906 wfProfileOut( $fname );
907 }
908
909 function addTrackbacks() {
910 global $wgOut, $wgUser;
911
912 $dbr =& wfGetDB(DB_SLAVE);
913 $tbs = $dbr->select(
914 /* FROM */ 'trackbacks',
915 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
916 /* WHERE */ array('tb_page' => $this->getID())
917 );
918
919 if (!$dbr->numrows($tbs))
920 return;
921
922 $tbtext = "";
923 while ($o = $dbr->fetchObject($tbs)) {
924 $rmvtxt = "";
925 if ($wgUser->isSysop()) {
926 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
927 . $o->tb_id . "&token=" . $wgUser->editToken());
928 $rmvtxt = wfMsg('trackbackremove', $delurl);
929 }
930 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
931 $o->tb_title,
932 $o->tb_url,
933 $o->tb_ex,
934 $o->tb_name,
935 $rmvtxt);
936 }
937 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
938 }
939
940 function deletetrackback() {
941 global $wgUser, $wgRequest, $wgOut, $wgTitle;
942
943 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
944 $wgOut->addWikitext(wfMsg('sessionfailure'));
945 return;
946 }
947
948 if ((!$wgUser->isAllowed('delete'))) {
949 $wgOut->sysopRequired();
950 return;
951 }
952
953 if (wfReadOnly()) {
954 $wgOut->readOnlyPage();
955 return;
956 }
957
958 $db =& wfGetDB(DB_MASTER);
959 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
960 $wgTitle->invalidateCache();
961 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
962 }
963
964 function render() {
965 global $wgOut;
966
967 $wgOut->setArticleBodyOnly(true);
968 $this->view();
969 }
970
971 function purge() {
972 global $wgUser, $wgRequest, $wgOut, $wgUseSquid;
973
974 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() || ! wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
975 // Invalidate the cache
976 $this->mTitle->invalidateCache();
977
978 if ( $wgUseSquid ) {
979 // Commit the transaction before the purge is sent
980 $dbw = wfGetDB( DB_MASTER );
981 $dbw->immediateCommit();
982
983 // Send purge
984 $update = SquidUpdate::newSimplePurge( $this->mTitle );
985 $update->doUpdate();
986 }
987 $this->view();
988 } else {
989 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
990 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
991 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
992 $msg = str_replace( '$1',
993 "<form method=\"post\" action=\"$action\">\n" .
994 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
995 "</form>\n", $msg );
996
997 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
998 $wgOut->setRobotpolicy( 'noindex,nofollow' );
999 $wgOut->addHTML( $msg );
1000 }
1001 }
1002
1003 /**
1004 * Insert a new empty page record for this article.
1005 * This *must* be followed up by creating a revision
1006 * and running $this->updateToLatest( $rev_id );
1007 * or else the record will be left in a funky state.
1008 * Best if all done inside a transaction.
1009 *
1010 * @param Database $dbw
1011 * @param string $restrictions
1012 * @return int The newly created page_id key
1013 * @access private
1014 */
1015 function insertOn( &$dbw, $restrictions = '' ) {
1016 $fname = 'Article::insertOn';
1017 wfProfileIn( $fname );
1018
1019 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1020 $dbw->insert( 'page', array(
1021 'page_id' => $page_id,
1022 'page_namespace' => $this->mTitle->getNamespace(),
1023 'page_title' => $this->mTitle->getDBkey(),
1024 'page_counter' => 0,
1025 'page_restrictions' => $restrictions,
1026 'page_is_redirect' => 0, # Will set this shortly...
1027 'page_is_new' => 1,
1028 'page_random' => wfRandom(),
1029 'page_touched' => $dbw->timestamp(),
1030 'page_latest' => 0, # Fill this in shortly...
1031 'page_len' => 0, # Fill this in shortly...
1032 ), $fname );
1033 $newid = $dbw->insertId();
1034
1035 $this->mTitle->resetArticleId( $newid );
1036
1037 wfProfileOut( $fname );
1038 return $newid;
1039 }
1040
1041 /**
1042 * Update the page record to point to a newly saved revision.
1043 *
1044 * @param Database $dbw
1045 * @param Revision $revision -- for ID number, and text used to set
1046 length and redirect status fields
1047 * @param int $lastRevision -- if given, will not overwrite the page field
1048 * when different from the currently set value.
1049 * Giving 0 indicates the new page flag should
1050 * be set on.
1051 * @return bool true on success, false on failure
1052 * @access private
1053 */
1054 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1055 $fname = 'Article::updateToRevision';
1056 wfProfileIn( $fname );
1057
1058 $conditions = array( 'page_id' => $this->getId() );
1059 if( !is_null( $lastRevision ) ) {
1060 # An extra check against threads stepping on each other
1061 $conditions['page_latest'] = $lastRevision;
1062 }
1063
1064 $text = $revision->getText();
1065 $dbw->update( 'page',
1066 array( /* SET */
1067 'page_latest' => $revision->getId(),
1068 'page_touched' => $dbw->timestamp(),
1069 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1070 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1071 'page_len' => strlen( $text ),
1072 ),
1073 $conditions,
1074 $fname );
1075
1076 wfProfileOut( $fname );
1077 return ( $dbw->affectedRows() != 0 );
1078 }
1079
1080 /**
1081 * If the given revision is newer than the currently set page_latest,
1082 * update the page record. Otherwise, do nothing.
1083 *
1084 * @param Database $dbw
1085 * @param Revision $revision
1086 */
1087 function updateIfNewerOn( &$dbw, $revision ) {
1088 $fname = 'Article::updateIfNewerOn';
1089 wfProfileIn( $fname );
1090
1091 $row = $dbw->selectRow(
1092 array( 'revision', 'page' ),
1093 array( 'rev_id', 'rev_timestamp' ),
1094 array(
1095 'page_id' => $this->getId(),
1096 'page_latest=rev_id' ),
1097 $fname );
1098 if( $row ) {
1099 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1100 wfProfileOut( $fname );
1101 return false;
1102 }
1103 $prev = $row->rev_id;
1104 } else {
1105 # No or missing previous revision; mark the page as new
1106 $prev = 0;
1107 }
1108
1109 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1110 wfProfileOut( $fname );
1111 return $ret;
1112 }
1113
1114 /**
1115 * Theoretically we could defer these whole insert and update
1116 * functions for after display, but that's taking a big leap
1117 * of faith, and we want to be able to report database
1118 * errors at some point.
1119 * @private
1120 */
1121 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1122 global $wgOut, $wgUser, $wgUseSquid;
1123
1124 $fname = 'Article::insertNewArticle';
1125 wfProfileIn( $fname );
1126
1127 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1128 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1129 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1130 wfProfileOut( $fname );
1131 return false;
1132 }
1133
1134 $this->mGoodAdjustment = $this->isCountable( $text );
1135 $this->mTotalAdjustment = 1;
1136
1137 $ns = $this->mTitle->getNamespace();
1138 $ttl = $this->mTitle->getDBkey();
1139
1140 # If this is a comment, add the summary as headline
1141 if($comment && $summary!="") {
1142 $text="== {$summary} ==\n\n".$text;
1143 }
1144 $text = $this->preSaveTransform( $text );
1145
1146 /* Silently ignore minoredit if not allowed */
1147 $isminor = $isminor && $wgUser->isAllowed('minoredit');
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->isAllowed('minoredit');
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 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, $wgOnlySysopsCanPatrol ) ) ) {
1503 RecentChange::markPatrolled( $rcid );
1504 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, $wgOnlySysopsCanPatrol ) );
1505 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1506 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1507 }
1508 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1509 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1510 }
1511 else
1512 {
1513 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1514 }
1515 }
1516
1517 /**
1518 * Add this page to $wgUser's watchlist
1519 */
1520
1521 function watch() {
1522
1523 global $wgUser, $wgOut;
1524
1525 if ( $wgUser->isAnon() ) {
1526 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1527 return;
1528 }
1529 if ( wfReadOnly() ) {
1530 $wgOut->readOnlyPage();
1531 return;
1532 }
1533
1534 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1535
1536 $wgUser->addWatch( $this->mTitle );
1537 $wgUser->saveSettings();
1538
1539 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1540
1541 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1542 $wgOut->setRobotpolicy( 'noindex,follow' );
1543
1544 $link = $this->mTitle->getPrefixedText();
1545 $text = wfMsg( 'addedwatchtext', $link );
1546 $wgOut->addWikiText( $text );
1547 }
1548
1549 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1550 }
1551
1552 /**
1553 * Stop watching a page
1554 */
1555
1556 function unwatch() {
1557
1558 global $wgUser, $wgOut;
1559
1560 if ( $wgUser->isAnon() ) {
1561 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1562 return;
1563 }
1564 if ( wfReadOnly() ) {
1565 $wgOut->readOnlyPage();
1566 return;
1567 }
1568
1569 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1570
1571 $wgUser->removeWatch( $this->mTitle );
1572 $wgUser->saveSettings();
1573
1574 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1575
1576 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1577 $wgOut->setRobotpolicy( 'noindex,follow' );
1578
1579 $link = $this->mTitle->getPrefixedText();
1580 $text = wfMsg( 'removedwatchtext', $link );
1581 $wgOut->addWikiText( $text );
1582 }
1583
1584 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1585 }
1586
1587 /**
1588 * action=protect handler
1589 */
1590 function protect() {
1591 require_once 'ProtectionForm.php';
1592 $form = new ProtectionForm( $this );
1593 $form->show();
1594 }
1595
1596 /**
1597 * action=unprotect handler (alias)
1598 */
1599 function unprotect() {
1600 $this->protect();
1601 }
1602
1603 /**
1604 * Update the article's restriction field, and leave a log entry.
1605 *
1606 * @param array $limit set of restriction keys
1607 * @param string $reason
1608 * @return bool true on success
1609 */
1610 function updateRestrictions( $limit = array(), $reason = '' ) {
1611 global $wgUser, $wgOut, $wgRequest;
1612
1613 if ( !$wgUser->isAllowed( 'protect' ) ) {
1614 return false;
1615 }
1616
1617 if( wfReadOnly() ) {
1618 return false;
1619 }
1620
1621 $id = $this->mTitle->getArticleID();
1622 if ( 0 == $id ) {
1623 return false;
1624 }
1625
1626 $flat = Article::flattenRestrictions( $limit );
1627 $protecting = ($flat != '');
1628
1629 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser,
1630 $limit, $reason ) ) ) {
1631
1632 $dbw =& wfGetDB( DB_MASTER );
1633 $dbw->update( 'page',
1634 array( /* SET */
1635 'page_touched' => $dbw->timestamp(),
1636 'page_restrictions' => $flat
1637 ), array( /* WHERE */
1638 'page_id' => $id
1639 ), 'Article::protect'
1640 );
1641
1642 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser,
1643 $limit, $reason ) );
1644
1645 $log = new LogPage( 'protect' );
1646 if( $protecting ) {
1647 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$flat]" ) );
1648 } else {
1649 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1650 }
1651 }
1652 return true;
1653 }
1654
1655 /**
1656 * Take an array of page restrictions and flatten it to a string
1657 * suitable for insertion into the page_restrictions field.
1658 * @param array $limit
1659 * @return string
1660 * @access private
1661 */
1662 function flattenRestrictions( $limit ) {
1663 if( !is_array( $limit ) ) {
1664 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1665 }
1666 $bits = array();
1667 foreach( $limit as $action => $restrictions ) {
1668 if( $restrictions != '' ) {
1669 $bits[] = "$action=$restrictions";
1670 }
1671 }
1672 return implode( ':', $bits );
1673 }
1674
1675 /*
1676 * UI entry point for page deletion
1677 */
1678 function delete() {
1679 global $wgUser, $wgOut, $wgRequest;
1680 $fname = 'Article::delete';
1681 $confirm = $wgRequest->wasPosted() &&
1682 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1683 $reason = $wgRequest->getText( 'wpReason' );
1684
1685 # This code desperately needs to be totally rewritten
1686
1687 # Check permissions
1688 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1689 $wgOut->sysopRequired();
1690 return;
1691 }
1692 if( wfReadOnly() ) {
1693 $wgOut->readOnlyPage();
1694 return;
1695 }
1696
1697 # Better double-check that it hasn't been deleted yet!
1698 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1699 if( !$this->mTitle->exists() ) {
1700 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1701 return;
1702 }
1703
1704 if( $confirm ) {
1705 $this->doDelete( $reason );
1706 return;
1707 }
1708
1709 # determine whether this page has earlier revisions
1710 # and insert a warning if it does
1711 # we select the text because it might be useful below
1712 $dbr =& $this->getDB();
1713 $ns = $this->mTitle->getNamespace();
1714 $title = $this->mTitle->getDBkey();
1715 $revisions = $dbr->select( array( 'page', 'revision' ),
1716 array( 'rev_id', 'rev_user_text' ),
1717 array(
1718 'page_namespace' => $ns,
1719 'page_title' => $title,
1720 'rev_page = page_id'
1721 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1722 );
1723
1724 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1725 $skin=$wgUser->getSkin();
1726 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1727 $wgOut->addHTML( $skin->historyLink() .'</b>');
1728 }
1729
1730 # Fetch article text
1731 $rev = Revision::newFromTitle( $this->mTitle );
1732
1733 # Fetch name(s) of contributors
1734 $rev_name = '';
1735 $all_same_user = true;
1736 while( $row = $dbr->fetchObject( $revisions ) ) {
1737 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1738 $all_same_user = false;
1739 } else {
1740 $rev_name = $row->rev_user_text;
1741 }
1742 }
1743
1744 if( !is_null( $rev ) ) {
1745 # if this is a mini-text, we can paste part of it into the deletion reason
1746 $text = $rev->getText();
1747
1748 #if this is empty, an earlier revision may contain "useful" text
1749 $blanked = false;
1750 if( $text == '' ) {
1751 $prev = $rev->getPrevious();
1752 if( $prev ) {
1753 $text = $prev->getText();
1754 $blanked = true;
1755 }
1756 }
1757
1758 $length = strlen( $text );
1759
1760 # this should not happen, since it is not possible to store an empty, new
1761 # page. Let's insert a standard text in case it does, though
1762 if( $length == 0 && $reason === '' ) {
1763 $reason = wfMsgForContent( 'exblank' );
1764 }
1765
1766 if( $length < 500 && $reason === '' ) {
1767 # comment field=255, let's grep the first 150 to have some user
1768 # space left
1769 global $wgContLang;
1770 $text = $wgContLang->truncate( $text, 150, '...' );
1771
1772 # let's strip out newlines
1773 $text = preg_replace( "/[\n\r]/", '', $text );
1774
1775 if( !$blanked ) {
1776 if( !$all_same_user ) {
1777 $reason = wfMsgForContent( 'excontent', $text );
1778 } else {
1779 $reason = wfMsgForContent( 'excontentauthor', $text, $rev_name );
1780 }
1781 } else {
1782 $reason = wfMsgForContent( 'exbeforeblank', $text );
1783 }
1784 }
1785 }
1786
1787 return $this->confirmDelete( '', $reason );
1788 }
1789
1790 /**
1791 * Output deletion confirmation dialog
1792 */
1793 function confirmDelete( $par, $reason ) {
1794 global $wgOut, $wgUser;
1795
1796 wfDebug( "Article::confirmDelete\n" );
1797
1798 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1799 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1800 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1801 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1802
1803 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1804
1805 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1806 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1807 $token = htmlspecialchars( $wgUser->editToken() );
1808
1809 $wgOut->addHTML( "
1810 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1811 <table border='0'>
1812 <tr>
1813 <td align='right'>
1814 <label for='wpReason'>{$delcom}:</label>
1815 </td>
1816 <td align='left'>
1817 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1818 </td>
1819 </tr>
1820 <tr>
1821 <td>&nbsp;</td>
1822 <td>
1823 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1824 </td>
1825 </tr>
1826 </table>
1827 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1828 </form>\n" );
1829
1830 $wgOut->returnToMain( false );
1831 }
1832
1833
1834 /**
1835 * Perform a deletion and output success or failure messages
1836 */
1837 function doDelete( $reason ) {
1838 global $wgOut, $wgUser, $wgContLang;
1839 $fname = 'Article::doDelete';
1840 wfDebug( $fname."\n" );
1841
1842 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1843 if ( $this->doDeleteArticle( $reason ) ) {
1844 $deleted = $this->mTitle->getPrefixedText();
1845
1846 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1847 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1848
1849 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1850 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1851
1852 $wgOut->addWikiText( $text );
1853 $wgOut->returnToMain( false );
1854 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1855 } else {
1856 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1857 }
1858 }
1859 }
1860
1861 /**
1862 * Back-end article deletion
1863 * Deletes the article with database consistency, writes logs, purges caches
1864 * Returns success
1865 */
1866 function doDeleteArticle( $reason ) {
1867 global $wgUser, $wgUseSquid, $wgDeferredUpdateList;
1868 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1869
1870 $fname = 'Article::doDeleteArticle';
1871 wfDebug( $fname."\n" );
1872
1873 $dbw =& wfGetDB( DB_MASTER );
1874 $ns = $this->mTitle->getNamespace();
1875 $t = $this->mTitle->getDBkey();
1876 $id = $this->mTitle->getArticleID();
1877
1878 if ( $t == '' || $id == 0 ) {
1879 return false;
1880 }
1881
1882 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1883 array_push( $wgDeferredUpdateList, $u );
1884
1885 $linksTo = $this->mTitle->getLinksTo();
1886
1887 # Squid purging
1888 if ( $wgUseSquid ) {
1889 $urls = array(
1890 $this->mTitle->getInternalURL(),
1891 $this->mTitle->getInternalURL( 'history' )
1892 );
1893
1894 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1895 array_push( $wgPostCommitUpdateList, $u );
1896
1897 }
1898
1899 # Client and file cache invalidation
1900 Title::touchArray( $linksTo );
1901
1902
1903 // For now, shunt the revision data into the archive table.
1904 // Text is *not* removed from the text table; bulk storage
1905 // is left intact to avoid breaking block-compression or
1906 // immutable storage schemes.
1907 //
1908 // For backwards compatibility, note that some older archive
1909 // table entries will have ar_text and ar_flags fields still.
1910 //
1911 // In the future, we may keep revisions and mark them with
1912 // the rev_deleted field, which is reserved for this purpose.
1913 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1914 array(
1915 'ar_namespace' => 'page_namespace',
1916 'ar_title' => 'page_title',
1917 'ar_comment' => 'rev_comment',
1918 'ar_user' => 'rev_user',
1919 'ar_user_text' => 'rev_user_text',
1920 'ar_timestamp' => 'rev_timestamp',
1921 'ar_minor_edit' => 'rev_minor_edit',
1922 'ar_rev_id' => 'rev_id',
1923 'ar_text_id' => 'rev_text_id',
1924 ), array(
1925 'page_id' => $id,
1926 'page_id = rev_page'
1927 ), $fname
1928 );
1929
1930 # Now that it's safely backed up, delete it
1931 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1932 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1933
1934 if ($wgUseTrackbacks)
1935 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
1936
1937 # Clean up recentchanges entries...
1938 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1939
1940 # Finally, clean up the link tables
1941 $t = $this->mTitle->getPrefixedDBkey();
1942
1943 Article::onArticleDelete( $this->mTitle );
1944
1945 # Delete outgoing links
1946 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1947 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1948 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1949
1950 # Log the deletion
1951 $log = new LogPage( 'delete' );
1952 $log->addEntry( 'delete', $this->mTitle, $reason );
1953
1954 # Clear the cached article id so the interface doesn't act like we exist
1955 $this->mTitle->resetArticleID( 0 );
1956 $this->mTitle->mArticleID = 0;
1957 return true;
1958 }
1959
1960 /**
1961 * Revert a modification
1962 */
1963 function rollback() {
1964 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
1965 $fname = 'Article::rollback';
1966
1967 if ( ! $wgUser->isAllowed('rollback') ) {
1968 $wgOut->sysopRequired();
1969 return;
1970 }
1971 if ( wfReadOnly() ) {
1972 $wgOut->readOnlyPage( $this->getContent( true ) );
1973 return;
1974 }
1975 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1976 array( $this->mTitle->getPrefixedText(),
1977 $wgRequest->getVal( 'from' ) ) ) ) {
1978 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1979 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1980 return;
1981 }
1982 $dbw =& wfGetDB( DB_MASTER );
1983
1984 # Enhanced rollback, marks edits rc_bot=1
1985 $bot = $wgRequest->getBool( 'bot' );
1986
1987 # Replace all this user's current edits with the next one down
1988 $tt = $this->mTitle->getDBKey();
1989 $n = $this->mTitle->getNamespace();
1990
1991 # Get the last editor, lock table exclusively
1992 $dbw->begin();
1993 $current = Revision::newFromTitle( $this->mTitle );
1994 if( is_null( $current ) ) {
1995 # Something wrong... no page?
1996 $dbw->rollback();
1997 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1998 return;
1999 }
2000
2001 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2002 if( $from != $current->getUserText() ) {
2003 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2004 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2005 htmlspecialchars( $this->mTitle->getPrefixedText()),
2006 htmlspecialchars( $from ),
2007 htmlspecialchars( $current->getUserText() ) ) );
2008 if( $current->getComment() != '') {
2009 $wgOut->addHTML(
2010 wfMsg( 'editcomment',
2011 htmlspecialchars( $current->getComment() ) ) );
2012 }
2013 return;
2014 }
2015
2016 # Get the last edit not by this guy
2017 $user = intval( $current->getUser() );
2018 $user_text = $dbw->addQuotes( $current->getUserText() );
2019 $s = $dbw->selectRow( 'revision',
2020 array( 'rev_id', 'rev_timestamp' ),
2021 array(
2022 'rev_page' => $current->getPage(),
2023 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2024 ), $fname,
2025 array(
2026 'USE INDEX' => 'page_timestamp',
2027 'ORDER BY' => 'rev_timestamp DESC' )
2028 );
2029 if( $s === false ) {
2030 # Something wrong
2031 $dbw->rollback();
2032 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2033 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2034 return;
2035 }
2036
2037 $set = array();
2038 if ( $bot ) {
2039 # Mark all reverted edits as bot
2040 $set['rc_bot'] = 1;
2041 }
2042 if ( $wgUseRCPatrol ) {
2043 # Mark all reverted edits as patrolled
2044 $set['rc_patrolled'] = 1;
2045 }
2046
2047 if ( $set ) {
2048 $dbw->update( 'recentchanges', $set,
2049 array( /* WHERE */
2050 'rc_cur_id' => $current->getPage(),
2051 'rc_user_text' => $current->getUserText(),
2052 "rc_timestamp > '{$s->rev_timestamp}'",
2053 ), $fname
2054 );
2055 }
2056
2057 # Get the edit summary
2058 $target = Revision::newFromId( $s->rev_id );
2059 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2060 $newComment = $wgRequest->getText( 'summary', $newComment );
2061
2062 # Save it!
2063 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2064 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2065 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2066
2067 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2068 Article::onArticleEdit( $this->mTitle );
2069
2070 $dbw->commit();
2071 $wgOut->returnToMain( false );
2072 }
2073
2074
2075 /**
2076 * Do standard deferred updates after page view
2077 * @private
2078 */
2079 function viewUpdates() {
2080 global $wgDeferredUpdateList;
2081
2082 if ( 0 != $this->getID() ) {
2083 global $wgDisableCounters;
2084 if( !$wgDisableCounters ) {
2085 Article::incViewCount( $this->getID() );
2086 $u = new SiteStatsUpdate( 1, 0, 0 );
2087 array_push( $wgDeferredUpdateList, $u );
2088 }
2089 }
2090
2091 # Update newtalk / watchlist notification status
2092 global $wgUser;
2093 $wgUser->clearNotification( $this->mTitle );
2094 }
2095
2096 /**
2097 * Do standard deferred updates after page edit.
2098 * Every 1000th edit, prune the recent changes table.
2099 * @private
2100 * @param string $text
2101 */
2102 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2103 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgParserCache;
2104
2105 $fname = 'Article::editUpdates';
2106 wfProfileIn( $fname );
2107
2108 # Parse the text
2109 $options = new ParserOptions;
2110 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2111
2112 # Save it to the parser cache
2113 $wgParserCache->save( $poutput, $this, $wgUser );
2114
2115 # Update the links tables
2116 $u = new LinksUpdate( $this->mTitle, $poutput );
2117 $u->doUpdate();
2118
2119 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2120 wfSeedRandom();
2121 if ( 0 == mt_rand( 0, 999 ) ) {
2122 # Periodically flush old entries from the recentchanges table.
2123 global $wgRCMaxAge;
2124
2125 $dbw =& wfGetDB( DB_MASTER );
2126 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2127 $recentchanges = $dbw->tableName( 'recentchanges' );
2128 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2129 $dbw->query( $sql );
2130 }
2131 }
2132
2133 $id = $this->getID();
2134 $title = $this->mTitle->getPrefixedDBkey();
2135 $shortTitle = $this->mTitle->getDBkey();
2136
2137 if ( 0 == $id ) {
2138 wfProfileOut( $fname );
2139 return;
2140 }
2141
2142 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2143 array_push( $wgDeferredUpdateList, $u );
2144 $u = new SearchUpdate( $id, $title, $text );
2145 array_push( $wgDeferredUpdateList, $u );
2146
2147 # If this is another user's talk page, update newtalk
2148
2149 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2150 $other = User::newFromName( $shortTitle );
2151 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2152 // An anonymous user
2153 $other = new User();
2154 $other->setName( $shortTitle );
2155 }
2156 if( $other ) {
2157 $other->setNewtalk( true );
2158 }
2159 }
2160
2161 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2162 $wgMessageCache->replace( $shortTitle, $text );
2163 }
2164
2165 wfProfileOut( $fname );
2166 }
2167
2168 /**
2169 * @todo document this function
2170 * @private
2171 * @param string $oldid Revision ID of this article revision
2172 */
2173 function setOldSubtitle( $oldid=0 ) {
2174 global $wgLang, $wgOut, $wgUser;
2175
2176 $current = ( $oldid == $this->mLatest );
2177 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2178 $sk = $wgUser->getSkin();
2179 $lnk = $current
2180 ? wfMsg( 'currentrevisionlink' )
2181 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2182 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2183 $nextlink = $current
2184 ? wfMsg( 'nextrevision' )
2185 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2186 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2187 $wgOut->setSubtitle( $r );
2188 }
2189
2190 /**
2191 * This function is called right before saving the wikitext,
2192 * so we can do things like signatures and links-in-context.
2193 *
2194 * @param string $text
2195 */
2196 function preSaveTransform( $text ) {
2197 global $wgParser, $wgUser;
2198 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2199 }
2200
2201 /* Caching functions */
2202
2203 /**
2204 * checkLastModified returns true if it has taken care of all
2205 * output to the client that is necessary for this request.
2206 * (that is, it has sent a cached version of the page)
2207 */
2208 function tryFileCache() {
2209 static $called = false;
2210 if( $called ) {
2211 wfDebug( " tryFileCache() -- called twice!?\n" );
2212 return;
2213 }
2214 $called = true;
2215 if($this->isFileCacheable()) {
2216 $touched = $this->mTouched;
2217 $cache = new CacheManager( $this->mTitle );
2218 if($cache->isFileCacheGood( $touched )) {
2219 global $wgOut;
2220 wfDebug( " tryFileCache() - about to load\n" );
2221 $cache->loadFromFileCache();
2222 return true;
2223 } else {
2224 wfDebug( " tryFileCache() - starting buffer\n" );
2225 ob_start( array(&$cache, 'saveToFileCache' ) );
2226 }
2227 } else {
2228 wfDebug( " tryFileCache() - not cacheable\n" );
2229 }
2230 }
2231
2232 /**
2233 * Check if the page can be cached
2234 * @return bool
2235 */
2236 function isFileCacheable() {
2237 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2238 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2239
2240 return $wgUseFileCache
2241 and (!$wgShowIPinHeader)
2242 and ($this->getID() != 0)
2243 and ($wgUser->isAnon())
2244 and (!$wgUser->getNewtalk())
2245 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2246 and (empty( $action ) || $action == 'view')
2247 and (!isset($oldid))
2248 and (!isset($diff))
2249 and (!isset($redirect))
2250 and (!isset($printable))
2251 and (!$this->mRedirectedFrom);
2252 }
2253
2254 /**
2255 * Loads page_touched and returns a value indicating if it should be used
2256 *
2257 */
2258 function checkTouched() {
2259 $fname = 'Article::checkTouched';
2260 if( !$this->mDataLoaded ) {
2261 $dbr =& $this->getDB();
2262 $data = $this->pageDataFromId( $dbr, $this->getId() );
2263 if( $data ) {
2264 $this->loadPageData( $data );
2265 }
2266 }
2267 return !$this->mIsRedirect;
2268 }
2269
2270 /**
2271 * Get the page_touched field
2272 */
2273 function getTouched() {
2274 # Ensure that page data has been loaded
2275 if( !$this->mDataLoaded ) {
2276 $dbr =& $this->getDB();
2277 $data = $this->pageDataFromId( $dbr, $this->getId() );
2278 if( $data ) {
2279 $this->loadPageData( $data );
2280 }
2281 }
2282 return $this->mTouched;
2283 }
2284
2285 /**
2286 * Edit an article without doing all that other stuff
2287 * The article must already exist; link tables etc
2288 * are not updated, caches are not flushed.
2289 *
2290 * @param string $text text submitted
2291 * @param string $comment comment submitted
2292 * @param bool $minor whereas it's a minor modification
2293 */
2294 function quickEdit( $text, $comment = '', $minor = 0 ) {
2295 $fname = 'Article::quickEdit';
2296 wfProfileIn( $fname );
2297
2298 $dbw =& wfGetDB( DB_MASTER );
2299 $dbw->begin();
2300 $revision = new Revision( array(
2301 'page' => $this->getId(),
2302 'text' => $text,
2303 'comment' => $comment,
2304 'minor_edit' => $minor ? 1 : 0,
2305 ) );
2306 $revisionId = $revision->insertOn( $dbw );
2307 $this->updateRevisionOn( $dbw, $revision );
2308 $dbw->commit();
2309
2310 wfProfileOut( $fname );
2311 }
2312
2313 /**
2314 * Used to increment the view counter
2315 *
2316 * @static
2317 * @param integer $id article id
2318 */
2319 function incViewCount( $id ) {
2320 $id = intval( $id );
2321 global $wgHitcounterUpdateFreq;
2322
2323 $dbw =& wfGetDB( DB_MASTER );
2324 $pageTable = $dbw->tableName( 'page' );
2325 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2326 $acchitsTable = $dbw->tableName( 'acchits' );
2327
2328 if( $wgHitcounterUpdateFreq <= 1 ){ //
2329 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2330 return;
2331 }
2332
2333 # Not important enough to warrant an error page in case of failure
2334 $oldignore = $dbw->ignoreErrors( true );
2335
2336 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2337
2338 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2339 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2340 # Most of the time (or on SQL errors), skip row count check
2341 $dbw->ignoreErrors( $oldignore );
2342 return;
2343 }
2344
2345 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2346 $row = $dbw->fetchObject( $res );
2347 $rown = intval( $row->n );
2348 if( $rown >= $wgHitcounterUpdateFreq ){
2349 wfProfileIn( 'Article::incViewCount-collect' );
2350 $old_user_abort = ignore_user_abort( true );
2351
2352 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2353 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2354 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2355 'GROUP BY hc_id');
2356 $dbw->query("DELETE FROM $hitcounterTable");
2357 $dbw->query('UNLOCK TABLES');
2358 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2359 'WHERE page_id = hc_id');
2360 $dbw->query("DROP TABLE $acchitsTable");
2361
2362 ignore_user_abort( $old_user_abort );
2363 wfProfileOut( 'Article::incViewCount-collect' );
2364 }
2365 $dbw->ignoreErrors( $oldignore );
2366 }
2367
2368 /**#@+
2369 * The onArticle*() functions are supposed to be a kind of hooks
2370 * which should be called whenever any of the specified actions
2371 * are done.
2372 *
2373 * This is a good place to put code to clear caches, for instance.
2374 *
2375 * This is called on page move and undelete, as well as edit
2376 * @static
2377 * @param $title_obj a title object
2378 */
2379
2380 function onArticleCreate($title_obj) {
2381 global $wgUseSquid, $wgPostCommitUpdateList;
2382
2383 $title_obj->touchLinks();
2384 $titles = $title_obj->getLinksTo();
2385
2386 # Purge squid
2387 if ( $wgUseSquid ) {
2388 $urls = $title_obj->getSquidURLs();
2389 foreach ( $titles as $linkTitle ) {
2390 $urls[] = $linkTitle->getInternalURL();
2391 }
2392 $u = new SquidUpdate( $urls );
2393 array_push( $wgPostCommitUpdateList, $u );
2394 }
2395 }
2396
2397 function onArticleDelete( $title ) {
2398 global $wgMessageCache;
2399
2400 $title->touchLinks();
2401
2402 if( $title->getNamespace() == NS_MEDIAWIKI) {
2403 $wgMessageCache->replace( $title->getDBkey(), false );
2404 }
2405 }
2406
2407 /**
2408 * Purge caches on page update etc
2409 */
2410 function onArticleEdit( $title ) {
2411 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2412
2413 $urls = array();
2414
2415 // Template namespace? Purge all articles linking here.
2416 // FIXME: When a templatelinks table arrives, use it for all includes.
2417 if ( $title->getNamespace() == NS_TEMPLATE) {
2418 $titles = $title->getLinksTo();
2419 Title::touchArray( $titles );
2420 if ( $wgUseSquid ) {
2421 foreach ( $titles as $link ) {
2422 $urls[] = $link->getInternalURL();
2423 }
2424 }
2425 }
2426
2427 # Squid updates
2428 if ( $wgUseSquid ) {
2429 $urls = array_merge( $urls, $title->getSquidURLs() );
2430 $u = new SquidUpdate( $urls );
2431 array_push( $wgPostCommitUpdateList, $u );
2432 }
2433
2434 # File cache
2435 if ( $wgUseFileCache ) {
2436 $cm = new CacheManager( $title );
2437 @unlink( $cm->fileCacheName() );
2438 }
2439 }
2440
2441 /**#@-*/
2442
2443 /**
2444 * Info about this page
2445 * Called for ?action=info when $wgAllowPageInfo is on.
2446 *
2447 * @access public
2448 */
2449 function info() {
2450 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2451 $fname = 'Article::info';
2452
2453 if ( !$wgAllowPageInfo ) {
2454 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2455 return;
2456 }
2457
2458 $page = $this->mTitle->getSubjectPage();
2459
2460 $wgOut->setPagetitle( $page->getPrefixedText() );
2461 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2462
2463 # first, see if the page exists at all.
2464 $exists = $page->getArticleId() != 0;
2465 if( !$exists ) {
2466 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2467 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2468 } else {
2469 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2470 }
2471 } else {
2472 $dbr =& $this->getDB( DB_SLAVE );
2473 $wl_clause = array(
2474 'wl_title' => $page->getDBkey(),
2475 'wl_namespace' => $page->getNamespace() );
2476 $numwatchers = $dbr->selectField(
2477 'watchlist',
2478 'COUNT(*)',
2479 $wl_clause,
2480 $fname,
2481 $this->getSelectOptions() );
2482
2483 $pageInfo = $this->pageCountInfo( $page );
2484 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2485
2486 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2487 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2488 if( $talkInfo ) {
2489 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2490 }
2491 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2492 if( $talkInfo ) {
2493 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2494 }
2495 $wgOut->addHTML( '</ul>' );
2496
2497 }
2498 }
2499
2500 /**
2501 * Return the total number of edits and number of unique editors
2502 * on a given page. If page does not exist, returns false.
2503 *
2504 * @param Title $title
2505 * @return array
2506 * @access private
2507 */
2508 function pageCountInfo( $title ) {
2509 $id = $title->getArticleId();
2510 if( $id == 0 ) {
2511 return false;
2512 }
2513
2514 $dbr =& $this->getDB( DB_SLAVE );
2515
2516 $rev_clause = array( 'rev_page' => $id );
2517 $fname = 'Article::pageCountInfo';
2518
2519 $edits = $dbr->selectField(
2520 'revision',
2521 'COUNT(rev_page)',
2522 $rev_clause,
2523 $fname,
2524 $this->getSelectOptions() );
2525
2526 $authors = $dbr->selectField(
2527 'revision',
2528 'COUNT(DISTINCT rev_user_text)',
2529 $rev_clause,
2530 $fname,
2531 $this->getSelectOptions() );
2532
2533 return array( 'edits' => $edits, 'authors' => $authors );
2534 }
2535
2536 /**
2537 * Return a list of templates used by this article.
2538 * Uses the templatelinks table
2539 *
2540 * @return array Array of Title objects
2541 */
2542 function getUsedTemplates() {
2543 $result = array();
2544 $id = $this->mTitle->getArticleID();
2545
2546 $dbr =& wfGetDB( DB_SLAVE );
2547 $res = $dbr->select( array( 'templatelinks' ),
2548 array( 'tl_namespace', 'tl_title' ),
2549 array( 'tl_from' => $id ),
2550 'Article:getUsedTemplates' );
2551 if ( false !== $res ) {
2552 if ( $dbr->numRows( $res ) ) {
2553 while ( $row = $dbr->fetchObject( $res ) ) {
2554 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2555 }
2556 }
2557 }
2558 $dbr->freeResult( $res );
2559 return $result;
2560 }
2561 }
2562
2563 ?>