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