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