public function validateApiAccessControl() { if (kIpAddressUtils::isInternalIp()) { return true; } if ($this->getEnforceHttpsApi() && infraRequestUtils::getProtocol() != infraRequestUtils::PROTOCOL_HTTPS) { KalturaLog::err('Action was accessed over HTTP while the partner is configured for HTTPS access only'); return false; } $accessControl = $this->getApiAccessControl(); if (is_null($accessControl)) { return true; } $context = new kEntryContextDataResult(); $scope = new accessControlScope(); $scope->setKs(kCurrentContext::$ks); $scope->setContexts(array(ContextType::PLAY)); $disableCache = $accessControl->applyContext($context, $scope); if ($disableCache) { kApiCache::disableCache(); } if (count($context->getMessages())) { header("X-Kaltura-API-Access-Control: " . implode(', ', $context->getMessages())); } if (count($context->getActions())) { $actions = $context->getActions(); foreach ($actions as $action) { /* @var $action kAccessControlAction */ if ($action->getType() == RuleActionType::BLOCK) { KalturaLog::err('Action was blocked by API access control'); return false; } } } return true; }
public function execute() { //entitlement should be disabled to serveFlavor action as we do not get ks on this action. KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); requestUtils::handleConditionalGet(); $flavorId = $this->getRequestParameter("flavorId"); $shouldProxy = $this->getRequestParameter("forceproxy", false); $fileName = $this->getRequestParameter("fileName"); $fileParam = $this->getRequestParameter("file"); $fileParam = basename($fileParam); $pathOnly = $this->getRequestParameter("pathOnly", false); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $flavorAsset = assetPeer::retrieveById($flavorId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entryId = $this->getRequestParameter("entryId"); if (!is_null($entryId) && $flavorAsset->getEntryId() != $entryId) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } if ($fileName) { header("Content-Disposition: attachment; filename=\"{$fileName}\""); header("Content-Type: application/force-download"); header("Content-Description: File Transfer"); } $clipTo = null; $entry = $flavorAsset->getentry(); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFlavor', $flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($entry, $flavorAsset); $version = $this->getRequestParameter("v"); if (!$version) { $version = $flavorAsset->getVersion(); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version); if ($pathOnly && kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR'])) { $path = null; list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, false, false); if ($file_sync) { $parent_file_sync = kFileSyncUtils::resolve($file_sync); $path = $parent_file_sync->getFullPath(); if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; } } $renderer = new kRendererString('{"sequences":[{"clips":[{"type":"source","path":"' . $path . '"}]}]}', 'application/json'); if ($path) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } if (kConf::hasParam('serve_flavor_allowed_partners') && !in_array($flavorAsset->getPartnerId(), kConf::get('serve_flavor_allowed_partners'))) { KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED); } if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } // always dump remote urls so they will be cached by the cdn transparently $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFileUtils::dumpUrl($remoteUrl); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $isFlv = false; if (!$shouldProxy) { $flvWrapper = new myFlvHandler($path); $isFlv = $flvWrapper->isFlv(); } $clipFrom = $this->getRequestParameter("clipFrom", 0); // milliseconds if (is_null($clipTo)) { $clipTo = $this->getRequestParameter("clipTo", self::NO_CLIP_TO); } // milliseconds if ($clipTo == 0) { $clipTo = self::NO_CLIP_TO; } if (!is_numeric($clipTo) || $clipTo < 0) { KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'clipTo must be a positive number'); } $seekFrom = $this->getRequestParameter("seekFrom", -1); if ($seekFrom <= 0) { $seekFrom = -1; } $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1); if ($seekFromBytes <= 0) { $seekFromBytes = -1; } if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; kFileUtils::dumpFile($path, null, null); KExternalErrors::dieGracefully(); } else { if (!$isFlv || $clipTo == self::NO_CLIP_TO && $seekFrom < 0 && $seekFromBytes < 0) { $limit_file_size = 0; if ($clipTo != self::NO_CLIP_TO) { if (strtolower($flavorAsset->getFileExt()) == 'mp4' && PermissionPeer::isValidForPartner(PermissionName::FEATURE_ACCURATE_SERVE_CLIPPING, $flavorAsset->getPartnerId())) { $contentPath = myContentStorage::getFSContentRootPath(); $tempClipName = $version . '_' . $clipTo . '.mp4'; $tempClipPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempclip", $flavorAsset->getIntId(), $flavorAsset->getId(), $tempClipName); if (!file_exists($tempClipPath)) { kFile::fullMkdir($tempClipPath); $clipToSec = round($clipTo / 1000, 3); $cmdLine = kConf::get("bin_path_ffmpeg") . " -i {$path} -vcodec copy -acodec copy -f mp4 -t {$clipToSec} -y {$tempClipPath} 2>&1"; KalturaLog::log("Executing {$cmdLine}"); $output = array(); $return_value = ""; exec($cmdLine, $output, $return_value); KalturaLog::log("ffmpeg returned {$return_value}, output:" . implode("\n", $output)); } if (file_exists($tempClipPath)) { KalturaLog::log("Dumping {$tempClipPath}"); kFileUtils::dumpFile($tempClipPath); } else { KalturaLog::err('Failed to clip the file using ffmpeg, falling back to rough clipping'); } } $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId()); if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) { $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration()); $limit_file_size = floor(@kFile::fileSize($path) * ($clipTo / $duration) * 1.2); } } $renderer = kFileUtils::getDumpFileRenderer($path, null, null, $limit_file_size); if (!$fileName) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } } $audioOnly = $this->getRequestParameter("audioOnly"); // milliseconds if ($audioOnly === '0') { // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) { $audioOnly = true; } $bytes = 0; if ($seekFrom !== -1 && $seekFrom !== 0) { list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly); list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly); $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte; } else { list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); } $metadataSize = $flvWrapper->getMetadataSize($audioOnly); $dataOffset = $metadataSize + myFlvHandler::getHeaderSize(); $totalLength = $dataOffset + $bytes; list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength); if ($totalLength < 1000) { // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache requestUtils::sendCdnHeaders("flv", $rangeLength, 0); } else { requestUtils::sendCdnHeaders("flv", $rangeLength); } // dont inject cuepoint into the stream $cuepointTime = 0; $cuepointPos = 0; try { Propel::close(); } catch (Exception $e) { $this->logMessage("serveFlavor: error closing db {$e}"); } header("Content-Type: video/x-flv"); $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos); KExternalErrors::dieGracefully(); }
function checkCache() { $baseDir = "/tmp/cache_v2"; $start_time = microtime(true); $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https" : "http"; $host = ""; if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { $host = $_SERVER['HTTP_X_FORWARDED_HOST']; } else { if (isset($_SERVER['HTTP_HOST'])) { $host = $_SERVER['HTTP_HOST']; } } $uri = $_SERVER["REQUEST_URI"]; if (function_exists('apc_fetch')) { $url = apc_fetch("redirect-" . $protocol . $uri); if ($url) { sendCachingHeaders(60, true, time()); header("X-Kaltura:cached-dispatcher-redirect"); header("Location:{$url}"); die; } $errorHeaders = apc_fetch("exterror-{$protocol}://{$host}{$uri}"); if ($errorHeaders !== false) { sendCachingHeaders(60, true, time()); foreach ($errorHeaders as $header) { header($header); } die; } } if (strpos($uri, "/playManifest") !== false) { require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kPlayManifestCacher.php"; $cache = kPlayManifestCacher::getInstance(); $cache->checkOrStart(); } else { if (strpos($uri, "/partnerservices2") !== false) { $params = $_GET + $_POST; unset($params['ks']); unset($params['kalsig']); $params['uri'] = $_SERVER['PATH_INFO']; $params['__protocol'] = $protocol; ksort($params); $keys = array_keys($params); $key = md5(implode("|", $params) . implode("|", $keys)); $cache_filename = "{$baseDir}/cache-{$key}"; if (file_exists($cache_filename)) { if (filemtime($cache_filename) + 600 < time()) { @unlink($cache_filename); @unlink($cache_filename . ".headers"); @unlink($cache_filename . ".log"); } else { $content_type = @file_get_contents("{$baseDir}/cache-{$key}.headers"); if ($content_type) { header("Content-Type: {$content_type}"); } $response = @file_get_contents("{$baseDir}/cache-{$key}"); if ($response) { header("Access-Control-Allow-Origin:*"); // avoid html5 xss issues if (strpos($uri, "/partnerservices2/executeplaylist") !== false) { $max_age = 60; sendCachingHeaders($max_age, true, time()); } else { sendCachingHeaders(0); } $processing_time = microtime(true) - $start_time; header("X-Kaltura:cached-dispatcher,{$key},{$processing_time}"); echo $response; die; } } } } else { if (strpos($uri, "/kwidget") !== false) { require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kCacheManager.php"; $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_PS2); if ($cache) { // check if we cached the patched swf with flashvars $uri = $protocol . $uri; $cachedResponse = $cache->get("kwidgetswf{$uri}"); if ($cachedResponse) { $max_age = 60 * 10; header("X-Kaltura:cached-dispatcher"); header("Content-Type: application/x-shockwave-flash"); sendCachingHeaders($max_age, true, time()); header("Content-Length: " . strlen($cachedResponse)); echo $cachedResponse; die; } $cachedResponse = $cache->get("kwidget{$uri}"); if ($cachedResponse) { header("X-Kaltura:cached-dispatcher"); header("Expires: Sun, 19 Nov 2000 08:52:00 GMT"); header("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); header("Pragma", "no-cache"); if (strpos($uri, "nowrapper") !== false) { header("Location:{$cachedResponse}"); die; } $referer = @$_SERVER['HTTP_REFERER']; $externalInterfaceDisabled = strstr($referer, "bebo.com") === false && strstr($referer, "myspace.com") === false && strstr($referer, "current.com") === false && strstr($referer, "myyearbook.com") === false && strstr($referer, "facebook.com") === false && strstr($referer, "friendster.com") === false ? "" : "&externalInterfaceDisabled=1"; $noncached_params = $externalInterfaceDisabled . "&referer=" . urlencode($referer); if (strpos($cachedResponse, "/swfparams/") > 0) { $cachedResponse = substr($cachedResponse, 0, -4) . urlencode($noncached_params) . ".swf"; } else { $cachedResponse .= $noncached_params; } header("Location:{$cachedResponse}"); die; } } } else { if (strpos($uri, "/thumbnail") !== false) { require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kCacheManager.php"; $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_PS2); if ($cache) { require_once dirname(__FILE__) . '/../apps/kaltura/lib/renderers/kRendererDumpFile.php'; $cachedResponse = $cache->get("thumb{$uri}"); if ($cachedResponse && is_array($cachedResponse)) { list($renderer, $invalidationKey, $cacheTime) = $cachedResponse; $keysStore = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_QUERY_CACHE_KEYS); if ($keysStore) { $modifiedTime = $keysStore->get($invalidationKey); if ($modifiedTime && $modifiedTime > $cacheTime) { return; // entry has changed (not necessarily the thumbnail) } } require_once dirname(__FILE__) . '/../apps/kaltura/lib/monitor/KalturaMonitorClient.php'; KalturaMonitorClient::initApiMonitor(true, 'extwidget.thumbnail', $renderer->partnerId); header("X-Kaltura:cached-dispatcher-thumb"); $renderer->output(); die; } } } else { if (strpos($uri, "/embedIframe/") !== false) { require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kCacheManager.php"; $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_PS2); if ($cache) { // check if we cached the patched swf with flashvars $cachedResponse = $cache->get("embedIframe{$uri}"); if ($cachedResponse) { header("X-Kaltura:cached-dispatcher"); sendCachingHeaders(0); header("Location:{$cachedResponse}"); die; } } } else { if (strpos($uri, "/serveFlavor/") !== false && function_exists('apc_fetch') && $_SERVER["REQUEST_METHOD"] == "GET") { require_once dirname(__FILE__) . '/../apps/kaltura/lib/renderers/kRendererDumpFile.php'; require_once dirname(__FILE__) . '/../apps/kaltura/lib/renderers/kRendererString.php'; require_once dirname(__FILE__) . '/../apps/kaltura/lib/monitor/KalturaMonitorClient.php'; require_once dirname(__FILE__) . '/../apps/kaltura/lib/request/kIpAddressUtils.php'; $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST']; $cacheKey = 'dumpFile-' . kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR']) . '-' . $host . $uri; $renderer = apc_fetch($cacheKey); if ($renderer) { KalturaMonitorClient::initApiMonitor(true, 'extwidget.serveFlavor', $renderer->partnerId); header("X-Kaltura:cached-dispatcher"); $renderer->output(); die; } } } } } } } }
protected function isAnonymous($ks) { if (kIpAddressUtils::isInternalIp()) { return false; } if (!$ks || !$ks->isAdmin() && ($ks->user === "0" || $ks->user === null)) { return true; } if (kConf::hasParam('cache_anonymous_users')) { $anonymousUsers = kConf::get('cache_anonymous_users'); foreach ($anonymousUsers as $userName => $partnerIds) { if ($ks->user == $userName && in_array($ks->partner_id, explode(',', $partnerIds))) { return true; } } } return false; }
/** * Init permission items map from DB for the given role * @param UserRole $dbRole */ private static function getPermissionsFromDb($dbRole) { $map = self::initEmptyMap(); // get all permission object names from role record if ($dbRole) { $tmpPermissionNames = $dbRole->getPermissionNames(true); $tmpPermissionNames = array_map('trim', explode(',', $tmpPermissionNames)); } else { $tmpPermissionNames = array(); } // add always allowed permissions if (self::$operatingPartner) { $alwaysAllowed = self::$operatingPartner->getAlwaysAllowedPermissionNames(); $alwaysAllowed = array_map('trim', explode(',', $alwaysAllowed)); } else { $alwaysAllowed = array(PermissionName::ALWAYS_ALLOWED_ACTIONS); } $tmpPermissionNames = array_merge($tmpPermissionNames, $alwaysAllowed); // if the request sent from the internal server set additional permission allowing access without KS // from internal servers if (kIpAddressUtils::isInternalIp()) { KalturaLog::debug('IP in range, adding ALWAYS_ALLOWED_FROM_INTERNAL_IP_ACTIONS permission'); $alwaysAllowedInternal = array(PermissionName::ALWAYS_ALLOWED_FROM_INTERNAL_IP_ACTIONS); $tmpPermissionNames = array_merge($tmpPermissionNames, $alwaysAllowedInternal); } $permissionNames = array(); foreach ($tmpPermissionNames as $name) { $permissionNames[$name] = $name; } $map[self::PERMISSION_NAMES_ARRAY] = $permissionNames; // get mapping of permissions to permission items $c = new Criteria(); $c->addAnd(PermissionPeer::NAME, $permissionNames, Criteria::IN); $c->addAnd(PermissionPeer::PARTNER_ID, array(strval(PartnerPeer::GLOBAL_PARTNER), strval(self::$operatingPartnerId)), Criteria::IN); $c->addAnd(PermissionItemPeer::PARTNER_ID, array(strval(PartnerPeer::GLOBAL_PARTNER), strval(self::$operatingPartnerId)), Criteria::IN); $lookups = PermissionToPermissionItemPeer::doSelectJoinAll($c); foreach ($lookups as $lookup) { $item = $lookup->getPermissionItem(); $permission = $lookup->getPermission(); if (!$item) { KalturaLog::err('PermissionToPermissionItem id [' . $lookup->getId() . '] is defined with PermissionItem id [' . $lookup->getPermissionItemId() . '] which does not exists!'); continue; } if (!$permission) { KalturaLog::err('PermissionToPermissionItem id [' . $lookup->getId() . '] is defined with Permission name [' . $lookup->getPermissionName() . '] which does not exists!'); continue; } // organize permission items in local arrays $type = $item->getType(); if ($type == PermissionItemType::API_ACTION_ITEM) { self::addApiAction($map, $item); } else { if ($type == PermissionItemType::API_PARAMETER_ITEM) { self::addApiParameter($map, $item); } } } // set partner group permission $c = new Criteria(); $c->addAnd(PermissionPeer::PARTNER_ID, self::$operatingPartnerId, Criteria::EQUAL); $c->addAnd(PermissionPeer::TYPE, PermissionType::PARTNER_GROUP, Criteria::EQUAL); $partnerGroupPermissions = PermissionPeer::doSelect($c); foreach ($partnerGroupPermissions as $pgPerm) { self::addPartnerGroupAction($map, $pgPerm); } return $map; }