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