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