/** * Start an impersonated session with Kaltura's server. * The result KS is the session key that you should pass to all services that requires a ticket. * * @action impersonate * @param string $secret Remember to provide the correct secret according to the sessionType you want * @param int $impersonatedPartnerId * @param string $userId * @param KalturaSessionType $type Regular session or Admin session * @param int $partnerId * @param int $expiry KS expiry time in seconds * @param string $privileges * @return string * * @throws APIErrors::START_SESSION_ERROR */ function impersonateAction($secret, $impersonatedPartnerId, $userId = "", $type = 0, $partnerId = null, $expiry = 86400, $privileges = null) { KalturaResponseCacher::disableCache(); // verify that partnerId exists and is in correspondence with given secret $result = myPartnerUtils::isValidSecret($partnerId, $secret, "", $expiry, $type); if ($result !== true) { throw new KalturaAPIException(APIErrors::START_SESSION_ERROR, $partnerId); } // verify partner is allowed to start session for another partner if (!myPartnerUtils::allowPartnerAccessPartner($partnerId, $this->partnerGroup(), $impersonatedPartnerId)) { throw new KalturaAPIException(APIErrors::START_SESSION_ERROR, $partnerId); } // get impersonated partner $impersonatedPartner = PartnerPeer::retrieveByPK($impersonatedPartnerId); if (!$impersonatedPartner) { // impersonated partner could not be fetched from the DB throw new KalturaAPIException(APIErrors::START_SESSION_ERROR, $partnerId); } // set the correct secret according to required session type if ($type == KalturaSessionType::ADMIN) { $impersonatedSecret = $impersonatedPartner->getAdminSecret(); } else { $impersonatedSecret = $impersonatedPartner->getSecret(); } // make sure the secret fits the one in the partner's table $ks = ""; $result = kSessionUtils::startKSession($impersonatedPartner->getId(), $impersonatedSecret, $userId, $ks, $expiry, $type, "", $privileges, $partnerId); if ($result >= 0) { return $ks; } else { throw new KalturaAPIException(APIErrors::START_SESSION_ERROR, $partnerId); } }
/** * Get license for encrypted content playback * * @action getLicense * @param string $flavorAssetId * @param string $referrer 64base encoded * @return string $response * */ public function getLicenseAction($flavorAssetId, $referrer = null) { KalturaResponseCacher::disableCache(); KalturaLog::debug('get license for flavor asset: ' . $flavorAssetId); try { $requestParams = requestUtils::getRequestParams(); if (!array_key_exists(WidevineLicenseProxyUtils::ASSETID, $requestParams)) { KalturaLog::err('assetid is missing on the request'); return WidevineLicenseProxyUtils::createErrorResponse(KalturaWidevineErrorCodes::WIDEVINE_ASSET_ID_CANNOT_BE_NULL, 0); } $wvAssetId = $requestParams[WidevineLicenseProxyUtils::ASSETID]; $this->validateLicenseRequest($flavorAssetId, $wvAssetId, $referrer); $privileges = null; $isAdmin = false; if (kCurrentContext::$ks_object) { $privileges = kCurrentContext::$ks_object->getPrivileges(); $isAdmin = kCurrentContext::$ks_object->isAdmin(); } $response = WidevineLicenseProxyUtils::sendLicenseRequest($requestParams, $privileges, $isAdmin); } catch (KalturaWidevineLicenseProxyException $e) { KalturaLog::err($e); $response = WidevineLicenseProxyUtils::createErrorResponse($e->getWvErrorCode(), $wvAssetId); } catch (Exception $e) { KalturaLog::err($e); $response = WidevineLicenseProxyUtils::createErrorResponse(KalturaWidevineErrorCodes::GENERAL_ERROR, $wvAssetId); } WidevineLicenseProxyUtils::printLicenseResponseStatus($response); return $response; }
/** * * @action getUploadedFileTokenByFileName * @param string $fileName * @return KalturaUploadResponse */ function getUploadedFileTokenByFileNameAction($fileName) { KalturaResponseCacher::disableConditionalCache(); $res = new KalturaUploadResponse(); $ksUnique = md5($this->getKs()->toSecureString()); $uniqueId = md5($fileName); $ext = pathinfo($fileName, PATHINFO_EXTENSION); $token = $ksUnique . "_" . $uniqueId . "." . $ext; $entryFullPath = myUploadUtils::getUploadPath($token, "", null, strtolower($ext)); // filesync ok if (!file_exists($entryFullPath)) { throw new KalturaAPIException(KalturaErrors::UPLOADED_FILE_NOT_FOUND_BY_TOKEN); } $res->uploadTokenId = $token; $res->fileSize = kFile::fileSize($entryFullPath); return $res; }
function setCacheExpiry($entriesCount, $feedId) { $expiryArr = kConf::hasMap("v3cache_getfeed_expiry") ? kConf::getMap("v3cache_getfeed_expiry") : array(); foreach ($expiryArr as $item) { if ($item["key"] == "partnerId" && $item["value"] == kCurrentContext::$partner_id || $item["key"] == "feedId" && $item["value"] == $feedId) { KalturaResponseCacher::setExpiry($item["expiry"]); return; } } $expiry = kConf::get("v3cache_getfeed_default_cache_time_frame", 'local', 86400); if (kConf::hasParam("v3cache_getfeed_short_limits_array")) { $shortLimits = kConf::get("v3cache_getfeed_short_limits_array"); } else { $shortLimits = array(50 => 900, 100 => 1800, 200 => 3600, 400 => 7200); } foreach ($shortLimits as $numOfEntries => $cacheTimeFrame) { if ($entriesCount <= $numOfEntries) { $expiry = min($expiry, $cacheTimeFrame); } } KalturaResponseCacher::setExpiry($expiry); }
public function execute($input_parameters = null) { if (class_exists('KalturaResponseCacher')) { KalturaResponseCacher::disableConditionalCache(); } $search = array(); $replace = array(); if (is_null($input_parameters)) { $search = array_reverse(array_keys($this->values)); $replace = array_reverse($this->values); } else { $i = 1; foreach ($input_parameters as $value) { $search[] = ':p' . $i++; if (is_null($value)) { $replace[] = "NULL"; } else { $replace[] = "'{$value}'"; } } $search = array_reverse($search); $replace = array_reverse($replace); } $sql = str_replace($search, $replace, $this->queryString); KalturaLog::debug($sql); $sqlStart = microtime(true); if (self::$dryRun) { KalturaLog::debug("Sql dry run - " . (microtime(true) - $sqlStart) . " seconds"); } else { try { parent::execute($input_parameters); } catch (PropelException $pex) { KalturaLog::alert($pex->getMessage()); throw new PropelException("Database error"); } KalturaLog::debug("Sql took - " . (microtime(true) - $sqlStart) . " seconds"); } }
/** * * @action getFaspUrl * @param string $flavorAssetId * @throws KalturaAPIException * @return string */ function getFaspUrlAction($flavorAssetId) { KalturaResponseCacher::disableCache(); $assetDb = assetPeer::retrieveById($flavorAssetId); if (!$assetDb || !$assetDb instanceof flavorAsset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $flavorAssetId); } if (!$assetDb->isLocalReadyStatus()) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_IS_NOT_READY); } $syncKey = $assetDb->getSyncKey(flavorAsset::FILE_SYNC_ASSET_SUB_TYPE_ASSET); /* @var $fileSync FileSync */ list($fileSync, $isFileSyncLocal) = kFileSyncUtils::getReadyFileSyncForKey($syncKey); $filePath = $fileSync->getFilePath(); $transferUser = $this->getFromAsperaConfig('transfer_user'); $transferHost = $this->getFromAsperaConfig('transfer_host'); $asperaNodeApi = new AsperaNodeApi($this->getFromAsperaConfig('node_api_user'), $this->getFromAsperaConfig('node_api_password'), $this->getFromAsperaConfig('node_api_host'), $this->getFromAsperaConfig('node_api_port')); $options = array('transfer_requests' => array('transfer_request' => array('remote_host' => $transferHost))); $tokenResponse = $asperaNodeApi->getToken($filePath, $options); $token = $tokenResponse->transfer_spec->token; $urlParams = array('auth' => 'no', 'token' => $token); return 'fasp://' . $transferUser . '@' . $transferHost . $filePath . '?' . http_build_query($urlParams, '', '&'); }
public function handleMultiRequest() { $listOfRequests = array(); $results = array(); $found = true; $i = 1; while ($found) { $currentService = isset($this->params[$i . ":service"]) ? $this->params[$i . ":service"] : null; $currentAction = isset($this->params[$i . ":action"]) ? $this->params[$i . ":action"] : null; $found = $currentAction && $currentService; if ($found) { $listOfRequests[$i]["service"] = $currentService; $listOfRequests[$i]["action"] = $currentAction; // find all the parameters for this request foreach ($this->params as $key => $val) { // the key "1:myparam" mean that we should input value of this key to request "1", for param "myparam" $keyArray = explode(":", $key); if ($keyArray[0] == $i) { array_shift($keyArray); // remove the request number $requestKey = implode(":", $keyArray); /* remarked by Dor - 13/10/2010 * There is no need to remove service and action from the params in case of multirequest * while they are needed in KalturaResponseCacher if (in_array($requestKey, array("service", "action"))) // don't add service name and action name to the params continue; */ $listOfRequests[$i]["params"][$requestKey] = $val; // store the param } } // clientTag param might be used in KalturaResponseCacher if (isset($this->params['clientTag']) && !isset($listOfRequests[$i]["params"]['clientTag'])) { $listOfRequests[$i]["params"]['clientTag'] = $this->params['clientTag']; } // if ks is not set for a specific request, copy the ks from the top params $currentKs = isset($listOfRequests[$i]["params"]["ks"]) ? $listOfRequests[$i]["params"]["ks"] : null; if (!$currentKs) { $mainKs = isset($this->params["ks"]) ? $this->params["ks"] : null; if ($mainKs) { $listOfRequests[$i]["params"]["ks"] = $mainKs; } } $currentPartner = isset($listOfRequests[$i]["params"]["partnerId"]) ? $listOfRequests[$i]["params"]["partnerId"] : null; if (!$currentPartner) { $mainPartner = isset($this->params["partnerId"]) ? $this->params["partnerId"] : null; if ($mainPartner) { $listOfRequests[$i]["params"]["partnerId"] = $mainPartner; } } $i++; } else { // will break the loop } } $i = 1; foreach ($listOfRequests as $currentRequest) { $currentService = $currentRequest["service"]; $currentAction = $currentRequest["action"]; $currentParams = $currentRequest["params"]; // check if we need to replace params with prev results foreach ($currentParams as $key => &$val) { $matches = array(); // keywords: multirequest, result, depend, pass // figuring out if requested params should be extracted from previous result // example: if you want to use KalturaPlaylist->playlistContent result from the first request // in your second request, the second request will contain the following value: // {1:result:playlistContent} if (preg_match('/\\{([0-9]*)\\:result\\:?(.*)?\\}/', $val, $matches)) { $resultIndex = $matches[1]; $resultKey = $matches[2]; if (count($results) >= $resultIndex) { if (strlen(trim($resultKey)) > 0) { $resultPathArray = explode(":", $resultKey); } else { $resultPathArray = array(); } $val = $this->getValueFromObject($results[$resultIndex], $resultPathArray); } } } try { // cached parameters should be different when the request is part of a multirequest // as part of multirequest - the cached data is a serialized php object // when not part of multirequest - the cached data is the actual response $currentParams['multirequest'] = true; unset($currentParams['format']); $cache = new KalturaResponseCacher($currentParams); if (!isset($currentParams['ks']) && kCurrentContext::$ks) { $cache->setKS(kCurrentContext::$ks); } $cachedResult = $cache->checkCache('X-Kaltura-Part-Of-MultiRequest'); if ($cachedResult) { $currentResult = unserialize($cachedResult); } else { $currentResult = $this->dispatcher->dispatch($currentService, $currentAction, $currentParams); // store serialized resposne in cache $cache->storeCache(serialize($currentResult)); } } catch (Exception $ex) { $currentResult = $this->getExceptionObject($ex); KalturaResponseCacher::disableCache(); } $results[$i] = $currentResult; $i++; } return $results; }
public function shouldConsumeSavedEvent(BaseObject $object) { return KalturaResponseCacher::isCacheEnabled(); }
/** * This action delivers entry-related data, based on the user's context: access control, restriction, playback format and storage information. * @action getContextData * @param string $entryId * @param KalturaEntryContextDataParams $contextDataParams * @return KalturaEntryContextDataResult */ public function getContextData($entryId, KalturaEntryContextDataParams $contextDataParams) { $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } $asset = null; if ($contextDataParams->flavorAssetId) { $asset = assetPeer::retrieveById($contextDataParams->flavorAssetId); if (!$asset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $contextDataParams->flavorAssetId); } } $contextDataHelper = new kContextDataHelper($dbEntry, $this->getPartner(), $asset); if ($dbEntry->getAccessControl() && $dbEntry->getAccessControl()->hasRules()) { $accessControlScope = $dbEntry->getAccessControl()->getScope(); } else { $accessControlScope = new accessControlScope(); } $contextDataParams->toObject($accessControlScope); $contextDataHelper->buildContextDataResult($accessControlScope, $contextDataParams->flavorTags, $contextDataParams->streamerType, $contextDataParams->mediaProtocol); if ($contextDataHelper->getDisableCache()) { KalturaResponseCacher::disableCache(); } $result = new KalturaEntryContextDataResult(); $result->fromObject($contextDataHelper->getContextDataResult()); $result->flavorAssets = KalturaFlavorAssetArray::fromDbArray($contextDataHelper->getAllowedFlavorAssets()); $result->streamerType = $contextDataHelper->getStreamerType(); $result->mediaProtocol = $contextDataHelper->getMediaProtocol(); $result->storageProfilesXML = $contextDataHelper->getStorageProfilesXML(); $result->isAdmin = $contextDataHelper->getIsAdmin(); $parentEntryId = $dbEntry->getParentEntryId(); if ($parentEntryId) { $dbEntry = $dbEntry->getParentEntry(); if (!$dbEntry) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $parentEntryId); } } $result->isScheduledNow = $dbEntry->isScheduledNow($contextDataParams->time); $result->pluginData = new KalturaPluginDataArray(); $pluginInstances = KalturaPluginManager::getPluginInstances('IKalturaEntryContextDataContributor'); foreach ($pluginInstances as $pluginInstance) { $pluginInstance->contributeToEntryContextDataResult($entryId, $contextDataParams, $result); } return $result; }
/** * Start an impersonated session with Kaltura's server. * The result KS info contains the session key that you should pass to all services that requires a ticket. * Type, expiry and privileges won't be changed if they're not set * * @action impersonateByKs * @param string $session The old KS of the impersonated partner * @param KalturaSessionType $type Type of the new KS * @param int $expiry Expiry time in seconds of the new KS * @param string $privileges Privileges of the new KS * @return KalturaSessionInfo * * @throws APIErrors::START_SESSION_ERROR */ function impersonateByKsAction($session, $type = null, $expiry = null, $privileges = null) { KalturaResponseCacher::disableCache(); $oldKS = null; try { $oldKS = ks::fromSecureString($session); } catch (Exception $e) { KalturaLog::err($e->getMessage()); throw new KalturaAPIException(APIErrors::START_SESSION_ERROR, $this->getPartnerId()); } $impersonatedPartnerId = $oldKS->partner_id; $impersonatedUserId = $oldKS->user; $impersonatedType = $oldKS->type; $impersonatedExpiry = $oldKS->valid_until - time(); $impersonatedPrivileges = $oldKS->privileges; if (!is_null($type)) { $impersonatedType = $type; } if (!is_null($expiry)) { $impersonatedExpiry = $expiry; } if ($privileges) { $impersonatedPrivileges = $privileges; } // verify partner is allowed to start session for another partner $impersonatedPartner = null; if (!myPartnerUtils::allowPartnerAccessPartner($this->getPartnerId(), $this->partnerGroup(), $impersonatedPartnerId)) { $c = PartnerPeer::getDefaultCriteria(); $c->addAnd(PartnerPeer::ID, $impersonatedPartnerId); $impersonatedPartner = PartnerPeer::doSelectOne($c); } else { // get impersonated partner $impersonatedPartner = PartnerPeer::retrieveByPK($impersonatedPartnerId); } if (!$impersonatedPartner) { KalturaLog::err("Impersonated partner [{$impersonatedPartnerId} ]could not be fetched from the DB"); throw new KalturaAPIException(APIErrors::START_SESSION_ERROR, $this->getPartnerId()); } // set the correct secret according to required session type if ($impersonatedType == KalturaSessionType::ADMIN) { $impersonatedSecret = $impersonatedPartner->getAdminSecret(); } else { $impersonatedSecret = $impersonatedPartner->getSecret(); } $sessionInfo = new KalturaSessionInfo(); $result = kSessionUtils::startKSession($impersonatedPartnerId, $impersonatedSecret, $impersonatedUserId, $sessionInfo->ks, $impersonatedExpiry, $impersonatedType, '', $impersonatedPrivileges, $this->getPartnerId()); if ($result < 0) { KalturaLog::err("Failed starting a session with result [{$result}]"); throw new KalturaAPIException(APIErrors::START_SESSION_ERROR, $this->getPartnerId()); } $sessionInfo->partnerId = $impersonatedPartnerId; $sessionInfo->userId = $impersonatedUserId; $sessionInfo->expiry = $impersonatedExpiry; $sessionInfo->sessionType = $impersonatedType; $sessionInfo->privileges = $impersonatedPrivileges; return $sessionInfo; }
/** * Serves the file content * * @action serveByFlavorParamsId * @serverOnly * @param string $entryId Document entry id * @param string $flavorParamsId Flavor params id * @param bool $forceProxy force to get the content without redirect * * @throws KalturaErrors::ENTRY_ID_NOT_FOUND * @throws KalturaErrors::FLAVOR_ASSET_IS_NOT_READY * @throws KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND */ public function serveByFlavorParamsIdAction($entryId, $flavorParamsId = null, $forceProxy = false) { KalturaResponseCacher::disableCache(); entryPeer::setDefaultCriteriaFilter(); $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry || $dbEntry->getType() != entryType::DOCUMENT) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } $ksObj = $this->getKs(); $ks = $ksObj ? $ksObj->getOriginalString() : null; $securyEntryHelper = new KSecureEntryHelper($dbEntry, $ks, null); $securyEntryHelper->validateForDownload(); $flavorAsset = null; assetPeer::resetInstanceCriteriaFilter(); if ($flavorParamsId) { $flavorAsset = assetPeer::retrieveByEntryIdAndParams($entryId, $flavorParamsId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_IS_NOT_READY, $flavorParamsId); } } else { $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $flavorParamsId); } } $fileName = $dbEntry->getName() . '.' . $flavorAsset->getFileExt(); return $this->serveFlavorAsset($flavorAsset, $fileName, $forceProxy); }
/** * Delivering the status of a live stream (on-air/offline) if it is possible * * @action isLive * @param string $id ID of the live stream * @param KalturaPlaybackProtocol $protocol protocol of the stream to test. * @return bool * * @throws KalturaErrors::LIVE_STREAM_STATUS_CANNOT_BE_DETERMINED * @throws KalturaErrors::INVALID_ENTRY_ID */ public function isLiveAction($id, $protocol) { KalturaResponseCacher::setExpiry(self::ISLIVE_ACTION_CACHE_EXPIRY); KalturaResponseCacher::setConditionalCacheExpiry(self::ISLIVE_ACTION_CONDITIONAL_CACHE_EXPIRY); if (!kCurrentContext::$ks) { kEntitlementUtils::initEntitlementEnforcement(null, false); $liveStreamEntry = kCurrentContext::initPartnerByEntryId($id); if (!$liveStreamEntry || $liveStreamEntry->getStatus() == entryStatus::DELETED) { throw new KalturaAPIException(KalturaErrors::INVALID_ENTRY_ID, $id); } // enforce entitlement $this->setPartnerFilters(kCurrentContext::getCurrentPartnerId()); } else { $liveStreamEntry = entryPeer::retrieveByPK($id); } if (!$liveStreamEntry || $liveStreamEntry->getType() != entryType::LIVE_STREAM) { throw new KalturaAPIException(KalturaErrors::INVALID_ENTRY_ID, $id); } /* @var $liveStreamEntry LiveStreamEntry */ if (in_array($liveStreamEntry->getSource(), array(KalturaSourceType::LIVE_STREAM, KalturaSourceType::LIVE_STREAM_ONTEXTDATA_CAPTIONS))) { return $liveStreamEntry->hasMediaServer(); } $dpda = new DeliveryProfileDynamicAttributes(); $dpda->setEntryId($id); $dpda->setFormat($protocol); switch ($protocol) { case KalturaPlaybackProtocol::HLS: case KalturaPlaybackProtocol::APPLE_HTTP: $url = $liveStreamEntry->getHlsStreamUrl(); foreach (array(KalturaPlaybackProtocol::HLS, KalturaPlaybackProtocol::APPLE_HTTP) as $hlsProtocol) { $config = $liveStreamEntry->getLiveStreamConfigurationByProtocol($hlsProtocol, requestUtils::getProtocol()); if ($config) { $url = $config->getUrl(); $protocol = $hlsProtocol; break; } } KalturaLog::info('Determining status of live stream URL [' . $url . ']'); $urlManager = DeliveryProfilePeer::getLiveDeliveryProfileByHostName(parse_url($url, PHP_URL_HOST), $dpda); if ($urlManager) { return $urlManager->isLive($url); } break; case KalturaPlaybackProtocol::HDS: case KalturaPlaybackProtocol::AKAMAI_HDS: $config = $liveStreamEntry->getLiveStreamConfigurationByProtocol($protocol, requestUtils::getProtocol()); if ($config) { $url = $config->getUrl(); KalturaLog::info('Determining status of live stream URL [' . $url . ']'); $urlManager = DeliveryProfilePeer::getLiveDeliveryProfileByHostName(parse_url($url, PHP_URL_HOST), $dpda); if ($urlManager) { return $urlManager->isLive($url); } } break; } throw new KalturaAPIException(KalturaErrors::LIVE_STREAM_STATUS_CANNOT_BE_DETERMINED, $protocol); }
/** * This action delivers entry-related data, based on the user's context: access control, restriction, playback format and storage information. * @action getContextData * @param string $entryId * @param KalturaEntryContextDataParams $contextDataParams * @return KalturaEntryContextDataResult */ public function getContextData($entryId, KalturaEntryContextDataParams $contextDataParams) { $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } $ks = $this->getKs(); $isAdmin = false; if ($ks) { $isAdmin = $ks->isAdmin(); } $accessControl = $dbEntry->getAccessControl(); /* @var $accessControl accessControl */ $result = new KalturaEntryContextDataResult(); $result->isAdmin = $isAdmin; $result->isScheduledNow = $dbEntry->isScheduledNow($contextDataParams->time); if ($dbEntry->getStartDate() && abs($dbEntry->getStartDate(null) - time()) <= 86400 || $dbEntry->getEndDate() && abs($dbEntry->getEndDate(null) - time()) <= 86400) { KalturaResponseCacher::setConditionalCacheExpiry(600); } if ($accessControl && $accessControl->hasRules()) { $disableCache = true; if (kConf::hasMap("optimized_playback")) { $partnerId = $accessControl->getPartnerId(); $optimizedPlayback = kConf::getMap("optimized_playback"); if (array_key_exists($partnerId, $optimizedPlayback)) { $params = $optimizedPlayback[$partnerId]; if (array_key_exists('cache_kdp_acccess_control', $params) && $params['cache_kdp_acccess_control']) { $disableCache = false; } } } $accessControlScope = $accessControl->getScope(); $contextDataParams->toObject($accessControlScope); $accessControlScope->setEntryId($entryId); $result->isAdmin = $accessControlScope->getKs() && $accessControlScope->getKs()->isAdmin(); $dbResult = new kEntryContextDataResult(); if ($accessControl->applyContext($dbResult) && $disableCache) { KalturaResponseCacher::disableCache(); } $result->fromObject($dbResult); } $partner = PartnerPeer::retrieveByPK($dbEntry->getPartnerId()); if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_REMOTE_STORAGE_DELIVERY_PRIORITY, $dbEntry->getPartnerId()) && $partner->getStorageServePriority() != StorageProfile::STORAGE_SERVE_PRIORITY_KALTURA_ONLY) { if (is_null($contextDataParams->flavorAssetId)) { if ($contextDataParams->flavorTags) { $assets = assetPeer::retrieveReadyByEntryIdAndTag($entryId, $contextDataParams->flavorTags); $asset = reset($assets); } else { $asset = assetPeer::retrieveBestPlayByEntryId($entryId); } if (!$asset) { throw new KalturaAPIException(KalturaErrors::NO_FLAVORS_FOUND, $entryId); } } else { $asset = assetPeer::retrieveByPK($contextDataParams->flavorAssetId); if (!$asset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $contextDataParams->flavorAssetId); } } if (!$asset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $entryId); } $assetSyncKey = $asset->getSyncKey(asset::FILE_SYNC_ASSET_SUB_TYPE_ASSET); $fileSyncs = kFileSyncUtils::getAllReadyExternalFileSyncsForKey($assetSyncKey); $storageProfilesXML = new SimpleXMLElement("<StorageProfiles/>"); foreach ($fileSyncs as $fileSync) { $storageProfileId = $fileSync->getDc(); $storageProfile = StorageProfilePeer::retrieveByPK($storageProfileId); if (!$storageProfile->getDeliveryRmpBaseUrl() && (!$contextDataParams->streamerType || $contextDataParams->streamerType == StorageProfile::PLAY_FORMAT_AUTO)) { $contextDataParams->streamerType = StorageProfile::PLAY_FORMAT_HTTP; $contextDataParams->mediaProtocol = StorageProfile::PLAY_FORMAT_HTTP; } $storageProfileXML = $storageProfilesXML->addChild("StorageProfile"); $storageProfileXML->addAttribute("storageProfileId", $storageProfileId); $storageProfileXML->addChild("Name", $storageProfile->getName()); $storageProfileXML->addChild("SystemName", $storageProfile->getSystemName()); } $result->storageProfilesXML = $storageProfilesXML->saveXML(); } if ($contextDataParams->streamerType && $contextDataParams->streamerType != StorageProfile::PLAY_FORMAT_AUTO) { $result->streamerType = $contextDataParams->streamerType; $result->mediaProtocol = $contextDataParams->mediaProtocol ? $contextDataParams->mediaProtocol : $contextDataParams->streamerType; } else { $result->streamerType = $this->getPartner()->getStreamerType(); if (!$result->streamerType) { $result->streamerType = StorageProfile::PLAY_FORMAT_HTTP; } $result->mediaProtocol = $this->getPartner()->getMediaProtocol(); if (!$result->mediaProtocol) { $result->mediaProtocol = StorageProfile::PLAY_FORMAT_HTTP; } } return $result; }
/** * batch suspendJobs action suspends jobs from running. * * @action suspendJobs */ function suspendJobsAction() { KalturaResponseCacher::disableCache(); kJobsSuspender::balanceJobsload(); }
/** * Set initial users password * * @param string $hashKey * @param string $newPassword new password to set * * @throws KalturaErrors::LOGIN_DATA_NOT_FOUND * @throws KalturaErrors::PASSWORD_STRUCTURE_INVALID * @throws KalturaErrors::NEW_PASSWORD_HASH_KEY_EXPIRED * @throws KalturaErrors::NEW_PASSWORD_HASH_KEY_INVALID * @throws KalturaErrors::PASSWORD_ALREADY_USED * @throws KalturaErrors::INTERNAL_SERVERL_ERROR */ protected function setInitialPasswordImpl($hashKey, $newPassword) { KalturaResponseCacher::disableCache(); try { $loginData = UserLoginDataPeer::isHashKeyValid($hashKey); if ($loginData) { $this->validateApiAccessControl($loginData->getLastLoginPartnerId()); } $result = UserLoginDataPeer::setInitialPassword($hashKey, $newPassword); } catch (kUserException $e) { $code = $e->getCode(); if ($code == kUserException::LOGIN_DATA_NOT_FOUND) { throw new KalturaAPIException(KalturaErrors::LOGIN_DATA_NOT_FOUND); } if ($code == kUserException::PASSWORD_STRUCTURE_INVALID) { $loginData = UserLoginDataPeer::isHashKeyValid($hashKey); $invalidPasswordStructureMessage = $loginData->getInvalidPasswordStructureMessage(); throw new KalturaAPIException(KalturaErrors::PASSWORD_STRUCTURE_INVALID, $invalidPasswordStructureMessage); } if ($code == kUserException::NEW_PASSWORD_HASH_KEY_EXPIRED) { throw new KalturaAPIException(KalturaErrors::NEW_PASSWORD_HASH_KEY_EXPIRED); } if ($code == kUserException::NEW_PASSWORD_HASH_KEY_INVALID) { throw new KalturaAPIException(KalturaErrors::NEW_PASSWORD_HASH_KEY_INVALID); } if ($code == kUserException::PASSWORD_ALREADY_USED) { throw new KalturaAPIException(KalturaErrors::PASSWORD_ALREADY_USED); } throw $e; } if (!$result) { throw new KalturaAPIException(KalturaErrors::INTERNAL_SERVERL_ERROR); } }
/** * @action getVersion * @return string the current server version */ function getVersionAction() { KalturaResponseCacher::disableCache(); $version = file_get_contents(realpath(dirname(__FILE__)) . '/../../VERSION.txt'); return trim($version); }
protected function validateApiAccessControl() { if (is_null($this->partner)) { return; } // ignore for system partners // for cases where an api action has a 'partnerId' parameter which will causes loading that partner instead of the ks partner if ($this->getKs() && $this->getKs()->partner_id < 0) { return; } $accessControl = $this->partner->getApiAccessControl(); if (is_null($accessControl)) { return; } $context = new kEntryContextDataResult(); $disableCache = $accessControl->applyContext($context, $this->getApiAccessControlScope()); if ($disableCache) { KalturaResponseCacher::disableCache(); } if (count($context->getAccessControlMessages())) { foreach ($context->getAccessControlMessages() as $msg) { header("X-Kaltura: api-access-control: {$msg}"); } } if (count($context->getAccessControlActions())) { $actions = $context->getAccessControlActions(); foreach ($actions as $action) { /* @var $action kAccessControlAction */ if ($action->getType() == accessControlActionType::BLOCK) { throw new KalturaAPIException(APIErrors::SERVICE_ACCESS_CONTROL_RESTRICTED, $this->serviceId . '->' . $this->actionName); } } } }
/** * @param asset $asset * @param bool $tokenizeUrl * @return string */ public function getAssetUrl(asset $asset, $tokenizeUrl = true) { $url = null; if ($asset instanceof thumbAsset) { $url = $this->doGetThumbnailAssetUrl($asset); } if ($asset instanceof flavorAsset) { $url = $this->doGetFlavorAssetUrl($asset); if ($tokenizeUrl) { $tokenizer = $this->getTokenizer(); if ($tokenizer) { $url = $tokenizer->tokenizeSingleUrl($url); if (class_exists('KalturaResponseCacher')) { KalturaResponseCacher::disableCache(); } } } } return $url; }
/** * Retrieve partner secret and admin secret * * @action getSecrets * @param int $partnerId * @param string $adminEmail * @param string $cmsPassword * @return KalturaPartner * * * @throws APIErrors::ADMIN_KUSER_NOT_FOUND */ public function getSecretsAction($partnerId, $adminEmail, $cmsPassword) { KalturaResponseCacher::disableCache(); $adminKuser = null; try { $adminKuser = UserLoginDataPeer::userLoginByEmail($adminEmail, $cmsPassword, $partnerId); } catch (kUserException $e) { throw new KalturaAPIException(APIErrors::ADMIN_KUSER_NOT_FOUND, "The data you entered is invalid"); } if (!$adminKuser || !$adminKuser->getIsAdmin()) { throw new KalturaAPIException(APIErrors::ADMIN_KUSER_NOT_FOUND, "The data you entered is invalid"); } KalturaLog::log("Admin Kuser found, going to validate password", KalturaLog::INFO); // user logged in - need to re-init kPermissionManager in order to determine current user's permissions $ks = null; kSessionUtils::createKSessionNoValidations($partnerId, $adminKuser->getPuserId(), $ks, 86400, $adminKuser->getIsAdmin(), "", '*'); kCurrentContext::initKsPartnerUser($ks); kPermissionManager::init(); $dbPartner = PartnerPeer::retrieveByPK($partnerId); $partner = new KalturaPartner(); $partner->fromPartner($dbPartner); $partner->cmsPassword = $cmsPassword; return $partner; }
public function getExceptionObject($ex, $service, $action) { KalturaResponseCacher::adjustApiCacheForException($ex); if ($ex instanceof KalturaAPIException) { KalturaLog::err($ex); $object = $ex; } else { if ($ex instanceof APIException) { $args = $ex->extra_data; $reflectionException = new ReflectionClass("KalturaAPIException"); $ex = $reflectionException->newInstanceArgs($args); KalturaLog::err($ex); $object = $ex; } else { if ($ex instanceof kCoreException) { switch ($ex->getCode()) { case kCoreException::USER_BLOCKED: $object = new KalturaAPIException(KalturaErrors::USER_BLOCKED); break; case kCoreException::PARTNER_BLOCKED: $object = new KalturaAPIException(KalturaErrors::SERVICE_FORBIDDEN_CONTENT_BLOCKED); break; case kCoreException::INVALID_KS: $object = new KalturaAPIException(KalturaErrors::INVALID_KS, $ex->getData(), ks::INVALID_STR, 'INVALID_STR'); break; case kCoreException::MAX_NUMBER_OF_ACCESS_CONTROLS_REACHED: $object = new KalturaAPIException(KalturaErrors::MAX_NUMBER_OF_ACCESS_CONTROLS_REACHED, $ex->getData()); break; case kCoreException::MAX_CATEGORIES_PER_ENTRY: $object = new KalturaAPIException(KalturaErrors::MAX_CATEGORIES_FOR_ENTRY_REACHED, $ex->getData()); break; case kCoreException::MAX_ASSETS_PER_ENTRY: $object = new KalturaAPIException(KalturaErrors::MAX_ASSETS_FOR_ENTRY_REACHED, asset::MAX_ASSETS_PER_ENTRY); break; case kCoreException::SEARCH_TOO_GENERAL: $object = new KalturaAPIException(KalturaErrors::SEARCH_TOO_GENERAL); break; case kCoreException::SOURCE_FILE_NOT_FOUND: $object = new KalturaAPIException(KalturaErrors::SOURCE_FILE_NOT_FOUND); break; case APIErrors::INVALID_ACTIONS_LIMIT: $object = new KalturaAPIException(APIErrors::INVALID_ACTIONS_LIMIT); break; case APIErrors::PRIVILEGE_IP_RESTRICTION: $object = new KalturaAPIException(APIErrors::PRIVILEGE_IP_RESTRICTION); break; case APIErrors::INVALID_SET_ROLE: $object = new KalturaAPIException(APIErrors::INVALID_SET_ROLE); break; case APIErrors::UNKNOWN_ROLE_ID: $object = new KalturaAPIException(APIErrors::UNKNOWN_ROLE_ID); break; case APIErrors::SEARCH_ENGINE_QUERY_FAILED: $object = new KalturaAPIException(APIErrors::SEARCH_ENGINE_QUERY_FAILED); break; case kCoreException::FILE_NOT_FOUND: $object = new KalturaAPIException(KalturaErrors::FILE_NOT_FOUND); break; case kCoreException::LOCK_TIMED_OUT: $object = new KalturaAPIException(KalturaErrors::LOCK_TIMED_OUT); break; case kCoreException::SPHINX_CRITERIA_EXCEEDED_MAX_MATCHES_ALLOWED: $object = new KalturaAPIException(KalturaErrors::SPHINX_CRITERIA_EXCEEDED_MAX_MATCHES_ALLOWED); break; case kCoreException::INVALID_ENTRY_ID: $object = new KalturaAPIException(KalturaErrors::INVALID_ENTRY_ID, $ex->getData()); break; case kCoreException::MAX_FILE_SYNCS_FOR_OBJECT_PER_DAY_REACHED: $object = new KalturaAPIException(KalturaErrors::MAX_FILE_SYNCS_FOR_OBJECT_PER_DAY_REACHED, $ex->getData()); break; case kCoreException::ID_NOT_FOUND: $object = new KalturaAPIException(KalturaErrors::INVALID_OBJECT_ID, $ex->getData()); break; default: KalturaLog::crit($ex); $object = new KalturaAPIException(KalturaErrors::INTERNAL_SERVERL_ERROR); } } else { if ($ex instanceof PropelException) { KalturaLog::alert($ex); $object = new KalturaAPIException(KalturaErrors::INTERNAL_DATABASE_ERROR); } else { KalturaLog::crit($ex); $object = new KalturaAPIException(KalturaErrors::INTERNAL_SERVERL_ERROR); } } } } return $this->handleErrorMapping($object, $service, $action); }
public function query() { if (class_exists('KalturaResponseCacher')) { KalturaResponseCacher::disableConditionalCache(); } $args = func_get_args(); $sql = $args[0]; KalturaLog::debug($sql); $comment = $this->getCommentWrapped(); $sql = $comment . $sql; $sqlStart = microtime(true); try { if (version_compare(PHP_VERSION, '5.3', '<')) { $result = call_user_func_array(array($this, 'parent::query'), $args); } else { $result = call_user_func_array('parent::query', $args); } } catch (PropelException $pex) { KalturaLog::alert($pex->getMessage()); throw new PropelException("Database error"); } KalturaLog::debug("Sql took - " . (microtime(true) - $sqlStart) . " seconds"); return $result; }
/** * Flag inappropriate media entry for moderation * * @action flag * @param string $entryId * @param KalturaModerationFlag $moderationFlag * * @throws KalturaErrors::ENTRY_ID_NOT_FOUND */ public function flagAction(KalturaModerationFlag $moderationFlag) { KalturaResponseCacher::disableCache(); return parent::flagEntry($moderationFlag, KalturaEntryType::MEDIA_CLIP); }
private function responseHandlingIsLive($isLive) { if (!$isLive) { KalturaResponseCacher::setExpiry(self::ISLIVE_ACTION_CACHE_EXPIRY_WHEN_NOT_LIVE); KalturaResponseCacher::setHeadersCacheExpiry(self::ISLIVE_ACTION_CACHE_EXPIRY_WHEN_NOT_LIVE); } else { KalturaResponseCacher::setExpiry(self::ISLIVE_ACTION_CACHE_EXPIRY_WHEN_LIVE); KalturaResponseCacher::setHeadersCacheExpiry(self::ISLIVE_ACTION_CACHE_EXPIRY_WHEN_LIVE); } return $isLive; }
/** * Starts a new KS (kaltura Session) based on application authentication token id * * @action startSession * @param string $id application token id * @param string $tokenHash hashed token, built of sha1 on current KS concatenated with the application token * @param string $userId session user id, will be ignored if a different user id already defined on the application token * @param KalturaSessionType $type session type, will be ignored if a different session type already defined on the application token * @param int $expiry session expiry (in seconds), could be overwritten by shorter expiry of the application token and the session-expiry that defined on the application token * @param string $privileges session privileges, will be appended to privileges that defined on the application token * @throws KalturaErrors::APP_TOKEN_ID_NOT_FOUND * @return KalturaSessionInfo */ function startSessionAction($id, $tokenHash, $userId = null, $type = null, $expiry = null) { $dbAppToken = AppTokenPeer::retrieveByPK($id); if (!$dbAppToken) { throw new KalturaAPIException(KalturaErrors::APP_TOKEN_ID_NOT_FOUND, $id); } if ($dbAppToken->getStatus() != AppTokenStatus::ACTIVE) { throw new KalturaAPIException(KalturaErrors::APP_TOKEN_NOT_ACTIVE, $id); } $appTokenHash = sha1(kCurrentContext::$ks . $dbAppToken->getToken()); if ($appTokenHash !== $tokenHash) { throw new KalturaAPIException(KalturaErrors::INVALID_APP_TOKEN_HASH); } KalturaResponseCacher::disableCache(); $tokenExpiry = $dbAppToken->getSessionDuration(); if (!is_null($dbAppToken->getExpiry())) { $tokenExpiry = min($tokenExpiry, $dbAppToken->getExpiry() - time()); if ($tokenExpiry < 0) { throw new KalturaAPIException(KalturaErrors::APP_TOKEN_EXPIRED, $id); } } if (!$expiry) { $expiry = $tokenExpiry; } $expiry = min($expiry, $tokenExpiry); if (!is_null($dbAppToken->getSessionType())) { $type = $dbAppToken->getSessionType(); } if (is_null($type)) { $type = SessionType::USER; } if (!is_null($dbAppToken->getSessionUserId())) { $userId = $dbAppToken->getSessionUserId(); } $partnerId = kCurrentContext::getCurrentPartnerId(); $partner = PartnerPeer::retrieveByPK($partnerId); $secret = $type == SessionType::ADMIN ? $partner->getAdminSecret() : $partner->getSecret(); $privilegesArray = array(ks::PRIVILEGE_SESSION_ID => array($id), ks::PRIVILEGE_APP_TOKEN => array($id)); if ($dbAppToken->getSessionPrivileges()) { $privilegesArray = array_merge_recursive($privilegesArray, ks::parsePrivileges($dbAppToken->getSessionPrivileges())); } $privileges = ks::buildPrivileges($privilegesArray); $ks = kSessionUtils::createKSession($partnerId, $secret, $userId, $expiry, $type, $privileges); if (!$ks) { throw new KalturaAPIException(APIErrors::START_SESSION_ERROR, $partnerId); } $sessionInfo = new KalturaSessionInfo(); $sessionInfo->ks = $ks->toSecureString(); $sessionInfo->partnerId = $partnerId; $sessionInfo->userId = $userId; $sessionInfo->expiry = $ks->valid_until; $sessionInfo->sessionType = $type; $sessionInfo->privileges = $privileges; return $sessionInfo; }
public function dispatch($service, $action, $params = array()) { $start = microtime(true); // prevent impersonate to partner zero $p = isset($params["p"]) && $params["p"] ? $params["p"] : null; if (!$p) { $p = isset($params["partnerId"]) && $params["partnerId"] ? $params["partnerId"] : null; } $GLOBALS["partnerId"] = $p; // set for logger $userId = ""; $ksStr = isset($params["ks"]) ? $params["ks"] : null; if (!$service) { throw new KalturaAPIException(KalturaErrors::SERVICE_NOT_SPECIFIED); } //strtolower on service - map is indexed according to lower-case service IDs $service = strtolower($service); $serviceActionItem = KalturaServicesMap::retrieveServiceActionItem($service, $action); $action = strtolower($action); if (!isset($serviceActionItem->actionMap[$action])) { KalturaLog::crit("Action does not exist!"); throw new KalturaAPIException(KalturaErrors::ACTION_DOES_NOT_EXISTS, $action, $service); } try { $actionReflector = new KalturaActionReflector($service, $action, $serviceActionItem->actionMap[$action]); } catch (Exception $e) { throw new Exception("Could not create action reflector for service [{$service}], action [{$action}]. Received error: " . $e->getMessage()); } $actionParams = $actionReflector->getActionParams(); $actionInfo = $actionReflector->getActionInfo(); // services.ct - check if partner is allowed to access service ... kCurrentContext::$host = isset($_SERVER["HOSTNAME"]) ? $_SERVER["HOSTNAME"] : gethostname(); kCurrentContext::$user_ip = requestUtils::getRemoteAddress(); kCurrentContext::$ps_vesion = "ps3"; kCurrentContext::$service = $serviceActionItem->serviceInfo->serviceName; kCurrentContext::$action = $action; kCurrentContext::$client_lang = isset($params['clientTag']) ? $params['clientTag'] : null; kCurrentContext::initKsPartnerUser($ksStr, $p, $userId); // validate it's ok to access this service $deserializer = new KalturaRequestDeserializer($params); $this->arguments = $deserializer->buildActionArguments($actionParams); KalturaLog::debug("Dispatching service [" . $service . "], action [" . $action . "], reqIndex [" . kCurrentContext::$multiRequest_index . "] with params " . print_r($this->arguments, true)); $responseProfile = $deserializer->getResponseProfile(); if ($responseProfile) { KalturaLog::debug("Response profile: " . print_r($responseProfile, true)); } kPermissionManager::init(kConf::get('enable_cache')); kEntitlementUtils::initEntitlementEnforcement(); $disableTags = $actionInfo->disableTags; if ($disableTags && is_array($disableTags) && count($disableTags)) { foreach ($disableTags as $disableTag) { KalturaCriterion::disableTag($disableTag); } } if ($actionInfo->validateUserObjectClass && $actionInfo->validateUserIdParamName && isset($actionParams[$actionInfo->validateUserIdParamName])) { // // TODO maybe if missing should throw something, maybe a bone? // if(!isset($actionParams[$actionInfo->validateUserIdParamName])) // throw new KalturaAPIException(KalturaErrors::MISSING_MANDATORY_PARAMETER, $actionInfo->validateUserIdParamName); KalturaLog::debug("validateUserIdParamName: " . $actionInfo->validateUserIdParamName); $objectId = $params[$actionInfo->validateUserIdParamName]; $this->validateUser($actionInfo->validateUserObjectClass, $objectId, $actionInfo->validateUserPrivilege, $actionInfo->validateOptions); } // initialize the service before invoking the action on it // action reflector will init the service to maintain the pluginable action transparency $actionReflector->initService($responseProfile); $invokeStart = microtime(true); KalturaLog::debug("Invoke start"); try { $res = $actionReflector->invoke($this->arguments); } catch (KalturaAPIException $e) { if ($actionInfo->returnType != 'file') { throw $e; } KalturaResponseCacher::adjustApiCacheForException($e); $res = new kRendererDieError($e->getCode(), $e->getMessage()); } kEventsManager::flushEvents(); KalturaLog::debug("Invoke took - " . (microtime(true) - $invokeStart) . " seconds"); KalturaLog::debug("Dispatch took - " . (microtime(true) - $start) . " seconds, memory: " . memory_get_peak_usage(true)); return $res; }
/** * Validates all registered media servers * * @action validateRegisteredMediaServers * @param string $entryId Live entry id * * @throws KalturaErrors::ENTRY_ID_NOT_FOUND */ function validateRegisteredMediaServersAction($entryId) { KalturaResponseCacher::disableCache(); $this->dumpApiRequest($entryId, false); $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry || !$dbEntry instanceof LiveEntry) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } /* @var $dbEntry LiveEntry */ if ($dbEntry->validateMediaServers()) { $dbEntry->save(); } }
<?php $start = microtime(true); set_time_limit(0); require_once dirname(__FILE__) . '/../../alpha/config/sfrootdir.php'; // check cache before loading anything require_once "../lib/KalturaResponseCacher.php"; $cache = new KalturaResponseCacher(null, "/web/cache/feed/", 86400); $cache->checkOrStart(); require_once "../bootstrap.php"; KalturaLog::setContext("syndicationFeedRenderer"); KalturaLog::debug(">------------------------------------- syndicationFeedRenderer -------------------------------------"); KalturaLog::info("syndicationFeedRenderer-start "); $feedId = $_GET['feedId']; $entryId = @$_GET['entryId']; try { $syndicationFeedRenderer = new KalturaSyndicationFeedRenderer($feedId); $syndicationFeedRenderer->addFlavorParamsAttachedFilter(); if (isset($entryId)) { $syndicationFeedRenderer->addEntryAttachedFilter($entryId); } $syndicationFeedRenderer->execute(); } catch (Exception $ex) { header('KalturaSyndication: ' . $ex->getMessage()); die; } $end = microtime(true); KalturaLog::info("syndicationFeedRenderer-end [" . ($end - $start) . "]"); KalturaLog::debug("<------------------------------------- syndicationFeedRenderer -------------------------------------"); $cache->end();
public function get($obj_name) { if (!self::$s_ready) { return NULL; } // $this->m_stats->m_gets++; if (class_exists('KalturaResponseCacher')) { KalturaResponseCacher::disableConditionalCache(); } $value = self::$s_memcache->get($this->m_namespace . $obj_name); if (!isset($value)) { $this->m_stats->m_misses++; return NULL; } else { $this->m_stats->m_hits++; return $value; } }
/** * Serves short link * * @action goto * @param string $id * @param bool $proxy proxy the response instead of redirect * @return file * * @throws KalturaErrors::INVALID_OBJECT_ID */ function gotoAction($id, $proxy = false) { KalturaResponseCacher::disableCache(); $dbShortLink = ShortLinkPeer::retrieveByPK($id); if (!$dbShortLink) { throw new KalturaAPIException(KalturaErrors::INVALID_OBJECT_ID, $id); } if ($proxy) { kFile::dumpUrl($dbShortLink->getFullUrl(), true, true); } header('Location: ' . $dbShortLink->getFullUrl()); die; }
/** * Serves the file content * * @action serveByFlavorParamsId * @param string $entryId Document entry id * @param string $flavorParamsId Flavor params id * @param bool $forceProxy force to get the content without redirect * @return file * * @throws KalturaErrors::ENTRY_ID_NOT_FOUND * @throws KalturaErrors::FLAVOR_ASSET_IS_NOT_READY * @throws KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND */ public function serveByFlavorParamsIdAction($entryId, $flavorParamsId = null, $forceProxy = false) { // temporary workaround for getting the referrer from a url with the format ....&forceProxy/true/referrer/... $referrer = null; if (isset($_GET["forceProxy"]) && kString::beginsWith($_GET["forceProxy"], "true/referrer/")) { $referrer = substr($_GET["forceProxy"], strlen("true/referrer/")); $referrer = base64_decode($referrer); } KalturaResponseCacher::disableCache(); myPartnerUtils::resetPartnerFilter('entry'); $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry || $dbEntry->getType() != entryType::DOCUMENT) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } $ksObj = $this->getKs(); $ks = $ksObj ? $ksObj->getOriginalString() : null; $securyEntryHelper = new KSecureEntryHelper($dbEntry, $ks, $referrer, ContextType::DOWNLOAD); $securyEntryHelper->validateForDownload(); $flavorAsset = null; if ($flavorParamsId) { $flavorAsset = assetPeer::retrieveByEntryIdAndParams($entryId, $flavorParamsId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_IS_NOT_READY, $flavorParamsId); } } else { $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $flavorParamsId); } } if (!$securyEntryHelper->isAssetAllowed($flavorAsset)) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $flavorParamsId); } $fileName = $dbEntry->getName() . '.' . $flavorAsset->getFileExt(); return $this->serveFlavorAsset($flavorAsset, $fileName, $forceProxy); }