2014-07-03 18:26:09 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
class CORSHelper
|
|
|
|
{
|
2017-03-10 15:10:56 +01:00
|
|
|
public static function enableCrossOriginRequests(&$request, &$response)
|
2014-07-03 18:26:09 +02:00
|
|
|
{
|
2022-03-14 11:15:04 +01:00
|
|
|
// Chrome sends the Origin header for all requests, so we whitelist the webserver's hostname as well.
|
2014-07-03 18:26:09 +02:00
|
|
|
$origin = $request->getHeader('Origin');
|
2021-10-07 19:05:56 +02:00
|
|
|
$allowedOrigins = self::getAllowedOrigins($request);
|
2017-07-18 20:39:53 +02:00
|
|
|
|
2021-10-12 11:09:46 +02:00
|
|
|
if ((!(preg_match('/https?:\/\/localhost/', $origin) === 1)) && ($origin != '')
|
2021-10-11 16:10:47 +02:00
|
|
|
&& (!in_array($origin, $allowedOrigins))
|
2021-10-07 19:05:56 +02:00
|
|
|
) {
|
2022-03-14 11:15:04 +01:00
|
|
|
// Don't allow CORS from other domains to prevent XSS.
|
2021-10-07 19:05:56 +02:00
|
|
|
Logging::error("request origin '{$origin}' is not in allowed '" . implode(', ', $allowedOrigins) . "'!");
|
2021-10-11 16:10:47 +02:00
|
|
|
|
2014-07-03 18:26:09 +02:00
|
|
|
throw new Zend_Controller_Action_Exception('Forbidden', 403);
|
|
|
|
}
|
2022-03-14 11:15:04 +01:00
|
|
|
// Allow AJAX requests from configured websites. We use this to allow other pages to use LibreTimes API.
|
2017-03-10 15:10:56 +01:00
|
|
|
if ($origin) {
|
|
|
|
$response = $response->setHeader('Access-Control-Allow-Origin', $origin);
|
|
|
|
}
|
2014-07-03 18:26:09 +02:00
|
|
|
}
|
2014-11-21 01:33:11 +01:00
|
|
|
|
2017-07-18 20:39:53 +02:00
|
|
|
/**
|
2021-10-11 16:10:47 +02:00
|
|
|
* Get all allowed origins.
|
2017-07-18 20:39:53 +02:00
|
|
|
*
|
|
|
|
* @param Request $request request object
|
|
|
|
*/
|
|
|
|
public static function getAllowedOrigins($request)
|
2014-11-21 01:33:11 +01:00
|
|
|
{
|
2017-03-10 15:10:56 +01:00
|
|
|
$allowedCorsUrls = array_map(
|
2021-10-11 16:10:47 +02:00
|
|
|
function ($v) { return trim($v); },
|
2017-03-10 15:10:56 +01:00
|
|
|
explode(PHP_EOL, Application_Model_Preference::GetAllowedCorsUrls())
|
|
|
|
);
|
2017-07-18 20:39:53 +02:00
|
|
|
|
|
|
|
// always allow the configured server in (as reported by the server and not what is i baseUrl)
|
|
|
|
$scheme = $request->getServer('REQUEST_SCHEME');
|
|
|
|
$host = $request->getServer('SERVER_NAME');
|
|
|
|
$port = $request->getServer('SERVER_PORT');
|
|
|
|
|
|
|
|
$portString = '';
|
|
|
|
if (
|
2021-10-11 16:10:47 +02:00
|
|
|
$scheme == 'https' && $port != 443
|
|
|
|
|| $scheme == 'http' && $port != 80
|
2017-07-18 20:39:53 +02:00
|
|
|
) {
|
|
|
|
$portString = sprintf(':%s', $port);
|
|
|
|
}
|
|
|
|
$requestedUrl = sprintf(
|
|
|
|
'%s://%s%s',
|
|
|
|
$scheme,
|
|
|
|
$host,
|
|
|
|
$portString
|
|
|
|
);
|
2021-10-11 16:10:47 +02:00
|
|
|
|
|
|
|
return array_merge($allowedCorsUrls, [
|
|
|
|
$requestedUrl,
|
|
|
|
]);
|
2014-11-21 01:33:11 +01:00
|
|
|
}
|
2014-09-05 01:11:09 +02:00
|
|
|
}
|