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