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