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