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