public function execute($add_extra_debug_data = true)
 {
     date_default_timezone_set(kConf::get("date_default_timezone"));
     // TODO - remove for production - use some configuration to determine
     kConfigTable::$should_use_cache = false;
     $start_impl = $end_impl = 0;
     $nocache = false;
     if ($this->getP("nocache")) {
         $nocache = true;
         $this->logMessage("Not using cache!");
         objectWrapperBase::useCache(false);
     }
     $add_benchmarks = $this->getP("add_benchmarks", false);
     // while testing our system - will match each service agains its description
     // $this->matchInDescription();
     $this->msg = array();
     $this->error = array();
     $this->debug = array();
     $start_time = microtime(true);
     $start = microtime(true);
     $this->benchmarkStart("beforeImpl");
     $this->response_type = $this->getP("format", self::DEFAULT_FORMAT);
     //
     /*
     		$should_debug = $this->getP ( "should_debug" , true );
     		if ( $should_debug == "false" ) $this->should_debug  = false;
     */
     if ($this->should_debug && $add_extra_debug_data) {
         $this->benchmarkStart("signature");
         $sig_type = $this->getP("sigtype", self::SIG_TYPE_POST);
         $signature_params = self::getParamsFromSigType($sig_type);
         $signatura_valid = self::validateSignature($signature_params);
         $this->benchmarkEnd("signature");
         $this->addDebug("sigtype", $sig_type);
         $this->addDebug("validateSignature", $signatura_valid);
         $this->addDebug("signature", self::signature($signature_params));
         //			$this->addDebug( "rawsignature" , self::signature( $signature_params , false ) );
     }
     $partner_id = $this->getP("partner_id");
     if (!$partner_id) {
         $partner_id = $this->getP("partnerId");
     }
     $subp_id = $this->getP("subp_id");
     if (!$subp_id) {
         $subp_id = $this->getP("subpId");
     }
     $puser_id = $this->getP("uid");
     $ks_str = $this->getP("ks");
     if ($ks_str == "{ks}") {
         $ks_str = "";
     }
     // if the client DIDN'T replace the dynamic ks - ignore it
     // the $execution_cache_key can be used by services to cache the results depending on the inpu parameters
     // if the $execution_cache_key is not null, the rendere will search for the result of the rendering depending on the $execution_cache_key
     // if it doesn't find it - it will create it (per format) and store it for next time
     $execution_cache_key = null;
     // moved the renderer here to see if has the $execution_cache_key and if so - skip the implementation
     $renderer = new kalturaWebserviceRenderer($this->response_context);
     $private_partner_data = false;
     try {
         try {
             $arr = list($partner_id, $subp_id, $uid, $private_partner_data) = $this->validateTicketSetPartner($partner_id, $subp_id, $puser_id, $ks_str);
         } catch (Exception $ex) {
             KalturaLog::log('validateTicketSetPartner failed - not caching response');
             defPartnerservices2baseAction::disableCache();
             throw $ex;
         }
         // if PS2 permission validation is enabled for the current partner, only the actions defined in kConf's parameter "ps2_actions_not_blocked_by_permissions" will be allowed
         $currentPartner = $this->getPartner();
         if ($currentPartner && $currentPartner->getEnabledService(PermissionName::FEATURE_PS2_PERMISSIONS_VALIDATION)) {
             if (!in_array(strtolower(get_class($this)), kConf::get('ps2_actions_not_blocked_by_permissions'))) {
                 KalturaLog::log('PS2 action ' . get_class($this) . ' is being blocked for partner ' . $currentPartner->getId() . ' defined with FEATURE_PS2_PERMISSIONS_VALIDATION enabled');
                 $this->addException(APIErrors::SERVICE_FORBIDDEN, get_class($this));
             }
         }
         $this->private_partner_data = $private_partner_data;
         //print_r ( $arr );
         // TODO - validate the matchIp is ok with the user's IP
         $this->validateIp();
         // most services should not attempt to cache the results - for them this will return null
         $execution_cache_key = $this->getExecutionCacheKeyWrapper($partner_id, $subp_id, $puser_id);
         // if the key is not null - it will be used in the renderer for using the cotent from the cache
         if ($nocache) {
             $renderer->deleteCacheKey($execution_cache_key, $this->response_type);
         } else {
             $renderer->setCacheKey($execution_cache_key);
         }
         if (!$renderer->hasContentForCacheKey($this->response_type)) {
             $this->benchmarkStart("applyPartnerFilters");
             //init entitlement before set the default criteire by myPartnerUtils::applyPartnerFilters
             kEntitlementUtils::initEntitlementEnforcement();
             // apply filters for Criteria so there will be no chance of exposure of date from other partners !
             // TODO - add the parameter for allowing kaltura network
             myPartnerUtils::applyPartnerFilters($partner_id, $private_partner_data, $this->partnerGroup2(), $this->kalturaNetwork2());
             $this->benchmarkEnd("applyPartnerFilters");
             $this->benchmarkStart("puserKuser");
             list($partner_id, $subp_id, $puser_id, $partner_prefix) = $this->preparePartnerPuserDetails($partner_id, $subp_id, $puser_id);
             $puser_kuser = $this->getPuserKuser($partner_id, $subp_id, $puser_id);
             $this->benchmarkEnd("puserKuser");
             $this->benchmarkEnd("beforeImpl");
             // ----------------------------- impl --------------------------
             $start_impl = microtime(true);
             $result = $this->executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser);
             $end_impl = microtime(true);
             kEventsManager::flushEvents();
         } else {
             /// the renderer claims to have the desired result ! just flow down the code ... ;)
         }
         // ----------------------------- impl --------------------------
     } catch (APIException $api_ex) {
         $message = $api_ex->getMessage();
         if ($this->should_debug && $message) {
             $this->addError(APIErrors::SERVERL_ERROR, "[{$message}]");
         } elseif ($api_ex->api_code) {
             call_user_func_array(array(&$this, 'addError'), $api_ex->extra_data);
             //				$this->addError ( $api_ex->api_code ,$api_ex->extra_data );
         }
     } catch (PropelException $pex) {
         KalturaLog::alert($pex->getMessage());
         $this->addError(APIErrors::INTERNAL_DATABASE_ERROR);
     } catch (Exception $ex) {
         $this->addError(APIErrors::INTERNAL_SERVERL_ERROR, $ex->getMessage());
         KalturaLog::err($ex->getMessage());
     }
     $execute_impl_end_time = microtime(true);
     // render according to the format_type
     $res = array();
     $this->addMsg("serverTime", time());
     $res['result'] = $this->msg;
     $res['error'] = $this->error;
     if ($this->should_debug) {
         // this specific debug line should be used
         $this->addDebug("execute_impl_time", $end_impl - $start_impl);
         $this->addDebug("execute_time", $execute_impl_end_time - $start_time);
         // will be used as a place holder and will be replaced after the rendering.
         if ($add_extra_debug_data) {
             $this->addDebug("total_time", self::__TOTAL_TIME__);
         }
         if ($add_benchmarks && count($this->benchmarks) > 0) {
             $this->addDebug("host", @$_ENV["HOSTNAME"]);
             $this->addDebug("benchmarks", $this->getBenchmarks());
         }
         $res['debug'] = $this->debug;
     }
     // ignore all the errors and debug - the first msg is the only html used
     if ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_HTML) {
         $res = "<html>";
         foreach ($this->msg as $html_bit) {
             $res .= $html_bit;
         }
         $res .= "</html>";
     }
     if ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_MRSS) {
         // in case of mRss - render only the result not the errors ot the debug
         list($response, $content_type) = $renderer->renderDataInRequestedFormat($res['result'], $this->response_type, true, self::$escape_text);
     } else {
         list($response, $content_type) = $renderer->renderDataInRequestedFormat($res, $this->response_type, true, self::$escape_text);
     }
     $end_time = microtime(true);
     if (is_string($response)) {
         $this->logMessage("Rendereing took: [" . ($end_time - $start_time) . "] seconds. Response size [" . strlen($response) . "]", SF_LOG_WARNING);
         $this->logMessage($response, SF_LOG_WARNING);
     } else {
         $this->logMessage("Rendereing took: [" . ($end_time - $start_time) . "]");
     }
     if ($this->should_debug && $add_extra_debug_data) {
         // fix the total time including the render time
         $str_time = (string) ($end_time - $start_time);
         if ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_PHP) {
             // replcate the placehoder with the real execution time
             // this is a nasty hack - we replace the serialized PHP value - the length of the placeholder is 14 characters
             // the length of the str_time can be less - replace the whole string phrase
             $replace_string = 's:' . strlen($str_time) . ':"' . $str_time;
             $response = str_replace('s:14:"' . self::__TOTAL_TIME__, $replace_string, $response);
         } elseif ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_PHP_ARRAY || $this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_PHP_OBJECT) {
             // the $response is not a string - we can't just replace it
             $res["debug"]["total_time"] = $str_time;
         } elseif ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_MRSS) {
             // do nothing to the result
         } else {
             $response = str_replace(self::__TOTAL_TIME__, $str_time, $response);
         }
     }
     header("Access-Control-Allow-Origin:*");
     // avoid html5 xss issues
     $this->setContentType($content_type);
     // while testing our system - will match each service agains its description
     // $this->matchOutDescription();
     return $response;
 }
Exemplo n.º 2
0
 /**
  * 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)
 {
     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);
     }
     if (!in_array($liveStreamEntry->getSource(), LiveEntry::$kalturaLiveSourceTypes)) {
         KalturaResponseCacher::setConditionalCacheExpiry(self::ISLIVE_ACTION_NON_KALTURA_LIVE_CONDITIONAL_CACHE_EXPIRY);
     }
     /* @var $liveStreamEntry LiveStreamEntry */
     if (in_array($liveStreamEntry->getSource(), array(KalturaSourceType::LIVE_STREAM, KalturaSourceType::LIVE_STREAM_ONTEXTDATA_CAPTIONS))) {
         return $this->responseHandlingIsLive($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 $this->responseHandlingIsLive($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 $this->responseHandlingIsLive($urlManager->isLive($url));
                 }
             }
             break;
     }
     throw new KalturaAPIException(KalturaErrors::LIVE_STREAM_STATUS_CANNOT_BE_DETERMINED, $protocol);
 }
Exemplo n.º 3
0
 public static function updateAccessControl($partnerId, $oldAccessControlId, $newAccessControlId)
 {
     $c = KalturaCriteria::create(entryPeer::OM_CLASS);
     //trying to fetch more entries than the $entryCount limit
     $c->setMaxRecords(self::ENTRIES_PER_ACCESS_CONTROL_UPDATE_LIMIT + 1);
     $c->add(entryPeer::ACCESS_CONTROL_ID, $oldAccessControlId);
     $partner = PartnerPeer::retrieveByPK($partnerId);
     $partnerEntitlement = $partner->getDefaultEntitlementEnforcement();
     kEntitlementUtils::initEntitlementEnforcement($partnerId, false);
     $entries = self::doSelect($c);
     $entryCount = count($entries);
     if ($entryCount == 0) {
         return;
     }
     if ($entryCount > self::ENTRIES_PER_ACCESS_CONTROL_UPDATE_LIMIT) {
         throw new kCoreException("exceeded max entries per access control update limit", kCoreException::EXCEEDED_MAX_ENTRIES_PER_ACCESS_CONTROL_UPDATE_LIMIT);
     }
     $entryIds = array();
     foreach ($entries as $entry) {
         $entryIds[] = $entry->getId();
     }
     $selectCriteria = new Criteria();
     $selectCriteria->add(entryPeer::PARTNER_ID, $partnerId);
     $selectCriteria->add(entryPeer::ID, $entryIds, Criteria::IN);
     $updateValues = new Criteria();
     $updateValues->add(entryPeer::ACCESS_CONTROL_ID, $newAccessControlId);
     $con = Propel::getConnection(self::DATABASE_NAME);
     BasePeer::doUpdate($selectCriteria, $updateValues, $con);
     foreach ($entries as $entry) {
         kEventsManager::raiseEventDeferred(new kObjectReadyForIndexEvent($entry));
     }
     if ($partnerEntitlement) {
         kEntitlementUtils::initEntitlementEnforcement($partnerId, true);
     }
 }
Exemplo n.º 4
0
 protected function initEntry()
 {
     $this->entryId = $this->getRequestParameter("entryId", null);
     // look for a valid token
     $expiry = $this->getRequestParameter("expiry");
     if ($expiry && $expiry <= time()) {
         KExternalErrors::dieError(KExternalErrors::EXPIRED_TOKEN);
     }
     $urlToken = $this->getRequestParameter("kt");
     if ($urlToken) {
         if ($_SERVER["REQUEST_METHOD"] != "GET" || !self::validateKalturaToken($_SERVER["REQUEST_URI"], $urlToken)) {
             KExternalErrors::dieError(KExternalErrors::INVALID_TOKEN);
         }
     }
     // initalize the context
     $ksStr = $this->getRequestParameter("ks");
     if ($ksStr && !$urlToken) {
         try {
             kCurrentContext::initKsPartnerUser($ksStr);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $this->entry = kCurrentContext::initPartnerByEntryId($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     // no need for any further check if a token was used
     if ($urlToken) {
         return;
     }
     // enforce entitlement
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$this->entry) {
         $this->entry = entryPeer::retrieveByPKNoFilter($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($this->entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     myPartnerUtils::blockInactivePartner($this->entry->getPartnerId());
     // enforce access control
     $base64Referrer = $this->getRequestParameter("referrer");
     $hashes = $this->getRequestParameter("hashes");
     $keyValueHashes = array();
     if ($hashes) {
         $hashes = urldecode($hashes);
         $hashes = explode(",", $hashes);
         foreach ($hashes as $keyValueHashString) {
             list($key, $value) = explode('=', $keyValueHashString);
             $keyValueHashes[$key] = $value;
         }
     }
     // replace space in the base64 string with + as space is invalid in base64 strings and caused
     // by symfony calling str_parse to replace + with spaces.
     // this happens only with params passed in the url path and not the query strings. specifically the ~ char at
     // a columns divided by 3 causes this issue (e.g. http://www.xyzw.com/~xxx)
     //replace also any - with + and _ with /
     $referrer = base64_decode(str_replace(array('-', '_', ' '), array('+', '/', '+'), $base64Referrer));
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     $this->secureEntryHelper = new KSecureEntryHelper($this->entry, $ksStr, $referrer, ContextType::PLAY, $keyValueHashes);
     if ($this->secureEntryHelper->shouldPreview()) {
         $previewLengthInMsecs = $this->secureEntryHelper->getPreviewLength() * 1000;
         $entryLengthInMsecs = $this->entry->getLengthInMsecs();
         if ($previewLengthInMsecs < $entryLengthInMsecs) {
             $this->deliveryAttributes->setClipTo($previewLengthInMsecs);
         }
     } else {
         $this->secureEntryHelper->validateForPlay();
     }
     if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENTITLEMENT, $this->entry->getPartnerId()) || $this->secureEntryHelper->hasRules()) {
         $this->forceUrlTokenization = true;
     }
 }
Exemplo n.º 5
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $entryId = $this->getRequestParameter("entry_id");
     $flavorId = $this->getRequestParameter("flavor");
     $fileName = $this->getRequestParameter("file_name");
     $fileName = basename($fileName);
     $ksStr = $this->getRequestParameter("ks");
     $referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $entry = null;
     if ($ksStr) {
         try {
             kCurrentContext::initKsPartnerUser($ksStr);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entryId);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$entry) {
         $entry = entryPeer::retrieveByPK($entryId);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.download', $entry->getPartnerId());
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     $shouldPreview = false;
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, ContextType::DOWNLOAD);
     if ($securyEntryHelper->shouldPreview()) {
         $shouldPreview = true;
     } else {
         $securyEntryHelper->validateForDownload();
     }
     $flavorAsset = null;
     if ($flavorId) {
         // get flavor asset
         $flavorAsset = assetPeer::retrieveById($flavorId);
         if (is_null($flavorAsset) || !$flavorAsset->isLocalReadyStatus()) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
         // the request flavor should belong to the requested entry
         if ($flavorAsset->getEntryId() != $entryId) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
         if (!$securyEntryHelper->isAssetAllowed($flavorAsset)) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
     } else {
         $flavorAssets = assetPeer::retrieveReadyWebByEntryId($entry->getId());
         foreach ($flavorAssets as $curFlavorAsset) {
             if ($securyEntryHelper->isAssetAllowed($curFlavorAsset)) {
                 $flavorAsset = $curFlavorAsset;
                 break;
             }
         }
     }
     // Gonen 26-04-2010: in case entry has no flavor with 'mbr' tag - we return the source
     if (!$flavorAsset && ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO)) {
         $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId);
         if (!$securyEntryHelper->isAssetAllowed($flavorAsset)) {
             $flavorAsset = null;
         }
     }
     if ($flavorAsset) {
         $syncKey = $this->getSyncKeyAndForFlavorAsset($entry, $flavorAsset);
     } else {
         $syncKey = $this->getBestSyncKeyForEntry($entry);
     }
     if (is_null($syncKey)) {
         KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
     }
     $this->handleFileSyncRedirection($syncKey);
     $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     list($fileBaseName, $fileExt) = kAssetUtils::getFileName($entry, $flavorAsset);
     if (!$fileName) {
         $fileName = $fileBaseName;
     }
     if ($fileExt && !is_dir($filePath)) {
         $fileName = $fileName . '.' . $fileExt;
     }
     $preview = 0;
     if ($shouldPreview && $flavorAsset) {
         $preview = $flavorAsset->estimateFileSize($entry, $securyEntryHelper->getPreviewLength());
     } else {
         if (kCurrentContext::$ks_object) {
             $preview = kCurrentContext::$ks_object->getPrivilegeValue(kSessionBase::PRIVILEGE_PREVIEW, 0);
         }
     }
     //enable downloading file_name which inside the flavor asset directory
     if (is_dir($filePath)) {
         $filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
     }
     $this->dumpFile($filePath, $fileName, $preview);
     KExternalErrors::dieGracefully();
     // no view
 }
Exemplo n.º 6
0
 public function execute()
 {
     requestUtils::handleConditionalGet();
     $entry_id = $this->getRequestParameter("entry_id");
     $ks_str = $this->getRequestParameter("ks");
     $base64_referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64_referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $clip_from = $this->getRequestParameter("clip_from", 0);
     // milliseconds
     $clip_to = $this->getRequestParameter("clip_to", 2147483647);
     // milliseconds
     if ($clip_to == 0) {
         $clip_to = 2147483647;
     }
     $request = $_SERVER["REQUEST_URI"];
     // remove dynamic fields from the url so we'll request a single url from the cdn
     $request = str_replace("/referrer/{$base64_referrer}", "", $request);
     $request = str_replace("/ks/{$ks_str}", "", $request);
     $entry = null;
     if ($ks_str) {
         try {
             kCurrentContext::initKsPartnerUser($ks_str);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entry_id);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     // workaround the filter which hides all the deleted entries -
     // now that deleted entries are part of xmls (they simply point to the 'deleted' templates), we should allow them here
     if (!$entry) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     if (!$entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     KalturaMonitorClient::initApiMonitor(false, 'keditorservices.flvclipper', $entry->getPartnerId());
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_BLOCK_FLVCLIPPER_ACTION, $entry->getPartnerId())) {
         KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED);
     }
     // set the memory size to be able to serve big files in a single chunk
     ini_set("memory_limit", "64M");
     // set the execution time to be able to serve big files in a single chunk
     ini_set("max_execution_time", 240);
     if ($entry->getType() == entryType::MIX && $entry->getStatus() == entryStatus::DELETED) {
         // because the fiter was turned off - a manual check for deleted entries must be done.
         KExternalErrors::dieGracefully();
     } else {
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
             $version = $this->getRequestParameter("version", null);
             $width = $this->getRequestParameter("width", -1);
             $height = $this->getRequestParameter("height", -1);
             $crop_provider = $this->getRequestParameter("crop_provider", null);
             $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
             $type = $this->getRequestParameter("type", 1);
             $quality = $this->getRequestParameter("quality", 0);
             $src_x = $this->getRequestParameter("src_x", 0);
             $src_y = $this->getRequestParameter("src_y", 0);
             $src_w = $this->getRequestParameter("src_w", 0);
             $src_h = $this->getRequestParameter("src_h", 0);
             $vid_sec = $this->getRequestParameter("vid_sec", -1);
             $vid_slice = $this->getRequestParameter("vid_slice", -1);
             $vid_slices = $this->getRequestParameter("vid_slices", -1);
             if ($width == -1 && $height == -1) {
                 $width = 640;
                 $height = 480;
             } else {
                 if ($width == -1) {
                     // if only either width or height is missing reset them to zero, and convertImage will handle them
                     $width = 0;
                 } else {
                     if ($height == -1) {
                         $height = 0;
                     }
                 }
             }
             $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices);
             kFileUtils::dumpFile($tempThumbPath, null, strpos($tempThumbPath, "_NOCACHE_") === false ? null : 0);
         }
     }
     $audio_only = $this->getRequestParameter("audio_only");
     // milliseconds
     $flavor = $this->getRequestParameter("flavor", 1);
     //
     $flavor_param_id = $this->getRequestParameter("flavor_param_id", null);
     //
     $streamer = $this->getRequestParameter("streamer");
     //
     if (substr($streamer, 0, 4) == "rtmp") {
         // the fms may add .mp4 to the end of the url
         $streamer = "rtmp";
     }
     // grab seek_from_bytes parameter and normalize url
     $seek_from_bytes = $this->getRequestParameter("seek_from_bytes", -1);
     $request = str_replace("/seek_from_bytes/{$seek_from_bytes}", "", $request);
     if ($seek_from_bytes <= 0) {
         $seek_from_bytes = -1;
     }
     // grab seek_from parameter and normalize url
     $seek_from = $this->getRequestParameter("seek_from", -1);
     $request = str_replace("/seek_from/{$seek_from}", "", $request);
     if ($seek_from <= 0) {
         $seek_from = -1;
     }
     $this->dump_from_byte = 0;
     // reset accurate seek from timestamp
     $seek_from_timestamp = -1;
     // backward compatibility
     if ($flavor === "0") {
         // for edit version
         $flavor = "edit";
     }
     if ($flavor === "1" || $flavor === 1) {
         // for play version
         $flavor = null;
     }
     // when flavor is null, we will get a default flavor
     if ($flavor == "edit") {
         $flavorAsset = assetPeer::retrieveBestEditByEntryId($entry->getId());
     } elseif (!is_null($flavor)) {
         $flavorAsset = assetPeer::retrieveById($flavor);
         // when specific asset was request, we don't validate its tags
         if ($flavorAsset && ($flavorAsset->getEntryId() != $entry->getId() || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY)) {
             $flavorAsset = null;
         }
         // we will throw an error later
     } elseif (is_null($flavor) && !is_null($flavor_param_id)) {
         $flavorAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $flavor_param_id);
         if ($flavorAsset && $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             $flavorAsset = null;
         }
         // we will throw an error later
     } else {
         if ($entry->getSource() == entry::ENTRY_MEDIA_SOURCE_WEBCAM) {
             $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
         } else {
             $flavorAsset = assetPeer::retrieveBestPlayByEntryId($entry->getId());
         }
         if (!$flavorAsset) {
             $flavorAssets = assetPeer::retrieveReadyFlavorsByEntryIdAndTag($entry->getId(), flavorParams::TAG_WEB);
             if (count($flavorAssets) > 0) {
                 $flavorAsset = $flavorAssets[0];
             }
         }
     }
     if (is_null($flavorAsset)) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     if (kFileSyncUtils::file_exists($syncKey, false)) {
         $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     } else {
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if (is_null($fileSync)) {
             KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]");
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
         if ($fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) {
             $urlManager = DeliveryProfilePeer::getRemoteDeliveryByStorageId(DeliveryProfileDynamicAttributes::init($fileSync->getDc(), $flavorAsset->getEntryId()), null, $flavorAsset);
             if (!$urlManager) {
                 KalturaLog::log("Error - failed to find an HTTP delivery for storage profile [" . $fileSync->getDc() . "]");
                 KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
             }
             $url = rtrim($urlManager->getUrl(), '/') . '/' . ltrim($urlManager->getFileSyncUrl($fileSync), '/');
             header('location: ' . $url);
             die;
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         $this->redirect($remoteUrl);
     }
     $flv_wrapper = new myFlvHandler($path);
     $isFlv = $flv_wrapper->isFlv();
     // scrubbing is not allowed within mp4 files
     if (!$isFlv) {
         $seek_from = $seek_from_bytes = -1;
     }
     if ($seek_from !== -1 && $seek_from !== 0) {
         if ($audio_only === '0') {
             // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations
         } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) {
             $audio_only = true;
         }
         list($bytes, $duration, $first_tag_byte, $to_byte) = $flv_wrapper->clip(0, -1, $audio_only);
         list($bytes, $duration, $from_byte, $to_byte, $seek_from_timestamp) = $flv_wrapper->clip($seek_from, -1, $audio_only);
         $seek_from_bytes = myFlvHandler::FLV_HEADER_SIZE + $flv_wrapper->getMetadataSize($audio_only) + $from_byte - $first_tag_byte;
     }
     // the direct path without a cdn is "http://s3kaltura.s3.amazonaws.com".$entry->getDataPath();
     $extStorageUrl = $entry->getExtStorageUrl();
     if ($extStorageUrl && substr_count($extStorageUrl, 's3kaltura')) {
         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
         if ($seek_from_timestamp == -1) {
             $seek_from_timestamp = $seek_from;
         }
         $request_host = parse_url($extStorageUrl, PHP_URL_HOST);
         $akamai_url = str_replace($request_host, "cdns3akmi.kaltura.com", $extStorageUrl);
         $akamai_url .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000);
         header("Location: {$akamai_url}");
         KExternalErrors::dieGracefully();
     } elseif ($extStorageUrl) {
         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
         if ($seek_from_timestamp == -1) {
             $seek_from_timestamp = $seek_from;
         }
         $extStorageUrl .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000);
         header("Location: {$extStorageUrl}");
         KExternalErrors::dieGracefully();
     }
     // use headers to detect cdn
     $cdn_name = "";
     $via_header = @$_SERVER["HTTP_VIA"];
     if (strpos($via_header, "llnw.net") !== false) {
         $cdn_name = "limelight";
     } else {
         if (strpos($via_header, "akamai") !== false) {
             $cdn_name = "akamai";
         } else {
             if (strpos($via_header, "Level3") !== false) {
                 $cdn_name = "level3";
             }
         }
     }
     // setting file extension - first trying frrom flavor asset
     $ext = $flavorAsset->getFileExt();
     // if failed, set extension according to file type (isFlv)
     if (!$ext) {
         $ext = $isFlv ? "flv" : "mp4";
     }
     $flv_extension = $streamer == "rtmp" ? "?" : "/a.{$ext}?novar=0";
     // dont check for rtmp / and for an already redirect url
     if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) {
         // check security using ks
         $securyEntryHelper = new KSecureEntryHelper($entry, $ks_str, $referrer, ContextType::PLAY);
         if ($securyEntryHelper->shouldPreview()) {
             $this->checkForPreview($securyEntryHelper, $clip_to);
         } else {
             $securyEntryHelper->validateForPlay($entry, $ks_str);
         }
     } else {
         // if needs security check using cdn authentication mechanism
         // for now assume this is a cdn request and don't check for security
     }
     // use limelight mediavault if either security policy requires it or if we're trying to seek within the video
     if ($entry->getSecurityPolicy() || $seek_from_bytes !== -1) {
         // we have three options:
         // arrived through limelight mediavault url - the url is secured
         // arrived directly through limelight (not secured through mediavault) - enforce ks and redirect to mediavault url
         // didnt use limelight - enforce ks
         // the cdns are configured to authenticate request for /s/....
         // check if we're already in a redirected secure link using the "/s/" prefix
         $secure_request = substr($request, 0, 3) == "/s/";
         if ($secure_request && ($cdn_name == "limelight" || $cdn_name == "level3")) {
             // request was validated by cdn let it through
         } else {
             // extract ks
             $ks_str = $this->getRequestParameter("ks", "");
             if ($entry->getSecurityPolicy()) {
                 if (!$ks_str) {
                     $this->logMessage("flvclipper - no KS");
                     KExternalErrors::dieGracefully();
                 }
                 $ks = kSessionUtils::crackKs($ks_str);
                 if (!$ks) {
                     $this->logMessage("flvclipper - invalid ks [{$ks_str}]");
                     KExternalErrors::dieGracefully();
                 }
                 $matched_privs = $ks->verifyPrivileges("sview", $entry_id);
                 $this->logMessage("flvclipper - verifyPrivileges name [sview], priv [{$entry_id}] [{$matched_privs}]");
                 if (!$matched_privs) {
                     $this->logMessage("flvclipper - doesnt not match required privlieges [{$ks_str}]");
                     KExternalErrors::dieGracefully();
                 }
             }
             if ($cdn_name == "limelight") {
                 $ll_url = requestUtils::getCdnHost() . "/s{$request}" . $flv_extension;
                 $secret = kConf::get("limelight_madiavault_password");
                 $expire = "&e=" . (time() + 120);
                 $ll_url .= $expire;
                 $fs = $seek_from_bytes == -1 ? "" : "&fs={$seek_from_bytes}";
                 $ll_url .= "&h=" . md5("{$secret}{$ll_url}") . $fs;
                 //header("Location: $ll_url");
                 $this->redirect($ll_url);
             } else {
                 if ($cdn_name == "level3") {
                     $level3_url = $request . $flv_extension;
                     if ($entry->getSecurityPolicy()) {
                         $level3_url = "/s{$level3_url}";
                         // set expire time in GMT hence the date("Z") offset
                         $expire = "&nva=" . strftime("%Y%m%d%H%M%S", time() - date("Z") + 30);
                         $level3_url .= $expire;
                         $secret = kConf::get("level3_authentication_key");
                         $hash = "0" . substr(self::hmac('sha1', $secret, $level3_url), 0, 20);
                         $level3_url .= "&h={$hash}";
                     }
                     $level3_url .= $seek_from_bytes == -1 ? "" : "&start={$seek_from_bytes}";
                     header("Location: {$level3_url}");
                     KExternalErrors::dieGracefully();
                 } else {
                     if ($cdn_name == "akamai") {
                         $akamai_url = $request . $flv_extension;
                         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
                         if ($seek_from_timestamp == -1) {
                             $seek_from_timestamp = $seek_from;
                         }
                         $akamai_url .= $seek_from_bytes == -1 ? "" : "&aktimeoffset=" . floor($seek_from_timestamp / 1000);
                         header("Location: {$akamai_url}");
                         KExternalErrors::dieGracefully();
                     }
                 }
             }
             // a seek request without a supporting cdn - we need to send the answer from our server
             if ($seek_from_bytes !== -1 && $via_header === null) {
                 $this->dump_from_byte = $seek_from_bytes;
             }
         }
     }
     // always add the file suffix to the request (needed for scrubbing by some cdns,
     // and also breaks without extension on some corporate antivirus).
     // we add the the novar paramter since a leaving a trailing "?" will be trimmed
     // and then the /seek_from request will result in another url which level3
     // will try to refetch from the origin
     // note that for streamer we dont add the file extension
     if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) {
         // a seek request without a supporting cdn - we need to send the answer from our server
         if ($seek_from_bytes !== -1 && $via_header === null) {
             $request .= "/seek_from_bytes/{$seek_from_bytes}";
         }
         requestUtils::sendCdnHeaders("flv", 0);
         header("Location: {$request}" . $flv_extension);
         KExternalErrors::dieGracefully();
     }
     // mp4
     if (!$isFlv) {
         $limit_file_size = 0;
         if ($clip_to != 2147483647) {
             $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId());
             if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) {
                 $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration());
                 $limit_file_size = floor(@kFile::fileSize($path) * ($clip_to / $duration) * 1.2);
             }
         }
         KalturaLog::info("serving file [{$path}] entry id [{$entry_id}] limit file size [{$limit_file_size}] clip_to [{$clip_to}]");
         kFileUtils::dumpFile($path, null, null, $limit_file_size);
     }
     $this->logMessage("flvclipperAction: serving file [{$path}] entry_id [{$entry_id}] clip_from [{$clip_from}] clip_to [{$clip_to}]", "warning");
     if ($audio_only === '0') {
         // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations
     } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) {
         $audio_only = true;
     }
     //$start = microtime(true);
     list($bytes, $duration, $from_byte, $to_byte, $from_ts, $cuepoint_pos) = myFlvStaticHandler::clip($path, $clip_from, $clip_to, $audio_only);
     $metadata_size = $flv_wrapper->getMetadataSize($audio_only);
     $this->from_byte = $from_byte;
     $this->to_byte = $to_byte;
     //$end1 = microtime(true);
     //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" );
     //$this->logMessage( "flvclipperAction: serving file [$path] t1 [" . ( $end1-$start) . "]");
     $data_offset = $metadata_size + myFlvHandler::getHeaderSize();
     // if we're returning a partial file adjust the total size:
     // substract the metadata and bytes which are not delivered
     if ($this->dump_from_byte >= $data_offset && !$audio_only) {
         $bytes -= $metadata_size + max(0, $this->dump_from_byte - $data_offset);
     }
     $this->total_length = $data_offset + $bytes;
     //echo " $bytes , $duration ,$from_byte , $to_byte, $cuepoint_pos\n"; die;
     $this->cuepoint_time = 0;
     $this->cuepoint_pos = 0;
     if ($streamer == "chunked" && $clip_to != 2147483647) {
         $this->cuepoint_time = $clip_to - 1;
         $this->cuepoint_pos = $cuepoint_pos;
         $this->total_length += myFlvHandler::CUEPOINT_TAG_SIZE;
     }
     //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes with header & md [" . $this->total_length . "] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" );
     $this->flv_wrapper = $flv_wrapper;
     $this->audio_only = $audio_only;
     try {
         Propel::close();
     } catch (Exception $e) {
         $this->logMessage("flvclipperAction: error closing db {$e}");
     }
     KExternalErrors::terminateDispatch();
     return sfView::SUCCESS;
 }
Exemplo n.º 7
0
 private function getFlavorAssetObject($flavorAssetId)
 {
     try {
         if (!kCurrentContext::$ks) {
             $flavorAsset = kCurrentContext::initPartnerByAssetId($flavorAssetId);
             // enforce entitlement
             $this->setPartnerFilters(kCurrentContext::getCurrentPartnerId());
             kEntitlementUtils::initEntitlementEnforcement();
         } else {
             $flavorAsset = assetPeer::retrieveById($flavorAssetId);
         }
         if (!$flavorAsset || $flavorAsset->getStatus() == asset::ASSET_STATUS_DELETED) {
             throw new KalturaWidevineLicenseProxyException(KalturaWidevineErrorCodes::FLAVOR_ASSET_ID_NOT_FOUND);
         }
         return $flavorAsset;
     } catch (PropelException $e) {
         throw new KalturaWidevineLicenseProxyException(KalturaWidevineErrorCodes::FLAVOR_ASSET_ID_NOT_FOUND);
     }
 }
 /**
  * Serve XML rendition of the Kaltura Live Transcoding Profile usable by the Wowza transcoding add-on
  * 
  * @action serve
  * @param string $streamName the id of the live entry with it's stream suffix
  * @param string $hostname the media server host name
  * @return file
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @throws WowzaErrors::INVALID_STREAM_NAME
  */
 public function serveAction($streamName, $hostname = null)
 {
     $matches = null;
     if (!preg_match('/^(\\d_.{8})_(\\d+)$/', $streamName, $matches)) {
         throw new KalturaAPIException(WowzaErrors::INVALID_STREAM_NAME, $streamName);
     }
     $entryId = $matches[1];
     $suffix = $matches[2];
     $entry = null;
     if (!kCurrentContext::$ks) {
         kEntitlementUtils::initEntitlementEnforcement(null, false);
         $entry = kCurrentContext::initPartnerByEntryId($entryId);
         if (!$entry || $entry->getStatus() == entryStatus::DELETED) {
             throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
         }
         // enforce entitlement
         $this->setPartnerFilters(kCurrentContext::getCurrentPartnerId());
     } else {
         $entry = entryPeer::retrieveByPK($entryId);
     }
     if (!$entry || $entry->getType() != KalturaEntryType::LIVE_STREAM || !in_array($entry->getSource(), array(KalturaSourceType::LIVE_STREAM, KalturaSourceType::LIVE_STREAM_ONTEXTDATA_CAPTIONS))) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $mediaServer = null;
     if ($hostname) {
         $mediaServer = MediaServerPeer::retrieveByHostname($hostname);
     }
     $conversionProfileId = $entry->getConversionProfileId();
     $liveParams = assetParamsPeer::retrieveByProfile($conversionProfileId);
     $liveParamsInput = null;
     $disableIngested = true;
     foreach ($liveParams as $liveParamsItem) {
         /* @var $liveParamsItem liveParams */
         if ($liveParamsItem->getStreamSuffix() == $suffix) {
             $liveParamsInput = $liveParamsItem;
             if (!$liveParamsInput->hasTag(assetParams::TAG_SOURCE)) {
                 $liveParams = array($liveParamsInput);
                 $disableIngested = false;
             }
             break;
         }
     }
     $ignoreLiveParamsIds = array();
     if ($disableIngested) {
         $conversionProfileAssetParams = flavorParamsConversionProfilePeer::retrieveByConversionProfile($conversionProfileId);
         foreach ($conversionProfileAssetParams as $conversionProfileAssetParamsItem) {
             /* @var $conversionProfileAssetParamsItem flavorParamsConversionProfile */
             if ($conversionProfileAssetParamsItem->getOrigin() == assetParamsOrigin::INGEST) {
                 $ignoreLiveParamsIds[] = $conversionProfileAssetParamsItem->getFlavorParamsId();
             }
         }
     }
     // translate the $liveParams to XML according to doc: http://www.wowza.com/forums/content.php?304#configTemplate
     $root = new SimpleXMLElement('<Root/>');
     $transcode = $root->addChild('Transcode');
     $encodes = $transcode->addChild('Encodes');
     $groups = array();
     foreach ($liveParams as $liveParamsItem) {
         /* @var $liveParamsItem liveParams */
         if (!$liveParamsItem->hasTag(assetParams::TAG_SOURCE) && in_array($liveParamsItem->getId(), $ignoreLiveParamsIds)) {
             continue;
         }
         $this->appendLiveParams($entry, $mediaServer, $encodes, $liveParamsItem);
         $tags = $liveParamsItem->getTagsArray();
         $tags[] = 'all';
         foreach ($tags as $tag) {
             if (!isset($groups[$tag])) {
                 $groups[$tag] = array();
             }
             $systemName = $liveParamsItem->getSystemName() ? $liveParamsItem->getSystemName() : $liveParamsItem->getId();
             $groups[$tag][] = $systemName;
         }
     }
     $decode = $transcode->addChild('Decode');
     $video = $decode->addChild('Video');
     $video->addChild('Deinterlace', 'false');
     $streamNameGroups = $transcode->addChild('StreamNameGroups');
     foreach ($groups as $groupName => $groupMembers) {
         $streamNameGroup = $streamNameGroups->addChild('StreamNameGroup');
         $streamNameGroup->addChild('Name', $groupName);
         $streamNameGroup->addChild('StreamName', '${SourceStreamName}_' . $groupName);
         $members = $streamNameGroup->addChild('Members');
         foreach ($groupMembers as $groupMember) {
             $member = $members->addChild('Member');
             $member->addChild('EncodeName', $groupMember);
         }
     }
     $properties = $transcode->addChild('Properties');
     $dom = new DOMDocument("1.0");
     $dom->preserveWhiteSpace = false;
     $dom->formatOutput = true;
     $dom->loadXML($root->asXML());
     return new kRendererString($dom->saveXML(), 'text/xml');
 }
Exemplo n.º 9
0
 /**
  * Serves thumbnail by its id
  *  
  * @action serve
  * @param string $thumbAssetId
  * @param int $version
  * @param KalturaThumbParams $thumbParams
  * @param KalturaThumbnailServeOptions $options
  * @return file
  *  
  * @throws KalturaErrors::THUMB_ASSET_IS_NOT_READY
  * @throws KalturaErrors::THUMB_ASSET_ID_NOT_FOUND
  */
 public function serveAction($thumbAssetId, $version = null, KalturaThumbParams $thumbParams = null, KalturaThumbnailServeOptions $options = null)
 {
     if (!kCurrentContext::$ks) {
         $thumbAsset = kCurrentContext::initPartnerByAssetId($thumbAssetId);
         if (!$thumbAsset || $thumbAsset->getStatus() == asset::ASSET_STATUS_DELETED) {
             throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_ID_NOT_FOUND, $thumbAssetId);
         }
         // enforce entitlement
         $this->setPartnerFilters(kCurrentContext::getCurrentPartnerId());
         kEntitlementUtils::initEntitlementEnforcement();
     } else {
         $thumbAsset = assetPeer::retrieveById($thumbAssetId);
     }
     if (!$thumbAsset || !$thumbAsset instanceof thumbAsset) {
         throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_ID_NOT_FOUND, $thumbAssetId);
     }
     $entry = entryPeer::retrieveByPK($thumbAsset->getEntryId());
     if (!$entry) {
         //we will throw thumb asset not found, as the user is not entitled, and should not know that the entry exists.
         throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_ID_NOT_FOUND, $thumbAssetId);
     }
     $securyEntryHelper = new KSecureEntryHelper($entry, kCurrentContext::$ks, null, ContextType::THUMBNAIL);
     $securyEntryHelper->validateAccessControl();
     $ext = $thumbAsset->getFileExt();
     if (is_null($ext)) {
         $ext = 'jpg';
     }
     $fileName = $thumbAsset->getEntryId() . "_" . $thumbAsset->getId() . ".{$ext}";
     if (!$thumbParams) {
         if ($options && $options->download) {
             header("Content-Disposition: attachment; filename=\"{$fileName}\"");
         }
         return $this->serveAsset($thumbAsset, $fileName, $version);
     }
     $thumbParams->validate();
     $syncKey = $thumbAsset->getSyncKey(asset::FILE_SYNC_ASSET_SUB_TYPE_ASSET, $version);
     if (!kFileSyncUtils::fileSync_exists($syncKey)) {
         throw new KalturaAPIException(KalturaErrors::FILE_DOESNT_EXIST);
     }
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     /* @var $fileSync FileSync */
     if (!$local) {
         if (!in_array($fileSync->getDc(), kDataCenterMgr::getDcIds())) {
             throw new KalturaAPIException(KalturaErrors::FILE_DOESNT_EXIST);
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         KalturaLog::info("Redirecting to [{$remoteUrl}]");
         header("Location: {$remoteUrl}");
         die;
     }
     $filePath = $fileSync->getFullPath();
     $thumbVersion = $thumbAsset->getId() . '_' . $version;
     $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $thumbVersion, $thumbParams->width, $thumbParams->height, $thumbParams->cropType, $thumbParams->backgroundColor, null, $thumbParams->quality, $thumbParams->cropX, $thumbParams->cropY, $thumbParams->cropWidth, $thumbParams->cropHeight, -1, 0, -1, $filePath, $thumbParams->density, $thumbParams->stripProfiles, null);
     if ($options && $options->download) {
         header("Content-Disposition: attachment; filename=\"{$fileName}\"");
     }
     $mimeType = kFile::mimeType($tempThumbPath);
     return $this->dumpFile($tempThumbPath, $mimeType);
 }
 /**
  * Serves thumbnail by its id
  *  
  * @action serve
  * @param string $thumbAssetId
  * @param int $version
  * @return file
  *  
  * @throws KalturaErrors::THUMB_ASSET_IS_NOT_READY
  * @throws KalturaErrors::THUMB_ASSET_ID_NOT_FOUND
  */
 public function serveAction($thumbAssetId, $version = null)
 {
     if (!kCurrentContext::$ks) {
         $thumbAsset = kCurrentContext::initPartnerByAssetId($thumbAssetId);
         if (!$thumbAsset || $thumbAsset->getStatus() == asset::ASSET_STATUS_DELETED) {
             throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_ID_NOT_FOUND, $thumbAssetId);
         }
         // enforce entitlement
         kEntitlementUtils::initEntitlementEnforcement();
     } else {
         $thumbAsset = assetPeer::retrieveById($thumbAssetId);
     }
     if (!$thumbAsset || !$thumbAsset instanceof thumbAsset) {
         throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_ID_NOT_FOUND, $thumbAssetId);
     }
     $entry = entryPeer::retrieveByPK($thumbAsset->getEntryId());
     if (!$entry) {
         //we will throw thumb asset not found, as the user is not entitled, and should not know that the entry exists.
         throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_ID_NOT_FOUND, $thumbAssetId);
     }
     $securyEntryHelper = new KSecureEntryHelper($entry, kCurrentContext::$ks, null, accessControlContextType::THUMBNAIL);
     $securyEntryHelper->validateAccessControl();
     $ext = $thumbAsset->getFileExt();
     if (is_null($ext)) {
         $ext = 'jpg';
     }
     $fileName = $thumbAsset->getEntryId() . "_" . $thumbAsset->getId() . ".{$ext}";
     return $this->serveAsset($thumbAsset, $fileName, $version);
 }
Exemplo n.º 11
0
 /**
  * @param entry $entry
  * @param SimpleXMLElement $mrss
  * @param kMrssParameters $mrssParams
  * @params string $features
  * @return SimpleXMLElement
  */
 public static function getEntryMrssXml(entry $entry, SimpleXMLElement $mrss = null, kMrssParameters $mrssParams = null, $features = null)
 {
     $instanceKey = self::generateInstanceKey($entry->getId(), $mrssParams, $features);
     if (is_null($mrss)) {
         $mrss = self::getInstanceFromPool($instanceKey);
         if ($mrss) {
             return $mrss;
         }
         $encoding = 'UTF-8';
         if ($mrssParams && !is_null($mrssParams->getEncoding())) {
             $encoding = $mrssParams->getEncoding();
         }
         if ($encoding) {
             $mrss = new SimpleXMLElement('<?xml version="1.0" encoding="' . $encoding . '"?><item/>');
         } else {
             $mrss = new SimpleXMLElement('<item/>');
         }
     }
     $mrss->addChild('entryId', $entry->getId());
     if ($entry->getReferenceID()) {
         $mrss->addChild('referenceID', self::stringToSafeXml($entry->getReferenceID()));
     }
     $mrss->addChild('createdAt', $entry->getCreatedAt(null));
     $mrss->addChild('updatedAt', $entry->getUpdatedAt(null));
     $mrss->addChild('title', self::stringToSafeXml($entry->getName()));
     if ($mrssParams && !is_null($mrssParams->getLink())) {
         $mrss->addChild('link', $mrssParams->getLink() . $entry->getId());
     }
     $mrss->addChild('type', $entry->getType());
     $mrss->addChild('licenseType', $entry->getLicenseType());
     $mrss->addChild('userId', $entry->getPuserId());
     $mrss->addChild('name', self::stringToSafeXml($entry->getName()));
     $mrss->addChild('status', self::stringToSafeXml($entry->getStatus()));
     $mrss->addChild('description', self::stringToSafeXml($entry->getDescription()));
     $thumbnailUrl = $mrss->addChild('thumbnailUrl');
     $thumbnailUrl->addAttribute('url', $entry->getThumbnailUrl());
     if (trim($entry->getTags(), " \r\n\t")) {
         $tags = $mrss->addChild('tags');
         foreach (explode(',', $entry->getTags()) as $tag) {
             $tags->addChild('tag', self::stringToSafeXml($tag));
         }
     }
     $categories = explode(',', $entry->getCategories());
     if (count($features) && in_array(ObjectFeatureType::CATEGORY_ENTRIES, $features)) {
         $partner = PartnerPeer::retrieveByPK(kCurrentContext::getCurrentPartnerId());
         $partnerEntitlement = $partner->getDefaultEntitlementEnforcement();
         kEntitlementUtils::initEntitlementEnforcement($partner->getId(), false);
         $categories = array();
         $categoryEntries = categoryEntryPeer::retrieveActiveByEntryId($entry->getId());
         $categoryIds = array();
         foreach ($categoryEntries as $categoryEntry) {
             $categoryIds[] = $categoryEntry->getCategoryId();
         }
         $entryCats = categoryPeer::retrieveByPKs($categoryIds);
         foreach ($entryCats as $entryCat) {
             $categories[] = $entryCat->getFullName();
         }
         if ($partnerEntitlement) {
             kEntitlementUtils::initEntitlementEnforcement($partner->getId(), true);
         }
         $keyToDelete = array_search(ObjectFeatureType::CATEGORY_ENTRIES, $features);
         unset($features[$keyToDelete]);
     }
     foreach ($categories as $category) {
         $category = trim($category);
         if ($category) {
             $categoryNode = $mrss->addChild('category', self::stringToSafeXml($category));
             if (strrpos($category, '>') > 0) {
                 $categoryNode->addAttribute('name', self::stringToSafeXml(substr($category, strrpos($category, '>') + 1)));
             } else {
                 $categoryNode->addAttribute('name', self::stringToSafeXml($category));
             }
         }
     }
     $mrss->addChild('partnerData', self::stringToSafeXml($entry->getPartnerData()));
     if ($entry->getAccessControlId()) {
         $mrss->addChild('accessControlId', $entry->getAccessControlId());
     }
     if ($entry->getConversionProfileId()) {
         $mrss->addChild('conversionProfileId', $entry->getConversionProfileId());
     }
     if ($entry->getStartDate(null)) {
         $mrss->addChild('startDate', $entry->getStartDate(null));
     }
     if ($entry->getEndDate(null)) {
         $mrss->addChild('endDate', $entry->getEndDate(null));
     }
     switch ($entry->getType()) {
         case entryType::MEDIA_CLIP:
             self::appendMediaEntryMrss($entry, $mrss);
             break;
         case entryType::MIX:
             self::appendMixEntryMrss($entry, $mrss);
             break;
         case entryType::PLAYLIST:
             self::appendPlaylistEntryMrss($entry, $mrss);
             break;
         case entryType::DATA:
             self::appendDataEntryMrss($entry, $mrss);
             break;
         case entryType::LIVE_STREAM:
             self::appendLiveStreamEntryMrss($entry, $mrss);
             break;
         default:
             break;
     }
     $assetsStatuses = array(asset::ASSET_STATUS_READY);
     if ($mrssParams && $mrssParams->getStatuses()) {
         $assetsStatuses = $mrssParams->getStatuses();
     }
     $assets = assetPeer::retrieveReadyByEntryId($entry->getId(), null, $assetsStatuses);
     foreach ($assets as $asset) {
         if ($mrssParams && !is_null($mrssParams->getFilterByFlavorParams()) && $asset->getFlavorParamsId() != $mrssParams->getFilterByFlavorParams()) {
             continue;
         }
         if ($asset instanceof flavorAsset) {
             self::appendFlavorAssetMrss($asset, $mrss, $mrssParams);
         }
         if ($asset instanceof thumbAsset) {
             self::appendThumbAssetMrss($asset, $mrss);
         }
     }
     $mrssContributors = self::getMrssContributors();
     if (count($mrssContributors)) {
         foreach ($mrssContributors as $mrssContributor) {
             try {
                 if (!count($features) || in_array($mrssContributor->getObjectFeatureType(), $features)) {
                     $mrssContributor->contribute($entry, $mrss, $mrssParams);
                 }
             } catch (kCoreException $ex) {
                 KalturaLog::err("Unable to add MRSS element for contributor [" . get_class($mrssContributor) . "] message [" . $ex->getMessage() . "]");
             }
         }
     }
     if ($mrssParams && $mrssParams->getIncludePlayerTag()) {
         $uiconfId = !is_null($mrssParams->getPlayerUiconfId()) ? '/ui_conf_id/' . $mrssParams->getPlayerUiconfId() : '';
         $playerUrl = kConf::get('apphome_url') . '/kwidget/wid/_' . $entry->getPartnerId() . '/entry_id/' . $entry->getId() . '/ui_conf' . ($uiconfId ? "/{$uiconfId}" : '');
         $player = $mrss->addChild('player');
         $player->addAttribute('url', $playerUrl);
     }
     if ($mrssParams && $mrssParams->getItemXpathsToExtend()) {
         self::addExtendingItemsToMrss($mrss, $mrssParams);
     }
     self::addInstanceToPool($instanceKey, $mrss);
     return $mrss;
 }
 public function __construct($feedId)
 {
     myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL3;
     $microTimeStart = microtime(true);
     KalturaLog::info("syndicationFeedRenderer- initialize ");
     // initialize the database for all services
     DbManager::setConfig(kConf::getDB());
     DbManager::initialize();
     $this->syndicationFeedDB = $syndicationFeedDB = syndicationFeedPeer::retrieveByPK($feedId);
     if (!$syndicationFeedDB) {
         throw new Exception("Feed Id not found");
     }
     kEntitlementUtils::initEntitlementEnforcement($syndicationFeedDB->getPartnerId(), $syndicationFeedDB->getEnforceEntitlement());
     if (!is_null($syndicationFeedDB->getPrivacyContext()) && $syndicationFeedDB->getPrivacyContext() != '') {
         kEntitlementUtils::setPrivacyContextSearch($syndicationFeedDB->getPrivacyContext());
     }
     $tmpSyndicationFeed = KalturaSyndicationFeedFactory::getInstanceByType($syndicationFeedDB->getType());
     $tmpSyndicationFeed->fromObject($syndicationFeedDB);
     $this->syndicationFeed = $tmpSyndicationFeed;
     // add partner to default criteria
     categoryPeer::addPartnerToCriteria($this->syndicationFeed->partnerId, true);
     assetPeer::addPartnerToCriteria($this->syndicationFeed->partnerId, true);
     entryPeer::setDefaultCriteriaFilter();
     $this->baseCriteria = entryPeer::getDefaultCriteriaFilter();
     $startDateCriterion = $this->baseCriteria->getNewCriterion(entryPeer::START_DATE, time(), Criteria::LESS_EQUAL);
     $startDateCriterion->addOr($this->baseCriteria->getNewCriterion(entryPeer::START_DATE, null));
     $this->baseCriteria->addAnd($startDateCriterion);
     $endDateCriterion = $this->baseCriteria->getNewCriterion(entryPeer::END_DATE, time(), Criteria::GREATER_EQUAL);
     $endDateCriterion->addOr($this->baseCriteria->getNewCriterion(entryPeer::END_DATE, null));
     $this->baseCriteria->addAnd($endDateCriterion);
     $entryFilter = new entryFilter();
     $entryFilter->setPartnerSearchScope($this->syndicationFeed->partnerId);
     $entryFilter->setStatusEquel(entryStatus::READY);
     $entryFilter->setTypeIn(array(entryType::MEDIA_CLIP, entryType::MIX));
     $entryFilter->setModerationStatusNotIn(array(entry::ENTRY_MODERATION_STATUS_REJECTED, entry::ENTRY_MODERATION_STATUS_PENDING_MODERATION));
     $entryFilter->attachToCriteria($this->baseCriteria);
     if ($this->syndicationFeed->playlistId) {
         $this->entryFilters = myPlaylistUtils::getPlaylistFiltersById($this->syndicationFeed->playlistId);
         foreach ($this->entryFilters as $entryFilter) {
             $entryFilter->setPartnerSearchScope(baseObjectFilter::MATCH_KALTURA_NETWORK_AND_PRIVATE);
             // partner scope already attached
         }
         $playlist = entryPeer::retrieveByPK($this->syndicationFeed->playlistId);
         if ($playlist) {
             if ($playlist->getMediaType() != entry::ENTRY_MEDIA_TYPE_XML) {
                 $this->staticPlaylist = true;
                 $this->staticPlaylistEntriesIdsOrder = explode(',', $playlist->getDataContent());
             }
         }
     } else {
         $this->entryFilters = array();
     }
     $microTimeEnd = microtime(true);
     KalturaLog::info("syndicationFeedRenderer- initialization done [" . ($microTimeEnd - $microTimeStart) . "]");
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     requestUtils::handleConditionalGet();
     $wams_asset_id = NULL;
     $wams_url = NULL;
     $entry_id = $this->getRequestParameter("entry_id");
     $type = $this->getRequestParameter("type");
     $ks = $this->getRequestParameter("ks");
     $file_sync = null;
     $ret_file_name = "name";
     $referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $request_file_name = $this->getRequestParameter("file_name");
     if ($request_file_name) {
         $ret_file_name = $request_file_name;
     }
     $direct_serve = $this->getRequestParameter("direct_serve");
     $entry = null;
     if ($ks) {
         try {
             kCurrentContext::initKsPartnerUser($ks);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entry_id);
         if (!$entry) {
             die;
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$entry) {
         $entry = entryPeer::retrieveByPK($entry_id);
         if (!$entry) {
             die;
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             die;
         }
     }
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     $securyEntryHelper = new KSecureEntryHelper($entry, $ks, $referrer, accessControlContextType::DOWNLOAD);
     $securyEntryHelper->validateForDownload();
     //		Rmoved by Tan-Tan - asked by Eran
     //		// allow access only via cdn unless these are documents (due to the current implementation of convert ppt2swf)
     //		if ($entry->getType() != entryType::DOCUMENT && $entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_IMAGE)
     //		{
     //			requestUtils::enforceCdnDelivery($entry->getPartnerId());
     //		}
     // relocate = did we use the redirect and added the extension to the name
     $relocate = $this->getRequestParameter("relocate");
     if ($ret_file_name == "name") {
         $ret_file_name = $entry->getName();
     }
     if ($ret_file_name) {
         //rawurlencode to content-disposition filename to handle spaces and other characters across different browsers
         //$name = rawurlencode($ret_file_name);
         // 19.04.2009 (Roman) - url encode is not needed when the filename in Content-Disposition header is in quotes
         // IE6/FF3/Chrome - Will show the filename correctly
         // IE7 - Will show the filename with underscores instead of spaces (this is better than showing %20)
         $name = $ret_file_name;
         if ($name) {
             if ($relocate) {
                 // if we have a good file extension (from the first time) - use it in the content-disposition
                 // in some browsers it will be stronger than the URL's extension
                 $file_ext = pathinfo($relocate, PATHINFO_EXTENSION);
                 $name .= ".{$file_ext}";
             }
             if (!$direct_serve) {
                 header("Content-Disposition: attachment; filename=\"{$name}\"");
             }
         }
     } else {
         $ret_file_name = $entry_id;
     }
     $format = $this->getRequestParameter("format");
     if ($type == "download" && $format && $entry->getType() != entryType::DOCUMENT) {
         // this is a video for a specifc extension - use the proper flavorAsset
         $flavor_asset = assetPeer::retrieveByEntryIdAndExtension($entry_id, $format);
         if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true);
         } else {
             header('KalturaRaw: no flavor asset for extension');
             header("HTTP/1.0 404 Not Found");
             die;
         }
         $archive_file = $file_sync->getFullPath();
         $mime_type = kFile::mimeType($archive_file);
         kFile::dumpFile($archive_file, $mime_type);
     }
     // TODO - move to a different action - document should be plugin
     if ($entry->getType() == entryType::DOCUMENT) {
         // use the fileSync from the entry
         if ($type == "download" && $format) {
             $flavor_asset = assetPeer::retrieveByEntryIdAndExtension($entry_id, $format);
         } else {
             $flavor_asset = assetPeer::retrieveOriginalByEntryId($entry_id);
         }
         if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true);
         } else {
             header('KalturaRaw: no flavor asset for extension');
             header("HTTP/1.0 404 Not Found");
             die;
         }
         // Gonen 2010-08-05 workaround to make sure file name includes correct extension
         // make sure a file extension is added to the downloaded file so browser will identify and
         // allow opening with default program
         // for direct serve we do not want to send content-disposition header
         if (!$direct_serve) {
             $ext = pathinfo($file_sync->getFullPath(), PATHINFO_EXTENSION);
             if ($relocate) {
                 // remove relocate file extension
                 $reloc_ext = pathinfo($relocate, PATHINFO_EXTENSION);
                 $name = str_replace(".{$reloc_ext}", '', $name);
             }
             header("Content-Disposition: attachment; filename=\"{$name}.{$ext}\"");
         }
         kFile::dumpFile($file_sync->getFullPath());
     } elseif ($entry->getType() == entryType::DATA) {
         $version = $this->getRequestParameter("version");
         $syncKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version);
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if ($local) {
             $path = $fileSync->getFullPath();
         } else {
             $path = kDataCenterMgr::getRedirectExternalUrl($fileSync);
             KalturaLog::info("Redirecting to [{$path}]");
         }
         if (!$path) {
             header('KalturaRaw: no data was found available for download');
             header("HTTP/1.0 404 Not Found");
         } else {
             kFile::dumpFile($path);
         }
     }
     //$archive_file = $entry->getArchiveFile();
     $media_type = $entry->getMediaType();
     if ($media_type == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         // image - use data for entry
         $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, null);
         $key = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         kFile::dumpFile(kFileSyncUtils::getLocalFilePathForKey($key, true));
     } elseif ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO || $media_type == entry::ENTRY_MEDIA_TYPE_AUDIO) {
         $format = $this->getRequestParameter("format");
         if ($type == "download" && $format) {
             // this is a video for a specifc extension - use the proper flavorAsset
             $flavor_asset = assetPeer::retrieveByEntryIdAndExtension($entry_id, $format);
             if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) {
                 $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true);
             } else {
                 header('KalturaRaw: no flavor asset for extension');
                 die;
             }
             $archive_file = $file_sync->getFullPath();
         } else {
             // flavorAsset of the original
             $flavor_asset = assetPeer::retrieveOriginalByEntryId($entry_id);
             if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) {
                 $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, false);
                 // NOT strict - if there is no archive, get the data version
                 if ($file_sync) {
                     $wams_asset_id = $file_sync->getWamsAssetId();
                     $archive_file = $file_sync->getFullPath();
                 }
             }
             if (!$flavor_asset || !$file_sync || $flavor_asset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
                 // either no archive asset or no fileSync for archive asset
                 // use fallback flavorAsset
                 $flavor_asset = assetPeer::retrieveBestPlayByEntryId($entry_id);
                 if (!$flavor_asset) {
                     header('KalturaRaw: no original flavor asset for entry, no best play asset for entry');
                     die;
                 }
                 $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, false);
                 // NOT strict - if there is no archive, get the data version
                 $archive_file = $file_sync->getFullPath();
             }
         }
     } elseif ($media_type == entry::ENTRY_MEDIA_TYPE_SHOW) {
         // in this case "raw" is a bad name
         // TODO - add the ability to fetch the actual XML by flagging "xml" or something
         $version = $this->getRequestParameter("version");
         // hotfix - links sent after flattening is done look like:
         // http://cdn.kaltura.com/p/387/sp/38700/raw/entry_id/0_ix99151g/version/100001
         // while waiting for flavor-adaptation in flattening, we want to find at least one file to return.
         $try_formats = array('mp4', 'mov', 'avi', 'flv');
         if ($format) {
             $key = array_search($format, $try_formats);
             if ($key !== FALSE) {
                 unset($try_formats[$key]);
             }
             $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $format, false);
         }
         if (!isset($file_sync) || !$file_sync || !file_exists($file_sync->getFullPath())) {
             foreach ($try_formats as $ext) {
                 KalturaLog::log("raw for mix - trying to find filesync for extension: [{$ext}] on entry [{$entry->getId()}]");
                 $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $ext, false);
                 if ($file_sync && file_exists($file_sync->getFullPath())) {
                     KalturaLog::log("raw for mix - found flattened video of extension: [{$ext}] continuing with this file {$file_sync->getFullPath()}");
                     break;
                 }
             }
             if (!$file_sync || !file_exists($file_sync->getFullPath())) {
                 $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $ext, true);
             }
         }
         // use fileSync for entry - roughcuts don't have flavors
         //$file_sync =  $this->redirectIfRemote ( $entry ,  entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD , $version , true );  // strict - nothing to do if no flattened version
         // if got to here - fileSync was found for one of the extensions - continue with that file
         $archive_file = $file_sync->getFullPath();
     } else {
         // no archive for this file
         header("HTTP/1.0 404 Not Found");
         die;
     }
     //		echo "[$archive_file][" . file_exists ( $archive_file ) . "]";
     if (empty($wams_asset_id)) {
         $mime_type = kFile::mimeType($archive_file);
     }
     //		echo "[[$mime_type]]";
     $shouldProxy = $this->getRequestParameter("forceproxy", false);
     if ($shouldProxy || !empty($relocate)) {
         if (!empty($wams_asset_id)) {
             $fileExt = pathinfo($archive_file, PATHINFO_EXTENSION);
             kWAMS::getInstance($entry->getPartnerId())->dumpFile($wams_asset_id, $fileExt);
             die;
         } else {
             // dump the file
             kFile::dumpFile($archive_file, $mime_type);
             die;
         }
     }
     // use new Location to add the best extension we can find for the file
     $file_ext = pathinfo($archive_file, PATHINFO_EXTENSION);
     if ($file_ext != "flv") {
         // if the file does not end with "flv" - it is the real extension
         $ext = $file_ext;
     } else {
         // for now - if "flv" return "flv" - // TODO - find the real extension from the file itself
         $ext = "flv";
     }
     // rebuild the URL and redirect to it with extraa parameters
     $url = $_SERVER["REQUEST_URI"];
     $format = $this->getRequestParameter("format");
     if (!$format) {
         $url = str_replace("format", "", $url);
     }
     if (!$ret_file_name) {
         // don't leave the name empty - if it is empty - use the entry id
         $ret_file_name = $entry_id;
     }
     $ret_file_name_safe = str_replace(' ', '-', $ret_file_name);
     // spaces replace with "-"
     $ret_file_name_safe = preg_replace('/[^a-zA-Z0-9-_]/', '', $ret_file_name_safe);
     // only "a-z", "A-Z", "0-9", "-" & "_" are left
     if (strpos($url, "?") > 0) {
         $url = str_replace("?", "/{$ret_file_name_safe}.{$ext}?", $url);
         $url .= "&relocate=f.{$ext}";
         // add the ufname as a query parameter
     } else {
         $url .= "/{$ret_file_name_safe}.{$ext}?relocate=f.{$ext}";
         // add the ufname as a query parameter
     }
     // or redirect if no proxy
     header("Location: {$url}");
     die;
 }
Exemplo n.º 14
0
 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;
 }
Exemplo n.º 15
0
 /**
  * @param string $captionAssetId
  * @throws KalturaAPIException
  * @return CaptionAsset
  */
 protected function validateForDownload($captionAssetId)
 {
     $captionAsset = null;
     if (!kCurrentContext::$ks) {
         $captionAsset = kCurrentContext::initPartnerByAssetId($captionAssetId);
         if (!$captionAsset || $captionAsset->getStatus() == asset::ASSET_STATUS_DELETED) {
             throw new KalturaAPIException(KalturaCaptionErrors::CAPTION_ASSET_ID_NOT_FOUND, $captionAssetId);
         }
         // enforce entitlement
         $this->setPartnerFilters(kCurrentContext::getCurrentPartnerId());
         kEntitlementUtils::initEntitlementEnforcement();
     } else {
         $captionAsset = assetPeer::retrieveById($captionAssetId);
     }
     if (!$captionAsset || !$captionAsset instanceof CaptionAsset) {
         throw new KalturaAPIException(KalturaCaptionErrors::CAPTION_ASSET_ID_NOT_FOUND, $captionAssetId);
     }
     if (kCurrentContext::$ks_object && kCurrentContext::$ks_object->verifyPrivileges(CaptionPlugin::KS_PRIVILEGE_CAPTION, $captionAsset->getEntryId())) {
         return $captionAsset;
     }
     $entry = entryPeer::retrieveByPK($captionAsset->getEntryId());
     if (!$entry) {
         //we will throw caption asset not found, as the user is not entitled, and should not know that the entry exists.
         throw new KalturaAPIException(KalturaCaptionErrors::CAPTION_ASSET_ID_NOT_FOUND, $captionAssetId);
     }
     $securyEntryHelper = new KSecureEntryHelper($entry, kCurrentContext::$ks, null, ContextType::DOWNLOAD);
     $securyEntryHelper->validateForDownload();
     return $captionAsset;
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $entryId = $this->getRequestParameter("entry_id");
     $flavorId = $this->getRequestParameter("flavor");
     $fileName = $this->getRequestParameter("file_name");
     $fileName = basename($fileName);
     $ksStr = $this->getRequestParameter("ks");
     $referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $entry = null;
     if ($ksStr) {
         try {
             kCurrentContext::initKsPartnerUser($ksStr);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entryId);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$entry) {
         $entry = entryPeer::retrieveByPK($entryId);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, accessControlContextType::DOWNLOAD);
     $securyEntryHelper->validateForDownload($entry, $ksStr);
     $flavorAsset = null;
     if ($flavorId) {
         // get flavor asset
         $flavorAsset = assetPeer::retrieveById($flavorId);
         if (is_null($flavorAsset) || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
         // the request flavor should belong to the requested entry
         if ($flavorAsset->getEntryId() != $entryId) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
     } else {
         $flavorAsset = assetPeer::retrieveBestPlayByEntryId($entry->getId());
     }
     // Gonen 26-04-2010: in case entry has no flavor with 'mbr' tag - we return the source
     if (!$flavorAsset && ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO)) {
         $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId);
     }
     if ($flavorAsset) {
         $syncKey = $this->getSyncKeyAndForFlavorAsset($entry, $flavorAsset);
     } else {
         $syncKey = $this->getBestSyncKeyForEntry($entry);
     }
     if (is_null($syncKey)) {
         KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
     }
     $this->handleFileSyncRedirection($syncKey);
     $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     $wamsAssetId = kFileSyncUtils::getWamsAssetIdForKey($syncKey);
     $wamsURL = kFileSyncUtils::getWamsURLForKey($syncKey);
     list($fileBaseName, $fileExt) = $this->getFileName($entry, $flavorAsset);
     if (!$fileName) {
         $fileName = $fileBaseName;
     }
     if ($fileExt && !is_dir($filePath)) {
         $fileName = $fileName . '.' . $fileExt;
     }
     //enable downloading file_name which inside the flavor asset directory
     if (is_dir($filePath)) {
         $filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
     }
     $this->dumpFile($filePath, $fileName, $wamsAssetId, $wamsURL);
     die;
     // no view
 }
 public function __construct($feedId, $feedProcessingKey = null, $ks = null)
 {
     $this->feedProcessingKey = $feedProcessingKey;
     myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL3;
     $microTimeStart = microtime(true);
     KalturaLog::info("syndicationFeedRenderer- initialize ");
     $this->syndicationFeedDb = $syndicationFeedDB = syndicationFeedPeer::retrieveByPK($feedId);
     if (!$syndicationFeedDB) {
         throw new Exception("Feed Id not found");
     }
     kCurrentContext::initKsPartnerUser($ks, $syndicationFeedDB->getPartnerId(), '');
     kPermissionManager::init();
     kEntitlementUtils::initEntitlementEnforcement($syndicationFeedDB->getPartnerId(), $syndicationFeedDB->getEnforceEntitlement());
     if (!is_null($syndicationFeedDB->getPrivacyContext()) && $syndicationFeedDB->getPrivacyContext() != '') {
         kEntitlementUtils::setPrivacyContextSearch($syndicationFeedDB->getPrivacyContext());
     }
     $tmpSyndicationFeed = KalturaSyndicationFeedFactory::getInstanceByType($syndicationFeedDB->getType());
     $tmpSyndicationFeed->fromObject($syndicationFeedDB);
     $this->syndicationFeed = $tmpSyndicationFeed;
     // add partner to default criteria
     myPartnerUtils::addPartnerToCriteria('category', $this->syndicationFeed->partnerId, true);
     myPartnerUtils::addPartnerToCriteria('asset', $this->syndicationFeed->partnerId, true);
     myPartnerUtils::resetPartnerFilter('entry');
     $this->baseCriteria = clone entryPeer::getDefaultCriteriaFilter();
     $startDateCriterion = $this->baseCriteria->getNewCriterion(entryPeer::START_DATE, time(), Criteria::LESS_EQUAL);
     $startDateCriterion->addOr($this->baseCriteria->getNewCriterion(entryPeer::START_DATE, null));
     $this->baseCriteria->addAnd($startDateCriterion);
     $endDateCriterion = $this->baseCriteria->getNewCriterion(entryPeer::END_DATE, time(), Criteria::GREATER_EQUAL);
     $endDateCriterion->addOr($this->baseCriteria->getNewCriterion(entryPeer::END_DATE, null));
     $this->baseCriteria->addAnd($endDateCriterion);
     $this->baseCriteria->addAnd(entryPeer::PARTNER_ID, $this->syndicationFeed->partnerId);
     $this->baseCriteria->addAnd(entryPeer::STATUS, entryStatus::READY);
     $this->baseCriteria->addAnd(entryPeer::TYPE, array(entryType::MEDIA_CLIP, entryType::MIX), Criteria::IN);
     $this->baseCriteria->addAnd(entryPeer::MODERATION_STATUS, array(entry::ENTRY_MODERATION_STATUS_REJECTED, entry::ENTRY_MODERATION_STATUS_PENDING_MODERATION), Criteria::NOT_IN);
     if ($this->syndicationFeed->playlistId) {
         $this->entryFilters = myPlaylistUtils::getPlaylistFiltersById($this->syndicationFeed->playlistId);
         foreach ($this->entryFilters as $entryFilter) {
             $entryFilter->setPartnerSearchScope(baseObjectFilter::MATCH_KALTURA_NETWORK_AND_PRIVATE);
             // partner scope already attached
         }
         $playlist = entryPeer::retrieveByPK($this->syndicationFeed->playlistId);
         if ($playlist) {
             if ($playlist->getMediaType() != entry::ENTRY_MEDIA_TYPE_XML) {
                 $this->staticPlaylist = true;
                 $this->staticPlaylistEntriesIdsOrder = explode(',', $playlist->getDataContent());
             }
         }
     } else {
         $this->entryFilters = array();
     }
     $microTimeEnd = microtime(true);
     KalturaLog::info("syndicationFeedRenderer- initialization done [" . ($microTimeEnd - $microTimeStart) . "]");
 }
 /**
  * Serves attachment by its id
  *  
  * @action serve
  * @param string $attachmentAssetId
  * @return file
  *  
  * @throws KalturaAttachmentErrors::ATTACHMENT_ASSET_ID_NOT_FOUND
  */
 public function serveAction($attachmentAssetId)
 {
     $attachmentAsset = null;
     if (!kCurrentContext::$ks) {
         $attachmentAsset = kCurrentContext::initPartnerByAssetId($attachmentAssetId);
         if (!$attachmentAsset || $attachmentAsset->getStatus() == asset::ASSET_STATUS_DELETED) {
             throw new KalturaAPIException(KalturaAttachmentErrors::ATTACHMENT_ASSET_ID_NOT_FOUND, $attachmentAssetId);
         }
         // enforce entitlement
         kEntitlementUtils::initEntitlementEnforcement();
     } else {
         $attachmentAsset = assetPeer::retrieveById($attachmentAssetId);
     }
     if (!$attachmentAsset || !$attachmentAsset instanceof AttachmentAsset) {
         throw new KalturaAPIException(KalturaAttachmentErrors::ATTACHMENT_ASSET_ID_NOT_FOUND, $attachmentAssetId);
     }
     $entry = entryPeer::retrieveByPK($attachmentAsset->getEntryId());
     if (!$entry) {
         //we will throw attachment asset not found, as the user is not entitled, and should not know that the entry exists.
         throw new KalturaAPIException(KalturaAttachmentErrors::ATTACHMENT_ASSET_ID_NOT_FOUND, $attachmentAssetId);
     }
     $securyEntryHelper = new KSecureEntryHelper($entry, kCurrentContext::$ks, null, accessControlContextType::DOWNLOAD);
     $securyEntryHelper->validateForDownload();
     $ext = $attachmentAsset->getFileExt();
     if (is_null($ext)) {
         $ext = 'txt';
     }
     $fileName = $attachmentAsset->getFilename();
     if (!$fileName) {
         $fileName = $attachmentAsset->getEntryId() . "_" . $attachmentAsset->getId() . ".{$ext}";
     }
     return $this->serveAsset($attachmentAsset, $fileName);
 }
 protected function initEntry()
 {
     $this->entryId = $this->getRequestParameter("entryId", null);
     // look for a valid token
     $expiry = $this->getRequestParameter("expiry");
     if ($expiry && $expiry <= time()) {
         KExternalErrors::dieError(KExternalErrors::EXPIRED_TOKEN);
     }
     $urlToken = $this->getRequestParameter("kt");
     if ($urlToken) {
         if ($_SERVER["REQUEST_METHOD"] != "GET" || !self::validateKalturaToken($_SERVER["REQUEST_URI"], $urlToken)) {
             KExternalErrors::dieError(KExternalErrors::INVALID_TOKEN);
         }
     }
     // initalize the context
     $ksStr = $this->getRequestParameter("ks");
     if ($ksStr && !$urlToken) {
         try {
             kCurrentContext::initKsPartnerUser($ksStr);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $this->entry = kCurrentContext::initPartnerByEntryId($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     // no need for any further check if a token was used
     if ($urlToken) {
         return;
     }
     // enforce entitlement
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$this->entry) {
         $this->entry = entryPeer::retrieveByPKNoFilter($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($this->entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     // enforce access control
     $base64Referrer = $this->getRequestParameter("referrer");
     // replace space in the base64 string with + as space is invalid in base64 strings and caused
     // by symfony calling str_parse to replace + with spaces.
     // this happens only with params passed in the url path and not the query strings. specifically the ~ char at
     // a columns divided by 3 causes this issue (e.g. http://www.xyzw.com/~xxx)
     $referrer = base64_decode(str_replace(" ", "+", $base64Referrer));
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     $this->secureEntryHelper = new KSecureEntryHelper($this->entry, $ksStr, $referrer, accessControlContextType::PLAY);
     if ($this->secureEntryHelper->shouldPreview()) {
         $this->clipTo = $this->secureEntryHelper->getPreviewLength() * 1000;
     } else {
         $this->secureEntryHelper->validateForPlay();
     }
 }