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