(bug 8407) Disallow indexing of "printable" versions
[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( $wgUser->isAllowed( 'autopatrol' ) ) {
1350 RecentChange::markPatrolled( $rcid );
1351 }
1352 }
1353 $wgUser->incEditCount();
1354 $dbw->commit();
1355 }
1356 } else {
1357 // Keep the same revision ID, but do some updates on it
1358 $revisionId = $this->getRevIdFetched();
1359 // Update page_touched, this is usually implicit in the page update
1360 // Other cache updates are done in onArticleEdit()
1361 $this->mTitle->invalidateCache();
1362 }
1363
1364 if( !$wgDBtransactions ) {
1365 ignore_user_abort( $userAbort );
1366 }
1367
1368 if ( $good ) {
1369 # Invalidate cache of this article and all pages using this article
1370 # as a template. Partly deferred.
1371 Article::onArticleEdit( $this->mTitle );
1372
1373 # Update links tables, site stats, etc.
1374 $changed = ( strcmp( $oldtext, $text ) != 0 );
1375 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1376 }
1377 } else {
1378 # Create new article
1379
1380 # Set statistics members
1381 # We work out if it's countable after PST to avoid counter drift
1382 # when articles are created with {{subst:}}
1383 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1384 $this->mTotalAdjustment = 1;
1385
1386 $dbw->begin();
1387
1388 # Add the page record; stake our claim on this title!
1389 # This will fail with a database query exception if the article already exists
1390 $newid = $this->insertOn( $dbw );
1391
1392 # Save the revision text...
1393 $revision = new Revision( array(
1394 'page' => $newid,
1395 'comment' => $summary,
1396 'minor_edit' => $isminor,
1397 'text' => $text
1398 ) );
1399 $revisionId = $revision->insertOn( $dbw );
1400
1401 $this->mTitle->resetArticleID( $newid );
1402
1403 # Update the page record with revision data
1404 $this->updateRevisionOn( $dbw, $revision, 0 );
1405
1406 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1407 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1408 '', strlen( $text ), $revisionId );
1409 # Mark as patrolled if the user can
1410 if( $wgUser->isAllowed( 'autopatrol' ) ) {
1411 RecentChange::markPatrolled( $rcid );
1412 }
1413 }
1414 $wgUser->incEditCount();
1415 $dbw->commit();
1416
1417 # Update links, etc.
1418 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1419
1420 # Clear caches
1421 Article::onArticleCreate( $this->mTitle );
1422
1423 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1424 $summary, $flags & EDIT_MINOR,
1425 null, null, &$flags ) );
1426 }
1427
1428 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1429 wfDoUpdates();
1430 }
1431
1432 wfRunHooks( 'ArticleSaveComplete',
1433 array( &$this, &$wgUser, $text,
1434 $summary, $flags & EDIT_MINOR,
1435 null, null, &$flags ) );
1436
1437 wfProfileOut( __METHOD__ );
1438 return $good;
1439 }
1440
1441 /**
1442 * @deprecated wrapper for doRedirect
1443 */
1444 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1445 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1446 }
1447
1448 /**
1449 * Output a redirect back to the article.
1450 * This is typically used after an edit.
1451 *
1452 * @param boolean $noRedir Add redirect=no
1453 * @param string $sectionAnchor section to redirect to, including "#"
1454 */
1455 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1456 global $wgOut;
1457 if ( $noRedir ) {
1458 $query = 'redirect=no';
1459 } else {
1460 $query = '';
1461 }
1462 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1463 }
1464
1465 /**
1466 * Mark this particular edit as patrolled
1467 */
1468 function markpatrolled() {
1469 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1470 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1471
1472 # Check RC patrol config. option
1473 if( !$wgUseRCPatrol ) {
1474 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1475 return;
1476 }
1477
1478 # Check permissions
1479 if( !$wgUser->isAllowed( 'patrol' ) ) {
1480 $wgOut->permissionRequired( 'patrol' );
1481 return;
1482 }
1483
1484 # If we haven't been given an rc_id value, we can't do anything
1485 $rcid = $wgRequest->getVal( 'rcid' );
1486 if( !$rcid ) {
1487 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1488 return;
1489 }
1490
1491 # Handle the 'MarkPatrolled' hook
1492 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1493 return;
1494 }
1495
1496 $return = SpecialPage::getTitleFor( 'Recentchanges' );
1497 # If it's left up to us, check that the user is allowed to patrol this edit
1498 # If the user has the "autopatrol" right, then we'll assume there are no
1499 # other conditions stopping them doing so
1500 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1501 $rc = RecentChange::newFromId( $rcid );
1502 # Graceful error handling, as we've done before here...
1503 # (If the recent change doesn't exist, then it doesn't matter whether
1504 # the user is allowed to patrol it or not; nothing is going to happen
1505 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1506 # The user made this edit, and can't patrol it
1507 # Tell them so, and then back off
1508 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1509 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1510 $wgOut->returnToMain( false, $return );
1511 return;
1512 }
1513 }
1514
1515 # Mark the edit as patrolled
1516 RecentChange::markPatrolled( $rcid );
1517 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1518
1519 # Inform the user
1520 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1521 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1522 $wgOut->returnToMain( false, $return );
1523 }
1524
1525 /**
1526 * User-interface handler for the "watch" action
1527 */
1528
1529 function watch() {
1530
1531 global $wgUser, $wgOut;
1532
1533 if ( $wgUser->isAnon() ) {
1534 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1535 return;
1536 }
1537 if ( wfReadOnly() ) {
1538 $wgOut->readOnlyPage();
1539 return;
1540 }
1541
1542 if( $this->doWatch() ) {
1543 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1544 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1545
1546 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1547 $text = wfMsg( 'addedwatchtext', $link );
1548 $wgOut->addWikiText( $text );
1549 }
1550
1551 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1552 }
1553
1554 /**
1555 * Add this page to $wgUser's watchlist
1556 * @return bool true on successful watch operation
1557 */
1558 function doWatch() {
1559 global $wgUser;
1560 if( $wgUser->isAnon() ) {
1561 return false;
1562 }
1563
1564 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1565 $wgUser->addWatch( $this->mTitle );
1566
1567 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1568 }
1569
1570 return false;
1571 }
1572
1573 /**
1574 * User interface handler for the "unwatch" action.
1575 */
1576 function unwatch() {
1577
1578 global $wgUser, $wgOut;
1579
1580 if ( $wgUser->isAnon() ) {
1581 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1582 return;
1583 }
1584 if ( wfReadOnly() ) {
1585 $wgOut->readOnlyPage();
1586 return;
1587 }
1588
1589 if( $this->doUnwatch() ) {
1590 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1591 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1592
1593 $link = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1594 $text = wfMsg( 'removedwatchtext', $link );
1595 $wgOut->addWikiText( $text );
1596 }
1597
1598 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1599 }
1600
1601 /**
1602 * Stop watching a page
1603 * @return bool true on successful unwatch
1604 */
1605 function doUnwatch() {
1606 global $wgUser;
1607 if( $wgUser->isAnon() ) {
1608 return false;
1609 }
1610
1611 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1612 $wgUser->removeWatch( $this->mTitle );
1613
1614 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1615 }
1616
1617 return false;
1618 }
1619
1620 /**
1621 * action=protect handler
1622 */
1623 function protect() {
1624 $form = new ProtectionForm( $this );
1625 $form->show();
1626 }
1627
1628 /**
1629 * action=unprotect handler (alias)
1630 */
1631 function unprotect() {
1632 $this->protect();
1633 }
1634
1635 /**
1636 * Update the article's restriction field, and leave a log entry.
1637 *
1638 * @param array $limit set of restriction keys
1639 * @param string $reason
1640 * @return bool true on success
1641 */
1642 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0 ) {
1643 global $wgUser, $wgRestrictionTypes, $wgContLang;
1644
1645 $id = $this->mTitle->getArticleID();
1646 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1647 return false;
1648 }
1649
1650 if (!$cascade) {
1651 $cascade = false;
1652 }
1653
1654 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1655 # we expect a single selection, but the schema allows otherwise.
1656 $current = array();
1657 foreach( $wgRestrictionTypes as $action )
1658 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1659
1660 $current = Article::flattenRestrictions( $current );
1661 $updated = Article::flattenRestrictions( $limit );
1662
1663 $changed = ( $current != $updated );
1664 $changed = $changed || ($this->mTitle->areRestrictionsCascading() != $cascade);
1665 $protect = ( $updated != '' );
1666
1667 # If nothing's changed, do nothing
1668 if( $changed ) {
1669 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1670
1671 $dbw =& wfGetDB( DB_MASTER );
1672
1673 # Prepare a null revision to be added to the history
1674 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1675 if( $reason )
1676 $comment .= ": $reason";
1677 if( $protect )
1678 $comment .= " [$updated]";
1679 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1680 $nullRevId = $nullRevision->insertOn( $dbw );
1681
1682 # Update restrictions table
1683 foreach( $limit as $action => $restrictions ) {
1684 if ($restrictions != '' ) {
1685 $dbw->replace( 'page_restrictions', array( 'pr_pagetype'),
1686 array( 'pr_page' => $id, 'pr_type' => $action
1687 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0 ), __METHOD__ );
1688 } else {
1689 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1690 'pr_type' => $action ), __METHOD__ );
1691 }
1692 }
1693
1694 # Update page record
1695 $dbw->update( 'page',
1696 array( /* SET */
1697 'page_touched' => $dbw->timestamp(),
1698 'page_restrictions' => '',
1699 'page_latest' => $nullRevId
1700 ), array( /* WHERE */
1701 'page_id' => $id
1702 ), 'Article::protect'
1703 );
1704 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1705
1706 # Update the protection log
1707 $log = new LogPage( 'protect' );
1708
1709 $cascade_description = '';
1710
1711 if ($cascade) {
1712 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1713 }
1714
1715 if( $protect ) {
1716 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description" ) );
1717 } else {
1718 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1719 }
1720
1721 } # End hook
1722 } # End "changed" check
1723
1724 return true;
1725 }
1726
1727 /**
1728 * Take an array of page restrictions and flatten it to a string
1729 * suitable for insertion into the page_restrictions field.
1730 * @param array $limit
1731 * @return string
1732 * @private
1733 */
1734 function flattenRestrictions( $limit ) {
1735 if( !is_array( $limit ) ) {
1736 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1737 }
1738 $bits = array();
1739 ksort( $limit );
1740 foreach( $limit as $action => $restrictions ) {
1741 if( $restrictions != '' ) {
1742 $bits[] = "$action=$restrictions";
1743 }
1744 }
1745 return implode( ':', $bits );
1746 }
1747
1748 /*
1749 * UI entry point for page deletion
1750 */
1751 function delete() {
1752 global $wgUser, $wgOut, $wgRequest;
1753 $confirm = $wgRequest->wasPosted() &&
1754 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1755 $reason = $wgRequest->getText( 'wpReason' );
1756
1757 # This code desperately needs to be totally rewritten
1758
1759 # Check permissions
1760 if( $wgUser->isAllowed( 'delete' ) ) {
1761 if( $wgUser->isBlocked( !$confirm ) ) {
1762 $wgOut->blockedPage();
1763 return;
1764 }
1765 } else {
1766 $wgOut->permissionRequired( 'delete' );
1767 return;
1768 }
1769
1770 if( wfReadOnly() ) {
1771 $wgOut->readOnlyPage();
1772 return;
1773 }
1774
1775 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1776
1777 # Better double-check that it hasn't been deleted yet!
1778 $dbw =& wfGetDB( DB_MASTER );
1779 $conds = $this->mTitle->pageCond();
1780 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1781 if ( $latest === false ) {
1782 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1783 return;
1784 }
1785
1786 if( $confirm ) {
1787 $this->doDelete( $reason );
1788 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1789 $this->doWatch();
1790 } elseif( $this->mTitle->userIsWatching() ) {
1791 $this->doUnwatch();
1792 }
1793 return;
1794 }
1795
1796 # determine whether this page has earlier revisions
1797 # and insert a warning if it does
1798 $maxRevisions = 20;
1799 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1800
1801 if( count( $authors ) > 1 && !$confirm ) {
1802 $skin=$wgUser->getSkin();
1803 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1804 }
1805
1806 # If a single user is responsible for all revisions, find out who they are
1807 if ( count( $authors ) == $maxRevisions ) {
1808 // Query bailed out, too many revisions to find out if they're all the same
1809 $authorOfAll = false;
1810 } else {
1811 $authorOfAll = reset( $authors );
1812 foreach ( $authors as $author ) {
1813 if ( $authorOfAll != $author ) {
1814 $authorOfAll = false;
1815 break;
1816 }
1817 }
1818 }
1819 # Fetch article text
1820 $rev = Revision::newFromTitle( $this->mTitle );
1821
1822 if( !is_null( $rev ) ) {
1823 # if this is a mini-text, we can paste part of it into the deletion reason
1824 $text = $rev->getText();
1825
1826 #if this is empty, an earlier revision may contain "useful" text
1827 $blanked = false;
1828 if( $text == '' ) {
1829 $prev = $rev->getPrevious();
1830 if( $prev ) {
1831 $text = $prev->getText();
1832 $blanked = true;
1833 }
1834 }
1835
1836 $length = strlen( $text );
1837
1838 # this should not happen, since it is not possible to store an empty, new
1839 # page. Let's insert a standard text in case it does, though
1840 if( $length == 0 && $reason === '' ) {
1841 $reason = wfMsgForContent( 'exblank' );
1842 }
1843
1844 if( $length < 500 && $reason === '' ) {
1845 # comment field=255, let's grep the first 150 to have some user
1846 # space left
1847 global $wgContLang;
1848 $text = $wgContLang->truncate( $text, 150, '...' );
1849
1850 # let's strip out newlines
1851 $text = preg_replace( "/[\n\r]/", '', $text );
1852
1853 if( !$blanked ) {
1854 if( $authorOfAll === false ) {
1855 $reason = wfMsgForContent( 'excontent', $text );
1856 } else {
1857 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1858 }
1859 } else {
1860 $reason = wfMsgForContent( 'exbeforeblank', $text );
1861 }
1862 }
1863 }
1864
1865 return $this->confirmDelete( '', $reason );
1866 }
1867
1868 /**
1869 * Get the last N authors
1870 * @param int $num Number of revisions to get
1871 * @param string $revLatest The latest rev_id, selected from the master (optional)
1872 * @return array Array of authors, duplicates not removed
1873 */
1874 function getLastNAuthors( $num, $revLatest = 0 ) {
1875 wfProfileIn( __METHOD__ );
1876
1877 // First try the slave
1878 // If that doesn't have the latest revision, try the master
1879 $continue = 2;
1880 $db =& wfGetDB( DB_SLAVE );
1881 do {
1882 $res = $db->select( array( 'page', 'revision' ),
1883 array( 'rev_id', 'rev_user_text' ),
1884 array(
1885 'page_namespace' => $this->mTitle->getNamespace(),
1886 'page_title' => $this->mTitle->getDBkey(),
1887 'rev_page = page_id'
1888 ), __METHOD__, $this->getSelectOptions( array(
1889 'ORDER BY' => 'rev_timestamp DESC',
1890 'LIMIT' => $num
1891 ) )
1892 );
1893 if ( !$res ) {
1894 wfProfileOut( __METHOD__ );
1895 return array();
1896 }
1897 $row = $db->fetchObject( $res );
1898 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1899 $db =& wfGetDB( DB_MASTER );
1900 $continue--;
1901 } else {
1902 $continue = 0;
1903 }
1904 } while ( $continue );
1905
1906 $authors = array( $row->rev_user_text );
1907 while ( $row = $db->fetchObject( $res ) ) {
1908 $authors[] = $row->rev_user_text;
1909 }
1910 wfProfileOut( __METHOD__ );
1911 return $authors;
1912 }
1913
1914 /**
1915 * Output deletion confirmation dialog
1916 */
1917 function confirmDelete( $par, $reason ) {
1918 global $wgOut, $wgUser;
1919
1920 wfDebug( "Article::confirmDelete\n" );
1921
1922 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1923 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1924 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1925 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1926
1927 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1928
1929 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1930 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1931 $token = htmlspecialchars( $wgUser->editToken() );
1932 $watch = Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '2' ) );
1933
1934 $wgOut->addHTML( "
1935 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1936 <table border='0'>
1937 <tr>
1938 <td align='right'>
1939 <label for='wpReason'>{$delcom}:</label>
1940 </td>
1941 <td align='left'>
1942 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
1943 </td>
1944 </tr>
1945 <tr>
1946 <td>&nbsp;</td>
1947 <td>$watch</td>
1948 </tr>
1949 <tr>
1950 <td>&nbsp;</td>
1951 <td>
1952 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
1953 </td>
1954 </tr>
1955 </table>
1956 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1957 </form>\n" );
1958
1959 $wgOut->returnToMain( false );
1960 }
1961
1962
1963 /**
1964 * Perform a deletion and output success or failure messages
1965 */
1966 function doDelete( $reason ) {
1967 global $wgOut, $wgUser;
1968 wfDebug( __METHOD__."\n" );
1969
1970 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1971 if ( $this->doDeleteArticle( $reason ) ) {
1972 $deleted = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1973
1974 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1975 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1976
1977 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1978 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1979
1980 $wgOut->addWikiText( $text );
1981 $wgOut->returnToMain( false );
1982 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1983 } else {
1984 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1985 }
1986 }
1987 }
1988
1989 /**
1990 * Back-end article deletion
1991 * Deletes the article with database consistency, writes logs, purges caches
1992 * Returns success
1993 */
1994 function doDeleteArticle( $reason ) {
1995 global $wgUseSquid, $wgDeferredUpdateList;
1996 global $wgUseTrackbacks;
1997
1998 wfDebug( __METHOD__."\n" );
1999
2000 $dbw =& wfGetDB( DB_MASTER );
2001 $ns = $this->mTitle->getNamespace();
2002 $t = $this->mTitle->getDBkey();
2003 $id = $this->mTitle->getArticleID();
2004
2005 if ( $t == '' || $id == 0 ) {
2006 return false;
2007 }
2008
2009 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2010 array_push( $wgDeferredUpdateList, $u );
2011
2012 // For now, shunt the revision data into the archive table.
2013 // Text is *not* removed from the text table; bulk storage
2014 // is left intact to avoid breaking block-compression or
2015 // immutable storage schemes.
2016 //
2017 // For backwards compatibility, note that some older archive
2018 // table entries will have ar_text and ar_flags fields still.
2019 //
2020 // In the future, we may keep revisions and mark them with
2021 // the rev_deleted field, which is reserved for this purpose.
2022 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2023 array(
2024 'ar_namespace' => 'page_namespace',
2025 'ar_title' => 'page_title',
2026 'ar_comment' => 'rev_comment',
2027 'ar_user' => 'rev_user',
2028 'ar_user_text' => 'rev_user_text',
2029 'ar_timestamp' => 'rev_timestamp',
2030 'ar_minor_edit' => 'rev_minor_edit',
2031 'ar_rev_id' => 'rev_id',
2032 'ar_text_id' => 'rev_text_id',
2033 'ar_text' => '\'\'', // Be explicit to appease
2034 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2035 ), array(
2036 'page_id' => $id,
2037 'page_id = rev_page'
2038 ), __METHOD__
2039 );
2040
2041 # Delete restrictions for it
2042 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2043
2044 # Now that it's safely backed up, delete it
2045 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2046
2047 # If using cascading deletes, we can skip some explicit deletes
2048 if ( !$dbw->cascadingDeletes() ) {
2049
2050 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2051
2052 if ($wgUseTrackbacks)
2053 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2054
2055 # Delete outgoing links
2056 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2057 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2058 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2059 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2060 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2061 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2062 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2063 }
2064
2065 # If using cleanup triggers, we can skip some manual deletes
2066 if ( !$dbw->cleanupTriggers() ) {
2067
2068 # Clean up recentchanges entries...
2069 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
2070 }
2071
2072 # Clear caches
2073 Article::onArticleDelete( $this->mTitle );
2074
2075 # Log the deletion
2076 $log = new LogPage( 'delete' );
2077 $log->addEntry( 'delete', $this->mTitle, $reason );
2078
2079 # Clear the cached article id so the interface doesn't act like we exist
2080 $this->mTitle->resetArticleID( 0 );
2081 $this->mTitle->mArticleID = 0;
2082 return true;
2083 }
2084
2085 /**
2086 * Revert a modification
2087 */
2088 function rollback() {
2089 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2090
2091 if( $wgUser->isAllowed( 'rollback' ) ) {
2092 if( $wgUser->isBlocked() ) {
2093 $wgOut->blockedPage();
2094 return;
2095 }
2096 } else {
2097 $wgOut->permissionRequired( 'rollback' );
2098 return;
2099 }
2100
2101 if ( wfReadOnly() ) {
2102 $wgOut->readOnlyPage( $this->getContent() );
2103 return;
2104 }
2105 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2106 array( $this->mTitle->getPrefixedText(),
2107 $wgRequest->getVal( 'from' ) ) ) ) {
2108 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2109 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2110 return;
2111 }
2112 $dbw =& wfGetDB( DB_MASTER );
2113
2114 # Enhanced rollback, marks edits rc_bot=1
2115 $bot = $wgRequest->getBool( 'bot' );
2116
2117 # Replace all this user's current edits with the next one down
2118
2119 # Get the last editor
2120 $current = Revision::newFromTitle( $this->mTitle );
2121 if( is_null( $current ) ) {
2122 # Something wrong... no page?
2123 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2124 return;
2125 }
2126
2127 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2128 if( $from != $current->getUserText() ) {
2129 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2130 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2131 htmlspecialchars( $this->mTitle->getPrefixedText()),
2132 htmlspecialchars( $from ),
2133 htmlspecialchars( $current->getUserText() ) ) );
2134 if( $current->getComment() != '') {
2135 $wgOut->addHTML(
2136 wfMsg( 'editcomment',
2137 htmlspecialchars( $current->getComment() ) ) );
2138 }
2139 return;
2140 }
2141
2142 # Get the last edit not by this guy
2143 $user = intval( $current->getUser() );
2144 $user_text = $dbw->addQuotes( $current->getUserText() );
2145 $s = $dbw->selectRow( 'revision',
2146 array( 'rev_id', 'rev_timestamp' ),
2147 array(
2148 'rev_page' => $current->getPage(),
2149 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2150 ), __METHOD__,
2151 array(
2152 'USE INDEX' => 'page_timestamp',
2153 'ORDER BY' => 'rev_timestamp DESC' )
2154 );
2155 if( $s === false ) {
2156 # Something wrong
2157 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2158 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2159 return;
2160 }
2161
2162 $set = array();
2163 if ( $bot ) {
2164 # Mark all reverted edits as bot
2165 $set['rc_bot'] = 1;
2166 }
2167 if ( $wgUseRCPatrol ) {
2168 # Mark all reverted edits as patrolled
2169 $set['rc_patrolled'] = 1;
2170 }
2171
2172 if ( $set ) {
2173 $dbw->update( 'recentchanges', $set,
2174 array( /* WHERE */
2175 'rc_cur_id' => $current->getPage(),
2176 'rc_user_text' => $current->getUserText(),
2177 "rc_timestamp > '{$s->rev_timestamp}'",
2178 ), __METHOD__
2179 );
2180 }
2181
2182 # Get the edit summary
2183 $target = Revision::newFromId( $s->rev_id );
2184 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2185 $newComment = $wgRequest->getText( 'summary', $newComment );
2186
2187 # Save it!
2188 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2189 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2190 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2191
2192 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2193
2194 $wgOut->returnToMain( false );
2195 }
2196
2197
2198 /**
2199 * Do standard deferred updates after page view
2200 * @private
2201 */
2202 function viewUpdates() {
2203 global $wgDeferredUpdateList;
2204
2205 if ( 0 != $this->getID() ) {
2206 global $wgDisableCounters;
2207 if( !$wgDisableCounters ) {
2208 Article::incViewCount( $this->getID() );
2209 $u = new SiteStatsUpdate( 1, 0, 0 );
2210 array_push( $wgDeferredUpdateList, $u );
2211 }
2212 }
2213
2214 # Update newtalk / watchlist notification status
2215 global $wgUser;
2216 $wgUser->clearNotification( $this->mTitle );
2217 }
2218
2219 /**
2220 * Do standard deferred updates after page edit.
2221 * Update links tables, site stats, search index and message cache.
2222 * Every 1000th edit, prune the recent changes table.
2223 *
2224 * @private
2225 * @param $text New text of the article
2226 * @param $summary Edit summary
2227 * @param $minoredit Minor edit
2228 * @param $timestamp_of_pagechange Timestamp associated with the page change
2229 * @param $newid rev_id value of the new revision
2230 * @param $changed Whether or not the content actually changed
2231 */
2232 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2233 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2234
2235 wfProfileIn( __METHOD__ );
2236
2237 # Parse the text
2238 $options = new ParserOptions;
2239 $options->setTidy(true);
2240 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2241
2242 # Save it to the parser cache
2243 $parserCache =& ParserCache::singleton();
2244 $parserCache->save( $poutput, $this, $wgUser );
2245
2246 # Update the links tables
2247 $u = new LinksUpdate( $this->mTitle, $poutput );
2248 $u->doUpdate();
2249
2250 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2251 wfSeedRandom();
2252 if ( 0 == mt_rand( 0, 999 ) ) {
2253 # Periodically flush old entries from the recentchanges table.
2254 global $wgRCMaxAge;
2255
2256 $dbw =& wfGetDB( DB_MASTER );
2257 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2258 $recentchanges = $dbw->tableName( 'recentchanges' );
2259 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2260 $dbw->query( $sql );
2261 }
2262 }
2263
2264 $id = $this->getID();
2265 $title = $this->mTitle->getPrefixedDBkey();
2266 $shortTitle = $this->mTitle->getDBkey();
2267
2268 if ( 0 == $id ) {
2269 wfProfileOut( __METHOD__ );
2270 return;
2271 }
2272
2273 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2274 array_push( $wgDeferredUpdateList, $u );
2275 $u = new SearchUpdate( $id, $title, $text );
2276 array_push( $wgDeferredUpdateList, $u );
2277
2278 # If this is another user's talk page, update newtalk
2279 # Don't do this if $changed = false otherwise some idiot can null-edit a
2280 # load of user talk pages and piss people off, nor if it's a minor edit
2281 # by a properly-flagged bot.
2282 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2283 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2284 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2285 $other = User::newFromName( $shortTitle );
2286 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2287 // An anonymous user
2288 $other = new User();
2289 $other->setName( $shortTitle );
2290 }
2291 if( $other ) {
2292 $other->setNewtalk( true );
2293 }
2294 }
2295 }
2296
2297 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2298 $wgMessageCache->replace( $shortTitle, $text );
2299 }
2300
2301 wfProfileOut( __METHOD__ );
2302 }
2303
2304 /**
2305 * Perform article updates on a special page creation.
2306 *
2307 * @param Revision $rev
2308 *
2309 * @fixme This is a shitty interface function. Kill it and replace the
2310 * other shitty functions like editUpdates and such so it's not needed
2311 * anymore.
2312 */
2313 function createUpdates( $rev ) {
2314 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2315 $this->mTotalAdjustment = 1;
2316 $this->editUpdates( $rev->getText(), $rev->getComment(),
2317 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2318 }
2319
2320 /**
2321 * Generate the navigation links when browsing through an article revisions
2322 * It shows the information as:
2323 * Revision as of \<date\>; view current revision
2324 * \<- Previous version | Next Version -\>
2325 *
2326 * @private
2327 * @param string $oldid Revision ID of this article revision
2328 */
2329 function setOldSubtitle( $oldid=0 ) {
2330 global $wgLang, $wgOut, $wgUser;
2331
2332 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2333 return;
2334 }
2335
2336 $revision = Revision::newFromId( $oldid );
2337
2338 $current = ( $oldid == $this->mLatest );
2339 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2340 $sk = $wgUser->getSkin();
2341 $lnk = $current
2342 ? wfMsg( 'currentrevisionlink' )
2343 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2344 $curdiff = $current
2345 ? wfMsg( 'diff' )
2346 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2347 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2348 $prevlink = $prev
2349 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2350 : wfMsg( 'previousrevision' );
2351 $prevdiff = $prev
2352 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2353 : wfMsg( 'diff' );
2354 $nextlink = $current
2355 ? wfMsg( 'nextrevision' )
2356 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2357 $nextdiff = $current
2358 ? wfMsg( 'diff' )
2359 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2360
2361 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2362 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2363
2364 $r = "\n\t\t\t\t<div id=\"mw-revision-info\">" . wfMsg( 'revision-info', $td, $userlinks ) . "</div>\n" .
2365 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2366 $wgOut->setSubtitle( $r );
2367 }
2368
2369 /**
2370 * This function is called right before saving the wikitext,
2371 * so we can do things like signatures and links-in-context.
2372 *
2373 * @param string $text
2374 */
2375 function preSaveTransform( $text ) {
2376 global $wgParser, $wgUser;
2377 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2378 }
2379
2380 /* Caching functions */
2381
2382 /**
2383 * checkLastModified returns true if it has taken care of all
2384 * output to the client that is necessary for this request.
2385 * (that is, it has sent a cached version of the page)
2386 */
2387 function tryFileCache() {
2388 static $called = false;
2389 if( $called ) {
2390 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2391 return;
2392 }
2393 $called = true;
2394 if($this->isFileCacheable()) {
2395 $touched = $this->mTouched;
2396 $cache = new HTMLFileCache( $this->mTitle );
2397 if($cache->isFileCacheGood( $touched )) {
2398 wfDebug( "Article::tryFileCache(): about to load file\n" );
2399 $cache->loadFromFileCache();
2400 return true;
2401 } else {
2402 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2403 ob_start( array(&$cache, 'saveToFileCache' ) );
2404 }
2405 } else {
2406 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2407 }
2408 }
2409
2410 /**
2411 * Check if the page can be cached
2412 * @return bool
2413 */
2414 function isFileCacheable() {
2415 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2416 $action = $wgRequest->getVal( 'action' );
2417 $oldid = $wgRequest->getVal( 'oldid' );
2418 $diff = $wgRequest->getVal( 'diff' );
2419 $redirect = $wgRequest->getVal( 'redirect' );
2420 $printable = $wgRequest->getVal( 'printable' );
2421
2422 return $wgUseFileCache
2423 and (!$wgShowIPinHeader)
2424 and ($this->getID() != 0)
2425 and ($wgUser->isAnon())
2426 and (!$wgUser->getNewtalk())
2427 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2428 and (empty( $action ) || $action == 'view')
2429 and (!isset($oldid))
2430 and (!isset($diff))
2431 and (!isset($redirect))
2432 and (!isset($printable))
2433 and (!$this->mRedirectedFrom);
2434 }
2435
2436 /**
2437 * Loads page_touched and returns a value indicating if it should be used
2438 *
2439 */
2440 function checkTouched() {
2441 if( !$this->mDataLoaded ) {
2442 $this->loadPageData();
2443 }
2444 return !$this->mIsRedirect;
2445 }
2446
2447 /**
2448 * Get the page_touched field
2449 */
2450 function getTouched() {
2451 # Ensure that page data has been loaded
2452 if( !$this->mDataLoaded ) {
2453 $this->loadPageData();
2454 }
2455 return $this->mTouched;
2456 }
2457
2458 /**
2459 * Get the page_latest field
2460 */
2461 function getLatest() {
2462 if ( !$this->mDataLoaded ) {
2463 $this->loadPageData();
2464 }
2465 return $this->mLatest;
2466 }
2467
2468 /**
2469 * Edit an article without doing all that other stuff
2470 * The article must already exist; link tables etc
2471 * are not updated, caches are not flushed.
2472 *
2473 * @param string $text text submitted
2474 * @param string $comment comment submitted
2475 * @param bool $minor whereas it's a minor modification
2476 */
2477 function quickEdit( $text, $comment = '', $minor = 0 ) {
2478 wfProfileIn( __METHOD__ );
2479
2480 $dbw =& wfGetDB( DB_MASTER );
2481 $dbw->begin();
2482 $revision = new Revision( array(
2483 'page' => $this->getId(),
2484 'text' => $text,
2485 'comment' => $comment,
2486 'minor_edit' => $minor ? 1 : 0,
2487 ) );
2488 $revision->insertOn( $dbw );
2489 $this->updateRevisionOn( $dbw, $revision );
2490 $dbw->commit();
2491
2492 wfProfileOut( __METHOD__ );
2493 }
2494
2495 /**
2496 * Used to increment the view counter
2497 *
2498 * @static
2499 * @param integer $id article id
2500 */
2501 function incViewCount( $id ) {
2502 $id = intval( $id );
2503 global $wgHitcounterUpdateFreq, $wgDBtype;
2504
2505 $dbw =& wfGetDB( DB_MASTER );
2506 $pageTable = $dbw->tableName( 'page' );
2507 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2508 $acchitsTable = $dbw->tableName( 'acchits' );
2509
2510 if( $wgHitcounterUpdateFreq <= 1 ) {
2511 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2512 return;
2513 }
2514
2515 # Not important enough to warrant an error page in case of failure
2516 $oldignore = $dbw->ignoreErrors( true );
2517
2518 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2519
2520 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2521 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2522 # Most of the time (or on SQL errors), skip row count check
2523 $dbw->ignoreErrors( $oldignore );
2524 return;
2525 }
2526
2527 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2528 $row = $dbw->fetchObject( $res );
2529 $rown = intval( $row->n );
2530 if( $rown >= $wgHitcounterUpdateFreq ){
2531 wfProfileIn( 'Article::incViewCount-collect' );
2532 $old_user_abort = ignore_user_abort( true );
2533
2534 if ($wgDBtype == 'mysql')
2535 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2536 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2537 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2538 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2539 'GROUP BY hc_id');
2540 $dbw->query("DELETE FROM $hitcounterTable");
2541 if ($wgDBtype == 'mysql') {
2542 $dbw->query('UNLOCK TABLES');
2543 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2544 'WHERE page_id = hc_id');
2545 }
2546 else {
2547 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2548 "FROM $acchitsTable WHERE page_id = hc_id");
2549 }
2550 $dbw->query("DROP TABLE $acchitsTable");
2551
2552 ignore_user_abort( $old_user_abort );
2553 wfProfileOut( 'Article::incViewCount-collect' );
2554 }
2555 $dbw->ignoreErrors( $oldignore );
2556 }
2557
2558 /**#@+
2559 * The onArticle*() functions are supposed to be a kind of hooks
2560 * which should be called whenever any of the specified actions
2561 * are done.
2562 *
2563 * This is a good place to put code to clear caches, for instance.
2564 *
2565 * This is called on page move and undelete, as well as edit
2566 * @static
2567 * @param $title_obj a title object
2568 */
2569
2570 static function onArticleCreate($title) {
2571 # The talk page isn't in the regular link tables, so we need to update manually:
2572 if ( $title->isTalkPage() ) {
2573 $other = $title->getSubjectPage();
2574 } else {
2575 $other = $title->getTalkPage();
2576 }
2577 $other->invalidateCache();
2578 $other->purgeSquid();
2579
2580 $title->touchLinks();
2581 $title->purgeSquid();
2582 }
2583
2584 static function onArticleDelete( $title ) {
2585 global $wgUseFileCache, $wgMessageCache;
2586
2587 $title->touchLinks();
2588 $title->purgeSquid();
2589
2590 # File cache
2591 if ( $wgUseFileCache ) {
2592 $cm = new HTMLFileCache( $title );
2593 @unlink( $cm->fileCacheName() );
2594 }
2595
2596 if( $title->getNamespace() == NS_MEDIAWIKI) {
2597 $wgMessageCache->replace( $title->getDBkey(), false );
2598 }
2599 }
2600
2601 /**
2602 * Purge caches on page update etc
2603 */
2604 static function onArticleEdit( $title ) {
2605 global $wgDeferredUpdateList, $wgUseFileCache;
2606
2607 // Invalidate caches of articles which include this page
2608 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2609 $wgDeferredUpdateList[] = $update;
2610
2611 # Purge squid for this page only
2612 $title->purgeSquid();
2613
2614 # Clear file cache
2615 if ( $wgUseFileCache ) {
2616 $cm = new HTMLFileCache( $title );
2617 @unlink( $cm->fileCacheName() );
2618 }
2619 }
2620
2621 /**#@-*/
2622
2623 /**
2624 * Info about this page
2625 * Called for ?action=info when $wgAllowPageInfo is on.
2626 *
2627 * @public
2628 */
2629 function info() {
2630 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2631
2632 if ( !$wgAllowPageInfo ) {
2633 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2634 return;
2635 }
2636
2637 $page = $this->mTitle->getSubjectPage();
2638
2639 $wgOut->setPagetitle( $page->getPrefixedText() );
2640 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2641
2642 # first, see if the page exists at all.
2643 $exists = $page->getArticleId() != 0;
2644 if( !$exists ) {
2645 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2646 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2647 } else {
2648 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2649 }
2650 } else {
2651 $dbr =& wfGetDB( DB_SLAVE );
2652 $wl_clause = array(
2653 'wl_title' => $page->getDBkey(),
2654 'wl_namespace' => $page->getNamespace() );
2655 $numwatchers = $dbr->selectField(
2656 'watchlist',
2657 'COUNT(*)',
2658 $wl_clause,
2659 __METHOD__,
2660 $this->getSelectOptions() );
2661
2662 $pageInfo = $this->pageCountInfo( $page );
2663 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2664
2665 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2666 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2667 if( $talkInfo ) {
2668 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2669 }
2670 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2671 if( $talkInfo ) {
2672 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2673 }
2674 $wgOut->addHTML( '</ul>' );
2675
2676 }
2677 }
2678
2679 /**
2680 * Return the total number of edits and number of unique editors
2681 * on a given page. If page does not exist, returns false.
2682 *
2683 * @param Title $title
2684 * @return array
2685 * @private
2686 */
2687 function pageCountInfo( $title ) {
2688 $id = $title->getArticleId();
2689 if( $id == 0 ) {
2690 return false;
2691 }
2692
2693 $dbr =& wfGetDB( DB_SLAVE );
2694
2695 $rev_clause = array( 'rev_page' => $id );
2696
2697 $edits = $dbr->selectField(
2698 'revision',
2699 'COUNT(rev_page)',
2700 $rev_clause,
2701 __METHOD__,
2702 $this->getSelectOptions() );
2703
2704 $authors = $dbr->selectField(
2705 'revision',
2706 'COUNT(DISTINCT rev_user_text)',
2707 $rev_clause,
2708 __METHOD__,
2709 $this->getSelectOptions() );
2710
2711 return array( 'edits' => $edits, 'authors' => $authors );
2712 }
2713
2714 /**
2715 * Return a list of templates used by this article.
2716 * Uses the templatelinks table
2717 *
2718 * @return array Array of Title objects
2719 */
2720 function getUsedTemplates() {
2721 $result = array();
2722 $id = $this->mTitle->getArticleID();
2723 if( $id == 0 ) {
2724 return array();
2725 }
2726
2727 $dbr =& wfGetDB( DB_SLAVE );
2728 $res = $dbr->select( array( 'templatelinks' ),
2729 array( 'tl_namespace', 'tl_title' ),
2730 array( 'tl_from' => $id ),
2731 'Article:getUsedTemplates' );
2732 if ( false !== $res ) {
2733 if ( $dbr->numRows( $res ) ) {
2734 while ( $row = $dbr->fetchObject( $res ) ) {
2735 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2736 }
2737 }
2738 }
2739 $dbr->freeResult( $res );
2740 return $result;
2741 }
2742
2743 /**
2744 * Return an auto-generated summary if the text provided is a redirect.
2745 *
2746 * @param string $text The wikitext to check
2747 * @return string '' or an appropriate summary
2748 */
2749 public static function getRedirectAutosummary( $text ) {
2750 $rt = Title::newFromRedirect( $text );
2751 if( is_object( $rt ) )
2752 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2753 else
2754 return '';
2755 }
2756
2757 /**
2758 * Return an auto-generated summary if the new text is much shorter than
2759 * the old text.
2760 *
2761 * @param string $oldtext The previous text of the page
2762 * @param string $text The submitted text of the page
2763 * @return string An appropriate autosummary, or an empty string.
2764 */
2765 public static function getBlankingAutosummary( $oldtext, $text ) {
2766 if ($oldtext!='' && $text=='') {
2767 return wfMsgForContent('autosumm-blank');
2768 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2769 #Removing more than 90% of the article
2770 global $wgContLang;
2771 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2772 return wfMsgForContent('autosumm-replace', $truncatedtext);
2773 } else {
2774 return '';
2775 }
2776 }
2777
2778 /**
2779 * Return an applicable autosummary if one exists for the given edit.
2780 * @param string $oldtext The previous text of the page.
2781 * @param string $newtext The submitted text of the page.
2782 * @param bitmask $flags A bitmask of flags submitted for the edit.
2783 * @return string An appropriate autosummary, or an empty string.
2784 */
2785 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2786
2787 # This code is UGLY UGLY UGLY.
2788 # Somebody PLEASE come up with a more elegant way to do it.
2789
2790 #Redirect autosummaries
2791 $summary = self::getRedirectAutosummary( $newtext );
2792
2793 if ($summary)
2794 return $summary;
2795
2796 #Blanking autosummaries
2797 if (!($flags & EDIT_NEW))
2798 $summary = self::getBlankingAutosummary( $oldtext, $newtext );
2799
2800 if ($summary)
2801 return $summary;
2802
2803 #New page autosummaries
2804 if ($flags & EDIT_NEW && strlen($newtext)) {
2805 #If they're making a new article, give its text, truncated, in the summary.
2806 global $wgContLang;
2807 $truncatedtext = $wgContLang->truncate(
2808 str_replace("\n", ' ', $newtext),
2809 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2810 '...' );
2811 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
2812 }
2813
2814 if ($summary)
2815 return $summary;
2816
2817 return $summary;
2818 }
2819
2820 /**
2821 * Add the primary page-view wikitext to the output buffer
2822 * Saves the text into the parser cache if possible.
2823 * Updates templatelinks if it is out of date.
2824 *
2825 * @param string $text
2826 * @param bool $cache
2827 */
2828 public function outputWikiText( $text, $cache = true ) {
2829 global $wgParser, $wgUser, $wgOut;
2830
2831 $popts = $wgOut->parserOptions();
2832 $popts->setTidy(true);
2833 $parserOutput = $wgParser->parse( $text, $this->mTitle,
2834 $popts, true, true, $this->getRevIdFetched() );
2835 $popts->setTidy(false);
2836 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
2837 $parserCache =& ParserCache::singleton();
2838 $parserCache->save( $parserOutput, $this, $wgUser );
2839 }
2840
2841 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
2842 // templatelinks table may have become out of sync,
2843 // especially if using variable-based transclusions.
2844 // For paranoia, check if things have changed and if
2845 // so apply updates to the database. This will ensure
2846 // that cascaded protections apply as soon as the changes
2847 // are visible.
2848
2849 # Get templates from templatelinks
2850 $id = $this->mTitle->getArticleID();
2851
2852 $tlTemplates = array();
2853
2854 $dbr =& wfGetDB( DB_SLAVE );
2855 $res = $dbr->select( array( 'templatelinks' ),
2856 array( 'tl_namespace', 'tl_title' ),
2857 array( 'tl_from' => $id ),
2858 'Article:getUsedTemplates' );
2859
2860 global $wgContLang;
2861
2862 if ( false !== $res ) {
2863 if ( $dbr->numRows( $res ) ) {
2864 while ( $row = $dbr->fetchObject( $res ) ) {
2865 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
2866 }
2867 }
2868 }
2869
2870 # Get templates from parser output.
2871 $poTemplates_allns = $parserOutput->getTemplates();
2872
2873 $poTemplates = array ();
2874 foreach ( $poTemplates_allns as $ns_templates ) {
2875 $poTemplates = array_merge( $poTemplates, $ns_templates );
2876 }
2877
2878 # Get the diff
2879 $templates_diff = array_diff( $poTemplates, $tlTemplates );
2880
2881 if ( count( $templates_diff ) > 0 ) {
2882 # Whee, link updates time.
2883 $u = new LinksUpdate( $this->mTitle, $parserOutput );
2884
2885 $dbw =& wfGetDb( DB_MASTER );
2886 $dbw->begin();
2887
2888 $u->doUpdate();
2889
2890 $dbw->commit();
2891 }
2892 }
2893
2894 $wgOut->addParserOutput( $parserOutput );
2895 }
2896
2897 }
2898
2899 ?>