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