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