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