Move the hook 'NewRevisionFromEditComplete'
[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 if( !$ok ) {
1463 /* Belated edit conflict! Run away!! */
1464 $good = false;
1465 $dbw->rollback();
1466 } else {
1467 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
1468
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 $reason string Prefilled reason
2172 */
2173 function confirmDelete( $reason ) {
2174 global $wgOut, $wgUser, $wgContLang;
2175 $align = $wgContLang->isRtl() ? 'left' : 'right';
2176
2177 wfDebug( "Article::confirmDelete\n" );
2178
2179 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2180 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2181 $wgOut->addWikiMsg( 'confirmdeletetext' );
2182
2183 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2184 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2185 $suppress .= Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2186 $suppress .= "</td></tr>";
2187 } else {
2188 $suppress = '';
2189 }
2190
2191 $form = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2192 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2193 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2194 Xml::openElement( 'table' ) .
2195 "<tr id=\"wpDeleteReasonListRow\">
2196 <td align='$align'>" .
2197 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2198 "</td>
2199 <td>" .
2200 Xml::listDropDown( 'wpDeleteReasonList',
2201 wfMsgForContent( 'deletereason-dropdown' ),
2202 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2203 "</td>
2204 </tr>
2205 <tr id=\"wpDeleteReasonRow\">
2206 <td align='$align'>" .
2207 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2208 "</td>
2209 <td>" .
2210 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2211 "</td>
2212 </tr>
2213 <tr>
2214 <td></td>
2215 <td>" .
2216 Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '3' ) ) .
2217 "</td>
2218 </tr>
2219 $suppress
2220 <tr>
2221 <td></td>
2222 <td>" .
2223 Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2224 "</td>
2225 </tr>" .
2226 Xml::closeElement( 'table' ) .
2227 Xml::closeElement( 'fieldset' ) .
2228 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2229 Xml::closeElement( 'form' );
2230
2231 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2232 $skin = $wgUser->getSkin();
2233 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2234 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2235 }
2236
2237 $wgOut->addHTML( $form );
2238 $this->showLogExtract( $wgOut );
2239 }
2240
2241
2242 /**
2243 * Show relevant lines from the deletion log
2244 */
2245 function showLogExtract( $out ) {
2246 $out->addHtml( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2247 LogEventsList::showLogExtract( $out, 'delete', $this->mTitle->getPrefixedText() );
2248 }
2249
2250
2251 /**
2252 * Perform a deletion and output success or failure messages
2253 */
2254 function doDelete( $reason, $suppress = false ) {
2255 global $wgOut, $wgUser;
2256 wfDebug( __METHOD__."\n" );
2257
2258 $id = $this->getId();
2259
2260 $error = '';
2261
2262 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error))) {
2263 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2264 $deleted = $this->mTitle->getPrefixedText();
2265
2266 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2267 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2268
2269 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2270
2271 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2272 $wgOut->returnToMain( false );
2273 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2274 } else {
2275 if ($error = '')
2276 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2277 else
2278 $wgOut->showFatalError( $error );
2279 }
2280 }
2281 }
2282
2283 /**
2284 * Back-end article deletion
2285 * Deletes the article with database consistency, writes logs, purges caches
2286 * Returns success
2287 */
2288 function doDeleteArticle( $reason, $suppress = false ) {
2289 global $wgUseSquid, $wgDeferredUpdateList;
2290 global $wgUseTrackbacks;
2291
2292 wfDebug( __METHOD__."\n" );
2293
2294 $dbw = wfGetDB( DB_MASTER );
2295 $ns = $this->mTitle->getNamespace();
2296 $t = $this->mTitle->getDBkey();
2297 $id = $this->mTitle->getArticleID();
2298
2299 if ( $t == '' || $id == 0 ) {
2300 return false;
2301 }
2302
2303 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2304 array_push( $wgDeferredUpdateList, $u );
2305
2306 // Bitfields to further suppress the content
2307 if ( $suppress ) {
2308 $bitfield = 0;
2309 // This should be 15...
2310 $bitfield |= Revision::DELETED_TEXT;
2311 $bitfield |= Revision::DELETED_COMMENT;
2312 $bitfield |= Revision::DELETED_USER;
2313 $bitfield |= Revision::DELETED_RESTRICTED;
2314 } else {
2315 $bitfield = 'rev_deleted';
2316 }
2317
2318 $dbw->begin();
2319 // For now, shunt the revision data into the archive table.
2320 // Text is *not* removed from the text table; bulk storage
2321 // is left intact to avoid breaking block-compression or
2322 // immutable storage schemes.
2323 //
2324 // For backwards compatibility, note that some older archive
2325 // table entries will have ar_text and ar_flags fields still.
2326 //
2327 // In the future, we may keep revisions and mark them with
2328 // the rev_deleted field, which is reserved for this purpose.
2329 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2330 array(
2331 'ar_namespace' => 'page_namespace',
2332 'ar_title' => 'page_title',
2333 'ar_comment' => 'rev_comment',
2334 'ar_user' => 'rev_user',
2335 'ar_user_text' => 'rev_user_text',
2336 'ar_timestamp' => 'rev_timestamp',
2337 'ar_minor_edit' => 'rev_minor_edit',
2338 'ar_rev_id' => 'rev_id',
2339 'ar_text_id' => 'rev_text_id',
2340 'ar_text' => '\'\'', // Be explicit to appease
2341 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2342 'ar_len' => 'rev_len',
2343 'ar_page_id' => 'page_id',
2344 'ar_deleted' => $bitfield
2345 ), array(
2346 'page_id' => $id,
2347 'page_id = rev_page'
2348 ), __METHOD__
2349 );
2350
2351 # Delete restrictions for it
2352 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2353
2354 # Fix category table counts
2355 $cats = array();
2356 $res = $dbw->select( 'categorylinks', 'cl_to',
2357 array( 'cl_from' => $id ), __METHOD__ );
2358 foreach( $res as $row ) {
2359 $cats []= $row->cl_to;
2360 }
2361 $this->updateCategoryCounts( array(), $cats );
2362
2363 # Now that it's safely backed up, delete it
2364 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2365 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2366 if( !$ok ) {
2367 $dbw->rollback();
2368 return false;
2369 }
2370
2371 # If using cascading deletes, we can skip some explicit deletes
2372 if ( !$dbw->cascadingDeletes() ) {
2373 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2374
2375 if ($wgUseTrackbacks)
2376 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2377
2378 # Delete outgoing links
2379 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2380 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2381 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2382 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2383 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2384 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2385 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2386 }
2387
2388 # If using cleanup triggers, we can skip some manual deletes
2389 if ( !$dbw->cleanupTriggers() ) {
2390
2391 # Clean up recentchanges entries...
2392 $dbw->delete( 'recentchanges',
2393 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG ),
2394 __METHOD__ );
2395 }
2396 $dbw->commit();
2397
2398 # Clear caches
2399 Article::onArticleDelete( $this->mTitle );
2400
2401 # Clear the cached article id so the interface doesn't act like we exist
2402 $this->mTitle->resetArticleID( 0 );
2403 $this->mTitle->mArticleID = 0;
2404
2405 # Log the deletion, if the page was suppressed, log it at Oversight instead
2406 $logtype = $suppress ? 'suppress' : 'delete';
2407 $log = new LogPage( $logtype );
2408
2409 # Make sure logging got through
2410 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2411
2412 return true;
2413 }
2414
2415 /**
2416 * Roll back the most recent consecutive set of edits to a page
2417 * from the same user; fails if there are no eligible edits to
2418 * roll back to, e.g. user is the sole contributor. This function
2419 * performs permissions checks on $wgUser, then calls commitRollback()
2420 * to do the dirty work
2421 *
2422 * @param string $fromP - Name of the user whose edits to rollback.
2423 * @param string $summary - Custom summary. Set to default summary if empty.
2424 * @param string $token - Rollback token.
2425 * @param bool $bot - If true, mark all reverted edits as bot.
2426 *
2427 * @param array $resultDetails contains result-specific array of additional values
2428 * 'alreadyrolled' : 'current' (rev)
2429 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2430 *
2431 * @return array of errors, each error formatted as
2432 * array(messagekey, param1, param2, ...).
2433 * On success, the array is empty. This array can also be passed to
2434 * OutputPage::showPermissionsErrorPage().
2435 */
2436 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2437 global $wgUser;
2438 $resultDetails = null;
2439
2440 # Check permissions
2441 $errors = array_merge( $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ),
2442 $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
2443 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2444 $errors[] = array( 'sessionfailure' );
2445
2446 if ( $wgUser->pingLimiter('rollback') || $wgUser->pingLimiter() ) {
2447 $errors[] = array( 'actionthrottledtext' );
2448 }
2449 # If there were errors, bail out now
2450 if(!empty($errors))
2451 return $errors;
2452
2453 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2454 }
2455
2456 /**
2457 * Backend implementation of doRollback(), please refer there for parameter
2458 * and return value documentation
2459 *
2460 * NOTE: This function does NOT check ANY permissions, it just commits the
2461 * rollback to the DB Therefore, you should only call this function direct-
2462 * ly if you want to use custom permissions checks. If you don't, use
2463 * doRollback() instead.
2464 */
2465 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2466 global $wgUseRCPatrol, $wgUser, $wgLang;
2467 $dbw = wfGetDB( DB_MASTER );
2468
2469 if( wfReadOnly() ) {
2470 return array( array( 'readonlytext' ) );
2471 }
2472
2473 # Get the last editor
2474 $current = Revision::newFromTitle( $this->mTitle );
2475 if( is_null( $current ) ) {
2476 # Something wrong... no page?
2477 return array(array('notanarticle'));
2478 }
2479
2480 $from = str_replace( '_', ' ', $fromP );
2481 if( $from != $current->getUserText() ) {
2482 $resultDetails = array( 'current' => $current );
2483 return array(array('alreadyrolled',
2484 htmlspecialchars($this->mTitle->getPrefixedText()),
2485 htmlspecialchars($fromP),
2486 htmlspecialchars($current->getUserText())
2487 ));
2488 }
2489
2490 # Get the last edit not by this guy
2491 $user = intval( $current->getUser() );
2492 $user_text = $dbw->addQuotes( $current->getUserText() );
2493 $s = $dbw->selectRow( 'revision',
2494 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2495 array( 'rev_page' => $current->getPage(),
2496 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2497 ), __METHOD__,
2498 array( 'USE INDEX' => 'page_timestamp',
2499 'ORDER BY' => 'rev_timestamp DESC' )
2500 );
2501 if( $s === false ) {
2502 # No one else ever edited this page
2503 return array(array('cantrollback'));
2504 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2505 # Only admins can see this text
2506 return array(array('notvisiblerev'));
2507 }
2508
2509 $set = array();
2510 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2511 # Mark all reverted edits as bot
2512 $set['rc_bot'] = 1;
2513 }
2514 if ( $wgUseRCPatrol ) {
2515 # Mark all reverted edits as patrolled
2516 $set['rc_patrolled'] = 1;
2517 }
2518
2519 if ( $set ) {
2520 $dbw->update( 'recentchanges', $set,
2521 array( /* WHERE */
2522 'rc_cur_id' => $current->getPage(),
2523 'rc_user_text' => $current->getUserText(),
2524 "rc_timestamp > '{$s->rev_timestamp}'",
2525 ), __METHOD__
2526 );
2527 }
2528
2529 # Generate the edit summary if necessary
2530 $target = Revision::newFromId( $s->rev_id );
2531 if( empty( $summary ) ){
2532 $summary = wfMsgForContent( 'revertpage' );
2533 }
2534
2535 # Allow the custom summary to use the same args as the default message
2536 $args = array(
2537 $target->getUserText(), $from, $s->rev_id,
2538 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2539 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2540 );
2541 $summary = wfMsgReplaceArgs( $summary, $args );
2542
2543 # Save
2544 $flags = EDIT_UPDATE;
2545
2546 if ($wgUser->isAllowed('minoredit'))
2547 $flags |= EDIT_MINOR;
2548
2549 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2550 $flags |= EDIT_FORCE_BOT;
2551 $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2552
2553 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2554
2555 $resultDetails = array(
2556 'summary' => $summary,
2557 'current' => $current,
2558 'target' => $target,
2559 );
2560 return array();
2561 }
2562
2563 /**
2564 * User interface for rollback operations
2565 */
2566 function rollback() {
2567 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2568 $details = null;
2569
2570 $result = $this->doRollback(
2571 $wgRequest->getVal( 'from' ),
2572 $wgRequest->getText( 'summary' ),
2573 $wgRequest->getVal( 'token' ),
2574 $wgRequest->getBool( 'bot' ),
2575 $details
2576 );
2577
2578 if( in_array( array( 'blocked' ), $result ) ) {
2579 $wgOut->blockedPage();
2580 return;
2581 }
2582 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2583 $wgOut->rateLimited();
2584 return;
2585 }
2586 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ){
2587 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2588 $errArray = $result[0];
2589 $errMsg = array_shift( $errArray );
2590 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2591 if( isset( $details['current'] ) ){
2592 $current = $details['current'];
2593 if( $current->getComment() != '' ) {
2594 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2595 }
2596 }
2597 return;
2598 }
2599 # Display permissions errors before read-only message -- there's no
2600 # point in misleading the user into thinking the inability to rollback
2601 # is only temporary.
2602 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2603 # array_diff is completely broken for arrays of arrays, sigh. Re-
2604 # move any 'readonlytext' error manually.
2605 $out = array();
2606 foreach( $result as $error ) {
2607 if( $error != array( 'readonlytext' ) ) {
2608 $out []= $error;
2609 }
2610 }
2611 $wgOut->showPermissionsErrorPage( $out );
2612 return;
2613 }
2614 if( $result == array( array('readonlytext') ) ) {
2615 $wgOut->readOnlyPage();
2616 return;
2617 }
2618
2619 $current = $details['current'];
2620 $target = $details['target'];
2621 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2622 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2623 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2624 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2625 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2626 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2627 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2628 $wgOut->returnToMain( false, $this->mTitle );
2629
2630 if( !$wgRequest->getBool( 'hidediff', false ) ) {
2631 $de = new DifferenceEngine( $this->mTitle, $current->getId(), 'next', false, true );
2632 $de->showDiff( '', '' );
2633 }
2634 }
2635
2636
2637 /**
2638 * Do standard deferred updates after page view
2639 * @private
2640 */
2641 function viewUpdates() {
2642 global $wgDeferredUpdateList, $wgUser;
2643
2644 if ( 0 != $this->getID() ) {
2645 # Don't update page view counters on views from bot users (bug 14044)
2646 global $wgDisableCounters;
2647 if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
2648 Article::incViewCount( $this->getID() );
2649 $u = new SiteStatsUpdate( 1, 0, 0 );
2650 array_push( $wgDeferredUpdateList, $u );
2651 }
2652 }
2653
2654 # Update newtalk / watchlist notification status
2655 $wgUser->clearNotification( $this->mTitle );
2656 }
2657
2658 /**
2659 * Prepare text which is about to be saved.
2660 * Returns a stdclass with source, pst and output members
2661 */
2662 function prepareTextForEdit( $text, $revid=null ) {
2663 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2664 // Already prepared
2665 return $this->mPreparedEdit;
2666 }
2667 global $wgParser;
2668 $edit = (object)array();
2669 $edit->revid = $revid;
2670 $edit->newText = $text;
2671 $edit->pst = $this->preSaveTransform( $text );
2672 $options = new ParserOptions;
2673 $options->setTidy( true );
2674 $options->enableLimitReport();
2675 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2676 $edit->oldText = $this->getContent();
2677 $this->mPreparedEdit = $edit;
2678 return $edit;
2679 }
2680
2681 /**
2682 * Do standard deferred updates after page edit.
2683 * Update links tables, site stats, search index and message cache.
2684 * Every 100th edit, prune the recent changes table.
2685 *
2686 * @private
2687 * @param $text New text of the article
2688 * @param $summary Edit summary
2689 * @param $minoredit Minor edit
2690 * @param $timestamp_of_pagechange Timestamp associated with the page change
2691 * @param $newid rev_id value of the new revision
2692 * @param $changed Whether or not the content actually changed
2693 */
2694 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2695 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2696
2697 wfProfileIn( __METHOD__ );
2698
2699 # Parse the text
2700 # Be careful not to double-PST: $text is usually already PST-ed once
2701 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2702 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2703 $editInfo = $this->prepareTextForEdit( $text, $newid );
2704 } else {
2705 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2706 $editInfo = $this->mPreparedEdit;
2707 }
2708
2709 # Save it to the parser cache
2710 if ( $wgEnableParserCache ) {
2711 $parserCache = ParserCache::singleton();
2712 $parserCache->save( $editInfo->output, $this, $wgUser );
2713 }
2714
2715 # Update the links tables
2716 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
2717 $u->doUpdate();
2718
2719 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2720 if ( 0 == mt_rand( 0, 99 ) ) {
2721 // Flush old entries from the `recentchanges` table; we do this on
2722 // random requests so as to avoid an increase in writes for no good reason
2723 global $wgRCMaxAge;
2724 $dbw = wfGetDB( DB_MASTER );
2725 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2726 $recentchanges = $dbw->tableName( 'recentchanges' );
2727 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2728 $dbw->query( $sql );
2729 }
2730 }
2731
2732 $id = $this->getID();
2733 $title = $this->mTitle->getPrefixedDBkey();
2734 $shortTitle = $this->mTitle->getDBkey();
2735
2736 if ( 0 == $id ) {
2737 wfProfileOut( __METHOD__ );
2738 return;
2739 }
2740
2741 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2742 array_push( $wgDeferredUpdateList, $u );
2743 $u = new SearchUpdate( $id, $title, $text );
2744 array_push( $wgDeferredUpdateList, $u );
2745
2746 # If this is another user's talk page, update newtalk
2747 # Don't do this if $changed = false otherwise some idiot can null-edit a
2748 # load of user talk pages and piss people off, nor if it's a minor edit
2749 # by a properly-flagged bot.
2750 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2751 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2752 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2753 $other = User::newFromName( $shortTitle );
2754 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2755 // An anonymous user
2756 $other = new User();
2757 $other->setName( $shortTitle );
2758 }
2759 if( $other ) {
2760 $other->setNewtalk( true );
2761 }
2762 }
2763 }
2764
2765 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2766 $wgMessageCache->replace( $shortTitle, $text );
2767 }
2768
2769 wfProfileOut( __METHOD__ );
2770 }
2771
2772 /**
2773 * Perform article updates on a special page creation.
2774 *
2775 * @param Revision $rev
2776 *
2777 * @todo This is a shitty interface function. Kill it and replace the
2778 * other shitty functions like editUpdates and such so it's not needed
2779 * anymore.
2780 */
2781 function createUpdates( $rev ) {
2782 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2783 $this->mTotalAdjustment = 1;
2784 $this->editUpdates( $rev->getText(), $rev->getComment(),
2785 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2786 }
2787
2788 /**
2789 * Generate the navigation links when browsing through an article revisions
2790 * It shows the information as:
2791 * Revision as of \<date\>; view current revision
2792 * \<- Previous version | Next Version -\>
2793 *
2794 * @private
2795 * @param string $oldid Revision ID of this article revision
2796 */
2797 function setOldSubtitle( $oldid=0 ) {
2798 global $wgLang, $wgOut, $wgUser;
2799
2800 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2801 return;
2802 }
2803
2804 $revision = Revision::newFromId( $oldid );
2805
2806 $current = ( $oldid == $this->mLatest );
2807 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2808 $sk = $wgUser->getSkin();
2809 $lnk = $current
2810 ? wfMsg( 'currentrevisionlink' )
2811 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2812 $curdiff = $current
2813 ? wfMsg( 'diff' )
2814 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2815 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2816 $prevlink = $prev
2817 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2818 : wfMsg( 'previousrevision' );
2819 $prevdiff = $prev
2820 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2821 : wfMsg( 'diff' );
2822 $nextlink = $current
2823 ? wfMsg( 'nextrevision' )
2824 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2825 $nextdiff = $current
2826 ? wfMsg( 'diff' )
2827 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2828
2829 $cdel='';
2830 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2831 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2832 if( $revision->isCurrent() ) {
2833 // We don't handle top deleted edits too well
2834 $cdel = wfMsgHtml('rev-delundel');
2835 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2836 // If revision was hidden from sysops
2837 $cdel = wfMsgHtml('rev-delundel');
2838 } else {
2839 $cdel = $sk->makeKnownLinkObj( $revdel,
2840 wfMsgHtml('rev-delundel'),
2841 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2842 '&oldid=' . urlencode( $oldid ) );
2843 // Bolden oversighted content
2844 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2845 $cdel = "<strong>$cdel</strong>";
2846 }
2847 $cdel = "(<small>$cdel</small>) ";
2848 }
2849 # Show user links if allowed to see them. Normally they
2850 # are hidden regardless, but since we can already see the text here...
2851 $userlinks = $sk->revUserTools( $revision, false );
2852
2853 $m = wfMsg( 'revision-info-current' );
2854 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2855 ? 'revision-info-current'
2856 : 'revision-info';
2857
2858 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2859
2860 "\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";
2861 $wgOut->setSubtitle( $r );
2862 }
2863
2864 /**
2865 * This function is called right before saving the wikitext,
2866 * so we can do things like signatures and links-in-context.
2867 *
2868 * @param string $text
2869 */
2870 function preSaveTransform( $text ) {
2871 global $wgParser, $wgUser;
2872 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2873 }
2874
2875 /* Caching functions */
2876
2877 /**
2878 * checkLastModified returns true if it has taken care of all
2879 * output to the client that is necessary for this request.
2880 * (that is, it has sent a cached version of the page)
2881 */
2882 function tryFileCache() {
2883 static $called = false;
2884 if( $called ) {
2885 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2886 return;
2887 }
2888 $called = true;
2889 if($this->isFileCacheable()) {
2890 $touched = $this->mTouched;
2891 $cache = new HTMLFileCache( $this->mTitle );
2892 if($cache->isFileCacheGood( $touched )) {
2893 wfDebug( "Article::tryFileCache(): about to load file\n" );
2894 $cache->loadFromFileCache();
2895 return true;
2896 } else {
2897 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2898 ob_start( array(&$cache, 'saveToFileCache' ) );
2899 }
2900 } else {
2901 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2902 }
2903 }
2904
2905 /**
2906 * Check if the page can be cached
2907 * @return bool
2908 */
2909 function isFileCacheable() {
2910 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2911 $action = $wgRequest->getVal( 'action' );
2912 $oldid = $wgRequest->getVal( 'oldid' );
2913 $diff = $wgRequest->getVal( 'diff' );
2914 $redirect = $wgRequest->getVal( 'redirect' );
2915 $printable = $wgRequest->getVal( 'printable' );
2916 $page = $wgRequest->getVal( 'page' );
2917
2918 //check for non-standard user language; this covers uselang,
2919 //and extensions for auto-detecting user language.
2920 $ulang = $wgLang->getCode();
2921 $clang = $wgContLang->getCode();
2922
2923 $cacheable = $wgUseFileCache
2924 && (!$wgShowIPinHeader)
2925 && ($this->getID() != 0)
2926 && ($wgUser->isAnon())
2927 && (!$wgUser->getNewtalk())
2928 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2929 && (empty( $action ) || $action == 'view')
2930 && (!isset($oldid))
2931 && (!isset($diff))
2932 && (!isset($redirect))
2933 && (!isset($printable))
2934 && !isset($page)
2935 && (!$this->mRedirectedFrom)
2936 && ($ulang === $clang);
2937
2938 if ( $cacheable ) {
2939 //extension may have reason to disable file caching on some pages.
2940 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2941 }
2942
2943 return $cacheable;
2944 }
2945
2946 /**
2947 * Loads page_touched and returns a value indicating if it should be used
2948 *
2949 */
2950 function checkTouched() {
2951 if( !$this->mDataLoaded ) {
2952 $this->loadPageData();
2953 }
2954 return !$this->mIsRedirect;
2955 }
2956
2957 /**
2958 * Get the page_touched field
2959 */
2960 function getTouched() {
2961 # Ensure that page data has been loaded
2962 if( !$this->mDataLoaded ) {
2963 $this->loadPageData();
2964 }
2965 return $this->mTouched;
2966 }
2967
2968 /**
2969 * Get the page_latest field
2970 */
2971 function getLatest() {
2972 if ( !$this->mDataLoaded ) {
2973 $this->loadPageData();
2974 }
2975 return $this->mLatest;
2976 }
2977
2978 /**
2979 * Edit an article without doing all that other stuff
2980 * The article must already exist; link tables etc
2981 * are not updated, caches are not flushed.
2982 *
2983 * @param string $text text submitted
2984 * @param string $comment comment submitted
2985 * @param bool $minor whereas it's a minor modification
2986 */
2987 function quickEdit( $text, $comment = '', $minor = 0 ) {
2988 wfProfileIn( __METHOD__ );
2989
2990 $dbw = wfGetDB( DB_MASTER );
2991 $dbw->begin();
2992 $revision = new Revision( array(
2993 'page' => $this->getId(),
2994 'text' => $text,
2995 'comment' => $comment,
2996 'minor_edit' => $minor ? 1 : 0,
2997 ) );
2998 $revision->insertOn( $dbw );
2999 $this->updateRevisionOn( $dbw, $revision );
3000 $dbw->commit();
3001
3002 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
3003
3004 wfProfileOut( __METHOD__ );
3005 }
3006
3007 /**
3008 * Used to increment the view counter
3009 *
3010 * @static
3011 * @param integer $id article id
3012 */
3013 function incViewCount( $id ) {
3014 $id = intval( $id );
3015 global $wgHitcounterUpdateFreq, $wgDBtype;
3016
3017 $dbw = wfGetDB( DB_MASTER );
3018 $pageTable = $dbw->tableName( 'page' );
3019 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3020 $acchitsTable = $dbw->tableName( 'acchits' );
3021
3022 if( $wgHitcounterUpdateFreq <= 1 ) {
3023 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3024 return;
3025 }
3026
3027 # Not important enough to warrant an error page in case of failure
3028 $oldignore = $dbw->ignoreErrors( true );
3029
3030 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3031
3032 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3033 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3034 # Most of the time (or on SQL errors), skip row count check
3035 $dbw->ignoreErrors( $oldignore );
3036 return;
3037 }
3038
3039 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3040 $row = $dbw->fetchObject( $res );
3041 $rown = intval( $row->n );
3042 if( $rown >= $wgHitcounterUpdateFreq ){
3043 wfProfileIn( 'Article::incViewCount-collect' );
3044 $old_user_abort = ignore_user_abort( true );
3045
3046 if ($wgDBtype == 'mysql')
3047 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3048 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3049 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3050 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3051 'GROUP BY hc_id');
3052 $dbw->query("DELETE FROM $hitcounterTable");
3053 if ($wgDBtype == 'mysql') {
3054 $dbw->query('UNLOCK TABLES');
3055 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3056 'WHERE page_id = hc_id');
3057 }
3058 else {
3059 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3060 "FROM $acchitsTable WHERE page_id = hc_id");
3061 }
3062 $dbw->query("DROP TABLE $acchitsTable");
3063
3064 ignore_user_abort( $old_user_abort );
3065 wfProfileOut( 'Article::incViewCount-collect' );
3066 }
3067 $dbw->ignoreErrors( $oldignore );
3068 }
3069
3070 /**#@+
3071 * The onArticle*() functions are supposed to be a kind of hooks
3072 * which should be called whenever any of the specified actions
3073 * are done.
3074 *
3075 * This is a good place to put code to clear caches, for instance.
3076 *
3077 * This is called on page move and undelete, as well as edit
3078 * @static
3079 * @param $title_obj a title object
3080 */
3081
3082 static function onArticleCreate($title) {
3083 # The talk page isn't in the regular link tables, so we need to update manually:
3084 if ( $title->isTalkPage() ) {
3085 $other = $title->getSubjectPage();
3086 } else {
3087 $other = $title->getTalkPage();
3088 }
3089 $other->invalidateCache();
3090 $other->purgeSquid();
3091
3092 $title->touchLinks();
3093 $title->purgeSquid();
3094 $title->deleteTitleProtection();
3095 }
3096
3097 static function onArticleDelete( $title ) {
3098 global $wgUseFileCache, $wgMessageCache;
3099
3100 // Update existence markers on article/talk tabs...
3101 if( $title->isTalkPage() ) {
3102 $other = $title->getSubjectPage();
3103 } else {
3104 $other = $title->getTalkPage();
3105 }
3106 $other->invalidateCache();
3107 $other->purgeSquid();
3108
3109 $title->touchLinks();
3110 $title->purgeSquid();
3111
3112 # File cache
3113 if ( $wgUseFileCache ) {
3114 $cm = new HTMLFileCache( $title );
3115 @unlink( $cm->fileCacheName() );
3116 }
3117
3118 # Messages
3119 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3120 $wgMessageCache->replace( $title->getDBkey(), false );
3121 }
3122 # Images
3123 if( $title->getNamespace() == NS_IMAGE ) {
3124 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3125 $update->doUpdate();
3126 }
3127 # User talk pages
3128 if( $title->getNamespace() == NS_USER_TALK ) {
3129 $user = User::newFromName( $title->getText(), false );
3130 $user->setNewtalk( false );
3131 }
3132 }
3133
3134 /**
3135 * Purge caches on page update etc
3136 */
3137 static function onArticleEdit( $title ) {
3138 global $wgDeferredUpdateList, $wgUseFileCache;
3139
3140 // Invalidate caches of articles which include this page
3141 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3142
3143 // Invalidate the caches of all pages which redirect here
3144 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3145
3146 # Purge squid for this page only
3147 $title->purgeSquid();
3148
3149 # Clear file cache
3150 if ( $wgUseFileCache ) {
3151 $cm = new HTMLFileCache( $title );
3152 @unlink( $cm->fileCacheName() );
3153 }
3154 }
3155
3156 /**#@-*/
3157
3158 /**
3159 * Overriden by ImagePage class, only present here to avoid a fatal error
3160 * Called for ?action=revert
3161 */
3162 public function revert(){
3163 global $wgOut;
3164 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3165 }
3166
3167 /**
3168 * Info about this page
3169 * Called for ?action=info when $wgAllowPageInfo is on.
3170 *
3171 * @public
3172 */
3173 function info() {
3174 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3175
3176 if ( !$wgAllowPageInfo ) {
3177 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3178 return;
3179 }
3180
3181 $page = $this->mTitle->getSubjectPage();
3182
3183 $wgOut->setPagetitle( $page->getPrefixedText() );
3184 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3185 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3186
3187 if( !$this->mTitle->exists() ) {
3188 $wgOut->addHtml( '<div class="noarticletext">' );
3189 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3190 // This doesn't quite make sense; the user is asking for
3191 // information about the _page_, not the message... -- RC
3192 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3193 } else {
3194 $msg = $wgUser->isLoggedIn()
3195 ? 'noarticletext'
3196 : 'noarticletextanon';
3197 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3198 }
3199 $wgOut->addHtml( '</div>' );
3200 } else {
3201 $dbr = wfGetDB( DB_SLAVE );
3202 $wl_clause = array(
3203 'wl_title' => $page->getDBkey(),
3204 'wl_namespace' => $page->getNamespace() );
3205 $numwatchers = $dbr->selectField(
3206 'watchlist',
3207 'COUNT(*)',
3208 $wl_clause,
3209 __METHOD__,
3210 $this->getSelectOptions() );
3211
3212 $pageInfo = $this->pageCountInfo( $page );
3213 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3214
3215 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3216 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3217 if( $talkInfo ) {
3218 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3219 }
3220 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3221 if( $talkInfo ) {
3222 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3223 }
3224 $wgOut->addHTML( '</ul>' );
3225
3226 }
3227 }
3228
3229 /**
3230 * Return the total number of edits and number of unique editors
3231 * on a given page. If page does not exist, returns false.
3232 *
3233 * @param Title $title
3234 * @return array
3235 * @private
3236 */
3237 function pageCountInfo( $title ) {
3238 $id = $title->getArticleId();
3239 if( $id == 0 ) {
3240 return false;
3241 }
3242
3243 $dbr = wfGetDB( DB_SLAVE );
3244
3245 $rev_clause = array( 'rev_page' => $id );
3246
3247 $edits = $dbr->selectField(
3248 'revision',
3249 'COUNT(rev_page)',
3250 $rev_clause,
3251 __METHOD__,
3252 $this->getSelectOptions() );
3253
3254 $authors = $dbr->selectField(
3255 'revision',
3256 'COUNT(DISTINCT rev_user_text)',
3257 $rev_clause,
3258 __METHOD__,
3259 $this->getSelectOptions() );
3260
3261 return array( 'edits' => $edits, 'authors' => $authors );
3262 }
3263
3264 /**
3265 * Return a list of templates used by this article.
3266 * Uses the templatelinks table
3267 *
3268 * @return array Array of Title objects
3269 */
3270 function getUsedTemplates() {
3271 $result = array();
3272 $id = $this->mTitle->getArticleID();
3273 if( $id == 0 ) {
3274 return array();
3275 }
3276
3277 $dbr = wfGetDB( DB_SLAVE );
3278 $res = $dbr->select( array( 'templatelinks' ),
3279 array( 'tl_namespace', 'tl_title' ),
3280 array( 'tl_from' => $id ),
3281 'Article:getUsedTemplates' );
3282 if ( false !== $res ) {
3283 if ( $dbr->numRows( $res ) ) {
3284 while ( $row = $dbr->fetchObject( $res ) ) {
3285 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3286 }
3287 }
3288 }
3289 $dbr->freeResult( $res );
3290 return $result;
3291 }
3292
3293 /**
3294 * Returns a list of hidden categories this page is a member of.
3295 * Uses the page_props and categorylinks tables.
3296 *
3297 * @return array Array of Title objects
3298 */
3299 function getHiddenCategories() {
3300 $result = array();
3301 $id = $this->mTitle->getArticleID();
3302 if( $id == 0 ) {
3303 return array();
3304 }
3305
3306 $dbr = wfGetDB( DB_SLAVE );
3307 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3308 array( 'cl_to' ),
3309 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3310 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3311 'Article:getHiddenCategories' );
3312 if ( false !== $res ) {
3313 if ( $dbr->numRows( $res ) ) {
3314 while ( $row = $dbr->fetchObject( $res ) ) {
3315 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3316 }
3317 }
3318 }
3319 $dbr->freeResult( $res );
3320 return $result;
3321 }
3322
3323 /**
3324 * Return an applicable autosummary if one exists for the given edit.
3325 * @param string $oldtext The previous text of the page.
3326 * @param string $newtext The submitted text of the page.
3327 * @param bitmask $flags A bitmask of flags submitted for the edit.
3328 * @return string An appropriate autosummary, or an empty string.
3329 */
3330 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3331 # Decide what kind of autosummary is needed.
3332
3333 # Redirect autosummaries
3334 $rt = Title::newFromRedirect( $newtext );
3335 if( is_object( $rt ) ) {
3336 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3337 }
3338
3339 # New page autosummaries
3340 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3341 # If they're making a new article, give its text, truncated, in the summary.
3342 global $wgContLang;
3343 $truncatedtext = $wgContLang->truncate(
3344 str_replace("\n", ' ', $newtext),
3345 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3346 '...' );
3347 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3348 }
3349
3350 # Blanking autosummaries
3351 if( $oldtext != '' && $newtext == '' ) {
3352 return wfMsgForContent('autosumm-blank');
3353 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3354 # Removing more than 90% of the article
3355 global $wgContLang;
3356 $truncatedtext = $wgContLang->truncate(
3357 $newtext,
3358 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3359 '...'
3360 );
3361 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3362 }
3363
3364 # If we reach this point, there's no applicable autosummary for our case, so our
3365 # autosummary is empty.
3366 return '';
3367 }
3368
3369 /**
3370 * Add the primary page-view wikitext to the output buffer
3371 * Saves the text into the parser cache if possible.
3372 * Updates templatelinks if it is out of date.
3373 *
3374 * @param string $text
3375 * @param bool $cache
3376 */
3377 public function outputWikiText( $text, $cache = true ) {
3378 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3379
3380 $popts = $wgOut->parserOptions();
3381 $popts->setTidy(true);
3382 $popts->enableLimitReport();
3383 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3384 $popts, true, true, $this->getRevIdFetched() );
3385 $popts->setTidy(false);
3386 $popts->enableLimitReport( false );
3387 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3388 $parserCache = ParserCache::singleton();
3389 $parserCache->save( $parserOutput, $this, $wgUser );
3390 }
3391
3392 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3393 // templatelinks table may have become out of sync,
3394 // especially if using variable-based transclusions.
3395 // For paranoia, check if things have changed and if
3396 // so apply updates to the database. This will ensure
3397 // that cascaded protections apply as soon as the changes
3398 // are visible.
3399
3400 # Get templates from templatelinks
3401 $id = $this->mTitle->getArticleID();
3402
3403 $tlTemplates = array();
3404
3405 $dbr = wfGetDB( DB_SLAVE );
3406 $res = $dbr->select( array( 'templatelinks' ),
3407 array( 'tl_namespace', 'tl_title' ),
3408 array( 'tl_from' => $id ),
3409 'Article:getUsedTemplates' );
3410
3411 global $wgContLang;
3412
3413 if ( false !== $res ) {
3414 if ( $dbr->numRows( $res ) ) {
3415 while ( $row = $dbr->fetchObject( $res ) ) {
3416 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3417 }
3418 }
3419 }
3420
3421 # Get templates from parser output.
3422 $poTemplates_allns = $parserOutput->getTemplates();
3423
3424 $poTemplates = array ();
3425 foreach ( $poTemplates_allns as $ns_templates ) {
3426 $poTemplates = array_merge( $poTemplates, $ns_templates );
3427 }
3428
3429 # Get the diff
3430 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3431
3432 if ( count( $templates_diff ) > 0 ) {
3433 # Whee, link updates time.
3434 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3435
3436 $dbw = wfGetDb( DB_MASTER );
3437 $dbw->begin();
3438
3439 $u->doUpdate();
3440
3441 $dbw->commit();
3442 }
3443 }
3444
3445 $wgOut->addParserOutput( $parserOutput );
3446 }
3447
3448 /**
3449 * Update all the appropriate counts in the category table, given that
3450 * we've added the categories $added and deleted the categories $deleted.
3451 *
3452 * @param $added array The names of categories that were added
3453 * @param $deleted array The names of categories that were deleted
3454 * @return null
3455 */
3456 public function updateCategoryCounts( $added, $deleted ) {
3457 $ns = $this->mTitle->getNamespace();
3458 $dbw = wfGetDB( DB_MASTER );
3459
3460 # First make sure the rows exist. If one of the "deleted" ones didn't
3461 # exist, we might legitimately not create it, but it's simpler to just
3462 # create it and then give it a negative value, since the value is bogus
3463 # anyway.
3464 #
3465 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3466 $insertCats = array_merge( $added, $deleted );
3467 if( !$insertCats ) {
3468 # Okay, nothing to do
3469 return;
3470 }
3471 $insertRows = array();
3472 foreach( $insertCats as $cat ) {
3473 $insertRows[] = array( 'cat_title' => $cat );
3474 }
3475 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3476
3477 $addFields = array( 'cat_pages = cat_pages + 1' );
3478 $removeFields = array( 'cat_pages = cat_pages - 1' );
3479 if( $ns == NS_CATEGORY ) {
3480 $addFields[] = 'cat_subcats = cat_subcats + 1';
3481 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3482 } elseif( $ns == NS_IMAGE ) {
3483 $addFields[] = 'cat_files = cat_files + 1';
3484 $removeFields[] = 'cat_files = cat_files - 1';
3485 }
3486
3487 if ( $added ) {
3488 $dbw->update(
3489 'category',
3490 $addFields,
3491 array( 'cat_title' => $added ),
3492 __METHOD__
3493 );
3494 }
3495 if ( $deleted ) {
3496 $dbw->update(
3497 'category',
3498 $removeFields,
3499 array( 'cat_title' => $deleted ),
3500 __METHOD__
3501 );
3502 }
3503 }
3504 }