Add returntoquery= parameter to Special:Userlogin which adds a query string to the...
[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, $output, $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 global $wgDeferredUpdateList;
156 $output->loginToUse();
157 $this->finalCleanup( $wgDeferredUpdateList, $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 * FIXME: why is this crap called "initialize" when it performs everything?
172 *
173 * @param $title Title
174 * @param $output OutputPage
175 * @param $request WebRequest
176 * @return bool true if the request is already executed
177 */
178 function initializeSpecialCases( &$title, &$output, $request ) {
179 wfProfileIn( __METHOD__ );
180
181 $action = $this->getVal( 'Action' );
182 if( is_null($title) || $title->getDBkey() == '' ) {
183 $title = SpecialPage::getTitleFor( 'Badtitle' );
184 # Die now before we mess up $wgArticle and the skin stops working
185 throw new ErrorPageError( 'badtitle', 'badtitletext' );
186 } else if( $title->getInterwiki() != '' ) {
187 if( $rdfrom = $request->getVal( 'rdfrom' ) ) {
188 $url = $title->getFullURL( 'rdfrom=' . urlencode( $rdfrom ) );
189 } else {
190 $url = $title->getFullURL();
191 }
192 /* Check for a redirect loop */
193 if( !preg_match( '/^' . preg_quote( $this->getVal('Server'), '/' ) . '/', $url ) && $title->isLocal() ) {
194 $output->redirect( $url );
195 } else {
196 $title = SpecialPage::getTitleFor( 'Badtitle' );
197 throw new ErrorPageError( 'badtitle', 'badtitletext' );
198 }
199 } else if( $action == 'view' && !$request->wasPosted() &&
200 ( !isset($this->GET['title']) || $title->getPrefixedDBKey() != $this->GET['title'] ) &&
201 !count( array_diff( array_keys( $this->GET ), array( 'action', 'title' ) ) ) )
202 {
203 $targetUrl = $title->getFullURL();
204 // Redirect to canonical url, make it a 301 to allow caching
205 if( $targetUrl == $request->getFullRequestURL() ) {
206 $message = "Redirect loop detected!\n\n" .
207 "This means the wiki got confused about what page was " .
208 "requested; this sometimes happens when moving a wiki " .
209 "to a new server or changing the server configuration.\n\n";
210
211 if( $this->getVal( 'UsePathInfo' ) ) {
212 $message .= "The wiki is trying to interpret the page " .
213 "title from the URL path portion (PATH_INFO), which " .
214 "sometimes fails depending on the web server. Try " .
215 "setting \"\$wgUsePathInfo = false;\" in your " .
216 "LocalSettings.php, or check that \$wgArticlePath " .
217 "is correct.";
218 } else {
219 $message .= "Your web server was detected as possibly not " .
220 "supporting URL path components (PATH_INFO) correctly; " .
221 "check your LocalSettings.php for a customized " .
222 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
223 "to true.";
224 }
225 wfHttpError( 500, "Internal error", $message );
226 return false;
227 } else {
228 $output->setSquidMaxage( 1200 );
229 $output->redirect( $targetUrl, '301' );
230 }
231 } else if( NS_SPECIAL == $title->getNamespace() ) {
232 /* actions that need to be made when we have a special pages */
233 SpecialPage::executePath( $title );
234 } else {
235 /* No match to special cases */
236 wfProfileOut( __METHOD__ );
237 return false;
238 }
239 /* Did match a special case */
240 wfProfileOut( __METHOD__ );
241 return true;
242 }
243
244 /**
245 * Create an Article object of the appropriate class for the given page.
246 *
247 * @param $title Title
248 * @return Article object
249 */
250 static function articleFromTitle( &$title ) {
251 if( NS_MEDIA == $title->getNamespace() ) {
252 // FIXME: where should this go?
253 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
254 }
255
256 $article = null;
257 wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
258 if( $article ) {
259 return $article;
260 }
261
262 switch( $title->getNamespace() ) {
263 case NS_FILE:
264 return new ImagePage( $title );
265 case NS_CATEGORY:
266 return new CategoryPage( $title );
267 default:
268 return new Article( $title );
269 }
270 }
271
272 /**
273 * Initialize the object to be known as $wgArticle for "standard" actions
274 * Create an Article object for the page, following redirects if needed.
275 *
276 * @param $title Title ($wgTitle)
277 * @param $output OutputPage ($wgOut)
278 * @param $request WebRequest ($wgRequest)
279 * @return mixed an Article, or a string to redirect to another URL
280 */
281 function initializeArticle( &$title, &$output, $request ) {
282 wfProfileIn( __METHOD__ );
283
284 $action = $this->getVal( 'action', 'view' );
285 $article = self::articleFromTitle( $title );
286 # NS_MEDIAWIKI has no redirects.
287 # It is also used for CSS/JS, so performance matters here...
288 if( $title->getNamespace() == NS_MEDIAWIKI ) {
289 wfProfileOut( __METHOD__ );
290 return $article;
291 }
292 // Namespace might change when using redirects
293 // Check for redirects ...
294 $file = ($title->getNamespace() == NS_FILE) ? $article->getFile() : null;
295 if( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
296 && !$request->getVal( 'oldid' ) && // ... and are not old revisions
297 $request->getVal( 'redirect' ) != 'no' && // ... unless explicitly told not to
298 // ... and the article is not a non-redirect image page with associated file
299 !( is_object( $file ) && $file->exists() && !$file->getRedirected() ) )
300 {
301 # Give extensions a change to ignore/handle redirects as needed
302 $ignoreRedirect = $target = false;
303
304 $dbr = wfGetDB( DB_SLAVE );
305 $article->loadPageData( $article->pageDataFromTitle( $dbr, $title ) );
306
307 wfRunHooks( 'InitializeArticleMaybeRedirect',
308 array(&$title,&$request,&$ignoreRedirect,&$target,&$article) );
309
310 // Follow redirects only for... redirects
311 if( !$ignoreRedirect && $article->isRedirect() ) {
312 # Is the target already set by an extension?
313 $target = $target ? $target : $article->followRedirect();
314 if( is_string( $target ) ) {
315 if( !$this->getVal( 'DisableHardRedirects' ) ) {
316 // we'll need to redirect
317 return $target;
318 }
319 }
320 if( is_object($target) ) {
321 // Rewrite environment to redirected article
322 $rarticle = self::articleFromTitle( $target );
323 $rarticle->loadPageData( $rarticle->pageDataFromTitle( $dbr, $target ) );
324 if( $rarticle->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
325 $rarticle->setRedirectedFrom( $title );
326 $article = $rarticle;
327 $title = $target;
328 $output->setTitle( $title );
329 }
330 }
331 } else {
332 $title = $article->getTitle();
333 }
334 }
335 wfProfileOut( __METHOD__ );
336 return $article;
337 }
338
339 /**
340 * Cleaning up request by doing:
341 ** deferred updates, DB transaction, and the output
342 *
343 * @param $deferredUpdates array of updates to do
344 * @param $output OutputPage
345 */
346 function finalCleanup( &$deferredUpdates, &$output ) {
347 wfProfileIn( __METHOD__ );
348 # Now commit any transactions, so that unreported errors after
349 # output() don't roll back the whole DB transaction
350 $factory = wfGetLBFactory();
351 $factory->commitMasterChanges();
352 # Output everything!
353 $output->output();
354 # Do any deferred jobs
355 $this->doUpdates( $deferredUpdates );
356 $this->doJobs();
357 wfProfileOut( __METHOD__ );
358 }
359
360 /**
361 * Deferred updates aren't really deferred anymore. It's important to report
362 * errors to the user, and that means doing this before OutputPage::output().
363 * Note that for page saves, the client will wait until the script exits
364 * anyway before following the redirect.
365 *
366 * @param $updates array of objects that hold an update to do
367 */
368 function doUpdates( &$updates ) {
369 wfProfileIn( __METHOD__ );
370 /* No need to get master connections in case of empty updates array */
371 if (!$updates) {
372 wfProfileOut( __METHOD__ );
373 return;
374 }
375
376 $dbw = wfGetDB( DB_MASTER );
377 foreach( $updates as $up ) {
378 $up->doUpdate();
379
380 # Commit after every update to prevent lock contention
381 if( $dbw->trxLevel() ) {
382 $dbw->commit();
383 }
384 }
385 wfProfileOut( __METHOD__ );
386 }
387
388 /**
389 * Do a job from the job queue
390 */
391 function doJobs() {
392 $jobRunRate = $this->getVal( 'JobRunRate' );
393
394 if( $jobRunRate <= 0 || wfReadOnly() ) {
395 return;
396 }
397 if( $jobRunRate < 1 ) {
398 $max = mt_getrandmax();
399 if( mt_rand( 0, $max ) > $max * $jobRunRate ) {
400 return;
401 }
402 $n = 1;
403 } else {
404 $n = intval( $jobRunRate );
405 }
406
407 while ( $n-- && false != ( $job = Job::pop() ) ) {
408 $output = $job->toString() . "\n";
409 $t = -wfTime();
410 $success = $job->run();
411 $t += wfTime();
412 $t = round( $t*1000 );
413 if( !$success ) {
414 $output .= "Error: " . $job->getLastError() . ", Time: $t ms\n";
415 } else {
416 $output .= "Success, Time: $t ms\n";
417 }
418 wfDebugLog( 'jobqueue', $output );
419 }
420 }
421
422 /**
423 * Ends this task peacefully
424 */
425 function restInPeace() {
426 wfLogProfilingData();
427 # Commit and close up!
428 $factory = wfGetLBFactory();
429 $factory->commitMasterChanges();
430 $factory->shutdown();
431 wfDebug( "Request ended normally\n" );
432 }
433
434 /**
435 * Perform one of the "standard" actions
436 *
437 * @param $output OutputPage
438 * @param $article Article
439 * @param $title Title
440 * @param $user User
441 * @param $request WebRequest
442 */
443 function performAction( &$output, &$article, &$title, &$user, &$request ) {
444 wfProfileIn( __METHOD__ );
445
446 if( !wfRunHooks( 'MediaWikiPerformAction', array( $output, $article, $title, $user, $request, $this ) ) ) {
447 wfProfileOut( __METHOD__ );
448 return;
449 }
450
451 $action = $this->getVal( 'Action' );
452 if( in_array( $action, $this->getVal( 'DisabledActions', array() ) ) ) {
453 /* No such action; this will switch to the default case */
454 $action = 'nosuchaction';
455 }
456
457 switch( $action ) {
458 case 'view':
459 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
460 $article->view();
461 break;
462 case 'raw': // includes JS/CSS
463 wfProfileIn( __METHOD__.'-raw' );
464 $raw = new RawPage( $article );
465 $raw->view();
466 wfProfileOut( __METHOD__.'-raw' );
467 break;
468 case 'watch':
469 case 'unwatch':
470 case 'delete':
471 case 'revert':
472 case 'rollback':
473 case 'protect':
474 case 'unprotect':
475 case 'info':
476 case 'markpatrolled':
477 case 'render':
478 case 'deletetrackback':
479 case 'purge':
480 $article->$action();
481 break;
482 case 'print':
483 $article->view();
484 break;
485 case 'dublincore':
486 if( !$this->getVal( 'EnableDublinCoreRdf' ) ) {
487 wfHttpError( 403, 'Forbidden', wfMsg( 'nodublincore' ) );
488 } else {
489 $rdf = new DublinCoreRdf( $article );
490 $rdf->show();
491 }
492 break;
493 case 'creativecommons':
494 if( !$this->getVal( 'EnableCreativeCommonsRdf' ) ) {
495 wfHttpError( 403, 'Forbidden', wfMsg( 'nocreativecommons' ) );
496 } else {
497 $rdf = new CreativeCommonsRdf( $article );
498 $rdf->show();
499 }
500 break;
501 case 'credits':
502 Credits::showPage( $article );
503 break;
504 case 'submit':
505 if( session_id() == '' ) {
506 /* Send a cookie so anons get talk message notifications */
507 wfSetupSession();
508 }
509 /* Continue... */
510 case 'edit':
511 case 'editredlink':
512 if( wfRunHooks( 'CustomEditor', array( $article, $user ) ) ) {
513 $internal = $request->getVal( 'internaledit' );
514 $external = $request->getVal( 'externaledit' );
515 $section = $request->getVal( 'section' );
516 $oldid = $request->getVal( 'oldid' );
517 if( !$this->getVal( 'UseExternalEditor' ) || $action=='submit' || $internal ||
518 $section || $oldid || ( !$user->getOption( 'externaleditor' ) && !$external ) ) {
519 $editor = new EditPage( $article );
520 $editor->submit();
521 } elseif( $this->getVal( 'UseExternalEditor' ) && ( $external || $user->getOption( 'externaleditor' ) ) ) {
522 $mode = $request->getVal( 'mode' );
523 $extedit = new ExternalEdit( $article, $mode );
524 $extedit->edit();
525 }
526 }
527 break;
528 case 'history':
529 if( $request->getFullRequestURL() == $title->getInternalURL( 'action=history' ) ) {
530 $output->setSquidMaxage( $this->getVal( 'SquidMaxage' ) );
531 }
532 $history = new PageHistory( $article );
533 $history->history();
534 break;
535 default:
536 if( wfRunHooks( 'UnknownAction', array( $action, $article ) ) ) {
537 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
538 }
539 }
540 wfProfileOut( __METHOD__ );
541
542 }
543
544 }; /* End of class MediaWiki */