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