Fix a couple of mistyped variable names, mysql strict incompatibilities, make cascadi...
[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 if (!$cascade) {
1643 $cascade = false;
1644 }
1645
1646 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1647 # we expect a single selection, but the schema allows otherwise.
1648 $current = array();
1649 foreach( $wgRestrictionTypes as $action )
1650 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1651
1652 $current = Article::flattenRestrictions( $current );
1653 $updated = Article::flattenRestrictions( $limit );
1654
1655 $changed = ( $current != $updated );
1656 $changed = $changed || ($this->mTitle->areRestrictionsCascading() != $cascade);
1657 $protect = ( $updated != '' );
1658
1659 # If nothing's changed, do nothing
1660 if( $changed ) {
1661 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1662
1663 $dbw =& wfGetDB( DB_MASTER );
1664
1665 # Prepare a null revision to be added to the history
1666 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1667 if( $reason )
1668 $comment .= ": $reason";
1669 if( $protect )
1670 $comment .= " [$updated]";
1671 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1672 $nullRevId = $nullRevision->insertOn( $dbw );
1673
1674 # Update restrictions table
1675 foreach( $limit as $action => $restrictions ) {
1676 if ($restrictions != '' ) {
1677 $dbw->replace( 'page_restrictions', array( 'pr_pagetype'),
1678 array( 'pr_page' => $id, 'pr_type' => $action
1679 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0 ), __METHOD__ );
1680 } else {
1681 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1682 'pr_type' => $action ), __METHOD__ );
1683 }
1684 }
1685
1686 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1687
1688 # Update the protection log
1689 $log = new LogPage( 'protect' );
1690
1691 $cascade_description = '';
1692
1693 if ($cascade) {
1694 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1695 }
1696
1697 if( $protect ) {
1698 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description" ) );
1699 } else {
1700 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1701 }
1702
1703 } # End hook
1704 } # End "changed" check
1705
1706 return true;
1707 }
1708
1709 /**
1710 * Take an array of page restrictions and flatten it to a string
1711 * suitable for insertion into the page_restrictions field.
1712 * @param array $limit
1713 * @return string
1714 * @private
1715 */
1716 function flattenRestrictions( $limit ) {
1717 if( !is_array( $limit ) ) {
1718 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1719 }
1720 $bits = array();
1721 ksort( $limit );
1722 foreach( $limit as $action => $restrictions ) {
1723 if( $restrictions != '' ) {
1724 $bits[] = "$action=$restrictions";
1725 }
1726 }
1727 return implode( ':', $bits );
1728 }
1729
1730 /*
1731 * UI entry point for page deletion
1732 */
1733 function delete() {
1734 global $wgUser, $wgOut, $wgRequest;
1735 $confirm = $wgRequest->wasPosted() &&
1736 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1737 $reason = $wgRequest->getText( 'wpReason' );
1738
1739 # This code desperately needs to be totally rewritten
1740
1741 # Check permissions
1742 if( $wgUser->isAllowed( 'delete' ) ) {
1743 if( $wgUser->isBlocked( !$confirm ) ) {
1744 $wgOut->blockedPage();
1745 return;
1746 }
1747 } else {
1748 $wgOut->permissionRequired( 'delete' );
1749 return;
1750 }
1751
1752 if( wfReadOnly() ) {
1753 $wgOut->readOnlyPage();
1754 return;
1755 }
1756
1757 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1758
1759 # Better double-check that it hasn't been deleted yet!
1760 $dbw =& wfGetDB( DB_MASTER );
1761 $conds = $this->mTitle->pageCond();
1762 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1763 if ( $latest === false ) {
1764 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1765 return;
1766 }
1767
1768 if( $confirm ) {
1769 $this->doDelete( $reason );
1770 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1771 $this->doWatch();
1772 } elseif( $this->mTitle->userIsWatching() ) {
1773 $this->doUnwatch();
1774 }
1775 return;
1776 }
1777
1778 # determine whether this page has earlier revisions
1779 # and insert a warning if it does
1780 $maxRevisions = 20;
1781 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1782
1783 if( count( $authors ) > 1 && !$confirm ) {
1784 $skin=$wgUser->getSkin();
1785 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1786 }
1787
1788 # If a single user is responsible for all revisions, find out who they are
1789 if ( count( $authors ) == $maxRevisions ) {
1790 // Query bailed out, too many revisions to find out if they're all the same
1791 $authorOfAll = false;
1792 } else {
1793 $authorOfAll = reset( $authors );
1794 foreach ( $authors as $author ) {
1795 if ( $authorOfAll != $author ) {
1796 $authorOfAll = false;
1797 break;
1798 }
1799 }
1800 }
1801 # Fetch article text
1802 $rev = Revision::newFromTitle( $this->mTitle );
1803
1804 if( !is_null( $rev ) ) {
1805 # if this is a mini-text, we can paste part of it into the deletion reason
1806 $text = $rev->getText();
1807
1808 #if this is empty, an earlier revision may contain "useful" text
1809 $blanked = false;
1810 if( $text == '' ) {
1811 $prev = $rev->getPrevious();
1812 if( $prev ) {
1813 $text = $prev->getText();
1814 $blanked = true;
1815 }
1816 }
1817
1818 $length = strlen( $text );
1819
1820 # this should not happen, since it is not possible to store an empty, new
1821 # page. Let's insert a standard text in case it does, though
1822 if( $length == 0 && $reason === '' ) {
1823 $reason = wfMsgForContent( 'exblank' );
1824 }
1825
1826 if( $length < 500 && $reason === '' ) {
1827 # comment field=255, let's grep the first 150 to have some user
1828 # space left
1829 global $wgContLang;
1830 $text = $wgContLang->truncate( $text, 150, '...' );
1831
1832 # let's strip out newlines
1833 $text = preg_replace( "/[\n\r]/", '', $text );
1834
1835 if( !$blanked ) {
1836 if( $authorOfAll === false ) {
1837 $reason = wfMsgForContent( 'excontent', $text );
1838 } else {
1839 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1840 }
1841 } else {
1842 $reason = wfMsgForContent( 'exbeforeblank', $text );
1843 }
1844 }
1845 }
1846
1847 return $this->confirmDelete( '', $reason );
1848 }
1849
1850 /**
1851 * Get the last N authors
1852 * @param int $num Number of revisions to get
1853 * @param string $revLatest The latest rev_id, selected from the master (optional)
1854 * @return array Array of authors, duplicates not removed
1855 */
1856 function getLastNAuthors( $num, $revLatest = 0 ) {
1857 wfProfileIn( __METHOD__ );
1858
1859 // First try the slave
1860 // If that doesn't have the latest revision, try the master
1861 $continue = 2;
1862 $db =& wfGetDB( DB_SLAVE );
1863 do {
1864 $res = $db->select( array( 'page', 'revision' ),
1865 array( 'rev_id', 'rev_user_text' ),
1866 array(
1867 'page_namespace' => $this->mTitle->getNamespace(),
1868 'page_title' => $this->mTitle->getDBkey(),
1869 'rev_page = page_id'
1870 ), __METHOD__, $this->getSelectOptions( array(
1871 'ORDER BY' => 'rev_timestamp DESC',
1872 'LIMIT' => $num
1873 ) )
1874 );
1875 if ( !$res ) {
1876 wfProfileOut( __METHOD__ );
1877 return array();
1878 }
1879 $row = $db->fetchObject( $res );
1880 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1881 $db =& wfGetDB( DB_MASTER );
1882 $continue--;
1883 } else {
1884 $continue = 0;
1885 }
1886 } while ( $continue );
1887
1888 $authors = array( $row->rev_user_text );
1889 while ( $row = $db->fetchObject( $res ) ) {
1890 $authors[] = $row->rev_user_text;
1891 }
1892 wfProfileOut( __METHOD__ );
1893 return $authors;
1894 }
1895
1896 /**
1897 * Output deletion confirmation dialog
1898 */
1899 function confirmDelete( $par, $reason ) {
1900 global $wgOut, $wgUser;
1901
1902 wfDebug( "Article::confirmDelete\n" );
1903
1904 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1905 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1906 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1907 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1908
1909 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1910
1911 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1912 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1913 $token = htmlspecialchars( $wgUser->editToken() );
1914 $watch = Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '2' ) );
1915
1916 $wgOut->addHTML( "
1917 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1918 <table border='0'>
1919 <tr>
1920 <td align='right'>
1921 <label for='wpReason'>{$delcom}:</label>
1922 </td>
1923 <td align='left'>
1924 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
1925 </td>
1926 </tr>
1927 <tr>
1928 <td>&nbsp;</td>
1929 <td>$watch</td>
1930 </tr>
1931 <tr>
1932 <td>&nbsp;</td>
1933 <td>
1934 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
1935 </td>
1936 </tr>
1937 </table>
1938 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1939 </form>\n" );
1940
1941 $wgOut->returnToMain( false );
1942 }
1943
1944
1945 /**
1946 * Perform a deletion and output success or failure messages
1947 */
1948 function doDelete( $reason ) {
1949 global $wgOut, $wgUser;
1950 wfDebug( __METHOD__."\n" );
1951
1952 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1953 if ( $this->doDeleteArticle( $reason ) ) {
1954 $deleted = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
1955
1956 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1957 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1958
1959 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1960 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1961
1962 $wgOut->addWikiText( $text );
1963 $wgOut->returnToMain( false );
1964 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1965 } else {
1966 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1967 }
1968 }
1969 }
1970
1971 /**
1972 * Back-end article deletion
1973 * Deletes the article with database consistency, writes logs, purges caches
1974 * Returns success
1975 */
1976 function doDeleteArticle( $reason ) {
1977 global $wgUseSquid, $wgDeferredUpdateList;
1978 global $wgUseTrackbacks;
1979
1980 wfDebug( __METHOD__."\n" );
1981
1982 $dbw =& wfGetDB( DB_MASTER );
1983 $ns = $this->mTitle->getNamespace();
1984 $t = $this->mTitle->getDBkey();
1985 $id = $this->mTitle->getArticleID();
1986
1987 if ( $t == '' || $id == 0 ) {
1988 return false;
1989 }
1990
1991 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1992 array_push( $wgDeferredUpdateList, $u );
1993
1994 // For now, shunt the revision data into the archive table.
1995 // Text is *not* removed from the text table; bulk storage
1996 // is left intact to avoid breaking block-compression or
1997 // immutable storage schemes.
1998 //
1999 // For backwards compatibility, note that some older archive
2000 // table entries will have ar_text and ar_flags fields still.
2001 //
2002 // In the future, we may keep revisions and mark them with
2003 // the rev_deleted field, which is reserved for this purpose.
2004 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2005 array(
2006 'ar_namespace' => 'page_namespace',
2007 'ar_title' => 'page_title',
2008 'ar_comment' => 'rev_comment',
2009 'ar_user' => 'rev_user',
2010 'ar_user_text' => 'rev_user_text',
2011 'ar_timestamp' => 'rev_timestamp',
2012 'ar_minor_edit' => 'rev_minor_edit',
2013 'ar_rev_id' => 'rev_id',
2014 'ar_text_id' => 'rev_text_id',
2015 'ar_text' => '\'\'', // Be explicit to appease
2016 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2017 ), array(
2018 'page_id' => $id,
2019 'page_id = rev_page'
2020 ), __METHOD__
2021 );
2022
2023 # Delete restrictions for it
2024 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2025
2026 # Now that it's safely backed up, delete it
2027 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2028
2029 # If using cascading deletes, we can skip some explicit deletes
2030 if ( !$dbw->cascadingDeletes() ) {
2031
2032 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2033
2034 if ($wgUseTrackbacks)
2035 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2036
2037 # Delete outgoing links
2038 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2039 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2040 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2041 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2042 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2043 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2044 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2045 }
2046
2047 # If using cleanup triggers, we can skip some manual deletes
2048 if ( !$dbw->cleanupTriggers() ) {
2049
2050 # Clean up recentchanges entries...
2051 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
2052 }
2053
2054 # Clear caches
2055 Article::onArticleDelete( $this->mTitle );
2056
2057 # Log the deletion
2058 $log = new LogPage( 'delete' );
2059 $log->addEntry( 'delete', $this->mTitle, $reason );
2060
2061 # Clear the cached article id so the interface doesn't act like we exist
2062 $this->mTitle->resetArticleID( 0 );
2063 $this->mTitle->mArticleID = 0;
2064 return true;
2065 }
2066
2067 /**
2068 * Revert a modification
2069 */
2070 function rollback() {
2071 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2072
2073 if( $wgUser->isAllowed( 'rollback' ) ) {
2074 if( $wgUser->isBlocked() ) {
2075 $wgOut->blockedPage();
2076 return;
2077 }
2078 } else {
2079 $wgOut->permissionRequired( 'rollback' );
2080 return;
2081 }
2082
2083 if ( wfReadOnly() ) {
2084 $wgOut->readOnlyPage( $this->getContent() );
2085 return;
2086 }
2087 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2088 array( $this->mTitle->getPrefixedText(),
2089 $wgRequest->getVal( 'from' ) ) ) ) {
2090 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2091 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2092 return;
2093 }
2094 $dbw =& wfGetDB( DB_MASTER );
2095
2096 # Enhanced rollback, marks edits rc_bot=1
2097 $bot = $wgRequest->getBool( 'bot' );
2098
2099 # Replace all this user's current edits with the next one down
2100
2101 # Get the last editor
2102 $current = Revision::newFromTitle( $this->mTitle );
2103 if( is_null( $current ) ) {
2104 # Something wrong... no page?
2105 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2106 return;
2107 }
2108
2109 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2110 if( $from != $current->getUserText() ) {
2111 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2112 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2113 htmlspecialchars( $this->mTitle->getPrefixedText()),
2114 htmlspecialchars( $from ),
2115 htmlspecialchars( $current->getUserText() ) ) );
2116 if( $current->getComment() != '') {
2117 $wgOut->addHTML(
2118 wfMsg( 'editcomment',
2119 htmlspecialchars( $current->getComment() ) ) );
2120 }
2121 return;
2122 }
2123
2124 # Get the last edit not by this guy
2125 $user = intval( $current->getUser() );
2126 $user_text = $dbw->addQuotes( $current->getUserText() );
2127 $s = $dbw->selectRow( 'revision',
2128 array( 'rev_id', 'rev_timestamp' ),
2129 array(
2130 'rev_page' => $current->getPage(),
2131 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2132 ), __METHOD__,
2133 array(
2134 'USE INDEX' => 'page_timestamp',
2135 'ORDER BY' => 'rev_timestamp DESC' )
2136 );
2137 if( $s === false ) {
2138 # Something wrong
2139 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2140 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2141 return;
2142 }
2143
2144 $set = array();
2145 if ( $bot ) {
2146 # Mark all reverted edits as bot
2147 $set['rc_bot'] = 1;
2148 }
2149 if ( $wgUseRCPatrol ) {
2150 # Mark all reverted edits as patrolled
2151 $set['rc_patrolled'] = 1;
2152 }
2153
2154 if ( $set ) {
2155 $dbw->update( 'recentchanges', $set,
2156 array( /* WHERE */
2157 'rc_cur_id' => $current->getPage(),
2158 'rc_user_text' => $current->getUserText(),
2159 "rc_timestamp > '{$s->rev_timestamp}'",
2160 ), __METHOD__
2161 );
2162 }
2163
2164 # Get the edit summary
2165 $target = Revision::newFromId( $s->rev_id );
2166 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2167 $newComment = $wgRequest->getText( 'summary', $newComment );
2168
2169 # Save it!
2170 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2171 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2172 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2173
2174 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2175
2176 $wgOut->returnToMain( false );
2177 }
2178
2179
2180 /**
2181 * Do standard deferred updates after page view
2182 * @private
2183 */
2184 function viewUpdates() {
2185 global $wgDeferredUpdateList;
2186
2187 if ( 0 != $this->getID() ) {
2188 global $wgDisableCounters;
2189 if( !$wgDisableCounters ) {
2190 Article::incViewCount( $this->getID() );
2191 $u = new SiteStatsUpdate( 1, 0, 0 );
2192 array_push( $wgDeferredUpdateList, $u );
2193 }
2194 }
2195
2196 # Update newtalk / watchlist notification status
2197 global $wgUser;
2198 $wgUser->clearNotification( $this->mTitle );
2199 }
2200
2201 /**
2202 * Do standard deferred updates after page edit.
2203 * Update links tables, site stats, search index and message cache.
2204 * Every 1000th edit, prune the recent changes table.
2205 *
2206 * @private
2207 * @param $text New text of the article
2208 * @param $summary Edit summary
2209 * @param $minoredit Minor edit
2210 * @param $timestamp_of_pagechange Timestamp associated with the page change
2211 * @param $newid rev_id value of the new revision
2212 * @param $changed Whether or not the content actually changed
2213 */
2214 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2215 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2216
2217 wfProfileIn( __METHOD__ );
2218
2219 # Parse the text
2220 $options = new ParserOptions;
2221 $options->setTidy(true);
2222 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2223
2224 # Save it to the parser cache
2225 $parserCache =& ParserCache::singleton();
2226 $parserCache->save( $poutput, $this, $wgUser );
2227
2228 # Update the links tables
2229 $u = new LinksUpdate( $this->mTitle, $poutput );
2230 $u->doUpdate();
2231
2232 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2233 wfSeedRandom();
2234 if ( 0 == mt_rand( 0, 999 ) ) {
2235 # Periodically flush old entries from the recentchanges table.
2236 global $wgRCMaxAge;
2237
2238 $dbw =& wfGetDB( DB_MASTER );
2239 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2240 $recentchanges = $dbw->tableName( 'recentchanges' );
2241 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2242 $dbw->query( $sql );
2243 }
2244 }
2245
2246 $id = $this->getID();
2247 $title = $this->mTitle->getPrefixedDBkey();
2248 $shortTitle = $this->mTitle->getDBkey();
2249
2250 if ( 0 == $id ) {
2251 wfProfileOut( __METHOD__ );
2252 return;
2253 }
2254
2255 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2256 array_push( $wgDeferredUpdateList, $u );
2257 $u = new SearchUpdate( $id, $title, $text );
2258 array_push( $wgDeferredUpdateList, $u );
2259
2260 # If this is another user's talk page, update newtalk
2261 # Don't do this if $changed = false otherwise some idiot can null-edit a
2262 # load of user talk pages and piss people off, nor if it's a minor edit
2263 # by a properly-flagged bot.
2264 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2265 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2266 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2267 $other = User::newFromName( $shortTitle );
2268 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2269 // An anonymous user
2270 $other = new User();
2271 $other->setName( $shortTitle );
2272 }
2273 if( $other ) {
2274 $other->setNewtalk( true );
2275 }
2276 }
2277 }
2278
2279 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2280 $wgMessageCache->replace( $shortTitle, $text );
2281 }
2282
2283 wfProfileOut( __METHOD__ );
2284 }
2285
2286 /**
2287 * Perform article updates on a special page creation.
2288 *
2289 * @param Revision $rev
2290 *
2291 * @fixme This is a shitty interface function. Kill it and replace the
2292 * other shitty functions like editUpdates and such so it's not needed
2293 * anymore.
2294 */
2295 function createUpdates( $rev ) {
2296 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2297 $this->mTotalAdjustment = 1;
2298 $this->editUpdates( $rev->getText(), $rev->getComment(),
2299 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2300 }
2301
2302 /**
2303 * Generate the navigation links when browsing through an article revisions
2304 * It shows the information as:
2305 * Revision as of \<date\>; view current revision
2306 * \<- Previous version | Next Version -\>
2307 *
2308 * @private
2309 * @param string $oldid Revision ID of this article revision
2310 */
2311 function setOldSubtitle( $oldid=0 ) {
2312 global $wgLang, $wgOut, $wgUser;
2313
2314 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2315 return;
2316 }
2317
2318 $revision = Revision::newFromId( $oldid );
2319
2320 $current = ( $oldid == $this->mLatest );
2321 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2322 $sk = $wgUser->getSkin();
2323 $lnk = $current
2324 ? wfMsg( 'currentrevisionlink' )
2325 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2326 $curdiff = $current
2327 ? wfMsg( 'diff' )
2328 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2329 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2330 $prevlink = $prev
2331 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2332 : wfMsg( 'previousrevision' );
2333 $prevdiff = $prev
2334 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2335 : wfMsg( 'diff' );
2336 $nextlink = $current
2337 ? wfMsg( 'nextrevision' )
2338 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2339 $nextdiff = $current
2340 ? wfMsg( 'diff' )
2341 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2342
2343 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2344 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2345
2346 $r = "\n\t\t\t\t<div id=\"mw-revision-info\">" . wfMsg( 'revision-info', $td, $userlinks ) . "</div>\n" .
2347 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2348 $wgOut->setSubtitle( $r );
2349 }
2350
2351 /**
2352 * This function is called right before saving the wikitext,
2353 * so we can do things like signatures and links-in-context.
2354 *
2355 * @param string $text
2356 */
2357 function preSaveTransform( $text ) {
2358 global $wgParser, $wgUser;
2359 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2360 }
2361
2362 /* Caching functions */
2363
2364 /**
2365 * checkLastModified returns true if it has taken care of all
2366 * output to the client that is necessary for this request.
2367 * (that is, it has sent a cached version of the page)
2368 */
2369 function tryFileCache() {
2370 static $called = false;
2371 if( $called ) {
2372 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2373 return;
2374 }
2375 $called = true;
2376 if($this->isFileCacheable()) {
2377 $touched = $this->mTouched;
2378 $cache = new HTMLFileCache( $this->mTitle );
2379 if($cache->isFileCacheGood( $touched )) {
2380 wfDebug( "Article::tryFileCache(): about to load file\n" );
2381 $cache->loadFromFileCache();
2382 return true;
2383 } else {
2384 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2385 ob_start( array(&$cache, 'saveToFileCache' ) );
2386 }
2387 } else {
2388 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2389 }
2390 }
2391
2392 /**
2393 * Check if the page can be cached
2394 * @return bool
2395 */
2396 function isFileCacheable() {
2397 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2398 $action = $wgRequest->getVal( 'action' );
2399 $oldid = $wgRequest->getVal( 'oldid' );
2400 $diff = $wgRequest->getVal( 'diff' );
2401 $redirect = $wgRequest->getVal( 'redirect' );
2402 $printable = $wgRequest->getVal( 'printable' );
2403
2404 return $wgUseFileCache
2405 and (!$wgShowIPinHeader)
2406 and ($this->getID() != 0)
2407 and ($wgUser->isAnon())
2408 and (!$wgUser->getNewtalk())
2409 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2410 and (empty( $action ) || $action == 'view')
2411 and (!isset($oldid))
2412 and (!isset($diff))
2413 and (!isset($redirect))
2414 and (!isset($printable))
2415 and (!$this->mRedirectedFrom);
2416 }
2417
2418 /**
2419 * Loads page_touched and returns a value indicating if it should be used
2420 *
2421 */
2422 function checkTouched() {
2423 if( !$this->mDataLoaded ) {
2424 $this->loadPageData();
2425 }
2426 return !$this->mIsRedirect;
2427 }
2428
2429 /**
2430 * Get the page_touched field
2431 */
2432 function getTouched() {
2433 # Ensure that page data has been loaded
2434 if( !$this->mDataLoaded ) {
2435 $this->loadPageData();
2436 }
2437 return $this->mTouched;
2438 }
2439
2440 /**
2441 * Get the page_latest field
2442 */
2443 function getLatest() {
2444 if ( !$this->mDataLoaded ) {
2445 $this->loadPageData();
2446 }
2447 return $this->mLatest;
2448 }
2449
2450 /**
2451 * Edit an article without doing all that other stuff
2452 * The article must already exist; link tables etc
2453 * are not updated, caches are not flushed.
2454 *
2455 * @param string $text text submitted
2456 * @param string $comment comment submitted
2457 * @param bool $minor whereas it's a minor modification
2458 */
2459 function quickEdit( $text, $comment = '', $minor = 0 ) {
2460 wfProfileIn( __METHOD__ );
2461
2462 $dbw =& wfGetDB( DB_MASTER );
2463 $dbw->begin();
2464 $revision = new Revision( array(
2465 'page' => $this->getId(),
2466 'text' => $text,
2467 'comment' => $comment,
2468 'minor_edit' => $minor ? 1 : 0,
2469 ) );
2470 $revision->insertOn( $dbw );
2471 $this->updateRevisionOn( $dbw, $revision );
2472 $dbw->commit();
2473
2474 wfProfileOut( __METHOD__ );
2475 }
2476
2477 /**
2478 * Used to increment the view counter
2479 *
2480 * @static
2481 * @param integer $id article id
2482 */
2483 function incViewCount( $id ) {
2484 $id = intval( $id );
2485 global $wgHitcounterUpdateFreq, $wgDBtype;
2486
2487 $dbw =& wfGetDB( DB_MASTER );
2488 $pageTable = $dbw->tableName( 'page' );
2489 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2490 $acchitsTable = $dbw->tableName( 'acchits' );
2491
2492 if( $wgHitcounterUpdateFreq <= 1 ) {
2493 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2494 return;
2495 }
2496
2497 # Not important enough to warrant an error page in case of failure
2498 $oldignore = $dbw->ignoreErrors( true );
2499
2500 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2501
2502 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2503 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2504 # Most of the time (or on SQL errors), skip row count check
2505 $dbw->ignoreErrors( $oldignore );
2506 return;
2507 }
2508
2509 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2510 $row = $dbw->fetchObject( $res );
2511 $rown = intval( $row->n );
2512 if( $rown >= $wgHitcounterUpdateFreq ){
2513 wfProfileIn( 'Article::incViewCount-collect' );
2514 $old_user_abort = ignore_user_abort( true );
2515
2516 if ($wgDBtype == 'mysql')
2517 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2518 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2519 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2520 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2521 'GROUP BY hc_id');
2522 $dbw->query("DELETE FROM $hitcounterTable");
2523 if ($wgDBtype == 'mysql') {
2524 $dbw->query('UNLOCK TABLES');
2525 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2526 'WHERE page_id = hc_id');
2527 }
2528 else {
2529 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2530 "FROM $acchitsTable WHERE page_id = hc_id");
2531 }
2532 $dbw->query("DROP TABLE $acchitsTable");
2533
2534 ignore_user_abort( $old_user_abort );
2535 wfProfileOut( 'Article::incViewCount-collect' );
2536 }
2537 $dbw->ignoreErrors( $oldignore );
2538 }
2539
2540 /**#@+
2541 * The onArticle*() functions are supposed to be a kind of hooks
2542 * which should be called whenever any of the specified actions
2543 * are done.
2544 *
2545 * This is a good place to put code to clear caches, for instance.
2546 *
2547 * This is called on page move and undelete, as well as edit
2548 * @static
2549 * @param $title_obj a title object
2550 */
2551
2552 static function onArticleCreate($title) {
2553 # The talk page isn't in the regular link tables, so we need to update manually:
2554 if ( $title->isTalkPage() ) {
2555 $other = $title->getSubjectPage();
2556 } else {
2557 $other = $title->getTalkPage();
2558 }
2559 $other->invalidateCache();
2560 $other->purgeSquid();
2561
2562 $title->touchLinks();
2563 $title->purgeSquid();
2564 }
2565
2566 static function onArticleDelete( $title ) {
2567 global $wgUseFileCache, $wgMessageCache;
2568
2569 $title->touchLinks();
2570 $title->purgeSquid();
2571
2572 # File cache
2573 if ( $wgUseFileCache ) {
2574 $cm = new HTMLFileCache( $title );
2575 @unlink( $cm->fileCacheName() );
2576 }
2577
2578 if( $title->getNamespace() == NS_MEDIAWIKI) {
2579 $wgMessageCache->replace( $title->getDBkey(), false );
2580 }
2581 }
2582
2583 /**
2584 * Purge caches on page update etc
2585 */
2586 static function onArticleEdit( $title ) {
2587 global $wgDeferredUpdateList, $wgUseFileCache;
2588
2589 // Invalidate caches of articles which include this page
2590 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2591 $wgDeferredUpdateList[] = $update;
2592
2593 # Purge squid for this page only
2594 $title->purgeSquid();
2595
2596 # Clear file cache
2597 if ( $wgUseFileCache ) {
2598 $cm = new HTMLFileCache( $title );
2599 @unlink( $cm->fileCacheName() );
2600 }
2601 }
2602
2603 /**#@-*/
2604
2605 /**
2606 * Info about this page
2607 * Called for ?action=info when $wgAllowPageInfo is on.
2608 *
2609 * @public
2610 */
2611 function info() {
2612 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2613
2614 if ( !$wgAllowPageInfo ) {
2615 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2616 return;
2617 }
2618
2619 $page = $this->mTitle->getSubjectPage();
2620
2621 $wgOut->setPagetitle( $page->getPrefixedText() );
2622 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2623
2624 # first, see if the page exists at all.
2625 $exists = $page->getArticleId() != 0;
2626 if( !$exists ) {
2627 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2628 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2629 } else {
2630 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2631 }
2632 } else {
2633 $dbr =& wfGetDB( DB_SLAVE );
2634 $wl_clause = array(
2635 'wl_title' => $page->getDBkey(),
2636 'wl_namespace' => $page->getNamespace() );
2637 $numwatchers = $dbr->selectField(
2638 'watchlist',
2639 'COUNT(*)',
2640 $wl_clause,
2641 __METHOD__,
2642 $this->getSelectOptions() );
2643
2644 $pageInfo = $this->pageCountInfo( $page );
2645 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2646
2647 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2648 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2649 if( $talkInfo ) {
2650 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2651 }
2652 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2653 if( $talkInfo ) {
2654 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2655 }
2656 $wgOut->addHTML( '</ul>' );
2657
2658 }
2659 }
2660
2661 /**
2662 * Return the total number of edits and number of unique editors
2663 * on a given page. If page does not exist, returns false.
2664 *
2665 * @param Title $title
2666 * @return array
2667 * @private
2668 */
2669 function pageCountInfo( $title ) {
2670 $id = $title->getArticleId();
2671 if( $id == 0 ) {
2672 return false;
2673 }
2674
2675 $dbr =& wfGetDB( DB_SLAVE );
2676
2677 $rev_clause = array( 'rev_page' => $id );
2678
2679 $edits = $dbr->selectField(
2680 'revision',
2681 'COUNT(rev_page)',
2682 $rev_clause,
2683 __METHOD__,
2684 $this->getSelectOptions() );
2685
2686 $authors = $dbr->selectField(
2687 'revision',
2688 'COUNT(DISTINCT rev_user_text)',
2689 $rev_clause,
2690 __METHOD__,
2691 $this->getSelectOptions() );
2692
2693 return array( 'edits' => $edits, 'authors' => $authors );
2694 }
2695
2696 /**
2697 * Return a list of templates used by this article.
2698 * Uses the templatelinks table
2699 *
2700 * @return array Array of Title objects
2701 */
2702 function getUsedTemplates() {
2703 $result = array();
2704 $id = $this->mTitle->getArticleID();
2705 if( $id == 0 ) {
2706 return array();
2707 }
2708
2709 $dbr =& wfGetDB( DB_SLAVE );
2710 $res = $dbr->select( array( 'templatelinks' ),
2711 array( 'tl_namespace', 'tl_title' ),
2712 array( 'tl_from' => $id ),
2713 'Article:getUsedTemplates' );
2714 if ( false !== $res ) {
2715 if ( $dbr->numRows( $res ) ) {
2716 while ( $row = $dbr->fetchObject( $res ) ) {
2717 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2718 }
2719 }
2720 }
2721 $dbr->freeResult( $res );
2722 return $result;
2723 }
2724
2725 /**
2726 * Return an auto-generated summary if the text provided is a redirect.
2727 *
2728 * @param string $text The wikitext to check
2729 * @return string '' or an appropriate summary
2730 */
2731 public static function getRedirectAutosummary( $text ) {
2732 $rt = Title::newFromRedirect( $text );
2733 if( is_object( $rt ) )
2734 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2735 else
2736 return '';
2737 }
2738
2739 /**
2740 * Return an auto-generated summary if the new text is much shorter than
2741 * the old text.
2742 *
2743 * @param string $oldtext The previous text of the page
2744 * @param string $text The submitted text of the page
2745 * @return string An appropriate autosummary, or an empty string.
2746 */
2747 public static function getBlankingAutosummary( $oldtext, $text ) {
2748 if ($oldtext!='' && $text=='') {
2749 return wfMsgForContent('autosumm-blank');
2750 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2751 #Removing more than 90% of the article
2752 global $wgContLang;
2753 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2754 return wfMsgForContent('autosumm-replace', $truncatedtext);
2755 } else {
2756 return '';
2757 }
2758 }
2759
2760 /**
2761 * Return an applicable autosummary if one exists for the given edit.
2762 * @param string $oldtext The previous text of the page.
2763 * @param string $newtext The submitted text of the page.
2764 * @param bitmask $flags A bitmask of flags submitted for the edit.
2765 * @return string An appropriate autosummary, or an empty string.
2766 */
2767 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2768
2769 # This code is UGLY UGLY UGLY.
2770 # Somebody PLEASE come up with a more elegant way to do it.
2771
2772 #Redirect autosummaries
2773 $summary = self::getRedirectAutosummary( $newtext );
2774
2775 if ($summary)
2776 return $summary;
2777
2778 #Blanking autosummaries
2779 if (!($flags & EDIT_NEW))
2780 $summary = self::getBlankingAutosummary( $oldtext, $newtext );
2781
2782 if ($summary)
2783 return $summary;
2784
2785 #New page autosummaries
2786 if ($flags & EDIT_NEW && strlen($newtext)) {
2787 #If they're making a new article, give its text, truncated, in the summary.
2788 global $wgContLang;
2789 $truncatedtext = $wgContLang->truncate(
2790 str_replace("\n", ' ', $newtext),
2791 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2792 '...' );
2793 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
2794 }
2795
2796 if ($summary)
2797 return $summary;
2798
2799 return $summary;
2800 }
2801
2802 /**
2803 * Add the primary page-view wikitext to the output buffer
2804 * Saves the text into the parser cache if possible.
2805 * Updates templatelinks if it is out of date.
2806 *
2807 * @param string $text
2808 * @param bool $cache
2809 */
2810 public function outputWikiText( $text, $cache = true ) {
2811 global $wgParser, $wgUser, $wgOut;
2812
2813 $popts = $wgOut->parserOptions();
2814 $popts->setTidy(true);
2815 $parserOutput = $wgParser->parse( $text, $this->mTitle,
2816 $popts, true, true, $this->getRevIdFetched() );
2817 $popts->setTidy(false);
2818 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
2819 $parserCache =& ParserCache::singleton();
2820 $parserCache->save( $parserOutput, $this, $wgUser );
2821 }
2822
2823 if ( !wfReadOnly() ) {
2824
2825 # Get templates from templatelinks
2826 $result = array();
2827 $id = $this->mTitle->getArticleID();
2828
2829 $tlTemplates = array();
2830
2831 $dbr =& wfGetDB( DB_SLAVE );
2832 $res = $dbr->select( array( 'templatelinks' ),
2833 array( 'tl_namespace', 'tl_title' ),
2834 array( 'tl_from' => $id ),
2835 'Article:getUsedTemplates' );
2836
2837 global $wgContLang;
2838
2839 if ( false !== $res ) {
2840 if ( $dbr->numRows( $res ) ) {
2841 while ( $row = $dbr->fetchObject( $res ) ) {
2842 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
2843 }
2844 }
2845 }
2846
2847 # Get templates from parser output.
2848 $poTemplates_allns = $parserOutput->getTemplates();
2849
2850 $poTemplates = array ();
2851 foreach ( $poTemplates_allns as $ns_templates ) {
2852 $poTemplates = array_merge( $poTemplates, $ns_templates );
2853 }
2854
2855 # Get the diff
2856 $templates_diff = array_diff( $poTemplates, $tlTemplates );
2857
2858 if ( count( $templates_diff ) > 0 ) {
2859 # Whee, link updates time.
2860 $u = new LinksUpdate( $this->mTitle, $parserOutput );
2861
2862 $dbw =& wfGetDb( DB_MASTER );
2863 $dbw->begin();
2864
2865 $u->doUpdate();
2866
2867 $dbw->commit();
2868 }
2869 }
2870
2871 $wgOut->addParserOutput( $parserOutput );
2872 }
2873
2874 }
2875
2876 ?>