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