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