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