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