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