/** * Will forward to the regular swf player according to the widget_id */ public function execute() { $ui_conf_id = $this->getRequestParameter("ui_conf_id"); if (!is_numeric($ui_conf_id)) { throw new Exception("Illegal Input was supplied"); } $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_{$ui_conf_id}.swf"; if (!file_exists($preloader_path)) { $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_2.swf"; } kFileUtils::dumpFile($preloader_path); }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { // where file is {entryId/flavorId}.{ism,ismc,ismv} $objectId = $type = null; $objectIdStr = $this->getRequestParameter("objectId"); if ($objectIdStr) { list($objectId, $type) = @explode(".", $objectIdStr); } if (!$type || !$objectId) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER); } $ks = $this->getRequestParameter("ks"); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $syncKey = $this->getFileSyncKey($objectId, $type); KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveIsm', $this->entry->getPartnerId()); myPartnerUtils::enforceDelivery($this->entry, $this->flavorAsset); if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for type [{$type}] objectId [{$objectId}]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFileUtils::dumpUrl($remoteUrl); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); if ($type == 'ism') { $fileData = $this->fixIsmManifestForReplacedEntry($path); $renderer = new kRendererString($fileData, 'image/ism'); $renderer->output(); KExternalErrors::dieGracefully(); } else { kFileUtils::dumpFile($path); } }
public function execute() { //entitlement should be disabled to serveFlavor action as we do not get ks on this action. KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); requestUtils::handleConditionalGet(); $flavorId = $this->getRequestParameter("flavorId"); $shouldProxy = $this->getRequestParameter("forceproxy", false); $fileName = $this->getRequestParameter("fileName"); $fileParam = $this->getRequestParameter("file"); $fileParam = basename($fileParam); $pathOnly = $this->getRequestParameter("pathOnly", false); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $flavorAsset = assetPeer::retrieveById($flavorId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entryId = $this->getRequestParameter("entryId"); if (!is_null($entryId) && $flavorAsset->getEntryId() != $entryId) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } if ($fileName) { header("Content-Disposition: attachment; filename=\"{$fileName}\""); header("Content-Type: application/force-download"); header("Content-Description: File Transfer"); } $clipTo = null; $entry = $flavorAsset->getentry(); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFlavor', $flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($entry, $flavorAsset); $version = $this->getRequestParameter("v"); if (!$version) { $version = $flavorAsset->getVersion(); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version); if ($pathOnly && kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR'])) { $path = null; list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, false, false); if ($file_sync) { $parent_file_sync = kFileSyncUtils::resolve($file_sync); $path = $parent_file_sync->getFullPath(); if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; } } $renderer = new kRendererString('{"sequences":[{"clips":[{"type":"source","path":"' . $path . '"}]}]}', 'application/json'); if ($path) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } if (kConf::hasParam('serve_flavor_allowed_partners') && !in_array($flavorAsset->getPartnerId(), kConf::get('serve_flavor_allowed_partners'))) { KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED); } if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } // always dump remote urls so they will be cached by the cdn transparently $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFileUtils::dumpUrl($remoteUrl); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $isFlv = false; if (!$shouldProxy) { $flvWrapper = new myFlvHandler($path); $isFlv = $flvWrapper->isFlv(); } $clipFrom = $this->getRequestParameter("clipFrom", 0); // milliseconds if (is_null($clipTo)) { $clipTo = $this->getRequestParameter("clipTo", self::NO_CLIP_TO); } // milliseconds if ($clipTo == 0) { $clipTo = self::NO_CLIP_TO; } if (!is_numeric($clipTo) || $clipTo < 0) { KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'clipTo must be a positive number'); } $seekFrom = $this->getRequestParameter("seekFrom", -1); if ($seekFrom <= 0) { $seekFrom = -1; } $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1); if ($seekFromBytes <= 0) { $seekFromBytes = -1; } if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; kFileUtils::dumpFile($path, null, null); KExternalErrors::dieGracefully(); } else { if (!$isFlv || $clipTo == self::NO_CLIP_TO && $seekFrom < 0 && $seekFromBytes < 0) { $limit_file_size = 0; if ($clipTo != self::NO_CLIP_TO) { if (strtolower($flavorAsset->getFileExt()) == 'mp4' && PermissionPeer::isValidForPartner(PermissionName::FEATURE_ACCURATE_SERVE_CLIPPING, $flavorAsset->getPartnerId())) { $contentPath = myContentStorage::getFSContentRootPath(); $tempClipName = $version . '_' . $clipTo . '.mp4'; $tempClipPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempclip", $flavorAsset->getIntId(), $flavorAsset->getId(), $tempClipName); if (!file_exists($tempClipPath)) { kFile::fullMkdir($tempClipPath); $clipToSec = round($clipTo / 1000, 3); $cmdLine = kConf::get("bin_path_ffmpeg") . " -i {$path} -vcodec copy -acodec copy -f mp4 -t {$clipToSec} -y {$tempClipPath} 2>&1"; KalturaLog::log("Executing {$cmdLine}"); $output = array(); $return_value = ""; exec($cmdLine, $output, $return_value); KalturaLog::log("ffmpeg returned {$return_value}, output:" . implode("\n", $output)); } if (file_exists($tempClipPath)) { KalturaLog::log("Dumping {$tempClipPath}"); kFileUtils::dumpFile($tempClipPath); } else { KalturaLog::err('Failed to clip the file using ffmpeg, falling back to rough clipping'); } } $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId()); if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) { $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration()); $limit_file_size = floor(@kFile::fileSize($path) * ($clipTo / $duration) * 1.2); } } $renderer = kFileUtils::getDumpFileRenderer($path, null, null, $limit_file_size); if (!$fileName) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } } $audioOnly = $this->getRequestParameter("audioOnly"); // milliseconds if ($audioOnly === '0') { // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) { $audioOnly = true; } $bytes = 0; if ($seekFrom !== -1 && $seekFrom !== 0) { list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly); list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly); $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte; } else { list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); } $metadataSize = $flvWrapper->getMetadataSize($audioOnly); $dataOffset = $metadataSize + myFlvHandler::getHeaderSize(); $totalLength = $dataOffset + $bytes; list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength); if ($totalLength < 1000) { // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache requestUtils::sendCdnHeaders("flv", $rangeLength, 0); } else { requestUtils::sendCdnHeaders("flv", $rangeLength); } // dont inject cuepoint into the stream $cuepointTime = 0; $cuepointPos = 0; try { Propel::close(); } catch (Exception $e) { $this->logMessage("serveFlavor: error closing db {$e}"); } header("Content-Type: video/x-flv"); $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos); KExternalErrors::dieGracefully(); }
/** * 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::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']; 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; } 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"; } 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::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); 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 serveFileToRemoteDataCenter($file_sync, $file_hash, $file_name) { $file_sync_id = $file_sync->getId(); KalturaLog::log("File sync id [{$file_sync_id}], file_hash [{$file_hash}], file_name [{$file_name}]"); // TODO - verify security $current_dc = self::getCurrentDc(); $current_dc_id = $current_dc["id"]; if ($file_sync->getDc() != $current_dc_id) { $error = "DC[{$current_dc_id}]: FileSync with id [{$file_sync_id}] does not belong to this DC"; KalturaLog::err($error); KExternalErrors::dieError(KExternalErrors::BAD_QUERY); } // resolve if file_sync is link $file_sync_resolved = $file_sync; $file_sync_resolved = kFileSyncUtils::resolve($file_sync); // check if file sync path leads to a file or a directory $resolvedPath = $file_sync_resolved->getFullPath(); $fileSyncIsDir = is_dir($resolvedPath); if ($fileSyncIsDir && $file_name) { $resolvedPath .= '/' . $file_name; } if (!file_exists($resolvedPath)) { $file_name_msg = $file_name ? "file name [{$file_name}] " : ''; $error = "DC[{$current_dc_id}]: Path for fileSync id [{$file_sync_id}] " . $file_name_msg . "does not exist, resolved path [{$resolvedPath}]"; KalturaLog::err($error); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } // validate the hash $expected_file_hash = md5($current_dc["secret"] . $file_sync_id); // will be verified on the other side to make sure not some attack or external invalid request if ($file_hash != $expected_file_hash) { $error = "DC[{$current_dc_id}]: FileSync with id [{$file_sync_id}] - invalid hash"; KalturaLog::err($error); KExternalErrors::dieError(KExternalErrors::INVALID_TOKEN); } if ($fileSyncIsDir && is_dir($resolvedPath)) { KalturaLog::log("Serving directory content from [" . $resolvedPath . "]"); $contents = kFile::listDir($resolvedPath); sort($contents, SORT_STRING); $contents = serialize($contents); header("file-sync-type: dir"); echo $contents; KExternalErrors::dieGracefully(); } else { KalturaLog::log("Serving file from [" . $resolvedPath . "]"); kFileUtils::dumpFile($resolvedPath); } }
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; }
<?php require_once __DIR__ . "/../../bootstrap.php"; KalturaLog::setContext("CLIENTS"); KalturaLog::debug(__FILE__ . " start"); $requestedName = isset($_GET["name"]) ? $_GET['name'] : null; if (!$requestedName) { die("File not found"); } $generatorOutputPath = KAutoloader::buildPath(KALTURA_ROOT_PATH, "generator", "output"); $generatorConfigPath = KAutoloader::buildPath(KALTURA_ROOT_PATH, "generator", "config.ini"); $config = new Zend_Config_Ini($generatorConfigPath); foreach ($config as $name => $item) { if ($name === $requestedName && $item->get("public-download")) { $fileName = $name . ".tar.gz"; $outputFilePath = KAutoloader::buildPath($generatorOutputPath, $fileName); $outputFilePath = realpath($outputFilePath); header("Content-disposition: attachment; filename={$fileName}"); kFileUtils::dumpFile($outputFilePath, "application/gzip"); die; } } die("File not found"); KalturaLog::debug(__FILE__ . " end");
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { requestUtils::handleConditionalGet(); $entry_id = $this->getRequestParameter("entry_id"); $type = $this->getRequestParameter("type"); $ks = $this->getRequestParameter("ks"); $file_sync = null; $ret_file_name = "name"; $referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($referrer); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ""; } $request_file_name = $this->getRequestParameter("file_name"); if ($request_file_name) { $ret_file_name = $request_file_name; } $direct_serve = $this->getRequestParameter("direct_serve"); $entry = null; if ($ks) { try { kCurrentContext::initKsPartnerUser($ks); } catch (Exception $ex) { KExternalErrors::dieError(KExternalErrors::INVALID_KS); } } else { $entry = kCurrentContext::initPartnerByEntryId($entry_id); if (!$entry) { KExternalErrors::dieGracefully(); } } kEntitlementUtils::initEntitlementEnforcement(); if (!$entry) { $entry = entryPeer::retrieveByPK($entry_id); if (!$entry) { KExternalErrors::dieGracefully(); } } else { if (!kEntitlementUtils::isEntryEntitled($entry)) { KExternalErrors::dieGracefully(); } } KalturaMonitorClient::initApiMonitor(false, 'extwidget.raw', $entry->getPartnerId()); myPartnerUtils::blockInactivePartner($entry->getPartnerId()); $securyEntryHelper = new KSecureEntryHelper($entry, $ks, $referrer, ContextType::DOWNLOAD); $securyEntryHelper->validateForDownload(); // 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}"; } $name = kString::removeNewLine($name); if (!$direct_serve) { $entry_data = $entry->getData(); if (strpos($name, ".") === false && !is_null($entry_data)) { $file_ext = pathinfo($entry_data, PATHINFO_EXTENSION); $image_extensions = kConf::get('image_file_ext'); if ($file_ext && in_array($file_ext, $image_extensions)) { $name .= '.' . $file_ext; } } header("Content-Disposition: attachment; filename=\"{$name}\""); } } } else { $ret_file_name = $entry_id; $name = $ret_file_name; } $name = str_replace(array("\t", "\r", "\n"), array(' ', '', ' '), $name); $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 = $this->getAllowedFlavorAssets($securyEntryHelper, $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"); KExternalErrors::dieGracefully(); } $archive_file = $file_sync->getFullPath(); $mime_type = kFile::mimeType($archive_file); kFileUtils::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 = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, $format); } else { $flavor_asset = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, null, true); } 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"); KExternalErrors::dieGracefully(); } // 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); } $name = kString::removeNewLine($name . '.' . $ext); header("Content-Disposition: attachment; filename=\"{$name}\""); } kFileUtils::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); header("Location: {$path}"); KExternalErrors::dieGracefully(); } if (!$path) { header('KalturaRaw: no data was found available for download'); header("HTTP/1.0 404 Not Found"); } else { kFileUtils::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); kFileUtils::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 = $this->getAllowedFlavorAssets($securyEntryHelper, $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'); KExternalErrors::dieGracefully(); } $archive_file = $file_sync->getFullPath(); } else { // flavorAsset of the original $flavor_asset = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, null, true); if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) { $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, false); // NOT strict - if there is no archive, get the data version if ($file_sync) { $archive_file = $file_sync->getFullPath(); } } if (!$flavor_asset || !$file_sync || $flavor_asset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) { // either no archive asset or no fileSync for archive asset // use fallback flavorAsset $flavor_asset = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, null, false, true); if (!$flavor_asset) { header('KalturaRaw: no original flavor asset for entry, no best play asset for entry'); KExternalErrors::dieGracefully(); } $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) { header('KalturaRaw: no file sync found for flavor [' . $flavor_asset->getId() . ']'); KExternalErrors::dieGracefully(); } $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"); KExternalErrors::dieGracefully(); } // echo "[$archive_file][" . file_exists ( $archive_file ) . "]"; $mime_type = kFile::mimeType($archive_file); // echo "[[$mime_type]]"; $shouldProxy = $this->getRequestParameter("forceproxy", false); if ($shouldProxy || !empty($relocate)) { // dump the file kFileUtils::dumpFile($archive_file, $mime_type); KExternalErrors::dieGracefully(); } // 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}"); KExternalErrors::dieGracefully(); }
private function dumpFile($file_path, $file_name, $limit_file_size = 0) { $file_name = str_replace("\n", ' ', $file_name); $relocate = $this->getRequestParameter("relocate"); $directServe = $this->getRequestParameter("direct_serve"); if (!$relocate) { $url = $_SERVER["REQUEST_URI"]; if (strpos($url, "?") !== false) { $url .= "&relocate="; } else { $url .= "/relocate/"; } $url .= kString::stripInvalidUrlChars($file_name); kFile::cacheRedirect($url); header("Location: {$url}"); KExternalErrors::dieGracefully(); } else { if (!$directServe) { header("Content-Disposition: attachment; filename=\"{$file_name}\""); } $mime_type = kFile::mimeType($file_path); kFileUtils::dumpFile($file_path, $mime_type, null, $limit_file_size); } }