public function __construct(KalturaDistributionJobData $distributionJobData = null)
 {
     if (!$distributionJobData) {
         return;
     }
     if (!$distributionJobData->distributionProfile instanceof KalturaDailymotionDistributionProfile) {
         return;
     }
     $flavorAssets = flavorAssetPeer::retrieveByIds(explode(',', $distributionJobData->entryDistribution->flavorAssetIds));
     if (count($flavorAssets)) {
         // if we have specific flavor assets for this distribution, grab the first one
         $flavorAsset = reset($flavorAssets);
     } else {
         // take the source asset
         $flavorAsset = flavorAssetPeer::retrieveOriginalReadyByEntryId($distributionJobData->entryDistribution->entryId);
     }
     if ($flavorAsset) {
         $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         $this->videoAssetFilePath = kFileSyncUtils::getLocalFilePathForKey($syncKey, true);
     }
     $thumbAssets = thumbAssetPeer::retrieveByIds(explode(',', $distributionJobData->entryDistribution->thumbAssetIds));
     if (count($thumbAssets)) {
         $syncKey = reset($thumbAssets)->getSyncKey(thumbAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         $this->thumbAssetFilePath = kFileSyncUtils::getLocalFilePathForKey($syncKey, true);
     }
 }
 public function __construct(KalturaDistributionJobData $distributionJobData = null)
 {
     if (!$distributionJobData) {
         return;
     }
     if (!$distributionJobData->distributionProfile instanceof KalturaYoutubeApiDistributionProfile) {
         return;
     }
     $flavorAssets = flavorAssetPeer::retrieveByIds(explode(',', $distributionJobData->entryDistribution->flavorAssetIds));
     if (count($flavorAssets)) {
         // if we have specific flavor assets for this distribution, grab the first one
         $flavorAsset = reset($flavorAssets);
     } else {
         // take the source asset
         $flavorAsset = flavorAssetPeer::retrieveOriginalReadyByEntryId($distributionJobData->entryDistribution->entryId);
     }
     if ($flavorAsset) {
         $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         $this->videoAssetFilePath = kFileSyncUtils::getLocalFilePathForKey($syncKey, true);
     }
     $thumbAssets = thumbAssetPeer::retrieveByIds(explode(',', $distributionJobData->entryDistribution->thumbAssetIds));
     if (count($thumbAssets)) {
         $syncKey = reset($thumbAssets)->getSyncKey(thumbAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         $this->thumbAssetFilePath = kFileSyncUtils::getLocalFilePathForKey($syncKey, true);
     }
     $this->loadPlaylistsFromMetadata($distributionJobData->entryDistribution->entryId, $distributionJobData->distributionProfile);
     $entryDistributionDb = EntryDistributionPeer::retrieveByPK($distributionJobData->entryDistributionId);
     //		if ($entryDistributionDb)
     //			$this->currentPlaylists = $entryDistributionDb->getFromCustomData('currentPlaylists');
     //		else
     //			KalturaLog::err('Entry distribution ['.$distributionJobData->entryDistributionId.'] not found');
 }
Example #3
0
 public function clearMemory()
 {
     accessControlPeer::clearInstancePool();
     BatchJobPeer::clearInstancePool();
     BulkUploadResultPeer::clearInstancePool();
     categoryPeer::clearInstancePool();
     EmailIngestionProfilePeer::clearInstancePool();
     entryPeer::clearInstancePool();
     FileSyncPeer::clearInstancePool();
     flavorAssetPeer::clearInstancePool();
     flavorParamsConversionProfilePeer::clearInstancePool();
     flavorParamsOutputPeer::clearInstancePool();
     flavorParamsPeer::clearInstancePool();
     kshowPeer::clearInstancePool();
     mediaInfoPeer::clearInstancePool();
     moderationFlagPeer::clearInstancePool();
     moderationPeer::clearInstancePool();
     notificationPeer::clearInstancePool();
     roughcutEntryPeer::clearInstancePool();
     SchedulerConfigPeer::clearInstancePool();
     SchedulerPeer::clearInstancePool();
     SchedulerStatusPeer::clearInstancePool();
     SchedulerWorkerPeer::clearInstancePool();
     StorageProfilePeer::clearInstancePool();
     syndicationFeedPeer::clearInstancePool();
     TrackEntryPeer::clearInstancePool();
     uiConfPeer::clearInstancePool();
     UploadTokenPeer::clearInstancePool();
     // TODO clear default filters
     // TODO call all memory cleaner plugins
     if (function_exists('gc_collect_cycles')) {
         // php 5.3 and above
         gc_collect_cycles();
     }
 }
 /**
  * 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");
     $ksStr = $this->getRequestParameter("ks");
     $referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     // get entry
     $entry = entryPeer::retrieveByPK($entryId);
     if (is_null($entry)) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer);
     $securyEntryHelper->validateForDownload($entry, $ksStr);
     $flavorAsset = null;
     if ($flavorId) {
         // get flavor asset
         $flavorAsset = flavorAssetPeer::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 = flavorAssetPeer::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 = flavorAssetPeer::retrieveOriginalByEntryId($entryId);
     }
     if ($flavorAsset) {
         $syncKey = $this->getSyncKeyAndForFlavorAsset($entry, $flavorAsset);
     } else {
         $syncKey = $this->getBestSyncKeyForEntry($entry);
     }
     list($fileBaseName, $fileExt) = $this->getFileName($entry, $flavorAsset);
     if (!$fileName) {
         $fileName = $fileBaseName;
     }
     if ($fileExt) {
         $fileName = $fileName . '.' . $fileExt;
     }
     if (is_null($syncKey)) {
         KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
     }
     $this->handleFileSyncRedirection($syncKey);
     $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     $this->dumpFile($filePath, $fileName);
     die;
     // no view
 }
Example #5
0
 /**
  * Get base entry by flavor ID with no filters.
  * 
  * @action getByFlavorId
  * @param string $flavorId
  * @param int $version Desired version of the data
  * @return KalturaBaseEntry The requested entry
  */
 public function getByFlavorIdAction($flavorId, $version = -1)
 {
     $flavorAssetDb = flavorAssetPeer::retrieveById($flavorId);
     if (!$flavorAssetDb) {
         throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $flavorId);
     }
     return $this->getAction($flavorAssetDb->getEntryId(), $version);
 }
Example #6
0
 public static function getInstance()
 {
     if (!self::$myInstance) {
         self::$myInstance = new flavorAssetPeer();
     }
     if (!self::$instance || !self::$instance instanceof flavorAssetPeer) {
         self::$instance = self::$myInstance;
     }
     return self::$myInstance;
 }
Example #7
0
 /**
  * @param string $entryId
  * @return mediaInfo
  */
 public static function retrieveOriginalByEntryId($entryId)
 {
     $sourceFlavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entryId);
     if (!$sourceFlavorAsset) {
         return null;
     }
     $criteria = new Criteria();
     $criteria->add(mediaInfoPeer::FLAVOR_ASSET_ID, $sourceFlavorAsset->getId());
     return mediaInfoPeer::doSelectOne($criteria);
 }
 public function initService($serviceId, $serviceName, $actionName)
 {
     parent::initService($serviceId, $serviceName, $actionName);
     parent::applyPartnerFilterForClass(flavorAssetPeer::getInstance());
     parent::applyPartnerFilterForClass(flavorParamsOutputPeer::getInstance());
     parent::applyPartnerFilterForClass(new conversionProfile2Peer());
     $partnerGroup = null;
     if ($actionName == 'add' || $actionName == 'update') {
         $partnerGroup = $this->partnerGroup . ',0';
     }
     parent::applyPartnerFilterForClass(flavorParamsPeer::getInstance(), $partnerGroup);
 }
 public function getEntryId(FileSync $fileSync)
 {
     if ($fileSync->getObjectType() == FileSyncObjectType::ENTRY) {
         return $fileSync->getObjectId();
     }
     if ($fileSync->getObjectType() == FileSyncObjectType::BATCHJOB) {
         $job = BatchJobPeer::retrieveByPK($fileSync->getObjectId());
         if ($job) {
             return $job->getEntryId();
         }
     }
     if ($fileSync->getObjectType() == FileSyncObjectType::FLAVOR_ASSET) {
         $flavor = flavorAssetPeer::retrieveById($fileSync->getObjectId());
         if ($flavor) {
             return $flavor->getEntryId();
         }
     }
     return null;
 }
 private function reconvertEntry($entry_id, $conversion_profile_id, $job_priority)
 {
     $entry = entryPeer::retrieveByPK($entry_id);
     $this->error = "";
     if (!$entry) {
         $error = "Cannot reconvert entry [{$entry_id}]. Might be a deleted entry";
         return array($entry_id, null, null, $error);
     }
     $flavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entry_id);
     if (!$flavorAsset) {
         $flavorAsset = flavorAssetPeer::retrieveReadyWebByEntryId($entry_id);
         if (!$flavorAsset) {
             $flavorAssets = flavorAssetPeer::retrieveByEntryId($entry_id);
             if (!$flavorAssets) {
                 $error = "Cannot find good enough flavor asset to re-convert from";
                 return array($entry_id, $entry, null, $error);
             }
             $flavorAsset = $flavorAssets[0];
             // choose the first one
         }
     }
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     if (!$filePath) {
         $error = "Cannot find a fileSync for the flavorAsset [" . $flavorAsset->getId() . "]";
         return array($entry_id, $entry, null, $error);
     }
     $dbBatchJob = new BatchJob();
     $dbBatchJob->setEntryId($entry_id);
     $dbBatchJob->setPartnerId($entry->getPartnerId());
     $dbBatchJob->setStatus(BatchJob::BATCHJOB_STATUS_PENDING);
     $dbBatchJob->setDc(kDataCenterMgr::getCurrentDcId());
     $dbBatchJob->setPriority($job_priority);
     $dbBatchJob->save();
     // creates a convert profile job
     $convertProfileData = new kConvertProfileJobData();
     $convertProfileData->setFlavorAssetId($flavorAsset->getId());
     $convertProfileData->setInputFileSyncLocalPath($filePath);
     kJobsManager::addJob($dbBatchJob, $convertProfileData, BatchJobType::CONVERT_PROFILE);
     // save again afget the addJob
     $dbBatchJob->save();
     return array($entry_id, $entry, $dbBatchJob, $error);
 }
 /**
  * 
  * @param int $objectType
  * @param string $objectId
  * @return ISyncableFile
  */
 public static function retrieveObject($objectType, $objectId)
 {
     $object = null;
     switch ($objectType) {
         case FileSyncObjectType::ENTRY:
             entryPeer::setUseCriteriaFilter(false);
             $object = entryPeer::retrieveByPK($objectId);
             entryPeer::setUseCriteriaFilter(true);
             break;
         case FileSyncObjectType::UICONF:
             uiConfPeer::setUseCriteriaFilter(false);
             $object = uiConfPeer::retrieveByPK($objectId);
             uiConfPeer::setUseCriteriaFilter(true);
             break;
         case FileSyncObjectType::BATCHJOB:
             BatchJobPeer::setUseCriteriaFilter(false);
             $object = BatchJobPeer::retrieveByPK($objectId);
             BatchJobPeer::setUseCriteriaFilter(true);
             break;
         case FileSyncObjectType::FLAVOR_ASSET:
             flavorAssetPeer::setUseCriteriaFilter(false);
             $object = flavorAssetPeer::retrieveById($objectId);
             flavorAssetPeer::setUseCriteriaFilter(true);
             break;
         case FileSyncObjectType::SYNDICATION_FEED:
             syndicationFeedPeer::setUseCriteriaFilter(false);
             $object = syndicationFeedPeer::retrieveByPK($objectId);
             syndicationFeedPeer::setUseCriteriaFilter(true);
             break;
     }
     if ($object == null) {
         $object = KalturaPluginManager::loadObject('ISyncableFile', $objectType, array('objectId' => $objectId));
     }
     if ($object == null) {
         $error = __METHOD__ . " Cannot find object type [" . $objectType . "] with object_id [" . $objectId . "]";
         KalturaLog::err($error);
         throw new Exception($error);
     }
     return $object;
 }
 /**
  * Called on the server side and enables you to populate the object with any data from the DB
  * 
  * @param KalturaDistributionJobData $distributionJobData
  */
 public function __construct(KalturaDistributionJobData $distributionJobData = null)
 {
     if (!$distributionJobData) {
         return;
     }
     if (!$distributionJobData->distributionProfile instanceof KalturaExampleDistributionProfile) {
         return;
     }
     $this->videoAssetFilePaths = new KalturaExampleDistributionAssetPathArray();
     // loads all the flavor assets that should be submitted to the remote destination site
     $flavorAssets = flavorAssetPeer::retrieveByIds(explode(',', $distributionJobData->entryDistribution->flavorAssetIds));
     foreach ($flavorAssets as $flavorAsset) {
         $videoAssetFilePath = new KalturaExampleDistributionAssetPath();
         $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         $videoAssetFilePath->path = kFileSyncUtils::getLocalFilePathForKey($syncKey, true);
         $this->videoAssetFilePaths[] = $videoAssetFilePath;
     }
     $thumbAssets = thumbAssetPeer::retrieveByIds(explode(',', $distributionJobData->entryDistribution->thumbAssetIds));
     if (count($thumbAssets)) {
         $thumbAsset = reset($thumbAssets);
         $syncKey = $thumbAssets->getSyncKey(thumbAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         $this->thumbAssetFilePath = kFileSyncUtils::getLocalFilePathForKey($syncKey, true);
     }
 }
 public static function decideProfileFlavorsConvert(BatchJob $parentJob, BatchJob $convertProfileJob, array $flavors, array $conversionProfileFlavorParams, mediaInfo $mediaInfo = null)
 {
     $entryId = $convertProfileJob->getEntryId();
     $originalFlavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entryId);
     if (is_null($originalFlavorAsset)) {
         $errDescription = 'Original flavor asset not found';
         KalturaLog::err($errDescription);
         $convertProfileJob = kJobsManager::failBatchJob($convertProfileJob, $errDescription, BatchJobType::CONVERT_PROFILE);
         kBatchManager::updateEntry($convertProfileJob, entryStatus::ERROR_CONVERTING);
         return false;
     }
     $errDescription = null;
     $finalFlavors = self::validateConversionProfile($convertProfileJob->getPartnerId(), $entryId, $mediaInfo, $flavors, $conversionProfileFlavorParams, $errDescription);
     KalturaLog::log(count($finalFlavors) . " flavors returned from the decision layer");
     if (is_null($finalFlavors)) {
         $convertProfileJob = kJobsManager::failBatchJob($convertProfileJob, $errDescription);
         KalturaLog::log("No flavors created");
         throw new Exception($errDescription);
     }
     if (strlen($errDescription)) {
         $err = $convertProfileJob->getDescription() . $errDescription;
         $convertProfileJob->setDescription($err);
         $convertProfileJob->save();
     }
     $srcSyncKey = $originalFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     $conversionsCreated = 0;
     $entry = $convertProfileJob->getEntry();
     if (!$entry) {
         throw new APIException(APIErrors::INVALID_ENTRY, $convertProfileJob, $entryId);
     }
     $flavorsCollections = array();
     // create a convert job per each flavor
     foreach ($finalFlavors as $flavor) {
         $flavorAsset = kBatchManager::createFlavorAsset($flavor, $entry->getPartnerId(), $entry->getId());
         if (!$flavorAsset) {
             KalturaLog::log("Flavor asset could not be created, flavor conversion won't be created");
             continue;
         }
         $collectionTag = $flavor->getCollectionTag();
         if ($collectionTag) {
             $flavorsCollections[$collectionTag][] = $flavor;
             continue;
         }
         KalturaLog::log("Adding flavor conversion with flavor params output id [" . $flavor->getId() . "] and flavor params asset id [" . $flavorAsset->getId() . "]");
         $madiaInfoId = $mediaInfo ? $mediaInfo->getId() : null;
         $createdJob = kJobsManager::addFlavorConvertJob($srcSyncKey, $flavor, $flavorAsset->getId(), $madiaInfoId, $parentJob);
         if ($createdJob) {
             $conversionsCreated++;
         }
     }
     foreach ($flavorsCollections as $tag => $flavors) {
         switch ($tag) {
             case flavorParams::TAG_ISM:
                 $createdJob = kJobsManager::addConvertIsmCollectionJob($tag, $srcSyncKey, $entry, $parentJob, $flavors);
                 if ($createdJob) {
                     $conversionsCreated++;
                 }
                 break;
             default:
                 KalturaLog::log("Error: Invalid collection tag [{$tag}]");
                 break;
         }
     }
     if (!$conversionsCreated) {
         $convertProfileJob = kJobsManager::failBatchJob($convertProfileJob, $errDescription);
         KalturaLog::log("No flavors created: {$errDescription}");
         return false;
     }
     return true;
 }
Example #14
0
 public static function handleBulkDownloadPending(BatchJob $dbBatchJob, kBulkDownloadJobData $data, BatchJob $twinJob = null)
 {
     $entryIds = explode(',', $data->getEntryIds());
     $flavorParamsId = $data->getFlavorParamsId();
     $jobIsFinished = true;
     foreach ($entryIds as $entryId) {
         $entry = entryPeer::retrieveByPK($entryId);
         if (is_null($entry)) {
             KalturaLog::err("Entry id [{$entryId}] not found.");
         } else {
             if ($entry->hasDownloadAsset($flavorParamsId)) {
                 // why we don't send the notification in case of image is ready?
                 $flavorAsset = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($entryId, $flavorParamsId);
                 if ($flavorAsset && $flavorAsset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) {
                     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                     $downloadUrl = $flavorAsset->getDownloadUrl();
                     $localPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
                     $downloadUrl = $flavorAsset->getDownloadUrl();
                     $notificationData = array("puserId" => $entry->getPuserId(), "entryId" => $entry->getId(), "entryIntId" => $entry->getIntId(), "entryVersion" => $entry->getVersion(), "fileFormat" => $flavorAsset->getFileExt(), "archivedFile" => $localPath, "downoladPath" => $localPath, "conversionQuality" => $entry->getConversionQuality(), "downloadUrl" => $downloadUrl);
                     $extraData = array("data" => json_encode($notificationData), "partner_id" => $entry->getPartnerId(), "puser_id" => $entry->getPuserId(), "entry_id" => $entry->getId(), "entry_int_id" => $entry->getIntId(), "entry_version" => $entry->getVersion(), "file_format" => $flavorAsset->getFileExt(), "archived_file" => $localPath, "downolad_path" => $localPath, "target" => $localPath, "conversion_quality" => $entry->getConversionQuality(), "download_url" => $downloadUrl, "status" => $entry->getStatus(), "abort" => $dbBatchJob->getAbort(), "progress" => $dbBatchJob->getProgress(), "message" => $dbBatchJob->getMessage(), "description" => $dbBatchJob->getDescription(), "updates_count" => $dbBatchJob->getUpdatesCount(), "job_type" => BatchJobType::DOWNLOAD, "status" => BatchJob::BATCHJOB_STATUS_FINISHED, "progress" => 100, "debug" => __LINE__);
                     myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_BATCH_JOB_SUCCEEDED, $dbBatchJob, $dbBatchJob->getPartnerId(), null, null, $extraData, $entryId);
                 }
             } else {
                 $jobIsFinished = false;
                 $entry->createDownloadAsset($dbBatchJob, $flavorParamsId, $data->getPuserId());
             }
         }
     }
     if ($jobIsFinished) {
         // mark the job as finished
         $dbBatchJob = kJobsManager::updateBatchJob($dbBatchJob, BatchJob::BATCHJOB_STATUS_FINISHED);
     } else {
         // mark the job as almost done
         $dbBatchJob = kJobsManager::updateBatchJob($dbBatchJob, BatchJob::BATCHJOB_STATUS_ALMOST_DONE);
     }
     return $dbBatchJob;
 }
Example #15
0
 /**
  * @param EntryDistribution $entryDistribution
  * @param int $action enum from DistributionAction
  * @return array<kDistributionValidationError>
  */
 public function validateForSubmission(EntryDistribution $entryDistribution, $action)
 {
     $validationErrors = array();
     $requiredFlavorParamsIds = $this->getRequiredFlavorParamsIdsArray();
     KalturaLog::log("Required Flavor Params Ids [" . print_r($requiredFlavorParamsIds, true) . "]");
     $entryFlavorAssets = flavorAssetPeer::retreiveReadyByEntryId($entryDistribution->getEntryId());
     $requiredFlavorParamsIdsKeys = array_flip($requiredFlavorParamsIds);
     foreach ($entryFlavorAssets as $entryFlavorAsset) {
         $flavorParamsId = $entryFlavorAsset->getFlavorParamsId();
         if (isset($requiredFlavorParamsIdsKeys[$flavorParamsId])) {
             unset($requiredFlavorParamsIds[$requiredFlavorParamsIdsKeys[$flavorParamsId]]);
         }
     }
     foreach ($requiredFlavorParamsIds as $requiredFlavorParamsId) {
         $validationErrors[] = $this->createValidationError($action, DistributionErrorType::MISSING_FLAVOR, $requiredFlavorParamsId);
     }
     $requiredThumbDimensions = $this->getRequiredThumbDimensionsObjects();
     KalturaLog::log("Required Thumb Dimensions [" . print_r($requiredThumbDimensions, true) . "]");
     $entryThumbAssets = thumbAssetPeer::retreiveReadyByEntryId($entryDistribution->getEntryId());
     $requiredThumbDimensionsWithKeys = array();
     foreach ($requiredThumbDimensions as $requiredThumbDimension) {
         $key = $requiredThumbDimension->getKey();
         $requiredThumbDimensionsWithKeys[$key] = $requiredThumbDimension;
     }
     foreach ($entryThumbAssets as $entryThumbAsset) {
         $key = $entryThumbAsset->getWidth() . 'x' . $entryThumbAsset->getHeight();
         if (isset($requiredThumbDimensionsWithKeys[$key])) {
             unset($requiredThumbDimensionsWithKeys[$key]);
         }
     }
     foreach ($requiredThumbDimensionsWithKeys as $key => $requiredThumbDimension) {
         $validationErrors[] = $this->createValidationError($action, DistributionErrorType::MISSING_THUMBNAIL, $key);
     }
     return $validationErrors;
 }
 protected function updatedVirusScanFailed(BatchJob $dbBatchJob, kVirusScanJobData $data, BatchJob $twinJob = null)
 {
     $entry = entryPeer::retrieveByPK($dbBatchJob->getEntryId());
     if ($entry) {
         $entry->setStatus(VirusScanPlugin::getEntryStatusCoreValue(VirusScanEntryStatus::INFECTED));
         $entry->save();
     } else {
         KalturaLog::err('Entry not found with id [' . $dbBatchJob->getEntryId() . ']');
         throw new Exception('Entry not found with id [' . $dbBatchJob->getEntryId() . ']');
     }
     $flavorAsset = flavorAssetPeer::retrieveById($data->getFlavorAssetId());
     if ($flavorAsset) {
         $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
         $flavorAsset->save();
     } else {
         KalturaLog::err('Flavor asset not found with id [' . $data->getFlavorAssetId() . ']');
         throw new Exception('Flavor asset not found with id [' . $data->getFlavorAssetId() . ']');
     }
     // do not resume flavor asset added event consumption
     return $dbBatchJob;
 }
Example #17
0
 /**
  * Copy flavor asset into new entry
  * 
  * @action addFromFlavorAsset
  * @param string $sourceFlavorAssetId Flavor asset id to be used as the new entry source
  * @param KalturaMediaEntry $mediaEntry Media entry metadata
  * @return KalturaMediaEntry The new media entry
  * @throws KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @throws KalturaErrors::ORIGINAL_FLAVOR_ASSET_NOT_CREATED
  */
 function addFromFlavorAssetAction($sourceFlavorAssetId, KalturaMediaEntry $mediaEntry = null)
 {
     $srcFlavorAsset = flavorAssetPeer::retrieveById($sourceFlavorAssetId);
     if (!$srcFlavorAsset) {
         throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $sourceFlavorAssetId);
     }
     $sourceEntryId = $srcFlavorAsset->getEntryId();
     $srcEntry = entryPeer::retrieveByPK($sourceEntryId);
     if (!$srcEntry || $srcEntry->getType() != entryType::MEDIA_CLIP) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $sourceEntryId);
     }
     if ($mediaEntry === null) {
         $mediaEntry = new KalturaMediaEntry();
     }
     $mediaEntry->mediaType = $srcEntry->getMediaType();
     return $this->addEntryFromFlavorAsset($mediaEntry, $srcEntry, $srcFlavorAsset);
 }
Example #18
0
 /**
  * Get Flavor Asset with the relevant Flavor Params (Flavor Params can exist without Flavor Asset & vice versa)
  * 
  * @action getFlavorAssetsWithParams
  * @param string $entryId
  * @return KalturaFlavorAssetWithParamsArray
  */
 public function getFlavorAssetsWithParamsAction($entryId)
 {
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     // get all the flavor params of partner 0 and the current partner (note that partner 0 is defined as partner group in service.ct)
     $flavorParamsDb = flavorParamsPeer::doSelect(new Criteria());
     // get the flavor assets for this entry
     $c = new Criteria();
     $c->add(flavorAssetPeer::ENTRY_ID, $entryId);
     $c->add(flavorAssetPeer::STATUS, array(flavorAsset::FLAVOR_ASSET_STATUS_DELETED, flavorAsset::FLAVOR_ASSET_STATUS_TEMP), Criteria::NOT_IN);
     $flavorAssetsDb = flavorAssetPeer::doSelect($c);
     // find what flavot params are required
     $requiredFlavorParams = array();
     foreach ($flavorAssetsDb as $item) {
         $requiredFlavorParams[$item->getFlavorParamsId()] = true;
     }
     // now merge the results, first organize the flavor params in an array with the id as the key
     $flavorParamsArray = array();
     foreach ($flavorParamsDb as $item) {
         $flavorParams = $item->getId();
         $flavorParamsArray[$flavorParams] = $item;
         if (isset($requiredFlavorParams[$flavorParams])) {
             unset($requiredFlavorParams[$flavorParams]);
         }
     }
     // adding missing required flavors params to the list
     if (count($requiredFlavorParams)) {
         $flavorParamsDb = flavorParamsPeer::retrieveByPKsNoFilter(array_keys($requiredFlavorParams));
         foreach ($flavorParamsDb as $item) {
             $flavorParamsArray[$item->getId()] = $item;
         }
     }
     $usedFlavorParams = array();
     // loop over the flavor assets and add them, if it has flavor params add them too
     $flavorAssetWithParamsArray = new KalturaFlavorAssetWithParamsArray();
     foreach ($flavorAssetsDb as $flavorAssetDb) {
         $flavorParamsId = $flavorAssetDb->getFlavorParamsId();
         $flavorAssetWithParams = new KalturaFlavorAssetWithParams();
         $flavorAssetWithParams->entryId = $entryId;
         $flavorAsset = new KalturaFlavorAsset();
         $flavorAsset->fromObject($flavorAssetDb);
         $flavorAssetWithParams->flavorAsset = $flavorAsset;
         if (isset($flavorParamsArray[$flavorParamsId])) {
             $flavorParamsDb = $flavorParamsArray[$flavorParamsId];
             $flavorParams = KalturaFlavorParamsFactory::getFlavorParamsInstance($flavorParamsDb->getType());
             $flavorParams->fromObject($flavorParamsDb);
             $flavorAssetWithParams->flavorParams = $flavorParams;
             // we want to log which flavor params are in use, there could be more
             // than one flavor asset using same params
             $usedFlavorParams[$flavorParamsId] = $flavorParamsId;
         }
         //			else if ($flavorAssetDb->getIsOriginal())
         //			{
         //				// create a dummy flavor params
         //				$flavorParams = new KalturaFlavorParams();
         //				$flavorParams->name = "Original source";
         //				$flavorAssetWithParams->flavorParams = $flavorParams;
         //			}
         $flavorAssetWithParamsArray[] = $flavorAssetWithParams;
     }
     // copy the remaining params
     foreach ($flavorParamsArray as $flavorParamsId => $flavorParamsDb) {
         if (isset($usedFlavorParams[$flavorParamsId])) {
             // flavor params already exists for a flavor asset, not need
             // to list it one more time
             continue;
         }
         $flavorParams = KalturaFlavorParamsFactory::getFlavorParamsInstance($flavorParamsDb->getType());
         $flavorParams->fromObject($flavorParamsDb);
         $flavorAssetWithParams = new KalturaFlavorAssetWithParams();
         $flavorAssetWithParams->entryId = $entryId;
         $flavorAssetWithParams->flavorParams = $flavorParams;
         $flavorAssetWithParamsArray[] = $flavorAssetWithParams;
     }
     return $flavorAssetWithParamsArray;
 }
 /**
  *  request conversion for all entries that doesnt have the required flavor param
  *  returns a comma-separated ids of conversion jobs
  *
  *  @action requestConversion
  *  @param string $feedId
  *  @return string
  */
 public function requestConversionAction($feedId)
 {
     // find entry ids that already converted to the flavor
     $feedRendererWithTheFlavor = new KalturaSyndicationFeedRenderer($feedId);
     $feedRendererWithTheFlavor->addFlavorParamsAttachedFilter();
     $entriesWithTheFlavor = $feedRendererWithTheFlavor->getEntriesIds();
     // create filter of the entries that not converted
     $entryFilter = new entryFilter();
     $entryFilter->setIdNotIn($entriesWithTheFlavor);
     // create feed with the new filter
     $feedRendererToConvert = new KalturaSyndicationFeedRenderer($feedId);
     $feedRendererToConvert->addFilter($entryFilter);
     $createdJobsIds = array();
     $flavorParamsId = $feedRendererToConvert->syndicationFeed->flavorParamId;
     while ($entry = $feedRendererToConvert->getNextEntry()) {
         $originalFlavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entry->getId());
         if (!is_null($originalFlavorAsset)) {
             $err = "";
             $job = kBusinessPreConvertDL::decideAddEntryFlavor(null, $entry->getId(), $flavorParamsId, $err);
             if ($job && is_object($job)) {
                 $createdJobsIds[] = $job->getId();
             }
         }
     }
     return implode(',', $createdJobsIds);
 }
Example #20
0
 private function calculateId()
 {
     $dc = kDataCenterMgr::getCurrentDc();
     for ($i = 0; $i < 10; $i++) {
         $id = $dc["id"] . '_' . kString::generateStringId();
         $existingObject = flavorAssetPeer::retrieveById($id);
         if ($existingObject) {
             KalturaLog::log(__METHOD__ . ": id [{$id}] already exists");
         } else {
             return $id;
         }
     }
     throw new Exception("Could not find unique id for flavorAsset");
 }
 public function execute()
 {
     $this->entryId = $this->getRequestParameter("entryId", null);
     $this->flavorId = $this->getRequestParameter("flavorId", null);
     $this->storageId = $this->getRequestParameter("storageId", null);
     $this->maxBitrate = $this->getRequestParameter("maxBitrate", null);
     $flavorIdsStr = $this->getRequestParameter("flavorIds", null);
     if ($flavorIdsStr) {
         $this->flavorIds = explode(",", $flavorIdsStr);
     }
     $this->entry = entryPeer::retrieveByPKNoFilter($this->entryId);
     if (!$this->entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     if (!$this->flavorId) {
         $flavorParamId = $this->getRequestParameter("flavorParamId", null);
         if ($flavorParamId) {
             $flavorAsset = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($entry->getId(), $flavorParamId);
             if (!$flavorAsset) {
                 KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
             }
             $this->flavorId = $flavorAsset->getId();
         }
     }
     $this->validateStorageId();
     $this->protocol = $this->getRequestParameter("protocol", null);
     if (!$this->protocol) {
         $this->protocol = StorageProfile::PLAY_FORMAT_HTTP;
     }
     $this->format = $this->getRequestParameter("format");
     if (!$this->format) {
         $this->format = StorageProfile::PLAY_FORMAT_HTTP;
     }
     $this->cdnHost = $this->getRequestParameter("cdnHost", null);
     $partner = $this->entry->getPartner();
     if (!$this->cdnHost || $partner->getForceCdnHost()) {
         $this->cdnHost = myPartnerUtils::getCdnHost($this->entry->getPartnerId(), $this->protocol);
     }
     if ($this->maxBitrate && (!is_numeric($this->maxBitrate) || $this->maxBitrate <= 0)) {
         KExternalErrors::dieError(KExternalErrors::INVALID_MAX_BITRATE);
     }
     $ksStr = $this->getRequestParameter("ks");
     $base64Referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64Referrer);
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     $securyEntryHelper = new KSecureEntryHelper($this->entry, $ksStr, $referrer);
     if ($securyEntryHelper->shouldPreview()) {
         $this->clipTo = $securyEntryHelper->getPreviewLength() * 1000;
     } else {
         $securyEntryHelper->validateForPlay($this->entry, $ksStr);
     }
     // grab seekFrom parameter and normalize url
     $this->seekFrom = $this->getRequestParameter("seekFrom", -1);
     if ($this->seekFrom <= 0) {
         $this->seekFrom = -1;
     }
     if ($this->entry->getStatus() == entryStatus::DELETED) {
         // because the fiter was turned off - a manual check for deleted entries must be done.
         die;
     }
     $xml = null;
     switch ($this->format) {
         case StorageProfile::PLAY_FORMAT_HTTP:
             $xml = $this->serveHttp();
             break;
         case StorageProfile::PLAY_FORMAT_RTMP:
             $xml = $this->serveRtmp();
             break;
         case StorageProfile::PLAY_FORMAT_SILVER_LIGHT:
             $xml = $this->serveSilverLight();
             break;
         case StorageProfile::PLAY_FORMAT_APPLE_HTTP:
             $xml = $this->serveAppleHttp();
             break;
         case "url":
             return $this->serveUrl();
             break;
         case "hdnetworksmil":
             $xml = $this->serveHDNetwork();
             break;
         case "hdnetwork":
             $duration = $this->entry->getDurationInt();
             $mediaUrl = "<media url=\"" . requestUtils::getHost() . str_replace("f4m", "smil", str_replace("hdnetwork", "hdnetworksmil", $_SERVER["REQUEST_URI"])) . "\"/>";
             $xml = $this->buildXml(self::PLAY_STREAM_TYPE_RECORDED, array(), 'video/x-flv', $duration, null, $mediaUrl);
             break;
     }
     if ($this->format == StorageProfile::PLAY_FORMAT_APPLE_HTTP) {
         header("Content-Type: text/plain; charset=UTF-8");
     } else {
         header("Content-Type: text/xml; charset=UTF-8");
         header("Content-Disposition: inline; filename=manifest.xml");
     }
     echo $xml;
     die;
 }
Example #22
0
 /**
  * Add the data to the flavor asset conversion log, creates it if doesn't exists
  * 
  * @action logConversion
  * @param string $flavorAssetId
  * @param string $data
  */
 function logConversionAction($flavorAssetId, $data)
 {
     $flavorAsset = flavorAssetPeer::retrieveById($flavorAssetId);
     // verifies that flavor asset exists
     if (!$flavorAsset) {
         throw new APIException(APIErrors::INVALID_FLAVOR_ASSET_ID, $flavorAssetId);
     }
     $flavorAsset->incLogFileVersion();
     $flavorAsset->save();
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_CONVERT_LOG);
     $log = kFileSyncUtils::file_get_contents($syncKey, true, false);
     $log .= $data;
     kFileSyncUtils::file_put_contents($syncKey, $log, false);
 }
Example #23
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     // where file is {entryId/flavorId}.{ism,ismc,ismv}
     $objectId = $type = null;
     $objectIdStr = $this->getRequestParameter("objectId");
     list($objectId, $type) = @explode(".", $objectIdStr);
     if (!$type || !$objectId) {
         die;
     }
     $ks = $this->getRequestParameter("ks");
     $referrer = base64_decode($this->getRequestParameter("referrer"));
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = '';
     }
     if ($type == "ism" || $type == "ismc") {
         // backward compatiblity - to be removed once ismc is created with pure objectId.ext instead of entryId_flavorId_version.ext
         if (strlen($objectId) != 10) {
             $version = substr($objectId, 13);
             $objectId = substr($objectId, 0, 10);
         } else {
             $version = null;
         }
         $entry = entryPeer::retrieveByPK($objectId);
         if (is_null($entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
         $syncKey = $entry->getSyncKey($type == "ism" ? entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM : entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC, $version);
     } else {
         if ($type == "ismv") {
             // backward compatiblity - to be removed once ismc is created with pure objectId.ext instead of entryId_flavorId_version.ext
             if (strlen($objectId) != 10) {
                 $version = substr($objectId, 22);
                 $objectId = substr($objectId, 11, 10);
             } else {
                 $version = null;
             }
             $flavorAsset = flavorAssetPeer::retrieveById($objectId);
             if (is_null($flavorAsset)) {
                 KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
             }
             $entry = entryPeer::retrieveByPK($flavorAsset->getEntryId());
             if (is_null($entry)) {
                 KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
             }
             $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version);
         } else {
             die;
         }
     }
     if (!kFileSyncUtils::file_exists($syncKey, false)) {
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if (is_null($fileSync)) {
             KalturaLog::log("Error - no FileSync for type [{$type}] objectId [{$objectId}]");
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         kFile::dumpUrl($remoteUrl);
     }
     $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     kFile::dumpFile($path);
 }
 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);
     // 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
     $entry = entryPeer::retrieveByPKNoFilter($entry_id);
     if (!$entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     // 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.
         die;
     } 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);
             kFile::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 = flavorAssetPeer::retrieveBestEditByEntryId($entry->getId());
     } elseif (!is_null($flavor)) {
         $flavorAsset = flavorAssetPeer::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 = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($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 = flavorAssetPeer::retrieveOriginalByEntryId($entry->getId());
         } else {
             $flavorAsset = flavorAssetPeer::retrieveBestPlayByEntryId($entry->getId());
         }
         if (!$flavorAsset) {
             $flavorAssets = flavorAssetPeer::retreiveReadyByEntryIdAndTag($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);
         }
         $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}");
         die;
     } 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}");
         die;
     }
     // 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);
         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");
                     die;
                 }
                 $ks = kSessionUtils::crackKs($ks_str);
                 if (!$ks) {
                     $this->logMessage("flvclipper - invalid ks [{$ks_str}]");
                     die;
                 }
                 $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}]");
                     die;
                 }
             }
             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}");
                     die;
                 } 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}");
                         die;
                     }
                 }
             }
             // 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);
         die;
     }
     // mp4
     if (!$isFlv) {
         kFile::dumpFile($path);
     }
     $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}");
     }
     return sfView::SUCCESS;
 }
Example #25
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     requestUtils::handleConditionalGet();
     $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 = entryPeer::retrieveByPK($entry_id);
     if (!$entry) {
         // what to return ??
         die;
     }
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     $securyEntryHelper = new KSecureEntryHelper($entry, $ks, $referrer);
     $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 = flavorAssetPeer::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 = flavorAssetPeer::retrieveByEntryIdAndExtension($entry_id, $format);
         } else {
             $flavor_asset = flavorAssetPeer::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 = flavorAssetPeer::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 = flavorAssetPeer::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) {
                     $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 = flavorAssetPeer::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 ) . "]";
     $mime_type = kFile::mimeType($archive_file);
     //		echo "[[$mime_type]]";
     if (!empty($relocate)) {
         // after relocation - dump the file
         kFile::dumpFile($archive_file, $mime_type);
         die;
     } else {
         // 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 && pathinfo($ret_file_name, PATHINFO_EXTENSION) != "") {
             // if the name holds an extension - prefer it over the real file's extension
             $ext = pathinfo($ret_file_name, PATHINFO_EXTENSION);
         }
         if (!$ret_file_name) {
             // don't leave the name empty - if it is empty - use the entry id
             $ret_file_name = $entry_id;
         }
         if (strpos($url, "?") > 0) {
             $url = str_replace("?", "/{$ret_file_name}.{$ext}?", $url);
             $url .= "&relocate=f.{$ext}";
             // add the ufname as a query parameter
         } else {
             $url .= "/{$ret_file_name}.{$ext}?relocate=f.{$ext}";
             // add the ufname as a query parameter
         }
         // redirect and create the url so it will have the ufname
         header("Location: {$url}");
     }
     die;
 }
Example #26
0
 /**
  * Convert entry
  * 
  * @param string $entryId Media entry id
  * @param int $conversionProfileId
  * @param KalturaConversionAttributeArray $dynamicConversionAttributes
  * @return int job id
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @throws KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND
  * @throws KalturaErrors::FLAVOR_PARAMS_NOT_FOUND
  */
 protected function convert($entryId, $conversionProfileId = null, KalturaConversionAttributeArray $dynamicConversionAttributes = null)
 {
     $entry = entryPeer::retrieveByPK($entryId);
     if (!$entry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $srcFlavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entryId);
     if (!$srcFlavorAsset) {
         throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING);
     }
     if (is_null($conversionProfileId) || $conversionProfileId <= 0) {
         $conversionProfile = myPartnerUtils::getConversionProfile2ForEntry($entryId);
         if (!$conversionProfile) {
             throw new KalturaAPIException(KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND, $conversionProfileId);
         }
         $conversionProfileId = $conversionProfile->getId();
     }
     $srcSyncKey = $srcFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     // if the file sync isn't local (wasn't synced yet) proxy request to other datacenter
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($srcSyncKey, true, false);
     if (!$local) {
         // over come a bug in kFileSyncUtils which return an unready filesync as the filesync of a remote dc
         $fileSync = kFileSyncUtils::getReadyExternalFileSyncForKey($srcSyncKey, 1 - kDataCenterMgr::getCurrentDcId());
         $fileSync = kFileSyncUtils::resolve($fileSync);
         kFile::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrl($fileSync));
     } else {
         if (!$fileSync) {
             throw new KalturaAPIException(KalturaErrors::FILE_DOESNT_EXIST);
         }
     }
     // even if it null
     $entry->setConversionQuality($conversionProfileId);
     $entry->setConversionProfileId($conversionProfileId);
     $entry->save();
     if ($dynamicConversionAttributes) {
         $flavors = flavorParamsPeer::retrieveByProfile($conversionProfileId);
         if (!count($flavors)) {
             throw new KalturaAPIException(KalturaErrors::FLAVOR_PARAMS_NOT_FOUND);
         }
         $srcFlavorParamsId = null;
         $flavorParams = $entry->getDynamicFlavorAttributes();
         foreach ($flavors as $flavor) {
             if ($flavor->hasTag(flavorParams::TAG_SOURCE)) {
                 $srcFlavorParamsId = $flavor->getId();
             }
             $flavorParams[$flavor->getId()] = $flavor;
         }
         $dynamicAttributes = array();
         foreach ($dynamicConversionAttributes as $dynamicConversionAttribute) {
             if (is_null($dynamicConversionAttribute->flavorParamsId)) {
                 $dynamicConversionAttribute->flavorParamsId = $srcFlavorParamsId;
             }
             if (is_null($dynamicConversionAttribute->flavorParamsId)) {
                 continue;
             }
             $dynamicAttributes[$dynamicConversionAttribute->flavorParamsId][trim($dynamicConversionAttribute->name)] = trim($dynamicConversionAttribute->value);
         }
         if (count($dynamicAttributes)) {
             $entry->setDynamicFlavorAttributes($dynamicAttributes);
             $entry->save();
         }
     }
     $srcFilePath = kFileSyncUtils::getLocalFilePathForKey($srcSyncKey);
     $job = kJobsManager::addConvertProfileJob(null, $entry, $srcFlavorAsset->getId(), $srcFilePath);
     if (!$job) {
         return null;
     }
     return $job->getId();
 }
Example #27
0
 /**
  * @param BaseObject $object
  */
 protected function setRelatedObject(AuditTrail $auditTrail, BaseObject $object)
 {
     if (class_exists('Metadata') && $object instanceof Metadata) {
         $auditTrail->setRelatedObjectType(AuditTrailObjectType::METADATA_PROFILE);
         $auditTrail->setRelatedObjectId($object->getMetadataProfileId());
     }
     if ($auditTrail->getAction() == AuditTrail::AUDIT_TRAIL_ACTION_FILE_SYNC_CREATED) {
         $peer = $object->getPeer();
         $objectType = $peer->getOMClass(false, null);
         $auditTrail->setRelatedObjectType($objectType);
         $auditTrail->setRelatedObjectId($object->getId());
     }
     if ($object instanceof FileSync) {
         switch ($object->getObjectType()) {
             case FileSyncObjectType::ENTRY:
                 $auditTrail->setRelatedObjectType(AuditTrailObjectType::ENTRY);
                 $auditTrail->setRelatedObjectId($object->getObjectId());
                 $auditTrail->setEntryId($object->getObjectId());
                 break;
             case FileSyncObjectType::UICONF:
                 $auditTrail->setRelatedObjectType(AuditTrailObjectType::UI_CONF);
                 $auditTrail->setRelatedObjectId($object->getObjectId());
                 break;
             case FileSyncObjectType::BATCHJOB:
                 $auditTrail->setRelatedObjectType(AuditTrailObjectType::BATCH_JOB);
                 $auditTrail->setRelatedObjectId($object->getObjectId());
                 $batchJob = BatchJobPeer::retrieveByPK($object->getObjectId());
                 if ($batchJob) {
                     $auditTrail->setEntryId($batchJob->getEntryId());
                 }
                 break;
             case FileSyncObjectType::FLAVOR_ASSET:
                 $auditTrail->setRelatedObjectType(AuditTrailObjectType::FLAVOR_ASSET);
                 $auditTrail->setRelatedObjectId($object->getObjectId());
                 $flavorAsset = flavorAssetPeer::retrieveById($object->getObjectId());
                 if ($flavorAsset) {
                     $auditTrail->setEntryId($flavorAsset->getEntryId());
                 }
                 break;
             case FileSyncObjectType::METADATA:
                 $auditTrail->setRelatedObjectType(AuditTrailObjectType::METADATA);
                 $auditTrail->setRelatedObjectId($object->getObjectId());
                 if (class_exists('Metadata')) {
                     $metadata = MetadataPeer::retrieveByPK($object->getObjectId());
                     if ($metadata && $metadata->getObjectType() == Metadata::TYPE_ENTRY) {
                         $auditTrail->setEntryId($metadata->getObjectId());
                     }
                 }
                 break;
             case FileSyncObjectType::METADATA_PROFILE:
                 $auditTrail->setRelatedObjectType(AuditTrailObjectType::METADATA_PROFILE);
                 $auditTrail->setRelatedObjectId($object->getObjectId());
                 break;
         }
     }
 }
 public function execute()
 {
     requestUtils::handleConditionalGet();
     $flavorId = $this->getRequestParameter("flavorId");
     $shouldProxy = $this->getRequestParameter("forceproxy", false);
     $ks = $this->getRequestParameter("ks");
     $fileParam = $this->getRequestParameter("file");
     $referrer = base64_decode($this->getRequestParameter("referrer"));
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = '';
     }
     $flavorAsset = flavorAssetPeer::retrieveById($flavorId);
     if (is_null($flavorAsset)) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     $entry = entryPeer::retrieveByPK($flavorAsset->getEntryId());
     if (is_null($entry)) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     myPartnerUtils::blockInactivePartner($flavorAsset->getPartnerId());
     myPartnerUtils::enforceDelivery($flavorAsset->getPartnerId());
     //disabled enforce cdn because of rtmp delivery
     //requestUtils::enforceCdnDelivery($flavorAsset->getPartnerId());
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     if (!kFileSyncUtils::file_exists($syncKey, false)) {
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if (is_null($fileSync)) {
             KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]");
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
         // always dump remote urls so they will be cached by the cdn transparently
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         kFile::dumpUrl($remoteUrl, true, true);
     }
     $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     $flvWrapper = new myFlvHandler($path);
     $isFlv = $flvWrapper->isFlv();
     $clipFrom = $this->getRequestParameter("clipFrom", 0);
     // milliseconds
     $clipTo = $this->getRequestParameter("clipTo", 2147483647);
     // milliseconds
     if ($clipTo == 0) {
         $clipTo = 2147483647;
     }
     if (is_dir($path) && $fileParam) {
         $path .= "/{$fileParam}";
         //echo "path($path),file($fileParam)";
         kFile::dumpFile($path, null, null);
         die;
     } else {
         if (!$isFlv) {
             $limit_file_size = 0;
             if ($clipTo != 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(@filesize($path) * ($clipTo / $duration));
                 }
             }
             kFile::dumpFile($path, null, null, $limit_file_size);
             die;
         }
     }
     $audioOnly = $this->getRequestParameter("audioOnly");
     // milliseconds
     if ($audioOnly === '0') {
         // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations
     } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) {
         $audioOnly = true;
     }
     $seekFrom = $this->getRequestParameter("seekFrom", -1);
     if ($seekFrom <= 0) {
         $seekFrom = -1;
     }
     $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1);
     if ($seekFromBytes <= 0) {
         $seekFromBytes = -1;
     }
     $bytes = 0;
     if ($seekFrom !== -1 && $seekFrom !== 0) {
         list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly);
         list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly);
         $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte;
     } else {
         list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly);
     }
     $metadataSize = $flvWrapper->getMetadataSize($audioOnly);
     $dataOffset = $metadataSize + myFlvHandler::getHeaderSize();
     $totalLength = $dataOffset + $bytes;
     list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly);
     list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength);
     if ($totalLength < 1000) {
         // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache
         requestUtils::sendCdnHeaders("flv", $rangeLength, 0);
     } else {
         requestUtils::sendCdnHeaders("flv", $rangeLength);
     }
     header('Content-Disposition: attachment; filename="video.flv"');
     // dont inject cuepoint into the stream
     $cuepointTime = 0;
     $cuepointPos = 0;
     try {
         Propel::close();
     } catch (Exception $e) {
         $this->logMessage("serveFlavor: error closing db {$e}");
     }
     header("Content-Type: video/x-flv");
     $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos);
     die;
 }
Example #29
0
 public static function copyEntry(entry $entry, Partner $toPartner = null, $dontCopyUsers = false)
 {
     KalturaLog::log("copyEntry - Copying entry [" . $entry->getId() . "] to partner [" . $toPartner->getId() . "]");
     $newEntry = $entry->copy();
     $newEntry->setIntId(null);
     if ($toPartner instanceof Partner) {
         $newEntry->setPartnerId($toPartner->getId());
         $newEntry->setSubpId($toPartner->getId() * 100);
         $newEntry->setAccessControlId($toPartner->getDefaultAccessControlId());
         $flavorParamsStr = $entry->getFlavorParamsIds();
         $flavorParams = explode(',', $flavorParamsStr);
         $newFlavorParams = array();
         foreach ($flavorParams as $flavorParamsId) {
             $newFlavorParamsId = kObjectCopyHandler::getMappedId('flavorParams', $flavorParamsId);
             if (is_null($newFlavorParamsId)) {
                 $newFlavorParamsId = $flavorParamsId;
             }
             $newFlavorParams[] = $newFlavorParamsId;
         }
         $newEntry->setFlavorParamsIds(implode(',', $newFlavorParams));
     }
     $newKuser = null;
     if (!$dontCopyUsers) {
         // copy the kuser (if the same puser id exists its kuser will be used)
         kuserPeer::setUseCriteriaFilter(false);
         $kuser = $entry->getKuser();
         $newKuser = kuserPeer::createKuserForPartner($newEntry->getPartnerId(), $kuser->getPuserId());
         $newEntry->setKuserId($newKuser->getId());
         kuserPeer::setUseCriteriaFilter(true);
     }
     // copy the kshow
     kshowPeer::setUseCriteriaFilter(false);
     $kshow = $entry->getKshow();
     if ($kshow) {
         $newKshow = $kshow->copy();
         $newKshow->setIntId(null);
         $newKshow->setPartnerId($toPartner->getId());
         $newKshow->setSubpId($toPartner->getId() * 100);
         if ($newKuser) {
             $newKshow->setProducerId($newKuser->getId());
         }
         $newKshow->save();
         $newEntry->setKshowId($newKshow->getId());
     }
     kshowPeer::setUseCriteriaFilter(true);
     // reset the statistics
     myEntryUtils::resetEntryStatistics($newEntry);
     // set the new partner id into the default category criteria filter
     $defaultCategoryFilter = categoryPeer::getCriteriaFilter()->getFilter();
     $oldPartnerId = $defaultCategoryFilter->get(categoryPeer::PARTNER_ID);
     $defaultCategoryFilter->remove(categoryPeer::PARTNER_ID);
     $defaultCategoryFilter->addAnd(categoryPeer::PARTNER_ID, $newEntry->getPartnerId());
     // save the entry
     $newEntry->save();
     // restore the original partner id in the default category criteria filter
     $defaultCategoryFilter->remove(categoryPeer::PARTNER_ID);
     $defaultCategoryFilter->addAnd(categoryPeer::PARTNER_ID, $oldPartnerId);
     KalturaLog::log("copyEntry - New entry [" . $newEntry->getId() . "] was created");
     // for any type that does not require assets:
     $shouldCopyDataForNonClip = $entry->getType() != entryType::MEDIA_CLIP;
     $shouldCopyDataForClip = false;
     // only images get their data copied
     if ($entry->getType() == entryType::MEDIA_CLIP) {
         if ($entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_VIDEO && $entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_AUDIO) {
             $shouldCopyDataForClip = true;
         }
     }
     if ($shouldCopyDataForNonClip || $shouldCopyDataForClip) {
         // copy the data
         $from = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         // replaced__getDataPath
         $to = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         // replaced__getDataPath
         KalturaLog::log("copyEntriesByType - copying entry data [" . $from . "] to [" . $to . "]");
         kFileSyncUtils::softCopy($from, $to);
     }
     $ismFrom = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM);
     if (kFileSyncUtils::fileSync_exists($ismFrom)) {
         $ismTo = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM);
         KalturaLog::log("copying entry ism [" . $ismFrom . "] to [" . $ismTo . "]");
         kFileSyncUtils::softCopy($ismFrom, $ismTo);
     }
     $ismcFrom = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC);
     if (kFileSyncUtils::fileSync_exists($ismcFrom)) {
         $ismcTo = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC);
         KalturaLog::log("copying entry ism [" . $ismcFrom . "] to [" . $ismcTo . "]");
         kFileSyncUtils::softCopy($ismcFrom, $ismcTo);
     }
     $from = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
     // replaced__getThumbnailPath
     $considerCopyThumb = true;
     // if entry is image - data is thumbnail, and it was copied
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         $considerCopyThumb = false;
     }
     // if entry is not clip, and there is no file in both DCs - nothing to copy
     if ($entry->getType() != entryType::MEDIA_CLIP && !kFileSyncUtils::file_exists($from, true)) {
         $considerCopyThumb = false;
     }
     if ($considerCopyThumb) {
         $skipThumb = false;
         // don't attempt to copy a thumbnail for images - it's the same as the data which was just created
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) {
             // check if audio entry has real thumb, if not - don't copy thumb.
             $originalFileSync = kFileSyncUtils::getOriginFileSyncForKey($from, false);
             if (!$originalFileSync) {
                 $skipThumb = true;
             }
         }
         if (!$skipThumb) {
             $to = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
             // replaced__getThumbnailPath
             KalturaLog::log("copyEntriesByType - copying entry thumbnail [" . $from . "] to [" . $to . "]");
             kFileSyncUtils::softCopy($from, $to);
         }
     }
     // added by Tan-Tan 12/01/2010 to support falvors copy
     $sourceFlavorAssets = flavorAssetPeer::retrieveByEntryId($entry->getId());
     foreach ($sourceFlavorAssets as $sourceFlavorAsset) {
         $sourceFlavorAsset->copyToEntry($newEntry->getId(), $newEntry->getPartnerId());
     }
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL2;
     requestUtils::handleConditionalGet();
     ignore_user_abort();
     $entry_id = $this->getRequestParameter("entry_id");
     $widget_id = $this->getRequestParameter("widget_id", 0);
     $upload_token_id = $this->getRequestParameter("upload_token_id");
     $version = $this->getRequestParameter("version", null);
     $width = $this->getRequestParameter("width", -1);
     $height = $this->getRequestParameter("height", -1);
     $type = $this->getRequestParameter("type", 1);
     $crop_provider = $this->getRequestParameter("crop_provider", null);
     $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);
     // actual width and height of image from which the src_* values were taken.
     // these will be used to multiply the src_* parameters to make them relate to the original image size.
     $rel_width = $this->getRequestParameter("rel_width", -1);
     $rel_height = $this->getRequestParameter("rel_height", -1);
     if ($width == -1 && $height == -1) {
         $width = 120;
         $height = 90;
     } 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;
             }
         }
     }
     $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
     if ($upload_token_id) {
         $upload_token = UploadTokenPeer::retrieveByPK($upload_token_id);
         if ($upload_token) {
             $thumb_full_path = myContentStorage::getFSCacheRootPath() . myContentStorage::getGeneralEntityPath("uploadtokenthumb", $upload_token->getIntId(), $upload_token->getId(), $upload_token->getId() . ".jpg");
             kFile::fullMkdir($thumb_full_path);
             if (file_exists($upload_token->getUploadTempPath())) {
                 $src_full_path = $upload_token->getUploadTempPath();
                 $valid_image_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_WBMP);
                 $image_type = exif_imagetype($src_full_path);
                 if (!in_array($image_type, $valid_image_types)) {
                     // capture full frame
                     myFileConverter::captureFrame($src_full_path, $thumb_full_path, 1, "image2", -1, -1, 3);
                     if (!file_exists($thumb_full_path)) {
                         myFileConverter::captureFrame($src_full_path, $thumb_full_path, 1, "image2", -1, -1, 0);
                     }
                     $src_full_path = $thumb_full_path;
                 }
                 // and resize it
                 myFileConverter::convertImage($src_full_path, $thumb_full_path, $width, $height, $type, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h);
                 kFile::dumpFile($thumb_full_path);
             }
         }
     }
     $entry = entryPeer::retrieveByPKNoFilter($entry_id);
     // multiply the passed $src_* values so that they will relate to the original image size, according to $src_display_*
     if ($rel_width != -1) {
         $widthRatio = $entry->getWidth() / $rel_width;
         $src_x = $src_x * $widthRatio;
         $src_w = $src_w * $widthRatio;
     }
     if ($rel_height != -1) {
         $heightRatio = $entry->getHeight() / $rel_height;
         $src_y = $src_y * $heightRatio;
         $src_h = $src_h * $heightRatio;
     }
     if (!$entry) {
         // get the widget
         $widget = widgetPeer::retrieveByPK($widget_id);
         if (!$widget) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_AND_WIDGET_NOT_FOUND);
         }
         // get the kshow
         $kshow_id = $widget->getKshowId();
         $kshow = kshowPeer::retrieveByPK($kshow_id);
         if ($kshow) {
             $entry_id = $kshow->getShowEntryId();
         } else {
             $entry_id = $widget->getEntryId();
         }
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB;
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA;
     }
     $dataKey = $entry->getSyncKey($subType);
     list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($dataKey, true, false);
     $tempThumbPath = null;
     $entry_status = $entry->getStatus();
     // both 640x480 and 0x0 requests are probably coming from the kdp
     // 640x480 - old kdp version requesting thumbnail
     // 0x0 - new kdp version requesting the thumbnail of an unready entry
     // we need to distinguish between calls from the kdp and calls from a browser: <img src=...>
     // that can't handle swf input
     if (($width == 640 && $height == 480 || $width == 0 && $height == 0) && ($entry_status == entryStatus::PRECONVERT || $entry_status == entryStatus::IMPORT || $entry_status == entryStatus::ERROR_CONVERTING || $entry_status == entryStatus::DELETED)) {
         $contentPath = myContentStorage::getFSContentRootPath();
         $msgPath = $contentPath . "content/templates/entry/bigthumbnail/";
         if ($entry_status == entryStatus::DELETED) {
             $msgPath .= $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK ? "entry_blocked.swf" : "entry_deleted.swf";
         } else {
             $msgPath .= $entry_status == entryStatus::ERROR_CONVERTING ? "entry_error.swf" : "entry_converting.swf";
         }
         kFile::dumpFile($msgPath, null, 0);
     }
     if (!$file_sync) {
         // if entry type is audio - serve generic thumb:
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) {
             if ($entry->getStatus() == entryStatus::DELETED && $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK) {
                 KalturaLog::log("rejected audio entry - not serving thumbnail");
                 KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
             }
             $contentPath = myContentStorage::getFSContentRootPath();
             $msgPath = $contentPath . "content/templates/entry/thumbnail/audio_thumb.jpg";
             $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, $msgPath);
             //kFile::dumpFile($tempThumbPath, null, 0);
         } elseif ($entry->getType() == entryType::LIVE_STREAM) {
             if ($entry->getStatus() == entryStatus::DELETED && $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK) {
                 KalturaLog::log("rejected live stream entry - not serving thumbnail");
                 KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
             }
             $contentPath = myContentStorage::getFSContentRootPath();
             $msgPath = $contentPath . "content/templates/entry/thumbnail/live_thumb.jpg";
             $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, $msgPath);
         } elseif ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_SHOW) {
             $contentPath = myContentStorage::getFSContentRootPath();
             $msgPath = $contentPath . "content/templates/entry/thumbnail/auto_edit.jpg";
             $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, $msgPath);
             //kFile::dumpFile($tempThumbPath, null, 0);
         } elseif ($entry->getType() == entryType::MEDIA_CLIP) {
             // commenting out the new behavior, in this case the thumbnail will be created in resizeEntryImage
             //$contentPath = myContentStorage::getFSContentRootPath();
             //$msgPath = $contentPath."content/templates/entry/thumbnail/broken_thumb.jpg";
             //header("Xkaltura-app: entry [$entry_id] in conversion, returning template broken thumb");
             //KalturaLog::log( "Entry in conversion, no thumbnail yet [$entry_id], created dynamic 1x1 jpg");
             //kFile::dumpFile($msgPath, null, 0);
             try {
                 $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);
             } catch (Exception $ex) {
                 if ($ex->getCode() == kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                     // get original flavor asset
                     $origFlavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entry_id);
                     if ($origFlavorAsset) {
                         $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                         $remoteFileSync = kFileSyncUtils::getOriginFileSyncForKey($syncKey, false);
                         if (!$remoteFileSync) {
                             // file does not exist on any DC - die
                             KalturaLog::log("Error - no FileSync for entry [{$entry_id}]");
                             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                         }
                         if ($remoteFileSync->getDc() == kDataCenterMgr::getCurrentDcId()) {
                             KalturaLog::log("ERROR - Trying to redirect to myself - stop here.");
                             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                         }
                         $remote_url = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync, $_SERVER['REQUEST_URI']);
                         KalturaLog::log(__METHOD__ . ": redirecting to [{$remote_url}]");
                         $this->redirect($remote_url);
                     }
                 }
             }
         } else {
             // file does not exist on any DC - die
             KalturaLog::log("Error - no FileSync for entry [{$entry_id}]");
             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
         }
     }
     if (!$local && !$tempThumbPath) {
         $remote_url = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']);
         KalturaLog::log(__METHOD__ . ": redirecting to [{$remote_url}]");
         $this->redirect($remote_url);
     }
     // if we didnt return a template for the player die and dont return the original deleted thumb
     if ($entry_status == entryStatus::DELETED) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
     }
     if (!$tempThumbPath) {
         try {
             $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);
         } catch (Exception $ex) {
             if ($ex->getCode() == kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 // get original flavor asset
                 $origFlavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entry_id);
                 if ($origFlavorAsset) {
                     $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                     $remoteFileSync = kFileSyncUtils::getOriginFileSyncForKey($syncKey, false);
                     if (!$remoteFileSync) {
                         // file does not exist on any DC - die
                         KalturaLog::log("Error - no FileSync for entry [{$entry_id}]");
                         KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                     }
                     if ($remoteFileSync->getDc() == kDataCenterMgr::getCurrentDcId()) {
                         KalturaLog::log("ERROR - Trying to redirect to myself - stop here.");
                         KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                     }
                     $remote_url = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync, $_SERVER['REQUEST_URI']);
                     KalturaLog::log(__METHOD__ . ": redirecting to [{$remote_url}]");
                     $this->redirect($remote_url);
                 }
             }
         }
     }
     $nocache = strpos($tempThumbPath, "_NOCACHE_") !== false;
     // notify external proxy, so it'll cache this url
     if (!$nocache && requestUtils::getHost() == kConf::get("apphome_url") && file_exists($tempThumbPath)) {
         self::notifyProxy($_SERVER["REQUEST_URI"]);
     }
     // cache result
     if (!$nocache) {
         $requestKey = $_SERVER["REQUEST_URI"];
         $cache = new myCache("thumb", 86400 * 30);
         // 30 days
         $cache->put($requestKey, $tempThumbPath);
     }
     kFile::dumpFile($tempThumbPath, null, $nocache ? 0 : null);
     // TODO - can delete from disk assuming we caneasily recreate it and it will anyway be cached in the CDN
     // however dumpfile dies at the end so we cant just write it here (maybe register a shutdown callback)
 }