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