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