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