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