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