* Clear newtalk marker on diff links with explicit current revision number
[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 // Needed to get the page's current revision
663 $this->loadPageData();
664 if( $diff == 0 || $diff == $this->mLatest ) {
665 # Run view updates for current revision only
666 $this->viewUpdates();
667 }
668 wfProfileOut( __METHOD__ );
669 return;
670 }
671
672 if ( empty( $oldid ) && $this->checkTouched() ) {
673 $wgOut->setETag($parserCache->getETag($this, $wgUser));
674
675 if( $wgOut->checkLastModified( $this->mTouched ) ){
676 wfProfileOut( __METHOD__ );
677 return;
678 } else if ( $this->tryFileCache() ) {
679 # tell wgOut that output is taken care of
680 $wgOut->disable();
681 $this->viewUpdates();
682 wfProfileOut( __METHOD__ );
683 return;
684 }
685 }
686
687 # Should the parser cache be used?
688 $pcache = $wgEnableParserCache &&
689 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
690 $this->exists() &&
691 empty( $oldid );
692 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
693 if ( $wgUser->getOption( 'stubthreshold' ) ) {
694 wfIncrStats( 'pcache_miss_stub' );
695 }
696
697 $wasRedirected = false;
698 if ( isset( $this->mRedirectedFrom ) ) {
699 // This is an internally redirected page view.
700 // We'll need a backlink to the source page for navigation.
701 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
702 $sk = $wgUser->getSkin();
703 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
704 $s = wfMsg( 'redirectedfrom', $redir );
705 $wgOut->setSubtitle( $s );
706 $wasRedirected = true;
707 }
708 } elseif ( !empty( $rdfrom ) ) {
709 // This is an externally redirected view, from some other wiki.
710 // If it was reported from a trusted site, supply a backlink.
711 global $wgRedirectSources;
712 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
713 $sk = $wgUser->getSkin();
714 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
715 $s = wfMsg( 'redirectedfrom', $redir );
716 $wgOut->setSubtitle( $s );
717 $wasRedirected = true;
718 }
719 }
720
721 $outputDone = false;
722 if ( $pcache ) {
723 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
724 wfRunHooks( 'ArticleViewHeader', array( &$this ) );
725 $outputDone = true;
726 }
727 }
728 if ( !$outputDone ) {
729 $text = $this->getContent();
730 if ( $text === false ) {
731 # Failed to load, replace text with error message
732 $t = $this->mTitle->getPrefixedText();
733 if( $oldid ) {
734 $t .= ',oldid='.$oldid;
735 $text = wfMsg( 'missingarticle', $t );
736 } else {
737 $text = wfMsg( 'noarticletext', $t );
738 }
739 }
740
741 # Another whitelist check in case oldid is altering the title
742 if ( !$this->mTitle->userCanRead() ) {
743 $wgOut->loginToUse();
744 $wgOut->output();
745 exit;
746 }
747
748 # We're looking at an old revision
749
750 if ( !empty( $oldid ) ) {
751 $wgOut->setRobotpolicy( 'noindex,nofollow' );
752 if( is_null( $this->mRevision ) ) {
753 // FIXME: This would be a nice place to load the 'no such page' text.
754 } else {
755 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
756 if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
757 if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
758 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
759 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
760 return;
761 } else {
762 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
763 // and we are allowed to see...
764 }
765 }
766 }
767
768 }
769 }
770 if( !$outputDone ) {
771 /**
772 * @fixme: this hook doesn't work most of the time, as it doesn't
773 * trigger when the parser cache is used.
774 */
775 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
776 $wgOut->setRevisionId( $this->getRevIdFetched() );
777 # wrap user css and user js in pre and don't parse
778 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
779 if (
780 $ns == NS_USER &&
781 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
782 ) {
783 $wgOut->addWikiText( wfMsg('clearyourcache'));
784 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
785 } else if ( $rt = Title::newFromRedirect( $text ) ) {
786 # Display redirect
787 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
788 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
789 # Don't overwrite the subtitle if this was an old revision
790 if( !$wasRedirected && $this->isCurrent() ) {
791 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
792 }
793 $targetUrl = $rt->escapeLocalURL();
794 # fixme unused $titleText :
795 $titleText = htmlspecialchars( $rt->getPrefixedText() );
796 $link = $sk->makeLinkObj( $rt );
797
798 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
799 '<span class="redirectText">'.$link.'</span>' );
800
801 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
802 $wgOut->addParserOutputNoText( $parseout );
803 } else if ( $pcache ) {
804 # Display content and save to parser cache
805 $wgOut->addPrimaryWikiText( $text, $this );
806 } else {
807 # Display content, don't attempt to save to parser cache
808 # Don't show section-edit links on old revisions... this way lies madness.
809 if( !$this->isCurrent() ) {
810 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
811 }
812 # Display content and don't save to parser cache
813 $wgOut->addPrimaryWikiText( $text, $this, false );
814
815 if( !$this->isCurrent() ) {
816 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
817 }
818 }
819 }
820 /* title may have been set from the cache */
821 $t = $wgOut->getPageTitle();
822 if( empty( $t ) ) {
823 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
824 }
825
826 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
827 if( $ns == NS_USER_TALK &&
828 User::isIP( $this->mTitle->getText() ) ) {
829 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
830 }
831
832 # If we have been passed an &rcid= parameter, we want to give the user a
833 # chance to mark this new article as patrolled.
834 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
835 $wgOut->addHTML(
836 "<div class='patrollink'>" .
837 wfMsg ( 'markaspatrolledlink',
838 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
839 ) .
840 '</div>'
841 );
842 }
843
844 # Trackbacks
845 if ($wgUseTrackbacks)
846 $this->addTrackbacks();
847
848 $this->viewUpdates();
849 wfProfileOut( __METHOD__ );
850 }
851
852 function addTrackbacks() {
853 global $wgOut, $wgUser;
854
855 $dbr =& wfGetDB(DB_SLAVE);
856 $tbs = $dbr->select(
857 /* FROM */ 'trackbacks',
858 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
859 /* WHERE */ array('tb_page' => $this->getID())
860 );
861
862 if (!$dbr->numrows($tbs))
863 return;
864
865 $tbtext = "";
866 while ($o = $dbr->fetchObject($tbs)) {
867 $rmvtxt = "";
868 if ($wgUser->isAllowed( 'trackback' )) {
869 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
870 . $o->tb_id . "&token=" . $wgUser->editToken());
871 $rmvtxt = wfMsg('trackbackremove', $delurl);
872 }
873 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
874 $o->tb_title,
875 $o->tb_url,
876 $o->tb_ex,
877 $o->tb_name,
878 $rmvtxt);
879 }
880 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
881 }
882
883 function deletetrackback() {
884 global $wgUser, $wgRequest, $wgOut, $wgTitle;
885
886 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
887 $wgOut->addWikitext(wfMsg('sessionfailure'));
888 return;
889 }
890
891 if ((!$wgUser->isAllowed('delete'))) {
892 $wgOut->permissionRequired( 'delete' );
893 return;
894 }
895
896 if (wfReadOnly()) {
897 $wgOut->readOnlyPage();
898 return;
899 }
900
901 $db =& wfGetDB(DB_MASTER);
902 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
903 $wgTitle->invalidateCache();
904 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
905 }
906
907 function render() {
908 global $wgOut;
909
910 $wgOut->setArticleBodyOnly(true);
911 $this->view();
912 }
913
914 /**
915 * Handle action=purge
916 */
917 function purge() {
918 global $wgUser, $wgRequest, $wgOut;
919
920 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
921 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
922 $this->doPurge();
923 }
924 } else {
925 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
926 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
927 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
928 $msg = str_replace( '$1',
929 "<form method=\"post\" action=\"$action\">\n" .
930 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
931 "</form>\n", $msg );
932
933 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
934 $wgOut->setRobotpolicy( 'noindex,nofollow' );
935 $wgOut->addHTML( $msg );
936 }
937 }
938
939 /**
940 * Perform the actions of a page purging
941 */
942 function doPurge() {
943 global $wgUseSquid;
944 // Invalidate the cache
945 $this->mTitle->invalidateCache();
946
947 if ( $wgUseSquid ) {
948 // Commit the transaction before the purge is sent
949 $dbw = wfGetDB( DB_MASTER );
950 $dbw->immediateCommit();
951
952 // Send purge
953 $update = SquidUpdate::newSimplePurge( $this->mTitle );
954 $update->doUpdate();
955 }
956 $this->view();
957 }
958
959 /**
960 * Insert a new empty page record for this article.
961 * This *must* be followed up by creating a revision
962 * and running $this->updateToLatest( $rev_id );
963 * or else the record will be left in a funky state.
964 * Best if all done inside a transaction.
965 *
966 * @param Database $dbw
967 * @param string $restrictions
968 * @return int The newly created page_id key
969 * @private
970 */
971 function insertOn( &$dbw, $restrictions = '' ) {
972 wfProfileIn( __METHOD__ );
973
974 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
975 $dbw->insert( 'page', array(
976 'page_id' => $page_id,
977 'page_namespace' => $this->mTitle->getNamespace(),
978 'page_title' => $this->mTitle->getDBkey(),
979 'page_counter' => 0,
980 'page_restrictions' => $restrictions,
981 'page_is_redirect' => 0, # Will set this shortly...
982 'page_is_new' => 1,
983 'page_random' => wfRandom(),
984 'page_touched' => $dbw->timestamp(),
985 'page_latest' => 0, # Fill this in shortly...
986 'page_len' => 0, # Fill this in shortly...
987 ), __METHOD__ );
988 $newid = $dbw->insertId();
989
990 $this->mTitle->resetArticleId( $newid );
991
992 wfProfileOut( __METHOD__ );
993 return $newid;
994 }
995
996 /**
997 * Update the page record to point to a newly saved revision.
998 *
999 * @param Database $dbw
1000 * @param Revision $revision For ID number, and text used to set
1001 length and redirect status fields
1002 * @param int $lastRevision If given, will not overwrite the page field
1003 * when different from the currently set value.
1004 * Giving 0 indicates the new page flag should
1005 * be set on.
1006 * @return bool true on success, false on failure
1007 * @private
1008 */
1009 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1010 wfProfileIn( __METHOD__ );
1011
1012 $conditions = array( 'page_id' => $this->getId() );
1013 if( !is_null( $lastRevision ) ) {
1014 # An extra check against threads stepping on each other
1015 $conditions['page_latest'] = $lastRevision;
1016 }
1017
1018 $text = $revision->getText();
1019 $dbw->update( 'page',
1020 array( /* SET */
1021 'page_latest' => $revision->getId(),
1022 'page_touched' => $dbw->timestamp(),
1023 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1024 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1025 'page_len' => strlen( $text ),
1026 ),
1027 $conditions,
1028 __METHOD__ );
1029
1030 wfProfileOut( __METHOD__ );
1031 return ( $dbw->affectedRows() != 0 );
1032 }
1033
1034 /**
1035 * If the given revision is newer than the currently set page_latest,
1036 * update the page record. Otherwise, do nothing.
1037 *
1038 * @param Database $dbw
1039 * @param Revision $revision
1040 */
1041 function updateIfNewerOn( &$dbw, $revision ) {
1042 wfProfileIn( __METHOD__ );
1043
1044 $row = $dbw->selectRow(
1045 array( 'revision', 'page' ),
1046 array( 'rev_id', 'rev_timestamp' ),
1047 array(
1048 'page_id' => $this->getId(),
1049 'page_latest=rev_id' ),
1050 __METHOD__ );
1051 if( $row ) {
1052 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1053 wfProfileOut( __METHOD__ );
1054 return false;
1055 }
1056 $prev = $row->rev_id;
1057 } else {
1058 # No or missing previous revision; mark the page as new
1059 $prev = 0;
1060 }
1061
1062 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1063 wfProfileOut( __METHOD__ );
1064 return $ret;
1065 }
1066
1067 /**
1068 * @return string Complete article text, or null if error
1069 */
1070 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1071 wfProfileIn( __METHOD__ );
1072
1073 if( $section == '' ) {
1074 // Whole-page edit; let the text through unmolested.
1075 } else {
1076 if( is_null( $edittime ) ) {
1077 $rev = Revision::newFromTitle( $this->mTitle );
1078 } else {
1079 $dbw =& wfGetDB( DB_MASTER );
1080 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1081 }
1082 if( is_null( $rev ) ) {
1083 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1084 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1085 return null;
1086 }
1087 $oldtext = $rev->getText();
1088
1089 if($section=='new') {
1090 if($summary) $subject="== {$summary} ==\n\n";
1091 $text=$oldtext."\n\n".$subject.$text;
1092 } else {
1093 global $wgParser;
1094 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1095 }
1096 }
1097
1098 wfProfileOut( __METHOD__ );
1099 return $text;
1100 }
1101
1102 /**
1103 * @deprecated use Article::doEdit()
1104 */
1105 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1106 $flags = EDIT_NEW | EDIT_DEFER_UPDATES |
1107 ( $isminor ? EDIT_MINOR : 0 ) |
1108 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 );
1109
1110 # If this is a comment, add the summary as headline
1111 if ( $comment && $summary != "" ) {
1112 $text = "== {$summary} ==\n\n".$text;
1113 }
1114
1115 $this->doEdit( $text, $summary, $flags );
1116
1117 $dbw =& wfGetDB( DB_MASTER );
1118 if ($watchthis) {
1119 if (!$this->mTitle->userIsWatching()) {
1120 $dbw->begin();
1121 $this->doWatch();
1122 $dbw->commit();
1123 }
1124 } else {
1125 if ( $this->mTitle->userIsWatching() ) {
1126 $dbw->begin();
1127 $this->doUnwatch();
1128 $dbw->commit();
1129 }
1130 }
1131 $this->doRedirect( $this->isRedirect( $text ) );
1132 }
1133
1134 /**
1135 * @deprecated use Article::doEdit()
1136 */
1137 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1138 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES |
1139 ( $minor ? EDIT_MINOR : 0 ) |
1140 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1141
1142 $good = $this->doEdit( $text, $summary, $flags );
1143 if ( $good ) {
1144 $dbw =& wfGetDB( DB_MASTER );
1145 if ($watchthis) {
1146 if (!$this->mTitle->userIsWatching()) {
1147 $dbw->begin();
1148 $this->doWatch();
1149 $dbw->commit();
1150 }
1151 } else {
1152 if ( $this->mTitle->userIsWatching() ) {
1153 $dbw->begin();
1154 $this->doUnwatch();
1155 $dbw->commit();
1156 }
1157 }
1158
1159 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1160 }
1161 return $good;
1162 }
1163
1164 /**
1165 * Article::doEdit()
1166 *
1167 * Change an existing article or create a new article. Updates RC and all necessary caches,
1168 * optionally via the deferred update array.
1169 *
1170 * $wgUser must be set before calling this function.
1171 *
1172 * @param string $text New text
1173 * @param string $summary Edit summary
1174 * @param integer $flags bitfield:
1175 * EDIT_NEW
1176 * Article is known or assumed to be non-existent, create a new one
1177 * EDIT_UPDATE
1178 * Article is known or assumed to be pre-existing, update it
1179 * EDIT_MINOR
1180 * Mark this edit minor, if the user is allowed to do so
1181 * EDIT_SUPPRESS_RC
1182 * Do not log the change in recentchanges
1183 * EDIT_FORCE_BOT
1184 * Mark the edit a "bot" edit regardless of user rights
1185 * EDIT_DEFER_UPDATES
1186 * Defer some of the updates until the end of index.php
1187 *
1188 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1189 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1190 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1191 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1192 * to MediaWiki's performance-optimised locking strategy.
1193 *
1194 * @return bool success
1195 */
1196 function doEdit( $text, $summary, $flags = 0 ) {
1197 global $wgUser, $wgDBtransactions;
1198
1199 wfProfileIn( __METHOD__ );
1200 $good = true;
1201
1202 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1203 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1204 if ( $aid ) {
1205 $flags |= EDIT_UPDATE;
1206 } else {
1207 $flags |= EDIT_NEW;
1208 }
1209 }
1210
1211 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1212 &$summary, $flags & EDIT_MINOR,
1213 null, null, &$flags ) ) )
1214 {
1215 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1216 wfProfileOut( __METHOD__ );
1217 return false;
1218 }
1219
1220 # Silently ignore EDIT_MINOR if not allowed
1221 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1222 $bot = $wgUser->isAllowed( 'bot' ) || ( $flags & EDIT_FORCE_BOT );
1223
1224 $text = $this->preSaveTransform( $text );
1225
1226 $dbw =& wfGetDB( DB_MASTER );
1227 $now = wfTimestampNow();
1228
1229 if ( $flags & EDIT_UPDATE ) {
1230 # Update article, but only if changed.
1231
1232 # Make sure the revision is either completely inserted or not inserted at all
1233 if( !$wgDBtransactions ) {
1234 $userAbort = ignore_user_abort( true );
1235 }
1236
1237 $oldtext = $this->getContent();
1238 $oldsize = strlen( $oldtext );
1239 $newsize = strlen( $text );
1240 $lastRevision = 0;
1241 $revisionId = 0;
1242
1243 if ( 0 != strcmp( $text, $oldtext ) ) {
1244 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1245 - (int)$this->isCountable( $oldtext );
1246 $this->mTotalAdjustment = 0;
1247
1248 $lastRevision = $dbw->selectField(
1249 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1250
1251 if ( !$lastRevision ) {
1252 # Article gone missing
1253 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1254 wfProfileOut( __METHOD__ );
1255 return false;
1256 }
1257
1258 $revision = new Revision( array(
1259 'page' => $this->getId(),
1260 'comment' => $summary,
1261 'minor_edit' => $isminor,
1262 'text' => $text
1263 ) );
1264
1265 $dbw->begin();
1266 $revisionId = $revision->insertOn( $dbw );
1267
1268 # Update page
1269 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1270
1271 if( !$ok ) {
1272 /* Belated edit conflict! Run away!! */
1273 $good = false;
1274 $dbw->rollback();
1275 } else {
1276 # Update recentchanges
1277 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1278 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1279 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1280 $revisionId );
1281
1282 # Mark as patrolled if the user can do so and has it set in their options
1283 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1284 RecentChange::markPatrolled( $rcid );
1285 }
1286 }
1287 $dbw->commit();
1288 }
1289 } else {
1290 // Keep the same revision ID, but do some updates on it
1291 $revisionId = $this->getRevIdFetched();
1292 // Update page_touched, this is usually implicit in the page update
1293 // Other cache updates are done in onArticleEdit()
1294 $this->mTitle->invalidateCache();
1295 }
1296
1297 if( !$wgDBtransactions ) {
1298 ignore_user_abort( $userAbort );
1299 }
1300
1301 if ( $good ) {
1302 # Invalidate cache of this article and all pages using this article
1303 # as a template. Partly deferred.
1304 Article::onArticleEdit( $this->mTitle );
1305
1306 # Update links tables, site stats, etc.
1307 $changed = ( strcmp( $oldtext, $text ) != 0 );
1308 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1309 }
1310 } else {
1311 # Create new article
1312
1313 # Set statistics members
1314 # We work out if it's countable after PST to avoid counter drift
1315 # when articles are created with {{subst:}}
1316 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1317 $this->mTotalAdjustment = 1;
1318
1319 $dbw->begin();
1320
1321 # Add the page record; stake our claim on this title!
1322 # This will fail with a database query exception if the article already exists
1323 $newid = $this->insertOn( $dbw );
1324
1325 # Save the revision text...
1326 $revision = new Revision( array(
1327 'page' => $newid,
1328 'comment' => $summary,
1329 'minor_edit' => $isminor,
1330 'text' => $text
1331 ) );
1332 $revisionId = $revision->insertOn( $dbw );
1333
1334 $this->mTitle->resetArticleID( $newid );
1335
1336 # Update the page record with revision data
1337 $this->updateRevisionOn( $dbw, $revision, 0 );
1338
1339 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1340 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1341 '', strlen( $text ), $revisionId );
1342 # Mark as patrolled if the user can and has the option set
1343 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1344 RecentChange::markPatrolled( $rcid );
1345 }
1346 }
1347 $dbw->commit();
1348
1349 # Update links, etc.
1350 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1351
1352 # Clear caches
1353 Article::onArticleCreate( $this->mTitle );
1354
1355 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1356 $summary, $flags & EDIT_MINOR,
1357 null, null, &$flags ) );
1358 }
1359
1360 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1361 wfDoUpdates();
1362 }
1363
1364 wfRunHooks( 'ArticleSaveComplete',
1365 array( &$this, &$wgUser, $text,
1366 $summary, $flags & EDIT_MINOR,
1367 null, null, &$flags ) );
1368
1369 wfProfileOut( __METHOD__ );
1370 return $good;
1371 }
1372
1373 /**
1374 * @deprecated wrapper for doRedirect
1375 */
1376 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1377 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1378 }
1379
1380 /**
1381 * Output a redirect back to the article.
1382 * This is typically used after an edit.
1383 *
1384 * @param boolean $noRedir Add redirect=no
1385 * @param string $sectionAnchor section to redirect to, including "#"
1386 */
1387 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1388 global $wgOut;
1389 if ( $noRedir ) {
1390 $query = 'redirect=no';
1391 } else {
1392 $query = '';
1393 }
1394 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1395 }
1396
1397 /**
1398 * Mark this particular edit as patrolled
1399 */
1400 function markpatrolled() {
1401 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1402 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1403
1404 # Check RC patrol config. option
1405 if( !$wgUseRCPatrol ) {
1406 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1407 return;
1408 }
1409
1410 # Check permissions
1411 if( !$wgUser->isAllowed( 'patrol' ) ) {
1412 $wgOut->permissionRequired( 'patrol' );
1413 return;
1414 }
1415
1416 $rcid = $wgRequest->getVal( 'rcid' );
1417 if ( !is_null ( $rcid ) ) {
1418 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1419 RecentChange::markPatrolled( $rcid );
1420 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1421 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1422 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1423 }
1424 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1425 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1426 }
1427 else {
1428 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1429 }
1430 }
1431
1432 /**
1433 * User-interface handler for the "watch" action
1434 */
1435
1436 function watch() {
1437
1438 global $wgUser, $wgOut;
1439
1440 if ( $wgUser->isAnon() ) {
1441 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1442 return;
1443 }
1444 if ( wfReadOnly() ) {
1445 $wgOut->readOnlyPage();
1446 return;
1447 }
1448
1449 if( $this->doWatch() ) {
1450 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1451 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1452
1453 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1454 $text = wfMsg( 'addedwatchtext', $link );
1455 $wgOut->addWikiText( $text );
1456 }
1457
1458 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1459 }
1460
1461 /**
1462 * Add this page to $wgUser's watchlist
1463 * @return bool true on successful watch operation
1464 */
1465 function doWatch() {
1466 global $wgUser;
1467 if( $wgUser->isAnon() ) {
1468 return false;
1469 }
1470
1471 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1472 $wgUser->addWatch( $this->mTitle );
1473 $wgUser->saveSettings();
1474
1475 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1476 }
1477
1478 return false;
1479 }
1480
1481 /**
1482 * User interface handler for the "unwatch" action.
1483 */
1484 function unwatch() {
1485
1486 global $wgUser, $wgOut;
1487
1488 if ( $wgUser->isAnon() ) {
1489 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1490 return;
1491 }
1492 if ( wfReadOnly() ) {
1493 $wgOut->readOnlyPage();
1494 return;
1495 }
1496
1497 if( $this->doUnwatch() ) {
1498 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1499 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1500
1501 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1502 $text = wfMsg( 'removedwatchtext', $link );
1503 $wgOut->addWikiText( $text );
1504 }
1505
1506 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1507 }
1508
1509 /**
1510 * Stop watching a page
1511 * @return bool true on successful unwatch
1512 */
1513 function doUnwatch() {
1514 global $wgUser;
1515 if( $wgUser->isAnon() ) {
1516 return false;
1517 }
1518
1519 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1520 $wgUser->removeWatch( $this->mTitle );
1521 $wgUser->saveSettings();
1522
1523 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1524 }
1525
1526 return false;
1527 }
1528
1529 /**
1530 * action=protect handler
1531 */
1532 function protect() {
1533 require_once 'ProtectionForm.php';
1534 $form = new ProtectionForm( $this );
1535 $form->show();
1536 }
1537
1538 /**
1539 * action=unprotect handler (alias)
1540 */
1541 function unprotect() {
1542 $this->protect();
1543 }
1544
1545 /**
1546 * Update the article's restriction field, and leave a log entry.
1547 *
1548 * @param array $limit set of restriction keys
1549 * @param string $reason
1550 * @return bool true on success
1551 */
1552 function updateRestrictions( $limit = array(), $reason = '' ) {
1553 global $wgUser, $wgRestrictionTypes, $wgContLang;
1554
1555 $id = $this->mTitle->getArticleID();
1556 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1557 return false;
1558 }
1559
1560 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1561 # we expect a single selection, but the schema allows otherwise.
1562 $current = array();
1563 foreach( $wgRestrictionTypes as $action )
1564 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1565
1566 $current = Article::flattenRestrictions( $current );
1567 $updated = Article::flattenRestrictions( $limit );
1568
1569 $changed = ( $current != $updated );
1570 $protect = ( $updated != '' );
1571
1572 # If nothing's changed, do nothing
1573 if( $changed ) {
1574 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1575
1576 $dbw =& wfGetDB( DB_MASTER );
1577
1578 # Prepare a null revision to be added to the history
1579 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1580 if( $reason )
1581 $comment .= ": $reason";
1582 if( $protect )
1583 $comment .= " [$updated]";
1584 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1585 $nullRevId = $nullRevision->insertOn( $dbw );
1586
1587 # Update page record
1588 $dbw->update( 'page',
1589 array( /* SET */
1590 'page_touched' => $dbw->timestamp(),
1591 'page_restrictions' => $updated,
1592 'page_latest' => $nullRevId
1593 ), array( /* WHERE */
1594 'page_id' => $id
1595 ), 'Article::protect'
1596 );
1597 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1598
1599 # Update the protection log
1600 $log = new LogPage( 'protect' );
1601 if( $protect ) {
1602 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]" ) );
1603 } else {
1604 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1605 }
1606
1607 } # End hook
1608 } # End "changed" check
1609
1610 return true;
1611 }
1612
1613 /**
1614 * Take an array of page restrictions and flatten it to a string
1615 * suitable for insertion into the page_restrictions field.
1616 * @param array $limit
1617 * @return string
1618 * @private
1619 */
1620 function flattenRestrictions( $limit ) {
1621 if( !is_array( $limit ) ) {
1622 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1623 }
1624 $bits = array();
1625 ksort( $limit );
1626 foreach( $limit as $action => $restrictions ) {
1627 if( $restrictions != '' ) {
1628 $bits[] = "$action=$restrictions";
1629 }
1630 }
1631 return implode( ':', $bits );
1632 }
1633
1634 /*
1635 * UI entry point for page deletion
1636 */
1637 function delete() {
1638 global $wgUser, $wgOut, $wgRequest;
1639 $confirm = $wgRequest->wasPosted() &&
1640 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1641 $reason = $wgRequest->getText( 'wpReason' );
1642
1643 # This code desperately needs to be totally rewritten
1644
1645 # Check permissions
1646 if( $wgUser->isAllowed( 'delete' ) ) {
1647 if( $wgUser->isBlocked( !$confirm ) ) {
1648 $wgOut->blockedPage();
1649 return;
1650 }
1651 } else {
1652 $wgOut->permissionRequired( 'delete' );
1653 return;
1654 }
1655
1656 if( wfReadOnly() ) {
1657 $wgOut->readOnlyPage();
1658 return;
1659 }
1660
1661 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1662
1663 # Better double-check that it hasn't been deleted yet!
1664 $dbw =& wfGetDB( DB_MASTER );
1665 $conds = $this->mTitle->pageCond();
1666 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1667 if ( $latest === false ) {
1668 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1669 return;
1670 }
1671
1672 if( $confirm ) {
1673 $this->doDelete( $reason );
1674 return;
1675 }
1676
1677 # determine whether this page has earlier revisions
1678 # and insert a warning if it does
1679 $maxRevisions = 20;
1680 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1681
1682 if( count( $authors ) > 1 && !$confirm ) {
1683 $skin=$wgUser->getSkin();
1684 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1685 }
1686
1687 # If a single user is responsible for all revisions, find out who they are
1688 if ( count( $authors ) == $maxRevisions ) {
1689 // Query bailed out, too many revisions to find out if they're all the same
1690 $authorOfAll = false;
1691 } else {
1692 $authorOfAll = reset( $authors );
1693 foreach ( $authors as $author ) {
1694 if ( $authorOfAll != $author ) {
1695 $authorOfAll = false;
1696 break;
1697 }
1698 }
1699 }
1700 # Fetch article text
1701 $rev = Revision::newFromTitle( $this->mTitle );
1702
1703 if( !is_null( $rev ) ) {
1704 # if this is a mini-text, we can paste part of it into the deletion reason
1705 $text = $rev->getText();
1706
1707 #if this is empty, an earlier revision may contain "useful" text
1708 $blanked = false;
1709 if( $text == '' ) {
1710 $prev = $rev->getPrevious();
1711 if( $prev ) {
1712 $text = $prev->getText();
1713 $blanked = true;
1714 }
1715 }
1716
1717 $length = strlen( $text );
1718
1719 # this should not happen, since it is not possible to store an empty, new
1720 # page. Let's insert a standard text in case it does, though
1721 if( $length == 0 && $reason === '' ) {
1722 $reason = wfMsgForContent( 'exblank' );
1723 }
1724
1725 if( $length < 500 && $reason === '' ) {
1726 # comment field=255, let's grep the first 150 to have some user
1727 # space left
1728 global $wgContLang;
1729 $text = $wgContLang->truncate( $text, 150, '...' );
1730
1731 # let's strip out newlines
1732 $text = preg_replace( "/[\n\r]/", '', $text );
1733
1734 if( !$blanked ) {
1735 if( $authorOfAll === false ) {
1736 $reason = wfMsgForContent( 'excontent', $text );
1737 } else {
1738 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1739 }
1740 } else {
1741 $reason = wfMsgForContent( 'exbeforeblank', $text );
1742 }
1743 }
1744 }
1745
1746 return $this->confirmDelete( '', $reason );
1747 }
1748
1749 /**
1750 * Get the last N authors
1751 * @param int $num Number of revisions to get
1752 * @param string $revLatest The latest rev_id, selected from the master (optional)
1753 * @return array Array of authors, duplicates not removed
1754 */
1755 function getLastNAuthors( $num, $revLatest = 0 ) {
1756 wfProfileIn( __METHOD__ );
1757
1758 // First try the slave
1759 // If that doesn't have the latest revision, try the master
1760 $continue = 2;
1761 $db =& wfGetDB( DB_SLAVE );
1762 do {
1763 $res = $db->select( array( 'page', 'revision' ),
1764 array( 'rev_id', 'rev_user_text' ),
1765 array(
1766 'page_namespace' => $this->mTitle->getNamespace(),
1767 'page_title' => $this->mTitle->getDBkey(),
1768 'rev_page = page_id'
1769 ), __METHOD__, $this->getSelectOptions( array(
1770 'ORDER BY' => 'rev_timestamp DESC',
1771 'LIMIT' => $num
1772 ) )
1773 );
1774 if ( !$res ) {
1775 wfProfileOut( __METHOD__ );
1776 return array();
1777 }
1778 $row = $db->fetchObject( $res );
1779 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1780 $db =& wfGetDB( DB_MASTER );
1781 $continue--;
1782 } else {
1783 $continue = 0;
1784 }
1785 } while ( $continue );
1786
1787 $authors = array( $row->rev_user_text );
1788 while ( $row = $db->fetchObject( $res ) ) {
1789 $authors[] = $row->rev_user_text;
1790 }
1791 wfProfileOut( __METHOD__ );
1792 return $authors;
1793 }
1794
1795 /**
1796 * Output deletion confirmation dialog
1797 */
1798 function confirmDelete( $par, $reason ) {
1799 global $wgOut, $wgUser;
1800
1801 wfDebug( "Article::confirmDelete\n" );
1802
1803 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1804 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1805 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1806 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1807
1808 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1809
1810 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1811 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1812 $token = htmlspecialchars( $wgUser->editToken() );
1813
1814 $wgOut->addHTML( "
1815 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1816 <table border='0'>
1817 <tr>
1818 <td align='right'>
1819 <label for='wpReason'>{$delcom}:</label>
1820 </td>
1821 <td align='left'>
1822 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1823 </td>
1824 </tr>
1825 <tr>
1826 <td>&nbsp;</td>
1827 <td>
1828 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1829 </td>
1830 </tr>
1831 </table>
1832 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1833 </form>\n" );
1834
1835 $wgOut->returnToMain( false );
1836 }
1837
1838
1839 /**
1840 * Perform a deletion and output success or failure messages
1841 */
1842 function doDelete( $reason ) {
1843 global $wgOut, $wgUser;
1844 wfDebug( __METHOD__."\n" );
1845
1846 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1847 if ( $this->doDeleteArticle( $reason ) ) {
1848 $deleted = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1849
1850 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1851 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1852
1853 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1854 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1855
1856 $wgOut->addWikiText( $text );
1857 $wgOut->returnToMain( false );
1858 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1859 } else {
1860 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1861 }
1862 }
1863 }
1864
1865 /**
1866 * Back-end article deletion
1867 * Deletes the article with database consistency, writes logs, purges caches
1868 * Returns success
1869 */
1870 function doDeleteArticle( $reason ) {
1871 global $wgUseSquid, $wgDeferredUpdateList;
1872 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1873
1874 wfDebug( __METHOD__."\n" );
1875
1876 $dbw =& wfGetDB( DB_MASTER );
1877 $ns = $this->mTitle->getNamespace();
1878 $t = $this->mTitle->getDBkey();
1879 $id = $this->mTitle->getArticleID();
1880
1881 if ( $t == '' || $id == 0 ) {
1882 return false;
1883 }
1884
1885 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1886 array_push( $wgDeferredUpdateList, $u );
1887
1888 // For now, shunt the revision data into the archive table.
1889 // Text is *not* removed from the text table; bulk storage
1890 // is left intact to avoid breaking block-compression or
1891 // immutable storage schemes.
1892 //
1893 // For backwards compatibility, note that some older archive
1894 // table entries will have ar_text and ar_flags fields still.
1895 //
1896 // In the future, we may keep revisions and mark them with
1897 // the rev_deleted field, which is reserved for this purpose.
1898 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1899 array(
1900 'ar_namespace' => 'page_namespace',
1901 'ar_title' => 'page_title',
1902 'ar_comment' => 'rev_comment',
1903 'ar_user' => 'rev_user',
1904 'ar_user_text' => 'rev_user_text',
1905 'ar_timestamp' => 'rev_timestamp',
1906 'ar_minor_edit' => 'rev_minor_edit',
1907 'ar_rev_id' => 'rev_id',
1908 'ar_text_id' => 'rev_text_id',
1909 ), array(
1910 'page_id' => $id,
1911 'page_id = rev_page'
1912 ), __METHOD__
1913 );
1914
1915 # Now that it's safely backed up, delete it
1916 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
1917
1918 # If using cascading deletes, we can skip some explicit deletes
1919 if ( !$dbw->cascadingDeletes() ) {
1920
1921 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
1922
1923 if ($wgUseTrackbacks)
1924 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
1925
1926 # Delete outgoing links
1927 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1928 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1929 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1930 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1931 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1932 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1933 }
1934
1935 # If using cleanup triggers, we can skip some manual deletes
1936 if ( !$dbw->cleanupTriggers() ) {
1937
1938 # Clean up recentchanges entries...
1939 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
1940 }
1941
1942 # Clear caches
1943 Article::onArticleDelete( $this->mTitle );
1944
1945 # Log the deletion
1946 $log = new LogPage( 'delete' );
1947 $log->addEntry( 'delete', $this->mTitle, $reason );
1948
1949 # Clear the cached article id so the interface doesn't act like we exist
1950 $this->mTitle->resetArticleID( 0 );
1951 $this->mTitle->mArticleID = 0;
1952 return true;
1953 }
1954
1955 /**
1956 * Revert a modification
1957 */
1958 function rollback() {
1959 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
1960
1961 if( $wgUser->isAllowed( 'rollback' ) ) {
1962 if( $wgUser->isBlocked() ) {
1963 $wgOut->blockedPage();
1964 return;
1965 }
1966 } else {
1967 $wgOut->permissionRequired( 'rollback' );
1968 return;
1969 }
1970
1971 if ( wfReadOnly() ) {
1972 $wgOut->readOnlyPage( $this->getContent() );
1973 return;
1974 }
1975 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1976 array( $this->mTitle->getPrefixedText(),
1977 $wgRequest->getVal( 'from' ) ) ) ) {
1978 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1979 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1980 return;
1981 }
1982 $dbw =& wfGetDB( DB_MASTER );
1983
1984 # Enhanced rollback, marks edits rc_bot=1
1985 $bot = $wgRequest->getBool( 'bot' );
1986
1987 # Replace all this user's current edits with the next one down
1988 $tt = $this->mTitle->getDBKey();
1989 $n = $this->mTitle->getNamespace();
1990
1991 # Get the last editor
1992 $current = Revision::newFromTitle( $this->mTitle );
1993 if( is_null( $current ) ) {
1994 # Something wrong... no page?
1995 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1996 return;
1997 }
1998
1999 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2000 if( $from != $current->getUserText() ) {
2001 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2002 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2003 htmlspecialchars( $this->mTitle->getPrefixedText()),
2004 htmlspecialchars( $from ),
2005 htmlspecialchars( $current->getUserText() ) ) );
2006 if( $current->getComment() != '') {
2007 $wgOut->addHTML(
2008 wfMsg( 'editcomment',
2009 htmlspecialchars( $current->getComment() ) ) );
2010 }
2011 return;
2012 }
2013
2014 # Get the last edit not by this guy
2015 $user = intval( $current->getUser() );
2016 $user_text = $dbw->addQuotes( $current->getUserText() );
2017 $s = $dbw->selectRow( 'revision',
2018 array( 'rev_id', 'rev_timestamp' ),
2019 array(
2020 'rev_page' => $current->getPage(),
2021 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2022 ), __METHOD__,
2023 array(
2024 'USE INDEX' => 'page_timestamp',
2025 'ORDER BY' => 'rev_timestamp DESC' )
2026 );
2027 if( $s === false ) {
2028 # Something wrong
2029 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2030 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2031 return;
2032 }
2033
2034 $set = array();
2035 if ( $bot ) {
2036 # Mark all reverted edits as bot
2037 $set['rc_bot'] = 1;
2038 }
2039 if ( $wgUseRCPatrol ) {
2040 # Mark all reverted edits as patrolled
2041 $set['rc_patrolled'] = 1;
2042 }
2043
2044 if ( $set ) {
2045 $dbw->update( 'recentchanges', $set,
2046 array( /* WHERE */
2047 'rc_cur_id' => $current->getPage(),
2048 'rc_user_text' => $current->getUserText(),
2049 "rc_timestamp > '{$s->rev_timestamp}'",
2050 ), __METHOD__
2051 );
2052 }
2053
2054 # Get the edit summary
2055 $target = Revision::newFromId( $s->rev_id );
2056 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2057 $newComment = $wgRequest->getText( 'summary', $newComment );
2058
2059 # Save it!
2060 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2061 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2062 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2063
2064 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2065
2066 $wgOut->returnToMain( false );
2067 }
2068
2069
2070 /**
2071 * Do standard deferred updates after page view
2072 * @private
2073 */
2074 function viewUpdates() {
2075 global $wgDeferredUpdateList;
2076
2077 if ( 0 != $this->getID() ) {
2078 global $wgDisableCounters;
2079 if( !$wgDisableCounters ) {
2080 Article::incViewCount( $this->getID() );
2081 $u = new SiteStatsUpdate( 1, 0, 0 );
2082 array_push( $wgDeferredUpdateList, $u );
2083 }
2084 }
2085
2086 # Update newtalk / watchlist notification status
2087 global $wgUser;
2088 $wgUser->clearNotification( $this->mTitle );
2089 }
2090
2091 /**
2092 * Do standard deferred updates after page edit.
2093 * Update links tables, site stats, search index and message cache.
2094 * Every 1000th edit, prune the recent changes table.
2095 *
2096 * @private
2097 * @param $text New text of the article
2098 * @param $summary Edit summary
2099 * @param $minoredit Minor edit
2100 * @param $timestamp_of_pagechange Timestamp associated with the page change
2101 * @param $newid rev_id value of the new revision
2102 * @param $changed Whether or not the content actually changed
2103 */
2104 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2105 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2106
2107 wfProfileIn( __METHOD__ );
2108
2109 # Parse the text
2110 $options = new ParserOptions;
2111 $options->setTidy(true);
2112 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2113
2114 # Save it to the parser cache
2115 $parserCache =& ParserCache::singleton();
2116 $parserCache->save( $poutput, $this, $wgUser );
2117
2118 # Update the links tables
2119 $u = new LinksUpdate( $this->mTitle, $poutput );
2120 $u->doUpdate();
2121
2122 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2123 wfSeedRandom();
2124 if ( 0 == mt_rand( 0, 999 ) ) {
2125 # Periodically flush old entries from the recentchanges table.
2126 global $wgRCMaxAge;
2127
2128 $dbw =& wfGetDB( DB_MASTER );
2129 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2130 $recentchanges = $dbw->tableName( 'recentchanges' );
2131 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2132 $dbw->query( $sql );
2133 }
2134 }
2135
2136 $id = $this->getID();
2137 $title = $this->mTitle->getPrefixedDBkey();
2138 $shortTitle = $this->mTitle->getDBkey();
2139
2140 if ( 0 == $id ) {
2141 wfProfileOut( __METHOD__ );
2142 return;
2143 }
2144
2145 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2146 array_push( $wgDeferredUpdateList, $u );
2147 $u = new SearchUpdate( $id, $title, $text );
2148 array_push( $wgDeferredUpdateList, $u );
2149
2150 # If this is another user's talk page, update newtalk
2151 # Don't do this if $changed = false otherwise some idiot can null-edit a
2152 # load of user talk pages and piss people off
2153 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed ) {
2154 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2155 $other = User::newFromName( $shortTitle );
2156 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2157 // An anonymous user
2158 $other = new User();
2159 $other->setName( $shortTitle );
2160 }
2161 if( $other ) {
2162 $other->setNewtalk( true );
2163 }
2164 }
2165 }
2166
2167 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2168 $wgMessageCache->replace( $shortTitle, $text );
2169 }
2170
2171 wfProfileOut( __METHOD__ );
2172 }
2173
2174 /**
2175 * Generate the navigation links when browsing through an article revisions
2176 * It shows the information as:
2177 * Revision as of \<date\>; view current revision
2178 * \<- Previous version | Next Version -\>
2179 *
2180 * @private
2181 * @param string $oldid Revision ID of this article revision
2182 */
2183 function setOldSubtitle( $oldid=0 ) {
2184 global $wgLang, $wgOut, $wgUser;
2185
2186 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2187 return;
2188 }
2189
2190 $revision = Revision::newFromId( $oldid );
2191
2192 $current = ( $oldid == $this->mLatest );
2193 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2194 $sk = $wgUser->getSkin();
2195 $lnk = $current
2196 ? wfMsg( 'currentrevisionlink' )
2197 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2198 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2199 $prevlink = $prev
2200 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2201 : wfMsg( 'previousrevision' );
2202 $prevdiff = $prev
2203 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2204 : wfMsg( 'diff' );
2205 $nextlink = $current
2206 ? wfMsg( 'nextrevision' )
2207 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2208 $nextdiff = $current
2209 ? wfMsg( 'diff' )
2210 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2211
2212 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2213 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2214
2215 $r = wfMsg( 'old-revision-navigation', $td, $lnk, $prevlink, $nextlink, $userlinks, $prevdiff, $nextdiff );
2216 $wgOut->setSubtitle( $r );
2217 }
2218
2219 /**
2220 * This function is called right before saving the wikitext,
2221 * so we can do things like signatures and links-in-context.
2222 *
2223 * @param string $text
2224 */
2225 function preSaveTransform( $text ) {
2226 global $wgParser, $wgUser;
2227 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2228 }
2229
2230 /* Caching functions */
2231
2232 /**
2233 * checkLastModified returns true if it has taken care of all
2234 * output to the client that is necessary for this request.
2235 * (that is, it has sent a cached version of the page)
2236 */
2237 function tryFileCache() {
2238 static $called = false;
2239 if( $called ) {
2240 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2241 return;
2242 }
2243 $called = true;
2244 if($this->isFileCacheable()) {
2245 $touched = $this->mTouched;
2246 $cache = new CacheManager( $this->mTitle );
2247 if($cache->isFileCacheGood( $touched )) {
2248 wfDebug( "Article::tryFileCache(): about to load file\n" );
2249 $cache->loadFromFileCache();
2250 return true;
2251 } else {
2252 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2253 ob_start( array(&$cache, 'saveToFileCache' ) );
2254 }
2255 } else {
2256 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2257 }
2258 }
2259
2260 /**
2261 * Check if the page can be cached
2262 * @return bool
2263 */
2264 function isFileCacheable() {
2265 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2266 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2267
2268 return $wgUseFileCache
2269 and (!$wgShowIPinHeader)
2270 and ($this->getID() != 0)
2271 and ($wgUser->isAnon())
2272 and (!$wgUser->getNewtalk())
2273 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2274 and (empty( $action ) || $action == 'view')
2275 and (!isset($oldid))
2276 and (!isset($diff))
2277 and (!isset($redirect))
2278 and (!isset($printable))
2279 and (!$this->mRedirectedFrom);
2280 }
2281
2282 /**
2283 * Loads page_touched and returns a value indicating if it should be used
2284 *
2285 */
2286 function checkTouched() {
2287 if( !$this->mDataLoaded ) {
2288 $this->loadPageData();
2289 }
2290 return !$this->mIsRedirect;
2291 }
2292
2293 /**
2294 * Get the page_touched field
2295 */
2296 function getTouched() {
2297 # Ensure that page data has been loaded
2298 if( !$this->mDataLoaded ) {
2299 $this->loadPageData();
2300 }
2301 return $this->mTouched;
2302 }
2303
2304 /**
2305 * Get the page_latest field
2306 */
2307 function getLatest() {
2308 if ( !$this->mDataLoaded ) {
2309 $this->loadPageData();
2310 }
2311 return $this->mLatest;
2312 }
2313
2314 /**
2315 * Edit an article without doing all that other stuff
2316 * The article must already exist; link tables etc
2317 * are not updated, caches are not flushed.
2318 *
2319 * @param string $text text submitted
2320 * @param string $comment comment submitted
2321 * @param bool $minor whereas it's a minor modification
2322 */
2323 function quickEdit( $text, $comment = '', $minor = 0 ) {
2324 wfProfileIn( __METHOD__ );
2325
2326 $dbw =& wfGetDB( DB_MASTER );
2327 $dbw->begin();
2328 $revision = new Revision( array(
2329 'page' => $this->getId(),
2330 'text' => $text,
2331 'comment' => $comment,
2332 'minor_edit' => $minor ? 1 : 0,
2333 ) );
2334 # fixme : $revisionId never used
2335 $revisionId = $revision->insertOn( $dbw );
2336 $this->updateRevisionOn( $dbw, $revision );
2337 $dbw->commit();
2338
2339 wfProfileOut( __METHOD__ );
2340 }
2341
2342 /**
2343 * Used to increment the view counter
2344 *
2345 * @static
2346 * @param integer $id article id
2347 */
2348 function incViewCount( $id ) {
2349 $id = intval( $id );
2350 global $wgHitcounterUpdateFreq, $wgDBtype;
2351
2352 $dbw =& wfGetDB( DB_MASTER );
2353 $pageTable = $dbw->tableName( 'page' );
2354 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2355 $acchitsTable = $dbw->tableName( 'acchits' );
2356
2357 if( $wgHitcounterUpdateFreq <= 1 ){ //
2358 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2359 return;
2360 }
2361
2362 # Not important enough to warrant an error page in case of failure
2363 $oldignore = $dbw->ignoreErrors( true );
2364
2365 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2366
2367 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2368 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2369 # Most of the time (or on SQL errors), skip row count check
2370 $dbw->ignoreErrors( $oldignore );
2371 return;
2372 }
2373
2374 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2375 $row = $dbw->fetchObject( $res );
2376 $rown = intval( $row->n );
2377 if( $rown >= $wgHitcounterUpdateFreq ){
2378 wfProfileIn( 'Article::incViewCount-collect' );
2379 $old_user_abort = ignore_user_abort( true );
2380
2381 if ($wgDBtype == 'mysql')
2382 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2383 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2384 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2385 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2386 'GROUP BY hc_id');
2387 $dbw->query("DELETE FROM $hitcounterTable");
2388 if ($wgDBtype == 'mysql')
2389 $dbw->query('UNLOCK TABLES');
2390 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2391 'WHERE page_id = hc_id');
2392 $dbw->query("DROP TABLE $acchitsTable");
2393
2394 ignore_user_abort( $old_user_abort );
2395 wfProfileOut( 'Article::incViewCount-collect' );
2396 }
2397 $dbw->ignoreErrors( $oldignore );
2398 }
2399
2400 /**#@+
2401 * The onArticle*() functions are supposed to be a kind of hooks
2402 * which should be called whenever any of the specified actions
2403 * are done.
2404 *
2405 * This is a good place to put code to clear caches, for instance.
2406 *
2407 * This is called on page move and undelete, as well as edit
2408 * @static
2409 * @param $title_obj a title object
2410 */
2411
2412 static function onArticleCreate($title) {
2413 # The talk page isn't in the regular link tables, so we need to update manually:
2414 if ( $title->isTalkPage() ) {
2415 $other = $title->getSubjectPage();
2416 } else {
2417 $other = $title->getTalkPage();
2418 }
2419 $other->invalidateCache();
2420 $other->purgeSquid();
2421
2422 $title->touchLinks();
2423 $title->purgeSquid();
2424 }
2425
2426 static function onArticleDelete( $title ) {
2427 global $wgUseFileCache, $wgMessageCache;
2428
2429 $title->touchLinks();
2430 $title->purgeSquid();
2431
2432 # File cache
2433 if ( $wgUseFileCache ) {
2434 $cm = new CacheManager( $title );
2435 @unlink( $cm->fileCacheName() );
2436 }
2437
2438 if( $title->getNamespace() == NS_MEDIAWIKI) {
2439 $wgMessageCache->replace( $title->getDBkey(), false );
2440 }
2441 }
2442
2443 /**
2444 * Purge caches on page update etc
2445 */
2446 static function onArticleEdit( $title ) {
2447 global $wgDeferredUpdateList, $wgUseFileCache;
2448
2449 $urls = array();
2450
2451 // Invalidate caches of articles which include this page
2452 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2453 $wgDeferredUpdateList[] = $update;
2454
2455 # Purge squid for this page only
2456 $title->purgeSquid();
2457
2458 # Clear file cache
2459 if ( $wgUseFileCache ) {
2460 $cm = new CacheManager( $title );
2461 @unlink( $cm->fileCacheName() );
2462 }
2463 }
2464
2465 /**#@-*/
2466
2467 /**
2468 * Info about this page
2469 * Called for ?action=info when $wgAllowPageInfo is on.
2470 *
2471 * @public
2472 */
2473 function info() {
2474 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2475
2476 if ( !$wgAllowPageInfo ) {
2477 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2478 return;
2479 }
2480
2481 $page = $this->mTitle->getSubjectPage();
2482
2483 $wgOut->setPagetitle( $page->getPrefixedText() );
2484 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2485
2486 # first, see if the page exists at all.
2487 $exists = $page->getArticleId() != 0;
2488 if( !$exists ) {
2489 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2490 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2491 } else {
2492 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2493 }
2494 } else {
2495 $dbr =& wfGetDB( DB_SLAVE );
2496 $wl_clause = array(
2497 'wl_title' => $page->getDBkey(),
2498 'wl_namespace' => $page->getNamespace() );
2499 $numwatchers = $dbr->selectField(
2500 'watchlist',
2501 'COUNT(*)',
2502 $wl_clause,
2503 __METHOD__,
2504 $this->getSelectOptions() );
2505
2506 $pageInfo = $this->pageCountInfo( $page );
2507 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2508
2509 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2510 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2511 if( $talkInfo ) {
2512 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2513 }
2514 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2515 if( $talkInfo ) {
2516 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2517 }
2518 $wgOut->addHTML( '</ul>' );
2519
2520 }
2521 }
2522
2523 /**
2524 * Return the total number of edits and number of unique editors
2525 * on a given page. If page does not exist, returns false.
2526 *
2527 * @param Title $title
2528 * @return array
2529 * @private
2530 */
2531 function pageCountInfo( $title ) {
2532 $id = $title->getArticleId();
2533 if( $id == 0 ) {
2534 return false;
2535 }
2536
2537 $dbr =& wfGetDB( DB_SLAVE );
2538
2539 $rev_clause = array( 'rev_page' => $id );
2540
2541 $edits = $dbr->selectField(
2542 'revision',
2543 'COUNT(rev_page)',
2544 $rev_clause,
2545 __METHOD__,
2546 $this->getSelectOptions() );
2547
2548 $authors = $dbr->selectField(
2549 'revision',
2550 'COUNT(DISTINCT rev_user_text)',
2551 $rev_clause,
2552 __METHOD__,
2553 $this->getSelectOptions() );
2554
2555 return array( 'edits' => $edits, 'authors' => $authors );
2556 }
2557
2558 /**
2559 * Return a list of templates used by this article.
2560 * Uses the templatelinks table
2561 *
2562 * @return array Array of Title objects
2563 */
2564 function getUsedTemplates() {
2565 $result = array();
2566 $id = $this->mTitle->getArticleID();
2567 if( $id == 0 ) {
2568 return array();
2569 }
2570
2571 $dbr =& wfGetDB( DB_SLAVE );
2572 $res = $dbr->select( array( 'templatelinks' ),
2573 array( 'tl_namespace', 'tl_title' ),
2574 array( 'tl_from' => $id ),
2575 'Article:getUsedTemplates' );
2576 if ( false !== $res ) {
2577 if ( $dbr->numRows( $res ) ) {
2578 while ( $row = $dbr->fetchObject( $res ) ) {
2579 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2580 }
2581 }
2582 }
2583 $dbr->freeResult( $res );
2584 return $result;
2585 }
2586 }
2587
2588 ?>