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