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