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