Make redirects work properly with flagging (bug 14714)
[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 static 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 * @todo Document, fixme $offset never used.
639 * @param $limit Integer: default 0.
640 * @param $offset Integer: default 0.
641 */
642 function getContributors($limit = 0, $offset = 0) {
643 # XXX: this is expensive; cache this info somewhere.
644
645 $contribs = array();
646 $dbr = wfGetDB( DB_SLAVE );
647 $revTable = $dbr->tableName( 'revision' );
648 $userTable = $dbr->tableName( 'user' );
649 $user = $this->getUser();
650 $pageId = $this->getId();
651
652 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
653 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
654 WHERE rev_page = $pageId
655 AND rev_user != $user
656 GROUP BY rev_user, rev_user_text, user_real_name
657 ORDER BY timestamp DESC";
658
659 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
660 $sql .= ' '. $this->getSelectOptions();
661
662 $res = $dbr->query($sql, __METHOD__);
663
664 while ( $line = $dbr->fetchObject( $res ) ) {
665 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
666 }
667
668 $dbr->freeResult($res);
669 return $contribs;
670 }
671
672 /**
673 * This is the default action of the script: just view the page of
674 * the given title.
675 */
676 function view() {
677 global $wgUser, $wgOut, $wgRequest, $wgContLang;
678 global $wgEnableParserCache, $wgStylePath, $wgParser;
679 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
680 global $wgDefaultRobotPolicy;
681 $sk = $wgUser->getSkin();
682
683 wfProfileIn( __METHOD__ );
684
685 $parserCache = ParserCache::singleton();
686 $ns = $this->mTitle->getNamespace(); # shortcut
687
688 # Get variables from query string
689 $oldid = $this->getOldID();
690
691 # getOldID may want us to redirect somewhere else
692 if ( $this->mRedirectUrl ) {
693 $wgOut->redirect( $this->mRedirectUrl );
694 wfProfileOut( __METHOD__ );
695 return;
696 }
697
698 $diff = $wgRequest->getVal( 'diff' );
699 $rcid = $wgRequest->getVal( 'rcid' );
700 $rdfrom = $wgRequest->getVal( 'rdfrom' );
701 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
702 $purge = $wgRequest->getVal( 'action' ) == 'purge';
703
704 $wgOut->setArticleFlag( true );
705
706 # Discourage indexing of printable versions, but encourage following
707 if( $wgOut->isPrintable() ) {
708 $policy = 'noindex,follow';
709 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
710 $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
711 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
712 # Honour customised robot policies for this namespace
713 $policy = $wgNamespaceRobotPolicies[$ns];
714 } else {
715 $policy = $wgDefaultRobotPolicy;
716 }
717 $wgOut->setRobotPolicy( $policy );
718
719 # If we got diff and oldid in the query, we want to see a
720 # diff page instead of the article.
721
722 if ( !is_null( $diff ) ) {
723 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
724
725 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge );
726 // DifferenceEngine directly fetched the revision:
727 $this->mRevIdFetched = $de->mNewid;
728 $de->showDiffPage( $diffOnly );
729
730 // Needed to get the page's current revision
731 $this->loadPageData();
732 if( $diff == 0 || $diff == $this->mLatest ) {
733 # Run view updates for current revision only
734 $this->viewUpdates();
735 }
736 wfProfileOut( __METHOD__ );
737 return;
738 }
739
740 if ( empty( $oldid ) && $this->checkTouched() ) {
741 $wgOut->setETag($parserCache->getETag($this, $wgUser));
742
743 if( $wgOut->checkLastModified( $this->mTouched ) ){
744 wfProfileOut( __METHOD__ );
745 return;
746 } else if ( $this->tryFileCache() ) {
747 # tell wgOut that output is taken care of
748 $wgOut->disable();
749 $this->viewUpdates();
750 wfProfileOut( __METHOD__ );
751 return;
752 }
753 }
754
755 # Should the parser cache be used?
756 $pcache = $this->useParserCache( $oldid );
757 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
758 if ( $wgUser->getOption( 'stubthreshold' ) ) {
759 wfIncrStats( 'pcache_miss_stub' );
760 }
761
762 $wasRedirected = false;
763 if ( isset( $this->mRedirectedFrom ) ) {
764 // This is an internally redirected page view.
765 // We'll need a backlink to the source page for navigation.
766 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
767 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
768 $s = wfMsg( 'redirectedfrom', $redir );
769 $wgOut->setSubtitle( $s );
770
771 // Set the fragment if one was specified in the redirect
772 if ( strval( $this->mTitle->getFragment() ) != '' ) {
773 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
774 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
775 }
776 $wasRedirected = true;
777 }
778 } elseif ( !empty( $rdfrom ) ) {
779 // This is an externally redirected view, from some other wiki.
780 // If it was reported from a trusted site, supply a backlink.
781 global $wgRedirectSources;
782 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
783 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
784 $s = wfMsg( 'redirectedfrom', $redir );
785 $wgOut->setSubtitle( $s );
786 $wasRedirected = true;
787 }
788 }
789
790 $outputDone = false;
791 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
792 if ( $pcache ) {
793 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
794 // Ensure that UI elements requiring revision ID have
795 // the correct version information.
796 $wgOut->setRevisionId( $this->mLatest );
797 $outputDone = true;
798 }
799 }
800 # Fetch content and check for errors
801 if ( !$outputDone ) {
802 $text = $this->getContent();
803 if ( $text === false ) {
804 # Failed to load, replace text with error message
805 $t = $this->mTitle->getPrefixedText();
806 if( $oldid ) {
807 $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
808 $text = wfMsg( 'missing-article', $t, $d );
809 } else {
810 $text = wfMsg( 'noarticletext' );
811 }
812 }
813
814 # Another whitelist check in case oldid is altering the title
815 if ( !$this->mTitle->userCanRead() ) {
816 $wgOut->loginToUse();
817 $wgOut->output();
818 wfProfileOut( __METHOD__ );
819 exit;
820 }
821
822 # We're looking at an old revision
823 if ( !empty( $oldid ) ) {
824 $wgOut->setRobotpolicy( 'noindex,nofollow' );
825 if( is_null( $this->mRevision ) ) {
826 // FIXME: This would be a nice place to load the 'no such page' text.
827 } else {
828 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
829 if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
830 if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
831 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
832 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
833 wfProfileOut( __METHOD__ );
834 return;
835 } else {
836 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
837 // and we are allowed to see...
838 }
839 }
840 }
841 }
842
843 $wgOut->setRevisionId( $this->getRevIdFetched() );
844
845 // Pages containing custom CSS or JavaScript get special treatment
846 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
847 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
848 // Give hooks a chance to customise the output
849 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
850 // Wrap the whole lot in a <pre> and don't parse
851 $m = array();
852 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
853 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
854 $wgOut->addHtml( htmlspecialchars( $this->mContent ) );
855 $wgOut->addHtml( "\n</pre>\n" );
856 }
857 } else if ( $rt = Title::newFromRedirect( $text ) ) {
858 # Don't append the subtitle if this was an old revision
859 $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() );
860 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
861 $wgOut->addParserOutputNoText( $parseout );
862 } else if ( $pcache ) {
863 # Display content and save to parser cache
864 $this->outputWikiText( $text );
865 } else {
866 # Display content, don't attempt to save to parser cache
867 # Don't show section-edit links on old revisions... this way lies madness.
868 if( !$this->isCurrent() ) {
869 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
870 }
871 # Display content and don't save to parser cache
872 # With timing hack -- TS 2006-07-26
873 $time = -wfTime();
874 $this->outputWikiText( $text, false );
875 $time += wfTime();
876
877 # Timing hack
878 if ( $time > 3 ) {
879 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
880 $this->mTitle->getPrefixedDBkey()));
881 }
882
883 if( !$this->isCurrent() ) {
884 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
885 }
886 }
887 }
888 /* title may have been set from the cache */
889 $t = $wgOut->getPageTitle();
890 if( empty( $t ) ) {
891 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
892 }
893
894 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
895 if( $ns == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
896 $wgOut->addWikiMsg('anontalkpagetext');
897 }
898
899 # If we have been passed an &rcid= parameter, we want to give the user a
900 # chance to mark this new article as patrolled.
901 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle->exists() ) {
902 $wgOut->addHTML(
903 "<div class='patrollink'>" .
904 wfMsgHtml( 'markaspatrolledlink',
905 $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
906 "action=markpatrolled&rcid=$rcid" )
907 ) .
908 '</div>'
909 );
910 }
911
912 # Trackbacks
913 if ($wgUseTrackbacks)
914 $this->addTrackbacks();
915
916 $this->viewUpdates();
917 wfProfileOut( __METHOD__ );
918 }
919
920 /*
921 * Should the parser cache be used?
922 */
923 protected function useParserCache( $oldid ) {
924 global $wgUser, $wgEnableParserCache;
925
926 return $wgEnableParserCache
927 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
928 && $this->exists()
929 && empty( $oldid )
930 && !$this->mTitle->isCssOrJsPage()
931 && !$this->mTitle->isCssJsSubpage();
932 }
933
934 protected function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
935 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
936
937 # Display redirect
938 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
939 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
940
941 if( $appendSubtitle ) {
942 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
943 }
944 $sk = $wgUser->getSkin();
945 if ( $forceKnown )
946 $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
947 else
948 $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
949
950 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
951 '<span class="redirectText">'.$link.'</span>' );
952
953 }
954
955 function addTrackbacks() {
956 global $wgOut, $wgUser;
957
958 $dbr = wfGetDB(DB_SLAVE);
959 $tbs = $dbr->select(
960 /* FROM */ 'trackbacks',
961 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
962 /* WHERE */ array('tb_page' => $this->getID())
963 );
964
965 if (!$dbr->numrows($tbs))
966 return;
967
968 $tbtext = "";
969 while ($o = $dbr->fetchObject($tbs)) {
970 $rmvtxt = "";
971 if ($wgUser->isAllowed( 'trackback' )) {
972 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
973 . $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
974 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
975 }
976 $tbtext .= "\n";
977 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
978 $o->tb_title,
979 $o->tb_url,
980 $o->tb_ex,
981 $o->tb_name,
982 $rmvtxt);
983 }
984 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
985 }
986
987 function deletetrackback() {
988 global $wgUser, $wgRequest, $wgOut, $wgTitle;
989
990 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
991 $wgOut->addWikiMsg( 'sessionfailure' );
992 return;
993 }
994
995 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
996
997 if (count($permission_errors)>0)
998 {
999 $wgOut->showPermissionsErrorPage( $permission_errors );
1000 return;
1001 }
1002
1003 $db = wfGetDB(DB_MASTER);
1004 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1005 $wgTitle->invalidateCache();
1006 $wgOut->addWikiMsg('trackbackdeleteok');
1007 }
1008
1009 function render() {
1010 global $wgOut;
1011
1012 $wgOut->setArticleBodyOnly(true);
1013 $this->view();
1014 }
1015
1016 /**
1017 * Handle action=purge
1018 */
1019 function purge() {
1020 global $wgUser, $wgRequest, $wgOut;
1021
1022 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1023 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1024 $this->doPurge();
1025 }
1026 } else {
1027 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1028 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1029 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1030 $msg = str_replace( '$1',
1031 "<form method=\"post\" action=\"$action\">\n" .
1032 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1033 "</form>\n", $msg );
1034
1035 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1036 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1037 $wgOut->addHTML( $msg );
1038 }
1039 }
1040
1041 /**
1042 * Perform the actions of a page purging
1043 */
1044 function doPurge() {
1045 global $wgUseSquid;
1046 // Invalidate the cache
1047 $this->mTitle->invalidateCache();
1048
1049 if ( $wgUseSquid ) {
1050 // Commit the transaction before the purge is sent
1051 $dbw = wfGetDB( DB_MASTER );
1052 $dbw->immediateCommit();
1053
1054 // Send purge
1055 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1056 $update->doUpdate();
1057 }
1058 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1059 global $wgMessageCache;
1060 if ( $this->getID() == 0 ) {
1061 $text = false;
1062 } else {
1063 $text = $this->getContent();
1064 }
1065 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1066 }
1067 $this->view();
1068 }
1069
1070 /**
1071 * Insert a new empty page record for this article.
1072 * This *must* be followed up by creating a revision
1073 * and running $this->updateToLatest( $rev_id );
1074 * or else the record will be left in a funky state.
1075 * Best if all done inside a transaction.
1076 *
1077 * @param Database $dbw
1078 * @return int The newly created page_id key
1079 * @private
1080 */
1081 function insertOn( $dbw ) {
1082 wfProfileIn( __METHOD__ );
1083
1084 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1085 $dbw->insert( 'page', array(
1086 'page_id' => $page_id,
1087 'page_namespace' => $this->mTitle->getNamespace(),
1088 'page_title' => $this->mTitle->getDBkey(),
1089 'page_counter' => 0,
1090 'page_restrictions' => '',
1091 'page_is_redirect' => 0, # Will set this shortly...
1092 'page_is_new' => 1,
1093 'page_random' => wfRandom(),
1094 'page_touched' => $dbw->timestamp(),
1095 'page_latest' => 0, # Fill this in shortly...
1096 'page_len' => 0, # Fill this in shortly...
1097 ), __METHOD__ );
1098 $newid = $dbw->insertId();
1099
1100 $this->mTitle->resetArticleId( $newid );
1101
1102 wfProfileOut( __METHOD__ );
1103 return $newid;
1104 }
1105
1106 /**
1107 * Update the page record to point to a newly saved revision.
1108 *
1109 * @param Database $dbw
1110 * @param Revision $revision For ID number, and text used to set
1111 length and redirect status fields
1112 * @param int $lastRevision If given, will not overwrite the page field
1113 * when different from the currently set value.
1114 * Giving 0 indicates the new page flag should
1115 * be set on.
1116 * @param bool $lastRevIsRedirect If given, will optimize adding and
1117 * removing rows in redirect table.
1118 * @return bool true on success, false on failure
1119 * @private
1120 */
1121 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1122 wfProfileIn( __METHOD__ );
1123
1124 $text = $revision->getText();
1125 $rt = Title::newFromRedirect( $text );
1126
1127 $conditions = array( 'page_id' => $this->getId() );
1128 if( !is_null( $lastRevision ) ) {
1129 # An extra check against threads stepping on each other
1130 $conditions['page_latest'] = $lastRevision;
1131 }
1132
1133 $dbw->update( 'page',
1134 array( /* SET */
1135 'page_latest' => $revision->getId(),
1136 'page_touched' => $dbw->timestamp(),
1137 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1138 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1139 'page_len' => strlen( $text ),
1140 ),
1141 $conditions,
1142 __METHOD__ );
1143
1144 $result = $dbw->affectedRows() != 0;
1145
1146 if ($result) {
1147 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1148 }
1149
1150 wfProfileOut( __METHOD__ );
1151 return $result;
1152 }
1153
1154 /**
1155 * Add row to the redirect table if this is a redirect, remove otherwise.
1156 *
1157 * @param Database $dbw
1158 * @param $redirectTitle a title object pointing to the redirect target,
1159 * or NULL if this is not a redirect
1160 * @param bool $lastRevIsRedirect If given, will optimize adding and
1161 * removing rows in redirect table.
1162 * @return bool true on success, false on failure
1163 * @private
1164 */
1165 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1166
1167 // Always update redirects (target link might have changed)
1168 // Update/Insert if we don't know if the last revision was a redirect or not
1169 // Delete if changing from redirect to non-redirect
1170 $isRedirect = !is_null($redirectTitle);
1171 if ($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1172
1173 wfProfileIn( __METHOD__ );
1174
1175 if ($isRedirect) {
1176
1177 // This title is a redirect, Add/Update row in the redirect table
1178 $set = array( /* SET */
1179 'rd_namespace' => $redirectTitle->getNamespace(),
1180 'rd_title' => $redirectTitle->getDBkey(),
1181 'rd_from' => $this->getId(),
1182 );
1183
1184 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1185 } else {
1186 // This is not a redirect, remove row from redirect table
1187 $where = array( 'rd_from' => $this->getId() );
1188 $dbw->delete( 'redirect', $where, __METHOD__);
1189 }
1190
1191 if( $this->getTitle()->getNamespace() == NS_IMAGE )
1192 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1193 wfProfileOut( __METHOD__ );
1194 return ( $dbw->affectedRows() != 0 );
1195 }
1196
1197 return true;
1198 }
1199
1200 /**
1201 * If the given revision is newer than the currently set page_latest,
1202 * update the page record. Otherwise, do nothing.
1203 *
1204 * @param Database $dbw
1205 * @param Revision $revision
1206 */
1207 function updateIfNewerOn( &$dbw, $revision ) {
1208 wfProfileIn( __METHOD__ );
1209
1210 $row = $dbw->selectRow(
1211 array( 'revision', 'page' ),
1212 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1213 array(
1214 'page_id' => $this->getId(),
1215 'page_latest=rev_id' ),
1216 __METHOD__ );
1217 if( $row ) {
1218 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1219 wfProfileOut( __METHOD__ );
1220 return false;
1221 }
1222 $prev = $row->rev_id;
1223 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1224 } else {
1225 # No or missing previous revision; mark the page as new
1226 $prev = 0;
1227 $lastRevIsRedirect = null;
1228 }
1229
1230 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1231 wfProfileOut( __METHOD__ );
1232 return $ret;
1233 }
1234
1235 /**
1236 * @return string Complete article text, or null if error
1237 */
1238 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1239 wfProfileIn( __METHOD__ );
1240
1241 if( $section == '' ) {
1242 // Whole-page edit; let the text through unmolested.
1243 } else {
1244 if( is_null( $edittime ) ) {
1245 $rev = Revision::newFromTitle( $this->mTitle );
1246 } else {
1247 $dbw = wfGetDB( DB_MASTER );
1248 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1249 }
1250 if( is_null( $rev ) ) {
1251 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1252 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1253 return null;
1254 }
1255 $oldtext = $rev->getText();
1256
1257 if( $section == 'new' ) {
1258 # Inserting a new section
1259 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1260 $text = strlen( trim( $oldtext ) ) > 0
1261 ? "{$oldtext}\n\n{$subject}{$text}"
1262 : "{$subject}{$text}";
1263 } else {
1264 # Replacing an existing section; roll out the big guns
1265 global $wgParser;
1266 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1267 }
1268
1269 }
1270
1271 wfProfileOut( __METHOD__ );
1272 return $text;
1273 }
1274
1275 /**
1276 * @deprecated use Article::doEdit()
1277 */
1278 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1279 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1280 ( $isminor ? EDIT_MINOR : 0 ) |
1281 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1282 ( $bot ? EDIT_FORCE_BOT : 0 );
1283
1284 # If this is a comment, add the summary as headline
1285 if ( $comment && $summary != "" ) {
1286 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1287 }
1288
1289 $this->doEdit( $text, $summary, $flags );
1290
1291 $dbw = wfGetDB( DB_MASTER );
1292 if ($watchthis) {
1293 if (!$this->mTitle->userIsWatching()) {
1294 $dbw->begin();
1295 $this->doWatch();
1296 $dbw->commit();
1297 }
1298 } else {
1299 if ( $this->mTitle->userIsWatching() ) {
1300 $dbw->begin();
1301 $this->doUnwatch();
1302 $dbw->commit();
1303 }
1304 }
1305 $this->doRedirect( $this->isRedirect( $text ) );
1306 }
1307
1308 /**
1309 * @deprecated use Article::doEdit()
1310 */
1311 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1312 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1313 ( $minor ? EDIT_MINOR : 0 ) |
1314 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1315
1316 $good = $this->doEdit( $text, $summary, $flags );
1317 if ( $good ) {
1318 $dbw = wfGetDB( DB_MASTER );
1319 if ($watchthis) {
1320 if (!$this->mTitle->userIsWatching()) {
1321 $dbw->begin();
1322 $this->doWatch();
1323 $dbw->commit();
1324 }
1325 } else {
1326 if ( $this->mTitle->userIsWatching() ) {
1327 $dbw->begin();
1328 $this->doUnwatch();
1329 $dbw->commit();
1330 }
1331 }
1332
1333 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1334 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1335
1336 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1337 }
1338 return $good;
1339 }
1340
1341 /**
1342 * Article::doEdit()
1343 *
1344 * Change an existing article or create a new article. Updates RC and all necessary caches,
1345 * optionally via the deferred update array.
1346 *
1347 * $wgUser must be set before calling this function.
1348 *
1349 * @param string $text New text
1350 * @param string $summary Edit summary
1351 * @param integer $flags bitfield:
1352 * EDIT_NEW
1353 * Article is known or assumed to be non-existent, create a new one
1354 * EDIT_UPDATE
1355 * Article is known or assumed to be pre-existing, update it
1356 * EDIT_MINOR
1357 * Mark this edit minor, if the user is allowed to do so
1358 * EDIT_SUPPRESS_RC
1359 * Do not log the change in recentchanges
1360 * EDIT_FORCE_BOT
1361 * Mark the edit a "bot" edit regardless of user rights
1362 * EDIT_DEFER_UPDATES
1363 * Defer some of the updates until the end of index.php
1364 * EDIT_AUTOSUMMARY
1365 * Fill in blank summaries with generated text where possible
1366 *
1367 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1368 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1369 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1370 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1371 * to MediaWiki's performance-optimised locking strategy.
1372 * @param $baseRevId, the revision ID this edit was based off, if any
1373 *
1374 * @return bool success
1375 */
1376 function doEdit( $text, $summary, $flags = 0, $baseRevId = false ) {
1377 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1378
1379 wfProfileIn( __METHOD__ );
1380 $good = true;
1381
1382 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1383 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1384 if ( $aid ) {
1385 $flags |= EDIT_UPDATE;
1386 } else {
1387 $flags |= EDIT_NEW;
1388 }
1389 }
1390
1391 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1392 &$summary, $flags & EDIT_MINOR,
1393 null, null, &$flags ) ) )
1394 {
1395 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1396 wfProfileOut( __METHOD__ );
1397 return false;
1398 }
1399
1400 # Silently ignore EDIT_MINOR if not allowed
1401 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1402 $bot = $flags & EDIT_FORCE_BOT;
1403
1404 $oldtext = $this->getContent();
1405 $oldsize = strlen( $oldtext );
1406
1407 # Provide autosummaries if one is not provided and autosummaries are enabled.
1408 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1409 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1410 }
1411
1412 $editInfo = $this->prepareTextForEdit( $text );
1413 $text = $editInfo->pst;
1414 $newsize = strlen( $text );
1415
1416 $dbw = wfGetDB( DB_MASTER );
1417 $now = wfTimestampNow();
1418
1419 if ( $flags & EDIT_UPDATE ) {
1420 # Update article, but only if changed.
1421
1422 # Make sure the revision is either completely inserted or not inserted at all
1423 if( !$wgDBtransactions ) {
1424 $userAbort = ignore_user_abort( true );
1425 }
1426
1427 $lastRevision = 0;
1428 $revisionId = 0;
1429
1430 $changed = ( strcmp( $text, $oldtext ) != 0 );
1431
1432 if ( $changed ) {
1433 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1434 - (int)$this->isCountable( $oldtext );
1435 $this->mTotalAdjustment = 0;
1436
1437 $lastRevision = $dbw->selectField(
1438 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1439
1440 if ( !$lastRevision ) {
1441 # Article gone missing
1442 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1443 wfProfileOut( __METHOD__ );
1444 return false;
1445 }
1446
1447 $revision = new Revision( array(
1448 'page' => $this->getId(),
1449 'comment' => $summary,
1450 'minor_edit' => $isminor,
1451 'text' => $text,
1452 'parent_id' => $lastRevision
1453 ) );
1454
1455 $dbw->begin();
1456 $revisionId = $revision->insertOn( $dbw );
1457
1458 # Update page
1459 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1460
1461 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId) );
1462
1463 if( !$ok ) {
1464 /* Belated edit conflict! Run away!! */
1465 $good = false;
1466 $dbw->rollback();
1467 } else {
1468 # Update recentchanges
1469 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1470 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1471 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1472 $revisionId );
1473
1474 # Mark as patrolled if the user can do so
1475 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1476 RecentChange::markPatrolled( $rcid );
1477 PatrolLog::record( $rcid, true );
1478 }
1479 }
1480 $wgUser->incEditCount();
1481 $dbw->commit();
1482 }
1483 } else {
1484 $revision = null;
1485 // Keep the same revision ID, but do some updates on it
1486 $revisionId = $this->getRevIdFetched();
1487 // Update page_touched, this is usually implicit in the page update
1488 // Other cache updates are done in onArticleEdit()
1489 $this->mTitle->invalidateCache();
1490 }
1491
1492 if( !$wgDBtransactions ) {
1493 ignore_user_abort( $userAbort );
1494 }
1495
1496 if ( $good ) {
1497 # Invalidate cache of this article and all pages using this article
1498 # as a template. Partly deferred.
1499 Article::onArticleEdit( $this->mTitle );
1500
1501 # Update links tables, site stats, etc.
1502 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1503 }
1504 } else {
1505 # Create new article
1506
1507 # Set statistics members
1508 # We work out if it's countable after PST to avoid counter drift
1509 # when articles are created with {{subst:}}
1510 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1511 $this->mTotalAdjustment = 1;
1512
1513 $dbw->begin();
1514
1515 # Add the page record; stake our claim on this title!
1516 # This will fail with a database query exception if the article already exists
1517 $newid = $this->insertOn( $dbw );
1518
1519 # Save the revision text...
1520 $revision = new Revision( array(
1521 'page' => $newid,
1522 'comment' => $summary,
1523 'minor_edit' => $isminor,
1524 'text' => $text
1525 ) );
1526 $revisionId = $revision->insertOn( $dbw );
1527
1528 $this->mTitle->resetArticleID( $newid );
1529
1530 # Update the page record with revision data
1531 $this->updateRevisionOn( $dbw, $revision, 0 );
1532
1533 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
1534
1535 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1536 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1537 '', strlen( $text ), $revisionId );
1538 # Mark as patrolled if the user can
1539 if( ($GLOBALS['wgUseRCPatrol'] || $GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1540 RecentChange::markPatrolled( $rcid );
1541 PatrolLog::record( $rcid, true );
1542 }
1543 }
1544 $wgUser->incEditCount();
1545 $dbw->commit();
1546
1547 # Update links, etc.
1548 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1549
1550 # Clear caches
1551 Article::onArticleCreate( $this->mTitle );
1552
1553 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1554 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1555 }
1556
1557 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1558 wfDoUpdates();
1559 }
1560
1561 if ( $good ) {
1562 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1563 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1564 }
1565
1566 wfProfileOut( __METHOD__ );
1567 return $good;
1568 }
1569
1570 /**
1571 * @deprecated wrapper for doRedirect
1572 */
1573 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1574 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1575 }
1576
1577 /**
1578 * Output a redirect back to the article.
1579 * This is typically used after an edit.
1580 *
1581 * @param boolean $noRedir Add redirect=no
1582 * @param string $sectionAnchor section to redirect to, including "#"
1583 * @param string $extraQuery, extra query params
1584 */
1585 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1586 global $wgOut;
1587 if ( $noRedir ) {
1588 $query = 'redirect=no';
1589 if( $extraQuery )
1590 $query .= "&$query";
1591 } else {
1592 $query = $extraQuery;
1593 }
1594 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1595 }
1596
1597 /**
1598 * Mark this particular edit/page as patrolled
1599 */
1600 function markpatrolled() {
1601 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1602 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1603
1604 # Check patrol config options
1605
1606 if ( !($wgUseNPPatrol || $wgUseRCPatrol)) {
1607 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1608 return;
1609 }
1610
1611 # If we haven't been given an rc_id value, we can't do anything
1612 $rcid = (int) $wgRequest->getVal('rcid');
1613 $rc = $rcid ? RecentChange::newFromId($rcid) : null;
1614 if ( is_null ( $rc ) )
1615 {
1616 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1617 return;
1618 }
1619
1620 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW) {
1621 // Only new pages can be patrolled if the general patrolling is off....???
1622 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1623 // front end here?
1624 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1625 return;
1626 }
1627
1628 # Check permissions
1629 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'patrol', $wgUser );
1630
1631 if (count($permission_errors)>0)
1632 {
1633 $wgOut->showPermissionsErrorPage( $permission_errors );
1634 return;
1635 }
1636
1637 # Handle the 'MarkPatrolled' hook
1638 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1639 return;
1640 }
1641
1642 #It would be nice to see where the user had actually come from, but for now just guess
1643 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1644 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1645
1646 # If it's left up to us, check that the user is allowed to patrol this edit
1647 # If the user has the "autopatrol" right, then we'll assume there are no
1648 # other conditions stopping them doing so
1649 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1650 $rc = RecentChange::newFromId( $rcid );
1651 # Graceful error handling, as we've done before here...
1652 # (If the recent change doesn't exist, then it doesn't matter whether
1653 # the user is allowed to patrol it or not; nothing is going to happen
1654 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1655 # The user made this edit, and can't patrol it
1656 # Tell them so, and then back off
1657 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1658 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1659 $wgOut->returnToMain( false, $return );
1660 return;
1661 }
1662 }
1663
1664 # Check that the revision isn't patrolled already
1665 # Prevents duplicate log entries
1666 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1667 # Mark the edit as patrolled
1668 RecentChange::markPatrolled( $rcid );
1669 PatrolLog::record( $rcid );
1670 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1671 }
1672
1673 # Inform the user
1674 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1675 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1676 $wgOut->returnToMain( false, $return );
1677 }
1678
1679 /**
1680 * User-interface handler for the "watch" action
1681 */
1682
1683 function watch() {
1684
1685 global $wgUser, $wgOut;
1686
1687 if ( $wgUser->isAnon() ) {
1688 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1689 return;
1690 }
1691 if ( wfReadOnly() ) {
1692 $wgOut->readOnlyPage();
1693 return;
1694 }
1695
1696 if( $this->doWatch() ) {
1697 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1698 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1699
1700 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1701 }
1702
1703 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1704 }
1705
1706 /**
1707 * Add this page to $wgUser's watchlist
1708 * @return bool true on successful watch operation
1709 */
1710 function doWatch() {
1711 global $wgUser;
1712 if( $wgUser->isAnon() ) {
1713 return false;
1714 }
1715
1716 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1717 $wgUser->addWatch( $this->mTitle );
1718
1719 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1720 }
1721
1722 return false;
1723 }
1724
1725 /**
1726 * User interface handler for the "unwatch" action.
1727 */
1728 function unwatch() {
1729
1730 global $wgUser, $wgOut;
1731
1732 if ( $wgUser->isAnon() ) {
1733 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1734 return;
1735 }
1736 if ( wfReadOnly() ) {
1737 $wgOut->readOnlyPage();
1738 return;
1739 }
1740
1741 if( $this->doUnwatch() ) {
1742 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1743 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1744
1745 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1746 }
1747
1748 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1749 }
1750
1751 /**
1752 * Stop watching a page
1753 * @return bool true on successful unwatch
1754 */
1755 function doUnwatch() {
1756 global $wgUser;
1757 if( $wgUser->isAnon() ) {
1758 return false;
1759 }
1760
1761 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1762 $wgUser->removeWatch( $this->mTitle );
1763
1764 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1765 }
1766
1767 return false;
1768 }
1769
1770 /**
1771 * action=protect handler
1772 */
1773 function protect() {
1774 $form = new ProtectionForm( $this );
1775 $form->execute();
1776 }
1777
1778 /**
1779 * action=unprotect handler (alias)
1780 */
1781 function unprotect() {
1782 $this->protect();
1783 }
1784
1785 /**
1786 * Update the article's restriction field, and leave a log entry.
1787 *
1788 * @param array $limit set of restriction keys
1789 * @param string $reason
1790 * @return bool true on success
1791 */
1792 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1793 global $wgUser, $wgRestrictionTypes, $wgContLang;
1794
1795 $id = $this->mTitle->getArticleID();
1796 if( array() != $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser ) || wfReadOnly() || $id == 0 ) {
1797 return false;
1798 }
1799
1800 if (!$cascade) {
1801 $cascade = false;
1802 }
1803
1804 // Take this opportunity to purge out expired restrictions
1805 Title::purgeExpiredRestrictions();
1806
1807 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1808 # we expect a single selection, but the schema allows otherwise.
1809 $current = array();
1810 foreach( $wgRestrictionTypes as $action )
1811 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1812
1813 $current = Article::flattenRestrictions( $current );
1814 $updated = Article::flattenRestrictions( $limit );
1815
1816 $changed = ( $current != $updated );
1817 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
1818 $changed = $changed || ($updated && $this->mTitle->mRestrictionsExpiry != $expiry);
1819 $protect = ( $updated != '' );
1820
1821 # If nothing's changed, do nothing
1822 if( $changed ) {
1823 global $wgGroupPermissions;
1824 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1825
1826 $dbw = wfGetDB( DB_MASTER );
1827
1828 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1829
1830 $expiry_description = '';
1831 if ( $encodedExpiry != 'infinity' ) {
1832 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1833 }
1834
1835 # Prepare a null revision to be added to the history
1836 $modified = $current != '' && $protect;
1837 if ( $protect ) {
1838 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1839 } else {
1840 $comment_type = 'unprotectedarticle';
1841 }
1842 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1843
1844 # Only restrictions with the 'protect' right can cascade...
1845 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1846 foreach( $limit as $action => $restriction ) {
1847 # FIXME: can $restriction be an array or what? (same as fixme above)
1848 if( $restriction != 'protect' && $restriction != 'sysop' ) {
1849 $cascade = false;
1850 break;
1851 }
1852 }
1853
1854 $cascade_description = '';
1855 if ($cascade) {
1856 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1857 }
1858
1859 if( $reason )
1860 $comment .= ": $reason";
1861 if( $protect )
1862 $comment .= " [$updated]";
1863 if ( $expiry_description && $protect )
1864 $comment .= "$expiry_description";
1865 if ( $cascade )
1866 $comment .= "$cascade_description";
1867
1868 # Update restrictions table
1869 foreach( $limit as $action => $restrictions ) {
1870 if ($restrictions != '' ) {
1871 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1872 array( 'pr_page' => $id, 'pr_type' => $action
1873 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
1874 , 'pr_expiry' => $encodedExpiry ), __METHOD__ );
1875 } else {
1876 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1877 'pr_type' => $action ), __METHOD__ );
1878 }
1879 }
1880
1881 # Insert a null revision
1882 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1883 $nullRevId = $nullRevision->insertOn( $dbw );
1884
1885 # Update page record
1886 $dbw->update( 'page',
1887 array( /* SET */
1888 'page_touched' => $dbw->timestamp(),
1889 'page_restrictions' => '',
1890 'page_latest' => $nullRevId
1891 ), array( /* WHERE */
1892 'page_id' => $id
1893 ), 'Article::protect'
1894 );
1895
1896 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, false) );
1897 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1898
1899 # Update the protection log
1900 $log = new LogPage( 'protect' );
1901 if( $protect ) {
1902 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle,
1903 trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1904 } else {
1905 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1906 }
1907
1908 } # End hook
1909 } # End "changed" check
1910
1911 return true;
1912 }
1913
1914 /**
1915 * Take an array of page restrictions and flatten it to a string
1916 * suitable for insertion into the page_restrictions field.
1917 * @param array $limit
1918 * @return string
1919 * @private
1920 */
1921 function flattenRestrictions( $limit ) {
1922 if( !is_array( $limit ) ) {
1923 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1924 }
1925 $bits = array();
1926 ksort( $limit );
1927 foreach( $limit as $action => $restrictions ) {
1928 if( $restrictions != '' ) {
1929 $bits[] = "$action=$restrictions";
1930 }
1931 }
1932 return implode( ':', $bits );
1933 }
1934
1935 /**
1936 * Auto-generates a deletion reason
1937 * @param bool &$hasHistory Whether the page has a history
1938 */
1939 public function generateReason(&$hasHistory)
1940 {
1941 global $wgContLang;
1942 $dbw = wfGetDB(DB_MASTER);
1943 // Get the last revision
1944 $rev = Revision::newFromTitle($this->mTitle);
1945 if(is_null($rev))
1946 return false;
1947 // Get the article's contents
1948 $contents = $rev->getText();
1949 $blank = false;
1950 // If the page is blank, use the text from the previous revision,
1951 // which can only be blank if there's a move/import/protect dummy revision involved
1952 if($contents == '')
1953 {
1954 $prev = $rev->getPrevious();
1955 if($prev)
1956 {
1957 $contents = $prev->getText();
1958 $blank = true;
1959 }
1960 }
1961
1962 // Find out if there was only one contributor
1963 // Only scan the last 20 revisions
1964 $limit = 20;
1965 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__,
1966 array('LIMIT' => $limit));
1967 if($res === false)
1968 // This page has no revisions, which is very weird
1969 return false;
1970 if($res->numRows() > 1)
1971 $hasHistory = true;
1972 else
1973 $hasHistory = false;
1974 $row = $dbw->fetchObject($res);
1975 $onlyAuthor = $row->rev_user_text;
1976 // Try to find a second contributor
1977 while( $row = $dbw->fetchObject($res) ) {
1978 if($row->rev_user_text != $onlyAuthor) {
1979 $onlyAuthor = false;
1980 break;
1981 }
1982 }
1983 $dbw->freeResult($res);
1984
1985 // Generate the summary with a '$1' placeholder
1986 if($blank) {
1987 // The current revision is blank and the one before is also
1988 // blank. It's just not our lucky day
1989 $reason = wfMsgForContent('exbeforeblank', '$1');
1990 } else {
1991 if($onlyAuthor)
1992 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1993 else
1994 $reason = wfMsgForContent('excontent', '$1');
1995 }
1996
1997 // Replace newlines with spaces to prevent uglyness
1998 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1999 // Calculate the maximum amount of chars to get
2000 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2001 $maxLength = 255 - (strlen($reason) - 2) - 3;
2002 $contents = $wgContLang->truncate($contents, $maxLength, '...');
2003 // Remove possible unfinished links
2004 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2005 // Now replace the '$1' placeholder
2006 $reason = str_replace( '$1', $contents, $reason );
2007 return $reason;
2008 }
2009
2010
2011 /*
2012 * UI entry point for page deletion
2013 */
2014 function delete() {
2015 global $wgUser, $wgOut, $wgRequest;
2016
2017 $confirm = $wgRequest->wasPosted() &&
2018 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2019
2020 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2021 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2022
2023 $reason = $this->DeleteReasonList;
2024
2025 if ( $reason != 'other' && $this->DeleteReason != '') {
2026 // Entry from drop down menu + additional comment
2027 $reason .= ': ' . $this->DeleteReason;
2028 } elseif ( $reason == 'other' ) {
2029 $reason = $this->DeleteReason;
2030 }
2031 # Flag to hide all contents of the archived revisions
2032 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
2033
2034 # This code desperately needs to be totally rewritten
2035
2036 # Read-only check...
2037 if ( wfReadOnly() ) {
2038 $wgOut->readOnlyPage();
2039 return;
2040 }
2041
2042 # Check permissions
2043 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2044
2045 if (count($permission_errors)>0) {
2046 $wgOut->showPermissionsErrorPage( $permission_errors );
2047 return;
2048 }
2049
2050 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2051
2052 # Better double-check that it hasn't been deleted yet!
2053 $dbw = wfGetDB( DB_MASTER );
2054 $conds = $this->mTitle->pageCond();
2055 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2056 if ( $latest === false ) {
2057 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2058 return;
2059 }
2060
2061 # Hack for big sites
2062 $bigHistory = $this->isBigDeletion();
2063 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2064 global $wgLang, $wgDeleteRevisionsLimit;
2065 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2066 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2067 return;
2068 }
2069
2070 if( $confirm ) {
2071 $this->doDelete( $reason, $suppress );
2072 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2073 $this->doWatch();
2074 } elseif( $this->mTitle->userIsWatching() ) {
2075 $this->doUnwatch();
2076 }
2077 return;
2078 }
2079
2080 // Generate deletion reason
2081 $hasHistory = false;
2082 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2083
2084 // If the page has a history, insert a warning
2085 if( $hasHistory && !$confirm ) {
2086 $skin=$wgUser->getSkin();
2087 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2088 if( $bigHistory ) {
2089 global $wgLang, $wgDeleteRevisionsLimit;
2090 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2091 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2092 }
2093 }
2094
2095 return $this->confirmDelete( '', $reason );
2096 }
2097
2098 /**
2099 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2100 */
2101 function isBigDeletion() {
2102 global $wgDeleteRevisionsLimit;
2103 if( $wgDeleteRevisionsLimit ) {
2104 $revCount = $this->estimateRevisionCount();
2105 return $revCount > $wgDeleteRevisionsLimit;
2106 }
2107 return false;
2108 }
2109
2110 /**
2111 * @return int approximate revision count
2112 */
2113 function estimateRevisionCount() {
2114 $dbr = wfGetDB();
2115 // For an exact count...
2116 //return $dbr->selectField( 'revision', 'COUNT(*)',
2117 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2118 return $dbr->estimateRowCount( 'revision', '*',
2119 array( 'rev_page' => $this->getId() ), __METHOD__ );
2120 }
2121
2122 /**
2123 * Get the last N authors
2124 * @param int $num Number of revisions to get
2125 * @param string $revLatest The latest rev_id, selected from the master (optional)
2126 * @return array Array of authors, duplicates not removed
2127 */
2128 function getLastNAuthors( $num, $revLatest = 0 ) {
2129 wfProfileIn( __METHOD__ );
2130
2131 // First try the slave
2132 // If that doesn't have the latest revision, try the master
2133 $continue = 2;
2134 $db = wfGetDB( DB_SLAVE );
2135 do {
2136 $res = $db->select( array( 'page', 'revision' ),
2137 array( 'rev_id', 'rev_user_text' ),
2138 array(
2139 'page_namespace' => $this->mTitle->getNamespace(),
2140 'page_title' => $this->mTitle->getDBkey(),
2141 'rev_page = page_id'
2142 ), __METHOD__, $this->getSelectOptions( array(
2143 'ORDER BY' => 'rev_timestamp DESC',
2144 'LIMIT' => $num
2145 ) )
2146 );
2147 if ( !$res ) {
2148 wfProfileOut( __METHOD__ );
2149 return array();
2150 }
2151 $row = $db->fetchObject( $res );
2152 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2153 $db = wfGetDB( DB_MASTER );
2154 $continue--;
2155 } else {
2156 $continue = 0;
2157 }
2158 } while ( $continue );
2159
2160 $authors = array( $row->rev_user_text );
2161 while ( $row = $db->fetchObject( $res ) ) {
2162 $authors[] = $row->rev_user_text;
2163 }
2164 wfProfileOut( __METHOD__ );
2165 return $authors;
2166 }
2167
2168 /**
2169 * Output deletion confirmation dialog
2170 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2171 * @param $reason string Prefilled reason
2172 */
2173 function confirmDelete( $par, $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' . $par ), '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 }