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