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