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