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