Improve efficiency of autoreviewing of edits rollbacks and merge into main function
[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 integer $baseRevID, the revision ID this is based off
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, true, $baseRevID );
1449
1450 # Update page
1451 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1452
1453 if( !$ok ) {
1454 /* Belated edit conflict! Run away!! */
1455 $good = false;
1456 $dbw->rollback();
1457 } else {
1458 # Update recentchanges
1459 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1460 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1461 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1462 $revisionId );
1463
1464 # Mark as patrolled if the user can do so
1465 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1466 RecentChange::markPatrolled( $rcid );
1467 PatrolLog::record( $rcid, true );
1468 }
1469 }
1470 $wgUser->incEditCount();
1471 $dbw->commit();
1472 }
1473 } else {
1474 $revision = null;
1475 // Keep the same revision ID, but do some updates on it
1476 $revisionId = $this->getRevIdFetched();
1477 // Update page_touched, this is usually implicit in the page update
1478 // Other cache updates are done in onArticleEdit()
1479 $this->mTitle->invalidateCache();
1480 }
1481
1482 if( !$wgDBtransactions ) {
1483 ignore_user_abort( $userAbort );
1484 }
1485
1486 if ( $good ) {
1487 # Invalidate cache of this article and all pages using this article
1488 # as a template. Partly deferred.
1489 Article::onArticleEdit( $this->mTitle );
1490
1491 # Update links tables, site stats, etc.
1492 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1493 }
1494 } else {
1495 # Create new article
1496
1497 # Set statistics members
1498 # We work out if it's countable after PST to avoid counter drift
1499 # when articles are created with {{subst:}}
1500 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1501 $this->mTotalAdjustment = 1;
1502
1503 $dbw->begin();
1504
1505 # Add the page record; stake our claim on this title!
1506 # This will fail with a database query exception if the article already exists
1507 $newid = $this->insertOn( $dbw );
1508
1509 # Save the revision text...
1510 $revision = new Revision( array(
1511 'page' => $newid,
1512 'comment' => $summary,
1513 'minor_edit' => $isminor,
1514 'text' => $text
1515 ) );
1516 $revisionId = $revision->insertOn( $dbw, true );
1517
1518 $this->mTitle->resetArticleID( $newid );
1519
1520 # Update the page record with revision data
1521 $this->updateRevisionOn( $dbw, $revision, 0 );
1522
1523 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1524 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1525 '', strlen( $text ), $revisionId );
1526 # Mark as patrolled if the user can
1527 if( ($GLOBALS['wgUseRCPatrol'] || $GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1528 RecentChange::markPatrolled( $rcid );
1529 PatrolLog::record( $rcid, true );
1530 }
1531 }
1532 $wgUser->incEditCount();
1533 $dbw->commit();
1534
1535 # Update links, etc.
1536 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1537
1538 # Clear caches
1539 Article::onArticleCreate( $this->mTitle );
1540
1541 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1542 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1543 }
1544
1545 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1546 wfDoUpdates();
1547 }
1548
1549 if ( $good ) {
1550 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1551 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1552 }
1553
1554 wfProfileOut( __METHOD__ );
1555 return $good;
1556 }
1557
1558 /**
1559 * @deprecated wrapper for doRedirect
1560 */
1561 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1562 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1563 }
1564
1565 /**
1566 * Output a redirect back to the article.
1567 * This is typically used after an edit.
1568 *
1569 * @param boolean $noRedir Add redirect=no
1570 * @param string $sectionAnchor section to redirect to, including "#"
1571 * @param string $extraq, extra query params
1572 */
1573 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1574 global $wgOut;
1575 if ( $noRedir ) {
1576 $query = 'redirect=no';
1577 if( $extraq )
1578 $query .= "&$query";
1579 } else {
1580 $query = $extraq;
1581 }
1582 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1583 }
1584
1585 /**
1586 * Mark this particular edit/page as patrolled
1587 */
1588 function markpatrolled() {
1589 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1590 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1591
1592 # Check patrol config options
1593
1594 if ( !($wgUseNPPatrol || $wgUseRCPatrol)) {
1595 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1596 return;
1597 }
1598
1599 # If we haven't been given an rc_id value, we can't do anything
1600 $rcid = (int) $wgRequest->getVal('rcid');
1601 $rc = $rcid ? RecentChange::newFromId($rcid) : null;
1602 if ( is_null ( $rc ) )
1603 {
1604 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1605 return;
1606 }
1607
1608 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW) {
1609 // Only new pages can be patrolled if the general patrolling is off....???
1610 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1611 // front end here?
1612 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1613 return;
1614 }
1615
1616 # Check permissions
1617 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'patrol', $wgUser );
1618
1619 if (count($permission_errors)>0)
1620 {
1621 $wgOut->showPermissionsErrorPage( $permission_errors );
1622 return;
1623 }
1624
1625 # Handle the 'MarkPatrolled' hook
1626 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1627 return;
1628 }
1629
1630 #It would be nice to see where the user had actually come from, but for now just guess
1631 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1632 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1633
1634 # If it's left up to us, check that the user is allowed to patrol this edit
1635 # If the user has the "autopatrol" right, then we'll assume there are no
1636 # other conditions stopping them doing so
1637 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1638 $rc = RecentChange::newFromId( $rcid );
1639 # Graceful error handling, as we've done before here...
1640 # (If the recent change doesn't exist, then it doesn't matter whether
1641 # the user is allowed to patrol it or not; nothing is going to happen
1642 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1643 # The user made this edit, and can't patrol it
1644 # Tell them so, and then back off
1645 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1646 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1647 $wgOut->returnToMain( false, $return );
1648 return;
1649 }
1650 }
1651
1652 # Check that the revision isn't patrolled already
1653 # Prevents duplicate log entries
1654 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1655 # Mark the edit as patrolled
1656 RecentChange::markPatrolled( $rcid );
1657 PatrolLog::record( $rcid );
1658 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1659 }
1660
1661 # Inform the user
1662 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1663 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1664 $wgOut->returnToMain( false, $return );
1665 }
1666
1667 /**
1668 * User-interface handler for the "watch" action
1669 */
1670
1671 function watch() {
1672
1673 global $wgUser, $wgOut;
1674
1675 if ( $wgUser->isAnon() ) {
1676 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1677 return;
1678 }
1679 if ( wfReadOnly() ) {
1680 $wgOut->readOnlyPage();
1681 return;
1682 }
1683
1684 if( $this->doWatch() ) {
1685 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1686 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1687
1688 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1689 }
1690
1691 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1692 }
1693
1694 /**
1695 * Add this page to $wgUser's watchlist
1696 * @return bool true on successful watch operation
1697 */
1698 function doWatch() {
1699 global $wgUser;
1700 if( $wgUser->isAnon() ) {
1701 return false;
1702 }
1703
1704 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1705 $wgUser->addWatch( $this->mTitle );
1706
1707 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1708 }
1709
1710 return false;
1711 }
1712
1713 /**
1714 * User interface handler for the "unwatch" action.
1715 */
1716 function unwatch() {
1717
1718 global $wgUser, $wgOut;
1719
1720 if ( $wgUser->isAnon() ) {
1721 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1722 return;
1723 }
1724 if ( wfReadOnly() ) {
1725 $wgOut->readOnlyPage();
1726 return;
1727 }
1728
1729 if( $this->doUnwatch() ) {
1730 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1731 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1732
1733 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1734 }
1735
1736 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1737 }
1738
1739 /**
1740 * Stop watching a page
1741 * @return bool true on successful unwatch
1742 */
1743 function doUnwatch() {
1744 global $wgUser;
1745 if( $wgUser->isAnon() ) {
1746 return false;
1747 }
1748
1749 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1750 $wgUser->removeWatch( $this->mTitle );
1751
1752 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1753 }
1754
1755 return false;
1756 }
1757
1758 /**
1759 * action=protect handler
1760 */
1761 function protect() {
1762 $form = new ProtectionForm( $this );
1763 $form->execute();
1764 }
1765
1766 /**
1767 * action=unprotect handler (alias)
1768 */
1769 function unprotect() {
1770 $this->protect();
1771 }
1772
1773 /**
1774 * Update the article's restriction field, and leave a log entry.
1775 *
1776 * @param array $limit set of restriction keys
1777 * @param string $reason
1778 * @return bool true on success
1779 */
1780 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1781 global $wgUser, $wgRestrictionTypes, $wgContLang;
1782
1783 $id = $this->mTitle->getArticleID();
1784 if( array() != $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser ) || wfReadOnly() || $id == 0 ) {
1785 return false;
1786 }
1787
1788 if (!$cascade) {
1789 $cascade = false;
1790 }
1791
1792 // Take this opportunity to purge out expired restrictions
1793 Title::purgeExpiredRestrictions();
1794
1795 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1796 # we expect a single selection, but the schema allows otherwise.
1797 $current = array();
1798 foreach( $wgRestrictionTypes as $action )
1799 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1800
1801 $current = Article::flattenRestrictions( $current );
1802 $updated = Article::flattenRestrictions( $limit );
1803
1804 $changed = ( $current != $updated );
1805 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
1806 $changed = $changed || ($updated && $this->mTitle->mRestrictionsExpiry != $expiry);
1807 $protect = ( $updated != '' );
1808
1809 # If nothing's changed, do nothing
1810 if( $changed ) {
1811 global $wgGroupPermissions;
1812 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1813
1814 $dbw = wfGetDB( DB_MASTER );
1815
1816 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1817
1818 $expiry_description = '';
1819 if ( $encodedExpiry != 'infinity' ) {
1820 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1821 }
1822
1823 # Prepare a null revision to be added to the history
1824 $modified = $current != '' && $protect;
1825 if ( $protect ) {
1826 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1827 } else {
1828 $comment_type = 'unprotectedarticle';
1829 }
1830 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1831
1832 foreach( $limit as $action => $restrictions ) {
1833 # Check if the group level required to edit also can protect pages
1834 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1835 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1836 $wgGroupPermissions[$restrictions]['protect'] );
1837 }
1838
1839 $cascade_description = '';
1840 if ($cascade) {
1841 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1842 }
1843
1844 if( $reason )
1845 $comment .= ": $reason";
1846 if( $protect )
1847 $comment .= " [$updated]";
1848 if ( $expiry_description && $protect )
1849 $comment .= "$expiry_description";
1850 if ( $cascade )
1851 $comment .= "$cascade_description";
1852
1853 # Update restrictions table
1854 foreach( $limit as $action => $restrictions ) {
1855 if ($restrictions != '' ) {
1856 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1857 array( 'pr_page' => $id, 'pr_type' => $action
1858 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
1859 , 'pr_expiry' => $encodedExpiry ), __METHOD__ );
1860 } else {
1861 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1862 'pr_type' => $action ), __METHOD__ );
1863 }
1864 }
1865
1866 # Insert a null revision
1867 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1868 $nullRevId = $nullRevision->insertOn( $dbw );
1869
1870 # Update page record
1871 $dbw->update( 'page',
1872 array( /* SET */
1873 'page_touched' => $dbw->timestamp(),
1874 'page_restrictions' => '',
1875 'page_latest' => $nullRevId
1876 ), array( /* WHERE */
1877 'page_id' => $id
1878 ), 'Article::protect'
1879 );
1880 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1881
1882 # Update the protection log
1883 $log = new LogPage( 'protect' );
1884 if( $protect ) {
1885 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1886 } else {
1887 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1888 }
1889
1890 } # End hook
1891 } # End "changed" check
1892
1893 return true;
1894 }
1895
1896 /**
1897 * Take an array of page restrictions and flatten it to a string
1898 * suitable for insertion into the page_restrictions field.
1899 * @param array $limit
1900 * @return string
1901 * @private
1902 */
1903 function flattenRestrictions( $limit ) {
1904 if( !is_array( $limit ) ) {
1905 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1906 }
1907 $bits = array();
1908 ksort( $limit );
1909 foreach( $limit as $action => $restrictions ) {
1910 if( $restrictions != '' ) {
1911 $bits[] = "$action=$restrictions";
1912 }
1913 }
1914 return implode( ':', $bits );
1915 }
1916
1917 /**
1918 * Auto-generates a deletion reason
1919 * @param bool &$hasHistory Whether the page has a history
1920 */
1921 public function generateReason(&$hasHistory)
1922 {
1923 global $wgContLang;
1924 $dbw = wfGetDB(DB_MASTER);
1925 // Get the last revision
1926 $rev = Revision::newFromTitle($this->mTitle);
1927 if(is_null($rev))
1928 return false;
1929 // Get the article's contents
1930 $contents = $rev->getText();
1931 $blank = false;
1932 // If the page is blank, use the text from the previous revision,
1933 // which can only be blank if there's a move/import/protect dummy revision involved
1934 if($contents == '')
1935 {
1936 $prev = $rev->getPrevious();
1937 if($prev)
1938 {
1939 $contents = $prev->getText();
1940 $blank = true;
1941 }
1942 }
1943
1944 // Find out if there was only one contributor
1945 // Only scan the last 20 revisions
1946 $limit = 20;
1947 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__,
1948 array('LIMIT' => $limit));
1949 if($res === false)
1950 // This page has no revisions, which is very weird
1951 return false;
1952 if($res->numRows() > 1)
1953 $hasHistory = true;
1954 else
1955 $hasHistory = false;
1956 $row = $dbw->fetchObject($res);
1957 $onlyAuthor = $row->rev_user_text;
1958 // Try to find a second contributor
1959 while( $row = $dbw->fetchObject($res) ) {
1960 if($row->rev_user_text != $onlyAuthor) {
1961 $onlyAuthor = false;
1962 break;
1963 }
1964 }
1965 $dbw->freeResult($res);
1966
1967 // Generate the summary with a '$1' placeholder
1968 if($blank) {
1969 // The current revision is blank and the one before is also
1970 // blank. It's just not our lucky day
1971 $reason = wfMsgForContent('exbeforeblank', '$1');
1972 } else {
1973 if($onlyAuthor)
1974 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1975 else
1976 $reason = wfMsgForContent('excontent', '$1');
1977 }
1978
1979 // Replace newlines with spaces to prevent uglyness
1980 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1981 // Calculate the maximum amount of chars to get
1982 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1983 $maxLength = 255 - (strlen($reason) - 2) - 3;
1984 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1985 // Remove possible unfinished links
1986 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1987 // Now replace the '$1' placeholder
1988 $reason = str_replace( '$1', $contents, $reason );
1989 return $reason;
1990 }
1991
1992
1993 /*
1994 * UI entry point for page deletion
1995 */
1996 function delete() {
1997 global $wgUser, $wgOut, $wgRequest;
1998
1999 $confirm = $wgRequest->wasPosted() &&
2000 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2001
2002 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2003 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2004
2005 $reason = $this->DeleteReasonList;
2006
2007 if ( $reason != 'other' && $this->DeleteReason != '') {
2008 // Entry from drop down menu + additional comment
2009 $reason .= ': ' . $this->DeleteReason;
2010 } elseif ( $reason == 'other' ) {
2011 $reason = $this->DeleteReason;
2012 }
2013 # Flag to hide all contents of the archived revisions
2014 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('hiderevision');
2015
2016 # This code desperately needs to be totally rewritten
2017
2018 # Read-only check...
2019 if ( wfReadOnly() ) {
2020 $wgOut->readOnlyPage();
2021 return;
2022 }
2023
2024 # Check permissions
2025 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2026
2027 if (count($permission_errors)>0) {
2028 $wgOut->showPermissionsErrorPage( $permission_errors );
2029 return;
2030 }
2031
2032 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2033
2034 # Better double-check that it hasn't been deleted yet!
2035 $dbw = wfGetDB( DB_MASTER );
2036 $conds = $this->mTitle->pageCond();
2037 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2038 if ( $latest === false ) {
2039 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2040 return;
2041 }
2042
2043 # Hack for big sites
2044 $bigHistory = $this->isBigDeletion();
2045 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2046 global $wgLang, $wgDeleteRevisionsLimit;
2047 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2048 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2049 return;
2050 }
2051
2052 if( $confirm ) {
2053 $this->doDelete( $reason, $suppress );
2054 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2055 $this->doWatch();
2056 } elseif( $this->mTitle->userIsWatching() ) {
2057 $this->doUnwatch();
2058 }
2059 return;
2060 }
2061
2062 // Generate deletion reason
2063 $hasHistory = false;
2064 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2065
2066 // If the page has a history, insert a warning
2067 if( $hasHistory && !$confirm ) {
2068 $skin=$wgUser->getSkin();
2069 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2070 if( $bigHistory ) {
2071 global $wgLang, $wgDeleteRevisionsLimit;
2072 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2073 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2074 }
2075 }
2076
2077 return $this->confirmDelete( '', $reason );
2078 }
2079
2080 /**
2081 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2082 */
2083 function isBigDeletion() {
2084 global $wgDeleteRevisionsLimit;
2085 if( $wgDeleteRevisionsLimit ) {
2086 $revCount = $this->estimateRevisionCount();
2087 return $revCount > $wgDeleteRevisionsLimit;
2088 }
2089 return false;
2090 }
2091
2092 /**
2093 * @return int approximate revision count
2094 */
2095 function estimateRevisionCount() {
2096 $dbr = wfGetDB();
2097 // For an exact count...
2098 //return $dbr->selectField( 'revision', 'COUNT(*)',
2099 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2100 return $dbr->estimateRowCount( 'revision', '*',
2101 array( 'rev_page' => $this->getId() ), __METHOD__ );
2102 }
2103
2104 /**
2105 * Get the last N authors
2106 * @param int $num Number of revisions to get
2107 * @param string $revLatest The latest rev_id, selected from the master (optional)
2108 * @return array Array of authors, duplicates not removed
2109 */
2110 function getLastNAuthors( $num, $revLatest = 0 ) {
2111 wfProfileIn( __METHOD__ );
2112
2113 // First try the slave
2114 // If that doesn't have the latest revision, try the master
2115 $continue = 2;
2116 $db = wfGetDB( DB_SLAVE );
2117 do {
2118 $res = $db->select( array( 'page', 'revision' ),
2119 array( 'rev_id', 'rev_user_text' ),
2120 array(
2121 'page_namespace' => $this->mTitle->getNamespace(),
2122 'page_title' => $this->mTitle->getDBkey(),
2123 'rev_page = page_id'
2124 ), __METHOD__, $this->getSelectOptions( array(
2125 'ORDER BY' => 'rev_timestamp DESC',
2126 'LIMIT' => $num
2127 ) )
2128 );
2129 if ( !$res ) {
2130 wfProfileOut( __METHOD__ );
2131 return array();
2132 }
2133 $row = $db->fetchObject( $res );
2134 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2135 $db = wfGetDB( DB_MASTER );
2136 $continue--;
2137 } else {
2138 $continue = 0;
2139 }
2140 } while ( $continue );
2141
2142 $authors = array( $row->rev_user_text );
2143 while ( $row = $db->fetchObject( $res ) ) {
2144 $authors[] = $row->rev_user_text;
2145 }
2146 wfProfileOut( __METHOD__ );
2147 return $authors;
2148 }
2149
2150 /**
2151 * Output deletion confirmation dialog
2152 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2153 * @param $reason string Prefilled reason
2154 */
2155 function confirmDelete( $par, $reason ) {
2156 global $wgOut, $wgUser, $wgContLang;
2157 $align = $wgContLang->isRtl() ? 'left' : 'right';
2158
2159 wfDebug( "Article::confirmDelete\n" );
2160
2161 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2162 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2163 $wgOut->addWikiMsg( 'confirmdeletetext' );
2164
2165 if( $wgUser->isAllowed( 'hiderevision' ) ) {
2166 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2167 $suppress .= Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2168 $suppress .= "</td></tr>";
2169 } else {
2170 $suppress = '';
2171 }
2172
2173 $form = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2174 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2175 Xml::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2176 Xml::openElement( 'table' ) .
2177 "<tr id=\"wpDeleteReasonListRow\">
2178 <td align='$align'>" .
2179 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2180 "</td>
2181 <td>" .
2182 Xml::listDropDown( 'wpDeleteReasonList',
2183 wfMsgForContent( 'deletereason-dropdown' ),
2184 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2185 "</td>
2186 </tr>
2187 <tr id=\"wpDeleteReasonRow\">
2188 <td align='$align'>" .
2189 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2190 "</td>
2191 <td>" .
2192 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2193 "</td>
2194 </tr>
2195 <tr>
2196 <td></td>
2197 <td>" .
2198 Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '3' ) ) .
2199 "</td>
2200 </tr>
2201 $suppress
2202 <tr>
2203 <td></td>
2204 <td>" .
2205 Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2206 "</td>
2207 </tr>" .
2208 Xml::closeElement( 'table' ) .
2209 Xml::closeElement( 'fieldset' ) .
2210 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2211 Xml::closeElement( 'form' );
2212
2213 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2214 $skin = $wgUser->getSkin();
2215 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2216 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2217 }
2218
2219 $wgOut->addHTML( $form );
2220 $this->showLogExtract( $wgOut );
2221 }
2222
2223
2224 /**
2225 * Show relevant lines from the deletion log
2226 */
2227 function showLogExtract( $out ) {
2228 $out->addHtml( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2229 LogEventsList::showLogExtract( $out, 'delete', $this->mTitle->getPrefixedText() );
2230 }
2231
2232
2233 /**
2234 * Perform a deletion and output success or failure messages
2235 */
2236 function doDelete( $reason, $suppress = false ) {
2237 global $wgOut, $wgUser;
2238 wfDebug( __METHOD__."\n" );
2239
2240 $id = $this->getId();
2241
2242 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2243 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2244 $deleted = $this->mTitle->getPrefixedText();
2245
2246 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2247 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2248
2249 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2250
2251 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2252 $wgOut->returnToMain( false );
2253 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2254 } else {
2255 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2256 }
2257 }
2258 }
2259
2260 /**
2261 * Back-end article deletion
2262 * Deletes the article with database consistency, writes logs, purges caches
2263 * Returns success
2264 */
2265 function doDeleteArticle( $reason, $suppress = false ) {
2266 global $wgUseSquid, $wgDeferredUpdateList;
2267 global $wgUseTrackbacks;
2268
2269 wfDebug( __METHOD__."\n" );
2270
2271 $dbw = wfGetDB( DB_MASTER );
2272 $ns = $this->mTitle->getNamespace();
2273 $t = $this->mTitle->getDBkey();
2274 $id = $this->mTitle->getArticleID();
2275
2276 if ( $t == '' || $id == 0 ) {
2277 return false;
2278 }
2279
2280 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2281 array_push( $wgDeferredUpdateList, $u );
2282
2283 // Bitfields to further suppress the content
2284 if ( $suppress ) {
2285 $bitfield = 0;
2286 // This should be 15...
2287 $bitfield |= Revision::DELETED_TEXT;
2288 $bitfield |= Revision::DELETED_COMMENT;
2289 $bitfield |= Revision::DELETED_USER;
2290 $bitfield |= Revision::DELETED_RESTRICTED;
2291 } else {
2292 $bitfield = 'rev_deleted';
2293 }
2294
2295 $dbw->begin();
2296 // For now, shunt the revision data into the archive table.
2297 // Text is *not* removed from the text table; bulk storage
2298 // is left intact to avoid breaking block-compression or
2299 // immutable storage schemes.
2300 //
2301 // For backwards compatibility, note that some older archive
2302 // table entries will have ar_text and ar_flags fields still.
2303 //
2304 // In the future, we may keep revisions and mark them with
2305 // the rev_deleted field, which is reserved for this purpose.
2306 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2307 array(
2308 'ar_namespace' => 'page_namespace',
2309 'ar_title' => 'page_title',
2310 'ar_comment' => 'rev_comment',
2311 'ar_user' => 'rev_user',
2312 'ar_user_text' => 'rev_user_text',
2313 'ar_timestamp' => 'rev_timestamp',
2314 'ar_minor_edit' => 'rev_minor_edit',
2315 'ar_rev_id' => 'rev_id',
2316 'ar_text_id' => 'rev_text_id',
2317 'ar_text' => '\'\'', // Be explicit to appease
2318 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2319 'ar_len' => 'rev_len',
2320 'ar_page_id' => 'page_id',
2321 'ar_deleted' => $bitfield
2322 ), array(
2323 'page_id' => $id,
2324 'page_id = rev_page'
2325 ), __METHOD__
2326 );
2327
2328 # Delete restrictions for it
2329 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2330
2331 # Fix category table counts
2332 $cats = array();
2333 $res = $dbw->select( 'categorylinks', 'cl_to',
2334 array( 'cl_from' => $id ), __METHOD__ );
2335 foreach( $res as $row ) {
2336 $cats []= $row->cl_to;
2337 }
2338 $this->updateCategoryCounts( array(), $cats );
2339
2340 # Now that it's safely backed up, delete it
2341 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2342 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2343 if( !$ok ) {
2344 $dbw->rollback();
2345 return false;
2346 }
2347
2348 # If using cascading deletes, we can skip some explicit deletes
2349 if ( !$dbw->cascadingDeletes() ) {
2350 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2351
2352 if ($wgUseTrackbacks)
2353 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2354
2355 # Delete outgoing links
2356 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2357 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2358 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2359 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2360 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2361 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2362 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2363 }
2364
2365 # If using cleanup triggers, we can skip some manual deletes
2366 if ( !$dbw->cleanupTriggers() ) {
2367
2368 # Clean up recentchanges entries...
2369 $dbw->delete( 'recentchanges',
2370 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG ),
2371 __METHOD__ );
2372 }
2373 $dbw->commit();
2374
2375 # Clear caches
2376 Article::onArticleDelete( $this->mTitle );
2377
2378 # Clear the cached article id so the interface doesn't act like we exist
2379 $this->mTitle->resetArticleID( 0 );
2380 $this->mTitle->mArticleID = 0;
2381
2382 # Log the deletion, if the page was suppressed, log it at Oversight instead
2383 $logtype = $suppress ? 'suppress' : 'delete';
2384 $log = new LogPage( $logtype );
2385
2386 # Make sure logging got through
2387 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2388
2389 return true;
2390 }
2391
2392 /**
2393 * Roll back the most recent consecutive set of edits to a page
2394 * from the same user; fails if there are no eligible edits to
2395 * roll back to, e.g. user is the sole contributor. This function
2396 * performs permissions checks on $wgUser, then calls commitRollback()
2397 * to do the dirty work
2398 *
2399 * @param string $fromP - Name of the user whose edits to rollback.
2400 * @param string $summary - Custom summary. Set to default summary if empty.
2401 * @param string $token - Rollback token.
2402 * @param bool $bot - If true, mark all reverted edits as bot.
2403 *
2404 * @param array $resultDetails contains result-specific array of additional values
2405 * 'alreadyrolled' : 'current' (rev)
2406 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2407 *
2408 * @return array of errors, each error formatted as
2409 * array(messagekey, param1, param2, ...).
2410 * On success, the array is empty. This array can also be passed to
2411 * OutputPage::showPermissionsErrorPage().
2412 */
2413 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2414 global $wgUser;
2415 $resultDetails = null;
2416
2417 # Check permissions
2418 $errors = array_merge( $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ),
2419 $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
2420 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2421 $errors[] = array( 'sessionfailure' );
2422
2423 if ( $wgUser->pingLimiter('rollback') || $wgUser->pingLimiter() ) {
2424 $errors[] = array( 'actionthrottledtext' );
2425 }
2426 # If there were errors, bail out now
2427 if(!empty($errors))
2428 return $errors;
2429
2430 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2431 }
2432
2433 /**
2434 * Backend implementation of doRollback(), please refer there for parameter
2435 * and return value documentation
2436 *
2437 * NOTE: This function does NOT check ANY permissions, it just commits the
2438 * rollback to the DB Therefore, you should only call this function direct-
2439 * ly if you want to use custom permissions checks. If you don't, use
2440 * doRollback() instead.
2441 */
2442 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2443 global $wgUseRCPatrol, $wgUser, $wgLang;
2444 $dbw = wfGetDB( DB_MASTER );
2445
2446 if( wfReadOnly() ) {
2447 return array( array( 'readonlytext' ) );
2448 }
2449
2450 # Get the last editor
2451 $current = Revision::newFromTitle( $this->mTitle );
2452 if( is_null( $current ) ) {
2453 # Something wrong... no page?
2454 return array(array('notanarticle'));
2455 }
2456
2457 $from = str_replace( '_', ' ', $fromP );
2458 if( $from != $current->getUserText() ) {
2459 $resultDetails = array( 'current' => $current );
2460 return array(array('alreadyrolled',
2461 htmlspecialchars($this->mTitle->getPrefixedText()),
2462 htmlspecialchars($fromP),
2463 htmlspecialchars($current->getUserText())
2464 ));
2465 }
2466
2467 # Get the last edit not by this guy
2468 $user = intval( $current->getUser() );
2469 $user_text = $dbw->addQuotes( $current->getUserText() );
2470 $s = $dbw->selectRow( 'revision',
2471 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2472 array( 'rev_page' => $current->getPage(),
2473 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2474 ), __METHOD__,
2475 array( 'USE INDEX' => 'page_timestamp',
2476 'ORDER BY' => 'rev_timestamp DESC' )
2477 );
2478 if( $s === false ) {
2479 # No one else ever edited this page
2480 return array(array('cantrollback'));
2481 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2482 # Only admins can see this text
2483 return array(array('notvisiblerev'));
2484 }
2485
2486 $set = array();
2487 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2488 # Mark all reverted edits as bot
2489 $set['rc_bot'] = 1;
2490 }
2491 if ( $wgUseRCPatrol ) {
2492 # Mark all reverted edits as patrolled
2493 $set['rc_patrolled'] = 1;
2494 }
2495
2496 if ( $set ) {
2497 $dbw->update( 'recentchanges', $set,
2498 array( /* WHERE */
2499 'rc_cur_id' => $current->getPage(),
2500 'rc_user_text' => $current->getUserText(),
2501 "rc_timestamp > '{$s->rev_timestamp}'",
2502 ), __METHOD__
2503 );
2504 }
2505
2506 # Generate the edit summary if necessary
2507 $target = Revision::newFromId( $s->rev_id );
2508 if( empty( $summary ) ){
2509 $summary = wfMsgForContent( 'revertpage' );
2510 }
2511
2512 # Allow the custom summary to use the same args as the default message
2513 $args = array(
2514 $target->getUserText(), $from, $s->rev_id,
2515 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2516 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2517 );
2518 $summary = wfMsgReplaceArgs( $summary, $args );
2519
2520 # Save
2521 $flags = EDIT_UPDATE;
2522
2523 if ($wgUser->isAllowed('minoredit'))
2524 $flags |= EDIT_MINOR;
2525
2526 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2527 $flags |= EDIT_FORCE_BOT;
2528 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2529
2530 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2531
2532 $resultDetails = array(
2533 'summary' => $summary,
2534 'current' => $current,
2535 'target' => $target,
2536 );
2537 return array();
2538 }
2539
2540 /**
2541 * User interface for rollback operations
2542 */
2543 function rollback() {
2544 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2545 $details = null;
2546
2547 $result = $this->doRollback(
2548 $wgRequest->getVal( 'from' ),
2549 $wgRequest->getText( 'summary' ),
2550 $wgRequest->getVal( 'token' ),
2551 $wgRequest->getBool( 'bot' ),
2552 $details
2553 );
2554
2555 if( in_array( array( 'blocked' ), $result ) ) {
2556 $wgOut->blockedPage();
2557 return;
2558 }
2559 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2560 $wgOut->rateLimited();
2561 return;
2562 }
2563 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ){
2564 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2565 $errArray = $result[0];
2566 $errMsg = array_shift( $errArray );
2567 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2568 if( isset( $details['current'] ) ){
2569 $current = $details['current'];
2570 if( $current->getComment() != '' ) {
2571 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2572 }
2573 }
2574 return;
2575 }
2576 # Display permissions errors before read-only message -- there's no
2577 # point in misleading the user into thinking the inability to rollback
2578 # is only temporary.
2579 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2580 # array_diff is completely broken for arrays of arrays, sigh. Re-
2581 # move any 'readonlytext' error manually.
2582 $out = array();
2583 foreach( $result as $error ) {
2584 if( $error != array( 'readonlytext' ) ) {
2585 $out []= $error;
2586 }
2587 }
2588 $wgOut->showPermissionsErrorPage( $out );
2589 return;
2590 }
2591 if( $result == array( array('readonlytext') ) ) {
2592 $wgOut->readOnlyPage();
2593 return;
2594 }
2595
2596 $current = $details['current'];
2597 $target = $details['target'];
2598 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2599 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2600 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2601 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2602 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2603 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2604 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2605 $wgOut->returnToMain( false, $this->mTitle );
2606 }
2607
2608
2609 /**
2610 * Do standard deferred updates after page view
2611 * @private
2612 */
2613 function viewUpdates() {
2614 global $wgDeferredUpdateList, $wgUser;
2615
2616 if ( 0 != $this->getID() ) {
2617 # Don't update page view counters on views from bot users (bug 14044)
2618 global $wgDisableCounters;
2619 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2620 Article::incViewCount( $this->getID() );
2621 $u = new SiteStatsUpdate( 1, 0, 0 );
2622 array_push( $wgDeferredUpdateList, $u );
2623 }
2624 }
2625
2626 # Update newtalk / watchlist notification status
2627 $wgUser->clearNotification( $this->mTitle );
2628 }
2629
2630 /**
2631 * Prepare text which is about to be saved.
2632 * Returns a stdclass with source, pst and output members
2633 */
2634 function prepareTextForEdit( $text, $revid=null ) {
2635 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2636 // Already prepared
2637 return $this->mPreparedEdit;
2638 }
2639 global $wgParser;
2640 $edit = (object)array();
2641 $edit->revid = $revid;
2642 $edit->newText = $text;
2643 $edit->pst = $this->preSaveTransform( $text );
2644 $options = new ParserOptions;
2645 $options->setTidy( true );
2646 $options->enableLimitReport();
2647 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2648 $edit->oldText = $this->getContent();
2649 $this->mPreparedEdit = $edit;
2650 return $edit;
2651 }
2652
2653 /**
2654 * Do standard deferred updates after page edit.
2655 * Update links tables, site stats, search index and message cache.
2656 * Every 100th edit, prune the recent changes table.
2657 *
2658 * @private
2659 * @param $text New text of the article
2660 * @param $summary Edit summary
2661 * @param $minoredit Minor edit
2662 * @param $timestamp_of_pagechange Timestamp associated with the page change
2663 * @param $newid rev_id value of the new revision
2664 * @param $changed Whether or not the content actually changed
2665 */
2666 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2667 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2668
2669 wfProfileIn( __METHOD__ );
2670
2671 # Parse the text
2672 # Be careful not to double-PST: $text is usually already PST-ed once
2673 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2674 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2675 $editInfo = $this->prepareTextForEdit( $text, $newid );
2676 } else {
2677 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2678 $editInfo = $this->mPreparedEdit;
2679 }
2680
2681 # Save it to the parser cache
2682 if ( $wgEnableParserCache ) {
2683 $parserCache = ParserCache::singleton();
2684 $parserCache->save( $editInfo->output, $this, $wgUser );
2685 }
2686
2687 # Update the links tables
2688 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
2689 $u->doUpdate();
2690
2691 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2692 if ( 0 == mt_rand( 0, 99 ) ) {
2693 // Flush old entries from the `recentchanges` table; we do this on
2694 // random requests so as to avoid an increase in writes for no good reason
2695 global $wgRCMaxAge;
2696 $dbw = wfGetDB( DB_MASTER );
2697 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2698 $recentchanges = $dbw->tableName( 'recentchanges' );
2699 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2700 $dbw->query( $sql );
2701 }
2702 }
2703
2704 $id = $this->getID();
2705 $title = $this->mTitle->getPrefixedDBkey();
2706 $shortTitle = $this->mTitle->getDBkey();
2707
2708 if ( 0 == $id ) {
2709 wfProfileOut( __METHOD__ );
2710 return;
2711 }
2712
2713 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2714 array_push( $wgDeferredUpdateList, $u );
2715 $u = new SearchUpdate( $id, $title, $text );
2716 array_push( $wgDeferredUpdateList, $u );
2717
2718 # If this is another user's talk page, update newtalk
2719 # Don't do this if $changed = false otherwise some idiot can null-edit a
2720 # load of user talk pages and piss people off, nor if it's a minor edit
2721 # by a properly-flagged bot.
2722 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2723 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2724 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2725 $other = User::newFromName( $shortTitle );
2726 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2727 // An anonymous user
2728 $other = new User();
2729 $other->setName( $shortTitle );
2730 }
2731 if( $other ) {
2732 $other->setNewtalk( true );
2733 }
2734 }
2735 }
2736
2737 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2738 $wgMessageCache->replace( $shortTitle, $text );
2739 }
2740
2741 wfProfileOut( __METHOD__ );
2742 }
2743
2744 /**
2745 * Perform article updates on a special page creation.
2746 *
2747 * @param Revision $rev
2748 *
2749 * @todo This is a shitty interface function. Kill it and replace the
2750 * other shitty functions like editUpdates and such so it's not needed
2751 * anymore.
2752 */
2753 function createUpdates( $rev ) {
2754 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2755 $this->mTotalAdjustment = 1;
2756 $this->editUpdates( $rev->getText(), $rev->getComment(),
2757 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2758 }
2759
2760 /**
2761 * Generate the navigation links when browsing through an article revisions
2762 * It shows the information as:
2763 * Revision as of \<date\>; view current revision
2764 * \<- Previous version | Next Version -\>
2765 *
2766 * @private
2767 * @param string $oldid Revision ID of this article revision
2768 */
2769 function setOldSubtitle( $oldid=0 ) {
2770 global $wgLang, $wgOut, $wgUser;
2771
2772 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2773 return;
2774 }
2775
2776 $revision = Revision::newFromId( $oldid );
2777
2778 $current = ( $oldid == $this->mLatest );
2779 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2780 $sk = $wgUser->getSkin();
2781 $lnk = $current
2782 ? wfMsg( 'currentrevisionlink' )
2783 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2784 $curdiff = $current
2785 ? wfMsg( 'diff' )
2786 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2787 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2788 $prevlink = $prev
2789 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2790 : wfMsg( 'previousrevision' );
2791 $prevdiff = $prev
2792 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2793 : wfMsg( 'diff' );
2794 $nextlink = $current
2795 ? wfMsg( 'nextrevision' )
2796 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2797 $nextdiff = $current
2798 ? wfMsg( 'diff' )
2799 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2800
2801 $cdel='';
2802 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2803 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2804 if( $revision->isCurrent() ) {
2805 // We don't handle top deleted edits too well
2806 $cdel = wfMsgHtml('rev-delundel');
2807 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2808 // If revision was hidden from sysops
2809 $cdel = wfMsgHtml('rev-delundel');
2810 } else {
2811 $cdel = $sk->makeKnownLinkObj( $revdel,
2812 wfMsgHtml('rev-delundel'),
2813 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2814 '&oldid=' . urlencode( $oldid ) );
2815 // Bolden oversighted content
2816 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2817 $cdel = "<strong>$cdel</strong>";
2818 }
2819 $cdel = "(<small>$cdel</small>) ";
2820 }
2821 # Show user links if allowed to see them. Normally they
2822 # are hidden regardless, but since we can already see the text here...
2823 $userlinks = $sk->revUserTools( $revision, false );
2824
2825 $m = wfMsg( 'revision-info-current' );
2826 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2827 ? 'revision-info-current'
2828 : 'revision-info';
2829
2830 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2831
2832 "\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";
2833 $wgOut->setSubtitle( $r );
2834 }
2835
2836 /**
2837 * This function is called right before saving the wikitext,
2838 * so we can do things like signatures and links-in-context.
2839 *
2840 * @param string $text
2841 */
2842 function preSaveTransform( $text ) {
2843 global $wgParser, $wgUser;
2844 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2845 }
2846
2847 /* Caching functions */
2848
2849 /**
2850 * checkLastModified returns true if it has taken care of all
2851 * output to the client that is necessary for this request.
2852 * (that is, it has sent a cached version of the page)
2853 */
2854 function tryFileCache() {
2855 static $called = false;
2856 if( $called ) {
2857 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2858 return;
2859 }
2860 $called = true;
2861 if($this->isFileCacheable()) {
2862 $touched = $this->mTouched;
2863 $cache = new HTMLFileCache( $this->mTitle );
2864 if($cache->isFileCacheGood( $touched )) {
2865 wfDebug( "Article::tryFileCache(): about to load file\n" );
2866 $cache->loadFromFileCache();
2867 return true;
2868 } else {
2869 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2870 ob_start( array(&$cache, 'saveToFileCache' ) );
2871 }
2872 } else {
2873 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2874 }
2875 }
2876
2877 /**
2878 * Check if the page can be cached
2879 * @return bool
2880 */
2881 function isFileCacheable() {
2882 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2883 $action = $wgRequest->getVal( 'action' );
2884 $oldid = $wgRequest->getVal( 'oldid' );
2885 $diff = $wgRequest->getVal( 'diff' );
2886 $redirect = $wgRequest->getVal( 'redirect' );
2887 $printable = $wgRequest->getVal( 'printable' );
2888 $page = $wgRequest->getVal( 'page' );
2889
2890 //check for non-standard user language; this covers uselang,
2891 //and extensions for auto-detecting user language.
2892 $ulang = $wgLang->getCode();
2893 $clang = $wgContLang->getCode();
2894
2895 $cacheable = $wgUseFileCache
2896 && (!$wgShowIPinHeader)
2897 && ($this->getID() != 0)
2898 && ($wgUser->isAnon())
2899 && (!$wgUser->getNewtalk())
2900 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2901 && (empty( $action ) || $action == 'view')
2902 && (!isset($oldid))
2903 && (!isset($diff))
2904 && (!isset($redirect))
2905 && (!isset($printable))
2906 && !isset($page)
2907 && (!$this->mRedirectedFrom)
2908 && ($ulang === $clang);
2909
2910 if ( $cacheable ) {
2911 //extension may have reason to disable file caching on some pages.
2912 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2913 }
2914
2915 return $cacheable;
2916 }
2917
2918 /**
2919 * Loads page_touched and returns a value indicating if it should be used
2920 *
2921 */
2922 function checkTouched() {
2923 if( !$this->mDataLoaded ) {
2924 $this->loadPageData();
2925 }
2926 return !$this->mIsRedirect;
2927 }
2928
2929 /**
2930 * Get the page_touched field
2931 */
2932 function getTouched() {
2933 # Ensure that page data has been loaded
2934 if( !$this->mDataLoaded ) {
2935 $this->loadPageData();
2936 }
2937 return $this->mTouched;
2938 }
2939
2940 /**
2941 * Get the page_latest field
2942 */
2943 function getLatest() {
2944 if ( !$this->mDataLoaded ) {
2945 $this->loadPageData();
2946 }
2947 return $this->mLatest;
2948 }
2949
2950 /**
2951 * Edit an article without doing all that other stuff
2952 * The article must already exist; link tables etc
2953 * are not updated, caches are not flushed.
2954 *
2955 * @param string $text text submitted
2956 * @param string $comment comment submitted
2957 * @param bool $minor whereas it's a minor modification
2958 */
2959 function quickEdit( $text, $comment = '', $minor = 0 ) {
2960 wfProfileIn( __METHOD__ );
2961
2962 $dbw = wfGetDB( DB_MASTER );
2963 $dbw->begin();
2964 $revision = new Revision( array(
2965 'page' => $this->getId(),
2966 'text' => $text,
2967 'comment' => $comment,
2968 'minor_edit' => $minor ? 1 : 0,
2969 ) );
2970 $revision->insertOn( $dbw );
2971 $this->updateRevisionOn( $dbw, $revision );
2972 $dbw->commit();
2973
2974 wfProfileOut( __METHOD__ );
2975 }
2976
2977 /**
2978 * Used to increment the view counter
2979 *
2980 * @static
2981 * @param integer $id article id
2982 */
2983 function incViewCount( $id ) {
2984 $id = intval( $id );
2985 global $wgHitcounterUpdateFreq, $wgDBtype;
2986
2987 $dbw = wfGetDB( DB_MASTER );
2988 $pageTable = $dbw->tableName( 'page' );
2989 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2990 $acchitsTable = $dbw->tableName( 'acchits' );
2991
2992 if( $wgHitcounterUpdateFreq <= 1 ) {
2993 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2994 return;
2995 }
2996
2997 # Not important enough to warrant an error page in case of failure
2998 $oldignore = $dbw->ignoreErrors( true );
2999
3000 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3001
3002 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3003 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3004 # Most of the time (or on SQL errors), skip row count check
3005 $dbw->ignoreErrors( $oldignore );
3006 return;
3007 }
3008
3009 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3010 $row = $dbw->fetchObject( $res );
3011 $rown = intval( $row->n );
3012 if( $rown >= $wgHitcounterUpdateFreq ){
3013 wfProfileIn( 'Article::incViewCount-collect' );
3014 $old_user_abort = ignore_user_abort( true );
3015
3016 if ($wgDBtype == 'mysql')
3017 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3018 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3019 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3020 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3021 'GROUP BY hc_id');
3022 $dbw->query("DELETE FROM $hitcounterTable");
3023 if ($wgDBtype == 'mysql') {
3024 $dbw->query('UNLOCK TABLES');
3025 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3026 'WHERE page_id = hc_id');
3027 }
3028 else {
3029 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3030 "FROM $acchitsTable WHERE page_id = hc_id");
3031 }
3032 $dbw->query("DROP TABLE $acchitsTable");
3033
3034 ignore_user_abort( $old_user_abort );
3035 wfProfileOut( 'Article::incViewCount-collect' );
3036 }
3037 $dbw->ignoreErrors( $oldignore );
3038 }
3039
3040 /**#@+
3041 * The onArticle*() functions are supposed to be a kind of hooks
3042 * which should be called whenever any of the specified actions
3043 * are done.
3044 *
3045 * This is a good place to put code to clear caches, for instance.
3046 *
3047 * This is called on page move and undelete, as well as edit
3048 * @static
3049 * @param $title_obj a title object
3050 */
3051
3052 static function onArticleCreate($title) {
3053 # The talk page isn't in the regular link tables, so we need to update manually:
3054 if ( $title->isTalkPage() ) {
3055 $other = $title->getSubjectPage();
3056 } else {
3057 $other = $title->getTalkPage();
3058 }
3059 $other->invalidateCache();
3060 $other->purgeSquid();
3061
3062 $title->touchLinks();
3063 $title->purgeSquid();
3064 $title->deleteTitleProtection();
3065 }
3066
3067 static function onArticleDelete( $title ) {
3068 global $wgUseFileCache, $wgMessageCache;
3069
3070 // Update existence markers on article/talk tabs...
3071 if( $title->isTalkPage() ) {
3072 $other = $title->getSubjectPage();
3073 } else {
3074 $other = $title->getTalkPage();
3075 }
3076 $other->invalidateCache();
3077 $other->purgeSquid();
3078
3079 $title->touchLinks();
3080 $title->purgeSquid();
3081
3082 # File cache
3083 if ( $wgUseFileCache ) {
3084 $cm = new HTMLFileCache( $title );
3085 @unlink( $cm->fileCacheName() );
3086 }
3087
3088 if( $title->getNamespace() == NS_MEDIAWIKI) {
3089 $wgMessageCache->replace( $title->getDBkey(), false );
3090 }
3091 if( $title->getNamespace() == NS_IMAGE ) {
3092 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3093 $update->doUpdate();
3094 }
3095 }
3096
3097 /**
3098 * Purge caches on page update etc
3099 */
3100 static function onArticleEdit( $title ) {
3101 global $wgDeferredUpdateList, $wgUseFileCache;
3102
3103 // Invalidate caches of articles which include this page
3104 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3105
3106 // Invalidate the caches of all pages which redirect here
3107 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3108
3109 # Purge squid for this page only
3110 $title->purgeSquid();
3111
3112 # Clear file cache
3113 if ( $wgUseFileCache ) {
3114 $cm = new HTMLFileCache( $title );
3115 @unlink( $cm->fileCacheName() );
3116 }
3117 }
3118
3119 /**#@-*/
3120
3121 /**
3122 * Overriden by ImagePage class, only present here to avoid a fatal error
3123 * Called for ?action=revert
3124 */
3125 public function revert(){
3126 global $wgOut;
3127 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3128 }
3129
3130 /**
3131 * Info about this page
3132 * Called for ?action=info when $wgAllowPageInfo is on.
3133 *
3134 * @public
3135 */
3136 function info() {
3137 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3138
3139 if ( !$wgAllowPageInfo ) {
3140 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3141 return;
3142 }
3143
3144 $page = $this->mTitle->getSubjectPage();
3145
3146 $wgOut->setPagetitle( $page->getPrefixedText() );
3147 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3148 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3149
3150 if( !$this->mTitle->exists() ) {
3151 $wgOut->addHtml( '<div class="noarticletext">' );
3152 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3153 // This doesn't quite make sense; the user is asking for
3154 // information about the _page_, not the message... -- RC
3155 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3156 } else {
3157 $msg = $wgUser->isLoggedIn()
3158 ? 'noarticletext'
3159 : 'noarticletextanon';
3160 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3161 }
3162 $wgOut->addHtml( '</div>' );
3163 } else {
3164 $dbr = wfGetDB( DB_SLAVE );
3165 $wl_clause = array(
3166 'wl_title' => $page->getDBkey(),
3167 'wl_namespace' => $page->getNamespace() );
3168 $numwatchers = $dbr->selectField(
3169 'watchlist',
3170 'COUNT(*)',
3171 $wl_clause,
3172 __METHOD__,
3173 $this->getSelectOptions() );
3174
3175 $pageInfo = $this->pageCountInfo( $page );
3176 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3177
3178 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3179 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3180 if( $talkInfo ) {
3181 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3182 }
3183 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3184 if( $talkInfo ) {
3185 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3186 }
3187 $wgOut->addHTML( '</ul>' );
3188
3189 }
3190 }
3191
3192 /**
3193 * Return the total number of edits and number of unique editors
3194 * on a given page. If page does not exist, returns false.
3195 *
3196 * @param Title $title
3197 * @return array
3198 * @private
3199 */
3200 function pageCountInfo( $title ) {
3201 $id = $title->getArticleId();
3202 if( $id == 0 ) {
3203 return false;
3204 }
3205
3206 $dbr = wfGetDB( DB_SLAVE );
3207
3208 $rev_clause = array( 'rev_page' => $id );
3209
3210 $edits = $dbr->selectField(
3211 'revision',
3212 'COUNT(rev_page)',
3213 $rev_clause,
3214 __METHOD__,
3215 $this->getSelectOptions() );
3216
3217 $authors = $dbr->selectField(
3218 'revision',
3219 'COUNT(DISTINCT rev_user_text)',
3220 $rev_clause,
3221 __METHOD__,
3222 $this->getSelectOptions() );
3223
3224 return array( 'edits' => $edits, 'authors' => $authors );
3225 }
3226
3227 /**
3228 * Return a list of templates used by this article.
3229 * Uses the templatelinks table
3230 *
3231 * @return array Array of Title objects
3232 */
3233 function getUsedTemplates() {
3234 $result = array();
3235 $id = $this->mTitle->getArticleID();
3236 if( $id == 0 ) {
3237 return array();
3238 }
3239
3240 $dbr = wfGetDB( DB_SLAVE );
3241 $res = $dbr->select( array( 'templatelinks' ),
3242 array( 'tl_namespace', 'tl_title' ),
3243 array( 'tl_from' => $id ),
3244 'Article:getUsedTemplates' );
3245 if ( false !== $res ) {
3246 if ( $dbr->numRows( $res ) ) {
3247 while ( $row = $dbr->fetchObject( $res ) ) {
3248 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3249 }
3250 }
3251 }
3252 $dbr->freeResult( $res );
3253 return $result;
3254 }
3255
3256 /**
3257 * Returns a list of hidden categories this page is a member of.
3258 * Uses the page_props and categorylinks tables.
3259 *
3260 * @return array Array of Title objects
3261 */
3262 function getHiddenCategories() {
3263 $result = array();
3264 $id = $this->mTitle->getArticleID();
3265 if( $id == 0 ) {
3266 return array();
3267 }
3268
3269 $dbr = wfGetDB( DB_SLAVE );
3270 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3271 array( 'cl_to' ),
3272 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3273 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3274 'Article:getHiddenCategories' );
3275 if ( false !== $res ) {
3276 if ( $dbr->numRows( $res ) ) {
3277 while ( $row = $dbr->fetchObject( $res ) ) {
3278 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3279 }
3280 }
3281 }
3282 $dbr->freeResult( $res );
3283 return $result;
3284 }
3285
3286 /**
3287 * Return an auto-generated summary if the text provided is a redirect.
3288 *
3289 * @param string $text The wikitext to check
3290 * @return string '' or an appropriate summary
3291 */
3292 public static function getRedirectAutosummary( $text ) {
3293 $rt = Title::newFromRedirect( $text );
3294 if( is_object( $rt ) )
3295 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3296 else
3297 return '';
3298 }
3299
3300 /**
3301 * Return an auto-generated summary if the new text is much shorter than
3302 * the old text.
3303 *
3304 * @param string $oldtext The previous text of the page
3305 * @param string $text The submitted text of the page
3306 * @return string An appropriate autosummary, or an empty string.
3307 */
3308 public static function getBlankingAutosummary( $oldtext, $text ) {
3309 if ($oldtext!='' && $text=='') {
3310 return wfMsgForContent('autosumm-blank');
3311 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3312 #Removing more than 90% of the article
3313 global $wgContLang;
3314 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3315 return wfMsgForContent('autosumm-replace', $truncatedtext);
3316 } else {
3317 return '';
3318 }
3319 }
3320
3321 /**
3322 * Return an applicable autosummary if one exists for the given edit.
3323 * @param string $oldtext The previous text of the page.
3324 * @param string $newtext The submitted text of the page.
3325 * @param bitmask $flags A bitmask of flags submitted for the edit.
3326 * @return string An appropriate autosummary, or an empty string.
3327 */
3328 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3329 global $wgUseAutomaticEditSummaries;
3330 if ( !$wgUseAutomaticEditSummaries ) return '';
3331
3332 # This code is UGLY UGLY UGLY.
3333 # Somebody PLEASE come up with a more elegant way to do it.
3334
3335 #Redirect autosummaries
3336 $summary = self::getRedirectAutosummary( $newtext );
3337
3338 if ($summary)
3339 return $summary;
3340
3341 #Blanking autosummaries
3342 if (!($flags & EDIT_NEW))
3343 $summary = self::getBlankingAutosummary( $oldtext, $newtext );
3344
3345 if ($summary)
3346 return $summary;
3347
3348 #New page autosummaries
3349 if ($flags & EDIT_NEW && strlen($newtext)) {
3350 #If they're making a new article, give its text, truncated, in the summary.
3351 global $wgContLang;
3352 $truncatedtext = $wgContLang->truncate(
3353 str_replace("\n", ' ', $newtext),
3354 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3355 '...' );
3356 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3357 }
3358
3359 if ($summary)
3360 return $summary;
3361
3362 return $summary;
3363 }
3364
3365 /**
3366 * Add the primary page-view wikitext to the output buffer
3367 * Saves the text into the parser cache if possible.
3368 * Updates templatelinks if it is out of date.
3369 *
3370 * @param string $text
3371 * @param bool $cache
3372 */
3373 public function outputWikiText( $text, $cache = true ) {
3374 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3375
3376 $popts = $wgOut->parserOptions();
3377 $popts->setTidy(true);
3378 $popts->enableLimitReport();
3379 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3380 $popts, true, true, $this->getRevIdFetched() );
3381 $popts->setTidy(false);
3382 $popts->enableLimitReport( false );
3383 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3384 $parserCache = ParserCache::singleton();
3385 $parserCache->save( $parserOutput, $this, $wgUser );
3386 }
3387
3388 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3389 // templatelinks table may have become out of sync,
3390 // especially if using variable-based transclusions.
3391 // For paranoia, check if things have changed and if
3392 // so apply updates to the database. This will ensure
3393 // that cascaded protections apply as soon as the changes
3394 // are visible.
3395
3396 # Get templates from templatelinks
3397 $id = $this->mTitle->getArticleID();
3398
3399 $tlTemplates = array();
3400
3401 $dbr = wfGetDB( DB_SLAVE );
3402 $res = $dbr->select( array( 'templatelinks' ),
3403 array( 'tl_namespace', 'tl_title' ),
3404 array( 'tl_from' => $id ),
3405 'Article:getUsedTemplates' );
3406
3407 global $wgContLang;
3408
3409 if ( false !== $res ) {
3410 if ( $dbr->numRows( $res ) ) {
3411 while ( $row = $dbr->fetchObject( $res ) ) {
3412 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3413 }
3414 }
3415 }
3416
3417 # Get templates from parser output.
3418 $poTemplates_allns = $parserOutput->getTemplates();
3419
3420 $poTemplates = array ();
3421 foreach ( $poTemplates_allns as $ns_templates ) {
3422 $poTemplates = array_merge( $poTemplates, $ns_templates );
3423 }
3424
3425 # Get the diff
3426 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3427
3428 if ( count( $templates_diff ) > 0 ) {
3429 # Whee, link updates time.
3430 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3431
3432 $dbw = wfGetDb( DB_MASTER );
3433 $dbw->begin();
3434
3435 $u->doUpdate();
3436
3437 $dbw->commit();
3438 }
3439 }
3440
3441 $wgOut->addParserOutput( $parserOutput );
3442 }
3443
3444 /**
3445 * Update all the appropriate counts in the category table, given that
3446 * we've added the categories $added and deleted the categories $deleted.
3447 *
3448 * @param $added array The names of categories that were added
3449 * @param $deleted array The names of categories that were deleted
3450 * @return null
3451 */
3452 public function updateCategoryCounts( $added, $deleted ) {
3453 $ns = $this->mTitle->getNamespace();
3454 $dbw = wfGetDB( DB_MASTER );
3455
3456 # First make sure the rows exist. If one of the "deleted" ones didn't
3457 # exist, we might legitimately not create it, but it's simpler to just
3458 # create it and then give it a negative value, since the value is bogus
3459 # anyway.
3460 #
3461 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3462 $insertCats = array_merge( $added, $deleted );
3463 if( !$insertCats ) {
3464 # Okay, nothing to do
3465 return;
3466 }
3467 $insertRows = array();
3468 foreach( $insertCats as $cat ) {
3469 $insertRows[] = array( 'cat_title' => $cat );
3470 }
3471 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3472
3473 $addFields = array( 'cat_pages = cat_pages + 1' );
3474 $removeFields = array( 'cat_pages = cat_pages - 1' );
3475 if( $ns == NS_CATEGORY ) {
3476 $addFields[] = 'cat_subcats = cat_subcats + 1';
3477 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3478 } elseif( $ns == NS_IMAGE ) {
3479 $addFields[] = 'cat_files = cat_files + 1';
3480 $removeFields[] = 'cat_files = cat_files - 1';
3481 }
3482
3483 if ( $added ) {
3484 $dbw->update(
3485 'category',
3486 $addFields,
3487 array( 'cat_title' => $added ),
3488 __METHOD__
3489 );
3490 }
3491 if ( $deleted ) {
3492 $dbw->update(
3493 'category',
3494 $removeFields,
3495 array( 'cat_title' => $deleted ),
3496 __METHOD__
3497 );
3498 }
3499 }
3500 }