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