API: Updating action=help credits to give Yuri and Vasiliev due credit
[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, $wgMessageCache;
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 $wgMessageCache->loadAllMessages();
151 $ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
152 } else {
153 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
154 }
155
156 return "<div class='noarticletext'>$ret</div>";
157 } else {
158 $this->loadContent();
159 wfProfileOut( __METHOD__ );
160 return $this->mContent;
161 }
162 }
163
164 /**
165 * This function returns the text of a section, specified by a number ($section).
166 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
167 * the first section before any such heading (section 0).
168 *
169 * If a section contains subsections, these are also returned.
170 *
171 * @param $text String: text to look in
172 * @param $section Integer: section number
173 * @return string text of the requested section
174 * @deprecated
175 */
176 function getSection($text,$section) {
177 global $wgParser;
178 return $wgParser->getSection( $text, $section );
179 }
180
181 /**
182 * @return int The oldid of the article that is to be shown, 0 for the
183 * current revision
184 */
185 function getOldID() {
186 if ( is_null( $this->mOldId ) ) {
187 $this->mOldId = $this->getOldIDFromRequest();
188 }
189 return $this->mOldId;
190 }
191
192 /**
193 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
194 *
195 * @return int The old id for the request
196 */
197 function getOldIDFromRequest() {
198 global $wgRequest;
199 $this->mRedirectUrl = false;
200 $oldid = $wgRequest->getVal( 'oldid' );
201 if ( isset( $oldid ) ) {
202 $oldid = intval( $oldid );
203 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
204 $nextid = $this->mTitle->getNextRevisionID( $oldid );
205 if ( $nextid ) {
206 $oldid = $nextid;
207 } else {
208 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
209 }
210 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
211 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
212 if ( $previd ) {
213 $oldid = $previd;
214 } else {
215 # TODO
216 }
217 }
218 # unused:
219 # $lastid = $oldid;
220 }
221
222 if ( !$oldid ) {
223 $oldid = 0;
224 }
225 return $oldid;
226 }
227
228 /**
229 * Load the revision (including text) into this object
230 */
231 function loadContent() {
232 if ( $this->mContentLoaded ) return;
233
234 # Query variables :P
235 $oldid = $this->getOldID();
236
237 # Pre-fill content with error message so that if something
238 # fails we'll have something telling us what we intended.
239 $this->mOldId = $oldid;
240 $this->fetchContent( $oldid );
241 }
242
243
244 /**
245 * Fetch a page record with the given conditions
246 * @param Database $dbr
247 * @param array $conditions
248 * @private
249 */
250 function pageData( $dbr, $conditions ) {
251 $fields = array(
252 'page_id',
253 'page_namespace',
254 'page_title',
255 'page_restrictions',
256 'page_counter',
257 'page_is_redirect',
258 'page_is_new',
259 'page_random',
260 'page_touched',
261 'page_latest',
262 'page_len',
263 );
264 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
265 $row = $dbr->selectRow(
266 'page',
267 $fields,
268 $conditions,
269 __METHOD__
270 );
271 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
272 return $row ;
273 }
274
275 /**
276 * @param Database $dbr
277 * @param Title $title
278 */
279 function pageDataFromTitle( $dbr, $title ) {
280 return $this->pageData( $dbr, array(
281 'page_namespace' => $title->getNamespace(),
282 'page_title' => $title->getDBkey() ) );
283 }
284
285 /**
286 * @param Database $dbr
287 * @param int $id
288 */
289 function pageDataFromId( $dbr, $id ) {
290 return $this->pageData( $dbr, array( 'page_id' => $id ) );
291 }
292
293 /**
294 * Set the general counter, title etc data loaded from
295 * some source.
296 *
297 * @param object $data
298 * @private
299 */
300 function loadPageData( $data = 'fromdb' ) {
301 if ( $data === 'fromdb' ) {
302 $dbr = $this->getDB();
303 $data = $this->pageDataFromId( $dbr, $this->getId() );
304 }
305
306 $lc =& LinkCache::singleton();
307 if ( $data ) {
308 $lc->addGoodLinkObj( $data->page_id, $this->mTitle );
309
310 $this->mTitle->mArticleID = $data->page_id;
311
312 # Old-fashioned restrictions.
313 $this->mTitle->loadRestrictions( $data->page_restrictions );
314
315 $this->mCounter = $data->page_counter;
316 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
317 $this->mIsRedirect = $data->page_is_redirect;
318 $this->mLatest = $data->page_latest;
319 } else {
320 if ( is_object( $this->mTitle ) ) {
321 $lc->addBadLinkObj( $this->mTitle );
322 }
323 $this->mTitle->mArticleID = 0;
324 }
325
326 $this->mDataLoaded = true;
327 }
328
329 /**
330 * Get text of an article from database
331 * Does *NOT* follow redirects.
332 * @param int $oldid 0 for whatever the latest revision is
333 * @return string
334 */
335 function fetchContent( $oldid = 0 ) {
336 if ( $this->mContentLoaded ) {
337 return $this->mContent;
338 }
339
340 $dbr = $this->getDB();
341
342 # Pre-fill content with error message so that if something
343 # fails we'll have something telling us what we intended.
344 $t = $this->mTitle->getPrefixedText();
345 if( $oldid ) {
346 $t .= ',oldid='.$oldid;
347 }
348 $this->mContent = wfMsg( 'missingarticle', $t ) ;
349
350 if( $oldid ) {
351 $revision = Revision::newFromId( $oldid );
352 if( is_null( $revision ) ) {
353 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
354 return false;
355 }
356 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
357 if( !$data ) {
358 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
359 return false;
360 }
361 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
362 $this->loadPageData( $data );
363 } else {
364 if( !$this->mDataLoaded ) {
365 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
366 if( !$data ) {
367 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
368 return false;
369 }
370 $this->loadPageData( $data );
371 }
372 $revision = Revision::newFromId( $this->mLatest );
373 if( is_null( $revision ) ) {
374 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$data->page_latest}\n" );
375 return false;
376 }
377 }
378
379 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
380 // We should instead work with the Revision object when we need it...
381 $this->mContent = $revision->revText(); // Loads if user is allowed
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->addWikiMsg( 'rev-deleted-text-permission' );
774 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
775 return;
776 } else {
777 $wgOut->addWikiMsg( '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->addWikiMsg('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->addWikiMsg( 'trackbackbox', $tbtext );
908 }
909
910 function deletetrackback() {
911 global $wgUser, $wgRequest, $wgOut, $wgTitle;
912
913 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
914 $wgOut->addWikiMsg( '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->addWikiMsg('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 if ( $this->getID() == 0 ) {
984 $text = false;
985 } else {
986 $text = $this->getContent();
987 }
988 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
989 }
990 $this->view();
991 }
992
993 /**
994 * Insert a new empty page record for this article.
995 * This *must* be followed up by creating a revision
996 * and running $this->updateToLatest( $rev_id );
997 * or else the record will be left in a funky state.
998 * Best if all done inside a transaction.
999 *
1000 * @param Database $dbw
1001 * @return int The newly created page_id key
1002 * @private
1003 */
1004 function insertOn( $dbw ) {
1005 wfProfileIn( __METHOD__ );
1006
1007 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1008 $dbw->insert( 'page', array(
1009 'page_id' => $page_id,
1010 'page_namespace' => $this->mTitle->getNamespace(),
1011 'page_title' => $this->mTitle->getDBkey(),
1012 'page_counter' => 0,
1013 'page_restrictions' => '',
1014 'page_is_redirect' => 0, # Will set this shortly...
1015 'page_is_new' => 1,
1016 'page_random' => wfRandom(),
1017 'page_touched' => $dbw->timestamp(),
1018 'page_latest' => 0, # Fill this in shortly...
1019 'page_len' => 0, # Fill this in shortly...
1020 ), __METHOD__ );
1021 $newid = $dbw->insertId();
1022
1023 $this->mTitle->resetArticleId( $newid );
1024
1025 wfProfileOut( __METHOD__ );
1026 return $newid;
1027 }
1028
1029 /**
1030 * Update the page record to point to a newly saved revision.
1031 *
1032 * @param Database $dbw
1033 * @param Revision $revision For ID number, and text used to set
1034 length and redirect status fields
1035 * @param int $lastRevision If given, will not overwrite the page field
1036 * when different from the currently set value.
1037 * Giving 0 indicates the new page flag should
1038 * be set on.
1039 * @param bool $lastRevIsRedirect If given, will optimize adding and
1040 * removing rows in redirect table.
1041 * @return bool true on success, false on failure
1042 * @private
1043 */
1044 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1045 wfProfileIn( __METHOD__ );
1046
1047 $text = $revision->getText();
1048 $rt = Title::newFromRedirect( $text );
1049
1050 $conditions = array( 'page_id' => $this->getId() );
1051 if( !is_null( $lastRevision ) ) {
1052 # An extra check against threads stepping on each other
1053 $conditions['page_latest'] = $lastRevision;
1054 }
1055
1056 $dbw->update( 'page',
1057 array( /* SET */
1058 'page_latest' => $revision->getId(),
1059 'page_touched' => $dbw->timestamp(),
1060 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1061 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1062 'page_len' => strlen( $text ),
1063 ),
1064 $conditions,
1065 __METHOD__ );
1066
1067 $result = $dbw->affectedRows() != 0;
1068
1069 if ($result) {
1070 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1071 }
1072
1073 wfProfileOut( __METHOD__ );
1074 return $result;
1075 }
1076
1077 /**
1078 * Add row to the redirect table if this is a redirect, remove otherwise.
1079 *
1080 * @param Database $dbw
1081 * @param $redirectTitle a title object pointing to the redirect target,
1082 * or NULL if this is not a redirect
1083 * @param bool $lastRevIsRedirect If given, will optimize adding and
1084 * removing rows in redirect table.
1085 * @return bool true on success, false on failure
1086 * @private
1087 */
1088 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1089
1090 // Always update redirects (target link might have changed)
1091 // Update/Insert if we don't know if the last revision was a redirect or not
1092 // Delete if changing from redirect to non-redirect
1093 $isRedirect = !is_null($redirectTitle);
1094 if ($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1095
1096 wfProfileIn( __METHOD__ );
1097
1098 if ($isRedirect) {
1099
1100 // This title is a redirect, Add/Update row in the redirect table
1101 $set = array( /* SET */
1102 'rd_namespace' => $redirectTitle->getNamespace(),
1103 'rd_title' => $redirectTitle->getDBkey(),
1104 'rd_from' => $this->getId(),
1105 );
1106
1107 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1108 } else {
1109 // This is not a redirect, remove row from redirect table
1110 $where = array( 'rd_from' => $this->getId() );
1111 $dbw->delete( 'redirect', $where, __METHOD__);
1112 }
1113
1114 wfProfileOut( __METHOD__ );
1115 return ( $dbw->affectedRows() != 0 );
1116 }
1117
1118 return true;
1119 }
1120
1121 /**
1122 * If the given revision is newer than the currently set page_latest,
1123 * update the page record. Otherwise, do nothing.
1124 *
1125 * @param Database $dbw
1126 * @param Revision $revision
1127 */
1128 function updateIfNewerOn( &$dbw, $revision ) {
1129 wfProfileIn( __METHOD__ );
1130
1131 $row = $dbw->selectRow(
1132 array( 'revision', 'page' ),
1133 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1134 array(
1135 'page_id' => $this->getId(),
1136 'page_latest=rev_id' ),
1137 __METHOD__ );
1138 if( $row ) {
1139 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1140 wfProfileOut( __METHOD__ );
1141 return false;
1142 }
1143 $prev = $row->rev_id;
1144 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1145 } else {
1146 # No or missing previous revision; mark the page as new
1147 $prev = 0;
1148 $lastRevIsRedirect = null;
1149 }
1150
1151 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1152 wfProfileOut( __METHOD__ );
1153 return $ret;
1154 }
1155
1156 /**
1157 * @return string Complete article text, or null if error
1158 */
1159 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1160 wfProfileIn( __METHOD__ );
1161
1162 if( $section == '' ) {
1163 // Whole-page edit; let the text through unmolested.
1164 } else {
1165 if( is_null( $edittime ) ) {
1166 $rev = Revision::newFromTitle( $this->mTitle );
1167 } else {
1168 $dbw = wfGetDB( DB_MASTER );
1169 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1170 }
1171 if( is_null( $rev ) ) {
1172 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1173 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1174 return null;
1175 }
1176 $oldtext = $rev->getText();
1177
1178 if( $section == 'new' ) {
1179 # Inserting a new section
1180 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1181 $text = strlen( trim( $oldtext ) ) > 0
1182 ? "{$oldtext}\n\n{$subject}{$text}"
1183 : "{$subject}{$text}";
1184 } else {
1185 # Replacing an existing section; roll out the big guns
1186 global $wgParser;
1187 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1188 }
1189
1190 }
1191
1192 wfProfileOut( __METHOD__ );
1193 return $text;
1194 }
1195
1196 /**
1197 * @deprecated use Article::doEdit()
1198 */
1199 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1200 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1201 ( $isminor ? EDIT_MINOR : 0 ) |
1202 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1203 ( $bot ? EDIT_FORCE_BOT : 0 );
1204
1205 # If this is a comment, add the summary as headline
1206 if ( $comment && $summary != "" ) {
1207 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1208 }
1209
1210 $this->doEdit( $text, $summary, $flags );
1211
1212 $dbw = wfGetDB( DB_MASTER );
1213 if ($watchthis) {
1214 if (!$this->mTitle->userIsWatching()) {
1215 $dbw->begin();
1216 $this->doWatch();
1217 $dbw->commit();
1218 }
1219 } else {
1220 if ( $this->mTitle->userIsWatching() ) {
1221 $dbw->begin();
1222 $this->doUnwatch();
1223 $dbw->commit();
1224 }
1225 }
1226 $this->doRedirect( $this->isRedirect( $text ) );
1227 }
1228
1229 /**
1230 * @deprecated use Article::doEdit()
1231 */
1232 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1233 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1234 ( $minor ? EDIT_MINOR : 0 ) |
1235 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1236
1237 $good = $this->doEdit( $text, $summary, $flags );
1238 if ( $good ) {
1239 $dbw = wfGetDB( DB_MASTER );
1240 if ($watchthis) {
1241 if (!$this->mTitle->userIsWatching()) {
1242 $dbw->begin();
1243 $this->doWatch();
1244 $dbw->commit();
1245 }
1246 } else {
1247 if ( $this->mTitle->userIsWatching() ) {
1248 $dbw->begin();
1249 $this->doUnwatch();
1250 $dbw->commit();
1251 }
1252 }
1253
1254 $extraq = ''; // Give extensions a chance to modify URL query on update
1255 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1256
1257 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1258 }
1259 return $good;
1260 }
1261
1262 /**
1263 * Article::doEdit()
1264 *
1265 * Change an existing article or create a new article. Updates RC and all necessary caches,
1266 * optionally via the deferred update array.
1267 *
1268 * $wgUser must be set before calling this function.
1269 *
1270 * @param string $text New text
1271 * @param string $summary Edit summary
1272 * @param integer $flags bitfield:
1273 * EDIT_NEW
1274 * Article is known or assumed to be non-existent, create a new one
1275 * EDIT_UPDATE
1276 * Article is known or assumed to be pre-existing, update it
1277 * EDIT_MINOR
1278 * Mark this edit minor, if the user is allowed to do so
1279 * EDIT_SUPPRESS_RC
1280 * Do not log the change in recentchanges
1281 * EDIT_FORCE_BOT
1282 * Mark the edit a "bot" edit regardless of user rights
1283 * EDIT_DEFER_UPDATES
1284 * Defer some of the updates until the end of index.php
1285 * EDIT_AUTOSUMMARY
1286 * Fill in blank summaries with generated text where possible
1287 *
1288 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1289 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1290 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1291 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1292 * to MediaWiki's performance-optimised locking strategy.
1293 *
1294 * @return bool success
1295 */
1296 function doEdit( $text, $summary, $flags = 0 ) {
1297 global $wgUser, $wgDBtransactions;
1298
1299 wfProfileIn( __METHOD__ );
1300 $good = true;
1301
1302 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1303 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1304 if ( $aid ) {
1305 $flags |= EDIT_UPDATE;
1306 } else {
1307 $flags |= EDIT_NEW;
1308 }
1309 }
1310
1311 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1312 &$summary, $flags & EDIT_MINOR,
1313 null, null, &$flags ) ) )
1314 {
1315 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1316 wfProfileOut( __METHOD__ );
1317 return false;
1318 }
1319
1320 # Silently ignore EDIT_MINOR if not allowed
1321 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1322 $bot = $flags & EDIT_FORCE_BOT;
1323
1324 $oldtext = $this->getContent();
1325 $oldsize = strlen( $oldtext );
1326
1327 # Provide autosummaries if one is not provided.
1328 if ($flags & EDIT_AUTOSUMMARY && $summary == '')
1329 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1330
1331 $editInfo = $this->prepareTextForEdit( $text );
1332 $text = $editInfo->pst;
1333 $newsize = strlen( $text );
1334
1335 $dbw = wfGetDB( DB_MASTER );
1336 $now = wfTimestampNow();
1337
1338 if ( $flags & EDIT_UPDATE ) {
1339 # Update article, but only if changed.
1340
1341 # Make sure the revision is either completely inserted or not inserted at all
1342 if( !$wgDBtransactions ) {
1343 $userAbort = ignore_user_abort( true );
1344 }
1345
1346 $lastRevision = 0;
1347 $revisionId = 0;
1348
1349 $changed = ( strcmp( $text, $oldtext ) != 0 );
1350
1351 if ( $changed ) {
1352 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1353 - (int)$this->isCountable( $oldtext );
1354 $this->mTotalAdjustment = 0;
1355
1356 $lastRevision = $dbw->selectField(
1357 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1358
1359 if ( !$lastRevision ) {
1360 # Article gone missing
1361 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1362 wfProfileOut( __METHOD__ );
1363 return false;
1364 }
1365
1366 $revision = new Revision( array(
1367 'page' => $this->getId(),
1368 'comment' => $summary,
1369 'minor_edit' => $isminor,
1370 'text' => $text
1371 ) );
1372
1373 $dbw->begin();
1374 $revisionId = $revision->insertOn( $dbw );
1375
1376 # Update page
1377 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1378
1379 if( !$ok ) {
1380 /* Belated edit conflict! Run away!! */
1381 $good = false;
1382 $dbw->rollback();
1383 } else {
1384 # Update recentchanges
1385 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1386 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1387 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1388 $revisionId );
1389
1390 # Mark as patrolled if the user can do so
1391 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1392 RecentChange::markPatrolled( $rcid );
1393 PatrolLog::record( $rcid, true );
1394 }
1395 }
1396 $wgUser->incEditCount();
1397 $dbw->commit();
1398 }
1399 } else {
1400 $revision = null;
1401 // Keep the same revision ID, but do some updates on it
1402 $revisionId = $this->getRevIdFetched();
1403 // Update page_touched, this is usually implicit in the page update
1404 // Other cache updates are done in onArticleEdit()
1405 $this->mTitle->invalidateCache();
1406 }
1407
1408 if( !$wgDBtransactions ) {
1409 ignore_user_abort( $userAbort );
1410 }
1411
1412 if ( $good ) {
1413 # Invalidate cache of this article and all pages using this article
1414 # as a template. Partly deferred.
1415 Article::onArticleEdit( $this->mTitle );
1416
1417 # Update links tables, site stats, etc.
1418 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1419 }
1420 } else {
1421 # Create new article
1422
1423 # Set statistics members
1424 # We work out if it's countable after PST to avoid counter drift
1425 # when articles are created with {{subst:}}
1426 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1427 $this->mTotalAdjustment = 1;
1428
1429 $dbw->begin();
1430
1431 # Add the page record; stake our claim on this title!
1432 # This will fail with a database query exception if the article already exists
1433 $newid = $this->insertOn( $dbw );
1434
1435 # Save the revision text...
1436 $revision = new Revision( array(
1437 'page' => $newid,
1438 'comment' => $summary,
1439 'minor_edit' => $isminor,
1440 'text' => $text
1441 ) );
1442 $revisionId = $revision->insertOn( $dbw );
1443
1444 $this->mTitle->resetArticleID( $newid );
1445
1446 # Update the page record with revision data
1447 $this->updateRevisionOn( $dbw, $revision, 0 );
1448
1449 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1450 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1451 '', strlen( $text ), $revisionId );
1452 # Mark as patrolled if the user can
1453 if( ($GLOBALS['wgUseRCPatrol'] || $GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1454 RecentChange::markPatrolled( $rcid );
1455 PatrolLog::record( $rcid, true );
1456 }
1457 }
1458 $wgUser->incEditCount();
1459 $dbw->commit();
1460
1461 # Update links, etc.
1462 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1463
1464 # Clear caches
1465 Article::onArticleCreate( $this->mTitle );
1466
1467 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1468 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1469 }
1470
1471 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1472 wfDoUpdates();
1473 }
1474
1475 if ( $good ) {
1476 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1477 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1478 }
1479
1480 wfProfileOut( __METHOD__ );
1481 return $good;
1482 }
1483
1484 /**
1485 * @deprecated wrapper for doRedirect
1486 */
1487 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1488 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1489 }
1490
1491 /**
1492 * Output a redirect back to the article.
1493 * This is typically used after an edit.
1494 *
1495 * @param boolean $noRedir Add redirect=no
1496 * @param string $sectionAnchor section to redirect to, including "#"
1497 * @param string $extraq, extra query params
1498 */
1499 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1500 global $wgOut;
1501 if ( $noRedir ) {
1502 $query = 'redirect=no';
1503 if( $extraq )
1504 $query .= "&$query";
1505 } else {
1506 $query = $extraq;
1507 }
1508 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1509 }
1510
1511 /**
1512 * Mark this particular edit/page as patrolled
1513 */
1514 function markpatrolled() {
1515 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1516 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1517
1518 # Check patrol config options
1519
1520 if ( !($wgUseNPPatrol || $wgUseRCPatrol)) {
1521 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1522 return;
1523 }
1524
1525 # If we haven't been given an rc_id value, we can't do anything
1526 $rcid = (int) $wgRequest->getVal('rcid');
1527 $rc = $rcid ? RecentChange::newFromId($rcid) : null;
1528 if ( is_null ( $rc ) )
1529 {
1530 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1531 return;
1532 }
1533
1534 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW) {
1535 // Only new pages can be patrolled if the general patrolling is off....???
1536 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1537 // front end here?
1538 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1539 return;
1540 }
1541
1542 # Check permissions
1543 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'patrol', $wgUser );
1544
1545 if (count($permission_errors)>0)
1546 {
1547 $wgOut->showPermissionsErrorPage( $permission_errors );
1548 return;
1549 }
1550
1551 # Handle the 'MarkPatrolled' hook
1552 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1553 return;
1554 }
1555
1556 #It would be nice to see where the user had actually come from, but for now just guess
1557 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1558 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1559
1560 # If it's left up to us, check that the user is allowed to patrol this edit
1561 # If the user has the "autopatrol" right, then we'll assume there are no
1562 # other conditions stopping them doing so
1563 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1564 $rc = RecentChange::newFromId( $rcid );
1565 # Graceful error handling, as we've done before here...
1566 # (If the recent change doesn't exist, then it doesn't matter whether
1567 # the user is allowed to patrol it or not; nothing is going to happen
1568 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1569 # The user made this edit, and can't patrol it
1570 # Tell them so, and then back off
1571 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1572 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1573 $wgOut->returnToMain( false, $return );
1574 return;
1575 }
1576 }
1577
1578 # Check that the revision isn't patrolled already
1579 # Prevents duplicate log entries
1580 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1581 # Mark the edit as patrolled
1582 RecentChange::markPatrolled( $rcid );
1583 PatrolLog::record( $rcid );
1584 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1585 }
1586
1587 # Inform the user
1588 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1589 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1590 $wgOut->returnToMain( false, $return );
1591 }
1592
1593 /**
1594 * User-interface handler for the "watch" action
1595 */
1596
1597 function watch() {
1598
1599 global $wgUser, $wgOut;
1600
1601 if ( $wgUser->isAnon() ) {
1602 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1603 return;
1604 }
1605 if ( wfReadOnly() ) {
1606 $wgOut->readOnlyPage();
1607 return;
1608 }
1609
1610 if( $this->doWatch() ) {
1611 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1612 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1613
1614 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1615 }
1616
1617 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1618 }
1619
1620 /**
1621 * Add this page to $wgUser's watchlist
1622 * @return bool true on successful watch operation
1623 */
1624 function doWatch() {
1625 global $wgUser;
1626 if( $wgUser->isAnon() ) {
1627 return false;
1628 }
1629
1630 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1631 $wgUser->addWatch( $this->mTitle );
1632
1633 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1634 }
1635
1636 return false;
1637 }
1638
1639 /**
1640 * User interface handler for the "unwatch" action.
1641 */
1642 function unwatch() {
1643
1644 global $wgUser, $wgOut;
1645
1646 if ( $wgUser->isAnon() ) {
1647 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1648 return;
1649 }
1650 if ( wfReadOnly() ) {
1651 $wgOut->readOnlyPage();
1652 return;
1653 }
1654
1655 if( $this->doUnwatch() ) {
1656 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1657 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1658
1659 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1660 }
1661
1662 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1663 }
1664
1665 /**
1666 * Stop watching a page
1667 * @return bool true on successful unwatch
1668 */
1669 function doUnwatch() {
1670 global $wgUser;
1671 if( $wgUser->isAnon() ) {
1672 return false;
1673 }
1674
1675 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1676 $wgUser->removeWatch( $this->mTitle );
1677
1678 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1679 }
1680
1681 return false;
1682 }
1683
1684 /**
1685 * action=protect handler
1686 */
1687 function protect() {
1688 $form = new ProtectionForm( $this );
1689 $form->execute();
1690 }
1691
1692 /**
1693 * action=unprotect handler (alias)
1694 */
1695 function unprotect() {
1696 $this->protect();
1697 }
1698
1699 /**
1700 * Update the article's restriction field, and leave a log entry.
1701 *
1702 * @param array $limit set of restriction keys
1703 * @param string $reason
1704 * @return bool true on success
1705 */
1706 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1707 global $wgUser, $wgRestrictionTypes, $wgContLang;
1708
1709 $id = $this->mTitle->getArticleID();
1710 if( array() != $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser ) || wfReadOnly() || $id == 0 ) {
1711 return false;
1712 }
1713
1714 if (!$cascade) {
1715 $cascade = false;
1716 }
1717
1718 // Take this opportunity to purge out expired restrictions
1719 Title::purgeExpiredRestrictions();
1720
1721 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1722 # we expect a single selection, but the schema allows otherwise.
1723 $current = array();
1724 foreach( $wgRestrictionTypes as $action )
1725 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1726
1727 $current = Article::flattenRestrictions( $current );
1728 $updated = Article::flattenRestrictions( $limit );
1729
1730 $changed = ( $current != $updated );
1731 $changed = $changed || ($this->mTitle->areRestrictionsCascading() != $cascade);
1732 $changed = $changed || ($this->mTitle->mRestrictionsExpiry != $expiry);
1733 $protect = ( $updated != '' );
1734
1735 # If nothing's changed, do nothing
1736 if( $changed ) {
1737 global $wgGroupPermissions;
1738 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1739
1740 $dbw = wfGetDB( DB_MASTER );
1741
1742 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1743
1744 $expiry_description = '';
1745 if ( $encodedExpiry != 'infinity' ) {
1746 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1747 }
1748
1749 # Prepare a null revision to be added to the history
1750 $modified = $current != '' && $protect;
1751 if ( $protect ) {
1752 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1753 } else {
1754 $comment_type = 'unprotectedarticle';
1755 }
1756 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1757
1758 foreach( $limit as $action => $restrictions ) {
1759 # Check if the group level required to edit also can protect pages
1760 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1761 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1762 $wgGroupPermissions[$restrictions]['protect'] );
1763 }
1764
1765 $cascade_description = '';
1766 if ($cascade) {
1767 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1768 }
1769
1770 if( $reason )
1771 $comment .= ": $reason";
1772 if( $protect )
1773 $comment .= " [$updated]";
1774 if ( $expiry_description && $protect )
1775 $comment .= "$expiry_description";
1776 if ( $cascade )
1777 $comment .= "$cascade_description";
1778
1779 # Update restrictions table
1780 foreach( $limit as $action => $restrictions ) {
1781 if ($restrictions != '' ) {
1782 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1783 array( 'pr_page' => $id, 'pr_type' => $action
1784 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
1785 , 'pr_expiry' => $encodedExpiry ), __METHOD__ );
1786 } else {
1787 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1788 'pr_type' => $action ), __METHOD__ );
1789 }
1790 }
1791
1792 # Insert a null revision
1793 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1794 $nullRevId = $nullRevision->insertOn( $dbw );
1795
1796 # Update page record
1797 $dbw->update( 'page',
1798 array( /* SET */
1799 'page_touched' => $dbw->timestamp(),
1800 'page_restrictions' => '',
1801 'page_latest' => $nullRevId
1802 ), array( /* WHERE */
1803 'page_id' => $id
1804 ), 'Article::protect'
1805 );
1806 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1807
1808 # Update the protection log
1809 $log = new LogPage( 'protect' );
1810
1811
1812
1813 if( $protect ) {
1814 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1815 } else {
1816 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1817 }
1818
1819 } # End hook
1820 } # End "changed" check
1821
1822 return true;
1823 }
1824
1825 /**
1826 * Take an array of page restrictions and flatten it to a string
1827 * suitable for insertion into the page_restrictions field.
1828 * @param array $limit
1829 * @return string
1830 * @private
1831 */
1832 function flattenRestrictions( $limit ) {
1833 if( !is_array( $limit ) ) {
1834 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1835 }
1836 $bits = array();
1837 ksort( $limit );
1838 foreach( $limit as $action => $restrictions ) {
1839 if( $restrictions != '' ) {
1840 $bits[] = "$action=$restrictions";
1841 }
1842 }
1843 return implode( ':', $bits );
1844 }
1845
1846 /**
1847 * Auto-generates a deletion reason
1848 * @param bool &$hasHistory Whether the page has a history
1849 */
1850 public function generateReason(&$hasHistory)
1851 {
1852 global $wgContLang;
1853 $dbw = wfGetDB(DB_MASTER);
1854 // Get the last revision
1855 $rev = Revision::newFromTitle($this->mTitle);
1856 if(is_null($rev))
1857 return false;
1858 // Get the article's contents
1859 $contents = $rev->getText();
1860 $blank = false;
1861 // If the page is blank, use the text from the previous revision,
1862 // which can only be blank if there's a move/import/protect dummy revision involved
1863 if($contents == '')
1864 {
1865 $prev = $rev->getPrevious();
1866 if($prev)
1867 {
1868 $contents = $prev->getText();
1869 $blank = true;
1870 }
1871 }
1872
1873 // Find out if there was only one contributor
1874 // Only scan the last 20 revisions
1875 $limit = 20;
1876 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__,
1877 array('LIMIT' => $limit));
1878 if($res === false)
1879 // This page has no revisions, which is very weird
1880 return false;
1881 if($res->numRows() > 1)
1882 $hasHistory = true;
1883 else
1884 $hasHistory = false;
1885 $row = $dbw->fetchObject($res);
1886 $onlyAuthor = $row->rev_user_text;
1887 // Try to find a second contributor
1888 while( $row = $dbw->fetchObject($res) ) {
1889 if($row->rev_user_text != $onlyAuthor) {
1890 $onlyAuthor = false;
1891 break;
1892 }
1893 }
1894 $dbw->freeResult($res);
1895
1896 // Generate the summary with a '$1' placeholder
1897 if($blank) {
1898 // The current revision is blank and the one before is also
1899 // blank. It's just not our lucky day
1900 $reason = wfMsgForContent('exbeforeblank', '$1');
1901 } else {
1902 if($onlyAuthor)
1903 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1904 else
1905 $reason = wfMsgForContent('excontent', '$1');
1906 }
1907
1908 // Replace newlines with spaces to prevent uglyness
1909 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1910 // Calculate the maximum amount of chars to get
1911 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1912 $maxLength = 255 - (strlen($reason) - 2) - 3;
1913 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1914 // Remove possible unfinished links
1915 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1916 // Now replace the '$1' placeholder
1917 $reason = str_replace( '$1', $contents, $reason );
1918 return $reason;
1919 }
1920
1921
1922 /*
1923 * UI entry point for page deletion
1924 */
1925 function delete() {
1926 global $wgUser, $wgOut, $wgRequest;
1927
1928 $confirm = $wgRequest->wasPosted() &&
1929 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1930
1931 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1932 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
1933
1934 $reason = $this->DeleteReasonList;
1935
1936 if ( $reason != 'other' && $this->DeleteReason != '') {
1937 // Entry from drop down menu + additional comment
1938 $reason .= ': ' . $this->DeleteReason;
1939 } elseif ( $reason == 'other' ) {
1940 $reason = $this->DeleteReason;
1941 }
1942 # Flag to hide all contents of the archived revisions
1943 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('deleterevision');
1944
1945 # This code desperately needs to be totally rewritten
1946
1947 # Read-only check...
1948 if ( wfReadOnly() ) {
1949 $wgOut->readOnlyPage();
1950 return;
1951 }
1952
1953 # Check permissions
1954 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1955
1956 if (count($permission_errors)>0) {
1957 $wgOut->showPermissionsErrorPage( $permission_errors );
1958 return;
1959 }
1960
1961 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
1962
1963 # Better double-check that it hasn't been deleted yet!
1964 $dbw = wfGetDB( DB_MASTER );
1965 $conds = $this->mTitle->pageCond();
1966 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1967 if ( $latest === false ) {
1968 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1969 return;
1970 }
1971
1972 # Hack for big sites
1973 $bigHistory = $this->isBigDeletion();
1974 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
1975 global $wgLang, $wgDeleteRevisionsLimit;
1976 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
1977 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
1978 return;
1979 }
1980
1981 if( $confirm ) {
1982 $this->doDelete( $reason, $suppress );
1983 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1984 $this->doWatch();
1985 } elseif( $this->mTitle->userIsWatching() ) {
1986 $this->doUnwatch();
1987 }
1988 return;
1989 }
1990
1991 // Generate deletion reason
1992 $hasHistory = false;
1993 if ( !$reason ) $reason = $this->generateReason($hasHistory);
1994
1995 // If the page has a history, insert a warning
1996 if( $hasHistory && !$confirm ) {
1997 $skin=$wgUser->getSkin();
1998 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1999 if( $bigHistory ) {
2000 global $wgLang, $wgDeleteRevisionsLimit;
2001 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2002 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2003 }
2004 }
2005
2006 return $this->confirmDelete( '', $reason );
2007 }
2008
2009 /**
2010 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2011 */
2012 function isBigDeletion() {
2013 global $wgDeleteRevisionsLimit;
2014 if( $wgDeleteRevisionsLimit ) {
2015 $revCount = $this->estimateRevisionCount();
2016 return $revCount > $wgDeleteRevisionsLimit;
2017 }
2018 return false;
2019 }
2020
2021 /**
2022 * @return int approximate revision count
2023 */
2024 function estimateRevisionCount() {
2025 $dbr = wfGetDB();
2026 // For an exact count...
2027 //return $dbr->selectField( 'revision', 'COUNT(*)',
2028 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2029 return $dbr->estimateRowCount( 'revision', '*',
2030 array( 'rev_page' => $this->getId() ), __METHOD__ );
2031 }
2032
2033 /**
2034 * Get the last N authors
2035 * @param int $num Number of revisions to get
2036 * @param string $revLatest The latest rev_id, selected from the master (optional)
2037 * @return array Array of authors, duplicates not removed
2038 */
2039 function getLastNAuthors( $num, $revLatest = 0 ) {
2040 wfProfileIn( __METHOD__ );
2041
2042 // First try the slave
2043 // If that doesn't have the latest revision, try the master
2044 $continue = 2;
2045 $db = wfGetDB( DB_SLAVE );
2046 do {
2047 $res = $db->select( array( 'page', 'revision' ),
2048 array( 'rev_id', 'rev_user_text' ),
2049 array(
2050 'page_namespace' => $this->mTitle->getNamespace(),
2051 'page_title' => $this->mTitle->getDBkey(),
2052 'rev_page = page_id'
2053 ), __METHOD__, $this->getSelectOptions( array(
2054 'ORDER BY' => 'rev_timestamp DESC',
2055 'LIMIT' => $num
2056 ) )
2057 );
2058 if ( !$res ) {
2059 wfProfileOut( __METHOD__ );
2060 return array();
2061 }
2062 $row = $db->fetchObject( $res );
2063 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2064 $db = wfGetDB( DB_MASTER );
2065 $continue--;
2066 } else {
2067 $continue = 0;
2068 }
2069 } while ( $continue );
2070
2071 $authors = array( $row->rev_user_text );
2072 while ( $row = $db->fetchObject( $res ) ) {
2073 $authors[] = $row->rev_user_text;
2074 }
2075 wfProfileOut( __METHOD__ );
2076 return $authors;
2077 }
2078
2079 /**
2080 * Output deletion confirmation dialog
2081 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2082 * @param $reason string Prefilled reason
2083 */
2084 function confirmDelete( $par, $reason ) {
2085 global $wgOut, $wgUser, $wgContLang;
2086 $align = $wgContLang->isRtl() ? 'left' : 'right';
2087
2088 wfDebug( "Article::confirmDelete\n" );
2089
2090 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2091 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2092 $wgOut->addWikiMsg( 'confirmdeletetext' );
2093
2094 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2095 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2096 $suppress .= Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2097 $suppress .= "</td></tr>";
2098 } else {
2099 $suppress = '';
2100 }
2101
2102 $form = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2103 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2104 Xml::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2105 Xml::openElement( 'table' ) .
2106 "<tr id=\"wpDeleteReasonListRow\">
2107 <td align='$align'>" .
2108 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2109 "</td>
2110 <td>" .
2111 Xml::listDropDown( 'wpDeleteReasonList',
2112 wfMsgForContent( 'deletereason-dropdown' ),
2113 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2114 "</td>
2115 </tr>
2116 <tr id=\"wpDeleteReasonRow\">
2117 <td align='$align'>" .
2118 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2119 "</td>
2120 <td>" .
2121 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2122 "</td>
2123 </tr>
2124 <tr>
2125 <td></td>
2126 <td>" .
2127 Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '3' ) ) .
2128 "</td>
2129 </tr>
2130 $suppress
2131 <tr>
2132 <td></td>
2133 <td>" .
2134 Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2135 "</td>
2136 </tr>" .
2137 Xml::closeElement( 'table' ) .
2138 Xml::closeElement( 'fieldset' ) .
2139 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2140 Xml::closeElement( 'form' );
2141
2142 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2143 $skin = $wgUser->getSkin();
2144 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2145 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2146 }
2147
2148 $wgOut->addHTML( $form );
2149 $this->showLogExtract( $wgOut );
2150 }
2151
2152
2153 /**
2154 * Show relevant lines from the deletion log
2155 */
2156 function showLogExtract( $out ) {
2157 $out->addHtml( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2158 $logViewer = new LogViewer(
2159 new LogReader(
2160 new FauxRequest(
2161 array( 'page' => $this->mTitle->getPrefixedText(),
2162 'type' => 'delete' ) ) ) );
2163 $logViewer->showList( $out );
2164 }
2165
2166
2167 /**
2168 * Perform a deletion and output success or failure messages
2169 */
2170 function doDelete( $reason, $suppress = false ) {
2171 global $wgOut, $wgUser;
2172 wfDebug( __METHOD__."\n" );
2173
2174 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2175 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2176 $deleted = $this->mTitle->getPrefixedText();
2177
2178 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2179 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2180
2181 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2182
2183 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2184 $wgOut->returnToMain( false );
2185 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2186 } else {
2187 $wgOut->showFatalError( wfMsg( 'cannotdelete' ).'<br/>'.wfMsg('cannotdelete-merge') );
2188 }
2189 }
2190 }
2191
2192 /**
2193 * Back-end article deletion
2194 * Deletes the article with database consistency, writes logs, purges caches
2195 * Returns success
2196 */
2197 function doDeleteArticle( $reason, $suppress = false ) {
2198 global $wgUseSquid, $wgDeferredUpdateList;
2199 global $wgUseTrackbacks;
2200
2201 wfDebug( __METHOD__."\n" );
2202
2203 $dbw = wfGetDB( DB_MASTER );
2204 $ns = $this->mTitle->getNamespace();
2205 $t = $this->mTitle->getDBkey();
2206 $id = $this->mTitle->getArticleID();
2207
2208 if ( $t == '' || $id == 0 ) {
2209 return false;
2210 }
2211
2212 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2213 array_push( $wgDeferredUpdateList, $u );
2214
2215 // Bitfields to further suppress the content
2216 if ( $suppress ) {
2217 $bitfield = 0;
2218 // This should be 15...
2219 $bitfield |= Revision::DELETED_TEXT;
2220 $bitfield |= Revision::DELETED_COMMENT;
2221 $bitfield |= Revision::DELETED_USER;
2222 $bitfield |= Revision::DELETED_RESTRICTED;
2223 } else {
2224 $bitfield = 'rev_deleted';
2225 }
2226
2227 // For now, shunt the revision data into the archive table.
2228 // Text is *not* removed from the text table; bulk storage
2229 // is left intact to avoid breaking block-compression or
2230 // immutable storage schemes.
2231 //
2232 // For backwards compatibility, note that some older archive
2233 // table entries will have ar_text and ar_flags fields still.
2234 //
2235 // In the future, we may keep revisions and mark them with
2236 // the rev_deleted field, which is reserved for this purpose.
2237 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2238 array(
2239 'ar_namespace' => 'page_namespace',
2240 'ar_title' => 'page_title',
2241 'ar_comment' => 'rev_comment',
2242 'ar_user' => 'rev_user',
2243 'ar_user_text' => 'rev_user_text',
2244 'ar_timestamp' => 'rev_timestamp',
2245 'ar_minor_edit' => 'rev_minor_edit',
2246 'ar_rev_id' => 'rev_id',
2247 'ar_text_id' => 'rev_text_id',
2248 'ar_text' => '\'\'', // Be explicit to appease
2249 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2250 'ar_len' => 'rev_len',
2251 'ar_page_id' => 'page_id',
2252 'ar_deleted' => $bitfield
2253 ), array(
2254 'page_id' => $id,
2255 'page_id = rev_page'
2256 ), __METHOD__
2257 );
2258
2259 # Delete restrictions for it
2260 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2261
2262 # Now that it's safely backed up, delete it
2263 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2264
2265 # If using cascading deletes, we can skip some explicit deletes
2266 if ( !$dbw->cascadingDeletes() ) {
2267
2268 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2269
2270 if ($wgUseTrackbacks)
2271 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2272
2273 # Delete outgoing links
2274 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2275 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2276 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2277 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2278 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2279 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2280 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2281 }
2282
2283 # If using cleanup triggers, we can skip some manual deletes
2284 if ( !$dbw->cleanupTriggers() ) {
2285
2286 # Clean up recentchanges entries...
2287 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
2288 }
2289
2290 # Clear caches
2291 Article::onArticleDelete( $this->mTitle );
2292
2293 # Log the deletion, if the page was suppressed, log it at Oversight instead
2294 $logtype = $suppress ? 'oversight' : 'delete';
2295 $log = new LogPage( $logtype );
2296 $log->addEntry( 'delete', $this->mTitle, $reason );
2297
2298 # Clear the cached article id so the interface doesn't act like we exist
2299 $this->mTitle->resetArticleID( 0 );
2300 $this->mTitle->mArticleID = 0;
2301 return true;
2302 }
2303
2304 /**
2305 * Roll back the most recent consecutive set of edits to a page
2306 * from the same user; fails if there are no eligible edits to
2307 * roll back to, e.g. user is the sole contributor. This function
2308 * performs permissions checks on $wgUser, then calls commitRollback()
2309 * to do the dirty work
2310 *
2311 * @param string $fromP - Name of the user whose edits to rollback.
2312 * @param string $summary - Custom summary. Set to default summary if empty.
2313 * @param string $token - Rollback token.
2314 * @param bool $bot - If true, mark all reverted edits as bot.
2315 *
2316 * @param array $resultDetails contains result-specific array of additional values
2317 * 'alreadyrolled' : 'current' (rev)
2318 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2319 *
2320 * @return array of errors, each error formatted as
2321 * array(messagekey, param1, param2, ...).
2322 * On success, the array is empty. This array can also be passed to
2323 * OutputPage::showPermissionsErrorPage().
2324 */
2325 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2326 global $wgUser;
2327 $resultDetails = null;
2328
2329 # Check permissions
2330 $errors = array_merge( $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ),
2331 $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
2332 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2333 $errors[] = array( 'sessionfailure' );
2334
2335 if ( $wgUser->pingLimiter('rollback') || $wgUser->pingLimiter() ) {
2336 $errors[] = array( 'actionthrottledtext' );
2337 }
2338 # If there were errors, bail out now
2339 if(!empty($errors))
2340 return $errors;
2341
2342 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2343 }
2344
2345 /**
2346 * Backend implementation of doRollback(), please refer there for parameter
2347 * and return value documentation
2348 *
2349 * NOTE: This function does NOT check ANY permissions, it just commits the
2350 * rollback to the DB Therefore, you should only call this function direct-
2351 * ly if you want to use custom permissions checks. If you don't, use
2352 * doRollback() instead.
2353 */
2354 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2355 global $wgUseRCPatrol, $wgUser;
2356 $dbw = wfGetDB( DB_MASTER );
2357
2358 if( wfReadOnly() ) {
2359 return array( array( 'readonlytext' ) );
2360 }
2361
2362 # Get the last editor
2363 $current = Revision::newFromTitle( $this->mTitle );
2364 if( is_null( $current ) ) {
2365 # Something wrong... no page?
2366 return array(array('notanarticle'));
2367 }
2368
2369 $from = str_replace( '_', ' ', $fromP );
2370 if( $from != $current->getUserText() ) {
2371 $resultDetails = array( 'current' => $current );
2372 return array(array('alreadyrolled',
2373 htmlspecialchars($this->mTitle->getPrefixedText()),
2374 htmlspecialchars($fromP),
2375 htmlspecialchars($current->getUserText())
2376 ));
2377 }
2378
2379 # Get the last edit not by this guy
2380 $user = intval( $current->getUser() );
2381 $user_text = $dbw->addQuotes( $current->getUserText() );
2382 $s = $dbw->selectRow( 'revision',
2383 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2384 array( 'rev_page' => $current->getPage(),
2385 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2386 ), __METHOD__,
2387 array( 'USE INDEX' => 'page_timestamp',
2388 'ORDER BY' => 'rev_timestamp DESC' )
2389 );
2390 if( $s === false ) {
2391 # No one else ever edited this page
2392 return array(array('cantrollback'));
2393 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2394 # Only admins can see this text
2395 return array(array('notvisiblerev'));
2396 }
2397
2398 $set = array();
2399 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2400 # Mark all reverted edits as bot
2401 $set['rc_bot'] = 1;
2402 }
2403 if ( $wgUseRCPatrol ) {
2404 # Mark all reverted edits as patrolled
2405 $set['rc_patrolled'] = 1;
2406 }
2407
2408 if ( $set ) {
2409 $dbw->update( 'recentchanges', $set,
2410 array( /* WHERE */
2411 'rc_cur_id' => $current->getPage(),
2412 'rc_user_text' => $current->getUserText(),
2413 "rc_timestamp > '{$s->rev_timestamp}'",
2414 ), __METHOD__
2415 );
2416 }
2417
2418 # Generate the edit summary if necessary
2419 $target = Revision::newFromId( $s->rev_id );
2420 if( empty( $summary ) )
2421 {
2422 global $wgLang;
2423 $summary = wfMsgForContent( 'revertpage',
2424 $target->getUserText(), $from,
2425 $s->rev_id, $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2426 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2427 );
2428 }
2429
2430 # Save
2431 $flags = EDIT_UPDATE;
2432
2433 if ($wgUser->isAllowed('minoredit'))
2434 $flags |= EDIT_MINOR;
2435
2436 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2437 $flags |= EDIT_FORCE_BOT;
2438 $this->doEdit( $target->getText(), $summary, $flags );
2439
2440 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2441
2442 $resultDetails = array(
2443 'summary' => $summary,
2444 'current' => $current,
2445 'target' => $target,
2446 );
2447 return array();
2448 }
2449
2450 /**
2451 * User interface for rollback operations
2452 */
2453 function rollback() {
2454 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2455 $details = null;
2456
2457 $result = $this->doRollback(
2458 $wgRequest->getVal( 'from' ),
2459 $wgRequest->getText( 'summary' ),
2460 $wgRequest->getVal( 'token' ),
2461 $wgRequest->getBool( 'bot' ),
2462 $details
2463 );
2464
2465 if( in_array( array( 'blocked' ), $result ) ) {
2466 $wgOut->blockedPage();
2467 return;
2468 }
2469 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2470 $wgOut->rateLimited();
2471 return;
2472 }
2473 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ){
2474 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2475 $errArray = $result[0];
2476 $errMsg = array_shift( $errArray );
2477 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2478 if( isset( $details['current'] ) ){
2479 $current = $details['current'];
2480 if( $current->getComment() != '' ) {
2481 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2482 }
2483 }
2484 return;
2485 }
2486 # Display permissions errors before read-only message -- there's no
2487 # point in misleading the user into thinking the inability to rollback
2488 # is only temporary.
2489 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2490 # array_diff is completely broken for arrays of arrays, sigh. Re-
2491 # move any 'readonlytext' error manually.
2492 $out = array();
2493 foreach( $result as $error ) {
2494 if( $error != array( 'readonlytext' ) ) {
2495 $out []= $error;
2496 }
2497 }
2498 $wgOut->showPermissionsErrorPage( $out );
2499 return;
2500 }
2501 if( $result == array( array('readonlytext') ) ) {
2502 $wgOut->readOnlyPage();
2503 return;
2504 }
2505
2506 $current = $details['current'];
2507 $target = $details['target'];
2508 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2509 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2510 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2511 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2512 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2513 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2514 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2515 $wgOut->returnToMain( false, $this->mTitle );
2516 }
2517
2518
2519 /**
2520 * Do standard deferred updates after page view
2521 * @private
2522 */
2523 function viewUpdates() {
2524 global $wgDeferredUpdateList;
2525
2526 if ( 0 != $this->getID() ) {
2527 global $wgDisableCounters;
2528 if( !$wgDisableCounters ) {
2529 Article::incViewCount( $this->getID() );
2530 $u = new SiteStatsUpdate( 1, 0, 0 );
2531 array_push( $wgDeferredUpdateList, $u );
2532 }
2533 }
2534
2535 # Update newtalk / watchlist notification status
2536 global $wgUser;
2537 $wgUser->clearNotification( $this->mTitle );
2538 }
2539
2540 /**
2541 * Prepare text which is about to be saved.
2542 * Returns a stdclass with source, pst and output members
2543 */
2544 function prepareTextForEdit( $text, $revid=null ) {
2545 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2546 // Already prepared
2547 return $this->mPreparedEdit;
2548 }
2549 global $wgParser;
2550 $edit = (object)array();
2551 $edit->revid = $revid;
2552 $edit->newText = $text;
2553 $edit->pst = $this->preSaveTransform( $text );
2554 $options = new ParserOptions;
2555 $options->setTidy( true );
2556 $options->enableLimitReport();
2557 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2558 $edit->oldText = $this->getContent();
2559 $this->mPreparedEdit = $edit;
2560 return $edit;
2561 }
2562
2563 /**
2564 * Do standard deferred updates after page edit.
2565 * Update links tables, site stats, search index and message cache.
2566 * Every 100th edit, prune the recent changes table.
2567 *
2568 * @private
2569 * @param $text New text of the article
2570 * @param $summary Edit summary
2571 * @param $minoredit Minor edit
2572 * @param $timestamp_of_pagechange Timestamp associated with the page change
2573 * @param $newid rev_id value of the new revision
2574 * @param $changed Whether or not the content actually changed
2575 */
2576 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2577 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2578
2579 wfProfileIn( __METHOD__ );
2580
2581 # Parse the text
2582 # Be careful not to double-PST: $text is usually already PST-ed once
2583 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2584 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2585 $editInfo = $this->prepareTextForEdit( $text, $newid );
2586 } else {
2587 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2588 $editInfo = $this->mPreparedEdit;
2589 }
2590
2591 # Save it to the parser cache
2592 if ( $wgEnableParserCache ) {
2593 $parserCache =& ParserCache::singleton();
2594 $parserCache->save( $editInfo->output, $this, $wgUser );
2595 }
2596
2597 # Update the links tables
2598 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
2599 $u->doUpdate();
2600
2601 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2602 if ( 0 == mt_rand( 0, 99 ) ) {
2603 // Flush old entries from the `recentchanges` table; we do this on
2604 // random requests so as to avoid an increase in writes for no good reason
2605 global $wgRCMaxAge;
2606 $dbw = wfGetDB( DB_MASTER );
2607 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2608 $recentchanges = $dbw->tableName( 'recentchanges' );
2609 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2610 $dbw->query( $sql );
2611 }
2612 }
2613
2614 $id = $this->getID();
2615 $title = $this->mTitle->getPrefixedDBkey();
2616 $shortTitle = $this->mTitle->getDBkey();
2617
2618 if ( 0 == $id ) {
2619 wfProfileOut( __METHOD__ );
2620 return;
2621 }
2622
2623 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2624 array_push( $wgDeferredUpdateList, $u );
2625 $u = new SearchUpdate( $id, $title, $text );
2626 array_push( $wgDeferredUpdateList, $u );
2627
2628 # If this is another user's talk page, update newtalk
2629 # Don't do this if $changed = false otherwise some idiot can null-edit a
2630 # load of user talk pages and piss people off, nor if it's a minor edit
2631 # by a properly-flagged bot.
2632 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2633 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2634 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2635 $other = User::newFromName( $shortTitle );
2636 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2637 // An anonymous user
2638 $other = new User();
2639 $other->setName( $shortTitle );
2640 }
2641 if( $other ) {
2642 $other->setNewtalk( true );
2643 }
2644 }
2645 }
2646
2647 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2648 $wgMessageCache->replace( $shortTitle, $text );
2649 }
2650
2651 wfProfileOut( __METHOD__ );
2652 }
2653
2654 /**
2655 * Perform article updates on a special page creation.
2656 *
2657 * @param Revision $rev
2658 *
2659 * @todo This is a shitty interface function. Kill it and replace the
2660 * other shitty functions like editUpdates and such so it's not needed
2661 * anymore.
2662 */
2663 function createUpdates( $rev ) {
2664 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2665 $this->mTotalAdjustment = 1;
2666 $this->editUpdates( $rev->getText(), $rev->getComment(),
2667 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2668 }
2669
2670 /**
2671 * Generate the navigation links when browsing through an article revisions
2672 * It shows the information as:
2673 * Revision as of \<date\>; view current revision
2674 * \<- Previous version | Next Version -\>
2675 *
2676 * @private
2677 * @param string $oldid Revision ID of this article revision
2678 */
2679 function setOldSubtitle( $oldid=0 ) {
2680 global $wgLang, $wgOut, $wgUser;
2681
2682 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2683 return;
2684 }
2685
2686 $revision = Revision::newFromId( $oldid );
2687
2688 $current = ( $oldid == $this->mLatest );
2689 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2690 $sk = $wgUser->getSkin();
2691 $lnk = $current
2692 ? wfMsg( 'currentrevisionlink' )
2693 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2694 $curdiff = $current
2695 ? wfMsg( 'diff' )
2696 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2697 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2698 $prevlink = $prev
2699 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2700 : wfMsg( 'previousrevision' );
2701 $prevdiff = $prev
2702 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2703 : wfMsg( 'diff' );
2704 $nextlink = $current
2705 ? wfMsg( 'nextrevision' )
2706 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2707 $nextdiff = $current
2708 ? wfMsg( 'diff' )
2709 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2710
2711 $cdel='';
2712 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2713 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2714 if( $revision->isCurrent() ) {
2715 // We don't handle top deleted edits too well
2716 $cdel = wfMsgHtml('rev-delundel');
2717 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2718 // If revision was hidden from sysops
2719 $cdel = wfMsgHtml('rev-delundel');
2720 } else {
2721 $cdel = $sk->makeKnownLinkObj( $revdel,
2722 wfMsgHtml('rev-delundel'),
2723 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2724 '&oldid=' . urlencode( $oldid ) );
2725 // Bolden oversighted content
2726 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2727 $cdel = "<strong>$cdel</strong>";
2728 }
2729 $cdel = "(<small>$cdel</small>) ";
2730 }
2731 # Show user links if allowed to see them. Normally they
2732 # are hidden regardless, but since we can already see the text here...
2733 $userlinks = $sk->revUserTools( $revision, false );
2734
2735 $m = wfMsg( 'revision-info-current' );
2736 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2737 ? 'revision-info-current'
2738 : 'revision-info';
2739
2740 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2741
2742 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2743 $wgOut->setSubtitle( $r );
2744 }
2745
2746 /**
2747 * This function is called right before saving the wikitext,
2748 * so we can do things like signatures and links-in-context.
2749 *
2750 * @param string $text
2751 */
2752 function preSaveTransform( $text ) {
2753 global $wgParser, $wgUser;
2754 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2755 }
2756
2757 /* Caching functions */
2758
2759 /**
2760 * checkLastModified returns true if it has taken care of all
2761 * output to the client that is necessary for this request.
2762 * (that is, it has sent a cached version of the page)
2763 */
2764 function tryFileCache() {
2765 static $called = false;
2766 if( $called ) {
2767 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2768 return;
2769 }
2770 $called = true;
2771 if($this->isFileCacheable()) {
2772 $touched = $this->mTouched;
2773 $cache = new HTMLFileCache( $this->mTitle );
2774 if($cache->isFileCacheGood( $touched )) {
2775 wfDebug( "Article::tryFileCache(): about to load file\n" );
2776 $cache->loadFromFileCache();
2777 return true;
2778 } else {
2779 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2780 ob_start( array(&$cache, 'saveToFileCache' ) );
2781 }
2782 } else {
2783 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2784 }
2785 }
2786
2787 /**
2788 * Check if the page can be cached
2789 * @return bool
2790 */
2791 function isFileCacheable() {
2792 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2793 $action = $wgRequest->getVal( 'action' );
2794 $oldid = $wgRequest->getVal( 'oldid' );
2795 $diff = $wgRequest->getVal( 'diff' );
2796 $redirect = $wgRequest->getVal( 'redirect' );
2797 $printable = $wgRequest->getVal( 'printable' );
2798 $page = $wgRequest->getVal( 'page' );
2799
2800 //check for non-standard user language; this covers uselang,
2801 //and extensions for auto-detecting user language.
2802 $ulang = $wgLang->getCode();
2803 $clang = $wgContLang->getCode();
2804
2805 $cacheable = $wgUseFileCache
2806 && (!$wgShowIPinHeader)
2807 && ($this->getID() != 0)
2808 && ($wgUser->isAnon())
2809 && (!$wgUser->getNewtalk())
2810 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2811 && (empty( $action ) || $action == 'view')
2812 && (!isset($oldid))
2813 && (!isset($diff))
2814 && (!isset($redirect))
2815 && (!isset($printable))
2816 && !isset($page)
2817 && (!$this->mRedirectedFrom)
2818 && ($ulang === $clang);
2819
2820 if ( $cacheable ) {
2821 //extension may have reason to disable file caching on some pages.
2822 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2823 }
2824
2825 return $cacheable;
2826 }
2827
2828 /**
2829 * Loads page_touched and returns a value indicating if it should be used
2830 *
2831 */
2832 function checkTouched() {
2833 if( !$this->mDataLoaded ) {
2834 $this->loadPageData();
2835 }
2836 return !$this->mIsRedirect;
2837 }
2838
2839 /**
2840 * Get the page_touched field
2841 */
2842 function getTouched() {
2843 # Ensure that page data has been loaded
2844 if( !$this->mDataLoaded ) {
2845 $this->loadPageData();
2846 }
2847 return $this->mTouched;
2848 }
2849
2850 /**
2851 * Get the page_latest field
2852 */
2853 function getLatest() {
2854 if ( !$this->mDataLoaded ) {
2855 $this->loadPageData();
2856 }
2857 return $this->mLatest;
2858 }
2859
2860 /**
2861 * Edit an article without doing all that other stuff
2862 * The article must already exist; link tables etc
2863 * are not updated, caches are not flushed.
2864 *
2865 * @param string $text text submitted
2866 * @param string $comment comment submitted
2867 * @param bool $minor whereas it's a minor modification
2868 */
2869 function quickEdit( $text, $comment = '', $minor = 0 ) {
2870 wfProfileIn( __METHOD__ );
2871
2872 $dbw = wfGetDB( DB_MASTER );
2873 $dbw->begin();
2874 $revision = new Revision( array(
2875 'page' => $this->getId(),
2876 'text' => $text,
2877 'comment' => $comment,
2878 'minor_edit' => $minor ? 1 : 0,
2879 ) );
2880 $revision->insertOn( $dbw );
2881 $this->updateRevisionOn( $dbw, $revision );
2882 $dbw->commit();
2883
2884 wfProfileOut( __METHOD__ );
2885 }
2886
2887 /**
2888 * Used to increment the view counter
2889 *
2890 * @static
2891 * @param integer $id article id
2892 */
2893 function incViewCount( $id ) {
2894 $id = intval( $id );
2895 global $wgHitcounterUpdateFreq, $wgDBtype;
2896
2897 $dbw = wfGetDB( DB_MASTER );
2898 $pageTable = $dbw->tableName( 'page' );
2899 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2900 $acchitsTable = $dbw->tableName( 'acchits' );
2901
2902 if( $wgHitcounterUpdateFreq <= 1 ) {
2903 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2904 return;
2905 }
2906
2907 # Not important enough to warrant an error page in case of failure
2908 $oldignore = $dbw->ignoreErrors( true );
2909
2910 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2911
2912 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2913 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2914 # Most of the time (or on SQL errors), skip row count check
2915 $dbw->ignoreErrors( $oldignore );
2916 return;
2917 }
2918
2919 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2920 $row = $dbw->fetchObject( $res );
2921 $rown = intval( $row->n );
2922 if( $rown >= $wgHitcounterUpdateFreq ){
2923 wfProfileIn( 'Article::incViewCount-collect' );
2924 $old_user_abort = ignore_user_abort( true );
2925
2926 if ($wgDBtype == 'mysql')
2927 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2928 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2929 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2930 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2931 'GROUP BY hc_id');
2932 $dbw->query("DELETE FROM $hitcounterTable");
2933 if ($wgDBtype == 'mysql') {
2934 $dbw->query('UNLOCK TABLES');
2935 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2936 'WHERE page_id = hc_id');
2937 }
2938 else {
2939 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2940 "FROM $acchitsTable WHERE page_id = hc_id");
2941 }
2942 $dbw->query("DROP TABLE $acchitsTable");
2943
2944 ignore_user_abort( $old_user_abort );
2945 wfProfileOut( 'Article::incViewCount-collect' );
2946 }
2947 $dbw->ignoreErrors( $oldignore );
2948 }
2949
2950 /**#@+
2951 * The onArticle*() functions are supposed to be a kind of hooks
2952 * which should be called whenever any of the specified actions
2953 * are done.
2954 *
2955 * This is a good place to put code to clear caches, for instance.
2956 *
2957 * This is called on page move and undelete, as well as edit
2958 * @static
2959 * @param $title_obj a title object
2960 */
2961
2962 static function onArticleCreate($title) {
2963 # The talk page isn't in the regular link tables, so we need to update manually:
2964 if ( $title->isTalkPage() ) {
2965 $other = $title->getSubjectPage();
2966 } else {
2967 $other = $title->getTalkPage();
2968 }
2969 $other->invalidateCache();
2970 $other->purgeSquid();
2971
2972 $title->touchLinks();
2973 $title->purgeSquid();
2974 $title->deleteTitleProtection();
2975 }
2976
2977 static function onArticleDelete( $title ) {
2978 global $wgUseFileCache, $wgMessageCache;
2979
2980 $title->touchLinks();
2981 $title->purgeSquid();
2982
2983 # File cache
2984 if ( $wgUseFileCache ) {
2985 $cm = new HTMLFileCache( $title );
2986 @unlink( $cm->fileCacheName() );
2987 }
2988
2989 if( $title->getNamespace() == NS_MEDIAWIKI) {
2990 $wgMessageCache->replace( $title->getDBkey(), false );
2991 }
2992 if( $title->getNamespace() == NS_IMAGE ) {
2993 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2994 $update->doUpdate();
2995 }
2996 }
2997
2998 /**
2999 * Purge caches on page update etc
3000 */
3001 static function onArticleEdit( $title ) {
3002 global $wgDeferredUpdateList, $wgUseFileCache;
3003
3004 // Invalidate caches of articles which include this page
3005 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3006
3007 // Invalidate the caches of all pages which redirect here
3008 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3009
3010 # Purge squid for this page only
3011 $title->purgeSquid();
3012
3013 # Clear file cache
3014 if ( $wgUseFileCache ) {
3015 $cm = new HTMLFileCache( $title );
3016 @unlink( $cm->fileCacheName() );
3017 }
3018 }
3019
3020 /**#@-*/
3021
3022 /**
3023 * Overriden by ImagePage class, only present here to avoid a fatal error
3024 * Called for ?action=revert
3025 */
3026 public function revert(){
3027 global $wgOut;
3028 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3029 }
3030
3031 /**
3032 * Info about this page
3033 * Called for ?action=info when $wgAllowPageInfo is on.
3034 *
3035 * @public
3036 */
3037 function info() {
3038 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3039
3040 if ( !$wgAllowPageInfo ) {
3041 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3042 return;
3043 }
3044
3045 $page = $this->mTitle->getSubjectPage();
3046
3047 $wgOut->setPagetitle( $page->getPrefixedText() );
3048 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3049 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3050
3051 if( !$this->mTitle->exists() ) {
3052 $wgOut->addHtml( '<div class="noarticletext">' );
3053 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3054 // This doesn't quite make sense; the user is asking for
3055 // information about the _page_, not the message... -- RC
3056 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3057 } else {
3058 $msg = $wgUser->isLoggedIn()
3059 ? 'noarticletext'
3060 : 'noarticletextanon';
3061 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3062 }
3063 $wgOut->addHtml( '</div>' );
3064 } else {
3065 $dbr = wfGetDB( DB_SLAVE );
3066 $wl_clause = array(
3067 'wl_title' => $page->getDBkey(),
3068 'wl_namespace' => $page->getNamespace() );
3069 $numwatchers = $dbr->selectField(
3070 'watchlist',
3071 'COUNT(*)',
3072 $wl_clause,
3073 __METHOD__,
3074 $this->getSelectOptions() );
3075
3076 $pageInfo = $this->pageCountInfo( $page );
3077 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3078
3079 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3080 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3081 if( $talkInfo ) {
3082 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3083 }
3084 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3085 if( $talkInfo ) {
3086 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3087 }
3088 $wgOut->addHTML( '</ul>' );
3089
3090 }
3091 }
3092
3093 /**
3094 * Return the total number of edits and number of unique editors
3095 * on a given page. If page does not exist, returns false.
3096 *
3097 * @param Title $title
3098 * @return array
3099 * @private
3100 */
3101 function pageCountInfo( $title ) {
3102 $id = $title->getArticleId();
3103 if( $id == 0 ) {
3104 return false;
3105 }
3106
3107 $dbr = wfGetDB( DB_SLAVE );
3108
3109 $rev_clause = array( 'rev_page' => $id );
3110
3111 $edits = $dbr->selectField(
3112 'revision',
3113 'COUNT(rev_page)',
3114 $rev_clause,
3115 __METHOD__,
3116 $this->getSelectOptions() );
3117
3118 $authors = $dbr->selectField(
3119 'revision',
3120 'COUNT(DISTINCT rev_user_text)',
3121 $rev_clause,
3122 __METHOD__,
3123 $this->getSelectOptions() );
3124
3125 return array( 'edits' => $edits, 'authors' => $authors );
3126 }
3127
3128 /**
3129 * Return a list of templates used by this article.
3130 * Uses the templatelinks table
3131 *
3132 * @return array Array of Title objects
3133 */
3134 function getUsedTemplates() {
3135 $result = array();
3136 $id = $this->mTitle->getArticleID();
3137 if( $id == 0 ) {
3138 return array();
3139 }
3140
3141 $dbr = wfGetDB( DB_SLAVE );
3142 $res = $dbr->select( array( 'templatelinks' ),
3143 array( 'tl_namespace', 'tl_title' ),
3144 array( 'tl_from' => $id ),
3145 'Article:getUsedTemplates' );
3146 if ( false !== $res ) {
3147 if ( $dbr->numRows( $res ) ) {
3148 while ( $row = $dbr->fetchObject( $res ) ) {
3149 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3150 }
3151 }
3152 }
3153 $dbr->freeResult( $res );
3154 return $result;
3155 }
3156
3157 /**
3158 * Returns a list of hidden categories this page is a member of.
3159 * Uses the page_props and categorylinks tables.
3160 *
3161 * @return array Array of Title objects
3162 */
3163 function getHiddenCategories() {
3164 $result = array();
3165 $id = $this->mTitle->getArticleID();
3166 if( $id == 0 ) {
3167 return array();
3168 }
3169
3170 $dbr = wfGetDB( DB_SLAVE );
3171 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3172 array( 'cl_to' ),
3173 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3174 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3175 'Article:getHiddenCategories' );
3176 if ( false !== $res ) {
3177 if ( $dbr->numRows( $res ) ) {
3178 while ( $row = $dbr->fetchObject( $res ) ) {
3179 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3180 }
3181 }
3182 }
3183 $dbr->freeResult( $res );
3184 return $result;
3185 }
3186
3187 /**
3188 * Return an auto-generated summary if the text provided is a redirect.
3189 *
3190 * @param string $text The wikitext to check
3191 * @return string '' or an appropriate summary
3192 */
3193 public static function getRedirectAutosummary( $text ) {
3194 $rt = Title::newFromRedirect( $text );
3195 if( is_object( $rt ) )
3196 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3197 else
3198 return '';
3199 }
3200
3201 /**
3202 * Return an auto-generated summary if the new text is much shorter than
3203 * the old text.
3204 *
3205 * @param string $oldtext The previous text of the page
3206 * @param string $text The submitted text of the page
3207 * @return string An appropriate autosummary, or an empty string.
3208 */
3209 public static function getBlankingAutosummary( $oldtext, $text ) {
3210 if ($oldtext!='' && $text=='') {
3211 return wfMsgForContent('autosumm-blank');
3212 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3213 #Removing more than 90% of the article
3214 global $wgContLang;
3215 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3216 return wfMsgForContent('autosumm-replace', $truncatedtext);
3217 } else {
3218 return '';
3219 }
3220 }
3221
3222 /**
3223 * Return an applicable autosummary if one exists for the given edit.
3224 * @param string $oldtext The previous text of the page.
3225 * @param string $newtext The submitted text of the page.
3226 * @param bitmask $flags A bitmask of flags submitted for the edit.
3227 * @return string An appropriate autosummary, or an empty string.
3228 */
3229 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3230
3231 # This code is UGLY UGLY UGLY.
3232 # Somebody PLEASE come up with a more elegant way to do it.
3233
3234 #Redirect autosummaries
3235 $summary = self::getRedirectAutosummary( $newtext );
3236
3237 if ($summary)
3238 return $summary;
3239
3240 #Blanking autosummaries
3241 if (!($flags & EDIT_NEW))
3242 $summary = self::getBlankingAutosummary( $oldtext, $newtext );
3243
3244 if ($summary)
3245 return $summary;
3246
3247 #New page autosummaries
3248 if ($flags & EDIT_NEW && strlen($newtext)) {
3249 #If they're making a new article, give its text, truncated, in the summary.
3250 global $wgContLang;
3251 $truncatedtext = $wgContLang->truncate(
3252 str_replace("\n", ' ', $newtext),
3253 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3254 '...' );
3255 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3256 }
3257
3258 if ($summary)
3259 return $summary;
3260
3261 return $summary;
3262 }
3263
3264 /**
3265 * Add the primary page-view wikitext to the output buffer
3266 * Saves the text into the parser cache if possible.
3267 * Updates templatelinks if it is out of date.
3268 *
3269 * @param string $text
3270 * @param bool $cache
3271 */
3272 public function outputWikiText( $text, $cache = true ) {
3273 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3274
3275 $popts = $wgOut->parserOptions();
3276 $popts->setTidy(true);
3277 $popts->enableLimitReport();
3278 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3279 $popts, true, true, $this->getRevIdFetched() );
3280 $popts->setTidy(false);
3281 $popts->enableLimitReport( false );
3282 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3283 $parserCache =& ParserCache::singleton();
3284 $parserCache->save( $parserOutput, $this, $wgUser );
3285 }
3286
3287 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3288 // templatelinks table may have become out of sync,
3289 // especially if using variable-based transclusions.
3290 // For paranoia, check if things have changed and if
3291 // so apply updates to the database. This will ensure
3292 // that cascaded protections apply as soon as the changes
3293 // are visible.
3294
3295 # Get templates from templatelinks
3296 $id = $this->mTitle->getArticleID();
3297
3298 $tlTemplates = array();
3299
3300 $dbr = wfGetDB( DB_SLAVE );
3301 $res = $dbr->select( array( 'templatelinks' ),
3302 array( 'tl_namespace', 'tl_title' ),
3303 array( 'tl_from' => $id ),
3304 'Article:getUsedTemplates' );
3305
3306 global $wgContLang;
3307
3308 if ( false !== $res ) {
3309 if ( $dbr->numRows( $res ) ) {
3310 while ( $row = $dbr->fetchObject( $res ) ) {
3311 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3312 }
3313 }
3314 }
3315
3316 # Get templates from parser output.
3317 $poTemplates_allns = $parserOutput->getTemplates();
3318
3319 $poTemplates = array ();
3320 foreach ( $poTemplates_allns as $ns_templates ) {
3321 $poTemplates = array_merge( $poTemplates, $ns_templates );
3322 }
3323
3324 # Get the diff
3325 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3326
3327 if ( count( $templates_diff ) > 0 ) {
3328 # Whee, link updates time.
3329 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3330
3331 $dbw = wfGetDb( DB_MASTER );
3332 $dbw->begin();
3333
3334 $u->doUpdate();
3335
3336 $dbw->commit();
3337 }
3338 }
3339
3340 $wgOut->addParserOutput( $parserOutput );
3341 }
3342
3343 }