Beispiel #1
0
 /**
  * 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;
 }
Beispiel #2
0
 /**
  * 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);
     }
 }
 /**
  *
  * @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 objectSaved(BaseObject $object)
 {
     KalturaResponseCacher::disableCache();
 }
 /**
  * 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;
 }
Beispiel #6
0
 /**
  * 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;
 }
 /**
  * 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();
     }
 }
Beispiel #8
0
 /**
  * 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);
 }
 /**
  * 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;
 }
 /**
  *
  * 
  * @action getTime
  * @return int Return current server timestamp
  */
 function getTimeAction()
 {
     KalturaResponseCacher::disableCache();
     return time();
 }
Beispiel #11
0
 /**
  * @action getVersion
  * @return string the current server version
  */
 function getVersionAction()
 {
     KalturaResponseCacher::disableCache();
     $version = file_get_contents(realpath(dirname(__FILE__)) . '/../../VERSION.txt');
     return trim($version);
 }
Beispiel #12
0
 /**
  * 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);
 }
 /**
  * @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;
 }
 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);
             }
         }
     }
 }
Beispiel #15
0
 /**
  * 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;
 }
Beispiel #16
0
 /**
  * batch suspendJobs action suspends jobs from running.
  *
  * @action suspendJobs
  */
 function suspendJobsAction()
 {
     KalturaResponseCacher::disableCache();
     kJobsSuspender::balanceJobsload();
 }
Beispiel #17
0
 /**
  * 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);
 }
 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;
 }
Beispiel #19
0
 /**
  * @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();
     $result = new KalturaEntryContextDataResult();
     $result->isAdmin = $isAdmin;
     $result->isScheduledNow = $dbEntry->isScheduledNow();
     // defaults
     $result->isSiteRestricted = false;
     $result->isCountryRestricted = false;
     $result->isSessionRestricted = false;
     $result->isIpAddressRestricted = false;
     $result->previewLength = -1;
     if ($accessControl && $accessControl->hasRestrictions()) {
         KalturaResponseCacher::disableCache();
         $accessControlScope = accessControlScope::partialInit();
         $accessControlScope->setReferrer($contextDataParams->referrer);
         $accessControlScope->setKs($this->getKs());
         $accessControlScope->setEntryId($entryId);
         $accessControl->setScope($accessControlScope);
         if ($accessControl->hasSiteRestriction()) {
             $result->isSiteRestricted = !$accessControl->getSiteRestriction()->isValid();
         }
         if ($accessControl->hasCountryRestriction()) {
             $result->isCountryRestricted = !$accessControl->getCountryRestriction()->isValid();
         }
         if ($accessControl->hasSessionRestriction()) {
             $result->isSessionRestricted = !$accessControl->getSessionRestriction()->isValid();
         }
         if ($accessControl->hasPreviewRestriction()) {
             $result->isSessionRestricted = !$accessControl->getPreviewRestriction()->isValid();
             $result->previewLength = $accessControl->getPreviewRestriction()->getPreviewLength();
         }
         if ($accessControl->hasIpAddressRestriction()) {
             $result->isIpAddressRestricted = !$accessControl->getIpAddressRestriction()->isValid();
         }
     }
     return $result;
 }
 /**
  * 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;
 }
Beispiel #21
0
 /**
  * Parse session key and return its info
  * 
  * @action get
  * @param string $session The KS to be parsed, keep it empty to use current session.
  * @return KalturaSessionInfo
  *
  * @throws APIErrors::START_SESSION_ERROR
  */
 function getAction($session = null)
 {
     KalturaResponseCacher::disableCache();
     if (!$session) {
         $session = kCurrentContext::$ks;
     }
     $ks = ks::fromSecureString($session);
     if (!myPartnerUtils::allowPartnerAccessPartner($this->getPartnerId(), $this->partnerGroup(), $ks->partner_id)) {
         throw new KalturaAPIException(APIErrors::PARTNER_ACCESS_FORBIDDEN, $this->getPartnerId(), $ks->partner_id);
     }
     $sessionInfo = new KalturaSessionInfo();
     $sessionInfo->partnerId = $ks->partner_id;
     $sessionInfo->userId = $ks->user;
     $sessionInfo->expiry = $ks->valid_until;
     $sessionInfo->sessionType = $ks->type;
     $sessionInfo->privileges = $ks->privileges;
     return $sessionInfo;
 }
 /**
  * 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);
     }
 }
Beispiel #23
0
 /**
  * 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);
     }
     if ($dbEntry->getStatus() != entryStatus::READY) {
         // the purpose of this is to solve a case in which a player attempts to play a non-ready entry,
         // and the request becomes cached for a long time, preventing playback even after the entry
         // becomes ready
         kApiCache::setExpiry(60);
     }
     $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);
     if (!$result->isScheduledNow && $this->getKs()) {
         // in case the sview is defined in the ks simulate schedule now true to allow player to pass verification
         if ($this->getKs()->verifyPrivileges(ks::PRIVILEGE_VIEW, ks::PRIVILEGE_WILDCARD) || $this->getKs()->verifyPrivileges(ks::PRIVILEGE_VIEW, $entryId)) {
             $result->isScheduledNow = true;
         }
     }
     $result->pluginData = new KalturaPluginDataArray();
     $pluginInstances = KalturaPluginManager::getPluginInstances('IKalturaEntryContextDataContributor');
     foreach ($pluginInstances as $pluginInstance) {
         $pluginInstance->contributeToEntryContextDataResult($dbEntry, $contextDataParams, $result);
     }
     return $result;
 }
 /**
  * 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;
 }
 /**
  * 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 {
         $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) {
             throw new KalturaAPIException(KalturaErrors::PASSWORD_STRUCTURE_INVALID);
         }
         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);
     }
 }