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