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