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