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