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