/** * Will forward to the regular swf player according to the widget_id */ public function execute() { $entryId = $this->getRequestParameter("entry_id"); $flavorId = $this->getRequestParameter("flavor"); $fileName = $this->getRequestParameter("file_name"); $ksStr = $this->getRequestParameter("ks"); $referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($referrer); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ""; } // get entry $entry = entryPeer::retrieveByPK($entryId); if (is_null($entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } myPartnerUtils::blockInactivePartner($entry->getPartnerId()); $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer); $securyEntryHelper->validateForDownload($entry, $ksStr); $flavorAsset = null; if ($flavorId) { // get flavor asset $flavorAsset = flavorAssetPeer::retrieveById($flavorId); if (is_null($flavorAsset) || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } // the request flavor should belong to the requested entry if ($flavorAsset->getEntryId() != $entryId) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } } else { $flavorAsset = flavorAssetPeer::retrieveBestPlayByEntryId($entry->getId()); } // Gonen 26-04-2010: in case entry has no flavor with 'mbr' tag - we return the source if (!$flavorAsset && ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO)) { $flavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entryId); } if ($flavorAsset) { $syncKey = $this->getSyncKeyAndForFlavorAsset($entry, $flavorAsset); } else { $syncKey = $this->getBestSyncKeyForEntry($entry); } list($fileBaseName, $fileExt) = $this->getFileName($entry, $flavorAsset); if (!$fileName) { $fileName = $fileBaseName; } if ($fileExt) { $fileName = $fileName . '.' . $fileExt; } if (is_null($syncKey)) { KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } $this->handleFileSyncRedirection($syncKey); $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $this->dumpFile($filePath, $fileName); die; // no view }
public function execute() { requestUtils::handleConditionalGet(); $flavorId = $this->getRequestParameter("flavorId"); $shouldProxy = $this->getRequestParameter("forceproxy", false); $ks = $this->getRequestParameter("ks"); $fileParam = $this->getRequestParameter("file"); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $flavorAsset = flavorAssetPeer::retrieveById($flavorId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entry = entryPeer::retrieveByPK($flavorAsset->getEntryId()); if (is_null($entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } myPartnerUtils::blockInactivePartner($flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($flavorAsset->getPartnerId()); //disabled enforce cdn because of rtmp delivery //requestUtils::enforceCdnDelivery($flavorAsset->getPartnerId()); $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } // always dump remote urls so they will be cached by the cdn transparently $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFile::dumpUrl($remoteUrl, true, true); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $flvWrapper = new myFlvHandler($path); $isFlv = $flvWrapper->isFlv(); $clipFrom = $this->getRequestParameter("clipFrom", 0); // milliseconds $clipTo = $this->getRequestParameter("clipTo", 2147483647); // milliseconds if ($clipTo == 0) { $clipTo = 2147483647; } if (is_dir($path) && $fileParam) { $path .= "/{$fileParam}"; //echo "path($path),file($fileParam)"; kFile::dumpFile($path, null, null); die; } else { if (!$isFlv) { $limit_file_size = 0; if ($clipTo != 2147483647) { $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId()); if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) { $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration()); $limit_file_size = floor(@filesize($path) * ($clipTo / $duration)); } } kFile::dumpFile($path, null, null, $limit_file_size); die; } } $audioOnly = $this->getRequestParameter("audioOnly"); // milliseconds if ($audioOnly === '0') { // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) { $audioOnly = true; } $seekFrom = $this->getRequestParameter("seekFrom", -1); if ($seekFrom <= 0) { $seekFrom = -1; } $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1); if ($seekFromBytes <= 0) { $seekFromBytes = -1; } $bytes = 0; if ($seekFrom !== -1 && $seekFrom !== 0) { list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly); list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly); $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte; } else { list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); } $metadataSize = $flvWrapper->getMetadataSize($audioOnly); $dataOffset = $metadataSize + myFlvHandler::getHeaderSize(); $totalLength = $dataOffset + $bytes; list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength); if ($totalLength < 1000) { // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache requestUtils::sendCdnHeaders("flv", $rangeLength, 0); } else { requestUtils::sendCdnHeaders("flv", $rangeLength); } header('Content-Disposition: attachment; filename="video.flv"'); // dont inject cuepoint into the stream $cuepointTime = 0; $cuepointPos = 0; try { Propel::close(); } catch (Exception $e) { $this->logMessage("serveFlavor: error closing db {$e}"); } header("Content-Type: video/x-flv"); $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos); die; }
/** * 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 }
protected function initEntry() { $this->entryId = $this->getRequestParameter("entryId", null); // look for a valid token $expiry = $this->getRequestParameter("expiry"); if ($expiry && $expiry <= time()) { KExternalErrors::dieError(KExternalErrors::EXPIRED_TOKEN); } $urlToken = $this->getRequestParameter("kt"); if ($urlToken) { if ($_SERVER["REQUEST_METHOD"] != "GET" || !self::validateKalturaToken($_SERVER["REQUEST_URI"], $urlToken)) { KExternalErrors::dieError(KExternalErrors::INVALID_TOKEN); } } // initalize the context $ksStr = $this->getRequestParameter("ks"); if ($ksStr && !$urlToken) { try { kCurrentContext::initKsPartnerUser($ksStr); } catch (Exception $ex) { KExternalErrors::dieError(KExternalErrors::INVALID_KS); } } else { $this->entry = kCurrentContext::initPartnerByEntryId($this->entryId); if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } // no need for any further check if a token was used if ($urlToken) { return; } // enforce entitlement kEntitlementUtils::initEntitlementEnforcement(); if (!$this->entry) { $this->entry = entryPeer::retrieveByPKNoFilter($this->entryId); if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } else { if (!kEntitlementUtils::isEntryEntitled($this->entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } myPartnerUtils::blockInactivePartner($this->entry->getPartnerId()); // enforce access control $base64Referrer = $this->getRequestParameter("referrer"); $hashes = $this->getRequestParameter("hashes"); $keyValueHashes = array(); if ($hashes) { $hashes = urldecode($hashes); $hashes = explode(",", $hashes); foreach ($hashes as $keyValueHashString) { list($key, $value) = explode('=', $keyValueHashString); $keyValueHashes[$key] = $value; } } // replace space in the base64 string with + as space is invalid in base64 strings and caused // by symfony calling str_parse to replace + with spaces. // this happens only with params passed in the url path and not the query strings. specifically the ~ char at // a columns divided by 3 causes this issue (e.g. http://www.xyzw.com/~xxx) //replace also any - with + and _ with / $referrer = base64_decode(str_replace(array('-', '_', ' '), array('+', '/', '+'), $base64Referrer)); if (!is_string($referrer)) { $referrer = ""; } // base64_decode can return binary data $this->secureEntryHelper = new KSecureEntryHelper($this->entry, $ksStr, $referrer, ContextType::PLAY, $keyValueHashes); if ($this->secureEntryHelper->shouldPreview()) { $previewLengthInMsecs = $this->secureEntryHelper->getPreviewLength() * 1000; $entryLengthInMsecs = $this->entry->getLengthInMsecs(); if ($previewLengthInMsecs < $entryLengthInMsecs) { $this->deliveryAttributes->setClipTo($previewLengthInMsecs); } } else { $this->secureEntryHelper->validateForPlay(); } if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENTITLEMENT, $this->entry->getPartnerId()) || $this->secureEntryHelper->hasRules()) { $this->forceUrlTokenization = true; } }
public function execute() { requestUtils::handleConditionalGet(); $entry_id = $this->getRequestParameter("entry_id"); $ks_str = $this->getRequestParameter("ks"); $base64_referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($base64_referrer); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ""; } $clip_from = $this->getRequestParameter("clip_from", 0); // milliseconds $clip_to = $this->getRequestParameter("clip_to", 2147483647); // milliseconds if ($clip_to == 0) { $clip_to = 2147483647; } $request = $_SERVER["REQUEST_URI"]; // remove dynamic fields from the url so we'll request a single url from the cdn $request = str_replace("/referrer/{$base64_referrer}", "", $request); $request = str_replace("/ks/{$ks_str}", "", $request); // workaround the filter which hides all the deleted entries - // now that deleted entries are part of xmls (they simply point to the 'deleted' templates), we should allow them here $entry = entryPeer::retrieveByPKNoFilter($entry_id); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } myPartnerUtils::blockInactivePartner($entry->getPartnerId()); // set the memory size to be able to serve big files in a single chunk ini_set("memory_limit", "64M"); // set the execution time to be able to serve big files in a single chunk ini_set("max_execution_time", 240); if ($entry->getType() == entryType::MIX && $entry->getStatus() == entryStatus::DELETED) { // because the fiter was turned off - a manual check for deleted entries must be done. die; } else { if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) { $version = $this->getRequestParameter("version", null); $width = $this->getRequestParameter("width", -1); $height = $this->getRequestParameter("height", -1); $crop_provider = $this->getRequestParameter("crop_provider", null); $bgcolor = $this->getRequestParameter("bgcolor", "ffffff"); $type = $this->getRequestParameter("type", 1); $quality = $this->getRequestParameter("quality", 0); $src_x = $this->getRequestParameter("src_x", 0); $src_y = $this->getRequestParameter("src_y", 0); $src_w = $this->getRequestParameter("src_w", 0); $src_h = $this->getRequestParameter("src_h", 0); $vid_sec = $this->getRequestParameter("vid_sec", -1); $vid_slice = $this->getRequestParameter("vid_slice", -1); $vid_slices = $this->getRequestParameter("vid_slices", -1); if ($width == -1 && $height == -1) { $width = 640; $height = 480; } else { if ($width == -1) { // if only either width or height is missing reset them to zero, and convertImage will handle them $width = 0; } else { if ($height == -1) { $height = 0; } } } $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices); kFile::dumpFile($tempThumbPath, null, strpos($tempThumbPath, "_NOCACHE_") === false ? null : 0); } } $audio_only = $this->getRequestParameter("audio_only"); // milliseconds $flavor = $this->getRequestParameter("flavor", 1); // $flavor_param_id = $this->getRequestParameter("flavor_param_id", null); // $streamer = $this->getRequestParameter("streamer"); // if (substr($streamer, 0, 4) == "rtmp") { // the fms may add .mp4 to the end of the url $streamer = "rtmp"; } // grab seek_from_bytes parameter and normalize url $seek_from_bytes = $this->getRequestParameter("seek_from_bytes", -1); $request = str_replace("/seek_from_bytes/{$seek_from_bytes}", "", $request); if ($seek_from_bytes <= 0) { $seek_from_bytes = -1; } // grab seek_from parameter and normalize url $seek_from = $this->getRequestParameter("seek_from", -1); $request = str_replace("/seek_from/{$seek_from}", "", $request); if ($seek_from <= 0) { $seek_from = -1; } $this->dump_from_byte = 0; // reset accurate seek from timestamp $seek_from_timestamp = -1; // backward compatibility if ($flavor === "0") { // for edit version $flavor = "edit"; } if ($flavor === "1" || $flavor === 1) { // for play version $flavor = null; } // when flavor is null, we will get a default flavor if ($flavor == "edit") { $flavorAsset = flavorAssetPeer::retrieveBestEditByEntryId($entry->getId()); } elseif (!is_null($flavor)) { $flavorAsset = flavorAssetPeer::retrieveById($flavor); // when specific asset was request, we don't validate its tags if ($flavorAsset && ($flavorAsset->getEntryId() != $entry->getId() || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY)) { $flavorAsset = null; } // we will throw an error later } elseif (is_null($flavor) && !is_null($flavor_param_id)) { $flavorAsset = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($entry->getId(), $flavor_param_id); if ($flavorAsset && $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) { $flavorAsset = null; } // we will throw an error later } else { if ($entry->getSource() == entry::ENTRY_MEDIA_SOURCE_WEBCAM) { $flavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entry->getId()); } else { $flavorAsset = flavorAssetPeer::retrieveBestPlayByEntryId($entry->getId()); } if (!$flavorAsset) { $flavorAssets = flavorAssetPeer::retreiveReadyByEntryIdAndTag($entry->getId(), flavorParams::TAG_WEB); if (count($flavorAssets) > 0) { $flavorAsset = $flavorAssets[0]; } } } if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (kFileSyncUtils::file_exists($syncKey, false)) { $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); } else { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); $this->redirect($remoteUrl); } $flv_wrapper = new myFlvHandler($path); $isFlv = $flv_wrapper->isFlv(); // scrubbing is not allowed within mp4 files if (!$isFlv) { $seek_from = $seek_from_bytes = -1; } if ($seek_from !== -1 && $seek_from !== 0) { if ($audio_only === '0') { // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) { $audio_only = true; } list($bytes, $duration, $first_tag_byte, $to_byte) = $flv_wrapper->clip(0, -1, $audio_only); list($bytes, $duration, $from_byte, $to_byte, $seek_from_timestamp) = $flv_wrapper->clip($seek_from, -1, $audio_only); $seek_from_bytes = myFlvHandler::FLV_HEADER_SIZE + $flv_wrapper->getMetadataSize($audio_only) + $from_byte - $first_tag_byte; } // the direct path without a cdn is "http://s3kaltura.s3.amazonaws.com".$entry->getDataPath(); $extStorageUrl = $entry->getExtStorageUrl(); if ($extStorageUrl && substr_count($extStorageUrl, 's3kaltura')) { // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from if ($seek_from_timestamp == -1) { $seek_from_timestamp = $seek_from; } $request_host = parse_url($extStorageUrl, PHP_URL_HOST); $akamai_url = str_replace($request_host, "cdns3akmi.kaltura.com", $extStorageUrl); $akamai_url .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000); header("Location: {$akamai_url}"); die; } elseif ($extStorageUrl) { // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from if ($seek_from_timestamp == -1) { $seek_from_timestamp = $seek_from; } $extStorageUrl .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000); header("Location: {$extStorageUrl}"); die; } // use headers to detect cdn $cdn_name = ""; $via_header = @$_SERVER["HTTP_VIA"]; if (strpos($via_header, "llnw.net") !== false) { $cdn_name = "limelight"; } else { if (strpos($via_header, "akamai") !== false) { $cdn_name = "akamai"; } else { if (strpos($via_header, "Level3") !== false) { $cdn_name = "level3"; } } } // setting file extension - first trying frrom flavor asset $ext = $flavorAsset->getFileExt(); // if failed, set extension according to file type (isFlv) if (!$ext) { $ext = $isFlv ? "flv" : "mp4"; } $flv_extension = $streamer == "rtmp" ? "?" : "/a.{$ext}?novar=0"; // dont check for rtmp / and for an already redirect url if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) { // check security using ks $securyEntryHelper = new KSecureEntryHelper($entry, $ks_str, $referrer); if ($securyEntryHelper->shouldPreview()) { $this->checkForPreview($securyEntryHelper, $clip_to); } else { $securyEntryHelper->validateForPlay($entry, $ks_str); } } else { // if needs security check using cdn authentication mechanism // for now assume this is a cdn request and don't check for security } // use limelight mediavault if either security policy requires it or if we're trying to seek within the video if ($entry->getSecurityPolicy() || $seek_from_bytes !== -1) { // we have three options: // arrived through limelight mediavault url - the url is secured // arrived directly through limelight (not secured through mediavault) - enforce ks and redirect to mediavault url // didnt use limelight - enforce ks // the cdns are configured to authenticate request for /s/.... // check if we're already in a redirected secure link using the "/s/" prefix $secure_request = substr($request, 0, 3) == "/s/"; if ($secure_request && ($cdn_name == "limelight" || $cdn_name == "level3")) { // request was validated by cdn let it through } else { // extract ks $ks_str = $this->getRequestParameter("ks", ""); if ($entry->getSecurityPolicy()) { if (!$ks_str) { $this->logMessage("flvclipper - no KS"); die; } $ks = kSessionUtils::crackKs($ks_str); if (!$ks) { $this->logMessage("flvclipper - invalid ks [{$ks_str}]"); die; } $matched_privs = $ks->verifyPrivileges("sview", $entry_id); $this->logMessage("flvclipper - verifyPrivileges name [sview], priv [{$entry_id}] [{$matched_privs}]"); if (!$matched_privs) { $this->logMessage("flvclipper - doesnt not match required privlieges [{$ks_str}]"); die; } } if ($cdn_name == "limelight") { $ll_url = requestUtils::getCdnHost() . "/s{$request}" . $flv_extension; $secret = kConf::get("limelight_madiavault_password"); $expire = "&e=" . (time() + 120); $ll_url .= $expire; $fs = $seek_from_bytes == -1 ? "" : "&fs={$seek_from_bytes}"; $ll_url .= "&h=" . md5("{$secret}{$ll_url}") . $fs; //header("Location: $ll_url"); $this->redirect($ll_url); } else { if ($cdn_name == "level3") { $level3_url = $request . $flv_extension; if ($entry->getSecurityPolicy()) { $level3_url = "/s{$level3_url}"; // set expire time in GMT hence the date("Z") offset $expire = "&nva=" . strftime("%Y%m%d%H%M%S", time() - date("Z") + 30); $level3_url .= $expire; $secret = kConf::get("level3_authentication_key"); $hash = "0" . substr(self::hmac('sha1', $secret, $level3_url), 0, 20); $level3_url .= "&h={$hash}"; } $level3_url .= $seek_from_bytes == -1 ? "" : "&start={$seek_from_bytes}"; header("Location: {$level3_url}"); die; } else { if ($cdn_name == "akamai") { $akamai_url = $request . $flv_extension; // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from if ($seek_from_timestamp == -1) { $seek_from_timestamp = $seek_from; } $akamai_url .= $seek_from_bytes == -1 ? "" : "&aktimeoffset=" . floor($seek_from_timestamp / 1000); header("Location: {$akamai_url}"); die; } } } // a seek request without a supporting cdn - we need to send the answer from our server if ($seek_from_bytes !== -1 && $via_header === null) { $this->dump_from_byte = $seek_from_bytes; } } } // always add the file suffix to the request (needed for scrubbing by some cdns, // and also breaks without extension on some corporate antivirus). // we add the the novar paramter since a leaving a trailing "?" will be trimmed // and then the /seek_from request will result in another url which level3 // will try to refetch from the origin // note that for streamer we dont add the file extension if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) { // a seek request without a supporting cdn - we need to send the answer from our server if ($seek_from_bytes !== -1 && $via_header === null) { $request .= "/seek_from_bytes/{$seek_from_bytes}"; } requestUtils::sendCdnHeaders("flv", 0); header("Location: {$request}" . $flv_extension); die; } // mp4 if (!$isFlv) { kFile::dumpFile($path); } $this->logMessage("flvclipperAction: serving file [{$path}] entry_id [{$entry_id}] clip_from [{$clip_from}] clip_to [{$clip_to}]", "warning"); if ($audio_only === '0') { // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) { $audio_only = true; } //$start = microtime(true); list($bytes, $duration, $from_byte, $to_byte, $from_ts, $cuepoint_pos) = myFlvStaticHandler::clip($path, $clip_from, $clip_to, $audio_only); $metadata_size = $flv_wrapper->getMetadataSize($audio_only); $this->from_byte = $from_byte; $this->to_byte = $to_byte; //$end1 = microtime(true); //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" ); //$this->logMessage( "flvclipperAction: serving file [$path] t1 [" . ( $end1-$start) . "]"); $data_offset = $metadata_size + myFlvHandler::getHeaderSize(); // if we're returning a partial file adjust the total size: // substract the metadata and bytes which are not delivered if ($this->dump_from_byte >= $data_offset && !$audio_only) { $bytes -= $metadata_size + max(0, $this->dump_from_byte - $data_offset); } $this->total_length = $data_offset + $bytes; //echo " $bytes , $duration ,$from_byte , $to_byte, $cuepoint_pos\n"; die; $this->cuepoint_time = 0; $this->cuepoint_pos = 0; if ($streamer == "chunked" && $clip_to != 2147483647) { $this->cuepoint_time = $clip_to - 1; $this->cuepoint_pos = $cuepoint_pos; $this->total_length += myFlvHandler::CUEPOINT_TAG_SIZE; } //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes with header & md [" . $this->total_length . "] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" ); $this->flv_wrapper = $flv_wrapper; $this->audio_only = $audio_only; try { Propel::close(); } catch (Exception $e) { $this->logMessage("flvclipperAction: error closing db {$e}"); } return sfView::SUCCESS; }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { // check if this is a request for the kdp without a wrapper // in case of an application loading the kdp (e.g. kmc) $nowrapper = $this->getRequestParameter("nowrapper", false); // allow caching if either the cache start time (cache_st) parameter // wasn't specified or if it is past the specified time $cache_st = $this->getRequestParameter("cache_st"); $allowCache = !$cache_st || $cache_st < time(); $referer = @$_SERVER['HTTP_REFERER']; $externalInterfaceDisabled = strstr($referer, "bebo.com") === false && strstr($referer, "myspace.com") === false && strstr($referer, "current.com") === false && strstr($referer, "myyearbook.com") === false && strstr($referer, "facebook.com") === false && strstr($referer, "friendster.com") === false ? "" : "&externalInterfaceDisabled=1"; // if there is no wrapper the loader is responsible for setting extra params to the kdp $noncached_params = ""; if (!$nowrapper) { $noncached_params = $externalInterfaceDisabled . "&referer=" . urlencode($referer); } $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https" : "http"; $requestKey = $protocol . $_SERVER["REQUEST_URI"]; // check if we cached the redirect url $cache_redirect = new myCache("kwidget", 10 * 60); // 10 minutes $cachedResponse = $cache_redirect->get($requestKey); if ($allowCache && $cachedResponse) { header("X-Kaltura:cached-action"); header("Expires: Sun, 19 Nov 2000 08:52:00 GMT"); header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); header("Pragma: no-cache"); header("Location:{$cachedResponse}" . $noncached_params); KExternalErrors::dieGracefully(); } // check if we cached the patched swf with flashvars $cache_swfdata = new myCache("kwidgetswf", 10 * 60); // 10 minutes $cachedResponse = $cache_swfdata->get($requestKey); if ($allowCache && $cachedResponse) { header("X-Kaltura:cached-action"); requestUtils::sendCdnHeaders("swf", strlen($cachedResponse), 60 * 10, null, true, time()); echo $cachedResponse; KExternalErrors::dieGracefully(); } $widget_id = $this->getRequestParameter("wid"); $show_version = $this->getRequestParameter("v"); $debug_kdp = $this->getRequestParameter("debug_kdp", false); $widget = widgetPeer::retrieveByPK($widget_id); if (!$widget) { KExternalErrors::dieGracefully(); } myPartnerUtils::blockInactivePartner($widget->getPartnerId()); // because of the routing rule - the entry_id & kmedia_type WILL exist. be sure to ignore them if smaller than 0 $kshow_id = $widget->getKshowId(); $entry_id = $widget->getEntryId(); $gallery_widget = !$kshow_id && !$entry_id; if (!$entry_id) { $entry_id = -1; } if ($widget->getSecurityType() != widget::WIDGET_SECURITY_TYPE_TIMEHASH) { // try eid - if failed entry_id $eid = $this->getRequestParameter("eid", $this->getRequestParameter("entry_id")); // try kid - if failed kshow_id $kid = $this->getRequestParameter("kid", $this->getRequestParameter("kshow_id")); if ($eid != null) { $entry_id = $eid; } elseif ($kid != null) { $kshow_id = $kid; } } if ($widget->getSecurityType() == widget::WIDGET_SECURITY_TYPE_MATCH_IP) { $allowCache = false; // here we'll attemp to match the ip of the request with that from the customData of the widget $custom_data = $widget->getCustomData(); $valid_country = false; if ($custom_data) { // in this case the custom_data should be of format: // valid_county_1,valid_country_2,...,valid_country_n;falback_entry_id $arr = explode(";", $custom_data); $countries_str = $arr[0]; $fallback_entry_id = isset($arr[1]) ? $arr[1] : null; $fallback_kshow_id = isset($arr[2]) ? $arr[2] : null; $current_country = ""; $valid_country = requestUtils::matchIpCountry($countries_str, $current_country); if (!$valid_country) { KalturaLog::log("kwidgetAction: Attempting to access widget [{$widget_id}] and entry [{$entry_id}] from country [{$current_country}]. Retrning entry_id: [{$fallback_entry_id}] kshow_id [{$fallback_kshow_id}]"); $entry_id = $fallback_entry_id; $kshow_id = $fallback_kshow_id; } } } elseif ($widget->getSecurityType() == widget::WIDGET_SECURITY_TYPE_FORCE_KS) { } $kmedia_type = -1; // support either uiconf_id or ui_conf_id $uiconf_id = $this->getRequestParameter("uiconf_id"); if (!$uiconf_id) { $uiconf_id = $this->getRequestParameter("ui_conf_id"); } if ($uiconf_id) { $widget_type = $uiconf_id; $uiconf_id_str = "&uiconf_id={$uiconf_id}"; } else { $widget_type = $widget->getUiConfId(); $uiconf_id_str = ""; } if (empty($widget_type)) { $widget_type = 3; } $kdata = $widget->getCustomData(); $partner_host = myPartnerUtils::getHost($widget->getPartnerId()); $partner_cdnHost = myPartnerUtils::getCdnHost($widget->getPartnerId()); $host = $partner_host; if ($widget_type == 10) { $swf_url = $host . "/swf/weplay.swf"; } else { $swf_url = $host . "/swf/kplayer.swf"; } $partner_id = $widget->getPartnerId(); $subp_id = $widget->getSubpId(); if (!$subp_id) { $subp_id = 0; } $uiConf = uiConfPeer::retrieveByPK($widget_type); // new ui_confs which are deleted should stop the script // the check for >100000 is for supporting very old mediawiki and such players if (!$uiConf && $widget_type > 100000) { KExternalErrors::dieGracefully(); } if ($uiConf) { $ui_conf_swf_url = $uiConf->getSwfUrl(); if (kString::beginsWith($ui_conf_swf_url, "http")) { $swf_url = $ui_conf_swf_url; // absolute URL } else { $use_cdn = $uiConf->getUseCdn(); $host = $use_cdn ? $partner_cdnHost : $partner_host; $swf_url = $host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . $ui_conf_swf_url; } if ($debug_kdp) { $swf_url = str_replace("/kdp/", "/kdp_debug/", $swf_url); } } if ($show_version < 0) { $show_version = null; } $ip = requestUtils::getRemoteAddress(); // to convert back, use long2ip // the widget log should change to reflect the new data, but for now - i used $widget_id instead of the widgget_type // WidgetLog::createWidgetLog( $referer , $ip , $kshow_id , $entry_id , $kmedia_type , $widget_id ); if ($entry_id == -1) { $entry_id = null; } $kdp3 = false; $base_wrapper_swf = myContentStorage::getFSFlashRootPath() . "/kdpwrapper/" . kConf::get('kdp_wrapper_version') . "/kdpwrapper.swf"; $widgetIdStr = "widget_id={$widget_id}"; $partnerIdStr = "partner_id={$partner_id}&subp_id={$subp_id}"; $entryVarName = 'entryId'; if ($widget->getIsPlayList()) { $entryVarName = 'playlistId'; } if ($uiConf) { $ks_flashvars = ""; $conf_vars = $uiConf->getConfVars(); if ($conf_vars) { $conf_vars = "&" . $conf_vars; } $wrapper_swf = $base_wrapper_swf; $partner = PartnerPeer::retrieveByPK($partner_id); if ($partner) { $partner_type = $partner->getType(); } if (version_compare($uiConf->getSwfUrlVersion(), "3.0", ">=")) { $kdp3 = true; // further in the code, $wrapper_swf is being used and not $base_wrapper_swf $wrapper_swf = $base_wrapper_swf = myContentStorage::getFSFlashRootPath() . '/kdp3wrapper/' . kConf::get('kdp3_wrapper_version') . '/kdp3wrapper.swf'; $widgetIdStr = "widgetId={$widget_id}"; $uiconf_id_str = "&uiConfId={$uiconf_id}"; $partnerIdStr = "partnerId={$partner_id}&subpId={$subp_id}"; } // if we are loaded without a wrapper (directly in flex) // 1. dont create the ks - keep url the same for caching // 2. dont patch the uiconf - patching is done only to wrapper anyway if ($nowrapper) { $dynamic_date = $widgetIdStr . "&host=" . str_replace("http://", "", str_replace("https://", "", $partner_host)) . "&cdnHost=" . str_replace("http://", "", str_replace("https://", "", $partner_cdnHost)) . $uiconf_id_str . $conf_vars; $url = "{$swf_url}?{$dynamic_date}"; } else { $swf_data = null; // if kdp version >= 2.5 if (version_compare($uiConf->getSwfUrlVersion(), "2.5", ">=")) { // create an anonymous session $ks = ""; $privileges = "view:*,widget:1"; if ($widget->getIsPlayList()) { $privileges = "list:*,widget:1"; } if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENTITLEMENT, $partner_id) && !$widget->getEnforceEntitlement() && $widget->getEntryId()) { $privileges .= ',' . kSessionBase::PRIVILEGE_DISABLE_ENTITLEMENT_FOR_ENTRY . ':' . $widget->getEntryId(); } if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENTITLEMENT, $partner_id) && !is_null($widget->getPrivacyContext()) && $widget->getPrivacyContext() != '') { $privileges .= ',' . kSessionBase::PRIVILEGE_PRIVACY_CONTEXT . ':' . $widget->getPrivacyContext(); } $result = kSessionUtils::createKSessionNoValidations($partner_id, 0, $ks, 86400, false, "", $privileges); $ks_flashvars = "&{$partnerIdStr}&uid=0&ts=" . microtime(true); if ($widget->getSecurityType() != widget::WIDGET_SECURITY_TYPE_FORCE_KS) { $ks_flashvars = "&ks={$ks}" . $ks_flashvars; } // patch kdpwrapper with getwidget and getuiconf $root = myContentStorage::getFSContentRootPath(); $confFile_mtime = $uiConf->getUpdatedAt(null); $swf_key = "widget_{$widget_id}_{$widget_type}_{$confFile_mtime}_" . md5($base_wrapper_swf . $swf_url) . ".swf"; $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_KWIDGET_SWF); if ($cache) { $swf_data = $cache->get($swf_key); } if (!$swf_data) { require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "api_v3" . DIRECTORY_SEPARATOR . "bootstrap.php"; $dispatcher = KalturaDispatcher::getInstance(); try { $widget_result = $dispatcher->dispatch("widget", "get", array("ks" => $ks, "id" => $widget_id)); $ui_conf_result = $dispatcher->dispatch("uiConf", "get", array("ks" => $ks, "id" => $widget_type)); } catch (Exception $ex) { KExternalErrors::dieGracefully(); } if (!$ui_conf_result->confFile) { KExternalErrors::dieGracefully(); } $serializer = new KalturaXmlSerializer(false); $widget_xml = $serializer->serialize($widget_result); $serializer = new KalturaXmlSerializer(false); $ui_conf_xml = $serializer->serialize($ui_conf_result); $result = "<xml><result>{$widget_xml}</result><result>{$ui_conf_xml}</result></xml>"; $patcher = new kPatchSwf(file_get_contents($root . $base_wrapper_swf)); $swf_data = $patcher->patch($result); if ($cache) { $cache->set($swf_key, $swf_data); } } } $kdp_version_2 = strpos($swf_url, "kdp/v2.") > 0; if ($partner_host == "http://www.kaltura.com" && !$kdp_version_2 && !$kdp3) { $partner_host = 1; // otherwise the kdp will try going to cdnwww.kaltura.com } $track_wrapper = ''; if (kConf::get('track_kdpwrapper') && kConf::get('kdpwrapper_track_url')) { $track_wrapper = "&wrapper_tracker_url=" . urlencode(kConf::get('kdpwrapper_track_url') . "?activation_key=" . kConf::get('kaltura_activation_key') . "&package_version=" . kConf::get('kaltura_version')); } $optimizedConfVars = null; $optimizedHost = null; if (kConf::hasMap("optimized_playback")) { $optimizedPlayback = kConf::getMap("optimized_playback"); if (array_key_exists($partner_id, $optimizedPlayback)) { // force a specific kdp for the partner $params = $optimizedPlayback[$partner_id]; if (array_key_exists('kdp_version', $params)) { $swf_url = $partner_cdnHost . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . "/flash/kdp3/" . $params['kdp_version'] . "/kdp3.swf"; } if (array_key_exists('conf_vars', $params)) { $optimizedConfVars = $params['conf_vars']; } if (array_key_exists('host', $params)) { $optimizedHost = $params['host']; } // cache immidiately $cache_st = 0; $allowCache = true; } } if ($optimizedConfVars === null) { $optimizedConfVars = "clientDefaultMethod=GET"; } $conf_vars = "&{$optimizedConfVars}&" . $conf_vars; $stats_host = $protocol == "https" ? kConf::get("stats_host_https") : kConf::get("stats_host"); $wrapper_stats = kConf::get('kdp3_wrapper_stats_url') ? "&wrapper_stats_url={$protocol}://{$stats_host}" . urlencode(str_replace("{partnerId}", $partner_id, kConf::get('kdp3_wrapper_stats_url'))) : ""; $partner_host = str_replace("http://", "", str_replace("https://", "", $partner_host)); // if the host is the default www domain use the cdn api domain if ($partner_host == kConf::get("www_host") && $optimizedHost === null) { $partner_host = kConf::get("cdn_api_host"); } else { if ($optimizedHost) { $partner_host = $optimizedHost; } } if ($protocol == "https" && ($partner_host = kConf::get("cdn_api_host"))) { $partner_host = kConf::get("cdn_api_host_https"); } $dynamic_date = $widgetIdStr . $track_wrapper . $wrapper_stats . "&kdpUrl=" . urlencode($swf_url) . "&host=" . $partner_host . "&cdnHost=" . str_replace("http://", "", str_replace("https://", "", $partner_cdnHost)) . "&statistics.statsDomain={$stats_host}" . ($show_version ? "&entryVersion={$show_version}" : "") . ($kshow_id ? "&kshowId={$kshow_id}" : "") . ($entry_id ? "&{$entryVarName}={$entry_id}" : "") . $uiconf_id_str . $ks_flashvars . ($cache_st ? "&clientTag=cache_st:{$cache_st}" : "") . $conf_vars; // patch wrapper with flashvars and dump to browser if (version_compare($uiConf->getSwfUrlVersion(), "2.6.6", ">=")) { $startTime = microtime(true); $patcher = new kPatchSwf($swf_data, "KALTURA_FLASHVARS_DATA"); $wrapper_data = $patcher->patch($dynamic_date . "&referer=" . urlencode($referer)); KalturaLog::log('Patching took ' . (microtime(true) - $startTime)); requestUtils::sendCdnHeaders("swf", strlen($wrapper_data), $allowCache ? 60 * 10 : 0, null, true, time()); if ($_SERVER["REQUEST_METHOD"] == "HEAD") { header('Content-Length: ' . strlen($wrapper_data)); } else { echo $wrapper_data; } if ($allowCache) { $cache_swfdata->put($requestKey, $wrapper_data); } KExternalErrors::dieGracefully(); } if ($swf_data) { $md5 = md5($swf_key); $wrapper_swf = "content/cacheswf/" . substr($md5, 0, 2) . "/" . substr($md5, 2, 2) . "/" . $swf_key; $wrapper_swf_path = "{$root}/{$wrapper_swf}"; if (!file_exists($wrapper_swf_path)) { kFile::fullMkdir($wrapper_swf_path); file_put_contents($wrapper_swf_path, $swf_data); } } // for now changed back to $host since kdp version prior to 1.0.15 didnt support loading by external domain kdpwrapper $url = $host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . "/{$wrapper_swf}?{$dynamic_date}"; } } else { $dynamic_date = "kshowId={$kshow_id}" . "&host=" . requestUtils::getRequestHostId() . ($show_version ? "&entryVersion={$show_version}" : "") . ($entry_id ? "&{$entryVarName}={$entry_id}" : "") . ($entry_id ? "&KmediaType={$kmedia_type}" : ""); $dynamic_date .= "&isWidget={$widget_type}&referer=" . urlencode($referer); $dynamic_date .= "&kdata={$kdata}"; $url = "{$swf_url}?{$dynamic_date}"; } // if referer has a query string an IE bug will prevent out flashvars to propagate // when nowrapper is true we cant use /swfparams either as there isnt a kdpwrapper if (!$nowrapper && $uiConf && version_compare($uiConf->getSwfUrlVersion(), "2.6.6", ">=")) { // apart from the /swfparam/ format, add .swf suffix to the end of the stream in case // a corporate firewall looks at the file suffix $pos = strpos($url, "?"); $url = substr($url, 0, $pos) . "/swfparams/" . urlencode(substr($url, $pos + 1)) . ".swf"; } if ($allowCache) { $cache_redirect->put($requestKey, $url); } if (strpos($url, "/swfparams/") > 0) { $url = substr($url, 0, -4) . urlencode($noncached_params) . ".swf"; } else { $url .= $noncached_params; } KExternalErrors::terminateDispatch(); $this->redirect($url); }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { requestUtils::handleConditionalGet(); $entry_id = $this->getRequestParameter("entry_id"); $type = $this->getRequestParameter("type"); $ks = $this->getRequestParameter("ks"); $file_sync = null; $ret_file_name = "name"; $referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($referrer); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ""; } $request_file_name = $this->getRequestParameter("file_name"); if ($request_file_name) { $ret_file_name = $request_file_name; } $direct_serve = $this->getRequestParameter("direct_serve"); $entry = entryPeer::retrieveByPK($entry_id); if (!$entry) { // what to return ?? die; } myPartnerUtils::blockInactivePartner($entry->getPartnerId()); $securyEntryHelper = new KSecureEntryHelper($entry, $ks, $referrer); $securyEntryHelper->validateForDownload(); // Rmoved by Tan-Tan - asked by Eran // // allow access only via cdn unless these are documents (due to the current implementation of convert ppt2swf) // if ($entry->getType() != entryType::DOCUMENT && $entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_IMAGE) // { // requestUtils::enforceCdnDelivery($entry->getPartnerId()); // } // relocate = did we use the redirect and added the extension to the name $relocate = $this->getRequestParameter("relocate"); if ($ret_file_name == "name") { $ret_file_name = $entry->getName(); } if ($ret_file_name) { //rawurlencode to content-disposition filename to handle spaces and other characters across different browsers //$name = rawurlencode($ret_file_name); // 19.04.2009 (Roman) - url encode is not needed when the filename in Content-Disposition header is in quotes // IE6/FF3/Chrome - Will show the filename correctly // IE7 - Will show the filename with underscores instead of spaces (this is better than showing %20) $name = $ret_file_name; if ($name) { if ($relocate) { // if we have a good file extension (from the first time) - use it in the content-disposition // in some browsers it will be stronger than the URL's extension $file_ext = pathinfo($relocate, PATHINFO_EXTENSION); $name .= ".{$file_ext}"; } if (!$direct_serve) { header("Content-Disposition: attachment; filename=\"{$name}\""); } } } else { $ret_file_name = $entry_id; } $format = $this->getRequestParameter("format"); if ($type == "download" && $format && $entry->getType() != entryType::DOCUMENT) { // this is a video for a specifc extension - use the proper flavorAsset $flavor_asset = flavorAssetPeer::retrieveByEntryIdAndExtension($entry_id, $format); if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) { $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true); } else { header('KalturaRaw: no flavor asset for extension'); header("HTTP/1.0 404 Not Found"); die; } $archive_file = $file_sync->getFullPath(); $mime_type = kFile::mimeType($archive_file); kFile::dumpFile($archive_file, $mime_type); } // TODO - move to a different action - document should be plugin if ($entry->getType() == entryType::DOCUMENT) { // use the fileSync from the entry if ($type == "download" && $format) { $flavor_asset = flavorAssetPeer::retrieveByEntryIdAndExtension($entry_id, $format); } else { $flavor_asset = flavorAssetPeer::retrieveOriginalByEntryId($entry_id); } if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) { $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true); } else { header('KalturaRaw: no flavor asset for extension'); header("HTTP/1.0 404 Not Found"); die; } // Gonen 2010-08-05 workaround to make sure file name includes correct extension // make sure a file extension is added to the downloaded file so browser will identify and // allow opening with default program // for direct serve we do not want to send content-disposition header if (!$direct_serve) { $ext = pathinfo($file_sync->getFullPath(), PATHINFO_EXTENSION); if ($relocate) { // remove relocate file extension $reloc_ext = pathinfo($relocate, PATHINFO_EXTENSION); $name = str_replace(".{$reloc_ext}", '', $name); } header("Content-Disposition: attachment; filename=\"{$name}.{$ext}\""); } kFile::dumpFile($file_sync->getFullPath()); } elseif ($entry->getType() == entryType::DATA) { $version = $this->getRequestParameter("version"); $syncKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version); list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if ($local) { $path = $fileSync->getFullPath(); } else { $path = kDataCenterMgr::getRedirectExternalUrl($fileSync); KalturaLog::info("Redirecting to [{$path}]"); } if (!$path) { header('KalturaRaw: no data was found available for download'); header("HTTP/1.0 404 Not Found"); } else { kFile::dumpFile($path); } } //$archive_file = $entry->getArchiveFile(); $media_type = $entry->getMediaType(); if ($media_type == entry::ENTRY_MEDIA_TYPE_IMAGE) { // image - use data for entry $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, null); $key = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); kFile::dumpFile(kFileSyncUtils::getLocalFilePathForKey($key, true)); } elseif ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO || $media_type == entry::ENTRY_MEDIA_TYPE_AUDIO) { $format = $this->getRequestParameter("format"); if ($type == "download" && $format) { // this is a video for a specifc extension - use the proper flavorAsset $flavor_asset = flavorAssetPeer::retrieveByEntryIdAndExtension($entry_id, $format); if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) { $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true); } else { header('KalturaRaw: no flavor asset for extension'); die; } $archive_file = $file_sync->getFullPath(); } else { // flavorAsset of the original $flavor_asset = flavorAssetPeer::retrieveOriginalByEntryId($entry_id); if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) { $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, false); // NOT strict - if there is no archive, get the data version if ($file_sync) { $archive_file = $file_sync->getFullPath(); } } if (!$flavor_asset || !$file_sync || $flavor_asset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) { // either no archive asset or no fileSync for archive asset // use fallback flavorAsset $flavor_asset = flavorAssetPeer::retrieveBestPlayByEntryId($entry_id); if (!$flavor_asset) { header('KalturaRaw: no original flavor asset for entry, no best play asset for entry'); die; } $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, false); // NOT strict - if there is no archive, get the data version $archive_file = $file_sync->getFullPath(); } } } elseif ($media_type == entry::ENTRY_MEDIA_TYPE_SHOW) { // in this case "raw" is a bad name // TODO - add the ability to fetch the actual XML by flagging "xml" or something $version = $this->getRequestParameter("version"); // hotfix - links sent after flattening is done look like: // http://cdn.kaltura.com/p/387/sp/38700/raw/entry_id/0_ix99151g/version/100001 // while waiting for flavor-adaptation in flattening, we want to find at least one file to return. $try_formats = array('mp4', 'mov', 'avi', 'flv'); if ($format) { $key = array_search($format, $try_formats); if ($key !== FALSE) { unset($try_formats[$key]); } $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $format, false); } if (!isset($file_sync) || !$file_sync || !file_exists($file_sync->getFullPath())) { foreach ($try_formats as $ext) { KalturaLog::log("raw for mix - trying to find filesync for extension: [{$ext}] on entry [{$entry->getId()}]"); $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $ext, false); if ($file_sync && file_exists($file_sync->getFullPath())) { KalturaLog::log("raw for mix - found flattened video of extension: [{$ext}] continuing with this file {$file_sync->getFullPath()}"); break; } } if (!$file_sync || !file_exists($file_sync->getFullPath())) { $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $ext, true); } } // use fileSync for entry - roughcuts don't have flavors //$file_sync = $this->redirectIfRemote ( $entry , entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD , $version , true ); // strict - nothing to do if no flattened version // if got to here - fileSync was found for one of the extensions - continue with that file $archive_file = $file_sync->getFullPath(); } else { // no archive for this file header("HTTP/1.0 404 Not Found"); die; } // echo "[$archive_file][" . file_exists ( $archive_file ) . "]"; $mime_type = kFile::mimeType($archive_file); // echo "[[$mime_type]]"; if (!empty($relocate)) { // after relocation - dump the file kFile::dumpFile($archive_file, $mime_type); die; } else { // use new Location to add the best extension we can find for the file $file_ext = pathinfo($archive_file, PATHINFO_EXTENSION); if ($file_ext != "flv") { // if the file does not end with "flv" - it is the real extension $ext = $file_ext; } else { // for now - if "flv" return "flv" - // TODO - find the real extension from the file itself $ext = "flv"; } // rebuild the URL and redirect to it with extraa parameters $url = $_SERVER["REQUEST_URI"]; $format = $this->getRequestParameter("format"); if (!$format) { $url = str_replace("format", "", $url); } if ($ret_file_name && pathinfo($ret_file_name, PATHINFO_EXTENSION) != "") { // if the name holds an extension - prefer it over the real file's extension $ext = pathinfo($ret_file_name, PATHINFO_EXTENSION); } if (!$ret_file_name) { // don't leave the name empty - if it is empty - use the entry id $ret_file_name = $entry_id; } if (strpos($url, "?") > 0) { $url = str_replace("?", "/{$ret_file_name}.{$ext}?", $url); $url .= "&relocate=f.{$ext}"; // add the ufname as a query parameter } else { $url .= "/{$ret_file_name}.{$ext}?relocate=f.{$ext}"; // add the ufname as a query parameter } // redirect and create the url so it will have the ufname header("Location: {$url}"); } die; }
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); $ks = $this->getRequestParameter("ks"); $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; // $securyEntryHelper = new KSecureEntryHelper($entry, $ks, $referrer, ContextType::PLAY); // if ($securyEntryHelper->shouldPreview()) // { // $clipTo = $securyEntryHelper->getPreviewLength() * 1000; // } // else // { // $securyEntryHelper->validateForPlay($entry, $ks); // } KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFlavor', $flavorAsset->getPartnerId()); myPartnerUtils::blockInactivePartner($flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($flavorAsset->getPartnerId()); $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('<?xml version="1.0" encoding="utf-8"?><xml><result>' . $path . '</result></xml>', 'text/xml'); if ($path) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } 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() { $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 }