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