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