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