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