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