Suggest running update.php on database error
[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, $request ) ) {
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 $ret = null;
112 if( $curid = $wgRequest->getInt( 'curid' ) ) {
113 // URLs like this are generated by RC, because rc_title isn't always accurate
114 $ret = Title::newFromID( $curid );
115 } elseif( $title == '' && $action != 'delete' ) {
116 $ret = Title::newMainPage();
117 } else {
118 $ret = Title::newFromURL( $title );
119 // check variant links so that interwiki links don't have to worry
120 // about the possible different language variants
121 if( count( $wgContLang->getVariants() ) > 1 && !is_null( $ret ) && $ret->getArticleID() == 0 )
122 $wgContLang->findVariantLink( $title, $ret );
123 }
124 // For non-special titles, check for implicit titles
125 if( is_null( $ret ) || $ret->getNamespace() != NS_SPECIAL ) {
126 // We can have urls with just ?diff=,?oldid= or even just ?diff=
127 $oldid = $wgRequest->getInt( 'oldid' );
128 $oldid = $oldid ? $oldid : $wgRequest->getInt( 'diff' );
129 // Allow oldid to override a changed or missing title
130 if( $oldid ) {
131 $rev = Revision::newFromId( $oldid );
132 $ret = $rev ? $rev->getTitle() : $ret;
133 }
134 }
135 return $ret;
136 }
137
138 /**
139 * Checks for search query and anon-cannot-read case
140 *
141 * @param $title Title
142 * @param $output OutputPage
143 * @param $request WebRequest
144 * @return boolean true if successful
145 */
146 function preliminaryChecks( &$title, &$output, $request ) {
147 if( $request->getCheck( 'search' ) ) {
148 // Compatibility with old search URLs which didn't use Special:Search
149 // Just check for presence here, so blank requests still
150 // show the search page when using ugly URLs (bug 8054).
151
152 // Do this above the read whitelist check for security...
153 $title = SpecialPage::getTitleFor( 'Search' );
154 }
155 // If the user is not logged in, the Namespace:title of the article must be in
156 // the Read array in order for the user to see it. (We have to check here to
157 // catch special pages etc. We check again in Article::view())
158 if( !is_null( $title ) && !$title->userCanRead() ) {
159 global $wgDeferredUpdateList;
160 $output->loginToUse();
161 $this->finalCleanup( $wgDeferredUpdateList, $output );
162 $output->disable();
163 return false;
164 }
165 return true;
166 }
167
168 /**
169 * Initialize some special cases:
170 * - bad titles
171 * - local interwiki redirects
172 * - redirect loop
173 * - special pages
174 *
175 * @param $title Title
176 * @param $output OutputPage
177 * @param $request WebRequest
178 * @return bool true if the request is already executed
179 */
180 function handleSpecialCases( &$title, &$output, $request ) {
181 wfProfileIn( __METHOD__ );
182 global $wgContLang, $wgUser;
183 $action = $this->getVal( 'Action' );
184 $perferred = $wgContLang->getPreferredVariant( false );
185
186 // Invalid titles. Bug 21776: The interwikis must redirect even if the page name is empty.
187 if( is_null($title) || ( ( $title->getDBkey() == '' ) && ( $title->getInterwiki() == '' ) ) ) {
188 $title = SpecialPage::getTitleFor( 'Badtitle' );
189 $output->setTitle( $title ); // bug 21456
190 // Die now before we mess up $wgArticle and the skin stops working
191 throw new ErrorPageError( 'badtitle', 'badtitletext' );
192
193 // Interwiki redirects
194 } else if( $title->getInterwiki() != '' ) {
195 if( $rdfrom = $request->getVal( 'rdfrom' ) ) {
196 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
197 } else {
198 $query = $request->getValues();
199 unset( $query['title'] );
200 $url = $title->getFullURL( $query );
201 }
202 /* Check for a redirect loop */
203 if( !preg_match( '/^' . preg_quote( $this->getVal('Server'), '/' ) . '/', $url ) && $title->isLocal() ) {
204 $output->redirect( $url );
205 } else {
206 $title = SpecialPage::getTitleFor( 'Badtitle' );
207 $output->setTitle( $title ); // bug 21456
208 wfProfileOut( __METHOD__ );
209 throw new ErrorPageError( 'badtitle', 'badtitletext' );
210 }
211 // Redirect loops, no title in URL, $wgUsePathInfo URLs, and URLs with a variant
212 } else if( $action == 'view' && !$request->wasPosted() &&
213 ( ( !$request->getVal( 'title' ) || $title->getPrefixedDBKey() != $request->getText( 'title' ) ) ||
214 // No valid variant in URL (if the main-language has multi-variants), to ensure
215 // anonymous access would always be redirect to a URL with 'variant' parameter
216 ( !$request->getVal( 'variant' ) && $wgContLang->hasVariants() && !$wgUser->isLoggedIn() ) ) &&
217 !count( array_diff( array_keys( $request->getValues() ), array( 'action', 'title' ) ) ) )
218 {
219 if( !$wgUser->isLoggedIn() ) {
220 $pref = $wgContLang->getPreferredVariant( false, $fromHeader = true );
221 $targetUrl = $title->getFullURL( '', $variant = $pref );
222 }
223 else
224 $targetUrl = $title->getFullURL();
225 // Redirect to canonical url, make it a 301 to allow caching
226 if( $targetUrl == $request->getFullRequestURL() ) {
227 $message = "Redirect loop detected!\n\n" .
228 "This means the wiki got confused about what page was " .
229 "requested; this sometimes happens when moving a wiki " .
230 "to a new server or changing the server configuration.\n\n";
231
232 if( $this->getVal( 'UsePathInfo' ) ) {
233 $message .= "The wiki is trying to interpret the page " .
234 "title from the URL path portion (PATH_INFO), which " .
235 "sometimes fails depending on the web server. Try " .
236 "setting \"\$wgUsePathInfo = false;\" in your " .
237 "LocalSettings.php, or check that \$wgArticlePath " .
238 "is correct.";
239 } else {
240 $message .= "Your web server was detected as possibly not " .
241 "supporting URL path components (PATH_INFO) correctly; " .
242 "check your LocalSettings.php for a customized " .
243 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
244 "to true.";
245 }
246 wfHttpError( 500, "Internal error", $message );
247 wfProfileOut( __METHOD__ );
248 return false;
249 } else {
250 $output->setSquidMaxage( 1200 );
251 $output->redirect( $targetUrl, '301' );
252 }
253 // Special pages
254 } else if( NS_SPECIAL == $title->getNamespace() ) {
255 /* actions that need to be made when we have a special pages */
256 SpecialPage::executePath( $title );
257 } else {
258 /* No match to special cases */
259 wfProfileOut( __METHOD__ );
260 return false;
261 }
262 /* Did match a special case */
263 wfProfileOut( __METHOD__ );
264 return true;
265 }
266
267 /**
268 * Create an Article object of the appropriate class for the given page.
269 *
270 * @param $title Title
271 * @return Article object
272 */
273 static function articleFromTitle( &$title ) {
274 if( NS_MEDIA == $title->getNamespace() ) {
275 // FIXME: where should this go?
276 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
277 }
278
279 $article = null;
280 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
281 if( $article ) {
282 return $article;
283 }
284
285 switch( $title->getNamespace() ) {
286 case NS_FILE:
287 return new ImagePage( $title );
288 case NS_CATEGORY:
289 return new CategoryPage( $title );
290 default:
291 return new Article( $title );
292 }
293 }
294
295 /**
296 * Initialize the object to be known as $wgArticle for "standard" actions
297 * Create an Article object for the page, following redirects if needed.
298 *
299 * @param $title Title ($wgTitle)
300 * @param $output OutputPage ($wgOut)
301 * @param $request WebRequest ($wgRequest)
302 * @return mixed an Article, or a string to redirect to another URL
303 */
304 function initializeArticle( &$title, &$output, $request ) {
305 wfProfileIn( __METHOD__ );
306
307 $action = $this->getVal( 'action', 'view' );
308 $article = self::articleFromTitle( $title );
309 // NS_MEDIAWIKI has no redirects.
310 // It is also used for CSS/JS, so performance matters here...
311 if( $title->getNamespace() == NS_MEDIAWIKI ) {
312 wfProfileOut( __METHOD__ );
313 return $article;
314 }
315 // Namespace might change when using redirects
316 // Check for redirects ...
317 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
318 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
319 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
320 !$request->getVal( 'diff' ) && // ... and not when showing diff
321 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
322 // ... and the article is not a non-redirect image page with associated file
323 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
324 {
325 // Give extensions a change to ignore/handle redirects as needed
326 $ignoreRedirect = $target = false;
327
328 $dbr = wfGetDB( DB_SLAVE );
329 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
330
331 wfRunHooks( 'InitializeArticleMaybeRedirect',
332 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
333
334 // Follow redirects only for... redirects.
335 // If $target is set, then a hook wanted to redirect.
336 if( !$ignoreRedirect && ($target || $article->isRedirect()) ) {
337 // Is the target already set by an extension?
338 $target = $target ? $target : $article->followRedirect();
339 if( is_string( $target ) ) {
340 if( !$this->getVal( 'DisableHardRedirects' ) ) {
341 // we'll need to redirect
342 wfProfileOut( __METHOD__ );
343 return $target;
344 }
345 }
346 if( is_object($target) ) {
347 // Rewrite environment to redirected article
348 $rarticle = self::articleFromTitle( $target );
349 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
350 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
351 $rarticle->setRedirectedFrom( $title );
352 $article = $rarticle;
353 $title = $target;
354 $output->setTitle( $title );
355 }
356 }
357 } else {
358 $title = $article->getTitle();
359 }
360 }
361 wfProfileOut( __METHOD__ );
362 return $article;
363 }
364
365 /**
366 * Cleaning up request by doing:
367 ** deferred updates, DB transaction, and the output
368 *
369 * @param $deferredUpdates array of updates to do
370 * @param $output OutputPage
371 */
372 function finalCleanup( &$deferredUpdates, &$output ) {
373 wfProfileIn( __METHOD__ );
374 // Now commit any transactions, so that unreported errors after
375 // output() don't roll back the whole DB transaction
376 $factory = wfGetLBFactory();
377 $factory->commitMasterChanges();
378 // Output everything!
379 $output->output();
380 // Do any deferred jobs
381 $this->doUpdates( $deferredUpdates );
382 $this->doJobs();
383 wfProfileOut( __METHOD__ );
384 }
385
386 /**
387 * Deferred updates aren't really deferred anymore. It's important to report
388 * errors to the user, and that means doing this before OutputPage::output().
389 * Note that for page saves, the client will wait until the script exits
390 * anyway before following the redirect.
391 *
392 * @param $updates array of objects that hold an update to do
393 */
394 function doUpdates( &$updates ) {
395 wfProfileIn( __METHOD__ );
396 /* No need to get master connections in case of empty updates array */
397 if (!$updates) {
398 wfProfileOut( __METHOD__ );
399 return;
400 }
401
402 $dbw = wfGetDB( DB_MASTER );
403 foreach( $updates as $up ) {
404 $up->doUpdate();
405
406 // Commit after every update to prevent lock contention
407 if( $dbw->trxLevel() ) {
408 $dbw->commit();
409 }
410 }
411 wfProfileOut( __METHOD__ );
412 }
413
414 /**
415 * Do a job from the job queue
416 */
417 function doJobs() {
418 $jobRunRate = $this->getVal( 'JobRunRate' );
419
420 if( $jobRunRate <= 0 || wfReadOnly() ) {
421 return;
422 }
423 if( $jobRunRate < 1 ) {
424 $max = mt_getrandmax();
425 if( mt_rand( 0, $max ) > $max * $jobRunRate ) {
426 return;
427 }
428 $n = 1;
429 } else {
430 $n = intval( $jobRunRate );
431 }
432
433 while ( $n-- && false != ( $job = Job::pop() ) ) {
434 $output = $job->toString() . "\n";
435 $t = -wfTime();
436 $success = $job->run();
437 $t += wfTime();
438 $t = round( $t*1000 );
439 if( !$success ) {
440 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
441 } else {
442 $output .= "Success, Time: $t ms\n";
443 }
444 wfDebugLog( 'jobqueue', $output );
445 }
446 }
447
448 /**
449 * Ends this task peacefully
450 */
451 function restInPeace() {
452 MessageCache::logMessages();
453 wfLogProfilingData();
454 // Commit and close up!
455 $factory = wfGetLBFactory();
456 $factory->commitMasterChanges();
457 $factory->shutdown();
458 wfDebug( "Request ended normally\n" );
459 }
460
461 /**
462 * Perform one of the "standard" actions
463 *
464 * @param $output OutputPage
465 * @param $article Article
466 * @param $title Title
467 * @param $user User
468 * @param $request WebRequest
469 */
470 function performAction( &$output, &$article, &$title, &$user, &$request ) {
471 wfProfileIn( __METHOD__ );
472
473 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
474 wfProfileOut( __METHOD__ );
475 return;
476 }
477
478 $action = $this->getVal( 'Action' );
479 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
480 /* No such action; this will switch to the default case */
481 $action = 'nosuchaction';
482 }
483
484 // Workaround for bug #20966: inability of IE to provide an action dependent
485 // on which submit button is clicked.
486 if ( $action === 'historysubmit' ) {
487 if ( $request->getBool( 'revisiondelete' ) ) {
488 $action = 'revisiondelete';
489 } elseif ( $request->getBool( 'revisionmove' ) ) {
490 $action = 'revisionmove';
491 } else {
492 $action = 'view';
493 }
494 }
495
496 switch( $action ) {
497 case 'view':
498 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
499 $article->view();
500 break;
501 case 'raw': // includes JS/CSS
502 wfProfileIn( __METHOD__.'-raw' );
503 $raw = new RawPage( $article );
504 $raw->view();
505 wfProfileOut( __METHOD__.'-raw' );
506 break;
507 case 'watch':
508 case 'unwatch':
509 case 'delete':
510 case 'revert':
511 case 'rollback':
512 case 'protect':
513 case 'unprotect':
514 case 'info':
515 case 'markpatrolled':
516 case 'render':
517 case 'deletetrackback':
518 case 'purge':
519 $article->$action();
520 break;
521 case 'print':
522 $article->view();
523 break;
524 case 'dublincore':
525 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
526 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
527 } else {
528 $rdf = new DublinCoreRdf( $article );
529 $rdf->show();
530 }
531 break;
532 case 'creativecommons':
533 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
534 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
535 } else {
536 $rdf = new CreativeCommonsRdf( $article );
537 $rdf->show();
538 }
539 break;
540 case 'credits':
541 Credits::showPage( $article );
542 break;
543 case 'submit':
544 if( session_id() == '' ) {
545 /* Send a cookie so anons get talk message notifications */
546 wfSetupSession();
547 }
548 /* Continue... */
549 case 'edit':
550 case 'editredlink':
551 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
552 $internal = $request->getVal( 'internaledit' );
553 $external = $request->getVal( 'externaledit' );
554 $section = $request->getVal( 'section' );
555 $oldid = $request->getVal( 'oldid' );
556 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
557 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
558 $editor = new EditPage( $article );
559 $editor->submit();
560 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
561 $mode = $request->getVal( 'mode' );
562 $extedit = new ExternalEdit( $article, $mode );
563 $extedit->edit();
564 }
565 }
566 break;
567 case 'history':
568 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
569 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
570 }
571 $history = new HistoryPage( $article );
572 $history->history();
573 break;
574 case 'revisiondelete':
575 // For show/hide submission from history page
576 $special = SpecialPage::getPage( 'Revisiondelete' );
577 $special->execute( '' );
578 break;
579 case 'revisionmove':
580 // For revision move submission from history page
581 $special = SpecialPage::getPage( 'RevisionMove' );
582 $special->execute( '' );
583 break;
584 default:
585 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
586 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
587 }
588 }
589 wfProfileOut( __METHOD__ );
590
591 }
592
593 }