Exemple #1
0
 /**
  * @param entry $entry
  * @param FileSyncKey $key
  */
 protected static function export(entry $entry, StorageProfile $externalStorage, FileSyncKey $key, $force = false)
 {
     /* @var $fileSync FileSync */
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($key, true, false);
     if (!$fileSync || $fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) {
         KalturaLog::info("no ready fileSync was found for key [{$key}]");
         return;
     }
     $externalFileSync = kFileSyncUtils::createPendingExternalSyncFileForKey($key, $externalStorage, $fileSync->getIsDir());
     $parent_file_sync = kFileSyncUtils::resolve($fileSync);
     $srcFileSyncPath = $parent_file_sync->getFileRoot() . $parent_file_sync->getFilePath();
     kJobsManager::addStorageExportJob(null, $entry->getId(), $entry->getPartnerId(), $externalStorage, $externalFileSync, $srcFileSyncPath, $force, $fileSync->getDc());
     return true;
 }
Exemple #2
0
 /**
  * 
  * @param $version
  * @param $format
  * @return FileSync
  */
 public function getDownloadFileSyncAndLocal($version = NULL, $format = null, $sub_type = null)
 {
     $flavorParams = myConversionProfileUtils::getFlavorParamsFromFileFormat($this->getPartnerId(), $format);
     if (!$flavorParams) {
         return null;
     }
     $flavorAssets = assetPeer::retrieveByEntryIdAndParams($this->getId(), $flavorParams->getId());
     if (!$flavorAssets) {
         return null;
     }
     $syncKey = $flavorAssets->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     if (!$syncKey) {
         return null;
     }
     return kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
 }
 /**
  * @param asset $asset
  * @params entry $entry
  * @return string
  */
 public static function getFileName(entry $entry, flavorAsset $flavorAsset = null)
 {
     $fileExt = "";
     $fileBaseName = $entry->getName();
     if ($flavorAsset) {
         $flavorParams = $flavorAsset->getFlavorParams();
         if ($flavorParams) {
             $fileBaseName = $fileBaseName . " (" . $flavorParams->getName() . ")";
         }
         $fileExt = $flavorAsset->getFileExt();
     } else {
         $syncKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if ($fileSync) {
             $fileExt = $fileSync->getFileExt();
         }
     }
     return array($fileBaseName, $fileExt);
 }
 /**
  *
  * @action getFaspUrl
  * @param string $flavorAssetId
  * @throws KalturaAPIException
  * @return string
  */
 function getFaspUrlAction($flavorAssetId)
 {
     KalturaResponseCacher::disableCache();
     $assetDb = assetPeer::retrieveById($flavorAssetId);
     if (!$assetDb || !$assetDb instanceof flavorAsset) {
         throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $flavorAssetId);
     }
     if (!$assetDb->isLocalReadyStatus()) {
         throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_IS_NOT_READY);
     }
     $syncKey = $assetDb->getSyncKey(flavorAsset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
     /* @var $fileSync FileSync */
     list($fileSync, $isFileSyncLocal) = kFileSyncUtils::getReadyFileSyncForKey($syncKey);
     $filePath = $fileSync->getFilePath();
     $transferUser = $this->getFromAsperaConfig('transfer_user');
     $transferHost = $this->getFromAsperaConfig('transfer_host');
     $asperaNodeApi = new AsperaNodeApi($this->getFromAsperaConfig('node_api_user'), $this->getFromAsperaConfig('node_api_password'), $this->getFromAsperaConfig('node_api_host'), $this->getFromAsperaConfig('node_api_port'));
     $options = array('transfer_requests' => array('transfer_request' => array('remote_host' => $transferHost)));
     $tokenResponse = $asperaNodeApi->getToken($filePath, $options);
     $token = $tokenResponse->transfer_spec->token;
     $urlParams = array('auth' => 'no', 'token' => $token);
     return 'fasp://' . $transferUser . '@' . $transferHost . $filePath . '?' . http_build_query($urlParams, '', '&');
 }
 public function execute()
 {
     //entitlement should be disabled to serveFlavor action as we do not get ks on this action.
     KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
     requestUtils::handleConditionalGet();
     $flavorId = $this->getRequestParameter("flavorId");
     $shouldProxy = $this->getRequestParameter("forceproxy", false);
     $fileName = $this->getRequestParameter("fileName");
     $fileParam = $this->getRequestParameter("file");
     $fileParam = basename($fileParam);
     $pathOnly = $this->getRequestParameter("pathOnly", false);
     $referrer = base64_decode($this->getRequestParameter("referrer"));
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = '';
     }
     $flavorAsset = assetPeer::retrieveById($flavorId);
     if (is_null($flavorAsset)) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     $entryId = $this->getRequestParameter("entryId");
     if (!is_null($entryId) && $flavorAsset->getEntryId() != $entryId) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     if ($fileName) {
         header("Content-Disposition: attachment; filename=\"{$fileName}\"");
         header("Content-Type: application/force-download");
         header("Content-Description: File Transfer");
     }
     $clipTo = null;
     $entry = $flavorAsset->getentry();
     if (!$entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFlavor', $flavorAsset->getPartnerId());
     myPartnerUtils::enforceDelivery($entry, $flavorAsset);
     $version = $this->getRequestParameter("v");
     if (!$version) {
         $version = $flavorAsset->getVersion();
     }
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version);
     if ($pathOnly && kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR'])) {
         $path = null;
         list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, false, false);
         if ($file_sync) {
             $parent_file_sync = kFileSyncUtils::resolve($file_sync);
             $path = $parent_file_sync->getFullPath();
             if ($fileParam && is_dir($path)) {
                 $path .= "/{$fileParam}";
             }
         }
         $renderer = new kRendererString('{"sequences":[{"clips":[{"type":"source","path":"' . $path . '"}]}]}', 'application/json');
         if ($path) {
             $this->storeCache($renderer, $flavorAsset->getPartnerId());
         }
         $renderer->output();
         KExternalErrors::dieGracefully();
     }
     if (kConf::hasParam('serve_flavor_allowed_partners') && !in_array($flavorAsset->getPartnerId(), kConf::get('serve_flavor_allowed_partners'))) {
         KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED);
     }
     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);
         kFileUtils::dumpUrl($remoteUrl);
     }
     $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     $isFlv = false;
     if (!$shouldProxy) {
         $flvWrapper = new myFlvHandler($path);
         $isFlv = $flvWrapper->isFlv();
     }
     $clipFrom = $this->getRequestParameter("clipFrom", 0);
     // milliseconds
     if (is_null($clipTo)) {
         $clipTo = $this->getRequestParameter("clipTo", self::NO_CLIP_TO);
     }
     // milliseconds
     if ($clipTo == 0) {
         $clipTo = self::NO_CLIP_TO;
     }
     if (!is_numeric($clipTo) || $clipTo < 0) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'clipTo must be a positive number');
     }
     $seekFrom = $this->getRequestParameter("seekFrom", -1);
     if ($seekFrom <= 0) {
         $seekFrom = -1;
     }
     $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1);
     if ($seekFromBytes <= 0) {
         $seekFromBytes = -1;
     }
     if ($fileParam && is_dir($path)) {
         $path .= "/{$fileParam}";
         kFileUtils::dumpFile($path, null, null);
         KExternalErrors::dieGracefully();
     } else {
         if (!$isFlv || $clipTo == self::NO_CLIP_TO && $seekFrom < 0 && $seekFromBytes < 0) {
             $limit_file_size = 0;
             if ($clipTo != self::NO_CLIP_TO) {
                 if (strtolower($flavorAsset->getFileExt()) == 'mp4' && PermissionPeer::isValidForPartner(PermissionName::FEATURE_ACCURATE_SERVE_CLIPPING, $flavorAsset->getPartnerId())) {
                     $contentPath = myContentStorage::getFSContentRootPath();
                     $tempClipName = $version . '_' . $clipTo . '.mp4';
                     $tempClipPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempclip", $flavorAsset->getIntId(), $flavorAsset->getId(), $tempClipName);
                     if (!file_exists($tempClipPath)) {
                         kFile::fullMkdir($tempClipPath);
                         $clipToSec = round($clipTo / 1000, 3);
                         $cmdLine = kConf::get("bin_path_ffmpeg") . " -i {$path} -vcodec copy -acodec copy -f mp4 -t {$clipToSec} -y {$tempClipPath} 2>&1";
                         KalturaLog::log("Executing {$cmdLine}");
                         $output = array();
                         $return_value = "";
                         exec($cmdLine, $output, $return_value);
                         KalturaLog::log("ffmpeg returned {$return_value}, output:" . implode("\n", $output));
                     }
                     if (file_exists($tempClipPath)) {
                         KalturaLog::log("Dumping {$tempClipPath}");
                         kFileUtils::dumpFile($tempClipPath);
                     } else {
                         KalturaLog::err('Failed to clip the file using ffmpeg, falling back to rough clipping');
                     }
                 }
                 $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId());
                 if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) {
                     $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration());
                     $limit_file_size = floor(@kFile::fileSize($path) * ($clipTo / $duration) * 1.2);
                 }
             }
             $renderer = kFileUtils::getDumpFileRenderer($path, null, null, $limit_file_size);
             if (!$fileName) {
                 $this->storeCache($renderer, $flavorAsset->getPartnerId());
             }
             $renderer->output();
             KExternalErrors::dieGracefully();
         }
     }
     $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;
     }
     $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);
     }
     // 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);
     KExternalErrors::dieGracefully();
 }
Exemple #6
0
 /**
  * @param flavorAsset $flavorAsset
  * @param SimpleXMLElement $mrss
  * @return SimpleXMLElement
  */
 protected static function appendFlavorAssetMrss(flavorAsset $flavorAsset, SimpleXMLElement $mrss = null, kMrssParameters $mrssParams = null)
 {
     if (!$mrss) {
         $mrss = new SimpleXMLElement('<item/>');
     }
     $servePlayManifest = false;
     $playManifestClientTag = null;
     $storageId = null;
     if ($mrssParams) {
         $servePlayManifest = $mrssParams->getServePlayManifest();
         $playManifestClientTag = $mrssParams->getPlayManifestClientTag();
         $storageId = $mrssParams->getStorageId();
     }
     $content = $mrss->addChild('content');
     $content->addAttribute('url', kAssetUtils::getAssetUrl($flavorAsset, $servePlayManifest, $playManifestClientTag, $storageId));
     $content->addAttribute('flavorAssetId', $flavorAsset->getId());
     $content->addAttribute('isSource', $flavorAsset->getIsOriginal() ? 'true' : 'false');
     $content->addAttribute('containerFormat', $flavorAsset->getContainerFormat());
     $content->addAttribute('extension', $flavorAsset->getFileExt());
     $content->addAttribute('createdAt', $flavorAsset->getCreatedAt());
     // get the file size
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     $fileSize = $fileSync && $fileSync->getFileSize() > 0 ? $fileSync->getFileSize() : $flavorAsset->getSize() * 1024;
     $mediaParams = array('format' => $flavorAsset->getContainerFormat(), 'videoBitrate' => $flavorAsset->getBitrate(), 'fileSize' => $fileSize, 'videoCodec' => $flavorAsset->getVideoCodecId(), 'audioBitrate' => 0, 'audioCodec' => '', 'frameRate' => $flavorAsset->getFrameRate(), 'height' => $flavorAsset->getHeight(), 'width' => $flavorAsset->getWidth());
     if (!is_null($flavorAsset->getFlavorParamsId())) {
         $content->addAttribute('flavorParamsId', $flavorAsset->getFlavorParamsId());
         $flavorParams = assetParamsPeer::retrieveByPK($flavorAsset->getFlavorParamsId());
         if ($flavorParams) {
             $content->addAttribute('flavorParamsName', $flavorParams->getName());
             $flavorParamsDetails = array('format' => $flavorParams->getFormat(), 'videoBitrate' => $flavorParams->getVideoBitrate(), 'videoCodec' => $flavorParams->getVideoCodec(), 'audioBitrate' => $flavorParams->getAudioBitrate(), 'audioCodec' => $flavorParams->getAudioCodec(), 'frameRate' => $flavorParams->getFrameRate(), 'height' => $flavorParams->getHeight(), 'width' => $flavorParams->getWidth());
             // merge the flavar param details with the flavor asset details
             // the flavor asset details take precedence whenever they exist
             $mediaParams = array_merge($flavorParamsDetails, array_filter($mediaParams));
         }
     }
     foreach ($mediaParams as $key => $value) {
         $content->addAttribute($key, $value);
     }
     $tags = $content->addChild('tags');
     foreach (explode(',', $flavorAsset->getTags()) as $tag) {
         $tags->addChild('tag', self::stringToSafeXml($tag));
     }
     if ($flavorAsset->hasTag(assetParams::TAG_SLWEB)) {
         self::addIsmLink($flavorAsset->getentry(), $mrss);
     }
 }
 private function handleFileSyncRedirection(FileSyncKey $syncKey)
 {
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     if (is_null($fileSync)) {
         KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
     }
     if (!$local) {
         $remote_url = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         $this->redirect($remote_url);
     }
 }
Exemple #8
0
 /**
  * serve action returns the original file.
  * 
  * @action serve
  * @param int $id job id
  * @return file
  * 
  */
 function serveAction($id)
 {
     $c = new Criteria();
     $c->addAnd(BatchJobPeer::ID, $id);
     $c->addAnd(BatchJobPeer::PARTNER_ID, $this->getPartnerId());
     $c->addAnd(BatchJobPeer::JOB_TYPE, BatchJobType::BULKUPLOAD);
     $batchJob = BatchJobPeer::doSelectOne($c);
     if (!$batchJob) {
         throw new KalturaAPIException(KalturaErrors::BULK_UPLOAD_NOT_FOUND, $id);
     }
     KalturaLog::info("Batch job found for jobid [{$id}] bulk upload type [" . $batchJob->getJobSubType() . "]");
     $syncKey = $batchJob->getSyncKey(BatchJob::FILE_SYNC_BATCHJOB_SUB_TYPE_BULKUPLOAD);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     header("Content-Type: text/plain; charset=UTF-8");
     if ($local) {
         $filePath = $fileSync->getFullPath();
         $mimeType = kFile::mimeType($filePath);
         return $this->dumpFile($filePath, $mimeType);
     } else {
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         KalturaLog::info("Redirecting to [{$remoteUrl}]");
         header("Location: {$remoteUrl}");
         die;
     }
 }
 private static function generateThumbnail(asset $srcAsset, thumbParamsOutput $destThumbParamsOutput, &$errDescription, $rotate = null)
 {
     $srcSyncKey = $srcAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($srcSyncKey, true, false);
     if (!$fileSync || $fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) {
         $errDescription = 'Source asset could has no valid file sync';
         return false;
     }
     $srcPath = $fileSync->getFullPath();
     $uniqid = uniqid('thumb_');
     $tempDir = kConf::get('cache_root_path') . DIRECTORY_SEPARATOR . 'thumb';
     if (!file_exists($tempDir)) {
         mkdir($tempDir, 0700, true);
     }
     $destPath = $tempDir . DIRECTORY_SEPARATOR . $uniqid . '.jpg';
     $logPath = $destPath . '.log';
     if (!file_exists($srcPath)) {
         $errDescription = "Source file [{$srcPath}] does not exist";
         return false;
     }
     if (!is_file($srcPath)) {
         $errDescription = "Source file [{$srcPath}] is not a file";
         return false;
     }
     try {
         if ($srcAsset->getType() == assetType::FLAVOR) {
             /* @var $srcAsset flavorAsset */
             $dar = null;
             $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($srcAsset->getId());
             if ($mediaInfo) {
                 $dar = $mediaInfo->getVideoDar();
             }
             // generates the thumbnail
             $thumbMaker = new KFFMpegThumbnailMaker($srcPath, $destPath, kConf::get('bin_path_ffmpeg'));
             $created = $thumbMaker->createThumnail($destThumbParamsOutput->getVideoOffset(), $srcAsset->getWidth(), $srcAsset->getHeight(), null, null, $dar);
             if (!$created || !file_exists($destPath)) {
                 $errDescription = "Thumbnail not captured";
                 return false;
             }
             $srcPath = $destPath;
             $uniqid = uniqid('thumb_');
             $tempDir = kConf::get('cache_root_path') . DIRECTORY_SEPARATOR . 'thumb';
             if (!file_exists($tempDir)) {
                 mkdir($tempDir, 0700, true);
             }
             $destPath = $tempDir . DIRECTORY_SEPARATOR . $uniqid . '.jpg';
         }
         if ($srcAsset->getType() == assetType::THUMBNAIL) {
             $tempDir = kConf::get('cache_root_path') . DIRECTORY_SEPARATOR . 'thumb';
             if (!file_exists($tempDir)) {
                 mkdir($tempDir, 0700, true);
             }
             $destPath = $tempDir . DIRECTORY_SEPARATOR . $uniqid . "." . $srcAsset->getFileExt();
         }
         $quality = $destThumbParamsOutput->getQuality();
         $cropType = $destThumbParamsOutput->getCropType();
         $cropX = $destThumbParamsOutput->getCropX();
         $cropY = $destThumbParamsOutput->getCropY();
         $cropWidth = $destThumbParamsOutput->getCropWidth();
         $cropHeight = $destThumbParamsOutput->getCropHeight();
         $bgcolor = $destThumbParamsOutput->getBackgroundColor();
         $width = $destThumbParamsOutput->getWidth();
         $height = $destThumbParamsOutput->getHeight();
         $scaleWidth = $destThumbParamsOutput->getScaleWidth();
         $scaleHeight = $destThumbParamsOutput->getScaleHeight();
         $density = $destThumbParamsOutput->getDensity();
         $stripProfiles = $destThumbParamsOutput->getStripProfiles();
         $cropper = new KImageMagickCropper($srcPath, $destPath, kConf::get('bin_path_imagemagick'), true);
         $cropped = $cropper->crop($quality, $cropType, $width, $height, $cropX, $cropY, $cropWidth, $cropHeight, $scaleWidth, $scaleHeight, $bgcolor, $density, $rotate, $stripProfiles);
         if (!$cropped || !file_exists($destPath)) {
             $errDescription = "Crop failed";
             return false;
         }
         return $destPath;
     } catch (Exception $ex) {
         $errDescription = $ex->getMessage();
         return false;
     }
 }
 /**
  * Convert entry
  * 
  * @param string $entryId Media entry id
  * @param int $conversionProfileId
  * @param KalturaConversionAttributeArray $dynamicConversionAttributes
  * @return bigint 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 = assetPeer::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();
     } else {
         //The search is with the entry's partnerId. so if conversion profile wasn't found it means that the
         //conversionId is not exist or the conversion profileId does'nt belong to this partner.
         $conversionProfile = conversionProfile2Peer::retrieveByPK($conversionProfileId);
         if (is_null($conversionProfile)) {
             throw new KalturaAPIException(KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND, $conversionProfileId);
         }
     }
     $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 (!$fileSync) {
         throw new KalturaAPIException(KalturaErrors::FILE_DOESNT_EXIST);
     } else {
         if (!$local) {
             kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrl($fileSync));
         }
     }
     // even if it null
     $entry->setConversionQuality($conversionProfileId);
     $entry->save();
     if ($dynamicConversionAttributes) {
         $flavors = assetParamsPeer::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();
 }
 /**
  * @param FileSyncKey $syncKey
  * @param string $contentMd5
  * @param bool $isFile
  * @return bool
  */
 public static function compareContent($syncKey, $contentMd5, $isFile = false)
 {
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, false, false);
     if (!$fileSync || !$fileSync->getContentMd5()) {
         return false;
     }
     if ($isFile) {
         return $fileSync->getContentMd5() == md5_file($contentMd5);
     } else {
         return $fileSync->getContentMd5() == md5($contentMd5);
     }
 }
 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;
 }
 public static function resizeEntryImage(entry $entry, $version, $width, $height, $type, $bgcolor = "ffffff", $crop_provider = null, $quality = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $vid_sec = -1, $vid_slice = 0, $vid_slices = -1, $orig_image_path = null, $density = 0, $stripProfiles = false, $thumbParams = null, $format = null)
 {
     if (is_null($thumbParams) || !$thumbParams instanceof kThumbnailParameters) {
         $thumbParams = new kThumbnailParameters();
     }
     $contentPath = myContentStorage::getFSContentRootPath();
     $entry_status = $entry->getStatus();
     $thumbName = $entry->getId() . "_{$width}_{$height}_{$type}_{$crop_provider}_{$bgcolor}_{$quality}_{$src_x}_{$src_y}_{$src_w}_{$src_h}_{$vid_sec}_{$vid_slice}_{$vid_slices}_{$entry_status}";
     if ($orig_image_path) {
         $thumbName .= '_oip_' . basename($orig_image_path);
     }
     if ($density) {
         $thumbName .= "_dns_{$density}";
     }
     if ($stripProfiles) {
         $thumbName .= "_stp_{$stripProfiles}";
     }
     $entryThumbFilename = $entry->getThumbnail() ? $entry->getThumbnail() : "0.jpg";
     if ($entry->getStatus() != entryStatus::READY || @$entryThumbFilename[0] == '&') {
         $thumbName .= "_NOCACHE_";
     }
     // we remove the & from the template thumb otherwise getGeneralEntityPath will drop $tempThumbName from the final path
     $entryThumbFilename = str_replace("&", "", $entryThumbFilename);
     //create final path for thumbnail created
     $finalBasePath = myContentStorage::getGeneralEntityPath("entry/tempthumb", $entry->getIntId(), $thumbName, $entryThumbFilename, $version);
     $finalThumbPath = $contentPath . $finalBasePath;
     //Add unique id to the proccesing file path to avoid file being overwritten when several identical (with same parameters) calls are made before the final thumbnail is created
     $thumbName .= "_" . uniqid() . "_";
     //create path for processing thumbnail request
     $processingBasePath = myContentStorage::getGeneralEntityPath("entry/tempthumb", $entry->getIntId(), $thumbName, $entryThumbFilename, $version);
     $processingThumbPath = $contentPath . $processingBasePath;
     if (!is_null($format)) {
         $finalThumbPath = kFile::replaceExt($finalThumbPath, $format);
         $processingThumbPath = kFile::replaceExt($processingThumbPath, $format);
     }
     if (file_exists($finalThumbPath) && @filesize($finalThumbPath)) {
         header("X-Kaltura:cached-thumb-exists," . md5($finalThumbPath));
         return $finalThumbPath;
     }
     if ($orig_image_path === null || !file_exists($orig_image_path)) {
         $orig_image_path = self::getLocalImageFilePathByEntry($entry, $version);
     }
     // remark added so ffmpeg will try to load the thumbnail from the original source
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE && !file_exists($orig_image_path)) {
         throw new kFileSyncException('no ready filesync on current DC', kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC);
     }
     // check a request for animated thumbs without a concrete vid_slice
     // in which case we'll create all the frames as one wide image
     $multi = $vid_slice == -1 && $vid_slices != -1;
     $count = $multi ? $vid_slices : 1;
     $im = null;
     if ($multi) {
         $vid_slice = 0;
     }
     while ($count--) {
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO && ($vid_sec != -1 || $vid_slices != -1) || !file_exists($orig_image_path)) {
             if ($vid_sec != -1) {
                 $calc_vid_sec = min($vid_sec, floor($entry->getLengthInMsecs() / 1000));
             } else {
                 if ($vid_slices != -1) {
                     $calc_vid_sec = floor($entry->getLengthInMsecs() / $vid_slices * min($vid_slice, $vid_slices) / 1000);
                 } else {
                     if ($entry->getStatus() != entryStatus::READY && $entry->getLengthInMsecs() == 0) {
                         $calc_vid_sec = $entry->getPartner() && $entry->getPartner()->getDefThumbOffset() ? $entry->getPartner()->getDefThumbOffset() : 3;
                     } else {
                         $calc_vid_sec = $entry->getBestThumbOffset();
                     }
                 }
             }
             $capturedThumbName = $entry->getId() . "_sec_{$calc_vid_sec}";
             $capturedThumbPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempthumb", $entry->getIntId(), $capturedThumbName, $entry->getThumbnail(), $version);
             $orig_image_path = $capturedThumbPath . "temp_1.jpg";
             // if we already captured the frame at that second, dont recapture, just use the existing file
             if (!file_exists($orig_image_path)) {
                 // limit creation of more than XX ffmpeg image extraction processes
                 if (kConf::hasParam("resize_thumb_max_processes_ffmpeg") && trim(exec("ps -e -ocmd|awk '{print \$1}'|grep -c " . kConf::get("bin_path_ffmpeg"))) > kConf::get("resize_thumb_max_processes_ffmpeg")) {
                     KExternalErrors::dieError(KExternalErrors::TOO_MANY_PROCESSES);
                 }
                 // creating the thumbnail is a very heavy operation
                 // prevent calling it in parallel for the same thubmnail for 5 minutes
                 $cache = new myCache("thumb-processing", 5 * 60);
                 // 5 minutes
                 $processing = $cache->get($orig_image_path);
                 if ($processing) {
                     KExternalErrors::dieError(KExternalErrors::PROCESSING_CAPTURE_THUMBNAIL);
                 }
                 $cache->put($orig_image_path, true);
                 $flavorAsset = assetPeer::retrieveHighestBitrateByEntryId($entry->getId(), flavorParams::TAG_THUMBSOURCE);
                 if (is_null($flavorAsset)) {
                     $flavorAsset = assetPeer::retrieveOriginalReadyByEntryId($entry->getId());
                     if ($flavorAsset) {
                         $flavorSyncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($flavorSyncKey, false, false);
                         if (!$fileSync) {
                             $flavorAsset = null;
                         }
                     }
                     if (is_null($flavorAsset) || !($flavorAsset->hasTag(flavorParams::TAG_MBR) || $flavorAsset->hasTag(flavorParams::TAG_WEB))) {
                         // try the best playable
                         $flavorAsset = assetPeer::retrieveHighestBitrateByEntryId($entry->getId(), null, flavorParams::TAG_SAVE_SOURCE);
                     }
                     if (is_null($flavorAsset)) {
                         // if no READY ORIGINAL entry is available, try to retrieve a non-READY ORIGINAL entry
                         $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
                     }
                 }
                 if (is_null($flavorAsset)) {
                     // if no READY ORIGINAL entry is available, try to retrieve a non-READY ORIGINAL entry
                     $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
                 }
                 if (is_null($flavorAsset)) {
                     KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
                 }
                 $flavorSyncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                 $entry_data_path = kFileSyncUtils::getReadyLocalFilePathForKey($flavorSyncKey);
                 if (!$entry_data_path) {
                     // since this is not really being processed on this server, and will probably cause redirect in thumbnailAction
                     // remove from cache so later requests will still get redirected and will not fail on PROCESSING_CAPTURE_THUMBNAIL
                     $cache->remove($orig_image_path);
                     throw new kFileSyncException('no ready filesync on current DC', kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC);
                 }
                 // close db connections as we won't be requiring the database anymore and capturing a thumbnail may take a long time
                 kFile::closeDbConnections();
                 myFileConverter::autoCaptureFrame($entry_data_path, $capturedThumbPath . "temp_", $calc_vid_sec, -1, -1);
                 $cache->remove($orig_image_path);
             }
         }
         // close db connections as we won't be requiring the database anymore and image manipulation may take a long time
         kFile::closeDbConnections();
         // limit creation of more than XX Imagemagick processes
         if (kConf::hasParam("resize_thumb_max_processes_imagemagick") && trim(exec("ps -e -ocmd|awk '{print \$1}'|grep -c " . kConf::get("bin_path_imagemagick"))) > kConf::get("resize_thumb_max_processes_imagemagick")) {
             KExternalErrors::dieError(KExternalErrors::TOO_MANY_PROCESSES);
         }
         // resizing (and editing)) an image file that failes results in a long server waiting time
         // prevent this waiting time (of future requests) in case the resizeing failes
         $cache = new myCache("thumb-processing-resize", 5 * 60);
         // 5 minutes
         $processing = $cache->get($orig_image_path);
         if ($processing) {
             KExternalErrors::dieError(KExternalErrors::PROCESSING_CAPTURE_THUMBNAIL);
         }
         kFile::fullMkdir($processingThumbPath);
         if ($crop_provider) {
             $convertedImagePath = myFileConverter::convertImageUsingCropProvider($orig_image_path, $processingThumbPath, $width, $height, $type, $crop_provider, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h, $density, $stripProfiles);
         } else {
             if (!file_exists($orig_image_path) || !filesize($orig_image_path)) {
                 KExternalErrors::dieError(KExternalErrors::IMAGE_RESIZE_FAILED);
             }
             $imageSizeArray = getimagesize($orig_image_path);
             if ($thumbParams->getSupportAnimatedThumbnail() && is_array($imageSizeArray) && $imageSizeArray[2] === IMAGETYPE_GIF) {
                 $processingThumbPath = kFile::replaceExt($processingThumbPath, "gif");
                 $finalThumbPath = kFile::replaceExt($finalThumbPath, "gif");
             }
             $convertedImagePath = myFileConverter::convertImage($orig_image_path, $processingThumbPath, $width, $height, $type, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h, $density, $stripProfiles, $thumbParams, $format);
         }
         // die if resize operation failed and add failed resizing to cache
         if ($convertedImagePath === null || !@filesize($convertedImagePath)) {
             $cache->put($orig_image_path, true);
             KExternalErrors::dieError(KExternalErrors::IMAGE_RESIZE_FAILED);
         }
         // if resizing secceded remove from cache of failed resizing
         if ($cache->get($orig_image_path)) {
             $cache->remove($orig_image_path, true);
         }
         if ($multi) {
             list($w, $h, $type, $attr, $srcIm) = myFileConverter::createImageByFile($processingThumbPath);
             if (!$im) {
                 $im = imagecreatetruecolor($w * $vid_slices, $h);
             }
             imagecopy($im, $srcIm, $w * $vid_slice, 0, 0, 0, $w, $h);
             imagedestroy($srcIm);
             ++$vid_slice;
         }
     }
     if ($multi) {
         imagejpeg($im, $processingThumbPath);
         imagedestroy($im);
     }
     kFile::fullMkdir($finalThumbPath);
     kFile::moveFile($processingThumbPath, $finalThumbPath);
     return $finalThumbPath;
 }
Exemple #14
0
 /**
  * Serves the file content
  * 
  * @action serve
  * @param flavorAsset $flavorAsset
  * @param string $fileName
  * @param bool $forceProxy
  * @return file
  * 
  * @throws KalturaErrors::FLAVOR_ASSET_IS_NOT_READY
  */
 protected function serveFlavorAsset(flavorAsset $flavorAsset, $fileName, $forceProxy = false)
 {
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     if (!$fileSync) {
         throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_IS_NOT_READY, $flavorAsset->getId());
     }
     /* @var $fileSync FileSync */
     if ($fileSync->getFileExt() != assetParams::CONTAINER_FORMAT_SWF) {
         header("Content-Disposition: attachment; filename=\"{$fileName}\"");
     }
     if ($local) {
         $filePath = $fileSync->getFullPath();
         $mimeType = kFile::mimeType($filePath);
         return $this->dumpFile($filePath, $mimeType);
     } else {
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         KalturaLog::info("Redirecting to [{$remoteUrl}]");
         if ($forceProxy) {
             kFileUtils::dumpUrl($remoteUrl);
         } else {
             // or redirect if no proxy
             header("Location: {$remoteUrl}");
             die;
         }
     }
 }
 private function getReplacedAndReplacingFileNames($asset, $fileSyncObjectSubType)
 {
     $replacingFileName = null;
     $fileName = null;
     $syncKey = $asset->getSyncKey($fileSyncObjectSubType);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true);
     if ($fileSync) {
         $replacingFileName = basename($fileSync->getFilePath());
         $fileExt = pathinfo($fileSync->getFilePath(), PATHINFO_EXTENSION);
         $fileName = $asset->getEntryId() . '_' . $asset->getId() . '_' . $fileSync->getVersion() . '.' . $fileExt;
     }
     return array($replacingFileName, $fileName);
 }
 /**
  * Will forward to the regular swf player according to the widget_id
  */
 public function execute()
 {
     KExternalErrors::setResponseErrorCode(KExternalErrors::HTTP_STATUS_NOT_FOUND);
     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->getIntRequestParameter("version", null, 0, 10000000);
     $type = $this->getIntRequestParameter("type", 1, 1, 5);
     //Hack: if KMS sends thumbnail request containing "!" char, the type should be treated as 5.
     $width = $this->getRequestParameter("width", -1);
     $height = $this->getRequestParameter("height", -1);
     if (strpos($width, "!") || strpos($height, "!")) {
         $type = 5;
     }
     $width = $this->getFloatRequestParameter("width", -1, -1, 10000);
     $height = $this->getFloatRequestParameter("height", -1, -1, 10000);
     $nearest_aspect_ratio = $this->getIntRequestParameter("nearest_aspect_ratio", 0, 0, 1);
     $imageFilePath = null;
     $crop_provider = $this->getRequestParameter("crop_provider", null);
     $quality = $this->getIntRequestParameter("quality", 0, 0, 100);
     $src_x = $this->getFloatRequestParameter("src_x", 0, 0, 10000);
     $src_y = $this->getFloatRequestParameter("src_y", 0, 0, 10000);
     $src_w = $this->getFloatRequestParameter("src_w", 0, 0, 10000);
     $src_h = $this->getFloatRequestParameter("src_h", 0, 0, 10000);
     $vid_sec = $this->getFloatRequestParameter("vid_sec", -1, -1);
     $vid_slice = $this->getRequestParameter("vid_slice", -1);
     $vid_slices = $this->getRequestParameter("vid_slices", -1);
     $density = $this->getFloatRequestParameter("density", 0, 0);
     $stripProfiles = $this->getRequestParameter("strip", null);
     $flavor_id = $this->getRequestParameter("flavor_id", null);
     $file_name = $this->getRequestParameter("file_name", null);
     $file_name = basename($file_name);
     // 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->getFloatRequestParameter("rel_width", -1, -1, 10000);
     $rel_height = $this->getFloatRequestParameter("rel_height", -1, -1, 10000);
     $def_width = $this->getFloatRequestParameter("def_width", -1, -1, 10000);
     $def_height = $this->getFloatRequestParameter("def_height", -1, -1, 10000);
     if ($width == -1 && $height == -1) {
         if ($def_width == -1) {
             $width = 120;
         } else {
             $width = $def_width;
         }
         if ($def_height == -1) {
             $height = 90;
         } else {
             $height = $def_height;
         }
     } else {
         if ($width == -1) {
             $width = 0;
         } else {
             if ($height == -1) {
                 $height = 0;
             }
         }
     }
     $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
     $partner = null;
     $format = $this->getRequestParameter("format", null);
     // validating the inputs
     if (!is_numeric($quality) || $quality < 0 || $quality > 100) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'quality must be between 20 and 100');
     }
     if (!is_numeric($src_x) || $src_x < 0 || $src_x > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_x must be between 0 and 10000');
     }
     if (!is_numeric($src_y) || $src_y < 0 || $src_y > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_y must be between 0 and 10000');
     }
     if (!is_numeric($src_w) || $src_w < 0 || $src_w > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_w must be between 0 and 10000');
     }
     if (!is_numeric($src_h) || $src_h < 0 || $src_h > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_h must be between 0 and 10000');
     }
     if (!is_numeric($width) || $width < 0 || $width > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'width must be between 0 and 10000');
     }
     if (!is_numeric($height) || $height < 0 || $height > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'height must be between 0 and 10000');
     }
     if (!is_numeric($density) || $density < 0) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'density must be positive');
     }
     if (!is_numeric($vid_sec) || $vid_sec < -1) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'vid_sec must be positive');
     }
     if (!preg_match('/^[0-9a-fA-F]{1,6}$/', $bgcolor)) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'bgcolor must be six hexadecimal characters');
     }
     if ($vid_slices != -1 && $vid_slices <= 0 || !is_numeric($vid_slices)) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'vid_slices must be positive');
     }
     if ($upload_token_id) {
         $upload_token = UploadTokenPeer::retrieveByPK($upload_token_id);
         if ($upload_token) {
             $partnerId = $upload_token->getPartnerId();
             $partner = PartnerPeer::retrieveByPK($partnerId);
             if ($partner) {
                 KalturaMonitorClient::initApiMonitor(false, 'extwidget.thumbnail', $partner->getId());
                 if ($quality == 0) {
                     $quality = $partner->getDefThumbQuality();
                 }
                 if ($density == 0) {
                     $density = $partner->getDefThumbDensity();
                 }
                 if (is_null($stripProfiles)) {
                     $stripProfiles = $partner->getStripThumbProfile();
                 }
             }
             $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, $density, $stripProfiles, null, $format);
                 kFileUtils::dumpFile($thumb_full_path);
             } else {
                 KalturaLog::info("token_id [{$upload_token_id}] not found in DC [" . kDataCenterMgr::getCurrentDcId() . "]. dump url to romote DC");
                 $remoteUrl = kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()) . $_SERVER['REQUEST_URI'];
                 kFileUtils::dumpUrl($remoteUrl);
             }
         }
     }
     if ($entry_id) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             // problem could be due to replication lag
             kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
         }
     } else {
         // 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);
         }
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.thumbnail', $entry->getPartnerId());
     if ($nearest_aspect_ratio) {
         // Get the entry's default thumbnail path (if any)
         $defaultThumbnailPath = myEntryUtils::getLocalImageFilePathByEntry($entry, $version);
         // Get the file path of the thumbnail with the nearest
         $selectedThumbnailDescriptor = kThumbnailUtils::getNearestAspectRatioThumbnailDescriptorByEntryId($entry_id, $width, $height, $defaultThumbnailPath);
         if ($selectedThumbnailDescriptor) {
             $imageFilePath = $selectedThumbnailDescriptor->getImageFilePath();
             $thumbWidth = $selectedThumbnailDescriptor->getWidth();
             $thumbHeight = $selectedThumbnailDescriptor->getHeight();
             // The required width and height will serve as the final crop values
             $src_w = $width;
             $src_h = $height;
             // Base on the thumbnail's dimensions
             kThumbnailUtils::scaleDimensions($thumbWidth, $thumbHeight, $width, $height, kThumbnailUtils::SCALE_UNIFORM_SMALLER_DIM, $width, $height);
             // Set crop type
             $type = KImageMagickCropper::CROP_AFTER_RESIZE;
         }
     }
     $partner = $entry->getPartner();
     // not allow capturing frames if the partner has FEATURE_DISALLOW_FRAME_CAPTURE permission
     if ($vid_sec != -1 || $vid_slice != -1 || $vid_slices != -1) {
         if ($partner->getEnabledService(PermissionName::FEATURE_BLOCK_THUMBNAIL_CAPTURE)) {
             KExternalErrors::dieError(KExternalErrors::NOT_ALLOWED_PARAMETER);
         }
     }
     if ($partner) {
         if ($quality == 0) {
             $quality = $partner->getDefThumbQuality();
         }
         if ($density == 0) {
             $density = $partner->getDefThumbDensity();
         }
     }
     $thumbParams = new kThumbnailParameters();
     $thumbParams->setSupportAnimatedThumbnail($partner->getSupportAnimatedThumbnails());
     if (is_null($stripProfiles)) {
         $stripProfiles = $partner->getStripThumbProfile();
     }
     //checks whether the thumbnail display should be restricted by KS
     $base64Referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64Referrer);
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     if (!$referrer) {
         $referrer = kApiCache::getHttpReferrer();
     }
     $ksStr = $this->getRequestParameter("ks");
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, ContextType::THUMBNAIL);
     $securyEntryHelper->validateForPlay();
     // multiply the passed $src_* values so that they will relate to the original image size, according to $src_display_*
     if ($rel_width != -1 && $rel_width) {
         $widthRatio = $entry->getWidth() / $rel_width;
         $src_x = $src_x * $widthRatio;
         $src_w = $src_w * $widthRatio;
     }
     if ($rel_height != -1 && $rel_height) {
         $heightRatio = $entry->getHeight() / $rel_height;
         $src_y = $src_y * $heightRatio;
         $src_h = $src_h * $heightRatio;
     }
     $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";
         }
         kFileUtils::dumpFile($msgPath, null, 0);
     }
     if (!$file_sync) {
         $tempThumbPath = $entry->getLocalThumbFilePath($version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $density, $stripProfiles, $flavor_id, $file_name);
         if (!$tempThumbPath) {
             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
         }
     }
     if (!$local && !$tempThumbPath && $file_sync) {
         if (!in_array($file_sync->getDc(), kDataCenterMgr::getDcIds())) {
             $remoteUrl = $file_sync->getExternalUrl($entry->getId());
             header("Location: {$remoteUrl}");
             KExternalErrors::dieGracefully();
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']);
         kFileUtils::dumpUrl($remoteUrl);
     }
     // 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, $imageFilePath, $density, $stripProfiles, $thumbParams, $format);
         } catch (Exception $ex) {
             if ($ex->getCode() != kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 KalturaLog::err("Resize image failed");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             // get original flavor asset
             $origFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry_id);
             if (!$origFlavorAsset) {
                 KalturaLog::err("No original flavor for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
             }
             $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::err("Trying to redirect to myself - stop here.");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             if (!in_array($remoteFileSync->getDc(), kDataCenterMgr::getDcIds())) {
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync);
             kFileUtils::dumpUrl($remoteUrl);
         }
     }
     $nocache = false;
     if ($securyEntryHelper->shouldDisableCache() || kApiCache::hasExtraFields() || !$securyEntryHelper->isKsWidget() && $securyEntryHelper->hasRules(ContextType::THUMBNAIL)) {
         $nocache = true;
     }
     $cache = null;
     if (!is_null($entry->getPartner())) {
         $partnerCacheAge = $entry->getPartner()->getThumbnailCacheAge();
     }
     if ($nocache) {
         $cacheAge = 0;
     } else {
         if ($partnerCacheAge) {
             $cacheAge = $partnerCacheAge;
         } else {
             if (strpos($tempThumbPath, "_NOCACHE_") !== false) {
                 $cacheAge = 60;
             } else {
                 $cacheAge = 3600;
                 $cache = new myCache("thumb", 2592000);
                 // 30 days, the max memcache allows
             }
         }
     }
     $lastModified = $entry->getAssetCacheTime();
     $renderer = kFileUtils::getDumpFileRenderer($tempThumbPath, null, $cacheAge, 0, $lastModified);
     $renderer->partnerId = $entry->getPartnerId();
     if ($cache) {
         $invalidationKey = $entry->getCacheInvalidationKeys();
         $invalidationKey = kQueryCache::CACHE_PREFIX_INVALIDATION_KEY . $invalidationKey[0];
         $cacheTime = time() - kQueryCache::CLOCK_SYNC_TIME_MARGIN_SEC;
         $cachedResponse = array($renderer, $invalidationKey, $cacheTime);
         $cache->put($_SERVER["REQUEST_URI"], $cachedResponse);
     }
     $renderer->output();
     KExternalErrors::dieGracefully();
     // 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)
 }
 /**
  * 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)
 }
 /**
  * @action generate
  * @param string $entryId
  * @param KalturaThumbParams $thumbParams
  * @param string $sourceAssetId id of the source asset (flavor or thumbnail) to be used as source for the thumbnail generation
  * @return KalturaThumbAsset
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @throws KalturaErrors::ENTRY_TYPE_NOT_SUPPORTED
  * @throws KalturaErrors::ENTRY_MEDIA_TYPE_NOT_SUPPORTED
  * @throws KalturaErrors::THUMB_ASSET_PARAMS_ID_NOT_FOUND
  * @throws KalturaErrors::INVALID_ENTRY_STATUS
  * @throws KalturaErrors::THUMB_ASSET_IS_NOT_READY
  * @validateUser entry entryId edit
  */
 public function generateAction($entryId, KalturaThumbParams $thumbParams, $sourceAssetId = null)
 {
     $entry = entryPeer::retrieveByPK($entryId);
     if (!$entry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     if (!in_array($entry->getType(), $this->mediaTypes)) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_TYPE_NOT_SUPPORTED, $entry->getType());
     }
     if ($entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_VIDEO) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_MEDIA_TYPE_NOT_SUPPORTED, $entry->getMediaType());
     }
     $validStatuses = array(entryStatus::ERROR_CONVERTING, entryStatus::PRECONVERT, entryStatus::READY);
     if (!in_array($entry->getStatus(), $validStatuses)) {
         throw new KalturaAPIException(KalturaErrors::INVALID_ENTRY_STATUS);
     }
     $destThumbParams = new thumbParams();
     $thumbParams->toUpdatableObject($destThumbParams);
     $srcAsset = kBusinessPreConvertDL::getSourceAssetForGenerateThumbnail($sourceAssetId, $destThumbParams->getSourceParamsId(), $entryId);
     if (is_null($srcAsset)) {
         throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_IS_NOT_READY);
     }
     $sourceFileSyncKey = $srcAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($sourceFileSyncKey, true);
     /* @var $fileSync FileSync */
     if (is_null($fileSync)) {
         throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_IS_NOT_READY);
     }
     if ($fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) {
         throw new KalturaAPIException(KalturaErrors::SOURCE_FILE_REMOTE);
     }
     if (!$local) {
         kFile::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrl($fileSync));
     }
     $runSync = is_null($fileSync->getWamsAssetId());
     $dbThumbAsset = kBusinessPreConvertDL::decideThumbGenerate($entry, $destThumbParams, null, $sourceAssetId, $runSync, $srcAsset);
     if (!$dbThumbAsset) {
         return null;
     }
     $thumbAsset = new KalturaThumbAsset();
     $thumbAsset->fromObject($dbThumbAsset);
     return $thumbAsset;
 }
 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;
 }
Exemple #20
0
 /**
  * serve action returan the file from dataContent field.
  * 
  * @action serve
  * @serverOnly
  * @param string $entryId Data entry id
  * @param int $version Desired version of the data
  * @param bool $forceProxy force to get the content without redirect
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  */
 function serveAction($entryId, $version = -1, $forceProxy = false)
 {
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry || $dbEntry->getType() != KalturaEntryType::DATA) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $ksObj = $this->getKs();
     $ks = $ksObj ? $ksObj->getOriginalString() : null;
     $securyEntryHelper = new KSecureEntryHelper($dbEntry, $ks, null);
     $securyEntryHelper->validateForDownload();
     if (!$version || $version == -1) {
         $version = null;
     }
     $fileName = $dbEntry->getName();
     $syncKey = $dbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     header("Content-Disposition: attachment; filename=\"{$fileName}\"");
     if ($local) {
         $filePath = $fileSync->getFullPath();
         $mimeType = kFile::mimeType($filePath);
         kFile::dumpFile($filePath, $mimeType);
     } else {
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         KalturaLog::info("Redirecting to [{$remoteUrl}]");
         if ($forceProxy) {
             kFile::dumpUrl($remoteUrl);
         } else {
             // or redirect if no proxy
             header("Location: {$remoteUrl}");
         }
     }
 }
Exemple #21
0
 public function isValidFileSync(FileSyncKey $key)
 {
     KalturaLog::log(__METHOD__ . " - key [{$key}], externalStorage id[" . $this->getId() . "]");
     list($kalturaFileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($key, false, false);
     if (!$kalturaFileSync) {
         KalturaLog::log(__METHOD__ . " key [{$key}] not found localy");
         return false;
     }
     KalturaLog::log(__METHOD__ . " validating file size [" . $kalturaFileSync->getFileSize() . "] is between min [" . $this->getMinFileSize() . "] and max [" . $this->getMaxFileSize() . "]");
     if ($this->getMaxFileSize() && $kalturaFileSync->getFileSize() > $this->getMaxFileSize()) {
         KalturaLog::log(__METHOD__ . " key [{$key}] file too big");
         return false;
     }
     if ($this->getMinFileSize() && $kalturaFileSync->getFileSize() < $this->getMinFileSize()) {
         KalturaLog::log(__METHOD__ . " key [{$key}] file too small");
         return false;
     }
     return true;
 }
 /**
  * returns absolute valid url for asset file
  * 
  * @action getAssetUrl
  * @param string $assetId
  * @return string
  * @throws KalturaErrors::INVALID_OBJECT_ID
  * @throws KalturaErrors::FLAVOR_ASSET_IS_NOT_READY
  * @throws KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND
  */
 function getAssetUrlAction($assetId)
 {
     assetPeer::resetInstanceCriteriaFilter();
     $asset = assetPeer::retrieveById($assetId);
     if (!$asset) {
         throw new KalturaAPIException(KalturaErrors::INVALID_OBJECT_ID, $assetId);
     }
     $ext = $asset->getFileExt();
     if (is_null($ext)) {
         $ext = 'jpg';
     }
     $fileName = $asset->getEntryId() . "_" . $asset->getId() . ".{$ext}";
     $syncKey = $asset->getSyncKey(asset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     if (!kFileSyncUtils::fileSync_exists($syncKey)) {
         throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_IS_NOT_READY, $asset->getId());
     }
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     if (!$fileSync) {
         throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $asset->getId());
     }
     return $fileSync->getExternalUrl();
 }
 public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser)
 {
     KalturaLog::log("adddownloadAction: executeImpl ( {$partner_id} , {$subp_id} , {$puser_id} , {$partner_prefix} , {$puser_kuser})");
     $entry_id = $this->getPM("entry_id");
     $version = $this->getP("version");
     $file_format = strtolower($this->getPM("file_format"));
     $conversion_quality = $this->getP("conversion_quality", null);
     $force_download = $this->getP("force_download", null);
     $entry = entryPeer::retrieveByPK($entry_id);
     if (!$entry) {
         KalturaLog::log("add download Action entry not found");
         $this->addError(APIErrors::INVALID_ENTRY_ID, $this->getObjectPrefix(), $entry_id);
         return;
     }
     KalturaLog::log("adddownloadAction: entry found [{$entry_id}]");
     /*			
     $content_path = myContentStorage::getFSContentRootPath();
     $file_name = $content_path . $entry->getDataPath( $version ); // replaced__getDataPath
     if (!file_exists($file_name))
     */
     $sync_key = null;
     $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
     if ($originalFlavorAsset) {
         $sync_key = $originalFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     }
     if (!$sync_key) {
         $sync_key = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version);
     }
     if (!kFileSyncUtils::file_exists($sync_key)) {
         // if not found local file - perhaps wasn't created here and wasn't synced yet
         // try to see if remote exists - and proxy the request if it is.
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($sync_key, true, true);
         if (!$local) {
             // take input params and add to URL
             $queryArr = array('entry_id' => $entry_id, 'version' => $version, 'file_format' => $file_format, 'conversion_quality' => $conversion_quality, 'force_download' => $force_download, 'ks' => $this->ks->toSecureString(), 'partner_id' => $partner_id, 'subp_id' => $subp_id, 'format' => $this->response_type);
             $get_query = http_build_query($queryArr, '', '&');
             $remote_url = kDataCenterMgr::getRedirectExternalUrl($fileSync, $_SERVER['REQUEST_URI']);
             $url = strpos($remote_url, '?') === FALSE ? $remote_url . '?' . $get_query : $remote_url . '&' . $get_query;
             // prxoy request to other DC
             KalturaLog::log(__METHOD__ . ": redirecting to [{$url}]");
             kFileUtils::dumpUrl($url);
         }
         KalturaLog::log("add download Action sync key doesn't exists");
         $this->addError(APIErrors::INVALID_ENTRY_VERSION, $this->getObjectPrefix(), $entry_id, $version);
         return;
     }
     if ($entry->getType() == entryType::MIX) {
         KalturaLog::log("The Batch job for flattening a mix is no longer supported");
         $this->addError(APIErrors::INVALID_ENTRY_TYPE, $this->getObjectPrefix(), $entry_id, $version);
         return;
     }
     $flavorParamsId = 0;
     if ($file_format != "original") {
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) {
             $file_format = "flv";
         }
         // Backward compatebility
         if (!$file_format && $entry->getType() == entryType::DOCUMENT) {
             $file_format = "swf";
         }
         $flavorParams = myConversionProfileUtils::getFlavorParamsFromFileFormat($partner_id, $file_format);
         $flavorParamsId = $flavorParams->getId();
     }
     $jobs = kJobsManager::addBulkDownloadJob($partner_id, $puser_id, $entry->getId(), $flavorParamsId);
     $job = $jobs[0];
     // remove kConvertJobData object from batchJob.data
     $job->setData(null);
     $jobWrapperClass = objectWrapperBase::getWrapperClass($job, objectWrapperBase::DETAIL_LEVEL_DETAILED);
     $this->addMsg("download", $jobWrapperClass);
     // Backwards compatebilty for document entries
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_DOCUMENT || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_PDF) {
         $this->addMsg("OOconvert", $jobWrapperClass);
         $download_path = $entry->getDownloadUrl();
         //TODO: once api_v3 will support parameters with '/' instead of '?', we can change this to war with api_v3
         $download_path .= '/direct_serve/true/type/download/forceproxy/true/format/' . $file_format;
         $this->addMsg('downloadUrl', $download_path);
     }
 }
 /**
  * @param ISyncableFile $syncable
  * @param int $fileSubType
  * @param string $fileName
  * @param bool $forceProxy
  * @throws KalturaErrors::FILE_DOESNT_EXIST
  */
 protected function serveFile(ISyncableFile $syncable, $fileSubType, $fileName, $entryId = null, $forceProxy = false)
 {
     /* @var $fileSync FileSync */
     $syncKey = $syncable->getSyncKey($fileSubType);
     if (!kFileSyncUtils::fileSync_exists($syncKey)) {
         throw new KalturaAPIException(KalturaErrors::FILE_DOESNT_EXIST);
     }
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     header("Content-Disposition: attachment; filename=\"{$fileName}\"");
     if ($local) {
         $filePath = $fileSync->getFullPath();
         $wamsAssetId = $fileSync->getWamsAssetId();
         if (empty($wamsAssetId)) {
             $mimeType = kFile::mimeType($filePath);
             kFile::dumpFile($filePath, $mimeType);
         } else {
             kWAMS::getInstance($fileSync->getPartnerId())->dumpFile($wamsAssetId, pathinfo($filePath, PATHINFO_EXTENSION));
         }
     } else {
         if (in_array($fileSync->getDc(), kDataCenterMgr::getDcIds())) {
             $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
             KalturaLog::info("Redirecting to [{$remoteUrl}]");
             if ($forceProxy) {
                 kFile::dumpApiRequest($remoteUrl);
             } else {
                 //TODO find or build function which redurects the API request with all its parameters without using curl.
                 // or redirect if no proxy
                 header("Location: {$remoteUrl}");
                 die;
             }
         } else {
             $remoteUrl = $fileSync->getExternalUrl($entryId);
             header("Location: {$remoteUrl}");
             die;
         }
     }
 }
 public static function generateThumbnail(asset $srcAsset, thumbParamsOutput $destThumbParamsOutput, &$errDescription)
 {
     $srcSyncKey = $srcAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($srcSyncKey, true, false);
     if (!$fileSync || $fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) {
         $errDescription = 'Source asset could has no valid file sync';
         return false;
     }
     $srcPath = $fileSync->getFullPath();
     $uniqid = uniqid('thumb_');
     $destPath = kConf::get('temp_folder') . "/thumb/{$uniqid}.jpg";
     $logPath = $destPath . '.log';
     if (!file_exists($srcPath)) {
         $errDescription = "Source file [{$srcPath}] does not exist";
         return false;
     }
     if (!is_file($srcPath)) {
         $errDescription = "Source file [{$srcPath}] is not a file";
         return false;
     }
     try {
         if ($srcAsset->getType() == assetType::FLAVOR) {
             // generates the thumbnail
             $thumbMaker = new KFFMpegThumbnailMaker($srcPath, $destPath, kConf::get('bin_path_ffmpeg'));
             $created = $thumbMaker->createThumnail($destThumbParamsOutput->getVideoOffset());
             if (!$created || !file_exists($destPath)) {
                 $errDescription = "Thumbnail not captured";
                 return false;
             }
             $srcPath = $destPath;
             $uniqid = uniqid('thumb_');
             $destPath = kConf::get('temp_folder') . "/thumb/{$uniqid}.jpg";
         }
         $quality = $destThumbParamsOutput->getQuality();
         $cropType = $destThumbParamsOutput->getCropType();
         $cropX = $destThumbParamsOutput->getCropX();
         $cropY = $destThumbParamsOutput->getCropY();
         $cropWidth = $destThumbParamsOutput->getCropWidth();
         $cropHeight = $destThumbParamsOutput->getCropHeight();
         $bgcolor = $destThumbParamsOutput->getBackgroundColor();
         $width = $destThumbParamsOutput->getWidth();
         $height = $destThumbParamsOutput->getHeight();
         $scaleWidth = $destThumbParamsOutput->getScaleWidth();
         $scaleHeight = $destThumbParamsOutput->getScaleHeight();
         $cropper = new KImageMagickCropper($srcPath, $destPath, kConf::get('bin_path_imagemagick'), true);
         $cropped = $cropper->crop($quality, $cropType, $width, $height, $cropX, $cropY, $cropWidth, $cropHeight, $scaleWidth, $scaleHeight, $bgcolor);
         if (!$cropped || !file_exists($destPath)) {
             $errDescription = "Crop failed";
             return false;
         }
         return $destPath;
     } catch (Exception $ex) {
         $errDescription = $ex->getMessage();
         return false;
     }
 }
Exemple #26
0
 /**
  * 
  * @param $entry
  * @param $sub_type
  * @param $version
  * @return FileSync
  */
 private function redirectIfRemote($obj, $sub_type, $version, $strict = true)
 {
     $dataKey = $obj->getSyncKey($sub_type, $version);
     list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($dataKey, true, false);
     if (!$file_sync) {
         if ($strict) {
             // file does not exist on any DC - die
             KalturaLog::log("Error - no FileSync for object [{$obj->getId()}]");
             header("HTTP/1.0 404 Not Found");
             die;
         } else {
             return null;
         }
     }
     return $this->redirectFileSyncIfRemote($file_sync, $local);
 }
 /**
  * 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->getIntRequestParameter("version", null, 0, 10000000);
     $type = $this->getIntRequestParameter("type", 1, 1, 5);
     //Hack: if KMS sends thumbnail request containing "!" char, the type should be treated as 5.
     $width = $this->getRequestParameter("width", -1);
     $height = $this->getRequestParameter("height", -1);
     if (strpos($width, "!") || strpos($height, "!")) {
         $type = 5;
     }
     $width = $this->getFloatRequestParameter("width", -1, -1, 10000);
     $height = $this->getFloatRequestParameter("height", -1, -1, 10000);
     $crop_provider = $this->getRequestParameter("crop_provider", null);
     $quality = $this->getIntRequestParameter("quality", 0, 0, 100);
     $src_x = $this->getFloatRequestParameter("src_x", 0, 0, 10000);
     $src_y = $this->getFloatRequestParameter("src_y", 0, 0, 10000);
     $src_w = $this->getFloatRequestParameter("src_w", 0, 0, 10000);
     $src_h = $this->getFloatRequestParameter("src_h", 0, 0, 10000);
     $vid_sec = $this->getFloatRequestParameter("vid_sec", -1, -1);
     $vid_slice = $this->getRequestParameter("vid_slice", -1);
     $vid_slices = $this->getRequestParameter("vid_slices", -1);
     $density = $this->getFloatRequestParameter("density", 0, 0);
     $stripProfiles = $this->getRequestParameter("strip", null);
     $flavor_id = $this->getRequestParameter("flavor_id", null);
     $file_name = $this->getRequestParameter("file_name", null);
     $file_name = basename($file_name);
     // 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->getFloatRequestParameter("rel_width", -1, -1, 10000);
     $rel_height = $this->getFloatRequestParameter("rel_height", -1, -1, 10000);
     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");
     $partner = null;
     // validating the inputs
     if (!is_numeric($quality) || $quality < 0 || $quality > 100) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'quality must be between 20 and 100');
     }
     if (!is_numeric($src_x) || $src_x < 0 || $src_x > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_x must be between 0 and 10000');
     }
     if (!is_numeric($src_y) || $src_y < 0 || $src_y > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_y must be between 0 and 10000');
     }
     if (!is_numeric($src_w) || $src_w < 0 || $src_w > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_w must be between 0 and 10000');
     }
     if (!is_numeric($src_h) || $src_h < 0 || $src_h > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_h must be between 0 and 10000');
     }
     if (!is_numeric($width) || $width < 0 || $width > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'width must be between 0 and 10000');
     }
     if (!is_numeric($height) || $height < 0 || $height > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'height must be between 0 and 10000');
     }
     if (!is_numeric($density) || $density < 0) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'density must be positive');
     }
     if (!is_numeric($vid_sec) || $vid_sec < -1) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'vid_sec must be positive');
     }
     if (!preg_match('/^[0-9a-fA-F]{1,6}$/', $bgcolor)) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'bgcolor must be six hexadecimal characters');
     }
     if ($upload_token_id) {
         $upload_token = UploadTokenPeer::retrieveByPK($upload_token_id);
         if ($upload_token) {
             $partnerId = $upload_token->getPartnerId();
             $partner = PartnerPeer::retrieveByPK($partnerId);
             if ($density == 0) {
                 $density = $partner->getDefThumbDensity();
             }
             if (is_null($stripProfiles)) {
                 $stripProfiles = $partner->getStripThumbProfile();
             }
             $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, $density, $stripProfiles);
                 kFile::dumpFile($thumb_full_path);
             } else {
                 KalturaLog::debug("token_id [{$upload_token_id}] not found in DC [" . kDataCenterMgr::getCurrentDcId() . "]. dump url to romote DC");
                 $remoteUrl = kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()) . $_SERVER['REQUEST_URI'];
                 kFile::dumpUrl($remoteUrl);
             }
         }
     }
     if ($entry_id) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             // problem could be due to replication lag
             kFile::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
         }
     } else {
         // 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);
         }
     }
     $partner = $entry->getPartner();
     if ($density == 0) {
         $density = $partner->getDefThumbDensity();
     }
     $thumbParams = new kThumbnailParameters();
     $thumbParams->setSupportAnimatedThumbnail($partner->getSupportAnimatedThumbnails());
     if (is_null($stripProfiles)) {
         $stripProfiles = $partner->getStripThumbProfile();
     }
     //checks whether the thumbnail display should be restricted by KS
     $base64Referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64Referrer);
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     if (!$referrer) {
         $referrer = kApiCache::getHttpReferrer();
     }
     $ksStr = $this->getRequestParameter("ks");
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, accessControlContextType::THUMBNAIL);
     $securyEntryHelper->validateForPlay();
     // 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;
     }
     $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB;
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA;
     }
     KalturaLog::debug("get thumbnail filesyncs");
     $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) {
         $tempThumbPath = $entry->getLocalThumbFilePath($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $density, $stripProfiles, $flavor_id, $file_name);
         if (!$tempThumbPath) {
             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
         }
     }
     if (!$local && !$tempThumbPath && $file_sync) {
         if (!in_array($file_sync->getDc(), kDataCenterMgr::getDcIds())) {
             $remoteUrl = $file_sync->getExternalUrl($entry->getId());
             header("Location: {$remoteUrl}");
             die;
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']);
         kFile::dumpUrl($remoteUrl);
     }
     // 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, null, $density, $stripProfiles, $thumbParams);
         } catch (Exception $ex) {
             if ($ex->getCode() != kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 KalturaLog::log("Error - resize image failed");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             // get original flavor asset
             $origFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry_id);
             if (!$origFlavorAsset) {
                 KalturaLog::log("Error - no original flavor for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
             }
             $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);
             }
             if (!in_array($remoteFileSync->getDc(), kDataCenterMgr::getDcIds())) {
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync);
             kFile::dumpUrl($remoteUrl);
         }
     }
     $nocache = strpos($tempThumbPath, "_NOCACHE_") !== false;
     if ($securyEntryHelper->shouldDisableCache() || kApiCache::hasExtraFields() || !$securyEntryHelper->isKsWidget() && $securyEntryHelper->hasRules()) {
         $nocache = true;
     }
     // 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)
 }
Exemple #28
0
 /**
  * @param BatchJob $batchJob
  * @param entry $entry
  * @param string $flavorAssetId
  * @param string $inputFileSyncLocalPath
  * @return BatchJob
  */
 public static function addConvertProfileJob(BatchJob $parentJob = null, entry $entry, $flavorAssetId, $inputFileSyncLocalPath)
 {
     KalturaLog::debug("Parent job [" . ($parentJob ? $parentJob->getId() : 'none') . "] entry [" . $entry->getId() . "] flavor asset [{$flavorAssetId}] input file [{$inputFileSyncLocalPath}]");
     if ($entry->getConversionQuality() == conversionProfile2::CONVERSION_PROFILE_NONE) {
         $entry->setStatus(entryStatus::PENDING);
         $entry->save();
         KalturaLog::notice('Entry should not be converted');
         return null;
     }
     $importingSources = false;
     // if file size is 0, do not create conversion profile and set entry status as error converting
     if (!file_exists($inputFileSyncLocalPath) || kFile::fileSize($inputFileSyncLocalPath) == 0) {
         KalturaLog::debug("Input file [{$inputFileSyncLocalPath}] does not exist");
         $partner = $entry->getPartner();
         $conversionProfile = myPartnerUtils::getConversionProfile2ForEntry($entry->getId());
         // load the asset params to the instance pool
         $flavorIds = flavorParamsConversionProfilePeer::getFlavorIdsByProfileId($conversionProfile->getId());
         assetParamsPeer::retrieveByPKs($flavorIds);
         $conversionRequired = false;
         $sourceFileRequiredStorages = array();
         $sourceIncludedInProfile = false;
         $flavorAsset = assetPeer::retrieveById($flavorAssetId);
         $flavors = flavorParamsConversionProfilePeer::retrieveByConversionProfile($conversionProfile->getId());
         KalturaLog::debug("Found flavors [" . count($flavors) . "] in conversion profile [" . $conversionProfile->getId() . "]");
         foreach ($flavors as $flavor) {
             /* @var $flavor flavorParamsConversionProfile */
             if ($flavor->getFlavorParamsId() == $flavorAsset->getFlavorParamsId()) {
                 KalturaLog::debug("Flavor [" . $flavor->getFlavorParamsId() . "] is ingested source");
                 $sourceIncludedInProfile = true;
                 continue;
             }
             $flavorParams = assetParamsPeer::retrieveByPK($flavor->getFlavorParamsId());
             if ($flavorParams instanceof liveParams || $flavor->getOrigin() == assetParamsOrigin::INGEST) {
                 KalturaLog::debug("Flavor [" . $flavor->getFlavorParamsId() . "] should be ingested");
                 continue;
             }
             if ($flavor->getOrigin() == assetParamsOrigin::CONVERT_WHEN_MISSING) {
                 $siblingFlavorAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $flavor->getFlavorParamsId());
                 if ($siblingFlavorAsset) {
                     KalturaLog::debug("Flavor [" . $flavor->getFlavorParamsId() . "] already ingested");
                     continue;
                 }
             }
             $sourceFileRequiredStorages[] = $flavorParams->getSourceRemoteStorageProfileId();
             $conversionRequired = true;
             break;
         }
         if ($conversionRequired) {
             foreach ($sourceFileRequiredStorages as $storageId) {
                 if ($storageId == StorageProfile::STORAGE_KALTURA_DC) {
                     $key = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                     list($syncFile, $local) = kFileSyncUtils::getReadyFileSyncForKey($key, true, false);
                     if ($syncFile && $syncFile->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL && $partner && $partner->getImportRemoteSourceForConvert()) {
                         KalturaLog::debug("Creates import job for remote file sync");
                         $url = $syncFile->getExternalUrl($entry->getId());
                         kJobsManager::addImportJob($parentJob, $entry->getId(), $partner->getId(), $url, $flavorAsset, null, null, true);
                         $importingSources = true;
                         continue;
                     }
                 } elseif ($flavorAsset->getExternalUrl($storageId)) {
                     continue;
                 }
                 kBatchManager::updateEntry($entry->getId(), entryStatus::ERROR_CONVERTING);
                 $flavorAsset = assetPeer::retrieveById($flavorAssetId);
                 $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
                 $flavorAsset->setDescription('Entry of size 0 should not be converted');
                 $flavorAsset->save();
                 KalturaLog::err('Entry of size 0 should not be converted');
                 return null;
             }
         } else {
             if ($flavorAsset->getStatus() == asset::FLAVOR_ASSET_STATUS_QUEUED) {
                 if ($sourceIncludedInProfile) {
                     $flavorAsset->setStatusLocalReady();
                 } else {
                     $flavorAsset->setStatus(asset::FLAVOR_ASSET_STATUS_DELETED);
                     $flavorAsset->setDeletedAt(time());
                 }
                 $flavorAsset->save();
                 if ($sourceIncludedInProfile) {
                     kBusinessPostConvertDL::handleConvertFinished(null, $flavorAsset);
                 }
             }
             return null;
         }
     }
     if ($entry->getStatus() != entryStatus::READY) {
         $entry->setStatus(entryStatus::PRECONVERT);
     }
     $jobData = new kConvertProfileJobData();
     $jobData->setFlavorAssetId($flavorAssetId);
     $jobData->setInputFileSyncLocalPath($inputFileSyncLocalPath);
     $jobData->setExtractMedia(true);
     if ($entry->getType() != entryType::MEDIA_CLIP) {
         $jobData->setExtractMedia(false);
         $entry->setCreateThumb(false);
     }
     $entry->save();
     $batchJob = null;
     if ($parentJob) {
         $batchJob = $parentJob->createChild(BatchJobType::CONVERT_PROFILE);
     } else {
         $batchJob = new BatchJob();
         $batchJob->setEntryId($entry->getId());
         $batchJob->setPartnerId($entry->getPartnerId());
         $batchJob->setUseNewRoot(true);
     }
     $batchJob->setObjectId($entry->getId());
     $batchJob->setObjectType(BatchJobObjectType::ENTRY);
     if ($importingSources) {
         $batchJob->setStatus(BatchJob::BATCHJOB_STATUS_DONT_PROCESS);
     }
     return self::addJob($batchJob, $jobData, BatchJobType::CONVERT_PROFILE);
 }
Exemple #29
0
 /**
  * will create thumbnail according to the entry type
  * @return the thumbnail path.
  */
 public function getLocalThumbFilePath($version, $width, $height, $type, $bgcolor = "ffffff", $crop_provider = null, $quality = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $vid_sec = -1, $vid_slice = 0, $vid_slices = -1, $density = 0, $stripProfiles = false, $flavorId = null, $fileName = null)
 {
     $contentPath = myContentStorage::getFSContentRootPath();
     // if entry type is audio - serve generic thumb:
     if ($this->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) {
         if ($this->getStatus() == entryStatus::DELETED || $this->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK) {
             KalturaLog::log("rejected audio entry - not serving thumbnail");
             KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
         }
         $audioEntryExist = false;
         $audioThumbEntry = null;
         $audioThumbEntryId = null;
         $partner = $this->getPartner();
         if ($partner) {
             $audioThumbEntryId = $partner->getAudioThumbEntryId();
         }
         if ($audioThumbEntryId) {
             $audioThumbEntry = entryPeer::retrieveByPK($audioThumbEntryId);
         }
         if ($audioThumbEntry && $audioThumbEntry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
             $fileSyncVersion = $partner->getAudioThumbEntryVersion();
             $audioEntryKey = $audioThumbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $fileSyncVersion);
             $contentPath = kFileSyncUtils::getLocalFilePathForKey($audioEntryKey);
             if ($contentPath) {
                 $msgPath = $contentPath;
                 $audioEntryExist = true;
             } else {
                 KalturaLog::err('no local file sync for entry id');
             }
         }
         if (!$audioEntryExist) {
             $msgPath = $contentPath . "content/templates/entry/thumbnail/audio_thumb.jpg";
         }
         return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $msgPath, $density, $stripProfiles);
     } elseif ($this->getMediaType() == entry::ENTRY_MEDIA_TYPE_SHOW) {
         // roughcut without any thumbnail, probably just created
         $msgPath = $contentPath . "content/templates/entry/thumbnail/auto_edit.jpg";
         return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $msgPath, $density, $stripProfiles);
     } elseif ($this->getType() == entryType::MEDIA_CLIP) {
         try {
             return myEntryUtils::resizeEntryImage($this, $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 = assetPeer::retrieveOriginalByEntryId($this->getId());
                 if ($origFlavorAsset) {
                     $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                     list($readyFileSync, $isLocal) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, TRUE, FALSE);
                     if ($readyFileSync) {
                         if ($isLocal) {
                             KalturaLog::err('Trying to redirect to myself - stop here.');
                             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                         }
                         //Ready fileSync is on the other DC - dumping
                         kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
                     }
                     KalturaLog::err('No ready fileSync found on any DC.');
                     KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                 }
             }
         }
     }
 }
 /**
  * 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);
 }