Exemplo n.º 1
0
 /**
  * here we'll manipulate the video asset and set the from_byte & to_byte from the milliseconds
  *
  */
 private static function fixMetadataImpl(&$xml_doc, &$total_duration, $timeline)
 {
     self::log(__METHOD__);
     /*
     	$xml_doc = new DOMDocument();
     	$xml_doc->loadXML( $content );
     */
     //		$meatadata_elem_list = $xml_doc->getElementsByTagName( "MetaData" );
     //		if ( $meatadata_elem_list != null && $meatadata_elem_list->length > 0 )
     $duration_list = $xml_doc->getElementsByTagName("SeqDuration");
     if ($duration_list != null && $duration_list->length > 0) {
         $total_duration = $duration_list->item(0)->nodeValue;
     }
     $xpath = new DOMXPath($xml_doc);
     $assets = $xpath->query($timeline == "video" ? "//VideoAssets/vidAsset" : ($timeline == "audio" ? "//AudioAssets/AudAsset" : "//VoiceAssets/voiAsset"));
     $lastTimestamp = 0;
     $real_start_byte = 0;
     // the start byte of the current clip in the final merged stream
     $calculated_total_bytes = 0;
     // use the entryPool and a 2-pass iteration to reduce the hits to the DB
     $id_list = array();
     $entry_pool = new entryPool();
     // first pass - populate the entryPool in a single request to the DB
     self::log(__METHOD__, "Before assets");
     foreach ($assets as $asset) {
         $type = $asset->getAttribute("type");
         if ($type != "VIDEO" && $type != "AUDIO") {
             continue;
         }
         // fetch the file name from the DB
         $asset_id = $asset->getAttribute("k_id");
         $id_list[] = $asset_id;
     }
     self::log(__METHOD__, "After assets", count($id_list), $id_list);
     if ($id_list) {
         $entry_pool->addEntries(entryPeer::retrieveByPKsNoFilter($id_list));
     }
     // second pass - the entryPool is supposed to already be populated
     $was_modified = false;
     foreach ($assets as $asset) {
         // fix only VIDEO assets
         $type = $asset->getAttribute("type");
         if ($type != "VIDEO" && $type != "AUDIO") {
             continue;
         }
         // fetch the file name from the DB
         $asset_id = $asset->getAttribute("k_id");
         self::log(__METHOD__, "in loop", $asset_id);
         //$entry = entryPeer::retrieveByPKNoFilter( $asset_id );
         $entry = $entry_pool->retrieveByPK($asset_id);
         // is supposed to exist already in the pool
         if ($entry == NULL) {
             // set an error on the asset element
             $asset->setAttribute("fix_status", "error in k_id [{$asset_id}]");
             $was_modified = true;
             continue;
         } elseif ($entry->getStatus() == entryStatus::DELETED) {
             // set an error on the asset element
             $asset->setAttribute("fix_status", "error in k_id [{$asset_id}] - asset was deleted");
             $was_modified = true;
             continue;
         }
         $file_name = null;
         //TODO: need to work on only an FLV asset
         $flavor_asset_play = assetPeer::retrieveBestPlayByEntryId($entry->getId());
         if (!$flavor_asset_play) {
             KalturaLog::log(__METHOD__ . ' ' . __LINE__ . ' no play flavor asset for entry ' . $entry->getId());
         } else {
             $file_name = kFileSyncUtils::getReadyLocalFilePathForKey($flavor_asset_play->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET));
         }
         $use_multi_flavor = false;
         $flv_file_name_edit = false;
         $flavor_asset_edit = assetPeer::retrieveBestEditByEntryId($entry->getId());
         if (!$flavor_asset_edit) {
             KalturaLog::log(__METHOD__ . ' ' . __LINE__ . ' no edit flavor asset for entry ' . $entry->getId());
         } else {
             $flv_file_name_edit = kFileSyncUtils::getReadyLocalFilePathForKey($flavor_asset_edit->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET));
             $use_multi_flavor = $flv_file_name_edit && file_exists($flv_file_name_edit) && $timeline == "video";
         }
         if (!$flv_file_name_edit && !$file_name) {
             KalturaLog::log(__METHOD__ . ' ' . __LINE__ . ' no edit & play flavor assets for entry ' . $entry->getId());
             continue;
         }
         $flv_file_name = kFile::fixPath($file_name);
         $stream_info_list = $asset->getElementsByTagName("StreamInfo");
         foreach ($stream_info_list as $stream_info) {
             $file_name = "?";
             try {
                 $stream_info->setAttribute("file_name", kFileSyncUtils::getReadyLocalFilePathForKey($flavor_asset_play->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET)));
                 // replaced__getDataPath
                 $start_byte = $stream_info->getAttribute("start_byte");
                 $end_byte = $stream_info->getAttribute("end_byte");
                 $total_bytes = $stream_info->getAttribute("total_bytes");
                 if ($start_byte == NULL) {
                     $start_byte = self::MISSING_VALUE;
                 }
                 if ($end_byte == NULL) {
                     $end_byte = self::MISSING_VALUE;
                 }
                 if ($total_bytes == NULL) {
                     $total_bytes = self::MISSING_VALUE;
                 }
                 $len_time = floor(1000 * $stream_info->getAttribute("len_time"));
                 if (1 || $start_byte == self::MISSING_VALUE || $end_byte == self::MISSING_VALUE || $total_bytes == self::MISSING_VALUE) {
                     // set the values from start_time & len_time - the original numbers are in seconds (with a decimal point)
                     $start_time = floor(1000 * $stream_info->getAttribute("start_time"));
                     $end_time = $start_time + $len_time;
                     $real_start_byte += $calculated_total_bytes;
                     $calculated_start_byte = 0;
                     $calculated_end_byte = 0;
                     $calculated_total_bytes = 0;
                     $calculated_real_seek_time = 0;
                     $calculated_start_byte_play = 0;
                     $calculated_end_byte_play = 0;
                     $calculated_total_bytes_play = 0;
                     /*		  				$file_name = $stream_info->getAttribute ( "file_name" );
                     						$flv_file_name = kFile::fixPath( myContentStorage::getFSContentRootPath() . $file_name );
                     						$ext = pathinfo ($flv_file_name, PATHINFO_EXTENSION);
                     						if ( $ext == NULL  )
                     							$flv_file_name .= ".flv";
                     	*/
                     try {
                         self::log(__METHOD__, "before findBytesFromTimestamps", $flv_file_name);
                         //$use_multi_flavor = myFlvStaticHandler::isMultiFlavor ( $flv_file_name  ) && $timeline == "video";
                         $calculated_real_seek_time = $lastTimestamp;
                         $start_time_play = null;
                         if ($use_multi_flavor) {
                             $start_time_play = $start_time;
                             // play
                             // $start_time_play - will be modified according to the first keyframe's time stamp AFTER (not before) the requested timestamp
                             $result = myFlvStaticHandler::findBytesFromTimestamps($flv_file_name, $start_time_play, $end_time, $calculated_start_byte_play, $calculated_end_byte_play, $calculated_total_bytes_play, $lastTimestamp, $timeline != "video", 1);
                             KalturaLog::log(__METHOD__ . ' ' . __LINE__ . " play {$result} = findBytesFromTimestamps({$flv_file_name} , {$start_time_play} , {$end_time} , {$calculated_start_byte_play} , {$calculated_end_byte_play} , {$calculated_total_bytes_play}, {$lastTimestamp}, {$timeline})");
                             if ($result) {
                                 if ($start_time_play != $start_time) {
                                     // we need to fill the gap between the user requested keyframe and the one actually found in the play (low res) flavor
                                     // 	edit - more keyfrmaes !
                                     $result = myFlvStaticHandler::findBytesFromTimestamps($flv_file_name_edit, $start_time, $start_time_play, $calculated_start_byte, $calculated_end_byte, $calculated_total_bytes, $lastTimestamp, $timeline != "video", 2);
                                     KalturaLog::log(__METHOD__ . ' ' . __LINE__ . " edit {$result} = findBytesFromTimestamps({$flv_file_name} , {$start_time_play} , {$end_time} , {$calculated_start_byte_play} , {$calculated_end_byte_play} , {$calculated_total_bytes_play}, {$lastTimestamp}, {$timeline})");
                                 }
                             }
                         } else {
                             // no reason to have multi-flavor files
                             // either because NOT video or because the edit flavor does not exist
                             $result = myFlvStaticHandler::findBytesFromTimestamps($flv_file_name, $start_time, $end_time, $calculated_start_byte, $calculated_end_byte, $calculated_total_bytes, $lastTimestamp, $timeline != "video", 0);
                             KalturaLog::log(__METHOD__ . ' ' . __LINE__ . " only play {$result} = findBytesFromTimestamps({$flv_file_name} , {$start_time_play} , {$end_time} , {$calculated_start_byte_play} , {$calculated_end_byte_play} , {$calculated_total_bytes_play}, {$lastTimestamp}, {$timeline})");
                         }
                         self::log(__METHOD__, "after findBytesFromTimestamps", $flv_file_name);
                     } catch (Exception $ex1) {
                         debugUtils::log("Error while converting time2bytes in file [{$file_name}]\n{$ex1}");
                         echo "Error while converting time2bytes in file [{$file_name}]\n{$ex1}";
                     }
                     $calculated_total_bytes += $calculated_total_bytes_play;
                     if ($result) {
                         if (1 || $start_byte == self::MISSING_VALUE) {
                             $stream_info->setAttribute("start_byte", $calculated_start_byte);
                             $stream_info->setAttribute("start_byte_play", $calculated_start_byte_play);
                         }
                         if (1 || $end_byte == self::MISSING_VALUE) {
                             $stream_info->setAttribute("end_byte", $calculated_end_byte);
                             $stream_info->setAttribute("end_byte_play", $calculated_end_byte_play);
                         }
                         if (1 || $calculated_total_bytes == self::MISSING_VALUE) {
                             $stream_info->setAttribute("total_bytes", $calculated_total_bytes);
                             $stream_info->setAttribute("real_start_byte", $real_start_byte);
                             $stream_info->setAttribute("real_end_byte", $real_start_byte + $calculated_total_bytes);
                         }
                         if (1 || $calculated_real_seek_time == self::MISSING_VALUE) {
                             // retrun the calculated_real_seek_time in seconds with 2 decimal points
                             $stream_info->setAttribute("real_seek_time", number_format($calculated_real_seek_time / 1000, 3, '.', ''));
                         }
                         if ($asset->hasAttribute("fix_status")) {
                             $asset->removeAttribute("fix_status");
                         }
                     } elseif (!$result) {
                         // set an error on the asset element
                         $asset->setAttribute("fix_status", "Missing file or invalid FLV structure");
                     }
                     $was_modified = true;
                 }
             } catch (Exception $ex2) {
                 echo "Error parsing file [{$file_name}]\n{$ex2}";
             }
         }
     }
     return $xml_doc;
     /*
       		if ( $was_modified )
       		{
       			return $xml_doc->saveXML();
       		}
       		else
       		{
       			// nothing was modified - use the original string
       			return $content;
       		}
     */
 }
Exemplo n.º 2
0
 /**
  *
  * @param $version
  * @param $format
  * @return FileSync
  */
 public function getDownloadFileSyncAndLocal($version = NULL, $format = null, $sub_type = null)
 {
     $sync_key = null;
     if ($this->getType() == entryType::MEDIA_CLIP) {
         if ($this->getMediaType() == self::ENTRY_MEDIA_TYPE_VIDEO || $this->getMediaType() == self::ENTRY_MEDIA_TYPE_AUDIO) {
             $flavor_assets = assetPeer::retrieveBestPlayByEntryId($this->getId());
             // uset the format as the extension
             if ($flavor_assets) {
                 $sync_key = $flavor_assets->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
             }
         } elseif ($this->getMediaType() == self::ENTRY_MEDIA_TYPE_IMAGE) {
             $sync_key = $this->getSyncKey(self::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version);
         }
     } elseif ($this->getType() == entryType::MIX) {
         // if roughcut - the version should be used
         $sync_key = $this->getSyncKey(self::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $version);
     } else {
         // if not roughcut -  the format should be used
         $sync_key = $this->getSyncKey(self::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $format);
     }
     if (!$sync_key) {
         return null;
     }
     return kFileSyncUtils::getReadyFileSyncForKey($sync_key, true, false);
 }
 /**
  * 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
 }
 /**
  * This action delivers entry-related data, based on the user's context: access control, restriction, playback format and storage information.
  * @action getContextData
  * @param string $entryId
  * @param KalturaEntryContextDataParams $contextDataParams
  * @return KalturaEntryContextDataResult
  */
 public function getContextData($entryId, KalturaEntryContextDataParams $contextDataParams)
 {
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $ks = $this->getKs();
     $isAdmin = false;
     if ($ks) {
         $isAdmin = $ks->isAdmin();
     }
     $accessControl = $dbEntry->getAccessControl();
     /* @var $accessControl accessControl */
     $result = new KalturaEntryContextDataResult();
     $result->isAdmin = $isAdmin;
     $result->isScheduledNow = $dbEntry->isScheduledNow($contextDataParams->time);
     if ($dbEntry->getStartDate() && abs($dbEntry->getStartDate(null) - time()) <= 86400 || $dbEntry->getEndDate() && abs($dbEntry->getEndDate(null) - time()) <= 86400) {
         KalturaResponseCacher::setConditionalCacheExpiry(600);
     }
     if ($accessControl && $accessControl->hasRules()) {
         $disableCache = true;
         if (kConf::hasMap("optimized_playback")) {
             $partnerId = $accessControl->getPartnerId();
             $optimizedPlayback = kConf::getMap("optimized_playback");
             if (array_key_exists($partnerId, $optimizedPlayback)) {
                 $params = $optimizedPlayback[$partnerId];
                 if (array_key_exists('cache_kdp_acccess_control', $params) && $params['cache_kdp_acccess_control']) {
                     $disableCache = false;
                 }
             }
         }
         $accessControlScope = $accessControl->getScope();
         $contextDataParams->toObject($accessControlScope);
         $accessControlScope->setEntryId($entryId);
         $result->isAdmin = $accessControlScope->getKs() && $accessControlScope->getKs()->isAdmin();
         $dbResult = new kEntryContextDataResult();
         if ($accessControl->applyContext($dbResult) && $disableCache) {
             KalturaResponseCacher::disableCache();
         }
         $result->fromObject($dbResult);
     }
     $partner = PartnerPeer::retrieveByPK($dbEntry->getPartnerId());
     if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_REMOTE_STORAGE_DELIVERY_PRIORITY, $dbEntry->getPartnerId()) && $partner->getStorageServePriority() != StorageProfile::STORAGE_SERVE_PRIORITY_KALTURA_ONLY) {
         if (is_null($contextDataParams->flavorAssetId)) {
             if ($contextDataParams->flavorTags) {
                 $assets = assetPeer::retrieveReadyByEntryIdAndTag($entryId, $contextDataParams->flavorTags);
                 $asset = reset($assets);
             } else {
                 $asset = assetPeer::retrieveBestPlayByEntryId($entryId);
             }
             if (!$asset) {
                 throw new KalturaAPIException(KalturaErrors::NO_FLAVORS_FOUND, $entryId);
             }
         } else {
             $asset = assetPeer::retrieveByPK($contextDataParams->flavorAssetId);
             if (!$asset) {
                 throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $contextDataParams->flavorAssetId);
             }
         }
         if (!$asset) {
             throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $entryId);
         }
         $assetSyncKey = $asset->getSyncKey(asset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
         $fileSyncs = kFileSyncUtils::getAllReadyExternalFileSyncsForKey($assetSyncKey);
         $storageProfilesXML = new SimpleXMLElement("<StorageProfiles/>");
         foreach ($fileSyncs as $fileSync) {
             $storageProfileId = $fileSync->getDc();
             $storageProfile = StorageProfilePeer::retrieveByPK($storageProfileId);
             if (!$storageProfile->getDeliveryRmpBaseUrl() && (!$contextDataParams->streamerType || $contextDataParams->streamerType == StorageProfile::PLAY_FORMAT_AUTO)) {
                 $contextDataParams->streamerType = StorageProfile::PLAY_FORMAT_HTTP;
                 $contextDataParams->mediaProtocol = StorageProfile::PLAY_FORMAT_HTTP;
             }
             $storageProfileXML = $storageProfilesXML->addChild("StorageProfile");
             $storageProfileXML->addAttribute("storageProfileId", $storageProfileId);
             $storageProfileXML->addChild("Name", $storageProfile->getName());
             $storageProfileXML->addChild("SystemName", $storageProfile->getSystemName());
         }
         $result->storageProfilesXML = $storageProfilesXML->saveXML();
     }
     if ($contextDataParams->streamerType && $contextDataParams->streamerType != StorageProfile::PLAY_FORMAT_AUTO) {
         $result->streamerType = $contextDataParams->streamerType;
         $result->mediaProtocol = $contextDataParams->mediaProtocol ? $contextDataParams->mediaProtocol : $contextDataParams->streamerType;
     } else {
         $result->streamerType = $this->getPartner()->getStreamerType();
         if (!$result->streamerType) {
             $result->streamerType = StorageProfile::PLAY_FORMAT_HTTP;
         }
         $result->mediaProtocol = $this->getPartner()->getMediaProtocol();
         if (!$result->mediaProtocol) {
             $result->mediaProtocol = StorageProfile::PLAY_FORMAT_HTTP;
         }
     }
     return $result;
 }
Exemplo n.º 5
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;
 }
 /**
 	return array('status' => $status, 'message' => $message, 'objects' => $objects);
 		objects - array of
 				'thumb' 
 				'title'  
 				'description' 
 				'id' - unique id to be passed to getMediaInfo 
 */
 public function searchMedia($media_type, $searchText, $page, $pageSize, $authData = null, $extraData = null)
 {
     $page_size = $pageSize > 20 ? 20 : $pageSize;
     $page--;
     if ($page < 0) {
         $page = 0;
     }
     $status = "ok";
     $message = '';
     $objects = array();
     $should_serach = true;
     if (kCurrentContext::isApiV3Context()) {
         $kuser = kuserPeer::getKuserByPartnerAndUid(self::$partner_id, self::$puser_id);
         $should_serach = true;
         $kuser_id = $kuser->getId();
     } else {
         $puser_kuser = PuserKuserPeer::retrieveByPartnerAndUid(self::$partner_id, self::$subp_id, self::$puser_id, true);
         if (!$puser_kuser) {
             // very bad - does not exist in system
             $should_serach = false;
         } else {
             $kuser = $puser_kuser->getKuser();
             if (!$kuser) {
                 $should_serach = false;
             } else {
                 $kuser_id = $kuser->getId();
             }
         }
     }
     //		echo "[" . self::$partner_id . "],[".  self::$subp_id . "],[" . self::$puser_id . "],[$kuser_id]";
     if ($should_serach) {
         $c = KalturaCriteria::create(entryPeer::OM_CLASS);
         $c->add(entryPeer::KUSER_ID, $kuser_id);
         $c->add(entryPeer::MEDIA_TYPE, $media_type);
         $c->add(entryPeer::TYPE, entryType::MEDIA_CLIP);
         //			$keywords_array = mySearchUtils::getKeywordsFromStr ( $searchText );
         $filter = new entryFilter();
         $filter->setPartnerSearchScope(self::$partner_id);
         $filter->addSearchMatchToCriteria($c, $searchText, entry::getSearchableColumnName());
         $c->setLimit($pageSize);
         $c->setOffset($page * $pageSize);
         $entry_results = entryPeer::doSelect($c);
         //JoinAll( $c );
         $number_of_results = $c->getRecordsCount();
         $number_of_pages = (int) ($number_of_results / $pageSize);
         if ($number_of_results % $pageSize != 0) {
             $number_of_pages += 1;
         }
         // if there are some left-overs - there must be a nother page
         // add thumbs when not image or video
         $should_add_thumbs = $media_type != entry::ENTRY_MEDIA_TYPE_AUDIO;
         foreach ($entry_results as $entry) {
             /* @var $entry entry */
             // send the id as the url
             $object = array("id" => $entry->getId(), "url" => $entry->getDataUrl(), "tags" => $entry->getTags(), "title" => $entry->getName(), "description" => $entry->getDescription(), "flash_playback_type" => $entry->getMediaTypeName());
             if ($should_add_thumbs) {
                 $object["thumb"] = $entry->getThumbnailUrl();
             }
             //Find the flavor sent over the dataUrl in order to send its extension
             $playedAsset = assetPeer::retrieveBestPlayByEntryId($entry->getId());
             if ($playedAsset) {
                 $object["file_ext"] = $playedAsset->getFileExt();
             }
             $objects[] = $object;
         }
     }
     return array('status' => $status, 'message' => $message, 'objects' => $objects, "needMediaInfo" => self::$NEED_MEDIA_INFO);
 }
 /**
  * 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;
 }