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