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