public function entryHandled(entry $dbEntry) { parent::entryHandled($dbEntry); $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($dbEntry->getId()); $syncKey = $originalFlavorAsset->getSyncKey(asset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); $sourceFilePath = kFileSyncUtils::getLocalFilePathForKey($syncKey); // call mediaInfo for file $dbMediaInfo = new mediaInfo(); try { $mediaInfoParser = new KMediaInfoMediaParser($sourceFilePath, kConf::get('bin_path_mediainfo')); $mediaInfo = $mediaInfoParser->getMediaInfo(); $dbMediaInfo = $mediaInfo->toInsertableObject($dbMediaInfo); $dbMediaInfo->setFlavorAssetId($originalFlavorAsset->getId()); $dbMediaInfo->save(); } catch (Exception $e) { KalturaLog::err("Getting media info: " . $e->getMessage()); $dbMediaInfo = null; } // fix flavor asset according to mediainfo if ($dbMediaInfo) { KDLWrap::ConvertMediainfoCdl2FlavorAsset($dbMediaInfo, $originalFlavorAsset); $flavorTags = KDLWrap::CDLMediaInfo2Tags($dbMediaInfo, array(flavorParams::TAG_WEB, flavorParams::TAG_MBR)); $originalFlavorAsset->setTags(implode(',', array_unique($flavorTags))); } $originalFlavorAsset->setStatusLocalReady(); $originalFlavorAsset->save(); $dbEntry->setStatus(entryStatus::READY); $dbEntry->save(); }
/** * @param string $entryId * @return mediaInfo */ public static function retrieveOriginalByEntryId($entryId) { $sourceFlavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (!$sourceFlavorAsset) { return null; } $criteria = new Criteria(); $criteria->add(mediaInfoPeer::FLAVOR_ASSET_ID, $sourceFlavorAsset->getId()); $criteria->addDescendingOrderByColumn(mediaInfoPeer::CREATED_AT); return mediaInfoPeer::doSelectOne($criteria); }
private function reconvertEntry($entry_id, $conversion_profile_id, $job_priority) { $entry = entryPeer::retrieveByPK($entry_id); $this->error = ""; if (!$entry) { $error = "Cannot reconvert entry [{$entry_id}]. Might be a deleted entry"; return array($entry_id, null, null, $error); } $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry_id); if (!$flavorAsset) { $flavorAsset = assetPeer::retrieveReadyWebByEntryId($entry_id); if (!$flavorAsset) { $flavorAssets = assetPeer::retrieveFlavorsByEntryId($entry_id); if (!$flavorAssets) { $error = "Cannot find good enough flavor asset to re-convert from"; return array($entry_id, $entry, null, $error); } $flavorAsset = $flavorAssets[0]; // choose the first one } } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); if (!$filePath) { $error = "Cannot find a fileSync for the flavorAsset [" . $flavorAsset->getId() . "]"; return array($entry_id, $entry, null, $error); } $dbBatchJob = new BatchJob(); $dbBatchJob->setEntryId($entry_id); $dbBatchJob->setPartnerId($entry->getPartnerId()); $dbBatchJob->setStatus(BatchJob::BATCHJOB_STATUS_PENDING); $dbBatchJob->setDc(kDataCenterMgr::getCurrentDcId()); //$dbBatchJob->setPriority ( $job_priority ); Not supported anymore $dbBatchJob->setObjectId($entry_id); $dbBatchJob->setObjectType(BatchJobObjectType::ENTRY); $dbBatchJob->setJobType(BatchJobType::CONVERT_PROFILE); $dbBatchJob->save(); // creates a convert profile job $convertProfileData = new kConvertProfileJobData(); $convertProfileData->setFlavorAssetId($flavorAsset->getId()); $convertProfileData->setInputFileSyncLocalPath($filePath); kJobsManager::addJob($dbBatchJob, $convertProfileData, BatchJobType::CONVERT_PROFILE); // save again afget the addJob $dbBatchJob->save(); return array($entry_id, $entry, $dbBatchJob, $error); }
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; }
public function execute() { requestUtils::handleConditionalGet(); $entry_id = $this->getRequestParameter("entry_id"); $ks_str = $this->getRequestParameter("ks"); $base64_referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($base64_referrer); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ""; } $clip_from = $this->getRequestParameter("clip_from", 0); // milliseconds $clip_to = $this->getRequestParameter("clip_to", 2147483647); // milliseconds if ($clip_to == 0) { $clip_to = 2147483647; } $request = $_SERVER["REQUEST_URI"]; // remove dynamic fields from the url so we'll request a single url from the cdn $request = str_replace("/referrer/{$base64_referrer}", "", $request); $request = str_replace("/ks/{$ks_str}", "", $request); $entry = null; if ($ks_str) { try { kCurrentContext::initKsPartnerUser($ks_str); } catch (Exception $ex) { KExternalErrors::dieError(KExternalErrors::INVALID_KS); } } else { $entry = kCurrentContext::initPartnerByEntryId($entry_id); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } kEntitlementUtils::initEntitlementEnforcement(); // workaround the filter which hides all the deleted entries - // now that deleted entries are part of xmls (they simply point to the 'deleted' templates), we should allow them here if (!$entry) { $entry = entryPeer::retrieveByPKNoFilter($entry_id); } else { if (!kEntitlementUtils::isEntryEntitled($entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } KalturaMonitorClient::initApiMonitor(false, 'keditorservices.flvclipper', $entry->getPartnerId()); myPartnerUtils::blockInactivePartner($entry->getPartnerId()); if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_BLOCK_FLVCLIPPER_ACTION, $entry->getPartnerId())) { KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED); } // set the memory size to be able to serve big files in a single chunk ini_set("memory_limit", "64M"); // set the execution time to be able to serve big files in a single chunk ini_set("max_execution_time", 240); if ($entry->getType() == entryType::MIX && $entry->getStatus() == entryStatus::DELETED) { // because the fiter was turned off - a manual check for deleted entries must be done. KExternalErrors::dieGracefully(); } else { if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) { $version = $this->getRequestParameter("version", null); $width = $this->getRequestParameter("width", -1); $height = $this->getRequestParameter("height", -1); $crop_provider = $this->getRequestParameter("crop_provider", null); $bgcolor = $this->getRequestParameter("bgcolor", "ffffff"); $type = $this->getRequestParameter("type", 1); $quality = $this->getRequestParameter("quality", 0); $src_x = $this->getRequestParameter("src_x", 0); $src_y = $this->getRequestParameter("src_y", 0); $src_w = $this->getRequestParameter("src_w", 0); $src_h = $this->getRequestParameter("src_h", 0); $vid_sec = $this->getRequestParameter("vid_sec", -1); $vid_slice = $this->getRequestParameter("vid_slice", -1); $vid_slices = $this->getRequestParameter("vid_slices", -1); if ($width == -1 && $height == -1) { $width = 640; $height = 480; } else { if ($width == -1) { // if only either width or height is missing reset them to zero, and convertImage will handle them $width = 0; } else { if ($height == -1) { $height = 0; } } } $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices); kFileUtils::dumpFile($tempThumbPath, null, strpos($tempThumbPath, "_NOCACHE_") === false ? null : 0); } } $audio_only = $this->getRequestParameter("audio_only"); // milliseconds $flavor = $this->getRequestParameter("flavor", 1); // $flavor_param_id = $this->getRequestParameter("flavor_param_id", null); // $streamer = $this->getRequestParameter("streamer"); // if (substr($streamer, 0, 4) == "rtmp") { // the fms may add .mp4 to the end of the url $streamer = "rtmp"; } // grab seek_from_bytes parameter and normalize url $seek_from_bytes = $this->getRequestParameter("seek_from_bytes", -1); $request = str_replace("/seek_from_bytes/{$seek_from_bytes}", "", $request); if ($seek_from_bytes <= 0) { $seek_from_bytes = -1; } // grab seek_from parameter and normalize url $seek_from = $this->getRequestParameter("seek_from", -1); $request = str_replace("/seek_from/{$seek_from}", "", $request); if ($seek_from <= 0) { $seek_from = -1; } $this->dump_from_byte = 0; // reset accurate seek from timestamp $seek_from_timestamp = -1; // backward compatibility if ($flavor === "0") { // for edit version $flavor = "edit"; } if ($flavor === "1" || $flavor === 1) { // for play version $flavor = null; } // when flavor is null, we will get a default flavor if ($flavor == "edit") { $flavorAsset = assetPeer::retrieveBestEditByEntryId($entry->getId()); } elseif (!is_null($flavor)) { $flavorAsset = assetPeer::retrieveById($flavor); // when specific asset was request, we don't validate its tags if ($flavorAsset && ($flavorAsset->getEntryId() != $entry->getId() || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY)) { $flavorAsset = null; } // we will throw an error later } elseif (is_null($flavor) && !is_null($flavor_param_id)) { $flavorAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $flavor_param_id); if ($flavorAsset && $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) { $flavorAsset = null; } // we will throw an error later } else { if ($entry->getSource() == entry::ENTRY_MEDIA_SOURCE_WEBCAM) { $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId()); } else { $flavorAsset = assetPeer::retrieveBestPlayByEntryId($entry->getId()); } if (!$flavorAsset) { $flavorAssets = assetPeer::retrieveReadyFlavorsByEntryIdAndTag($entry->getId(), flavorParams::TAG_WEB); if (count($flavorAssets) > 0) { $flavorAsset = $flavorAssets[0]; } } } if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (kFileSyncUtils::file_exists($syncKey, false)) { $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); } else { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } if ($fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) { $urlManager = DeliveryProfilePeer::getRemoteDeliveryByStorageId(DeliveryProfileDynamicAttributes::init($fileSync->getDc(), $flavorAsset->getEntryId()), null, $flavorAsset); if (!$urlManager) { KalturaLog::log("Error - failed to find an HTTP delivery for storage profile [" . $fileSync->getDc() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } $url = rtrim($urlManager->getUrl(), '/') . '/' . ltrim($urlManager->getFileSyncUrl($fileSync), '/'); header('location: ' . $url); die; } $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); $this->redirect($remoteUrl); } $flv_wrapper = new myFlvHandler($path); $isFlv = $flv_wrapper->isFlv(); // scrubbing is not allowed within mp4 files if (!$isFlv) { $seek_from = $seek_from_bytes = -1; } if ($seek_from !== -1 && $seek_from !== 0) { if ($audio_only === '0') { // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) { $audio_only = true; } list($bytes, $duration, $first_tag_byte, $to_byte) = $flv_wrapper->clip(0, -1, $audio_only); list($bytes, $duration, $from_byte, $to_byte, $seek_from_timestamp) = $flv_wrapper->clip($seek_from, -1, $audio_only); $seek_from_bytes = myFlvHandler::FLV_HEADER_SIZE + $flv_wrapper->getMetadataSize($audio_only) + $from_byte - $first_tag_byte; } // the direct path without a cdn is "http://s3kaltura.s3.amazonaws.com".$entry->getDataPath(); $extStorageUrl = $entry->getExtStorageUrl(); if ($extStorageUrl && substr_count($extStorageUrl, 's3kaltura')) { // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from if ($seek_from_timestamp == -1) { $seek_from_timestamp = $seek_from; } $request_host = parse_url($extStorageUrl, PHP_URL_HOST); $akamai_url = str_replace($request_host, "cdns3akmi.kaltura.com", $extStorageUrl); $akamai_url .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000); header("Location: {$akamai_url}"); KExternalErrors::dieGracefully(); } elseif ($extStorageUrl) { // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from if ($seek_from_timestamp == -1) { $seek_from_timestamp = $seek_from; } $extStorageUrl .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000); header("Location: {$extStorageUrl}"); KExternalErrors::dieGracefully(); } // use headers to detect cdn $cdn_name = ""; $via_header = @$_SERVER["HTTP_VIA"]; if (strpos($via_header, "llnw.net") !== false) { $cdn_name = "limelight"; } else { if (strpos($via_header, "akamai") !== false) { $cdn_name = "akamai"; } else { if (strpos($via_header, "Level3") !== false) { $cdn_name = "level3"; } } } // setting file extension - first trying frrom flavor asset $ext = $flavorAsset->getFileExt(); // if failed, set extension according to file type (isFlv) if (!$ext) { $ext = $isFlv ? "flv" : "mp4"; } $flv_extension = $streamer == "rtmp" ? "?" : "/a.{$ext}?novar=0"; // dont check for rtmp / and for an already redirect url if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) { // check security using ks $securyEntryHelper = new KSecureEntryHelper($entry, $ks_str, $referrer, ContextType::PLAY); if ($securyEntryHelper->shouldPreview()) { $this->checkForPreview($securyEntryHelper, $clip_to); } else { $securyEntryHelper->validateForPlay($entry, $ks_str); } } else { // if needs security check using cdn authentication mechanism // for now assume this is a cdn request and don't check for security } // use limelight mediavault if either security policy requires it or if we're trying to seek within the video if ($entry->getSecurityPolicy() || $seek_from_bytes !== -1) { // we have three options: // arrived through limelight mediavault url - the url is secured // arrived directly through limelight (not secured through mediavault) - enforce ks and redirect to mediavault url // didnt use limelight - enforce ks // the cdns are configured to authenticate request for /s/.... // check if we're already in a redirected secure link using the "/s/" prefix $secure_request = substr($request, 0, 3) == "/s/"; if ($secure_request && ($cdn_name == "limelight" || $cdn_name == "level3")) { // request was validated by cdn let it through } else { // extract ks $ks_str = $this->getRequestParameter("ks", ""); if ($entry->getSecurityPolicy()) { if (!$ks_str) { $this->logMessage("flvclipper - no KS"); KExternalErrors::dieGracefully(); } $ks = kSessionUtils::crackKs($ks_str); if (!$ks) { $this->logMessage("flvclipper - invalid ks [{$ks_str}]"); KExternalErrors::dieGracefully(); } $matched_privs = $ks->verifyPrivileges("sview", $entry_id); $this->logMessage("flvclipper - verifyPrivileges name [sview], priv [{$entry_id}] [{$matched_privs}]"); if (!$matched_privs) { $this->logMessage("flvclipper - doesnt not match required privlieges [{$ks_str}]"); KExternalErrors::dieGracefully(); } } if ($cdn_name == "limelight") { $ll_url = requestUtils::getCdnHost() . "/s{$request}" . $flv_extension; $secret = kConf::get("limelight_madiavault_password"); $expire = "&e=" . (time() + 120); $ll_url .= $expire; $fs = $seek_from_bytes == -1 ? "" : "&fs={$seek_from_bytes}"; $ll_url .= "&h=" . md5("{$secret}{$ll_url}") . $fs; //header("Location: $ll_url"); $this->redirect($ll_url); } else { if ($cdn_name == "level3") { $level3_url = $request . $flv_extension; if ($entry->getSecurityPolicy()) { $level3_url = "/s{$level3_url}"; // set expire time in GMT hence the date("Z") offset $expire = "&nva=" . strftime("%Y%m%d%H%M%S", time() - date("Z") + 30); $level3_url .= $expire; $secret = kConf::get("level3_authentication_key"); $hash = "0" . substr(self::hmac('sha1', $secret, $level3_url), 0, 20); $level3_url .= "&h={$hash}"; } $level3_url .= $seek_from_bytes == -1 ? "" : "&start={$seek_from_bytes}"; header("Location: {$level3_url}"); KExternalErrors::dieGracefully(); } else { if ($cdn_name == "akamai") { $akamai_url = $request . $flv_extension; // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from if ($seek_from_timestamp == -1) { $seek_from_timestamp = $seek_from; } $akamai_url .= $seek_from_bytes == -1 ? "" : "&aktimeoffset=" . floor($seek_from_timestamp / 1000); header("Location: {$akamai_url}"); KExternalErrors::dieGracefully(); } } } // a seek request without a supporting cdn - we need to send the answer from our server if ($seek_from_bytes !== -1 && $via_header === null) { $this->dump_from_byte = $seek_from_bytes; } } } // always add the file suffix to the request (needed for scrubbing by some cdns, // and also breaks without extension on some corporate antivirus). // we add the the novar paramter since a leaving a trailing "?" will be trimmed // and then the /seek_from request will result in another url which level3 // will try to refetch from the origin // note that for streamer we dont add the file extension if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) { // a seek request without a supporting cdn - we need to send the answer from our server if ($seek_from_bytes !== -1 && $via_header === null) { $request .= "/seek_from_bytes/{$seek_from_bytes}"; } requestUtils::sendCdnHeaders("flv", 0); header("Location: {$request}" . $flv_extension); KExternalErrors::dieGracefully(); } // mp4 if (!$isFlv) { $limit_file_size = 0; if ($clip_to != 2147483647) { $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId()); if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) { $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration()); $limit_file_size = floor(@kFile::fileSize($path) * ($clip_to / $duration) * 1.2); } } KalturaLog::info("serving file [{$path}] entry id [{$entry_id}] limit file size [{$limit_file_size}] clip_to [{$clip_to}]"); kFileUtils::dumpFile($path, null, null, $limit_file_size); } $this->logMessage("flvclipperAction: serving file [{$path}] entry_id [{$entry_id}] clip_from [{$clip_from}] clip_to [{$clip_to}]", "warning"); if ($audio_only === '0') { // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) { $audio_only = true; } //$start = microtime(true); list($bytes, $duration, $from_byte, $to_byte, $from_ts, $cuepoint_pos) = myFlvStaticHandler::clip($path, $clip_from, $clip_to, $audio_only); $metadata_size = $flv_wrapper->getMetadataSize($audio_only); $this->from_byte = $from_byte; $this->to_byte = $to_byte; //$end1 = microtime(true); //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" ); //$this->logMessage( "flvclipperAction: serving file [$path] t1 [" . ( $end1-$start) . "]"); $data_offset = $metadata_size + myFlvHandler::getHeaderSize(); // if we're returning a partial file adjust the total size: // substract the metadata and bytes which are not delivered if ($this->dump_from_byte >= $data_offset && !$audio_only) { $bytes -= $metadata_size + max(0, $this->dump_from_byte - $data_offset); } $this->total_length = $data_offset + $bytes; //echo " $bytes , $duration ,$from_byte , $to_byte, $cuepoint_pos\n"; die; $this->cuepoint_time = 0; $this->cuepoint_pos = 0; if ($streamer == "chunked" && $clip_to != 2147483647) { $this->cuepoint_time = $clip_to - 1; $this->cuepoint_pos = $cuepoint_pos; $this->total_length += myFlvHandler::CUEPOINT_TAG_SIZE; } //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes with header & md [" . $this->total_length . "] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" ); $this->flv_wrapper = $flv_wrapper; $this->audio_only = $audio_only; try { Propel::close(); } catch (Exception $e) { $this->logMessage("flvclipperAction: error closing db {$e}"); } KExternalErrors::terminateDispatch(); return sfView::SUCCESS; }
public static function handleConvertProfileFinished(BatchJob $dbBatchJob, kConvertProfileJobData $data, BatchJob $twinJob = null) { KalturaLog::debug("Convert Profile finished"); $originalflavorAsset = assetPeer::retrieveOriginalByEntryId($dbBatchJob->getEntryId()); if ($originalflavorAsset && $originalflavorAsset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_TEMP) { $originalflavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_DELETED); $originalflavorAsset->setDeletedAt(time()); $originalflavorAsset->save(); } kFlowHelper::generateThumbnailsFromFlavor($dbBatchJob->getEntryId(), $dbBatchJob); return $dbBatchJob; }
/** * 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) }
/** * 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(); }
public static function exportSourceAssetFromJob(BatchJob $dbBatchJob) { // convert profile finished - export source flavor if ($dbBatchJob->getJobType() == BatchJobType::CONVERT_PROFILE) { $externalStorages = StorageProfilePeer::retrieveAutomaticByPartnerId($dbBatchJob->getPartnerId()); $sourceFlavor = assetPeer::retrieveOriginalByEntryId($dbBatchJob->getEntryId()); if (!$sourceFlavor) { KalturaLog::debug('Cannot find source flavor for entry id [' . $dbBatchJob->getEntryId() . ']'); } else { if (!$sourceFlavor->isLocalReadyStatus()) { KalturaLog::debug('Source flavor id [' . $sourceFlavor->getId() . '] has status [' . $sourceFlavor->getStatus() . '] - not ready for export'); } else { foreach ($externalStorages as $externalStorage) { if ($externalStorage->triggerFitsReadyAsset($dbBatchJob->getEntryId())) { self::exportFlavorAsset($sourceFlavor, $externalStorage); } } } } } // convert collection finished - export ism and ismc files if ($dbBatchJob->getJobType() == BatchJobType::CONVERT_COLLECTION && $dbBatchJob->getJobSubType() == conversionEngineType::EXPRESSION_ENCODER3) { $entry = $dbBatchJob->getEntry(); $externalStorages = StorageProfilePeer::retrieveAutomaticByPartnerId($dbBatchJob->getPartnerId()); foreach ($externalStorages as $externalStorage) { if ($externalStorage->triggerFitsReadyAsset($entry->getId())) { $ismKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM); if (kFileSyncUtils::fileSync_exists($ismKey)) { self::export($entry, $externalStorage, $ismKey); } $ismcKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC); if (kFileSyncUtils::fileSync_exists($ismcKey)) { self::export($entry, $externalStorage, $ismcKey); } } } } return true; }
/** * request conversion for all entries that doesnt have the required flavor param * returns a comma-separated ids of conversion jobs * * @action requestConversion * @param string $feedId * @return string * @throws KalturaErrors::INVALID_FEED_ID */ public function requestConversionAction($feedId) { $syndicationFeedDB = syndicationFeedPeer::retrieveByPK($feedId); if (!$syndicationFeedDB) { throw new KalturaAPIException(KalturaErrors::INVALID_FEED_ID, $feedId); } // find entry ids that already converted to the flavor $feedRendererWithTheFlavor = new KalturaSyndicationFeedRenderer($feedId); $feedRendererWithTheFlavor->addFlavorParamsAttachedFilter(); $entriesWithTheFlavor = $feedRendererWithTheFlavor->getEntriesIds(); // create filter of the entries that not converted $entryFilter = new entryFilter(); $entryFilter->setIdNotIn($entriesWithTheFlavor); // create feed with the new filter $feedRendererToConvert = new KalturaSyndicationFeedRenderer($feedId); $feedRendererToConvert->addFilter($entryFilter); $createdJobsIds = array(); $flavorParamsId = $feedRendererToConvert->syndicationFeed->flavorParamId; while ($entry = $feedRendererToConvert->getNextEntry()) { $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId()); if (!is_null($originalFlavorAsset)) { $err = ""; $job = kBusinessPreConvertDL::decideAddEntryFlavor(null, $entry->getId(), $flavorParamsId, $err); if ($job && is_object($job)) { $createdJobsIds[] = $job->getId(); } } } return implode(',', $createdJobsIds); }
/** * Serves the file content * * @action serveByFlavorParamsId * @serverOnly * @param string $entryId Document entry id * @param string $flavorParamsId Flavor params id * @param bool $forceProxy force to get the content without redirect * * @throws KalturaErrors::ENTRY_ID_NOT_FOUND * @throws KalturaErrors::FLAVOR_ASSET_IS_NOT_READY * @throws KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND */ public function serveByFlavorParamsIdAction($entryId, $flavorParamsId = null, $forceProxy = false) { KalturaResponseCacher::disableCache(); entryPeer::setDefaultCriteriaFilter(); $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry || $dbEntry->getType() != entryType::DOCUMENT) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } $ksObj = $this->getKs(); $ks = $ksObj ? $ksObj->getOriginalString() : null; $securyEntryHelper = new KSecureEntryHelper($dbEntry, $ks, null); $securyEntryHelper->validateForDownload(); $flavorAsset = null; assetPeer::resetInstanceCriteriaFilter(); if ($flavorParamsId) { $flavorAsset = assetPeer::retrieveByEntryIdAndParams($entryId, $flavorParamsId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_IS_NOT_READY, $flavorParamsId); } } else { $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $flavorParamsId); } } $fileName = $dbEntry->getName() . '.' . $flavorAsset->getFileExt(); return $this->serveFlavorAsset($flavorAsset, $fileName, $forceProxy); }
/** * addFlavorConvertJob adds a single flavor conversion * * @param FileSyncKey $srcSyncKey * @param flavorParamsOutput $flavor * @param int $flavorAssetId * @param int $mediaInfoId * @param BatchJob $parentJob * @param int $lastEngineType * @param BatchJob $dbConvertFlavorJob * @return BatchJob */ public static function addFlavorConvertJob(FileSyncKey $srcSyncKey, flavorParamsOutput $flavor, $flavorAssetId, $mediaInfoId = null, BatchJob $parentJob = null, $lastEngineType = null, BatchJob $dbConvertFlavorJob = null) { $localPath = null; $remoteUrl = null; $flavorAsset = assetPeer::retrieveById($flavorAssetId); if (!$flavorAsset) { KalturaLog::err("No flavor asset found for id [{$flavorAssetId}]"); return null; } if ($flavor->getSourceRemoteStorageProfileId() == StorageProfile::STORAGE_KALTURA_DC) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($srcSyncKey, true, false); $partner = PartnerPeer::retrieveByPK($flavorAsset->getPartnerId()); if (!$fileSync) { kBatchManager::updateEntry($flavorAsset->getEntryId(), entryStatus::ERROR_CONVERTING); $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR); $flavorAsset->setDescription("Source file sync not found: {$srcSyncKey}"); $flavorAsset->save(); KalturaLog::err("Source file sync not found: {$srcSyncKey}"); return null; } if (!$local) { if ($fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL && $partner && $partner->getImportRemoteSourceForConvert()) { KalturaLog::debug("Creates import job for remote file sync"); $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_WAIT_FOR_CONVERT); $flavorAsset->setDescription("Source file sync is importing: {$srcSyncKey}"); $flavorAsset->save(); $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($flavorAsset->getEntryId()); $url = $fileSync->getExternalUrl($flavorAsset->getEntryId()); return kJobsManager::addImportJob($parentJob, $flavorAsset->getEntryId(), $partner->getId(), $url, $originalFlavorAsset, null, null, true); } throw new kCoreException("Source file not found for flavor conversion [{$flavorAssetId}]", kCoreException::SOURCE_FILE_NOT_FOUND); } if ($fileSync->getFileType() != FileSync::FILE_SYNC_FILE_TYPE_URL) { $localPath = $fileSync->getFullPath(); } $remoteUrl = $fileSync->getExternalUrl($flavorAsset->getEntryId()); } else { $fileSync = kFileSyncUtils::getReadyExternalFileSyncForKey($srcSyncKey, $flavor->getSourceRemoteStorageProfileId()); if (!$fileSync) { kBatchManager::updateEntry($flavorAsset->getEntryId(), entryStatus::ERROR_CONVERTING); $description = "Remote source file sync not found {$srcSyncKey}, storage profile id [" . $flavor->getSourceRemoteStorageProfileId() . "]"; KalturaLog::err($description); $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR); $flavorAsset->setDescription($description); $flavorAsset->save(); return null; } $localPath = $fileSync->getFilePath(); $remoteUrl = $fileSync->getExternalUrl($flavorAsset->getEntryId()); } $wamsAssetId = $fileSync->getWamsAssetId(); // creates convert data $convertData = new kConvertJobData(); $convertData->setSrcFileSyncLocalPath($localPath); $convertData->setSrcFileSyncRemoteUrl($remoteUrl); $convertData->setMediaInfoId($mediaInfoId); $convertData->setFlavorParamsOutputId($flavor->getId()); $convertData->setFlavorAssetId($flavorAssetId); $convertData->setSrcFileSyncWamsAssetId($wamsAssetId); KalturaLog::log("Conversion engines string: '" . $flavor->getConversionEngines() . "'"); $currentConversionEngine = null; // TODO remove after all old version flavors migrated // parse supported engine types $conversionEngines = array(); if (!$flavor->getEngineVersion()) { $conversionEngines = explode(',', $flavor->getConversionEngines()); KalturaLog::log(count($conversionEngines) . " conversion engines found for the flavor"); $currentConversionEngine = reset($conversionEngines); // gets the first engine type } // remove until here if (is_null($lastEngineType)) { KalturaLog::log("Last Engine Type is null, engine version [" . $flavor->getEngineVersion() . "]"); if ($flavor->getEngineVersion()) { $operatorSet = new kOperatorSets(); $operatorSet->setSerialized($flavor->getOperators()); $nextOperator = $operatorSet->getOperator(); if (!$nextOperator) { KalturaLog::err("First operator is invalid"); return null; } KalturaLog::log("Set first operator in first set"); $currentConversionEngine = $nextOperator->id; } } else { if ($parentJob && $flavor->getEngineVersion() && ($parentJob->getJobType() == BatchJobType::CONVERT || $parentJob->getJobType() == BatchJobType::POSTCONVERT)) { // using next oprator KalturaLog::log("Adding next conversion operator"); $parentData = $parentJob->getData(); if (!$parentData || !$parentData instanceof kConvartableJobData) { KalturaLog::err("Parent job data is invalid"); return null; } $operatorSet = new kOperatorSets(); $operatorSet->setSerialized($flavor->getOperators()); $nextOperatorSet = $parentData->getCurrentOperationSet(); $nextOperatorIndex = $parentData->getCurrentOperationIndex() + 1; $nextOperator = $operatorSet->getOperator($nextOperatorSet, $nextOperatorIndex); if (!$nextOperator) { KalturaLog::err("Next operator is invalid"); return null; } KalturaLog::log("Moving to next operator [{$nextOperatorIndex}] in set [{$nextOperatorSet}]"); $convertData->setCurrentOperationSet($nextOperatorSet); $convertData->setCurrentOperationIndex($nextOperatorIndex); $currentConversionEngine = $nextOperator->id; } else { // TODO remove after all old version flavors migrated KalturaLog::log("Last used conversion engine is [{$lastEngineType}]"); // searching for $lastEngineType in the list while ($lastEngineType != $currentConversionEngine && next($conversionEngines)) { $currentConversionEngine = current($conversionEngines); } // takes the next engine $currentConversionEngine = next($conversionEngines); if (!$currentConversionEngine) { KalturaLog::err("There is no other conversion engine to use"); return null; } } } if (!is_null($fileSync->getWamsAssetId())) { $currentConversionEngine = conversionEngineType::WAMS; } KalturaLog::log("Using conversion engine [{$currentConversionEngine}]"); // creats a child convert job if (is_null($dbConvertFlavorJob)) { if ($parentJob) { $dbConvertFlavorJob = $parentJob->createChild(); KalturaLog::log("Created from parent convert job with entry id [" . $dbConvertFlavorJob->getEntryId() . "]"); } else { $dbConvertFlavorJob = new BatchJob(); $dbConvertFlavorJob->setEntryId($flavor->getEntryId()); $dbConvertFlavorJob->setPartnerId($flavor->getPartnerId()); $dbConvertFlavorJob->save(); KalturaLog::log("Created from flavor convert job with entry id [" . $dbConvertFlavorJob->getEntryId() . "]"); } } if (!is_null($fileSync->getWamsAssetId())) { $srcFileSize = kWAMS::getInstance($flavor->getPartnerId())->getFileSizeForAssetId($fileSync->getWamsAssetId()); } else { $srcFileSize = kFile::fileSize($convertData->getSrcFileSyncLocalPath()); } $dbConvertFlavorJob->setFileSize($srcFileSize); // TODO remove after all old version flavors migrated if (in_array(conversionEngineType::ENCODING_COM, $conversionEngines)) { $dbConvertFlavorJob->setOnStressDivertTo(conversionEngineType::ENCODING_COM); } // remove until here /* // Remarked by Dor until Tantan's return. // Code is supposed to get a configuration file from the engine and attach it to the batch job. // Was added for document conversion and is not used for now because of a bug of PDFCreator. KalturaLog::log("Calling CDLProceessFlavor with flavor params output[" . $flavor->getId() . "]"); $config = KDLWrap::CDLProceessFlavor($flavor); if($config) { $syncKey = $dbConvertFlavorJob->getSyncKey(BatchJob::FILE_SYNC_BATCHJOB_SUB_TYPE_CONFIG); kFileSyncUtils::file_put_contents($syncKey, $config); $fileSync = kFileSyncUtils::getLocalFileSyncForKey($syncKey); $remoteUrl = $fileSync->getExternalUrl($flavor->getEntryId()); $localPath = kFileSyncUtils::getLocalFilePathForKey($syncKey); $convertData->setConfigLocalPath($localPath); $convertData->setConfigRemoteUrl($remoteUrl); } */ $dbCurrentConversionEngine = kPluginableEnumsManager::apiToCore('conversionEngineType', $currentConversionEngine); return kJobsManager::addJob($dbConvertFlavorJob, $convertData, BatchJobType::CONVERT, $dbCurrentConversionEngine); }
/** * Set a given flavor as the original flavor * * @action setAsSource * @param string $assetId * @validateUser entry entryId edit * @throws KalturaErrors::ASSET_ID_NOT_FOUND */ public function setAsSourceAction($assetId) { // Retrieve required $asset = assetPeer::retrieveById($assetId); if (is_null($asset)) { throw new KalturaAPIException(KalturaErrors::ASSET_ID_NOT_FOUND, $assetId); } if ($asset->getIsOriginal()) { return; } // Retrieve original $originalAsset = assetPeer::retrieveOriginalByEntryId($asset->getEntryId()); if (!is_null($originalAsset)) { // Set original to non-original $originalAsset->setIsOriginal(false); $originalAsset->save(); } // Set required as original $asset->setIsOriginal(true); $asset->save(); }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { requestUtils::handleConditionalGet(); $wams_asset_id = NULL; $wams_url = NULL; $entry_id = $this->getRequestParameter("entry_id"); $type = $this->getRequestParameter("type"); $ks = $this->getRequestParameter("ks"); $file_sync = null; $ret_file_name = "name"; $referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($referrer); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ""; } $request_file_name = $this->getRequestParameter("file_name"); if ($request_file_name) { $ret_file_name = $request_file_name; } $direct_serve = $this->getRequestParameter("direct_serve"); $entry = null; if ($ks) { try { kCurrentContext::initKsPartnerUser($ks); } catch (Exception $ex) { KExternalErrors::dieError(KExternalErrors::INVALID_KS); } } else { $entry = kCurrentContext::initPartnerByEntryId($entry_id); if (!$entry) { die; } } kEntitlementUtils::initEntitlementEnforcement(); if (!$entry) { $entry = entryPeer::retrieveByPK($entry_id); if (!$entry) { die; } } else { if (!kEntitlementUtils::isEntryEntitled($entry)) { die; } } myPartnerUtils::blockInactivePartner($entry->getPartnerId()); $securyEntryHelper = new KSecureEntryHelper($entry, $ks, $referrer, accessControlContextType::DOWNLOAD); $securyEntryHelper->validateForDownload(); // Rmoved by Tan-Tan - asked by Eran // // allow access only via cdn unless these are documents (due to the current implementation of convert ppt2swf) // if ($entry->getType() != entryType::DOCUMENT && $entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_IMAGE) // { // requestUtils::enforceCdnDelivery($entry->getPartnerId()); // } // relocate = did we use the redirect and added the extension to the name $relocate = $this->getRequestParameter("relocate"); if ($ret_file_name == "name") { $ret_file_name = $entry->getName(); } if ($ret_file_name) { //rawurlencode to content-disposition filename to handle spaces and other characters across different browsers //$name = rawurlencode($ret_file_name); // 19.04.2009 (Roman) - url encode is not needed when the filename in Content-Disposition header is in quotes // IE6/FF3/Chrome - Will show the filename correctly // IE7 - Will show the filename with underscores instead of spaces (this is better than showing %20) $name = $ret_file_name; if ($name) { if ($relocate) { // if we have a good file extension (from the first time) - use it in the content-disposition // in some browsers it will be stronger than the URL's extension $file_ext = pathinfo($relocate, PATHINFO_EXTENSION); $name .= ".{$file_ext}"; } if (!$direct_serve) { header("Content-Disposition: attachment; filename=\"{$name}\""); } } } else { $ret_file_name = $entry_id; } $format = $this->getRequestParameter("format"); if ($type == "download" && $format && $entry->getType() != entryType::DOCUMENT) { // this is a video for a specifc extension - use the proper flavorAsset $flavor_asset = assetPeer::retrieveByEntryIdAndExtension($entry_id, $format); if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) { $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true); } else { header('KalturaRaw: no flavor asset for extension'); header("HTTP/1.0 404 Not Found"); die; } $archive_file = $file_sync->getFullPath(); $mime_type = kFile::mimeType($archive_file); kFile::dumpFile($archive_file, $mime_type); } // TODO - move to a different action - document should be plugin if ($entry->getType() == entryType::DOCUMENT) { // use the fileSync from the entry if ($type == "download" && $format) { $flavor_asset = assetPeer::retrieveByEntryIdAndExtension($entry_id, $format); } else { $flavor_asset = assetPeer::retrieveOriginalByEntryId($entry_id); } if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) { $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true); } else { header('KalturaRaw: no flavor asset for extension'); header("HTTP/1.0 404 Not Found"); die; } // Gonen 2010-08-05 workaround to make sure file name includes correct extension // make sure a file extension is added to the downloaded file so browser will identify and // allow opening with default program // for direct serve we do not want to send content-disposition header if (!$direct_serve) { $ext = pathinfo($file_sync->getFullPath(), PATHINFO_EXTENSION); if ($relocate) { // remove relocate file extension $reloc_ext = pathinfo($relocate, PATHINFO_EXTENSION); $name = str_replace(".{$reloc_ext}", '', $name); } header("Content-Disposition: attachment; filename=\"{$name}.{$ext}\""); } kFile::dumpFile($file_sync->getFullPath()); } elseif ($entry->getType() == entryType::DATA) { $version = $this->getRequestParameter("version"); $syncKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version); list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if ($local) { $path = $fileSync->getFullPath(); } else { $path = kDataCenterMgr::getRedirectExternalUrl($fileSync); KalturaLog::info("Redirecting to [{$path}]"); } if (!$path) { header('KalturaRaw: no data was found available for download'); header("HTTP/1.0 404 Not Found"); } else { kFile::dumpFile($path); } } //$archive_file = $entry->getArchiveFile(); $media_type = $entry->getMediaType(); if ($media_type == entry::ENTRY_MEDIA_TYPE_IMAGE) { // image - use data for entry $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, null); $key = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); kFile::dumpFile(kFileSyncUtils::getLocalFilePathForKey($key, true)); } elseif ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO || $media_type == entry::ENTRY_MEDIA_TYPE_AUDIO) { $format = $this->getRequestParameter("format"); if ($type == "download" && $format) { // this is a video for a specifc extension - use the proper flavorAsset $flavor_asset = assetPeer::retrieveByEntryIdAndExtension($entry_id, $format); if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) { $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true); } else { header('KalturaRaw: no flavor asset for extension'); die; } $archive_file = $file_sync->getFullPath(); } else { // flavorAsset of the original $flavor_asset = assetPeer::retrieveOriginalByEntryId($entry_id); if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) { $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, false); // NOT strict - if there is no archive, get the data version if ($file_sync) { $wams_asset_id = $file_sync->getWamsAssetId(); $archive_file = $file_sync->getFullPath(); } } if (!$flavor_asset || !$file_sync || $flavor_asset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) { // either no archive asset or no fileSync for archive asset // use fallback flavorAsset $flavor_asset = assetPeer::retrieveBestPlayByEntryId($entry_id); if (!$flavor_asset) { header('KalturaRaw: no original flavor asset for entry, no best play asset for entry'); die; } $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, false); // NOT strict - if there is no archive, get the data version $archive_file = $file_sync->getFullPath(); } } } elseif ($media_type == entry::ENTRY_MEDIA_TYPE_SHOW) { // in this case "raw" is a bad name // TODO - add the ability to fetch the actual XML by flagging "xml" or something $version = $this->getRequestParameter("version"); // hotfix - links sent after flattening is done look like: // http://cdn.kaltura.com/p/387/sp/38700/raw/entry_id/0_ix99151g/version/100001 // while waiting for flavor-adaptation in flattening, we want to find at least one file to return. $try_formats = array('mp4', 'mov', 'avi', 'flv'); if ($format) { $key = array_search($format, $try_formats); if ($key !== FALSE) { unset($try_formats[$key]); } $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $format, false); } if (!isset($file_sync) || !$file_sync || !file_exists($file_sync->getFullPath())) { foreach ($try_formats as $ext) { KalturaLog::log("raw for mix - trying to find filesync for extension: [{$ext}] on entry [{$entry->getId()}]"); $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $ext, false); if ($file_sync && file_exists($file_sync->getFullPath())) { KalturaLog::log("raw for mix - found flattened video of extension: [{$ext}] continuing with this file {$file_sync->getFullPath()}"); break; } } if (!$file_sync || !file_exists($file_sync->getFullPath())) { $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $ext, true); } } // use fileSync for entry - roughcuts don't have flavors //$file_sync = $this->redirectIfRemote ( $entry , entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD , $version , true ); // strict - nothing to do if no flattened version // if got to here - fileSync was found for one of the extensions - continue with that file $archive_file = $file_sync->getFullPath(); } else { // no archive for this file header("HTTP/1.0 404 Not Found"); die; } // echo "[$archive_file][" . file_exists ( $archive_file ) . "]"; if (empty($wams_asset_id)) { $mime_type = kFile::mimeType($archive_file); } // echo "[[$mime_type]]"; $shouldProxy = $this->getRequestParameter("forceproxy", false); if ($shouldProxy || !empty($relocate)) { if (!empty($wams_asset_id)) { $fileExt = pathinfo($archive_file, PATHINFO_EXTENSION); kWAMS::getInstance($entry->getPartnerId())->dumpFile($wams_asset_id, $fileExt); die; } else { // dump the file kFile::dumpFile($archive_file, $mime_type); die; } } // use new Location to add the best extension we can find for the file $file_ext = pathinfo($archive_file, PATHINFO_EXTENSION); if ($file_ext != "flv") { // if the file does not end with "flv" - it is the real extension $ext = $file_ext; } else { // for now - if "flv" return "flv" - // TODO - find the real extension from the file itself $ext = "flv"; } // rebuild the URL and redirect to it with extraa parameters $url = $_SERVER["REQUEST_URI"]; $format = $this->getRequestParameter("format"); if (!$format) { $url = str_replace("format", "", $url); } if (!$ret_file_name) { // don't leave the name empty - if it is empty - use the entry id $ret_file_name = $entry_id; } $ret_file_name_safe = str_replace(' ', '-', $ret_file_name); // spaces replace with "-" $ret_file_name_safe = preg_replace('/[^a-zA-Z0-9-_]/', '', $ret_file_name_safe); // only "a-z", "A-Z", "0-9", "-" & "_" are left if (strpos($url, "?") > 0) { $url = str_replace("?", "/{$ret_file_name_safe}.{$ext}?", $url); $url .= "&relocate=f.{$ext}"; // add the ufname as a query parameter } else { $url .= "/{$ret_file_name_safe}.{$ext}?relocate=f.{$ext}"; // add the ufname as a query parameter } // or redirect if no proxy header("Location: {$url}"); die; }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { $entryId = $this->getRequestParameter("entry_id"); $flavorId = $this->getRequestParameter("flavor"); $fileName = $this->getRequestParameter("file_name"); $fileName = basename($fileName); $ksStr = $this->getRequestParameter("ks"); $referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($referrer); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ""; } $entry = null; if ($ksStr) { try { kCurrentContext::initKsPartnerUser($ksStr); } catch (Exception $ex) { KExternalErrors::dieError(KExternalErrors::INVALID_KS); } } else { $entry = kCurrentContext::initPartnerByEntryId($entryId); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } kEntitlementUtils::initEntitlementEnforcement(); if (!$entry) { $entry = entryPeer::retrieveByPK($entryId); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } else { if (!kEntitlementUtils::isEntryEntitled($entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } KalturaMonitorClient::initApiMonitor(false, 'extwidget.download', $entry->getPartnerId()); myPartnerUtils::blockInactivePartner($entry->getPartnerId()); $shouldPreview = false; $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, ContextType::DOWNLOAD); if ($securyEntryHelper->shouldPreview()) { $shouldPreview = true; } else { $securyEntryHelper->validateForDownload(); } $flavorAsset = null; if ($flavorId) { // get flavor asset $flavorAsset = assetPeer::retrieveById($flavorId); if (is_null($flavorAsset) || !$flavorAsset->isLocalReadyStatus()) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } // the request flavor should belong to the requested entry if ($flavorAsset->getEntryId() != $entryId) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } if (!$securyEntryHelper->isAssetAllowed($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } } else { $flavorAssets = assetPeer::retrieveReadyWebByEntryId($entry->getId()); foreach ($flavorAssets as $curFlavorAsset) { if ($securyEntryHelper->isAssetAllowed($curFlavorAsset)) { $flavorAsset = $curFlavorAsset; break; } } } // Gonen 26-04-2010: in case entry has no flavor with 'mbr' tag - we return the source if (!$flavorAsset && ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO)) { $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (!$securyEntryHelper->isAssetAllowed($flavorAsset)) { $flavorAsset = null; } } if ($flavorAsset) { $syncKey = $this->getSyncKeyAndForFlavorAsset($entry, $flavorAsset); } else { $syncKey = $this->getBestSyncKeyForEntry($entry); } if (is_null($syncKey)) { KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } $this->handleFileSyncRedirection($syncKey); $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); list($fileBaseName, $fileExt) = kAssetUtils::getFileName($entry, $flavorAsset); if (!$fileName) { $fileName = $fileBaseName; } if ($fileExt && !is_dir($filePath)) { $fileName = $fileName . '.' . $fileExt; } $preview = 0; if ($shouldPreview && $flavorAsset) { $preview = $flavorAsset->estimateFileSize($entry, $securyEntryHelper->getPreviewLength()); } else { if (kCurrentContext::$ks_object) { $preview = kCurrentContext::$ks_object->getPrivilegeValue(kSessionBase::PRIVILEGE_PREVIEW, 0); } } //enable downloading file_name which inside the flavor asset directory if (is_dir($filePath)) { $filePath = $filePath . DIRECTORY_SEPARATOR . $fileName; } $this->dumpFile($filePath, $fileName, $preview); KExternalErrors::dieGracefully(); // no view }
/** * Add and convert new Flavor Asset for Entry with specific Flavor Params * * @action convert * @param string $entryId * @param int $flavorParamsId * @validateUser entry entryId edit */ public function convertAction($entryId, $flavorParamsId) { $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } $flavorParamsDb = assetParamsPeer::retrieveByPK($flavorParamsId); assetParamsPeer::setUseCriteriaFilter(false); if (!$flavorParamsDb) { throw new KalturaAPIException(KalturaErrors::FLAVOR_PARAMS_ID_NOT_FOUND, $flavorParamsId); } $validStatuses = array(entryStatus::ERROR_CONVERTING, entryStatus::PRECONVERT, entryStatus::READY); if (!in_array($dbEntry->getStatus(), $validStatuses)) { throw new KalturaAPIException(KalturaErrors::INVALID_ENTRY_STATUS); } $conversionProfile = $dbEntry->getconversionProfile2(); if (!$conversionProfile) { throw new KalturaAPIException(KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND, $dbEntry->getConversionProfileId()); } $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (is_null($originalFlavorAsset) || !$originalFlavorAsset->isLocalReadyStatus()) { throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING); } $srcSyncKey = $originalFlavorAsset->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); /* @var $fileSync FileSync */ if (!$fileSync) { throw new KalturaAPIException(KalturaErrors::FILE_DOESNT_EXIST); } if (!$local && $fileSync->getFileType() != FileSync::FILE_SYNC_FILE_TYPE_URL) { kFile::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrl($fileSync)); } $err = ""; $dynamicFlavorAttributes = $dbEntry->getDynamicFlavorAttributesForAssetParams($flavorParamsDb->getId()); kBusinessPreConvertDL::decideAddEntryFlavor(null, $dbEntry->getId(), $flavorParamsId, $err, null, $dynamicFlavorAttributes); }
public static function checkForPendingLiveClips(entry $entry) { if ($entry->getSource() != EntrySourceType::RECORDED_LIVE) { KalturaLog::notice("Entry [" . $entry->getId() . "] is not a recorded live"); return; } $liveEntry = entryPeer::retrieveByPKNoFilter($entry->getRootEntryId()); if (!$liveEntry || $liveEntry->getStatus() == entryStatus::DELETED || !$liveEntry instanceof LiveEntry) { KalturaLog::notice("Entry root [" . $entry->getRootEntryId() . "] is not a valid live entry"); return; } /* @var $liveEntry LiveEntry */ $pendingMediaEntries = $liveEntry->getAttachedPendingMediaEntries(); foreach ($pendingMediaEntries as $pendingMediaEntry) { /* @var $pendingMediaEntry kPendingMediaEntry */ if ($pendingMediaEntry->getRequiredDuration() && $pendingMediaEntry->getRequiredDuration() > $entry->getLengthInMsecs()) { KalturaLog::info("Pending entry [" . $pendingMediaEntry->getEntryId() . "] required duration [" . $pendingMediaEntry->getRequiredDuration() . "] while entry duration [" . $entry->getLengthInMsecs() . "] is too short"); continue; } $liveEntry->dettachPendingMediaEntry($pendingMediaEntry->getEntryId()); $pendingEntry = entryPeer::retrieveByPK($pendingMediaEntry->getEntryId()); if (!$pendingEntry) { KalturaLog::info("Pending entry [" . $pendingMediaEntry->getEntryId() . "] not found"); continue; } $sourceAsset = assetPeer::retrieveOriginalByEntryId($entry->getId()); if (!$sourceAsset) { $sourceAssets = assetPeer::retrieveReadyFlavorsByEntryId($entry->getId()); $sourceAsset = array_pop($sourceAssets); } if (!$sourceAsset) { KalturaLog::info("Pending entry [" . $pendingMediaEntry->getEntryId() . "] source asset not found"); continue; } /* @var $sourceAsset flavorAsset */ $operationAttributes = new kClipAttributes(); $operationAttributes->setOffset($pendingMediaEntry->getOffset()); $operationAttributes->setDuration($pendingMediaEntry->getDuration()); $targetAsset = assetPeer::retrieveOriginalByEntryId($pendingMediaEntry->getEntryId()); if (!$targetAsset) { $targetAsset = kFlowHelper::createOriginalFlavorAsset($entry->getPartnerId(), $pendingMediaEntry->getEntryId()); } $targetAsset->setFileExt($sourceAsset->getFileExt()); $targetAsset->save(); $sourceSyncKey = $sourceAsset->getSyncKey(asset::FILE_SYNC_ASSET_SUB_TYPE_ASSET); $targetSyncKey = $targetAsset->getSyncKey(asset::FILE_SYNC_ASSET_SUB_TYPE_ASSET); kFileSyncUtils::createSyncFileLinkForKey($targetSyncKey, $sourceSyncKey); $errDescription = ''; kBusinessPreConvertDL::decideAddEntryFlavor(null, $pendingMediaEntry->getEntryId(), $operationAttributes->getAssetParamsId(), $errDescription, $targetAsset->getId(), array($operationAttributes)); } $liveEntry->save(); }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { $entryId = $this->getRequestParameter("entry_id"); $flavorId = $this->getRequestParameter("flavor"); $fileName = $this->getRequestParameter("file_name"); $fileName = basename($fileName); $ksStr = $this->getRequestParameter("ks"); $referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($referrer); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ""; } $entry = null; if ($ksStr) { try { kCurrentContext::initKsPartnerUser($ksStr); } catch (Exception $ex) { KExternalErrors::dieError(KExternalErrors::INVALID_KS); } } else { $entry = kCurrentContext::initPartnerByEntryId($entryId); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } kEntitlementUtils::initEntitlementEnforcement(); if (!$entry) { $entry = entryPeer::retrieveByPK($entryId); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } else { if (!kEntitlementUtils::isEntryEntitled($entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } myPartnerUtils::blockInactivePartner($entry->getPartnerId()); $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, accessControlContextType::DOWNLOAD); $securyEntryHelper->validateForDownload($entry, $ksStr); $flavorAsset = null; if ($flavorId) { // get flavor asset $flavorAsset = assetPeer::retrieveById($flavorId); if (is_null($flavorAsset) || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } // the request flavor should belong to the requested entry if ($flavorAsset->getEntryId() != $entryId) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } } else { $flavorAsset = assetPeer::retrieveBestPlayByEntryId($entry->getId()); } // Gonen 26-04-2010: in case entry has no flavor with 'mbr' tag - we return the source if (!$flavorAsset && ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO)) { $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); } if ($flavorAsset) { $syncKey = $this->getSyncKeyAndForFlavorAsset($entry, $flavorAsset); } else { $syncKey = $this->getBestSyncKeyForEntry($entry); } if (is_null($syncKey)) { KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } $this->handleFileSyncRedirection($syncKey); $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $wamsAssetId = kFileSyncUtils::getWamsAssetIdForKey($syncKey); $wamsURL = kFileSyncUtils::getWamsURLForKey($syncKey); list($fileBaseName, $fileExt) = $this->getFileName($entry, $flavorAsset); if (!$fileName) { $fileName = $fileBaseName; } if ($fileExt && !is_dir($filePath)) { $fileName = $fileName . '.' . $fileExt; } //enable downloading file_name which inside the flavor asset directory if (is_dir($filePath)) { $filePath = $filePath . DIRECTORY_SEPARATOR . $fileName; } $this->dumpFile($filePath, $fileName, $wamsAssetId, $wamsURL); die; // no view }
public static function decideProfileFlavorsConvert(BatchJob $parentJob, BatchJob $convertProfileJob, array $flavors, array $conversionProfileFlavorParams, $conversionProfileId, mediaInfo $mediaInfo = null) { $entryId = $convertProfileJob->getEntryId(); $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (is_null($originalFlavorAsset)) { $errDescription = 'Original flavor asset not found'; self::setError($errDescription, $convertProfileJob, BatchJobType::CONVERT_PROFILE, $convertProfileJob->getEntryId()); return false; } $errDescription = null; try { $finalFlavors = self::validateConversionProfile($convertProfileJob->getPartnerId(), $entryId, $mediaInfo, $flavors, $conversionProfileFlavorParams, $errDescription); } catch (Exception $e) { $code = $e->getCode(); if ($code == KDLErrors::SanityInvalidFrameDim || $code == KDLErrors::NoValidMediaStream) { $convertProfileJob = kJobsManager::failBatchJob($convertProfileJob, $errDescription); KalturaLog::err($e->getMessage()); throw $e; } } KalturaLog::log(count($finalFlavors) . " flavors returned from the decision layer"); if (is_null($finalFlavors)) { $convertProfileJob = kJobsManager::failBatchJob($convertProfileJob, $errDescription); KalturaLog::log("No flavors created"); //throw new Exception($errDescription); no need to throw alert if the root job failed } if (strlen($errDescription)) { $err = $convertProfileJob->getDescription() . $errDescription; $convertProfileJob->setDescription($err); $convertProfileJob->save(); //Check if the error thrown is invalid file - no media content if (strpos($errDescription, KDLErrors::ToString(KDLErrors::NoValidMediaStream)) !== false) { throw new Exception(KDLErrors::ToString(KDLErrors::NoValidMediaStream), KDLErrors::NoValidMediaStream); } } $conversionsCreated = 0; $waitingAssets = 0; $entry = $convertProfileJob->getEntry(); if (!$entry) { throw new APIException(APIErrors::INVALID_ENTRY, $convertProfileJob, $entryId); } $flavorsCollections = array(); // create a convert job per each flavor foreach ($finalFlavors as $flavor) { $flavorAsset = kBatchManager::createFlavorAsset($flavor, $entry->getPartnerId(), $entry->getId()); if (!$flavorAsset) { continue; } $collectionTag = $flavor->getCollectionTag(); /* * CHANGE: collection porcessing only for ExpressionEncoder jobs * to allow FFmpeg/ISMV processing */ KalturaLog::log("Check for collection case - engines(" . $flavor->getConversionEngines() . ")"); if ($collectionTag && $flavor->getConversionEngines() == conversionEngineType::EXPRESSION_ENCODER3) { $flavorsCollections[$collectionTag][] = $flavor; } else { KalturaLog::log("Adding flavor conversion with flavor params output id [" . $flavor->getId() . "] and flavor params asset id [" . $flavorAsset->getId() . "]"); $madiaInfoId = $mediaInfo ? $mediaInfo->getId() : null; $createdJob = self::decideFlavorConvert($flavorAsset, $flavor, $originalFlavorAsset, $conversionProfileId, $madiaInfoId, $parentJob); if ($createdJob) { $conversionsCreated++; } if ($flavorAsset->getStatus() == flavorAsset::ASSET_STATUS_WAIT_FOR_CONVERT) { $waitingAssets++; } } } foreach ($flavorsCollections as $tag => $flavors) { $createdJob = self::decideCollectionConvert($tag, $originalFlavorAsset, $entry, $parentJob, $flavors); if ($createdJob) { $conversionsCreated++; } } if (!$conversionsCreated && !$waitingAssets) { KalturaLog::log("No flavors created: {$errDescription}"); $convertProfileJob = kJobsManager::failBatchJob($convertProfileJob, $errDescription); return false; } return true; }
/** * batch addConvertProfileJobAction creates a new convert profile job * * @action addConvertProfileJob * @param string $entryId the id of the entry to be reconverted * @return KalturaBatchJobResponse */ function addConvertProfileJobAction($entryId) { $entry = entryPeer::retrieveByPK($entryId); if (!$entry) { throw new KalturaAPIException(APIErrors::INVALID_ENTRY_ID, 'entry', $entryId); } $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (!kFileSyncUtils::file_exists($syncKey, true)) { throw new KalturaAPIException(APIErrors::NO_FILES_RECEIVED); } $inputFileSyncLocalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey); $wamsAssetId = kFileSyncUtils::getWamsAssetIdForKey($syncKey); $batchJob = kJobsManager::addConvertProfileJob(null, $entry, $flavorAsset->getId(), $inputFileSyncLocalPath, $wamsAssetId); return $this->getStatusAction($batchJob->getId(), KalturaBatchJobType::CONVERT_PROFILE); }
private static function deleteTemporaryFlavors($entryId) { $originalflavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if ($originalflavorAsset && $originalflavorAsset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_TEMP) { $originalflavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_DELETED); $originalflavorAsset->setDeletedAt(time()); $originalflavorAsset->save(); } $conversionProfile = myPartnerUtils::getConversionProfile2ForEntry($entryId); if (!$conversionProfile) { return; } $criteria = new Criteria(); $criteria->add(flavorParamsConversionProfilePeer::CONVERSION_PROFILE_ID, $conversionProfile->getId()); $criteria->add(flavorParamsConversionProfilePeer::DELETE_POLICY, AssetParamsDeletePolicy::DELETE); $tempFlavorsParams = flavorParamsConversionProfilePeer::doSelect($criteria); foreach ($tempFlavorsParams as $tempFlavorsParam) { $tempFlavorAsset = assetPeer::retrieveByEntryIdAndParams($entryId, $tempFlavorsParam->getFlavorParamsId()); if ($tempFlavorAsset) { $tempFlavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_DELETED); $tempFlavorAsset->setDeletedAt(time()); $tempFlavorAsset->save(); } } }
public function entryHandled(entry $dbEntry) { $srcEntry = entryPeer::retrieveByPK($this->entryId); if ($srcEntry->getType() == KalturaEntryType::MEDIA_CLIP && $dbEntry->getType() == KalturaEntryType::MEDIA_CLIP && $dbEntry->getMediaType() == KalturaMediaType::IMAGE) { if ($dbEntry->getMediaType() == KalturaMediaType::IMAGE) { $dbEntry->setDimensions($srcEntry->getWidth(), $srcEntry->getHeight()); $dbEntry->setMediaDate($srcEntry->getMediaDate(null)); $dbEntry->save(); } else { $srcFlavorAsset = null; if (is_null($this->flavorParamsId)) { $srcFlavorAsset = assetPeer::retrieveOriginalByEntryId($this->entryId); } else { $srcFlavorAsset = assetPeer::retrieveByEntryIdAndParams($this->entryId, $this->flavorParamsId); } if ($srcFlavorAsset) { $dbEntry->setDimensions($srcFlavorAsset->getWidth(), $srcFlavorAsset->getHeight()); $dbEntry->save(); } } } return parent::entryHandled($dbEntry); }
/** * Copy entry into new entry * * @action addFromEntry * @param string $sourceEntryId Media entry id to copy from * @param KalturaMediaEntry $mediaEntry Media entry metadata * @param int $sourceFlavorParamsId The flavor to be used as the new entry source, source flavor will be used if not specified * @return KalturaMediaEntry The new media entry * @throws KalturaErrors::ENTRY_ID_NOT_FOUND * @throws KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING * @throws KalturaErrors::FLAVOR_PARAMS_NOT_FOUND * @throws KalturaErrors::ORIGINAL_FLAVOR_ASSET_NOT_CREATED * * @deprecated use media.add instead */ function addFromEntryAction($sourceEntryId, KalturaMediaEntry $mediaEntry = null, $sourceFlavorParamsId = null) { if ($mediaEntry->conversionQuality && !$mediaEntry->conversionProfileId) { $mediaEntry->conversionProfileId = $mediaEntry->conversionQuality; } $srcEntry = entryPeer::retrieveByPK($sourceEntryId); if (!$srcEntry || $srcEntry->getType() != entryType::MEDIA_CLIP) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $sourceEntryId); } $srcFlavorAsset = null; if (is_null($sourceFlavorParamsId)) { $srcFlavorAsset = assetPeer::retrieveOriginalByEntryId($sourceEntryId); if (!$srcFlavorAsset) { throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING); } } else { $srcFlavorAssets = assetPeer::retrieveReadyByEntryIdAndFlavorParams($sourceEntryId, array($sourceFlavorParamsId)); if (count($srcFlavorAssets)) { $srcFlavorAsset = reset($srcFlavorAssets); } else { throw new KalturaAPIException(KalturaErrors::FLAVOR_PARAMS_NOT_FOUND); } } if ($mediaEntry === null) { $mediaEntry = new KalturaMediaEntry(); } $mediaEntry->mediaType = $srcEntry->getMediaType(); return $this->addEntryFromFlavorAsset($mediaEntry, $srcEntry, $srcFlavorAsset); }
/** * 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) }
public static function decideProfileFlavorsConvert(BatchJob $parentJob, BatchJob $convertProfileJob, array $flavors, array $conversionProfileFlavorParams, mediaInfo $mediaInfo = null) { $entryId = $convertProfileJob->getEntryId(); $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (is_null($originalFlavorAsset)) { $errDescription = 'Original flavor asset not found'; KalturaLog::err($errDescription); $convertProfileJob = kJobsManager::failBatchJob($convertProfileJob, $errDescription, BatchJobType::CONVERT_PROFILE); kBatchManager::updateEntry($convertProfileJob->getEntryId(), entryStatus::ERROR_CONVERTING); return false; } $errDescription = null; $finalFlavors = self::validateConversionProfile($convertProfileJob->getPartnerId(), $entryId, $mediaInfo, $flavors, $conversionProfileFlavorParams, $errDescription); KalturaLog::log(count($finalFlavors) . " flavors returned from the decision layer"); if (is_null($finalFlavors)) { $convertProfileJob = kJobsManager::failBatchJob($convertProfileJob, $errDescription); KalturaLog::log("No flavors created"); //throw new Exception($errDescription); no need to throw alert if the root job failed } if (strlen($errDescription)) { $err = $convertProfileJob->getDescription() . $errDescription; $convertProfileJob->setDescription($err); $convertProfileJob->save(); } $srcSyncKey = $originalFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); $conversionsCreated = 0; $entry = $convertProfileJob->getEntry(); if (!$entry) { throw new APIException(APIErrors::INVALID_ENTRY, $convertProfileJob, $entryId); } $flavorsCollections = array(); // create a convert job per each flavor foreach ($finalFlavors as $flavor) { $flavorAsset = kBatchManager::createFlavorAsset($flavor, $entry->getPartnerId(), $entry->getId()); if (!$flavorAsset) { KalturaLog::log("Flavor asset could not be created, flavor conversion won't be created"); continue; } $collectionTag = $flavor->getCollectionTag(); if ($collectionTag) { $flavorsCollections[$collectionTag][] = $flavor; continue; } KalturaLog::log("Adding flavor conversion with flavor params output id [" . $flavor->getId() . "] and flavor params asset id [" . $flavorAsset->getId() . "]"); $madiaInfoId = $mediaInfo ? $mediaInfo->getId() : null; $createdJob = kJobsManager::addFlavorConvertJob($srcSyncKey, $flavor, $flavorAsset->getId(), $madiaInfoId, $parentJob); if ($createdJob) { $conversionsCreated++; } } foreach ($flavorsCollections as $tag => $flavors) { switch ($tag) { case flavorParams::TAG_ISM: $createdJob = kJobsManager::addConvertIsmCollectionJob($tag, $srcSyncKey, $entry, $parentJob, $flavors); if ($createdJob) { $conversionsCreated++; } break; default: KalturaLog::log("Error: Invalid collection tag [{$tag}]"); break; } } if (!$conversionsCreated) { $convertProfileJob = kJobsManager::failBatchJob($convertProfileJob, $errDescription); KalturaLog::log("No flavors created: {$errDescription}"); return false; } return true; }
/** * Serves the file content * * @action serveByFlavorParamsId * @param string $entryId Document entry id * @param string $flavorParamsId Flavor params id * @param bool $forceProxy force to get the content without redirect * @return file * * @throws KalturaErrors::ENTRY_ID_NOT_FOUND * @throws KalturaErrors::FLAVOR_ASSET_IS_NOT_READY * @throws KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND */ public function serveByFlavorParamsIdAction($entryId, $flavorParamsId = null, $forceProxy = false) { // temporary workaround for getting the referrer from a url with the format ....&forceProxy/true/referrer/... $referrer = null; if (isset($_GET["forceProxy"]) && kString::beginsWith($_GET["forceProxy"], "true/referrer/")) { $referrer = substr($_GET["forceProxy"], strlen("true/referrer/")); $referrer = base64_decode($referrer); } KalturaResponseCacher::disableCache(); myPartnerUtils::resetPartnerFilter('entry'); $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry || $dbEntry->getType() != entryType::DOCUMENT) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } $ksObj = $this->getKs(); $ks = $ksObj ? $ksObj->getOriginalString() : null; $securyEntryHelper = new KSecureEntryHelper($dbEntry, $ks, $referrer, ContextType::DOWNLOAD); $securyEntryHelper->validateForDownload(); $flavorAsset = null; if ($flavorParamsId) { $flavorAsset = assetPeer::retrieveByEntryIdAndParams($entryId, $flavorParamsId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_IS_NOT_READY, $flavorParamsId); } } else { $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $flavorParamsId); } } if (!$securyEntryHelper->isAssetAllowed($flavorAsset)) { throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_ID_NOT_FOUND, $flavorParamsId); } $fileName = $dbEntry->getName() . '.' . $flavorAsset->getFileExt(); return $this->serveFlavorAsset($flavorAsset, $fileName, $forceProxy); }
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); } }
public static function handleFlavorReady(BatchJob $dbBatchJob, $flavorAssetId) { // verifies that flavor asset created if (!$flavorAssetId) { throw new APIException(APIErrors::INVALID_FLAVOR_ASSET_ID, $flavorAssetId); } $currentFlavorAsset = assetPeer::retrieveById($flavorAssetId); // verifies that flavor asset exists if (!$currentFlavorAsset) { throw new APIException(APIErrors::INVALID_FLAVOR_ASSET_ID, $flavorAssetId); } // if the flavor deleted then it shouldn't be taken into ready calculations if ($currentFlavorAsset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_DELETED) { return $currentFlavorAsset; } // Remarked because we want the original flavor ready behavior to work the same as other flavors // // $rootBatchJob = $dbBatchJob->getRootJob(); // // // happens in case of post convert on the original (in case of bypass) // if($rootBatchJob && $currentFlavorAsset->getIsOriginal()) // { // kJobsManager::updateBatchJob($rootBatchJob, BatchJob::BATCHJOB_STATUS_FINISHED); // return $dbBatchJob; // } $sourceMediaInfo = mediaInfoPeer::retrieveOriginalByEntryId($dbBatchJob->getEntryId()); /* * For intermediate source generation, both the source and the asset have the same asset id. * In this case sourceMediaInfo should be retrieved as the first version of source asset mediaInfo */ if (isset($sourceMediaInfo) && $sourceMediaInfo->getFlavorAssetId() == $flavorAssetId) { $productMediaInfo = $sourceMediaInfo; $entry = $dbBatchJob->getEntry(); $operationAttributes = $entry->getOperationAttributes(); // if in clipping operation - take the latest created mediainfo object $ascending = empty($operationAttributes) ? 1 : 0; $sourceMediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAssetId, $ascending); KalturaLog::log("Intermediate source generation - assetId(" . $flavorAssetId . "),src MdInf id(" . $sourceMediaInfo->getId() . "),product MdInf id(" . $productMediaInfo->getId()) . ")"; } else { $productMediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($currentFlavorAsset->getId()); } $targetFlavor = assetParamsOutputPeer::retrieveByAssetId($currentFlavorAsset->getId()); //Retrieve convert job executing engien $convertEngineType = null; if ($dbBatchJob->getParentJob()) { $dbParentBatchJob = $dbBatchJob->getParentJob(); if ($dbParentBatchJob->getJobType() == BatchJobType::CONVERT) { $convertEngineType = $dbParentBatchJob->getJobSubType(); } } $postConvertData = $dbBatchJob->getData(); $postConvertAssetType = BatchJob::POSTCONVERT_ASSET_TYPE_FLAVOR; if ($postConvertData instanceof kPostConvertJobData) { $postConvertAssetType = $postConvertData->getPostConvertAssetType(); } // don't validate in case of bypass, in case target flavor or media info are null // or ISM/ISMC manifest assets if ($postConvertAssetType != BatchJob::POSTCONVERT_ASSET_TYPE_BYPASS && $targetFlavor && $productMediaInfo && !$targetFlavor->hasTag(assetParams::TAG_ISM_MANIFEST)) { try { $productFlavor = KDLWrap::CDLValidateProduct($sourceMediaInfo, $targetFlavor, $productMediaInfo, $convertEngineType); } catch (Exception $e) { KalturaLog::err('KDL Error: ' . print_r($e, true)); } $err = kBusinessConvertDL::parseFlavorDescription($productFlavor); KalturaLog::debug("BCDL: job id [" . $dbBatchJob->getId() . "] flavor params output id [" . $targetFlavor->getId() . "] flavor asset id [" . $currentFlavorAsset->getId() . "] desc: {$err}"); if (!$productFlavor->IsValid()) { $description = $currentFlavorAsset->getDescription() . "\n{$err}"; // mark the asset as ready $currentFlavorAsset->setDescription($description); $currentFlavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR); $currentFlavorAsset->save(); if (!kConf::get('ignore_cdl_failure')) { kJobsManager::failBatchJob($dbBatchJob, $err); return null; } } } // mark the asset as ready $currentFlavorAsset->setStatusLocalReady(); $currentFlavorAsset->save(); $waitingFlavorAssets = assetPeer::retrieveByEntryIdAndStatus($currentFlavorAsset->getEntryId(), flavorAsset::FLAVOR_ASSET_STATUS_WAIT_FOR_CONVERT); $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($currentFlavorAsset->getEntryId()); foreach ($waitingFlavorAssets as $waitingFlavorAsset) { $flavor = assetParamsOutputPeer::retrieveByAsset($waitingFlavorAsset); KalturaLog::debug('Check waiting flavor asset [' . $waitingFlavorAsset->getId() . ']'); if ($dbBatchJob->getParentJob()) { $parentJob = $dbBatchJob->getParentJob(); } else { $parentJob = $dbBatchJob; } kBusinessPreConvertDL::decideFlavorConvert($waitingFlavorAsset, $flavor, $originalFlavorAsset, null, null, $parentJob); } kFlowHelper::generateThumbnailsFromFlavor($dbBatchJob->getEntryId(), $dbBatchJob, $currentFlavorAsset->getFlavorParamsId()); if ($currentFlavorAsset->getIsOriginal()) { $entry = $currentFlavorAsset->getentry(); if ($entry) { kBusinessConvertDL::checkForPendingLiveClips($entry); } } return $currentFlavorAsset; }
/** * 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); } } } } }
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) { if (is_null($thumbParams) || !$thumbParams instanceof kThumbnailParameters) { $thumbParams = new kThumbnailParameters(); } $contentPath = myContentStorage::getFSContentRootPath(); $entry_status = $entry->getStatus(); $tempThumbName = $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) { $tempThumbName .= '_oip_' . basename($orig_image_path); } if ($density) { $tempThumbName .= "_dns_{$density}"; } if ($stripProfiles) { $tempThumbName .= "_stp_{$stripProfiles}"; } $entryThumbFilename = $entry->getThumbnail() ? $entry->getThumbnail() : "0.jpg"; if ($entry->getStatus() != entryStatus::READY || @$entryThumbFilename[0] == '&') { $tempThumbName .= "_NOCACHE_"; } // we remove the & from the template thumb otherwise getGeneralEntityPath will drop $tempThumbName from the final path $entryThumbFilename = str_replace("&", "", $entryThumbFilename); $basePath = myContentStorage::getGeneralEntityPath("entry/tempthumb", $entry->getIntId(), $tempThumbName, $entryThumbFilename, $version); $tempThumbPath = $contentPath . $basePath; if (file_exists($tempThumbPath) && @filesize($tempThumbPath)) { header("X-Kaltura:cached-thumb-exists," . md5($tempThumbPath)); return $tempThumbPath; } if ($orig_image_path === null || !file_exists($orig_image_path)) { $sub_type = $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE ? entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA : entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB; $orig_image_key = $entry->getSyncKey($sub_type, $version); $orig_image_path = kFileSyncUtils::getReadyLocalFilePathForKey($orig_image_key); } // 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)) { // 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 (is_null($flavorAsset) || !($flavorAsset->hasTag(flavorParams::TAG_MBR) || $flavorAsset->hasTag(flavorParams::TAG_WEB))) { // try the best playable $flavorAsset = assetPeer::retrieveHighestBitrateByEntryId($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)) { // 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); $entry_data_wams_asset_id = kFileSyncUtils::getWamsAssetIdForKey($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); } if (!empty($entry_data_wams_asset_id)) { $thumbMaker = new KWAMSThumbnailMaker($entry_data_wams_asset_id, $orig_image_path); if (!$thumbMaker->createThumbnail($calc_vid_sec, -1, -1)) { if (!$thumbMaker->createThumbnail(0, -1, -1)) { $kalturaPath = realpath(dirname(__FILE__) . '/../../../../'); copy($kalturaPath . '/res/broken_thumb.jpg', $orig_image_path); } } } else { myFileConverter::autoCaptureFrame($entry_data_path, $capturedThumbPath . "temp_", $calc_vid_sec, -1, -1); } $cache->remove($orig_image_path); } } // 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($tempThumbPath); if ($crop_provider) { $convertedImagePath = myFileConverter::convertImageUsingCropProvider($orig_image_path, $tempThumbPath, $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)) { KExternalErrors::dieError(KExternalErrors::IMAGE_RESIZE_FAILED); } $imageSizeArray = getimagesize($orig_image_path); if ($thumbParams->getSupportAnimatedThumbnail() && is_array($imageSizeArray) && $imageSizeArray[2] === IMAGETYPE_GIF) { $tempThumbPath = kFile::replaceExt($tempThumbPath, "gif"); } $convertedImagePath = myFileConverter::convertImage($orig_image_path, $tempThumbPath, $width, $height, $type, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h, $density, $stripProfiles, $thumbParams); } // 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($tempThumbPath); 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, $tempThumbPath); imagedestroy($im); } return $tempThumbPath; }