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