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