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