Revert r44801 "Tweaks from profiling"
[lhc/web/wiklou.git] / includes / Wiki.php
1 <?php
2 /**
3 * MediaWiki is the to-be base class for this whole project
4 */
5 class MediaWiki {
6
7 var $GET; /* Stores the $_GET variables at time of creation, can be changed */
8 var $params = array();
9
10 /** Constructor. It just save the $_GET variable */
11 function __construct() {
12 $this->GET = $_GET;
13 }
14
15 /**
16 * Stores key/value pairs to circumvent global variables
17 * Note that keys are case-insensitive!
18 *
19 * @param $key String: key to store
20 * @param $value Mixed: value to put for the key
21 */
22 function setVal( $key, &$value ) {
23 $key = strtolower( $key );
24 $this->params[$key] =& $value;
25 }
26
27 /**
28 * Retrieves key/value pairs to circumvent global variables
29 * Note that keys are case-insensitive!
30 *
31 * @param $key String: key to get
32 * @param $default Mixed: default value if if the key doesn't exist
33 */
34 function getVal( $key, $default = '' ) {
35 $key = strtolower( $key );
36 if( isset( $this->params[$key] ) ) {
37 return $this->params[$key];
38 }
39 return $default;
40 }
41
42 /**
43 * Initialization of ... everything
44 * Performs the request too
45 *
46 * @param $title Title ($wgTitle)
47 * @param $article Article
48 * @param $output OutputPage
49 * @param $user User
50 * @param $request WebRequest
51 */
52 function initialize( &$title, &$article, &$output, &$user, $request ) {
53 wfProfileIn( __METHOD__ );
54 $this->preliminaryChecks( $title, $output, $request );
55 if( !$this->initializeSpecialCases( $title, $output, $request ) ) {
56 $new_article = $this->initializeArticle( $title, $request );
57 if( is_object( $new_article ) ) {
58 $article = $new_article;
59 $this->performAction( $output, $article, $title, $user, $request );
60 } elseif( is_string( $new_article ) ) {
61 $output->redirect( $new_article );
62 } else {
63 wfProfileOut( __METHOD__ );
64 throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
65 }
66 }
67 wfProfileOut( __METHOD__ );
68 }
69
70 /**
71 * Check if the maximum lag of database slaves is higher that $maxLag, and
72 * if it's the case, output an error message
73 *
74 * @param $maxLag int: maximum lag allowed for the request, as supplied by
75 * the client
76 * @return bool true if the request can continue
77 */
78 function checkMaxLag( $maxLag ) {
79 list( $host, $lag ) = wfGetLB()->getMaxLag();
80 if( $lag > $maxLag ) {
81 wfMaxlagError( $host, $lag, $maxLag );
82 return false;
83 } else {
84 return true;
85 }
86 }
87
88
89 /**
90 * Checks some initial queries
91 * Note that $title here is *not* a Title object, but a string!
92 *
93 * @param $title String
94 * @param $action String
95 * @return Title object to be $wgTitle
96 */
97 function checkInitialQueries( $title, $action ) {
98 global $wgOut, $wgRequest, $wgContLang;
99 if( $wgRequest->getVal( 'printable' ) === 'yes' ) {
100 $wgOut->setPrintable();
101 }
102 $ret = NULL;
103 if( $curid = $wgRequest->getInt( 'curid' ) ) {
104 # URLs like this are generated by RC, because rc_title isn't always accurate
105 $ret = Title::newFromID( $curid );
106 } elseif( '' == $title && 'delete' != $action ) {
107 $ret = Title::newMainPage();
108 } else {
109 $ret = Title::newFromURL( $title );
110 // check variant links so that interwiki links don't have to worry
111 // about the possible different language variants
112 if( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 )
113 $wgContLang->findVariantLink( $title, $ret );
114
115 }
116 if( ( $oldid = $wgRequest->getInt( 'oldid' ) )
117 && ( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) ) {
118 // Allow oldid to override a changed or missing title.
119 $rev = Revision::newFromId( $oldid );
120 if( $rev ) {
121 $ret = $rev->getTitle();
122 }
123 }
124 return $ret;
125 }
126
127 /**
128 * Checks for search query and anon-cannot-read case
129 *
130 * @param $title Title
131 * @param $output OutputPage
132 * @param $request WebRequest
133 */
134 function preliminaryChecks( &$title, &$output, $request ) {
135 if( $request->getCheck( 'search' ) ) {
136 // Compatibility with old search URLs which didn't use Special:Search
137 // Just check for presence here, so blank requests still
138 // show the search page when using ugly URLs (bug 8054).
139
140 // Do this above the read whitelist check for security...
141 $title = SpecialPage::getTitleFor( 'Search' );
142 }
143 # If the user is not logged in, the Namespace:title of the article must be in
144 # the Read array in order for the user to see it. (We have to check here to
145 # catch special pages etc. We check again in Article::view())
146 if( !is_null( $title ) && !$title->userCanRead() ) {
147 $output->loginToUse();
148 $output->output();
149 exit;
150 }
151 }
152
153 /**
154 * Initialize some special cases:
155 * - bad titles
156 * - local interwiki redirects
157 * - redirect loop
158 * - special pages
159 *
160 * @param $title Title
161 * @param $output OutputPage
162 * @param $request WebRequest
163 * @return bool true if the request is already executed
164 */
165 function initializeSpecialCases( &$title, &$output, $request ) {
166 wfProfileIn( __METHOD__ );
167
168 $action = $this->getVal( 'Action' );
169 if( is_null($title) || $title->getDBkey() == '' ) {
170 $title = SpecialPage::getTitleFor( 'Badtitle' );
171 # Die now before we mess up $wgArticle and the skin stops working
172 throw new ErrorPageError( 'badtitle', 'badtitletext' );
173 } else if( $title->getInterwiki() != '' ) {
174 if( $rdfrom = $request->getVal( 'rdfrom' ) ) {
175 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
176 } else {
177 $url = $title->getFullURL();
178 }
179 /* Check for a redirect loop */
180 if( !preg_match( '/^' . preg_quote( $this->getVal('Server'), '/' ) . '/', $url ) && $title->isLocal() ) {
181 $output->redirect( $url );
182 } else {
183 $title = SpecialPage::getTitleFor( 'Badtitle' );
184 throw new ErrorPageError( 'badtitle', 'badtitletext' );
185 }
186 } else if( $action == 'view' && !$request->wasPosted() &&
187 ( !isset($this->GET['title']) || $title->getPrefixedDBKey() != $this->GET['title'] ) &&
188 !count( array_diff( array_keys( $this->GET ), array( 'action', 'title' ) ) ) )
189 {
190 $targetUrl = $title->getFullURL();
191 // Redirect to canonical url, make it a 301 to allow caching
192 if( $targetUrl == $request->getFullRequestURL() ) {
193 $message = "Redirect loop detected!\n\n" .
194 "This means the wiki got confused about what page was " .
195 "requested; this sometimes happens when moving a wiki " .
196 "to a new server or changing the server configuration.\n\n";
197
198 if( $this->getVal( 'UsePathInfo' ) ) {
199 $message .= "The wiki is trying to interpret the page " .
200 "title from the URL path portion (PATH_INFO), which " .
201 "sometimes fails depending on the web server. Try " .
202 "setting \"\$wgUsePathInfo = false;\" in your " .
203 "LocalSettings.php, or check that \$wgArticlePath " .
204 "is correct.";
205 } else {
206 $message .= "Your web server was detected as possibly not " .
207 "supporting URL path components (PATH_INFO) correctly; " .
208 "check your LocalSettings.php for a customized " .
209 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
210 "to true.";
211 }
212 wfHttpError( 500, "Internal error", $message );
213 return false;
214 } else {
215 $output->setSquidMaxage( 1200 );
216 $output->redirect( $targetUrl, '301' );
217 }
218 } else if( NS_SPECIAL == $title->getNamespace() ) {
219 /* actions that need to be made when we have a special pages */
220 SpecialPage::executePath( $title );
221 } else {
222 /* Try low-level file cache hit */
223 if( $title->getNamespace() != NS_MEDIAWIKI && HTMLFileCache::useFileCache() ) {
224 $cache = new HTMLFileCache( $title );
225 if( $cache->isFileCacheGood( /* Assume up to date */ ) ) {
226 global $wgOut;
227 /* Check incoming headers to see if client has this cached */
228 if( !$wgOut->checkLastModified( $cache->fileCacheTime() ) ) {
229 wfDebug( "MediaWiki::initializeSpecialCases(): about to load file cache\n" );
230 $cache->loadFromFileCache();
231 # Tell $wgOut that output is taken care of
232 $wgOut->disable();
233 # Do any stats increment/watchlist stuff
234 $article = self::articleFromTitle( $title );
235 $article->viewUpdates();
236 }
237 wfProfileOut( __METHOD__ );
238 return true;
239 }
240 }
241 /* No match to special cases */
242 wfProfileOut( __METHOD__ );
243 return false;
244 }
245 /* Did match a special case */
246 wfProfileOut( __METHOD__ );
247 return true;
248 }
249
250 /**
251 * Create an Article object of the appropriate class for the given page.
252 *
253 * @param $title Title
254 * @return Article object
255 */
256 static function articleFromTitle( &$title ) {
257 if( NS_MEDIA == $title->getNamespace() ) {
258 // FIXME: where should this go?
259 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
260 }
261
262 $article = null;
263 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
264 if( $article ) {
265 return $article;
266 }
267
268 switch( $title->getNamespace() ) {
269 case NS_FILE:
270 return new ImagePage( $title );
271 case NS_CATEGORY:
272 return new CategoryPage( $title );
273 default:
274 return new Article( $title );
275 }
276 }
277
278 /**
279 * Initialize the object to be known as $wgArticle for "standard" actions
280 * Create an Article object for the page, following redirects if needed.
281 *
282 * @param $title Title ($wgTitle)
283 * @param $request WebRequest
284 * @return mixed an Article, or a string to redirect to another URL
285 */
286 function initializeArticle( &$title, $request ) {
287 wfProfileIn( __METHOD__ );
288
289 $action = $this->getVal( 'action' );
290 $article = self::articleFromTitle( $title );
291
292 // Namespace might change when using redirects
293 // Check for redirects ...
294 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
295 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
296 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
297 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
298 // ... and the article is not a non-redirect image page with associated file
299 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
300 {
301 # Give extensions a change to ignore/handle redirects as needed
302 $ignoreRedirect = $target = false;
303
304 $dbr = wfGetDB( DB_SLAVE );
305 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
306
307 wfRunHooks( 'InitializeArticleMaybeRedirect',
308 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
309
310 // Follow redirects only for... redirects
311 if( !$ignoreRedirect && $article->isRedirect() ) {
312 # Is the target already set by an extension?
313 $target = $target ? $target : $article->followRedirect();
314 if( is_string( $target ) ) {
315 if( !$this->getVal( 'DisableHardRedirects' ) ) {
316 // we'll need to redirect
317 return $target;
318 }
319 }
320
321 if( is_object( $target ) ) {
322 // Rewrite environment to redirected article
323 $rarticle = self::articleFromTitle( $target );
324 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
325 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
326 $rarticle->setRedirectedFrom( $title );
327 $article = $rarticle;
328 $title = $target;
329 }
330 }
331 } else {
332 $title = $article->getTitle();
333 }
334 }
335 wfProfileOut( __METHOD__ );
336 return $article;
337 }
338
339 /**
340 * Cleaning up by doing deferred updates, calling LBFactory and doing the output
341 *
342 * @param $deferredUpdates array of updates to do
343 * @param $output OutputPage
344 */
345 function finalCleanup( &$deferredUpdates, &$output ) {
346 wfProfileIn( __METHOD__ );
347 # Now commit any transactions, so that unreported errors after output() don't roll back the whole thing
348 $factory = wfGetLBFactory();
349 $factory->commitMasterChanges();
350 # Output everything!
351 $output->output();
352 # Do any deferred jobs
353 $this->doUpdates( $deferredUpdates );
354 $this->doJobs();
355 # Commit and close up!
356 $factory->shutdown();
357 wfProfileOut( __METHOD__ );
358 }
359
360 /**
361 * Deferred updates aren't really deferred anymore. It's important to report
362 * errors to the user, and that means doing this before OutputPage::output().
363 * Note that for page saves, the client will wait until the script exits
364 * anyway before following the redirect.
365 *
366 * @param $updates array of objects that hold an update to do
367 */
368 function doUpdates( &$updates ) {
369 wfProfileIn( __METHOD__ );
370 /* No need to get master connections in case of empty updates array */
371 if (!$updates) {
372 wfProfileOut( __METHOD__ );
373 return;
374 }
375
376 $dbw = wfGetDB( DB_MASTER );
377 foreach( $updates as $up ) {
378 $up->doUpdate();
379
380 # Commit after every update to prevent lock contention
381 if( $dbw->trxLevel() ) {
382 $dbw->commit();
383 }
384 }
385 wfProfileOut( __METHOD__ );
386 }
387
388 /**
389 * Do a job from the job queue
390 */
391 function doJobs() {
392 $jobRunRate = $this->getVal( 'JobRunRate' );
393
394 if( $jobRunRate <= 0 || wfReadOnly() ) {
395 return;
396 }
397 if( $jobRunRate < 1 ) {
398 $max = mt_getrandmax();
399 if( mt_rand( 0, $max ) > $max * $jobRunRate ) {
400 return;
401 }
402 $n = 1;
403 } else {
404 $n = intval( $jobRunRate );
405 }
406
407 while ( $n-- && false != ( $job = Job::pop() ) ) {
408 $output = $job->toString() . "\n";
409 $t = -wfTime();
410 $success = $job->run();
411 $t += wfTime();
412 $t = round( $t*1000 );
413 if( !$success ) {
414 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
415 } else {
416 $output .= "Success, Time: $t ms\n";
417 }
418 wfDebugLog( 'jobqueue', $output );
419 }
420 }
421
422 /**
423 * Ends this task peacefully
424 */
425 function restInPeace() {
426 wfLogProfilingData();
427 wfDebug( "Request ended normally\n" );
428 }
429
430 /**
431 * Perform one of the "standard" actions
432 *
433 * @param $output OutputPage
434 * @param $article Article
435 * @param $title Title
436 * @param $user User
437 * @param $request WebRequest
438 */
439 function performAction( &$output, &$article, &$title, &$user, &$request ) {
440 wfProfileIn( __METHOD__ );
441
442 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
443 wfProfileOut( __METHOD__ );
444 return;
445 }
446
447 $action = $this->getVal( 'Action' );
448 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
449 /* No such action; this will switch to the default case */
450 $action = 'nosuchaction';
451 }
452
453 switch( $action ) {
454 case 'view':
455 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
456 $article->view();
457 break;
458 case 'raw': // includes JS/CSS
459 $raw = new RawPage( $article );
460 $raw->view();
461 break;
462 case 'watch':
463 case 'unwatch':
464 case 'delete':
465 case 'revert':
466 case 'rollback':
467 case 'protect':
468 case 'unprotect':
469 case 'info':
470 case 'markpatrolled':
471 case 'render':
472 case 'deletetrackback':
473 case 'purge':
474 $article->$action();
475 break;
476 case 'print':
477 $article->view();
478 break;
479 case 'dublincore':
480 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
481 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
482 } else {
483 $rdf = new DublinCoreRdf( $article );
484 $rdf->show();
485 }
486 break;
487 case 'creativecommons':
488 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
489 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
490 } else {
491 $rdf = new CreativeCommonsRdf( $article );
492 $rdf->show();
493 }
494 break;
495 case 'credits':
496 Credits::showPage( $article );
497 break;
498 case 'submit':
499 if( session_id() == '' ) {
500 /* Send a cookie so anons get talk message notifications */
501 wfSetupSession();
502 }
503 /* Continue... */
504 case 'edit':
505 case 'editredlink':
506 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
507 $internal = $request->getVal( 'internaledit' );
508 $external = $request->getVal( 'externaledit' );
509 $section = $request->getVal( 'section' );
510 $oldid = $request->getVal( 'oldid' );
511 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
512 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
513 $editor = new EditPage( $article );
514 $editor->submit();
515 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
516 $mode = $request->getVal( 'mode' );
517 $extedit = new ExternalEdit( $article, $mode );
518 $extedit->edit();
519 }
520 }
521 break;
522 case 'history':
523 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
524 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
525 }
526 $history = new PageHistory( $article );
527 $history->history();
528 break;
529 default:
530 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
531 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
532 }
533 }
534 wfProfileOut( __METHOD__ );
535
536 }
537
538 }; /* End of class MediaWiki */