* (bug 10422) Change <pre> on CSS/JS pages to <div> and allow wikitext
[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 // Add classes, give directionality. Do parse it as wikitext
788 // (bug 10422).
789 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
790 $wgOut->addHtml( "<div class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
791 $wgOut->addWikiText( $this->mContent );
792 $wgOut->addHtml( "\n</div>\n" );
793 }
794
795 elseif ( $rt = Title::newFromRedirect( $text ) ) {
796 # Display redirect
797 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
798 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
799 # Don't overwrite the subtitle if this was an old revision
800 if( !$wasRedirected && $this->isCurrent() ) {
801 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
802 }
803 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
804
805 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
806 '<span class="redirectText">'.$link.'</span>' );
807
808 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
809 $wgOut->addParserOutputNoText( $parseout );
810 } else if ( $pcache ) {
811 # Display content and save to parser cache
812 $this->outputWikiText( $text );
813 } else {
814 # Display content, don't attempt to save to parser cache
815 # Don't show section-edit links on old revisions... this way lies madness.
816 if( !$this->isCurrent() ) {
817 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
818 }
819 # Display content and don't save to parser cache
820 # With timing hack -- TS 2006-07-26
821 $time = -wfTime();
822 $this->outputWikiText( $text, false );
823 $time += wfTime();
824
825 # Timing hack
826 if ( $time > 3 ) {
827 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
828 $this->mTitle->getPrefixedDBkey()));
829 }
830
831 if( !$this->isCurrent() ) {
832 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
833 }
834
835 }
836 }
837 /* title may have been set from the cache */
838 $t = $wgOut->getPageTitle();
839 if( empty( $t ) ) {
840 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
841 }
842
843 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
844 if( $ns == NS_USER_TALK &&
845 User::isIP( $this->mTitle->getText() ) ) {
846 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
847 }
848
849 # If we have been passed an &rcid= parameter, we want to give the user a
850 # chance to mark this new article as patrolled.
851 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
852 $wgOut->addHTML(
853 "<div class='patrollink'>" .
854 wfMsgHtml( 'markaspatrolledlink',
855 $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
856 "action=markpatrolled&rcid=$rcid" )
857 ) .
858 '</div>'
859 );
860 }
861
862 # Trackbacks
863 if ($wgUseTrackbacks)
864 $this->addTrackbacks();
865
866 $this->viewUpdates();
867 wfProfileOut( __METHOD__ );
868 }
869
870 function addTrackbacks() {
871 global $wgOut, $wgUser;
872
873 $dbr = wfGetDB(DB_SLAVE);
874 $tbs = $dbr->select(
875 /* FROM */ 'trackbacks',
876 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
877 /* WHERE */ array('tb_page' => $this->getID())
878 );
879
880 if (!$dbr->numrows($tbs))
881 return;
882
883 $tbtext = "";
884 while ($o = $dbr->fetchObject($tbs)) {
885 $rmvtxt = "";
886 if ($wgUser->isAllowed( 'trackback' )) {
887 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
888 . $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
889 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
890 }
891 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
892 $o->tb_title,
893 $o->tb_url,
894 $o->tb_ex,
895 $o->tb_name,
896 $rmvtxt);
897 }
898 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
899 }
900
901 function deletetrackback() {
902 global $wgUser, $wgRequest, $wgOut, $wgTitle;
903
904 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
905 $wgOut->addWikitext(wfMsg('sessionfailure'));
906 return;
907 }
908
909 if ((!$wgUser->isAllowed('delete'))) {
910 $wgOut->permissionRequired( 'delete' );
911 return;
912 }
913
914 if (wfReadOnly()) {
915 $wgOut->readOnlyPage();
916 return;
917 }
918
919 $db = wfGetDB(DB_MASTER);
920 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
921 $wgTitle->invalidateCache();
922 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
923 }
924
925 function render() {
926 global $wgOut;
927
928 $wgOut->setArticleBodyOnly(true);
929 $this->view();
930 }
931
932 /**
933 * Handle action=purge
934 */
935 function purge() {
936 global $wgUser, $wgRequest, $wgOut;
937
938 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
939 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
940 $this->doPurge();
941 }
942 } else {
943 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
944 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
945 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
946 $msg = str_replace( '$1',
947 "<form method=\"post\" action=\"$action\">\n" .
948 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
949 "</form>\n", $msg );
950
951 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
952 $wgOut->setRobotpolicy( 'noindex,nofollow' );
953 $wgOut->addHTML( $msg );
954 }
955 }
956
957 /**
958 * Perform the actions of a page purging
959 */
960 function doPurge() {
961 global $wgUseSquid;
962 // Invalidate the cache
963 $this->mTitle->invalidateCache();
964
965 if ( $wgUseSquid ) {
966 // Commit the transaction before the purge is sent
967 $dbw = wfGetDB( DB_MASTER );
968 $dbw->immediateCommit();
969
970 // Send purge
971 $update = SquidUpdate::newSimplePurge( $this->mTitle );
972 $update->doUpdate();
973 }
974 $this->view();
975 }
976
977 /**
978 * Insert a new empty page record for this article.
979 * This *must* be followed up by creating a revision
980 * and running $this->updateToLatest( $rev_id );
981 * or else the record will be left in a funky state.
982 * Best if all done inside a transaction.
983 *
984 * @param Database $dbw
985 * @return int The newly created page_id key
986 * @private
987 */
988 function insertOn( $dbw ) {
989 wfProfileIn( __METHOD__ );
990
991 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
992 $dbw->insert( 'page', array(
993 'page_id' => $page_id,
994 'page_namespace' => $this->mTitle->getNamespace(),
995 'page_title' => $this->mTitle->getDBkey(),
996 'page_counter' => 0,
997 'page_restrictions' => '',
998 'page_is_redirect' => 0, # Will set this shortly...
999 'page_is_new' => 1,
1000 'page_random' => wfRandom(),
1001 'page_touched' => $dbw->timestamp(),
1002 'page_latest' => 0, # Fill this in shortly...
1003 'page_len' => 0, # Fill this in shortly...
1004 ), __METHOD__ );
1005 $newid = $dbw->insertId();
1006
1007 $this->mTitle->resetArticleId( $newid );
1008
1009 wfProfileOut( __METHOD__ );
1010 return $newid;
1011 }
1012
1013 /**
1014 * Update the page record to point to a newly saved revision.
1015 *
1016 * @param Database $dbw
1017 * @param Revision $revision For ID number, and text used to set
1018 length and redirect status fields
1019 * @param int $lastRevision If given, will not overwrite the page field
1020 * when different from the currently set value.
1021 * Giving 0 indicates the new page flag should
1022 * be set on.
1023 * @param bool $lastRevIsRedirect If given, will optimize adding and
1024 * removing rows in redirect table.
1025 * @return bool true on success, false on failure
1026 * @private
1027 */
1028 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1029 wfProfileIn( __METHOD__ );
1030
1031 $text = $revision->getText();
1032 $rt = Title::newFromRedirect( $text );
1033
1034 $conditions = array( 'page_id' => $this->getId() );
1035 if( !is_null( $lastRevision ) ) {
1036 # An extra check against threads stepping on each other
1037 $conditions['page_latest'] = $lastRevision;
1038 }
1039
1040 $dbw->update( 'page',
1041 array( /* SET */
1042 'page_latest' => $revision->getId(),
1043 'page_touched' => $dbw->timestamp(),
1044 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1045 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1046 'page_len' => strlen( $text ),
1047 ),
1048 $conditions,
1049 __METHOD__ );
1050
1051 $result = $dbw->affectedRows() != 0;
1052
1053 if ($result) {
1054 // FIXME: Should the result from updateRedirectOn() be returned instead?
1055 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1056 }
1057
1058 wfProfileOut( __METHOD__ );
1059 return $result;
1060 }
1061
1062 /**
1063 * Add row to the redirect table if this is a redirect, remove otherwise.
1064 *
1065 * @param Database $dbw
1066 * @param $redirectTitle a title object pointing to the redirect target,
1067 * or NULL if this is not a redirect
1068 * @param bool $lastRevIsRedirect If given, will optimize adding and
1069 * removing rows in redirect table.
1070 * @return bool true on success, false on failure
1071 * @private
1072 */
1073 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1074
1075 // Always update redirects (target link might have changed)
1076 // Update/Insert if we don't know if the last revision was a redirect or not
1077 // Delete if changing from redirect to non-redirect
1078 $isRedirect = !is_null($redirectTitle);
1079 if ($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1080
1081 wfProfileIn( __METHOD__ );
1082
1083 if ($isRedirect) {
1084
1085 // This title is a redirect, Add/Update row in the redirect table
1086 $set = array( /* SET */
1087 'rd_namespace' => $redirectTitle->getNamespace(),
1088 'rd_title' => $redirectTitle->getDBkey(),
1089 'rd_from' => $this->getId(),
1090 );
1091
1092 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1093 } else {
1094 // This is not a redirect, remove row from redirect table
1095 $where = array( 'rd_from' => $this->getId() );
1096 $dbw->delete( 'redirect', $where, __METHOD__);
1097 }
1098
1099 wfProfileOut( __METHOD__ );
1100 return ( $dbw->affectedRows() != 0 );
1101 }
1102
1103 return true;
1104 }
1105
1106 /**
1107 * If the given revision is newer than the currently set page_latest,
1108 * update the page record. Otherwise, do nothing.
1109 *
1110 * @param Database $dbw
1111 * @param Revision $revision
1112 */
1113 function updateIfNewerOn( &$dbw, $revision ) {
1114 wfProfileIn( __METHOD__ );
1115
1116 $row = $dbw->selectRow(
1117 array( 'revision', 'page' ),
1118 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1119 array(
1120 'page_id' => $this->getId(),
1121 'page_latest=rev_id' ),
1122 __METHOD__ );
1123 if( $row ) {
1124 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1125 wfProfileOut( __METHOD__ );
1126 return false;
1127 }
1128 $prev = $row->rev_id;
1129 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1130 } else {
1131 # No or missing previous revision; mark the page as new
1132 $prev = 0;
1133 $lastRevIsRedirect = null;
1134 }
1135
1136 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1137 wfProfileOut( __METHOD__ );
1138 return $ret;
1139 }
1140
1141 /**
1142 * @return string Complete article text, or null if error
1143 */
1144 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1145 wfProfileIn( __METHOD__ );
1146
1147 if( $section == '' ) {
1148 // Whole-page edit; let the text through unmolested.
1149 } else {
1150 if( is_null( $edittime ) ) {
1151 $rev = Revision::newFromTitle( $this->mTitle );
1152 } else {
1153 $dbw = wfGetDB( DB_MASTER );
1154 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1155 }
1156 if( is_null( $rev ) ) {
1157 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1158 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1159 return null;
1160 }
1161 $oldtext = $rev->getText();
1162
1163 if( $section == 'new' ) {
1164 # Inserting a new section
1165 $subject = $summary ? "== {$summary} ==\n\n" : '';
1166 $text = strlen( trim( $oldtext ) ) > 0
1167 ? "{$oldtext}\n\n{$subject}{$text}"
1168 : "{$subject}{$text}";
1169 } else {
1170 # Replacing an existing section; roll out the big guns
1171 global $wgParser;
1172 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1173 }
1174
1175 }
1176
1177 wfProfileOut( __METHOD__ );
1178 return $text;
1179 }
1180
1181 /**
1182 * @deprecated use Article::doEdit()
1183 */
1184 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1185 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1186 ( $isminor ? EDIT_MINOR : 0 ) |
1187 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 );
1188
1189 # If this is a comment, add the summary as headline
1190 if ( $comment && $summary != "" ) {
1191 $text = "== {$summary} ==\n\n".$text;
1192 }
1193
1194 $this->doEdit( $text, $summary, $flags );
1195
1196 $dbw = wfGetDB( DB_MASTER );
1197 if ($watchthis) {
1198 if (!$this->mTitle->userIsWatching()) {
1199 $dbw->begin();
1200 $this->doWatch();
1201 $dbw->commit();
1202 }
1203 } else {
1204 if ( $this->mTitle->userIsWatching() ) {
1205 $dbw->begin();
1206 $this->doUnwatch();
1207 $dbw->commit();
1208 }
1209 }
1210 $this->doRedirect( $this->isRedirect( $text ) );
1211 }
1212
1213 /**
1214 * @deprecated use Article::doEdit()
1215 */
1216 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1217 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1218 ( $minor ? EDIT_MINOR : 0 ) |
1219 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1220
1221 $good = $this->doEdit( $text, $summary, $flags );
1222 if ( $good ) {
1223 $dbw = wfGetDB( DB_MASTER );
1224 if ($watchthis) {
1225 if (!$this->mTitle->userIsWatching()) {
1226 $dbw->begin();
1227 $this->doWatch();
1228 $dbw->commit();
1229 }
1230 } else {
1231 if ( $this->mTitle->userIsWatching() ) {
1232 $dbw->begin();
1233 $this->doUnwatch();
1234 $dbw->commit();
1235 }
1236 }
1237
1238 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1239 }
1240 return $good;
1241 }
1242
1243 /**
1244 * Article::doEdit()
1245 *
1246 * Change an existing article or create a new article. Updates RC and all necessary caches,
1247 * optionally via the deferred update array.
1248 *
1249 * $wgUser must be set before calling this function.
1250 *
1251 * @param string $text New text
1252 * @param string $summary Edit summary
1253 * @param integer $flags bitfield:
1254 * EDIT_NEW
1255 * Article is known or assumed to be non-existent, create a new one
1256 * EDIT_UPDATE
1257 * Article is known or assumed to be pre-existing, update it
1258 * EDIT_MINOR
1259 * Mark this edit minor, if the user is allowed to do so
1260 * EDIT_SUPPRESS_RC
1261 * Do not log the change in recentchanges
1262 * EDIT_FORCE_BOT
1263 * Mark the edit a "bot" edit regardless of user rights
1264 * EDIT_DEFER_UPDATES
1265 * Defer some of the updates until the end of index.php
1266 * EDIT_AUTOSUMMARY
1267 * Fill in blank summaries with generated text where possible
1268 *
1269 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1270 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1271 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1272 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1273 * to MediaWiki's performance-optimised locking strategy.
1274 *
1275 * @return bool success
1276 */
1277 function doEdit( $text, $summary, $flags = 0 ) {
1278 global $wgUser, $wgDBtransactions;
1279
1280 wfProfileIn( __METHOD__ );
1281 $good = true;
1282
1283 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1284 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1285 if ( $aid ) {
1286 $flags |= EDIT_UPDATE;
1287 } else {
1288 $flags |= EDIT_NEW;
1289 }
1290 }
1291
1292 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1293 &$summary, $flags & EDIT_MINOR,
1294 null, null, &$flags ) ) )
1295 {
1296 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1297 wfProfileOut( __METHOD__ );
1298 return false;
1299 }
1300
1301 # Silently ignore EDIT_MINOR if not allowed
1302 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1303 $bot = $wgUser->isAllowed( 'bot' ) || ( $flags & EDIT_FORCE_BOT );
1304
1305 $oldtext = $this->getContent();
1306 $oldsize = strlen( $oldtext );
1307
1308 # Provide autosummaries if one is not provided.
1309 if ($flags & EDIT_AUTOSUMMARY && $summary == '')
1310 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1311
1312 $text = $this->preSaveTransform( $text );
1313 $newsize = strlen( $text );
1314
1315 $dbw = wfGetDB( DB_MASTER );
1316 $now = wfTimestampNow();
1317
1318 if ( $flags & EDIT_UPDATE ) {
1319 # Update article, but only if changed.
1320
1321 # Make sure the revision is either completely inserted or not inserted at all
1322 if( !$wgDBtransactions ) {
1323 $userAbort = ignore_user_abort( true );
1324 }
1325
1326 $lastRevision = 0;
1327 $revisionId = 0;
1328
1329 if ( 0 != strcmp( $text, $oldtext ) ) {
1330 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1331 - (int)$this->isCountable( $oldtext );
1332 $this->mTotalAdjustment = 0;
1333
1334 $lastRevision = $dbw->selectField(
1335 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1336
1337 if ( !$lastRevision ) {
1338 # Article gone missing
1339 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1340 wfProfileOut( __METHOD__ );
1341 return false;
1342 }
1343
1344 $revision = new Revision( array(
1345 'page' => $this->getId(),
1346 'comment' => $summary,
1347 'minor_edit' => $isminor,
1348 'text' => $text
1349 ) );
1350
1351 $dbw->begin();
1352 $revisionId = $revision->insertOn( $dbw );
1353
1354 # Update page
1355 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1356
1357 if( !$ok ) {
1358 /* Belated edit conflict! Run away!! */
1359 $good = false;
1360 $dbw->rollback();
1361 } else {
1362 # Update recentchanges
1363 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1364 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1365 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1366 $revisionId );
1367
1368 # Mark as patrolled if the user can do so
1369 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1370 RecentChange::markPatrolled( $rcid );
1371 PatrolLog::record( $rcid, true );
1372 }
1373 }
1374 $wgUser->incEditCount();
1375 $dbw->commit();
1376 }
1377 } else {
1378 // Keep the same revision ID, but do some updates on it
1379 $revisionId = $this->getRevIdFetched();
1380 // Update page_touched, this is usually implicit in the page update
1381 // Other cache updates are done in onArticleEdit()
1382 $this->mTitle->invalidateCache();
1383 }
1384
1385 if( !$wgDBtransactions ) {
1386 ignore_user_abort( $userAbort );
1387 }
1388
1389 if ( $good ) {
1390 # Invalidate cache of this article and all pages using this article
1391 # as a template. Partly deferred.
1392 Article::onArticleEdit( $this->mTitle );
1393
1394 # Update links tables, site stats, etc.
1395 $changed = ( strcmp( $oldtext, $text ) != 0 );
1396 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1397 }
1398 } else {
1399 # Create new article
1400
1401 # Set statistics members
1402 # We work out if it's countable after PST to avoid counter drift
1403 # when articles are created with {{subst:}}
1404 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1405 $this->mTotalAdjustment = 1;
1406
1407 $dbw->begin();
1408
1409 # Add the page record; stake our claim on this title!
1410 # This will fail with a database query exception if the article already exists
1411 $newid = $this->insertOn( $dbw );
1412
1413 # Save the revision text...
1414 $revision = new Revision( array(
1415 'page' => $newid,
1416 'comment' => $summary,
1417 'minor_edit' => $isminor,
1418 'text' => $text
1419 ) );
1420 $revisionId = $revision->insertOn( $dbw );
1421
1422 $this->mTitle->resetArticleID( $newid );
1423
1424 # Update the page record with revision data
1425 $this->updateRevisionOn( $dbw, $revision, 0 );
1426
1427 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1428 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1429 '', strlen( $text ), $revisionId );
1430 # Mark as patrolled if the user can
1431 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1432 RecentChange::markPatrolled( $rcid );
1433 PatrolLog::record( $rcid, true );
1434 }
1435 }
1436 $wgUser->incEditCount();
1437 $dbw->commit();
1438
1439 # Update links, etc.
1440 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1441
1442 # Clear caches
1443 Article::onArticleCreate( $this->mTitle );
1444
1445 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1446 $summary, $flags & EDIT_MINOR,
1447 null, null, &$flags ) );
1448 }
1449
1450 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1451 wfDoUpdates();
1452 }
1453
1454 wfRunHooks( 'ArticleSaveComplete',
1455 array( &$this, &$wgUser, $text,
1456 $summary, $flags & EDIT_MINOR,
1457 null, null, &$flags ) );
1458
1459 wfProfileOut( __METHOD__ );
1460 return $good;
1461 }
1462
1463 /**
1464 * @deprecated wrapper for doRedirect
1465 */
1466 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1467 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1468 }
1469
1470 /**
1471 * Output a redirect back to the article.
1472 * This is typically used after an edit.
1473 *
1474 * @param boolean $noRedir Add redirect=no
1475 * @param string $sectionAnchor section to redirect to, including "#"
1476 */
1477 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1478 global $wgOut;
1479 if ( $noRedir ) {
1480 $query = 'redirect=no';
1481 } else {
1482 $query = '';
1483 }
1484 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1485 }
1486
1487 /**
1488 * Mark this particular edit as patrolled
1489 */
1490 function markpatrolled() {
1491 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1492 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1493
1494 # Check RC patrol config. option
1495 if( !$wgUseRCPatrol ) {
1496 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1497 return;
1498 }
1499
1500 # Check permissions
1501 if( !$wgUser->isAllowed( 'patrol' ) ) {
1502 $wgOut->permissionRequired( 'patrol' );
1503 return;
1504 }
1505
1506 # If we haven't been given an rc_id value, we can't do anything
1507 $rcid = $wgRequest->getVal( 'rcid' );
1508 if( !$rcid ) {
1509 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1510 return;
1511 }
1512
1513 # Handle the 'MarkPatrolled' hook
1514 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1515 return;
1516 }
1517
1518 $return = SpecialPage::getTitleFor( 'Recentchanges' );
1519 # If it's left up to us, check that the user is allowed to patrol this edit
1520 # If the user has the "autopatrol" right, then we'll assume there are no
1521 # other conditions stopping them doing so
1522 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1523 $rc = RecentChange::newFromId( $rcid );
1524 # Graceful error handling, as we've done before here...
1525 # (If the recent change doesn't exist, then it doesn't matter whether
1526 # the user is allowed to patrol it or not; nothing is going to happen
1527 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1528 # The user made this edit, and can't patrol it
1529 # Tell them so, and then back off
1530 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1531 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1532 $wgOut->returnToMain( false, $return );
1533 return;
1534 }
1535 }
1536
1537 # Mark the edit as patrolled
1538 RecentChange::markPatrolled( $rcid );
1539 PatrolLog::record( $rcid );
1540 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1541
1542 # Inform the user
1543 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1544 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1545 $wgOut->returnToMain( false, $return );
1546 }
1547
1548 /**
1549 * User-interface handler for the "watch" action
1550 */
1551
1552 function watch() {
1553
1554 global $wgUser, $wgOut;
1555
1556 if ( $wgUser->isAnon() ) {
1557 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1558 return;
1559 }
1560 if ( wfReadOnly() ) {
1561 $wgOut->readOnlyPage();
1562 return;
1563 }
1564
1565 if( $this->doWatch() ) {
1566 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1567 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1568
1569 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1570 $text = wfMsg( 'addedwatchtext', $link );
1571 $wgOut->addWikiText( $text );
1572 }
1573
1574 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1575 }
1576
1577 /**
1578 * Add this page to $wgUser's watchlist
1579 * @return bool true on successful watch operation
1580 */
1581 function doWatch() {
1582 global $wgUser;
1583 if( $wgUser->isAnon() ) {
1584 return false;
1585 }
1586
1587 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1588 $wgUser->addWatch( $this->mTitle );
1589
1590 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1591 }
1592
1593 return false;
1594 }
1595
1596 /**
1597 * User interface handler for the "unwatch" action.
1598 */
1599 function unwatch() {
1600
1601 global $wgUser, $wgOut;
1602
1603 if ( $wgUser->isAnon() ) {
1604 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1605 return;
1606 }
1607 if ( wfReadOnly() ) {
1608 $wgOut->readOnlyPage();
1609 return;
1610 }
1611
1612 if( $this->doUnwatch() ) {
1613 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1614 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1615
1616 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1617 $text = wfMsg( 'removedwatchtext', $link );
1618 $wgOut->addWikiText( $text );
1619 }
1620
1621 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1622 }
1623
1624 /**
1625 * Stop watching a page
1626 * @return bool true on successful unwatch
1627 */
1628 function doUnwatch() {
1629 global $wgUser;
1630 if( $wgUser->isAnon() ) {
1631 return false;
1632 }
1633
1634 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1635 $wgUser->removeWatch( $this->mTitle );
1636
1637 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1638 }
1639
1640 return false;
1641 }
1642
1643 /**
1644 * action=protect handler
1645 */
1646 function protect() {
1647 $form = new ProtectionForm( $this );
1648 $form->execute();
1649 }
1650
1651 /**
1652 * action=unprotect handler (alias)
1653 */
1654 function unprotect() {
1655 $this->protect();
1656 }
1657
1658 /**
1659 * Update the article's restriction field, and leave a log entry.
1660 *
1661 * @param array $limit set of restriction keys
1662 * @param string $reason
1663 * @return bool true on success
1664 */
1665 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1666 global $wgUser, $wgRestrictionTypes, $wgContLang;
1667
1668 $id = $this->mTitle->getArticleID();
1669 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1670 return false;
1671 }
1672
1673 if (!$cascade) {
1674 $cascade = false;
1675 }
1676
1677 // Take this opportunity to purge out expired restrictions
1678 Title::purgeExpiredRestrictions();
1679
1680 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1681 # we expect a single selection, but the schema allows otherwise.
1682 $current = array();
1683 foreach( $wgRestrictionTypes as $action )
1684 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1685
1686 $current = Article::flattenRestrictions( $current );
1687 $updated = Article::flattenRestrictions( $limit );
1688
1689 $changed = ( $current != $updated );
1690 $changed = $changed || ($this->mTitle->areRestrictionsCascading() != $cascade);
1691 $changed = $changed || ($this->mTitle->mRestrictionsExpiry != $expiry);
1692 $protect = ( $updated != '' );
1693
1694 # If nothing's changed, do nothing
1695 if( $changed ) {
1696 global $wgGroupPermissions;
1697 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1698
1699 $dbw = wfGetDB( DB_MASTER );
1700
1701 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1702
1703 $expiry_description = '';
1704 if ( $encodedExpiry != 'infinity' ) {
1705 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1706 }
1707
1708 # Prepare a null revision to be added to the history
1709 $modified = $current != '' && $protect;
1710 if ( $protect ) {
1711 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1712 } else {
1713 $comment_type = 'unprotectedarticle';
1714 }
1715 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1716
1717 foreach( $limit as $action => $restrictions ) {
1718 # Check if the group level required to edit also can protect pages
1719 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1720 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1721 }
1722
1723 $cascade_description = '';
1724 if ($cascade) {
1725 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1726 }
1727
1728 if( $reason )
1729 $comment .= ": $reason";
1730 if( $protect )
1731 $comment .= " [$updated]";
1732 if ( $expiry_description && $protect )
1733 $comment .= "$expiry_description";
1734 if ( $cascade )
1735 $comment .= "$cascade_description";
1736
1737 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1738 $nullRevId = $nullRevision->insertOn( $dbw );
1739
1740 # Update restrictions table
1741 foreach( $limit as $action => $restrictions ) {
1742 if ($restrictions != '' ) {
1743 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1744 array( 'pr_page' => $id, 'pr_type' => $action
1745 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
1746 , 'pr_expiry' => $encodedExpiry ), __METHOD__ );
1747 } else {
1748 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1749 'pr_type' => $action ), __METHOD__ );
1750 }
1751 }
1752
1753 # Update page record
1754 $dbw->update( 'page',
1755 array( /* SET */
1756 'page_touched' => $dbw->timestamp(),
1757 'page_restrictions' => '',
1758 'page_latest' => $nullRevId
1759 ), array( /* WHERE */
1760 'page_id' => $id
1761 ), 'Article::protect'
1762 );
1763 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1764
1765 # Update the protection log
1766 $log = new LogPage( 'protect' );
1767
1768 if( $protect ) {
1769 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1770 } else {
1771 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1772 }
1773
1774 } # End hook
1775 } # End "changed" check
1776
1777 return true;
1778 }
1779
1780 /**
1781 * Take an array of page restrictions and flatten it to a string
1782 * suitable for insertion into the page_restrictions field.
1783 * @param array $limit
1784 * @return string
1785 * @private
1786 */
1787 function flattenRestrictions( $limit ) {
1788 if( !is_array( $limit ) ) {
1789 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1790 }
1791 $bits = array();
1792 ksort( $limit );
1793 foreach( $limit as $action => $restrictions ) {
1794 if( $restrictions != '' ) {
1795 $bits[] = "$action=$restrictions";
1796 }
1797 }
1798 return implode( ':', $bits );
1799 }
1800
1801 /*
1802 * UI entry point for page deletion
1803 */
1804 function delete() {
1805 global $wgUser, $wgOut, $wgRequest;
1806 $confirm = $wgRequest->wasPosted() &&
1807 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1808 $reason = $wgRequest->getText( 'wpReason' );
1809
1810 # This code desperately needs to be totally rewritten
1811
1812 # Check permissions
1813 if( $wgUser->isAllowed( 'delete' ) ) {
1814 if( $wgUser->isBlocked( !$confirm ) ) {
1815 $wgOut->blockedPage();
1816 return;
1817 }
1818 } else {
1819 $wgOut->permissionRequired( 'delete' );
1820 return;
1821 }
1822
1823 if( wfReadOnly() ) {
1824 $wgOut->readOnlyPage();
1825 return;
1826 }
1827
1828 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1829
1830 # Better double-check that it hasn't been deleted yet!
1831 $dbw = wfGetDB( DB_MASTER );
1832 $conds = $this->mTitle->pageCond();
1833 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1834 if ( $latest === false ) {
1835 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1836 return;
1837 }
1838
1839 if( $confirm ) {
1840 $this->doDelete( $reason );
1841 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1842 $this->doWatch();
1843 } elseif( $this->mTitle->userIsWatching() ) {
1844 $this->doUnwatch();
1845 }
1846 return;
1847 }
1848
1849 # determine whether this page has earlier revisions
1850 # and insert a warning if it does
1851 $maxRevisions = 20;
1852 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1853
1854 if( count( $authors ) > 1 && !$confirm ) {
1855 $skin=$wgUser->getSkin();
1856 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1857 }
1858
1859 # If a single user is responsible for all revisions, find out who they are
1860 if ( count( $authors ) == $maxRevisions ) {
1861 // Query bailed out, too many revisions to find out if they're all the same
1862 $authorOfAll = false;
1863 } else {
1864 $authorOfAll = reset( $authors );
1865 foreach ( $authors as $author ) {
1866 if ( $authorOfAll != $author ) {
1867 $authorOfAll = false;
1868 break;
1869 }
1870 }
1871 }
1872 # Fetch article text
1873 $rev = Revision::newFromTitle( $this->mTitle );
1874
1875 if( !is_null( $rev ) ) {
1876 # if this is a mini-text, we can paste part of it into the deletion reason
1877 $text = $rev->getText();
1878
1879 #if this is empty, an earlier revision may contain "useful" text
1880 $blanked = false;
1881 if( $text == '' ) {
1882 $prev = $rev->getPrevious();
1883 if( $prev ) {
1884 $text = $prev->getText();
1885 $blanked = true;
1886 }
1887 }
1888
1889 $length = strlen( $text );
1890
1891 # this should not happen, since it is not possible to store an empty, new
1892 # page. Let's insert a standard text in case it does, though
1893 if( $length == 0 && $reason === '' ) {
1894 $reason = wfMsgForContent( 'exblank' );
1895 }
1896
1897 if( $reason === '' ) {
1898 # comment field=255, let's grep the first 150 to have some user
1899 # space left
1900 global $wgContLang;
1901 $text = $wgContLang->truncate( $text, 150, '...' );
1902
1903 # let's strip out newlines
1904 $text = preg_replace( "/[\n\r]/", '', $text );
1905
1906 if( !$blanked ) {
1907 if( $authorOfAll === false ) {
1908 $reason = wfMsgForContent( 'excontent', $text );
1909 } else {
1910 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1911 }
1912 } else {
1913 $reason = wfMsgForContent( 'exbeforeblank', $text );
1914 }
1915 }
1916 }
1917
1918 return $this->confirmDelete( '', $reason );
1919 }
1920
1921 /**
1922 * Get the last N authors
1923 * @param int $num Number of revisions to get
1924 * @param string $revLatest The latest rev_id, selected from the master (optional)
1925 * @return array Array of authors, duplicates not removed
1926 */
1927 function getLastNAuthors( $num, $revLatest = 0 ) {
1928 wfProfileIn( __METHOD__ );
1929
1930 // First try the slave
1931 // If that doesn't have the latest revision, try the master
1932 $continue = 2;
1933 $db = wfGetDB( DB_SLAVE );
1934 do {
1935 $res = $db->select( array( 'page', 'revision' ),
1936 array( 'rev_id', 'rev_user_text' ),
1937 array(
1938 'page_namespace' => $this->mTitle->getNamespace(),
1939 'page_title' => $this->mTitle->getDBkey(),
1940 'rev_page = page_id'
1941 ), __METHOD__, $this->getSelectOptions( array(
1942 'ORDER BY' => 'rev_timestamp DESC',
1943 'LIMIT' => $num
1944 ) )
1945 );
1946 if ( !$res ) {
1947 wfProfileOut( __METHOD__ );
1948 return array();
1949 }
1950 $row = $db->fetchObject( $res );
1951 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1952 $db = wfGetDB( DB_MASTER );
1953 $continue--;
1954 } else {
1955 $continue = 0;
1956 }
1957 } while ( $continue );
1958
1959 $authors = array( $row->rev_user_text );
1960 while ( $row = $db->fetchObject( $res ) ) {
1961 $authors[] = $row->rev_user_text;
1962 }
1963 wfProfileOut( __METHOD__ );
1964 return $authors;
1965 }
1966
1967 /**
1968 * Output deletion confirmation dialog
1969 */
1970 function confirmDelete( $par, $reason ) {
1971 global $wgOut, $wgUser;
1972
1973 wfDebug( "Article::confirmDelete\n" );
1974
1975 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1976 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1977 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1978 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1979
1980 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1981
1982 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1983 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1984 $token = htmlspecialchars( $wgUser->editToken() );
1985 $watch = Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '2' ) );
1986
1987 $wgOut->addHTML( "
1988 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1989 <table border='0'>
1990 <tr>
1991 <td align='right'>
1992 <label for='wpReason'>{$delcom}:</label>
1993 </td>
1994 <td align='left'>
1995 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
1996 </td>
1997 </tr>
1998 <tr>
1999 <td>&nbsp;</td>
2000 <td>$watch</td>
2001 </tr>
2002 <tr>
2003 <td>&nbsp;</td>
2004 <td>
2005 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2006 </td>
2007 </tr>
2008 </table>
2009 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2010 </form>\n" );
2011
2012 $wgOut->returnToMain( false );
2013
2014 $this->showLogExtract( $wgOut );
2015 }
2016
2017
2018 /**
2019 * Show relevant lines from the deletion log
2020 */
2021 function showLogExtract( $out ) {
2022 $out->addHtml( '<h2>' . htmlspecialchars( LogPage::logName( 'delete' ) ) . '</h2>' );
2023 $logViewer = new LogViewer(
2024 new LogReader(
2025 new FauxRequest(
2026 array( 'page' => $this->mTitle->getPrefixedText(),
2027 'type' => 'delete' ) ) ) );
2028 $logViewer->showList( $out );
2029 }
2030
2031
2032 /**
2033 * Perform a deletion and output success or failure messages
2034 */
2035 function doDelete( $reason ) {
2036 global $wgOut, $wgUser;
2037 wfDebug( __METHOD__."\n" );
2038
2039 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2040 if ( $this->doDeleteArticle( $reason ) ) {
2041 $deleted = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2042
2043 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2044 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2045
2046 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2047 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2048
2049 $wgOut->addWikiText( $text );
2050 $wgOut->returnToMain( false );
2051 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2052 } else {
2053 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2054 }
2055 }
2056 }
2057
2058 /**
2059 * Back-end article deletion
2060 * Deletes the article with database consistency, writes logs, purges caches
2061 * Returns success
2062 */
2063 function doDeleteArticle( $reason ) {
2064 global $wgUseSquid, $wgDeferredUpdateList;
2065 global $wgUseTrackbacks;
2066
2067 wfDebug( __METHOD__."\n" );
2068
2069 $dbw = wfGetDB( DB_MASTER );
2070 $ns = $this->mTitle->getNamespace();
2071 $t = $this->mTitle->getDBkey();
2072 $id = $this->mTitle->getArticleID();
2073
2074 if ( $t == '' || $id == 0 ) {
2075 return false;
2076 }
2077
2078 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2079 array_push( $wgDeferredUpdateList, $u );
2080
2081 // For now, shunt the revision data into the archive table.
2082 // Text is *not* removed from the text table; bulk storage
2083 // is left intact to avoid breaking block-compression or
2084 // immutable storage schemes.
2085 //
2086 // For backwards compatibility, note that some older archive
2087 // table entries will have ar_text and ar_flags fields still.
2088 //
2089 // In the future, we may keep revisions and mark them with
2090 // the rev_deleted field, which is reserved for this purpose.
2091 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2092 array(
2093 'ar_namespace' => 'page_namespace',
2094 'ar_title' => 'page_title',
2095 'ar_comment' => 'rev_comment',
2096 'ar_user' => 'rev_user',
2097 'ar_user_text' => 'rev_user_text',
2098 'ar_timestamp' => 'rev_timestamp',
2099 'ar_minor_edit' => 'rev_minor_edit',
2100 'ar_rev_id' => 'rev_id',
2101 'ar_text_id' => 'rev_text_id',
2102 'ar_text' => '\'\'', // Be explicit to appease
2103 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2104 'ar_len' => 'rev_len'
2105 ), array(
2106 'page_id' => $id,
2107 'page_id = rev_page'
2108 ), __METHOD__
2109 );
2110
2111 # Delete restrictions for it
2112 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2113
2114 # Now that it's safely backed up, delete it
2115 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2116
2117 # If using cascading deletes, we can skip some explicit deletes
2118 if ( !$dbw->cascadingDeletes() ) {
2119
2120 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2121
2122 if ($wgUseTrackbacks)
2123 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2124
2125 # Delete outgoing links
2126 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2127 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2128 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2129 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2130 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2131 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2132 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2133 }
2134
2135 # If using cleanup triggers, we can skip some manual deletes
2136 if ( !$dbw->cleanupTriggers() ) {
2137
2138 # Clean up recentchanges entries...
2139 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
2140 }
2141
2142 # Clear caches
2143 Article::onArticleDelete( $this->mTitle );
2144
2145 # Log the deletion
2146 $log = new LogPage( 'delete' );
2147 $log->addEntry( 'delete', $this->mTitle, $reason );
2148
2149 # Clear the cached article id so the interface doesn't act like we exist
2150 $this->mTitle->resetArticleID( 0 );
2151 $this->mTitle->mArticleID = 0;
2152 return true;
2153 }
2154
2155 /**
2156 * Revert a modification
2157 */
2158 function rollback() {
2159 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2160
2161 if( $wgUser->isAllowed( 'rollback' ) ) {
2162 if( $wgUser->isBlocked() ) {
2163 $wgOut->blockedPage();
2164 return;
2165 }
2166 } else {
2167 $wgOut->permissionRequired( 'rollback' );
2168 return;
2169 }
2170
2171 if ( wfReadOnly() ) {
2172 $wgOut->readOnlyPage( $this->getContent() );
2173 return;
2174 }
2175 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2176 array( $this->mTitle->getPrefixedText(),
2177 $wgRequest->getVal( 'from' ) ) ) ) {
2178 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2179 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2180 return;
2181 }
2182 $dbw = wfGetDB( DB_MASTER );
2183
2184 # Enhanced rollback, marks edits rc_bot=1
2185 $bot = $wgRequest->getBool( 'bot' );
2186
2187 # Replace all this user's current edits with the next one down
2188
2189 # Get the last editor
2190 $current = Revision::newFromTitle( $this->mTitle );
2191 if( is_null( $current ) ) {
2192 # Something wrong... no page?
2193 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2194 return;
2195 }
2196
2197 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2198 if( $from != $current->getUserText() ) {
2199 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2200 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2201 htmlspecialchars( $this->mTitle->getPrefixedText()),
2202 htmlspecialchars( $from ),
2203 htmlspecialchars( $current->getUserText() ) ) );
2204 if( $current->getComment() != '') {
2205 $wgOut->addHTML(
2206 wfMsg( 'editcomment',
2207 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2208 }
2209 return;
2210 }
2211
2212 # Get the last edit not by this guy
2213 $user = intval( $current->getUser() );
2214 $user_text = $dbw->addQuotes( $current->getUserText() );
2215 $s = $dbw->selectRow( 'revision',
2216 array( 'rev_id', 'rev_timestamp' ),
2217 array(
2218 'rev_page' => $current->getPage(),
2219 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2220 ), __METHOD__,
2221 array(
2222 'USE INDEX' => 'page_timestamp',
2223 'ORDER BY' => 'rev_timestamp DESC' )
2224 );
2225 if( $s === false ) {
2226 # Something wrong
2227 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2228 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2229 return;
2230 }
2231
2232 $set = array();
2233 if ( $bot ) {
2234 # Mark all reverted edits as bot
2235 $set['rc_bot'] = 1;
2236 }
2237 if ( $wgUseRCPatrol ) {
2238 # Mark all reverted edits as patrolled
2239 $set['rc_patrolled'] = 1;
2240 }
2241
2242 if ( $set ) {
2243 $dbw->update( 'recentchanges', $set,
2244 array( /* WHERE */
2245 'rc_cur_id' => $current->getPage(),
2246 'rc_user_text' => $current->getUserText(),
2247 "rc_timestamp > '{$s->rev_timestamp}'",
2248 ), __METHOD__
2249 );
2250 }
2251
2252 # Get the edit summary
2253 $target = Revision::newFromId( $s->rev_id );
2254 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2255 $newComment = $wgRequest->getText( 'summary', $newComment );
2256
2257 # Save it!
2258 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2259 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2260 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2261
2262 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2263
2264 $wgOut->returnToMain( false );
2265 }
2266
2267
2268 /**
2269 * Do standard deferred updates after page view
2270 * @private
2271 */
2272 function viewUpdates() {
2273 global $wgDeferredUpdateList;
2274
2275 if ( 0 != $this->getID() ) {
2276 global $wgDisableCounters;
2277 if( !$wgDisableCounters ) {
2278 Article::incViewCount( $this->getID() );
2279 $u = new SiteStatsUpdate( 1, 0, 0 );
2280 array_push( $wgDeferredUpdateList, $u );
2281 }
2282 }
2283
2284 # Update newtalk / watchlist notification status
2285 global $wgUser;
2286 $wgUser->clearNotification( $this->mTitle );
2287 }
2288
2289 /**
2290 * Do standard deferred updates after page edit.
2291 * Update links tables, site stats, search index and message cache.
2292 * Every 1000th edit, prune the recent changes table.
2293 *
2294 * @private
2295 * @param $text New text of the article
2296 * @param $summary Edit summary
2297 * @param $minoredit Minor edit
2298 * @param $timestamp_of_pagechange Timestamp associated with the page change
2299 * @param $newid rev_id value of the new revision
2300 * @param $changed Whether or not the content actually changed
2301 */
2302 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2303 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2304
2305 wfProfileIn( __METHOD__ );
2306
2307 # Parse the text
2308 $options = new ParserOptions;
2309 $options->setTidy(true);
2310 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2311
2312 # Save it to the parser cache
2313 $parserCache =& ParserCache::singleton();
2314 $parserCache->save( $poutput, $this, $wgUser );
2315
2316 # Update the links tables
2317 $u = new LinksUpdate( $this->mTitle, $poutput );
2318 $u->doUpdate();
2319
2320 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2321 wfSeedRandom();
2322 if ( 0 == mt_rand( 0, 99 ) ) {
2323 # Periodically flush old entries from the recentchanges table.
2324 global $wgRCMaxAge;
2325
2326 $dbw = wfGetDB( DB_MASTER );
2327 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2328 $recentchanges = $dbw->tableName( 'recentchanges' );
2329 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2330 $dbw->query( $sql );
2331 }
2332 }
2333
2334 $id = $this->getID();
2335 $title = $this->mTitle->getPrefixedDBkey();
2336 $shortTitle = $this->mTitle->getDBkey();
2337
2338 if ( 0 == $id ) {
2339 wfProfileOut( __METHOD__ );
2340 return;
2341 }
2342
2343 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2344 array_push( $wgDeferredUpdateList, $u );
2345 $u = new SearchUpdate( $id, $title, $text );
2346 array_push( $wgDeferredUpdateList, $u );
2347
2348 # If this is another user's talk page, update newtalk
2349 # Don't do this if $changed = false otherwise some idiot can null-edit a
2350 # load of user talk pages and piss people off, nor if it's a minor edit
2351 # by a properly-flagged bot.
2352 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2353 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2354 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2355 $other = User::newFromName( $shortTitle );
2356 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2357 // An anonymous user
2358 $other = new User();
2359 $other->setName( $shortTitle );
2360 }
2361 if( $other ) {
2362 $other->setNewtalk( true );
2363 }
2364 }
2365 }
2366
2367 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2368 $wgMessageCache->replace( $shortTitle, $text );
2369 }
2370
2371 wfProfileOut( __METHOD__ );
2372 }
2373
2374 /**
2375 * Perform article updates on a special page creation.
2376 *
2377 * @param Revision $rev
2378 *
2379 * @todo This is a shitty interface function. Kill it and replace the
2380 * other shitty functions like editUpdates and such so it's not needed
2381 * anymore.
2382 */
2383 function createUpdates( $rev ) {
2384 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2385 $this->mTotalAdjustment = 1;
2386 $this->editUpdates( $rev->getText(), $rev->getComment(),
2387 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2388 }
2389
2390 /**
2391 * Generate the navigation links when browsing through an article revisions
2392 * It shows the information as:
2393 * Revision as of \<date\>; view current revision
2394 * \<- Previous version | Next Version -\>
2395 *
2396 * @private
2397 * @param string $oldid Revision ID of this article revision
2398 */
2399 function setOldSubtitle( $oldid=0 ) {
2400 global $wgLang, $wgOut, $wgUser;
2401
2402 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2403 return;
2404 }
2405
2406 $revision = Revision::newFromId( $oldid );
2407
2408 $current = ( $oldid == $this->mLatest );
2409 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2410 $sk = $wgUser->getSkin();
2411 $lnk = $current
2412 ? wfMsg( 'currentrevisionlink' )
2413 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2414 $curdiff = $current
2415 ? wfMsg( 'diff' )
2416 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2417 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2418 $prevlink = $prev
2419 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2420 : wfMsg( 'previousrevision' );
2421 $prevdiff = $prev
2422 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2423 : wfMsg( 'diff' );
2424 $nextlink = $current
2425 ? wfMsg( 'nextrevision' )
2426 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2427 $nextdiff = $current
2428 ? wfMsg( 'diff' )
2429 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2430
2431 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2432 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2433
2434 $m = wfMsg( 'revision-info-current' );
2435 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2436 ? 'revision-info-current'
2437 : 'revision-info';
2438
2439 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2440 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2441 $wgOut->setSubtitle( $r );
2442 }
2443
2444 /**
2445 * This function is called right before saving the wikitext,
2446 * so we can do things like signatures and links-in-context.
2447 *
2448 * @param string $text
2449 */
2450 function preSaveTransform( $text ) {
2451 global $wgParser, $wgUser;
2452 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2453 }
2454
2455 /* Caching functions */
2456
2457 /**
2458 * checkLastModified returns true if it has taken care of all
2459 * output to the client that is necessary for this request.
2460 * (that is, it has sent a cached version of the page)
2461 */
2462 function tryFileCache() {
2463 static $called = false;
2464 if( $called ) {
2465 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2466 return;
2467 }
2468 $called = true;
2469 if($this->isFileCacheable()) {
2470 $touched = $this->mTouched;
2471 $cache = new HTMLFileCache( $this->mTitle );
2472 if($cache->isFileCacheGood( $touched )) {
2473 wfDebug( "Article::tryFileCache(): about to load file\n" );
2474 $cache->loadFromFileCache();
2475 return true;
2476 } else {
2477 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2478 ob_start( array(&$cache, 'saveToFileCache' ) );
2479 }
2480 } else {
2481 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2482 }
2483 }
2484
2485 /**
2486 * Check if the page can be cached
2487 * @return bool
2488 */
2489 function isFileCacheable() {
2490 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2491 $action = $wgRequest->getVal( 'action' );
2492 $oldid = $wgRequest->getVal( 'oldid' );
2493 $diff = $wgRequest->getVal( 'diff' );
2494 $redirect = $wgRequest->getVal( 'redirect' );
2495 $printable = $wgRequest->getVal( 'printable' );
2496 $page = $wgRequest->getVal( 'page' );
2497
2498 //check for non-standard user language; this covers uselang,
2499 //and extensions for auto-detecting user language.
2500 $ulang = $wgLang->getCode();
2501 $clang = $wgContLang->getCode();
2502
2503 $cacheable = $wgUseFileCache
2504 && (!$wgShowIPinHeader)
2505 && ($this->getID() != 0)
2506 && ($wgUser->isAnon())
2507 && (!$wgUser->getNewtalk())
2508 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2509 && (empty( $action ) || $action == 'view')
2510 && (!isset($oldid))
2511 && (!isset($diff))
2512 && (!isset($redirect))
2513 && (!isset($printable))
2514 && !isset($page)
2515 && (!$this->mRedirectedFrom)
2516 && ($ulang === $clang);
2517
2518 if ( $cacheable ) {
2519 //extension may have reason to disable file caching on some pages.
2520 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2521 }
2522
2523 return $cacheable;
2524 }
2525
2526 /**
2527 * Loads page_touched and returns a value indicating if it should be used
2528 *
2529 */
2530 function checkTouched() {
2531 if( !$this->mDataLoaded ) {
2532 $this->loadPageData();
2533 }
2534 return !$this->mIsRedirect;
2535 }
2536
2537 /**
2538 * Get the page_touched field
2539 */
2540 function getTouched() {
2541 # Ensure that page data has been loaded
2542 if( !$this->mDataLoaded ) {
2543 $this->loadPageData();
2544 }
2545 return $this->mTouched;
2546 }
2547
2548 /**
2549 * Get the page_latest field
2550 */
2551 function getLatest() {
2552 if ( !$this->mDataLoaded ) {
2553 $this->loadPageData();
2554 }
2555 return $this->mLatest;
2556 }
2557
2558 /**
2559 * Edit an article without doing all that other stuff
2560 * The article must already exist; link tables etc
2561 * are not updated, caches are not flushed.
2562 *
2563 * @param string $text text submitted
2564 * @param string $comment comment submitted
2565 * @param bool $minor whereas it's a minor modification
2566 */
2567 function quickEdit( $text, $comment = '', $minor = 0 ) {
2568 wfProfileIn( __METHOD__ );
2569
2570 $dbw = wfGetDB( DB_MASTER );
2571 $dbw->begin();
2572 $revision = new Revision( array(
2573 'page' => $this->getId(),
2574 'text' => $text,
2575 'comment' => $comment,
2576 'minor_edit' => $minor ? 1 : 0,
2577 ) );
2578 $revision->insertOn( $dbw );
2579 $this->updateRevisionOn( $dbw, $revision );
2580 $dbw->commit();
2581
2582 wfProfileOut( __METHOD__ );
2583 }
2584
2585 /**
2586 * Used to increment the view counter
2587 *
2588 * @static
2589 * @param integer $id article id
2590 */
2591 function incViewCount( $id ) {
2592 $id = intval( $id );
2593 global $wgHitcounterUpdateFreq, $wgDBtype;
2594
2595 $dbw = wfGetDB( DB_MASTER );
2596 $pageTable = $dbw->tableName( 'page' );
2597 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2598 $acchitsTable = $dbw->tableName( 'acchits' );
2599
2600 if( $wgHitcounterUpdateFreq <= 1 ) {
2601 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2602 return;
2603 }
2604
2605 # Not important enough to warrant an error page in case of failure
2606 $oldignore = $dbw->ignoreErrors( true );
2607
2608 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2609
2610 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2611 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2612 # Most of the time (or on SQL errors), skip row count check
2613 $dbw->ignoreErrors( $oldignore );
2614 return;
2615 }
2616
2617 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2618 $row = $dbw->fetchObject( $res );
2619 $rown = intval( $row->n );
2620 if( $rown >= $wgHitcounterUpdateFreq ){
2621 wfProfileIn( 'Article::incViewCount-collect' );
2622 $old_user_abort = ignore_user_abort( true );
2623
2624 if ($wgDBtype == 'mysql')
2625 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2626 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2627 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2628 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2629 'GROUP BY hc_id');
2630 $dbw->query("DELETE FROM $hitcounterTable");
2631 if ($wgDBtype == 'mysql') {
2632 $dbw->query('UNLOCK TABLES');
2633 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2634 'WHERE page_id = hc_id');
2635 }
2636 else {
2637 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2638 "FROM $acchitsTable WHERE page_id = hc_id");
2639 }
2640 $dbw->query("DROP TABLE $acchitsTable");
2641
2642 ignore_user_abort( $old_user_abort );
2643 wfProfileOut( 'Article::incViewCount-collect' );
2644 }
2645 $dbw->ignoreErrors( $oldignore );
2646 }
2647
2648 /**#@+
2649 * The onArticle*() functions are supposed to be a kind of hooks
2650 * which should be called whenever any of the specified actions
2651 * are done.
2652 *
2653 * This is a good place to put code to clear caches, for instance.
2654 *
2655 * This is called on page move and undelete, as well as edit
2656 * @static
2657 * @param $title_obj a title object
2658 */
2659
2660 static function onArticleCreate($title) {
2661 # The talk page isn't in the regular link tables, so we need to update manually:
2662 if ( $title->isTalkPage() ) {
2663 $other = $title->getSubjectPage();
2664 } else {
2665 $other = $title->getTalkPage();
2666 }
2667 $other->invalidateCache();
2668 $other->purgeSquid();
2669
2670 $title->touchLinks();
2671 $title->purgeSquid();
2672 }
2673
2674 static function onArticleDelete( $title ) {
2675 global $wgUseFileCache, $wgMessageCache;
2676
2677 $title->touchLinks();
2678 $title->purgeSquid();
2679
2680 # File cache
2681 if ( $wgUseFileCache ) {
2682 $cm = new HTMLFileCache( $title );
2683 @unlink( $cm->fileCacheName() );
2684 }
2685
2686 if( $title->getNamespace() == NS_MEDIAWIKI) {
2687 $wgMessageCache->replace( $title->getDBkey(), false );
2688 }
2689 }
2690
2691 /**
2692 * Purge caches on page update etc
2693 */
2694 static function onArticleEdit( $title ) {
2695 global $wgDeferredUpdateList, $wgUseFileCache;
2696
2697 // Invalidate caches of articles which include this page
2698 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2699 $wgDeferredUpdateList[] = $update;
2700
2701 # Purge squid for this page only
2702 $title->purgeSquid();
2703
2704 # Clear file cache
2705 if ( $wgUseFileCache ) {
2706 $cm = new HTMLFileCache( $title );
2707 @unlink( $cm->fileCacheName() );
2708 }
2709 }
2710
2711 /**#@-*/
2712
2713 /**
2714 * Info about this page
2715 * Called for ?action=info when $wgAllowPageInfo is on.
2716 *
2717 * @public
2718 */
2719 function info() {
2720 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2721
2722 if ( !$wgAllowPageInfo ) {
2723 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2724 return;
2725 }
2726
2727 $page = $this->mTitle->getSubjectPage();
2728
2729 $wgOut->setPagetitle( $page->getPrefixedText() );
2730 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2731
2732 # first, see if the page exists at all.
2733 $exists = $page->getArticleId() != 0;
2734 if( !$exists ) {
2735 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2736 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2737 } else {
2738 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2739 }
2740 } else {
2741 $dbr = wfGetDB( DB_SLAVE );
2742 $wl_clause = array(
2743 'wl_title' => $page->getDBkey(),
2744 'wl_namespace' => $page->getNamespace() );
2745 $numwatchers = $dbr->selectField(
2746 'watchlist',
2747 'COUNT(*)',
2748 $wl_clause,
2749 __METHOD__,
2750 $this->getSelectOptions() );
2751
2752 $pageInfo = $this->pageCountInfo( $page );
2753 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2754
2755 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2756 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2757 if( $talkInfo ) {
2758 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2759 }
2760 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2761 if( $talkInfo ) {
2762 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2763 }
2764 $wgOut->addHTML( '</ul>' );
2765
2766 }
2767 }
2768
2769 /**
2770 * Return the total number of edits and number of unique editors
2771 * on a given page. If page does not exist, returns false.
2772 *
2773 * @param Title $title
2774 * @return array
2775 * @private
2776 */
2777 function pageCountInfo( $title ) {
2778 $id = $title->getArticleId();
2779 if( $id == 0 ) {
2780 return false;
2781 }
2782
2783 $dbr = wfGetDB( DB_SLAVE );
2784
2785 $rev_clause = array( 'rev_page' => $id );
2786
2787 $edits = $dbr->selectField(
2788 'revision',
2789 'COUNT(rev_page)',
2790 $rev_clause,
2791 __METHOD__,
2792 $this->getSelectOptions() );
2793
2794 $authors = $dbr->selectField(
2795 'revision',
2796 'COUNT(DISTINCT rev_user_text)',
2797 $rev_clause,
2798 __METHOD__,
2799 $this->getSelectOptions() );
2800
2801 return array( 'edits' => $edits, 'authors' => $authors );
2802 }
2803
2804 /**
2805 * Return a list of templates used by this article.
2806 * Uses the templatelinks table
2807 *
2808 * @return array Array of Title objects
2809 */
2810 function getUsedTemplates() {
2811 $result = array();
2812 $id = $this->mTitle->getArticleID();
2813 if( $id == 0 ) {
2814 return array();
2815 }
2816
2817 $dbr = wfGetDB( DB_SLAVE );
2818 $res = $dbr->select( array( 'templatelinks' ),
2819 array( 'tl_namespace', 'tl_title' ),
2820 array( 'tl_from' => $id ),
2821 'Article:getUsedTemplates' );
2822 if ( false !== $res ) {
2823 if ( $dbr->numRows( $res ) ) {
2824 while ( $row = $dbr->fetchObject( $res ) ) {
2825 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2826 }
2827 }
2828 }
2829 $dbr->freeResult( $res );
2830 return $result;
2831 }
2832
2833 /**
2834 * Return an auto-generated summary if the text provided is a redirect.
2835 *
2836 * @param string $text The wikitext to check
2837 * @return string '' or an appropriate summary
2838 */
2839 public static function getRedirectAutosummary( $text ) {
2840 $rt = Title::newFromRedirect( $text );
2841 if( is_object( $rt ) )
2842 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2843 else
2844 return '';
2845 }
2846
2847 /**
2848 * Return an auto-generated summary if the new text is much shorter than
2849 * the old text.
2850 *
2851 * @param string $oldtext The previous text of the page
2852 * @param string $text The submitted text of the page
2853 * @return string An appropriate autosummary, or an empty string.
2854 */
2855 public static function getBlankingAutosummary( $oldtext, $text ) {
2856 if ($oldtext!='' && $text=='') {
2857 return wfMsgForContent('autosumm-blank');
2858 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2859 #Removing more than 90% of the article
2860 global $wgContLang;
2861 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2862 return wfMsgForContent('autosumm-replace', $truncatedtext);
2863 } else {
2864 return '';
2865 }
2866 }
2867
2868 /**
2869 * Return an applicable autosummary if one exists for the given edit.
2870 * @param string $oldtext The previous text of the page.
2871 * @param string $newtext The submitted text of the page.
2872 * @param bitmask $flags A bitmask of flags submitted for the edit.
2873 * @return string An appropriate autosummary, or an empty string.
2874 */
2875 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2876
2877 # This code is UGLY UGLY UGLY.
2878 # Somebody PLEASE come up with a more elegant way to do it.
2879
2880 #Redirect autosummaries
2881 $summary = self::getRedirectAutosummary( $newtext );
2882
2883 if ($summary)
2884 return $summary;
2885
2886 #Blanking autosummaries
2887 if (!($flags & EDIT_NEW))
2888 $summary = self::getBlankingAutosummary( $oldtext, $newtext );
2889
2890 if ($summary)
2891 return $summary;
2892
2893 #New page autosummaries
2894 if ($flags & EDIT_NEW && strlen($newtext)) {
2895 #If they're making a new article, give its text, truncated, in the summary.
2896 global $wgContLang;
2897 $truncatedtext = $wgContLang->truncate(
2898 str_replace("\n", ' ', $newtext),
2899 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2900 '...' );
2901 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
2902 }
2903
2904 if ($summary)
2905 return $summary;
2906
2907 return $summary;
2908 }
2909
2910 /**
2911 * Add the primary page-view wikitext to the output buffer
2912 * Saves the text into the parser cache if possible.
2913 * Updates templatelinks if it is out of date.
2914 *
2915 * @param string $text
2916 * @param bool $cache
2917 */
2918 public function outputWikiText( $text, $cache = true ) {
2919 global $wgParser, $wgUser, $wgOut;
2920
2921 $popts = $wgOut->parserOptions();
2922 $popts->setTidy(true);
2923 $parserOutput = $wgParser->parse( $text, $this->mTitle,
2924 $popts, true, true, $this->getRevIdFetched() );
2925 $popts->setTidy(false);
2926 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
2927 $parserCache =& ParserCache::singleton();
2928 $parserCache->save( $parserOutput, $this, $wgUser );
2929 }
2930
2931 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
2932 // templatelinks table may have become out of sync,
2933 // especially if using variable-based transclusions.
2934 // For paranoia, check if things have changed and if
2935 // so apply updates to the database. This will ensure
2936 // that cascaded protections apply as soon as the changes
2937 // are visible.
2938
2939 # Get templates from templatelinks
2940 $id = $this->mTitle->getArticleID();
2941
2942 $tlTemplates = array();
2943
2944 $dbr = wfGetDB( DB_SLAVE );
2945 $res = $dbr->select( array( 'templatelinks' ),
2946 array( 'tl_namespace', 'tl_title' ),
2947 array( 'tl_from' => $id ),
2948 'Article:getUsedTemplates' );
2949
2950 global $wgContLang;
2951
2952 if ( false !== $res ) {
2953 if ( $dbr->numRows( $res ) ) {
2954 while ( $row = $dbr->fetchObject( $res ) ) {
2955 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
2956 }
2957 }
2958 }
2959
2960 # Get templates from parser output.
2961 $poTemplates_allns = $parserOutput->getTemplates();
2962
2963 $poTemplates = array ();
2964 foreach ( $poTemplates_allns as $ns_templates ) {
2965 $poTemplates = array_merge( $poTemplates, $ns_templates );
2966 }
2967
2968 # Get the diff
2969 $templates_diff = array_diff( $poTemplates, $tlTemplates );
2970
2971 if ( count( $templates_diff ) > 0 ) {
2972 # Whee, link updates time.
2973 $u = new LinksUpdate( $this->mTitle, $parserOutput );
2974
2975 $dbw = wfGetDb( DB_MASTER );
2976 $dbw->begin();
2977
2978 $u->doUpdate();
2979
2980 $dbw->commit();
2981 }
2982 }
2983
2984 $wgOut->addParserOutput( $parserOutput );
2985 }
2986
2987 }
2988
2989