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