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