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