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