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