/**
  * 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 executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser)
 {
     KalturaLog::log("adddownloadAction: executeImpl ( {$partner_id} , {$subp_id} , {$puser_id} , {$partner_prefix} , {$puser_kuser})");
     $entry_id = $this->getPM("entry_id");
     $version = $this->getP("version");
     $file_format = strtolower($this->getPM("file_format"));
     $conversion_quality = $this->getP("conversion_quality", null);
     $force_download = $this->getP("force_download", null);
     $entry = entryPeer::retrieveByPK($entry_id);
     if (!$entry) {
         KalturaLog::log("add download Action entry not found");
         $this->addError(APIErrors::INVALID_ENTRY_ID, $this->getObjectPrefix(), $entry_id);
         return;
     }
     KalturaLog::log("adddownloadAction: entry found [{$entry_id}]");
     /*			
     $content_path = myContentStorage::getFSContentRootPath();
     $file_name = $content_path . $entry->getDataPath( $version ); // replaced__getDataPath
     if (!file_exists($file_name))
     */
     $sync_key = null;
     $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
     if ($originalFlavorAsset) {
         $sync_key = $originalFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     }
     if (!$sync_key) {
         $sync_key = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version);
     }
     if (!kFileSyncUtils::file_exists($sync_key)) {
         // if not found local file - perhaps wasn't created here and wasn't synced yet
         // try to see if remote exists - and proxy the request if it is.
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($sync_key, true, true);
         if (!$local) {
             // take input params and add to URL
             $queryArr = array('entry_id' => $entry_id, 'version' => $version, 'file_format' => $file_format, 'conversion_quality' => $conversion_quality, 'force_download' => $force_download, 'ks' => $this->ks->toSecureString(), 'partner_id' => $partner_id, 'subp_id' => $subp_id, 'format' => $this->response_type);
             $get_query = http_build_query($queryArr, '', '&');
             $remote_url = kDataCenterMgr::getRedirectExternalUrl($fileSync, $_SERVER['REQUEST_URI']);
             $url = strpos($remote_url, '?') === FALSE ? $remote_url . '?' . $get_query : $remote_url . '&' . $get_query;
             // prxoy request to other DC
             KalturaLog::log(__METHOD__ . ": redirecting to [{$url}]");
             kFileUtils::dumpUrl($url);
         }
         KalturaLog::log("add download Action sync key doesn't exists");
         $this->addError(APIErrors::INVALID_ENTRY_VERSION, $this->getObjectPrefix(), $entry_id, $version);
         return;
     }
     if ($entry->getType() == entryType::MIX) {
         KalturaLog::log("The Batch job for flattening a mix is no longer supported");
         $this->addError(APIErrors::INVALID_ENTRY_TYPE, $this->getObjectPrefix(), $entry_id, $version);
         return;
     }
     $flavorParamsId = 0;
     if ($file_format != "original") {
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) {
             $file_format = "flv";
         }
         // Backward compatebility
         if (!$file_format && $entry->getType() == entryType::DOCUMENT) {
             $file_format = "swf";
         }
         $flavorParams = myConversionProfileUtils::getFlavorParamsFromFileFormat($partner_id, $file_format);
         $flavorParamsId = $flavorParams->getId();
     }
     $jobs = kJobsManager::addBulkDownloadJob($partner_id, $puser_id, $entry->getId(), $flavorParamsId);
     $job = $jobs[0];
     // remove kConvertJobData object from batchJob.data
     $job->setData(null);
     $jobWrapperClass = objectWrapperBase::getWrapperClass($job, objectWrapperBase::DETAIL_LEVEL_DETAILED);
     $this->addMsg("download", $jobWrapperClass);
     // Backwards compatebilty for document entries
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_DOCUMENT || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_PDF) {
         $this->addMsg("OOconvert", $jobWrapperClass);
         $download_path = $entry->getDownloadUrl();
         //TODO: once api_v3 will support parameters with '/' instead of '?', we can change this to war with api_v3
         $download_path .= '/direct_serve/true/type/download/forceproxy/true/format/' . $file_format;
         $this->addMsg('downloadUrl', $download_path);
     }
 }
 public 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()
 {
     $uiconf_id = $this->getRequestParameter('uiconf_id');
     if (!$uiconf_id) {
         KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'uiconf_id');
     }
     $uiConf = uiConfPeer::retrieveByPK($uiconf_id);
     if (!$uiConf) {
         KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND);
     }
     $partner_id = $this->getRequestParameter('partner_id', $uiConf->getPartnerId());
     if (!$partner_id) {
         KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'partner_id');
     }
     $widget_id = $this->getRequestParameter("widget_id", '_' . $partner_id);
     $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https" : "http";
     $host = myPartnerUtils::getCdnHost($partner_id, $protocol, 'api');
     $ui_conf_html5_url = $uiConf->getHtml5Url();
     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('html5_url', $params)) {
                 $ui_conf_html5_url = $params['html5_url'];
             }
         }
     }
     $autoEmbed = $this->getRequestParameter('autoembed');
     $iframeEmbed = $this->getRequestParameter('iframeembed');
     $scriptName = $iframeEmbed ? 'mwEmbedFrame.php' : 'mwEmbedLoader.php';
     if ($ui_conf_html5_url && $iframeEmbed) {
         $ui_conf_html5_url = str_replace('mwEmbedLoader.php', 'mwEmbedFrame.php', $ui_conf_html5_url);
     }
     $relativeUrl = true;
     // true if ui_conf html5_url is relative (doesnt start with an http prefix)
     if (kString::beginsWith($ui_conf_html5_url, "http")) {
         $relativeUrl = false;
         $url = $ui_conf_html5_url;
         // absolute URL
     } else {
         if (!$iframeEmbed) {
             $host = "{$protocol}://" . kConf::get('html5lib_host') . "/";
         }
         if ($ui_conf_html5_url) {
             $url = $host . $ui_conf_html5_url;
         } else {
             $html5_version = kConf::get('html5_version');
             $url = "{$host}/html5/html5lib/{$html5_version}/" . $scriptName;
         }
     }
     // append uiconf_id and partner id for optimizing loading of html5 library. append them only for "standard" urls by looking for the mwEmbedLoader.php/mwEmbedFrame.php suffix
     if (kString::endsWith($url, $scriptName)) {
         $url .= "/p/{$partner_id}/uiconf_id/{$uiconf_id}";
         if (!$autoEmbed) {
             $entry_id = $this->getRequestParameter('entry_id');
             if ($entry_id) {
                 $url .= "/entry_id/{$entry_id}";
             }
         }
     }
     header("pragma:");
     if ($iframeEmbed) {
         $url .= (strpos($url, "?") === false ? "?" : "&") . 'wid=' . $widget_id . '&' . $_SERVER["QUERY_STRING"];
     } else {
         $params = "protocol={$protocol}&" . $_SERVER["QUERY_STRING"];
         $url .= (strpos($url, "?") === false ? "?" : "&") . $params;
         if ($relativeUrl) {
             header('Content-Type: application/javascript');
             kFileUtils::dumpUrl($url, true, false, array("X-Forwarded-For" => requestUtils::getRemoteAddress()));
         }
     }
     requestUtils::sendCachingHeaders(60, true, time());
     kFile::cacheRedirect($url);
     header("Location:{$url}");
     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)
 }
Exemple #6
0
 /**
  * Serves the file content
  * 
  * @action serve
  * @param flavorAsset $flavorAsset
  * @param string $fileName
  * @param bool $forceProxy
  * @return file
  * 
  * @throws KalturaErrors::FLAVOR_ASSET_IS_NOT_READY
  */
 protected function serveFlavorAsset(flavorAsset $flavorAsset, $fileName, $forceProxy = false)
 {
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     if (!$fileSync) {
         throw new KalturaAPIException(KalturaErrors::FLAVOR_ASSET_IS_NOT_READY, $flavorAsset->getId());
     }
     /* @var $fileSync FileSync */
     if ($fileSync->getFileExt() != assetParams::CONTAINER_FORMAT_SWF) {
         header("Content-Disposition: attachment; filename=\"{$fileName}\"");
     }
     if ($local) {
         $filePath = $fileSync->getFullPath();
         $mimeType = kFile::mimeType($filePath);
         return $this->dumpFile($filePath, $mimeType);
     } else {
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         KalturaLog::info("Redirecting to [{$remoteUrl}]");
         if ($forceProxy) {
             kFileUtils::dumpUrl($remoteUrl);
         } else {
             // or redirect if no proxy
             header("Location: {$remoteUrl}");
             die;
         }
     }
 }
Exemple #7
0
 /**
  *
  * @param $entry
  * @param $sub_type
  * @param $version
  * @return FileSync
  */
 private function redirectFileSyncIfRemote($file_sync, $local)
 {
     if (!$local) {
         $shouldProxy = $this->getRequestParameter("forceproxy", false);
         $remote_url = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']);
         KalturaLog::log(__METHOD__ . ": redirecting to [{$remote_url}]");
         if ($shouldProxy) {
             kFileUtils::dumpUrl($remote_url);
         } else {
             // or redirect if no proxy
             $this->redirect($remote_url);
         }
     }
     return $file_sync;
 }
Exemple #8
0
 /**
  * serve action returan the file from dataContent field.
  * 
  * @action serve
  * @param string $entryId Data entry id
  * @param int $version Desired version of the data
  * @param bool $forceProxy force to get the content without redirect
  * @return file
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  */
 function serveAction($entryId, $version = -1, $forceProxy = false)
 {
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry || $dbEntry->getType() != KalturaEntryType::DATA) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $ksObj = $this->getKs();
     $ks = $ksObj ? $ksObj->getOriginalString() : null;
     $securyEntryHelper = new KSecureEntryHelper($dbEntry, $ks, null, ContextType::DOWNLOAD);
     $securyEntryHelper->validateForDownload();
     if (!$version || $version == -1) {
         $version = null;
     }
     $fileName = $dbEntry->getName();
     $syncKey = $dbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     header("Content-Disposition: attachment; filename=\"{$fileName}\"");
     if ($local) {
         $filePath = $fileSync->getFullPath();
         $mimeType = kFile::mimeType($filePath);
         return $this->dumpFile($filePath, $mimeType);
     } else {
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         KalturaLog::info("Redirecting to [{$remoteUrl}]");
         if ($forceProxy) {
             kFileUtils::dumpUrl($remoteUrl);
         } else {
             // or redirect if no proxy
             header("Location: {$remoteUrl}");
             die;
         }
     }
 }
Exemple #9
0
 public function getLocalThumbFilePath($version, $width, $height, $type, $bgcolor = "ffffff", $crop_provider = null, $quality = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $vid_sec = -1, $vid_slice = 0, $vid_slices = -1, $density = 0, $stripProfiles = false, $flavorId = null, $fileName = null)
 {
     KalturaLog::log("flavor_id [{$flavorId}] file_name [{$fileName}]");
     if (is_null($flavorId)) {
         KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'flavor_id');
     }
     $flavor = assetPeer::retrieveById($flavorId);
     if (is_null($flavor)) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND, $flavorId);
     }
     $flavorSyncKey = $flavor->getSyncKey(asset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
     $file_path = kFileSyncUtils::getReadyLocalFilePathForKey($flavorSyncKey);
     $orig_image_path = null;
     if (is_dir($file_path)) {
         if (is_null($fileName)) {
             KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'file name');
         }
         $orig_image_path = $file_path . DIRECTORY_SEPARATOR . $fileName;
     }
     try {
         return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $orig_image_path, $density);
     } catch (Exception $ex) {
         if ($ex->getCode() == kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
             $remoteFileSync = kFileSyncUtils::getOriginFileSyncForKey($flavorSyncKey, false);
             if (!$remoteFileSync) {
                 // file does not exist on any DC - die
                 KalturaLog::err("No FileSync for flavor [{$flavorId}]");
                 KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
             }
             if ($remoteFileSync->getDc() == kDataCenterMgr::getCurrentDcId()) {
                 KalturaLog::err("Trying to redirect to myself - stop here.");
                 KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
             }
             if (!in_array($remoteFileSync->getDc(), kDataCenterMgr::getDcIds())) {
                 KalturaLog::err("Origin file sync is on remote storage.");
                 KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
             }
             $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync);
             kFileUtils::dumpUrl($remoteUrl);
         }
     }
 }
Exemple #10
0
 /**
  * Serves short link
  * 
  * @action goto
  * @param string $id
  * @param bool $proxy proxy the response instead of redirect
  * @return file
  * 
  * @throws KalturaErrors::INVALID_OBJECT_ID
  */
 function gotoAction($id, $proxy = false)
 {
     KalturaResponseCacher::disableCache();
     $dbShortLink = ShortLinkPeer::retrieveByPK($id);
     if (!$dbShortLink) {
         throw new KalturaAPIException(KalturaErrors::INVALID_OBJECT_ID, $id);
     }
     if ($proxy) {
         kFileUtils::dumpUrl($dbShortLink->getFullUrl(), true, true);
     }
     header('Location: ' . $dbShortLink->getFullUrl());
     die;
 }