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