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