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