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