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