(bug 13745) Fix regression from r33133 by changing INSERT to REPLACE
[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 .= ',oldid='.$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 .= ',oldid='.$oldid;
801 $text = wfMsg( 'missingarticle', $t );
802 } else {
803 $text = wfMsg( 'noarticletext', $t );
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 return;
827 } else {
828 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
829 // and we are allowed to see...
830 }
831 }
832 }
833
834 }
835 }
836 if( !$outputDone ) {
837 $wgOut->setRevisionId( $this->getRevIdFetched() );
838
839 // Pages containing custom CSS or JavaScript get special treatment
840 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
841 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
842
843 // Give hooks a chance to customise the output
844 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
845 // Wrap the whole lot in a <pre> and don't parse
846 $m = array();
847 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
848 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
849 $wgOut->addHtml( htmlspecialchars( $this->mContent ) );
850 $wgOut->addHtml( "\n</pre>\n" );
851 }
852
853 }
854
855 elseif ( $rt = Title::newFromRedirect( $text ) ) {
856 # Display redirect
857 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
858 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
859 # Don't overwrite the subtitle if this was an old revision
860 if( !$wasRedirected && $this->isCurrent() ) {
861 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
862 }
863 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
864
865 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
866 '<span class="redirectText">'.$link.'</span>' );
867
868 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
869 $wgOut->addParserOutputNoText( $parseout );
870 } else if ( $pcache ) {
871 # Display content and save to parser cache
872 $this->outputWikiText( $text );
873 } else {
874 # Display content, don't attempt to save to parser cache
875 # Don't show section-edit links on old revisions... this way lies madness.
876 if( !$this->isCurrent() ) {
877 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
878 }
879 # Display content and don't save to parser cache
880 # With timing hack -- TS 2006-07-26
881 $time = -wfTime();
882 $this->outputWikiText( $text, false );
883 $time += wfTime();
884
885 # Timing hack
886 if ( $time > 3 ) {
887 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
888 $this->mTitle->getPrefixedDBkey()));
889 }
890
891 if( !$this->isCurrent() ) {
892 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
893 }
894
895 }
896 }
897 /* title may have been set from the cache */
898 $t = $wgOut->getPageTitle();
899 if( empty( $t ) ) {
900 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
901 }
902
903 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
904 if( $ns == NS_USER_TALK &&
905 IP::isValid( $this->mTitle->getText() ) ) {
906 $wgOut->addWikiMsg('anontalkpagetext');
907 }
908
909 # If we have been passed an &rcid= parameter, we want to give the user a
910 # chance to mark this new article as patrolled.
911 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle->exists() ) {
912 $wgOut->addHTML(
913 "<div class='patrollink'>" .
914 wfMsgHtml( 'markaspatrolledlink',
915 $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
916 "action=markpatrolled&rcid=$rcid" )
917 ) .
918 '</div>'
919 );
920 }
921
922 # Trackbacks
923 if ($wgUseTrackbacks)
924 $this->addTrackbacks();
925
926 $this->viewUpdates();
927 wfProfileOut( __METHOD__ );
928 }
929
930 function addTrackbacks() {
931 global $wgOut, $wgUser;
932
933 $dbr = wfGetDB(DB_SLAVE);
934 $tbs = $dbr->select(
935 /* FROM */ 'trackbacks',
936 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
937 /* WHERE */ array('tb_page' => $this->getID())
938 );
939
940 if (!$dbr->numrows($tbs))
941 return;
942
943 $tbtext = "";
944 while ($o = $dbr->fetchObject($tbs)) {
945 $rmvtxt = "";
946 if ($wgUser->isAllowed( 'trackback' )) {
947 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
948 . $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
949 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
950 }
951 $tbtext .= "\n";
952 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
953 $o->tb_title,
954 $o->tb_url,
955 $o->tb_ex,
956 $o->tb_name,
957 $rmvtxt);
958 }
959 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
960 }
961
962 function deletetrackback() {
963 global $wgUser, $wgRequest, $wgOut, $wgTitle;
964
965 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
966 $wgOut->addWikiMsg( 'sessionfailure' );
967 return;
968 }
969
970 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
971
972 if (count($permission_errors)>0)
973 {
974 $wgOut->showPermissionsErrorPage( $permission_errors );
975 return;
976 }
977
978 $db = wfGetDB(DB_MASTER);
979 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
980 $wgTitle->invalidateCache();
981 $wgOut->addWikiMsg('trackbackdeleteok');
982 }
983
984 function render() {
985 global $wgOut;
986
987 $wgOut->setArticleBodyOnly(true);
988 $this->view();
989 }
990
991 /**
992 * Handle action=purge
993 */
994 function purge() {
995 global $wgUser, $wgRequest, $wgOut;
996
997 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
998 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
999 $this->doPurge();
1000 }
1001 } else {
1002 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1003 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
1004 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1005 $msg = str_replace( '$1',
1006 "<form method=\"post\" action=\"$action\">\n" .
1007 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1008 "</form>\n", $msg );
1009
1010 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1011 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1012 $wgOut->addHTML( $msg );
1013 }
1014 }
1015
1016 /**
1017 * Perform the actions of a page purging
1018 */
1019 function doPurge() {
1020 global $wgUseSquid;
1021 // Invalidate the cache
1022 $this->mTitle->invalidateCache();
1023
1024 if ( $wgUseSquid ) {
1025 // Commit the transaction before the purge is sent
1026 $dbw = wfGetDB( DB_MASTER );
1027 $dbw->immediateCommit();
1028
1029 // Send purge
1030 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1031 $update->doUpdate();
1032 }
1033 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1034 global $wgMessageCache;
1035 if ( $this->getID() == 0 ) {
1036 $text = false;
1037 } else {
1038 $text = $this->getContent();
1039 }
1040 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1041 }
1042 $this->view();
1043 }
1044
1045 /**
1046 * Insert a new empty page record for this article.
1047 * This *must* be followed up by creating a revision
1048 * and running $this->updateToLatest( $rev_id );
1049 * or else the record will be left in a funky state.
1050 * Best if all done inside a transaction.
1051 *
1052 * @param Database $dbw
1053 * @return int The newly created page_id key
1054 * @private
1055 */
1056 function insertOn( $dbw ) {
1057 wfProfileIn( __METHOD__ );
1058
1059 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1060 $dbw->insert( 'page', array(
1061 'page_id' => $page_id,
1062 'page_namespace' => $this->mTitle->getNamespace(),
1063 'page_title' => $this->mTitle->getDBkey(),
1064 'page_counter' => 0,
1065 'page_restrictions' => '',
1066 'page_is_redirect' => 0, # Will set this shortly...
1067 'page_is_new' => 1,
1068 'page_random' => wfRandom(),
1069 'page_touched' => $dbw->timestamp(),
1070 'page_latest' => 0, # Fill this in shortly...
1071 'page_len' => 0, # Fill this in shortly...
1072 ), __METHOD__ );
1073 $newid = $dbw->insertId();
1074
1075 $this->mTitle->resetArticleId( $newid );
1076
1077 wfProfileOut( __METHOD__ );
1078 return $newid;
1079 }
1080
1081 /**
1082 * Update the page record to point to a newly saved revision.
1083 *
1084 * @param Database $dbw
1085 * @param Revision $revision For ID number, and text used to set
1086 length and redirect status fields
1087 * @param int $lastRevision If given, will not overwrite the page field
1088 * when different from the currently set value.
1089 * Giving 0 indicates the new page flag should
1090 * be set on.
1091 * @param bool $lastRevIsRedirect If given, will optimize adding and
1092 * removing rows in redirect table.
1093 * @return bool true on success, false on failure
1094 * @private
1095 */
1096 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1097 wfProfileIn( __METHOD__ );
1098
1099 $text = $revision->getText();
1100 $rt = Title::newFromRedirect( $text );
1101
1102 $conditions = array( 'page_id' => $this->getId() );
1103 if( !is_null( $lastRevision ) ) {
1104 # An extra check against threads stepping on each other
1105 $conditions['page_latest'] = $lastRevision;
1106 }
1107
1108 $dbw->update( 'page',
1109 array( /* SET */
1110 'page_latest' => $revision->getId(),
1111 'page_touched' => $dbw->timestamp(),
1112 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1113 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1114 'page_len' => strlen( $text ),
1115 ),
1116 $conditions,
1117 __METHOD__ );
1118
1119 $result = $dbw->affectedRows() != 0;
1120
1121 if ($result) {
1122 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1123 }
1124
1125 wfProfileOut( __METHOD__ );
1126 return $result;
1127 }
1128
1129 /**
1130 * Add row to the redirect table if this is a redirect, remove otherwise.
1131 *
1132 * @param Database $dbw
1133 * @param $redirectTitle a title object pointing to the redirect target,
1134 * or NULL if this is not a redirect
1135 * @param bool $lastRevIsRedirect If given, will optimize adding and
1136 * removing rows in redirect table.
1137 * @return bool true on success, false on failure
1138 * @private
1139 */
1140 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1141
1142 // Always update redirects (target link might have changed)
1143 // Update/Insert if we don't know if the last revision was a redirect or not
1144 // Delete if changing from redirect to non-redirect
1145 $isRedirect = !is_null($redirectTitle);
1146 if ($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1147
1148 wfProfileIn( __METHOD__ );
1149
1150 if ($isRedirect) {
1151
1152 // This title is a redirect, Add/Update row in the redirect table
1153 $set = array( /* SET */
1154 'rd_namespace' => $redirectTitle->getNamespace(),
1155 'rd_title' => $redirectTitle->getDBkey(),
1156 'rd_from' => $this->getId(),
1157 );
1158
1159 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1160 } else {
1161 // This is not a redirect, remove row from redirect table
1162 $where = array( 'rd_from' => $this->getId() );
1163 $dbw->delete( 'redirect', $where, __METHOD__);
1164 }
1165
1166 if( $this->getTitle()->getNamespace() == NS_IMAGE )
1167 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1168 wfProfileOut( __METHOD__ );
1169 return ( $dbw->affectedRows() != 0 );
1170 }
1171
1172 return true;
1173 }
1174
1175 /**
1176 * If the given revision is newer than the currently set page_latest,
1177 * update the page record. Otherwise, do nothing.
1178 *
1179 * @param Database $dbw
1180 * @param Revision $revision
1181 */
1182 function updateIfNewerOn( &$dbw, $revision ) {
1183 wfProfileIn( __METHOD__ );
1184
1185 $row = $dbw->selectRow(
1186 array( 'revision', 'page' ),
1187 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1188 array(
1189 'page_id' => $this->getId(),
1190 'page_latest=rev_id' ),
1191 __METHOD__ );
1192 if( $row ) {
1193 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1194 wfProfileOut( __METHOD__ );
1195 return false;
1196 }
1197 $prev = $row->rev_id;
1198 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1199 } else {
1200 # No or missing previous revision; mark the page as new
1201 $prev = 0;
1202 $lastRevIsRedirect = null;
1203 }
1204
1205 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1206 wfProfileOut( __METHOD__ );
1207 return $ret;
1208 }
1209
1210 /**
1211 * @return string Complete article text, or null if error
1212 */
1213 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1214 wfProfileIn( __METHOD__ );
1215
1216 if( $section == '' ) {
1217 // Whole-page edit; let the text through unmolested.
1218 } else {
1219 if( is_null( $edittime ) ) {
1220 $rev = Revision::newFromTitle( $this->mTitle );
1221 } else {
1222 $dbw = wfGetDB( DB_MASTER );
1223 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1224 }
1225 if( is_null( $rev ) ) {
1226 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1227 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1228 return null;
1229 }
1230 $oldtext = $rev->getText();
1231
1232 if( $section == 'new' ) {
1233 # Inserting a new section
1234 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1235 $text = strlen( trim( $oldtext ) ) > 0
1236 ? "{$oldtext}\n\n{$subject}{$text}"
1237 : "{$subject}{$text}";
1238 } else {
1239 # Replacing an existing section; roll out the big guns
1240 global $wgParser;
1241 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1242 }
1243
1244 }
1245
1246 wfProfileOut( __METHOD__ );
1247 return $text;
1248 }
1249
1250 /**
1251 * @deprecated use Article::doEdit()
1252 */
1253 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1254 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1255 ( $isminor ? EDIT_MINOR : 0 ) |
1256 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1257 ( $bot ? EDIT_FORCE_BOT : 0 );
1258
1259 # If this is a comment, add the summary as headline
1260 if ( $comment && $summary != "" ) {
1261 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1262 }
1263
1264 $this->doEdit( $text, $summary, $flags );
1265
1266 $dbw = wfGetDB( DB_MASTER );
1267 if ($watchthis) {
1268 if (!$this->mTitle->userIsWatching()) {
1269 $dbw->begin();
1270 $this->doWatch();
1271 $dbw->commit();
1272 }
1273 } else {
1274 if ( $this->mTitle->userIsWatching() ) {
1275 $dbw->begin();
1276 $this->doUnwatch();
1277 $dbw->commit();
1278 }
1279 }
1280 $this->doRedirect( $this->isRedirect( $text ) );
1281 }
1282
1283 /**
1284 * @deprecated use Article::doEdit()
1285 */
1286 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1287 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1288 ( $minor ? EDIT_MINOR : 0 ) |
1289 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1290
1291 $good = $this->doEdit( $text, $summary, $flags );
1292 if ( $good ) {
1293 $dbw = wfGetDB( DB_MASTER );
1294 if ($watchthis) {
1295 if (!$this->mTitle->userIsWatching()) {
1296 $dbw->begin();
1297 $this->doWatch();
1298 $dbw->commit();
1299 }
1300 } else {
1301 if ( $this->mTitle->userIsWatching() ) {
1302 $dbw->begin();
1303 $this->doUnwatch();
1304 $dbw->commit();
1305 }
1306 }
1307
1308 $extraq = ''; // Give extensions a chance to modify URL query on update
1309 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1310
1311 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1312 }
1313 return $good;
1314 }
1315
1316 /**
1317 * Article::doEdit()
1318 *
1319 * Change an existing article or create a new article. Updates RC and all necessary caches,
1320 * optionally via the deferred update array.
1321 *
1322 * $wgUser must be set before calling this function.
1323 *
1324 * @param string $text New text
1325 * @param string $summary Edit summary
1326 * @param integer $flags bitfield:
1327 * EDIT_NEW
1328 * Article is known or assumed to be non-existent, create a new one
1329 * EDIT_UPDATE
1330 * Article is known or assumed to be pre-existing, update it
1331 * EDIT_MINOR
1332 * Mark this edit minor, if the user is allowed to do so
1333 * EDIT_SUPPRESS_RC
1334 * Do not log the change in recentchanges
1335 * EDIT_FORCE_BOT
1336 * Mark the edit a "bot" edit regardless of user rights
1337 * EDIT_DEFER_UPDATES
1338 * Defer some of the updates until the end of index.php
1339 * EDIT_AUTOSUMMARY
1340 * Fill in blank summaries with generated text where possible
1341 *
1342 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1343 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1344 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1345 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1346 * to MediaWiki's performance-optimised locking strategy.
1347 *
1348 * @return bool success
1349 */
1350 function doEdit( $text, $summary, $flags = 0 ) {
1351 global $wgUser, $wgDBtransactions;
1352
1353 wfProfileIn( __METHOD__ );
1354 $good = true;
1355
1356 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1357 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1358 if ( $aid ) {
1359 $flags |= EDIT_UPDATE;
1360 } else {
1361 $flags |= EDIT_NEW;
1362 }
1363 }
1364
1365 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1366 &$summary, $flags & EDIT_MINOR,
1367 null, null, &$flags ) ) )
1368 {
1369 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1370 wfProfileOut( __METHOD__ );
1371 return false;
1372 }
1373
1374 # Silently ignore EDIT_MINOR if not allowed
1375 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1376 $bot = $flags & EDIT_FORCE_BOT;
1377
1378 $oldtext = $this->getContent();
1379 $oldsize = strlen( $oldtext );
1380
1381 # Provide autosummaries if one is not provided.
1382 if ($flags & EDIT_AUTOSUMMARY && $summary == '')
1383 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1384
1385 $editInfo = $this->prepareTextForEdit( $text );
1386 $text = $editInfo->pst;
1387 $newsize = strlen( $text );
1388
1389 $dbw = wfGetDB( DB_MASTER );
1390 $now = wfTimestampNow();
1391
1392 if ( $flags & EDIT_UPDATE ) {
1393 # Update article, but only if changed.
1394
1395 # Make sure the revision is either completely inserted or not inserted at all
1396 if( !$wgDBtransactions ) {
1397 $userAbort = ignore_user_abort( true );
1398 }
1399
1400 $lastRevision = 0;
1401 $revisionId = 0;
1402
1403 $changed = ( strcmp( $text, $oldtext ) != 0 );
1404
1405 if ( $changed ) {
1406 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1407 - (int)$this->isCountable( $oldtext );
1408 $this->mTotalAdjustment = 0;
1409
1410 $lastRevision = $dbw->selectField(
1411 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1412
1413 if ( !$lastRevision ) {
1414 # Article gone missing
1415 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1416 wfProfileOut( __METHOD__ );
1417 return false;
1418 }
1419
1420 $revision = new Revision( array(
1421 'page' => $this->getId(),
1422 'comment' => $summary,
1423 'minor_edit' => $isminor,
1424 'text' => $text,
1425 'parent_id' => $lastRevision
1426 ) );
1427
1428 $dbw->begin();
1429 $revisionId = $revision->insertOn( $dbw );
1430
1431 # Update page
1432 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1433
1434 if( !$ok ) {
1435 /* Belated edit conflict! Run away!! */
1436 $good = false;
1437 $dbw->rollback();
1438 } else {
1439 # Update recentchanges
1440 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1441 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1442 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1443 $revisionId );
1444
1445 # Mark as patrolled if the user can do so
1446 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1447 RecentChange::markPatrolled( $rcid );
1448 PatrolLog::record( $rcid, true );
1449 }
1450 }
1451 $wgUser->incEditCount();
1452 $dbw->commit();
1453 }
1454 } else {
1455 $revision = null;
1456 // Keep the same revision ID, but do some updates on it
1457 $revisionId = $this->getRevIdFetched();
1458 // Update page_touched, this is usually implicit in the page update
1459 // Other cache updates are done in onArticleEdit()
1460 $this->mTitle->invalidateCache();
1461 }
1462
1463 if( !$wgDBtransactions ) {
1464 ignore_user_abort( $userAbort );
1465 }
1466
1467 if ( $good ) {
1468 # Invalidate cache of this article and all pages using this article
1469 # as a template. Partly deferred.
1470 Article::onArticleEdit( $this->mTitle );
1471
1472 # Update links tables, site stats, etc.
1473 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1474 }
1475 } else {
1476 # Create new article
1477
1478 # Set statistics members
1479 # We work out if it's countable after PST to avoid counter drift
1480 # when articles are created with {{subst:}}
1481 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1482 $this->mTotalAdjustment = 1;
1483
1484 $dbw->begin();
1485
1486 # Add the page record; stake our claim on this title!
1487 # This will fail with a database query exception if the article already exists
1488 $newid = $this->insertOn( $dbw );
1489
1490 # Save the revision text...
1491 $revision = new Revision( array(
1492 'page' => $newid,
1493 'comment' => $summary,
1494 'minor_edit' => $isminor,
1495 'text' => $text
1496 ) );
1497 $revisionId = $revision->insertOn( $dbw );
1498
1499 $this->mTitle->resetArticleID( $newid );
1500
1501 # Update the page record with revision data
1502 $this->updateRevisionOn( $dbw, $revision, 0 );
1503
1504 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1505 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
1506 '', strlen( $text ), $revisionId );
1507 # Mark as patrolled if the user can
1508 if( ($GLOBALS['wgUseRCPatrol'] || $GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1509 RecentChange::markPatrolled( $rcid );
1510 PatrolLog::record( $rcid, true );
1511 }
1512 }
1513 $wgUser->incEditCount();
1514 $dbw->commit();
1515
1516 # Update links, etc.
1517 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1518
1519 # Clear caches
1520 Article::onArticleCreate( $this->mTitle );
1521
1522 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1523 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1524 }
1525
1526 if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
1527 wfDoUpdates();
1528 }
1529
1530 if ( $good ) {
1531 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1532 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1533 }
1534
1535 wfProfileOut( __METHOD__ );
1536 return $good;
1537 }
1538
1539 /**
1540 * @deprecated wrapper for doRedirect
1541 */
1542 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1543 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1544 }
1545
1546 /**
1547 * Output a redirect back to the article.
1548 * This is typically used after an edit.
1549 *
1550 * @param boolean $noRedir Add redirect=no
1551 * @param string $sectionAnchor section to redirect to, including "#"
1552 * @param string $extraq, extra query params
1553 */
1554 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1555 global $wgOut;
1556 if ( $noRedir ) {
1557 $query = 'redirect=no';
1558 if( $extraq )
1559 $query .= "&$query";
1560 } else {
1561 $query = $extraq;
1562 }
1563 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1564 }
1565
1566 /**
1567 * Mark this particular edit/page as patrolled
1568 */
1569 function markpatrolled() {
1570 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1571 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1572
1573 # Check patrol config options
1574
1575 if ( !($wgUseNPPatrol || $wgUseRCPatrol)) {
1576 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1577 return;
1578 }
1579
1580 # If we haven't been given an rc_id value, we can't do anything
1581 $rcid = (int) $wgRequest->getVal('rcid');
1582 $rc = $rcid ? RecentChange::newFromId($rcid) : null;
1583 if ( is_null ( $rc ) )
1584 {
1585 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1586 return;
1587 }
1588
1589 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW) {
1590 // Only new pages can be patrolled if the general patrolling is off....???
1591 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1592 // front end here?
1593 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1594 return;
1595 }
1596
1597 # Check permissions
1598 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'patrol', $wgUser );
1599
1600 if (count($permission_errors)>0)
1601 {
1602 $wgOut->showPermissionsErrorPage( $permission_errors );
1603 return;
1604 }
1605
1606 # Handle the 'MarkPatrolled' hook
1607 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1608 return;
1609 }
1610
1611 #It would be nice to see where the user had actually come from, but for now just guess
1612 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1613 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1614
1615 # If it's left up to us, check that the user is allowed to patrol this edit
1616 # If the user has the "autopatrol" right, then we'll assume there are no
1617 # other conditions stopping them doing so
1618 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1619 $rc = RecentChange::newFromId( $rcid );
1620 # Graceful error handling, as we've done before here...
1621 # (If the recent change doesn't exist, then it doesn't matter whether
1622 # the user is allowed to patrol it or not; nothing is going to happen
1623 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1624 # The user made this edit, and can't patrol it
1625 # Tell them so, and then back off
1626 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1627 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1628 $wgOut->returnToMain( false, $return );
1629 return;
1630 }
1631 }
1632
1633 # Check that the revision isn't patrolled already
1634 # Prevents duplicate log entries
1635 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1636 # Mark the edit as patrolled
1637 RecentChange::markPatrolled( $rcid );
1638 PatrolLog::record( $rcid );
1639 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1640 }
1641
1642 # Inform the user
1643 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1644 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1645 $wgOut->returnToMain( false, $return );
1646 }
1647
1648 /**
1649 * User-interface handler for the "watch" action
1650 */
1651
1652 function watch() {
1653
1654 global $wgUser, $wgOut;
1655
1656 if ( $wgUser->isAnon() ) {
1657 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1658 return;
1659 }
1660 if ( wfReadOnly() ) {
1661 $wgOut->readOnlyPage();
1662 return;
1663 }
1664
1665 if( $this->doWatch() ) {
1666 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1667 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1668
1669 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1670 }
1671
1672 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1673 }
1674
1675 /**
1676 * Add this page to $wgUser's watchlist
1677 * @return bool true on successful watch operation
1678 */
1679 function doWatch() {
1680 global $wgUser;
1681 if( $wgUser->isAnon() ) {
1682 return false;
1683 }
1684
1685 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1686 $wgUser->addWatch( $this->mTitle );
1687
1688 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1689 }
1690
1691 return false;
1692 }
1693
1694 /**
1695 * User interface handler for the "unwatch" action.
1696 */
1697 function unwatch() {
1698
1699 global $wgUser, $wgOut;
1700
1701 if ( $wgUser->isAnon() ) {
1702 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1703 return;
1704 }
1705 if ( wfReadOnly() ) {
1706 $wgOut->readOnlyPage();
1707 return;
1708 }
1709
1710 if( $this->doUnwatch() ) {
1711 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1712 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1713
1714 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1715 }
1716
1717 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1718 }
1719
1720 /**
1721 * Stop watching a page
1722 * @return bool true on successful unwatch
1723 */
1724 function doUnwatch() {
1725 global $wgUser;
1726 if( $wgUser->isAnon() ) {
1727 return false;
1728 }
1729
1730 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1731 $wgUser->removeWatch( $this->mTitle );
1732
1733 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1734 }
1735
1736 return false;
1737 }
1738
1739 /**
1740 * action=protect handler
1741 */
1742 function protect() {
1743 $form = new ProtectionForm( $this );
1744 $form->execute();
1745 }
1746
1747 /**
1748 * action=unprotect handler (alias)
1749 */
1750 function unprotect() {
1751 $this->protect();
1752 }
1753
1754 /**
1755 * Update the article's restriction field, and leave a log entry.
1756 *
1757 * @param array $limit set of restriction keys
1758 * @param string $reason
1759 * @return bool true on success
1760 */
1761 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1762 global $wgUser, $wgRestrictionTypes, $wgContLang;
1763
1764 $id = $this->mTitle->getArticleID();
1765 if( array() != $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser ) || wfReadOnly() || $id == 0 ) {
1766 return false;
1767 }
1768
1769 if (!$cascade) {
1770 $cascade = false;
1771 }
1772
1773 // Take this opportunity to purge out expired restrictions
1774 Title::purgeExpiredRestrictions();
1775
1776 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1777 # we expect a single selection, but the schema allows otherwise.
1778 $current = array();
1779 foreach( $wgRestrictionTypes as $action )
1780 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1781
1782 $current = Article::flattenRestrictions( $current );
1783 $updated = Article::flattenRestrictions( $limit );
1784
1785 $changed = ( $current != $updated );
1786 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
1787 $changed = $changed || ($updated && $this->mTitle->mRestrictionsExpiry != $expiry);
1788 $protect = ( $updated != '' );
1789
1790 # If nothing's changed, do nothing
1791 if( $changed ) {
1792 global $wgGroupPermissions;
1793 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1794
1795 $dbw = wfGetDB( DB_MASTER );
1796
1797 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1798
1799 $expiry_description = '';
1800 if ( $encodedExpiry != 'infinity' ) {
1801 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1802 }
1803
1804 # Prepare a null revision to be added to the history
1805 $modified = $current != '' && $protect;
1806 if ( $protect ) {
1807 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1808 } else {
1809 $comment_type = 'unprotectedarticle';
1810 }
1811 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1812
1813 foreach( $limit as $action => $restrictions ) {
1814 # Check if the group level required to edit also can protect pages
1815 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1816 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1817 $wgGroupPermissions[$restrictions]['protect'] );
1818 }
1819
1820 $cascade_description = '';
1821 if ($cascade) {
1822 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1823 }
1824
1825 if( $reason )
1826 $comment .= ": $reason";
1827 if( $protect )
1828 $comment .= " [$updated]";
1829 if ( $expiry_description && $protect )
1830 $comment .= "$expiry_description";
1831 if ( $cascade )
1832 $comment .= "$cascade_description";
1833
1834 # Update restrictions table
1835 foreach( $limit as $action => $restrictions ) {
1836 if ($restrictions != '' ) {
1837 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1838 array( 'pr_page' => $id, 'pr_type' => $action
1839 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
1840 , 'pr_expiry' => $encodedExpiry ), __METHOD__ );
1841 } else {
1842 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1843 'pr_type' => $action ), __METHOD__ );
1844 }
1845 }
1846
1847 # Insert a null revision
1848 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1849 $nullRevId = $nullRevision->insertOn( $dbw );
1850
1851 # Update page record
1852 $dbw->update( 'page',
1853 array( /* SET */
1854 'page_touched' => $dbw->timestamp(),
1855 'page_restrictions' => '',
1856 'page_latest' => $nullRevId
1857 ), array( /* WHERE */
1858 'page_id' => $id
1859 ), 'Article::protect'
1860 );
1861 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1862
1863 # Update the protection log
1864 $log = new LogPage( 'protect' );
1865
1866
1867
1868 if( $protect ) {
1869 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1870 } else {
1871 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1872 }
1873
1874 } # End hook
1875 } # End "changed" check
1876
1877 return true;
1878 }
1879
1880 /**
1881 * Take an array of page restrictions and flatten it to a string
1882 * suitable for insertion into the page_restrictions field.
1883 * @param array $limit
1884 * @return string
1885 * @private
1886 */
1887 function flattenRestrictions( $limit ) {
1888 if( !is_array( $limit ) ) {
1889 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1890 }
1891 $bits = array();
1892 ksort( $limit );
1893 foreach( $limit as $action => $restrictions ) {
1894 if( $restrictions != '' ) {
1895 $bits[] = "$action=$restrictions";
1896 }
1897 }
1898 return implode( ':', $bits );
1899 }
1900
1901 /**
1902 * Auto-generates a deletion reason
1903 * @param bool &$hasHistory Whether the page has a history
1904 */
1905 public function generateReason(&$hasHistory)
1906 {
1907 global $wgContLang;
1908 $dbw = wfGetDB(DB_MASTER);
1909 // Get the last revision
1910 $rev = Revision::newFromTitle($this->mTitle);
1911 if(is_null($rev))
1912 return false;
1913 // Get the article's contents
1914 $contents = $rev->getText();
1915 $blank = false;
1916 // If the page is blank, use the text from the previous revision,
1917 // which can only be blank if there's a move/import/protect dummy revision involved
1918 if($contents == '')
1919 {
1920 $prev = $rev->getPrevious();
1921 if($prev)
1922 {
1923 $contents = $prev->getText();
1924 $blank = true;
1925 }
1926 }
1927
1928 // Find out if there was only one contributor
1929 // Only scan the last 20 revisions
1930 $limit = 20;
1931 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__,
1932 array('LIMIT' => $limit));
1933 if($res === false)
1934 // This page has no revisions, which is very weird
1935 return false;
1936 if($res->numRows() > 1)
1937 $hasHistory = true;
1938 else
1939 $hasHistory = false;
1940 $row = $dbw->fetchObject($res);
1941 $onlyAuthor = $row->rev_user_text;
1942 // Try to find a second contributor
1943 while( $row = $dbw->fetchObject($res) ) {
1944 if($row->rev_user_text != $onlyAuthor) {
1945 $onlyAuthor = false;
1946 break;
1947 }
1948 }
1949 $dbw->freeResult($res);
1950
1951 // Generate the summary with a '$1' placeholder
1952 if($blank) {
1953 // The current revision is blank and the one before is also
1954 // blank. It's just not our lucky day
1955 $reason = wfMsgForContent('exbeforeblank', '$1');
1956 } else {
1957 if($onlyAuthor)
1958 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1959 else
1960 $reason = wfMsgForContent('excontent', '$1');
1961 }
1962
1963 // Replace newlines with spaces to prevent uglyness
1964 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1965 // Calculate the maximum amount of chars to get
1966 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1967 $maxLength = 255 - (strlen($reason) - 2) - 3;
1968 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1969 // Remove possible unfinished links
1970 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1971 // Now replace the '$1' placeholder
1972 $reason = str_replace( '$1', $contents, $reason );
1973 return $reason;
1974 }
1975
1976
1977 /*
1978 * UI entry point for page deletion
1979 */
1980 function delete() {
1981 global $wgUser, $wgOut, $wgRequest;
1982
1983 $confirm = $wgRequest->wasPosted() &&
1984 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1985
1986 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1987 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
1988
1989 $reason = $this->DeleteReasonList;
1990
1991 if ( $reason != 'other' && $this->DeleteReason != '') {
1992 // Entry from drop down menu + additional comment
1993 $reason .= ': ' . $this->DeleteReason;
1994 } elseif ( $reason == 'other' ) {
1995 $reason = $this->DeleteReason;
1996 }
1997 # Flag to hide all contents of the archived revisions
1998 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('deleterevision');
1999
2000 # This code desperately needs to be totally rewritten
2001
2002 # Read-only check...
2003 if ( wfReadOnly() ) {
2004 $wgOut->readOnlyPage();
2005 return;
2006 }
2007
2008 # Check permissions
2009 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2010
2011 if (count($permission_errors)>0) {
2012 $wgOut->showPermissionsErrorPage( $permission_errors );
2013 return;
2014 }
2015
2016 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2017
2018 # Better double-check that it hasn't been deleted yet!
2019 $dbw = wfGetDB( DB_MASTER );
2020 $conds = $this->mTitle->pageCond();
2021 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2022 if ( $latest === false ) {
2023 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2024 return;
2025 }
2026
2027 # Hack for big sites
2028 $bigHistory = $this->isBigDeletion();
2029 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2030 global $wgLang, $wgDeleteRevisionsLimit;
2031 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2032 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2033 return;
2034 }
2035
2036 if( $confirm ) {
2037 $this->doDelete( $reason, $suppress );
2038 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2039 $this->doWatch();
2040 } elseif( $this->mTitle->userIsWatching() ) {
2041 $this->doUnwatch();
2042 }
2043 return;
2044 }
2045
2046 // Generate deletion reason
2047 $hasHistory = false;
2048 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2049
2050 // If the page has a history, insert a warning
2051 if( $hasHistory && !$confirm ) {
2052 $skin=$wgUser->getSkin();
2053 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2054 if( $bigHistory ) {
2055 global $wgLang, $wgDeleteRevisionsLimit;
2056 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2057 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2058 }
2059 }
2060
2061 return $this->confirmDelete( '', $reason );
2062 }
2063
2064 /**
2065 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2066 */
2067 function isBigDeletion() {
2068 global $wgDeleteRevisionsLimit;
2069 if( $wgDeleteRevisionsLimit ) {
2070 $revCount = $this->estimateRevisionCount();
2071 return $revCount > $wgDeleteRevisionsLimit;
2072 }
2073 return false;
2074 }
2075
2076 /**
2077 * @return int approximate revision count
2078 */
2079 function estimateRevisionCount() {
2080 $dbr = wfGetDB();
2081 // For an exact count...
2082 //return $dbr->selectField( 'revision', 'COUNT(*)',
2083 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2084 return $dbr->estimateRowCount( 'revision', '*',
2085 array( 'rev_page' => $this->getId() ), __METHOD__ );
2086 }
2087
2088 /**
2089 * Get the last N authors
2090 * @param int $num Number of revisions to get
2091 * @param string $revLatest The latest rev_id, selected from the master (optional)
2092 * @return array Array of authors, duplicates not removed
2093 */
2094 function getLastNAuthors( $num, $revLatest = 0 ) {
2095 wfProfileIn( __METHOD__ );
2096
2097 // First try the slave
2098 // If that doesn't have the latest revision, try the master
2099 $continue = 2;
2100 $db = wfGetDB( DB_SLAVE );
2101 do {
2102 $res = $db->select( array( 'page', 'revision' ),
2103 array( 'rev_id', 'rev_user_text' ),
2104 array(
2105 'page_namespace' => $this->mTitle->getNamespace(),
2106 'page_title' => $this->mTitle->getDBkey(),
2107 'rev_page = page_id'
2108 ), __METHOD__, $this->getSelectOptions( array(
2109 'ORDER BY' => 'rev_timestamp DESC',
2110 'LIMIT' => $num
2111 ) )
2112 );
2113 if ( !$res ) {
2114 wfProfileOut( __METHOD__ );
2115 return array();
2116 }
2117 $row = $db->fetchObject( $res );
2118 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2119 $db = wfGetDB( DB_MASTER );
2120 $continue--;
2121 } else {
2122 $continue = 0;
2123 }
2124 } while ( $continue );
2125
2126 $authors = array( $row->rev_user_text );
2127 while ( $row = $db->fetchObject( $res ) ) {
2128 $authors[] = $row->rev_user_text;
2129 }
2130 wfProfileOut( __METHOD__ );
2131 return $authors;
2132 }
2133
2134 /**
2135 * Output deletion confirmation dialog
2136 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2137 * @param $reason string Prefilled reason
2138 */
2139 function confirmDelete( $par, $reason ) {
2140 global $wgOut, $wgUser, $wgContLang;
2141 $align = $wgContLang->isRtl() ? 'left' : 'right';
2142
2143 wfDebug( "Article::confirmDelete\n" );
2144
2145 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2146 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2147 $wgOut->addWikiMsg( 'confirmdeletetext' );
2148
2149 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2150 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2151 $suppress .= Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2152 $suppress .= "</td></tr>";
2153 } else {
2154 $suppress = '';
2155 }
2156
2157 $form = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2158 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2159 Xml::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2160 Xml::openElement( 'table' ) .
2161 "<tr id=\"wpDeleteReasonListRow\">
2162 <td align='$align'>" .
2163 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2164 "</td>
2165 <td>" .
2166 Xml::listDropDown( 'wpDeleteReasonList',
2167 wfMsgForContent( 'deletereason-dropdown' ),
2168 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2169 "</td>
2170 </tr>
2171 <tr id=\"wpDeleteReasonRow\">
2172 <td align='$align'>" .
2173 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2174 "</td>
2175 <td>" .
2176 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2177 "</td>
2178 </tr>
2179 <tr>
2180 <td></td>
2181 <td>" .
2182 Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '3' ) ) .
2183 "</td>
2184 </tr>
2185 $suppress
2186 <tr>
2187 <td></td>
2188 <td>" .
2189 Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2190 "</td>
2191 </tr>" .
2192 Xml::closeElement( 'table' ) .
2193 Xml::closeElement( 'fieldset' ) .
2194 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2195 Xml::closeElement( 'form' );
2196
2197 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2198 $skin = $wgUser->getSkin();
2199 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2200 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2201 }
2202
2203 $wgOut->addHTML( $form );
2204 $this->showLogExtract( $wgOut );
2205 }
2206
2207
2208 /**
2209 * Show relevant lines from the deletion log
2210 */
2211 function showLogExtract( $out ) {
2212 $out->addHtml( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2213 LogEventsList::showLogExtract( $out, 'delete', $this->mTitle->getPrefixedText() );
2214 }
2215
2216
2217 /**
2218 * Perform a deletion and output success or failure messages
2219 */
2220 function doDelete( $reason, $suppress = false ) {
2221 global $wgOut, $wgUser;
2222 wfDebug( __METHOD__."\n" );
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));
2236 } else {
2237 $wgOut->showFatalError( wfMsg( 'cannotdelete' ).'<br/>'.wfMsg('cannotdelete-merge') );
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 // For now, shunt the revision data into the archive table.
2278 // Text is *not* removed from the text table; bulk storage
2279 // is left intact to avoid breaking block-compression or
2280 // immutable storage schemes.
2281 //
2282 // For backwards compatibility, note that some older archive
2283 // table entries will have ar_text and ar_flags fields still.
2284 //
2285 // In the future, we may keep revisions and mark them with
2286 // the rev_deleted field, which is reserved for this purpose.
2287 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2288 array(
2289 'ar_namespace' => 'page_namespace',
2290 'ar_title' => 'page_title',
2291 'ar_comment' => 'rev_comment',
2292 'ar_user' => 'rev_user',
2293 'ar_user_text' => 'rev_user_text',
2294 'ar_timestamp' => 'rev_timestamp',
2295 'ar_minor_edit' => 'rev_minor_edit',
2296 'ar_rev_id' => 'rev_id',
2297 'ar_text_id' => 'rev_text_id',
2298 'ar_text' => '\'\'', // Be explicit to appease
2299 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2300 'ar_len' => 'rev_len',
2301 'ar_page_id' => 'page_id',
2302 'ar_deleted' => $bitfield
2303 ), array(
2304 'page_id' => $id,
2305 'page_id = rev_page'
2306 ), __METHOD__
2307 );
2308
2309 # Delete restrictions for it
2310 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2311
2312 # Fix category table counts
2313 $cats = array();
2314 $res = $dbw->select( 'categorylinks', 'cl_to',
2315 array( 'cl_from' => $id ), __METHOD__ );
2316 foreach( $res as $row ) {
2317 $cats []= $row->cl_to;
2318 }
2319 $this->updateCategoryCounts( array(), $cats );
2320
2321 # Now that it's safely backed up, delete it
2322 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2323
2324 # If using cascading deletes, we can skip some explicit deletes
2325 if ( !$dbw->cascadingDeletes() ) {
2326 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2327
2328 if ($wgUseTrackbacks)
2329 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2330
2331 # Delete outgoing links
2332 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2333 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2334 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2335 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2336 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2337 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2338 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2339 }
2340
2341 # If using cleanup triggers, we can skip some manual deletes
2342 if ( !$dbw->cleanupTriggers() ) {
2343
2344 # Clean up recentchanges entries...
2345 $dbw->delete( 'recentchanges',
2346 array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG ),
2347 __METHOD__ );
2348 }
2349
2350 # Clear caches
2351 Article::onArticleDelete( $this->mTitle );
2352
2353 # Clear the cached article id so the interface doesn't act like we exist
2354 $this->mTitle->resetArticleID( 0 );
2355 $this->mTitle->mArticleID = 0;
2356
2357 # Log the deletion, if the page was suppressed, log it at Oversight instead
2358 $logtype = $suppress ? 'suppress' : 'delete';
2359 $log = new LogPage( $logtype );
2360 $log->addEntry( 'delete', $this->mTitle, $reason );
2361
2362 return true;
2363 }
2364
2365 /**
2366 * Roll back the most recent consecutive set of edits to a page
2367 * from the same user; fails if there are no eligible edits to
2368 * roll back to, e.g. user is the sole contributor. This function
2369 * performs permissions checks on $wgUser, then calls commitRollback()
2370 * to do the dirty work
2371 *
2372 * @param string $fromP - Name of the user whose edits to rollback.
2373 * @param string $summary - Custom summary. Set to default summary if empty.
2374 * @param string $token - Rollback token.
2375 * @param bool $bot - If true, mark all reverted edits as bot.
2376 *
2377 * @param array $resultDetails contains result-specific array of additional values
2378 * 'alreadyrolled' : 'current' (rev)
2379 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2380 *
2381 * @return array of errors, each error formatted as
2382 * array(messagekey, param1, param2, ...).
2383 * On success, the array is empty. This array can also be passed to
2384 * OutputPage::showPermissionsErrorPage().
2385 */
2386 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2387 global $wgUser;
2388 $resultDetails = null;
2389
2390 # Check permissions
2391 $errors = array_merge( $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ),
2392 $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
2393 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2394 $errors[] = array( 'sessionfailure' );
2395
2396 if ( $wgUser->pingLimiter('rollback') || $wgUser->pingLimiter() ) {
2397 $errors[] = array( 'actionthrottledtext' );
2398 }
2399 # If there were errors, bail out now
2400 if(!empty($errors))
2401 return $errors;
2402
2403 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2404 }
2405
2406 /**
2407 * Backend implementation of doRollback(), please refer there for parameter
2408 * and return value documentation
2409 *
2410 * NOTE: This function does NOT check ANY permissions, it just commits the
2411 * rollback to the DB Therefore, you should only call this function direct-
2412 * ly if you want to use custom permissions checks. If you don't, use
2413 * doRollback() instead.
2414 */
2415 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2416 global $wgUseRCPatrol, $wgUser;
2417 $dbw = wfGetDB( DB_MASTER );
2418
2419 if( wfReadOnly() ) {
2420 return array( array( 'readonlytext' ) );
2421 }
2422
2423 # Get the last editor
2424 $current = Revision::newFromTitle( $this->mTitle );
2425 if( is_null( $current ) ) {
2426 # Something wrong... no page?
2427 return array(array('notanarticle'));
2428 }
2429
2430 $from = str_replace( '_', ' ', $fromP );
2431 if( $from != $current->getUserText() ) {
2432 $resultDetails = array( 'current' => $current );
2433 return array(array('alreadyrolled',
2434 htmlspecialchars($this->mTitle->getPrefixedText()),
2435 htmlspecialchars($fromP),
2436 htmlspecialchars($current->getUserText())
2437 ));
2438 }
2439
2440 # Get the last edit not by this guy
2441 $user = intval( $current->getUser() );
2442 $user_text = $dbw->addQuotes( $current->getUserText() );
2443 $s = $dbw->selectRow( 'revision',
2444 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2445 array( 'rev_page' => $current->getPage(),
2446 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2447 ), __METHOD__,
2448 array( 'USE INDEX' => 'page_timestamp',
2449 'ORDER BY' => 'rev_timestamp DESC' )
2450 );
2451 if( $s === false ) {
2452 # No one else ever edited this page
2453 return array(array('cantrollback'));
2454 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2455 # Only admins can see this text
2456 return array(array('notvisiblerev'));
2457 }
2458
2459 $set = array();
2460 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2461 # Mark all reverted edits as bot
2462 $set['rc_bot'] = 1;
2463 }
2464 if ( $wgUseRCPatrol ) {
2465 # Mark all reverted edits as patrolled
2466 $set['rc_patrolled'] = 1;
2467 }
2468
2469 if ( $set ) {
2470 $dbw->update( 'recentchanges', $set,
2471 array( /* WHERE */
2472 'rc_cur_id' => $current->getPage(),
2473 'rc_user_text' => $current->getUserText(),
2474 "rc_timestamp > '{$s->rev_timestamp}'",
2475 ), __METHOD__
2476 );
2477 }
2478
2479 # Generate the edit summary if necessary
2480 $target = Revision::newFromId( $s->rev_id );
2481 if( empty( $summary ) )
2482 {
2483 global $wgLang;
2484 $summary = wfMsgForContent( 'revertpage',
2485 $target->getUserText(), $from,
2486 $s->rev_id, $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2487 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2488 );
2489 }
2490
2491 # Save
2492 $flags = EDIT_UPDATE;
2493
2494 if ($wgUser->isAllowed('minoredit'))
2495 $flags |= EDIT_MINOR;
2496
2497 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2498 $flags |= EDIT_FORCE_BOT;
2499 $this->doEdit( $target->getText(), $summary, $flags );
2500
2501 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2502
2503 $resultDetails = array(
2504 'summary' => $summary,
2505 'current' => $current,
2506 'target' => $target,
2507 );
2508 return array();
2509 }
2510
2511 /**
2512 * User interface for rollback operations
2513 */
2514 function rollback() {
2515 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2516 $details = null;
2517
2518 $result = $this->doRollback(
2519 $wgRequest->getVal( 'from' ),
2520 $wgRequest->getText( 'summary' ),
2521 $wgRequest->getVal( 'token' ),
2522 $wgRequest->getBool( 'bot' ),
2523 $details
2524 );
2525
2526 if( in_array( array( 'blocked' ), $result ) ) {
2527 $wgOut->blockedPage();
2528 return;
2529 }
2530 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2531 $wgOut->rateLimited();
2532 return;
2533 }
2534 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ){
2535 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2536 $errArray = $result[0];
2537 $errMsg = array_shift( $errArray );
2538 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2539 if( isset( $details['current'] ) ){
2540 $current = $details['current'];
2541 if( $current->getComment() != '' ) {
2542 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2543 }
2544 }
2545 return;
2546 }
2547 # Display permissions errors before read-only message -- there's no
2548 # point in misleading the user into thinking the inability to rollback
2549 # is only temporary.
2550 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2551 # array_diff is completely broken for arrays of arrays, sigh. Re-
2552 # move any 'readonlytext' error manually.
2553 $out = array();
2554 foreach( $result as $error ) {
2555 if( $error != array( 'readonlytext' ) ) {
2556 $out []= $error;
2557 }
2558 }
2559 $wgOut->showPermissionsErrorPage( $out );
2560 return;
2561 }
2562 if( $result == array( array('readonlytext') ) ) {
2563 $wgOut->readOnlyPage();
2564 return;
2565 }
2566
2567 $current = $details['current'];
2568 $target = $details['target'];
2569 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2570 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2571 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2572 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2573 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2574 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2575 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2576 $wgOut->returnToMain( false, $this->mTitle );
2577 }
2578
2579
2580 /**
2581 * Do standard deferred updates after page view
2582 * @private
2583 */
2584 function viewUpdates() {
2585 global $wgDeferredUpdateList;
2586
2587 if ( 0 != $this->getID() ) {
2588 global $wgDisableCounters;
2589 if( !$wgDisableCounters ) {
2590 Article::incViewCount( $this->getID() );
2591 $u = new SiteStatsUpdate( 1, 0, 0 );
2592 array_push( $wgDeferredUpdateList, $u );
2593 }
2594 }
2595
2596 # Update newtalk / watchlist notification status
2597 global $wgUser;
2598 $wgUser->clearNotification( $this->mTitle );
2599 }
2600
2601 /**
2602 * Prepare text which is about to be saved.
2603 * Returns a stdclass with source, pst and output members
2604 */
2605 function prepareTextForEdit( $text, $revid=null ) {
2606 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2607 // Already prepared
2608 return $this->mPreparedEdit;
2609 }
2610 global $wgParser;
2611 $edit = (object)array();
2612 $edit->revid = $revid;
2613 $edit->newText = $text;
2614 $edit->pst = $this->preSaveTransform( $text );
2615 $options = new ParserOptions;
2616 $options->setTidy( true );
2617 $options->enableLimitReport();
2618 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2619 $edit->oldText = $this->getContent();
2620 $this->mPreparedEdit = $edit;
2621 return $edit;
2622 }
2623
2624 /**
2625 * Do standard deferred updates after page edit.
2626 * Update links tables, site stats, search index and message cache.
2627 * Every 100th edit, prune the recent changes table.
2628 *
2629 * @private
2630 * @param $text New text of the article
2631 * @param $summary Edit summary
2632 * @param $minoredit Minor edit
2633 * @param $timestamp_of_pagechange Timestamp associated with the page change
2634 * @param $newid rev_id value of the new revision
2635 * @param $changed Whether or not the content actually changed
2636 */
2637 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2638 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2639
2640 wfProfileIn( __METHOD__ );
2641
2642 # Parse the text
2643 # Be careful not to double-PST: $text is usually already PST-ed once
2644 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2645 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2646 $editInfo = $this->prepareTextForEdit( $text, $newid );
2647 } else {
2648 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2649 $editInfo = $this->mPreparedEdit;
2650 }
2651
2652 # Save it to the parser cache
2653 if ( $wgEnableParserCache ) {
2654 $parserCache = ParserCache::singleton();
2655 $parserCache->save( $editInfo->output, $this, $wgUser );
2656 }
2657
2658 # Update the links tables
2659 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
2660 $u->doUpdate();
2661
2662 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2663 if ( 0 == mt_rand( 0, 99 ) ) {
2664 // Flush old entries from the `recentchanges` table; we do this on
2665 // random requests so as to avoid an increase in writes for no good reason
2666 global $wgRCMaxAge;
2667 $dbw = wfGetDB( DB_MASTER );
2668 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2669 $recentchanges = $dbw->tableName( 'recentchanges' );
2670 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2671 $dbw->query( $sql );
2672 }
2673 }
2674
2675 $id = $this->getID();
2676 $title = $this->mTitle->getPrefixedDBkey();
2677 $shortTitle = $this->mTitle->getDBkey();
2678
2679 if ( 0 == $id ) {
2680 wfProfileOut( __METHOD__ );
2681 return;
2682 }
2683
2684 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2685 array_push( $wgDeferredUpdateList, $u );
2686 $u = new SearchUpdate( $id, $title, $text );
2687 array_push( $wgDeferredUpdateList, $u );
2688
2689 # If this is another user's talk page, update newtalk
2690 # Don't do this if $changed = false otherwise some idiot can null-edit a
2691 # load of user talk pages and piss people off, nor if it's a minor edit
2692 # by a properly-flagged bot.
2693 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2694 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2695 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2696 $other = User::newFromName( $shortTitle );
2697 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2698 // An anonymous user
2699 $other = new User();
2700 $other->setName( $shortTitle );
2701 }
2702 if( $other ) {
2703 $other->setNewtalk( true );
2704 }
2705 }
2706 }
2707
2708 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2709 $wgMessageCache->replace( $shortTitle, $text );
2710 }
2711
2712 wfProfileOut( __METHOD__ );
2713 }
2714
2715 /**
2716 * Perform article updates on a special page creation.
2717 *
2718 * @param Revision $rev
2719 *
2720 * @todo This is a shitty interface function. Kill it and replace the
2721 * other shitty functions like editUpdates and such so it's not needed
2722 * anymore.
2723 */
2724 function createUpdates( $rev ) {
2725 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2726 $this->mTotalAdjustment = 1;
2727 $this->editUpdates( $rev->getText(), $rev->getComment(),
2728 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2729 }
2730
2731 /**
2732 * Generate the navigation links when browsing through an article revisions
2733 * It shows the information as:
2734 * Revision as of \<date\>; view current revision
2735 * \<- Previous version | Next Version -\>
2736 *
2737 * @private
2738 * @param string $oldid Revision ID of this article revision
2739 */
2740 function setOldSubtitle( $oldid=0 ) {
2741 global $wgLang, $wgOut, $wgUser;
2742
2743 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2744 return;
2745 }
2746
2747 $revision = Revision::newFromId( $oldid );
2748
2749 $current = ( $oldid == $this->mLatest );
2750 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2751 $sk = $wgUser->getSkin();
2752 $lnk = $current
2753 ? wfMsg( 'currentrevisionlink' )
2754 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2755 $curdiff = $current
2756 ? wfMsg( 'diff' )
2757 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2758 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2759 $prevlink = $prev
2760 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2761 : wfMsg( 'previousrevision' );
2762 $prevdiff = $prev
2763 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2764 : wfMsg( 'diff' );
2765 $nextlink = $current
2766 ? wfMsg( 'nextrevision' )
2767 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2768 $nextdiff = $current
2769 ? wfMsg( 'diff' )
2770 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2771
2772 $cdel='';
2773 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2774 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2775 if( $revision->isCurrent() ) {
2776 // We don't handle top deleted edits too well
2777 $cdel = wfMsgHtml('rev-delundel');
2778 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2779 // If revision was hidden from sysops
2780 $cdel = wfMsgHtml('rev-delundel');
2781 } else {
2782 $cdel = $sk->makeKnownLinkObj( $revdel,
2783 wfMsgHtml('rev-delundel'),
2784 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2785 '&oldid=' . urlencode( $oldid ) );
2786 // Bolden oversighted content
2787 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2788 $cdel = "<strong>$cdel</strong>";
2789 }
2790 $cdel = "(<small>$cdel</small>) ";
2791 }
2792 # Show user links if allowed to see them. Normally they
2793 # are hidden regardless, but since we can already see the text here...
2794 $userlinks = $sk->revUserTools( $revision, false );
2795
2796 $m = wfMsg( 'revision-info-current' );
2797 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2798 ? 'revision-info-current'
2799 : 'revision-info';
2800
2801 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2802
2803 "\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";
2804 $wgOut->setSubtitle( $r );
2805 }
2806
2807 /**
2808 * This function is called right before saving the wikitext,
2809 * so we can do things like signatures and links-in-context.
2810 *
2811 * @param string $text
2812 */
2813 function preSaveTransform( $text ) {
2814 global $wgParser, $wgUser;
2815 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2816 }
2817
2818 /* Caching functions */
2819
2820 /**
2821 * checkLastModified returns true if it has taken care of all
2822 * output to the client that is necessary for this request.
2823 * (that is, it has sent a cached version of the page)
2824 */
2825 function tryFileCache() {
2826 static $called = false;
2827 if( $called ) {
2828 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2829 return;
2830 }
2831 $called = true;
2832 if($this->isFileCacheable()) {
2833 $touched = $this->mTouched;
2834 $cache = new HTMLFileCache( $this->mTitle );
2835 if($cache->isFileCacheGood( $touched )) {
2836 wfDebug( "Article::tryFileCache(): about to load file\n" );
2837 $cache->loadFromFileCache();
2838 return true;
2839 } else {
2840 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2841 ob_start( array(&$cache, 'saveToFileCache' ) );
2842 }
2843 } else {
2844 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2845 }
2846 }
2847
2848 /**
2849 * Check if the page can be cached
2850 * @return bool
2851 */
2852 function isFileCacheable() {
2853 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2854 $action = $wgRequest->getVal( 'action' );
2855 $oldid = $wgRequest->getVal( 'oldid' );
2856 $diff = $wgRequest->getVal( 'diff' );
2857 $redirect = $wgRequest->getVal( 'redirect' );
2858 $printable = $wgRequest->getVal( 'printable' );
2859 $page = $wgRequest->getVal( 'page' );
2860
2861 //check for non-standard user language; this covers uselang,
2862 //and extensions for auto-detecting user language.
2863 $ulang = $wgLang->getCode();
2864 $clang = $wgContLang->getCode();
2865
2866 $cacheable = $wgUseFileCache
2867 && (!$wgShowIPinHeader)
2868 && ($this->getID() != 0)
2869 && ($wgUser->isAnon())
2870 && (!$wgUser->getNewtalk())
2871 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2872 && (empty( $action ) || $action == 'view')
2873 && (!isset($oldid))
2874 && (!isset($diff))
2875 && (!isset($redirect))
2876 && (!isset($printable))
2877 && !isset($page)
2878 && (!$this->mRedirectedFrom)
2879 && ($ulang === $clang);
2880
2881 if ( $cacheable ) {
2882 //extension may have reason to disable file caching on some pages.
2883 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2884 }
2885
2886 return $cacheable;
2887 }
2888
2889 /**
2890 * Loads page_touched and returns a value indicating if it should be used
2891 *
2892 */
2893 function checkTouched() {
2894 if( !$this->mDataLoaded ) {
2895 $this->loadPageData();
2896 }
2897 return !$this->mIsRedirect;
2898 }
2899
2900 /**
2901 * Get the page_touched field
2902 */
2903 function getTouched() {
2904 # Ensure that page data has been loaded
2905 if( !$this->mDataLoaded ) {
2906 $this->loadPageData();
2907 }
2908 return $this->mTouched;
2909 }
2910
2911 /**
2912 * Get the page_latest field
2913 */
2914 function getLatest() {
2915 if ( !$this->mDataLoaded ) {
2916 $this->loadPageData();
2917 }
2918 return $this->mLatest;
2919 }
2920
2921 /**
2922 * Edit an article without doing all that other stuff
2923 * The article must already exist; link tables etc
2924 * are not updated, caches are not flushed.
2925 *
2926 * @param string $text text submitted
2927 * @param string $comment comment submitted
2928 * @param bool $minor whereas it's a minor modification
2929 */
2930 function quickEdit( $text, $comment = '', $minor = 0 ) {
2931 wfProfileIn( __METHOD__ );
2932
2933 $dbw = wfGetDB( DB_MASTER );
2934 $dbw->begin();
2935 $revision = new Revision( array(
2936 'page' => $this->getId(),
2937 'text' => $text,
2938 'comment' => $comment,
2939 'minor_edit' => $minor ? 1 : 0,
2940 ) );
2941 $revision->insertOn( $dbw );
2942 $this->updateRevisionOn( $dbw, $revision );
2943 $dbw->commit();
2944
2945 wfProfileOut( __METHOD__ );
2946 }
2947
2948 /**
2949 * Used to increment the view counter
2950 *
2951 * @static
2952 * @param integer $id article id
2953 */
2954 function incViewCount( $id ) {
2955 $id = intval( $id );
2956 global $wgHitcounterUpdateFreq, $wgDBtype;
2957
2958 $dbw = wfGetDB( DB_MASTER );
2959 $pageTable = $dbw->tableName( 'page' );
2960 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2961 $acchitsTable = $dbw->tableName( 'acchits' );
2962
2963 if( $wgHitcounterUpdateFreq <= 1 ) {
2964 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2965 return;
2966 }
2967
2968 # Not important enough to warrant an error page in case of failure
2969 $oldignore = $dbw->ignoreErrors( true );
2970
2971 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2972
2973 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2974 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2975 # Most of the time (or on SQL errors), skip row count check
2976 $dbw->ignoreErrors( $oldignore );
2977 return;
2978 }
2979
2980 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2981 $row = $dbw->fetchObject( $res );
2982 $rown = intval( $row->n );
2983 if( $rown >= $wgHitcounterUpdateFreq ){
2984 wfProfileIn( 'Article::incViewCount-collect' );
2985 $old_user_abort = ignore_user_abort( true );
2986
2987 if ($wgDBtype == 'mysql')
2988 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2989 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2990 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2991 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2992 'GROUP BY hc_id');
2993 $dbw->query("DELETE FROM $hitcounterTable");
2994 if ($wgDBtype == 'mysql') {
2995 $dbw->query('UNLOCK TABLES');
2996 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2997 'WHERE page_id = hc_id');
2998 }
2999 else {
3000 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3001 "FROM $acchitsTable WHERE page_id = hc_id");
3002 }
3003 $dbw->query("DROP TABLE $acchitsTable");
3004
3005 ignore_user_abort( $old_user_abort );
3006 wfProfileOut( 'Article::incViewCount-collect' );
3007 }
3008 $dbw->ignoreErrors( $oldignore );
3009 }
3010
3011 /**#@+
3012 * The onArticle*() functions are supposed to be a kind of hooks
3013 * which should be called whenever any of the specified actions
3014 * are done.
3015 *
3016 * This is a good place to put code to clear caches, for instance.
3017 *
3018 * This is called on page move and undelete, as well as edit
3019 * @static
3020 * @param $title_obj a title object
3021 */
3022
3023 static function onArticleCreate($title) {
3024 # The talk page isn't in the regular link tables, so we need to update manually:
3025 if ( $title->isTalkPage() ) {
3026 $other = $title->getSubjectPage();
3027 } else {
3028 $other = $title->getTalkPage();
3029 }
3030 $other->invalidateCache();
3031 $other->purgeSquid();
3032
3033 $title->touchLinks();
3034 $title->purgeSquid();
3035 $title->deleteTitleProtection();
3036 }
3037
3038 static function onArticleDelete( $title ) {
3039 global $wgUseFileCache, $wgMessageCache;
3040
3041 // Update existence markers on article/talk tabs...
3042 if( $title->isTalkPage() ) {
3043 $other = $title->getSubjectPage();
3044 } else {
3045 $other = $title->getTalkPage();
3046 }
3047 $other->invalidateCache();
3048 $other->purgeSquid();
3049
3050 $title->touchLinks();
3051 $title->purgeSquid();
3052
3053 # File cache
3054 if ( $wgUseFileCache ) {
3055 $cm = new HTMLFileCache( $title );
3056 @unlink( $cm->fileCacheName() );
3057 }
3058
3059 if( $title->getNamespace() == NS_MEDIAWIKI) {
3060 $wgMessageCache->replace( $title->getDBkey(), false );
3061 }
3062 if( $title->getNamespace() == NS_IMAGE ) {
3063 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3064 $update->doUpdate();
3065 }
3066 }
3067
3068 /**
3069 * Purge caches on page update etc
3070 */
3071 static function onArticleEdit( $title ) {
3072 global $wgDeferredUpdateList, $wgUseFileCache;
3073
3074 // Invalidate caches of articles which include this page
3075 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3076
3077 // Invalidate the caches of all pages which redirect here
3078 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3079
3080 # Purge squid for this page only
3081 $title->purgeSquid();
3082
3083 # Clear file cache
3084 if ( $wgUseFileCache ) {
3085 $cm = new HTMLFileCache( $title );
3086 @unlink( $cm->fileCacheName() );
3087 }
3088 }
3089
3090 /**#@-*/
3091
3092 /**
3093 * Overriden by ImagePage class, only present here to avoid a fatal error
3094 * Called for ?action=revert
3095 */
3096 public function revert(){
3097 global $wgOut;
3098 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3099 }
3100
3101 /**
3102 * Info about this page
3103 * Called for ?action=info when $wgAllowPageInfo is on.
3104 *
3105 * @public
3106 */
3107 function info() {
3108 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3109
3110 if ( !$wgAllowPageInfo ) {
3111 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3112 return;
3113 }
3114
3115 $page = $this->mTitle->getSubjectPage();
3116
3117 $wgOut->setPagetitle( $page->getPrefixedText() );
3118 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3119 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3120
3121 if( !$this->mTitle->exists() ) {
3122 $wgOut->addHtml( '<div class="noarticletext">' );
3123 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3124 // This doesn't quite make sense; the user is asking for
3125 // information about the _page_, not the message... -- RC
3126 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3127 } else {
3128 $msg = $wgUser->isLoggedIn()
3129 ? 'noarticletext'
3130 : 'noarticletextanon';
3131 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3132 }
3133 $wgOut->addHtml( '</div>' );
3134 } else {
3135 $dbr = wfGetDB( DB_SLAVE );
3136 $wl_clause = array(
3137 'wl_title' => $page->getDBkey(),
3138 'wl_namespace' => $page->getNamespace() );
3139 $numwatchers = $dbr->selectField(
3140 'watchlist',
3141 'COUNT(*)',
3142 $wl_clause,
3143 __METHOD__,
3144 $this->getSelectOptions() );
3145
3146 $pageInfo = $this->pageCountInfo( $page );
3147 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3148
3149 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3150 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3151 if( $talkInfo ) {
3152 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3153 }
3154 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3155 if( $talkInfo ) {
3156 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3157 }
3158 $wgOut->addHTML( '</ul>' );
3159
3160 }
3161 }
3162
3163 /**
3164 * Return the total number of edits and number of unique editors
3165 * on a given page. If page does not exist, returns false.
3166 *
3167 * @param Title $title
3168 * @return array
3169 * @private
3170 */
3171 function pageCountInfo( $title ) {
3172 $id = $title->getArticleId();
3173 if( $id == 0 ) {
3174 return false;
3175 }
3176
3177 $dbr = wfGetDB( DB_SLAVE );
3178
3179 $rev_clause = array( 'rev_page' => $id );
3180
3181 $edits = $dbr->selectField(
3182 'revision',
3183 'COUNT(rev_page)',
3184 $rev_clause,
3185 __METHOD__,
3186 $this->getSelectOptions() );
3187
3188 $authors = $dbr->selectField(
3189 'revision',
3190 'COUNT(DISTINCT rev_user_text)',
3191 $rev_clause,
3192 __METHOD__,
3193 $this->getSelectOptions() );
3194
3195 return array( 'edits' => $edits, 'authors' => $authors );
3196 }
3197
3198 /**
3199 * Return a list of templates used by this article.
3200 * Uses the templatelinks table
3201 *
3202 * @return array Array of Title objects
3203 */
3204 function getUsedTemplates() {
3205 $result = array();
3206 $id = $this->mTitle->getArticleID();
3207 if( $id == 0 ) {
3208 return array();
3209 }
3210
3211 $dbr = wfGetDB( DB_SLAVE );
3212 $res = $dbr->select( array( 'templatelinks' ),
3213 array( 'tl_namespace', 'tl_title' ),
3214 array( 'tl_from' => $id ),
3215 'Article:getUsedTemplates' );
3216 if ( false !== $res ) {
3217 if ( $dbr->numRows( $res ) ) {
3218 while ( $row = $dbr->fetchObject( $res ) ) {
3219 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3220 }
3221 }
3222 }
3223 $dbr->freeResult( $res );
3224 return $result;
3225 }
3226
3227 /**
3228 * Returns a list of hidden categories this page is a member of.
3229 * Uses the page_props and categorylinks tables.
3230 *
3231 * @return array Array of Title objects
3232 */
3233 function getHiddenCategories() {
3234 $result = array();
3235 $id = $this->mTitle->getArticleID();
3236 if( $id == 0 ) {
3237 return array();
3238 }
3239
3240 $dbr = wfGetDB( DB_SLAVE );
3241 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3242 array( 'cl_to' ),
3243 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3244 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3245 'Article:getHiddenCategories' );
3246 if ( false !== $res ) {
3247 if ( $dbr->numRows( $res ) ) {
3248 while ( $row = $dbr->fetchObject( $res ) ) {
3249 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3250 }
3251 }
3252 }
3253 $dbr->freeResult( $res );
3254 return $result;
3255 }
3256
3257 /**
3258 * Return an auto-generated summary if the text provided is a redirect.
3259 *
3260 * @param string $text The wikitext to check
3261 * @return string '' or an appropriate summary
3262 */
3263 public static function getRedirectAutosummary( $text ) {
3264 $rt = Title::newFromRedirect( $text );
3265 if( is_object( $rt ) )
3266 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3267 else
3268 return '';
3269 }
3270
3271 /**
3272 * Return an auto-generated summary if the new text is much shorter than
3273 * the old text.
3274 *
3275 * @param string $oldtext The previous text of the page
3276 * @param string $text The submitted text of the page
3277 * @return string An appropriate autosummary, or an empty string.
3278 */
3279 public static function getBlankingAutosummary( $oldtext, $text ) {
3280 if ($oldtext!='' && $text=='') {
3281 return wfMsgForContent('autosumm-blank');
3282 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3283 #Removing more than 90% of the article
3284 global $wgContLang;
3285 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3286 return wfMsgForContent('autosumm-replace', $truncatedtext);
3287 } else {
3288 return '';
3289 }
3290 }
3291
3292 /**
3293 * Return an applicable autosummary if one exists for the given edit.
3294 * @param string $oldtext The previous text of the page.
3295 * @param string $newtext The submitted text of the page.
3296 * @param bitmask $flags A bitmask of flags submitted for the edit.
3297 * @return string An appropriate autosummary, or an empty string.
3298 */
3299 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3300
3301 # This code is UGLY UGLY UGLY.
3302 # Somebody PLEASE come up with a more elegant way to do it.
3303
3304 #Redirect autosummaries
3305 $summary = self::getRedirectAutosummary( $newtext );
3306
3307 if ($summary)
3308 return $summary;
3309
3310 #Blanking autosummaries
3311 if (!($flags & EDIT_NEW))
3312 $summary = self::getBlankingAutosummary( $oldtext, $newtext );
3313
3314 if ($summary)
3315 return $summary;
3316
3317 #New page autosummaries
3318 if ($flags & EDIT_NEW && strlen($newtext)) {
3319 #If they're making a new article, give its text, truncated, in the summary.
3320 global $wgContLang;
3321 $truncatedtext = $wgContLang->truncate(
3322 str_replace("\n", ' ', $newtext),
3323 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3324 '...' );
3325 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3326 }
3327
3328 if ($summary)
3329 return $summary;
3330
3331 return $summary;
3332 }
3333
3334 /**
3335 * Add the primary page-view wikitext to the output buffer
3336 * Saves the text into the parser cache if possible.
3337 * Updates templatelinks if it is out of date.
3338 *
3339 * @param string $text
3340 * @param bool $cache
3341 */
3342 public function outputWikiText( $text, $cache = true ) {
3343 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3344
3345 $popts = $wgOut->parserOptions();
3346 $popts->setTidy(true);
3347 $popts->enableLimitReport();
3348 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3349 $popts, true, true, $this->getRevIdFetched() );
3350 $popts->setTidy(false);
3351 $popts->enableLimitReport( false );
3352 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3353 $parserCache = ParserCache::singleton();
3354 $parserCache->save( $parserOutput, $this, $wgUser );
3355 }
3356
3357 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3358 // templatelinks table may have become out of sync,
3359 // especially if using variable-based transclusions.
3360 // For paranoia, check if things have changed and if
3361 // so apply updates to the database. This will ensure
3362 // that cascaded protections apply as soon as the changes
3363 // are visible.
3364
3365 # Get templates from templatelinks
3366 $id = $this->mTitle->getArticleID();
3367
3368 $tlTemplates = array();
3369
3370 $dbr = wfGetDB( DB_SLAVE );
3371 $res = $dbr->select( array( 'templatelinks' ),
3372 array( 'tl_namespace', 'tl_title' ),
3373 array( 'tl_from' => $id ),
3374 'Article:getUsedTemplates' );
3375
3376 global $wgContLang;
3377
3378 if ( false !== $res ) {
3379 if ( $dbr->numRows( $res ) ) {
3380 while ( $row = $dbr->fetchObject( $res ) ) {
3381 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3382 }
3383 }
3384 }
3385
3386 # Get templates from parser output.
3387 $poTemplates_allns = $parserOutput->getTemplates();
3388
3389 $poTemplates = array ();
3390 foreach ( $poTemplates_allns as $ns_templates ) {
3391 $poTemplates = array_merge( $poTemplates, $ns_templates );
3392 }
3393
3394 # Get the diff
3395 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3396
3397 if ( count( $templates_diff ) > 0 ) {
3398 # Whee, link updates time.
3399 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3400
3401 $dbw = wfGetDb( DB_MASTER );
3402 $dbw->begin();
3403
3404 $u->doUpdate();
3405
3406 $dbw->commit();
3407 }
3408 }
3409
3410 $wgOut->addParserOutput( $parserOutput );
3411 }
3412
3413 /**
3414 * Update all the appropriate counts in the category table, given that
3415 * we've added the categories $added and deleted the categories $deleted.
3416 *
3417 * @param $added array The names of categories that were added
3418 * @param $deleted array The names of categories that were deleted
3419 * @return null
3420 */
3421 public function updateCategoryCounts( $added, $deleted ) {
3422 $ns = $this->mTitle->getNamespace();
3423 $dbw = wfGetDB( DB_MASTER );
3424
3425 # First make sure the rows exist. If one of the "deleted" ones didn't
3426 # exist, we might legitimately not create it, but it's simpler to just
3427 # create it and then give it a negative value, since the value is bogus
3428 # anyway.
3429 #
3430 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3431 $insertCats = array_merge( $added, $deleted );
3432 if( !$insertCats ) {
3433 # Okay, nothing to do
3434 return;
3435 }
3436 $insertRows = array();
3437 foreach( $insertCats as $cat ) {
3438 $insertRows[] = array( 'cat_title' => $cat );
3439 }
3440 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3441
3442 $addFields = array( 'cat_pages = cat_pages + 1' );
3443 $removeFields = array( 'cat_pages = cat_pages - 1' );
3444 if( $ns == NS_CATEGORY ) {
3445 $addFields[] = 'cat_subcats = cat_subcats + 1';
3446 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3447 } elseif( $ns == NS_IMAGE ) {
3448 $addFields[] = 'cat_files = cat_files + 1';
3449 $removeFields[] = 'cat_files = cat_files - 1';
3450 }
3451
3452 if ( $added ) {
3453 $dbw->update(
3454 'category',
3455 $addFields,
3456 array( 'cat_title' => $added ),
3457 __METHOD__
3458 );
3459 }
3460 if ( $deleted ) {
3461 $dbw->update(
3462 'category',
3463 $removeFields,
3464 array( 'cat_title' => $deleted ),
3465 __METHOD__
3466 );
3467 }
3468 }
3469 }