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