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