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