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