public function validateEntry(entry $dbEntry)
 {
     parent::validateEntry($dbEntry);
     $this->validatePropertyNotNull('resources');
     $dc = null;
     foreach ($this->resources as $resource) {
         $resource->validateEntry($dbEntry);
         if (!$resource instanceof KalturaDataCenterContentResource) {
             continue;
         }
         $theDc = $resource->getDc();
         if (is_null($theDc)) {
             continue;
         }
         if (is_null($dc)) {
             $dc = $theDc;
         } elseif ($dc != $theDc) {
             throw new KalturaAPIException(KalturaErrors::RESOURCES_MULTIPLE_DATA_CENTERS);
         }
     }
     if (!is_null($dc) && $dc != kDataCenterMgr::getCurrentDcId()) {
         $remoteHost = kDataCenterMgr::getRemoteDcExternalUrlByDcId($dc);
         kFileUtils::dumpApiRequest($remoteHost);
     }
 }
Example #2
0
 /**
  * Creates perioding metadata sync-point events on a live stream
  * 
  * @action createPeriodicSyncPoints
  * @actionAlias liveStream.createPeriodicSyncPoints
  * @param string $entryId Kaltura live-stream entry id
  * @param int $interval Events interval in seconds 
  * @param int $duration Duration in seconds
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @throws KalturaErrors::NO_MEDIA_SERVER_FOUND
  * @throws KalturaErrors::MEDIA_SERVER_SERVICE_NOT_FOUND
  */
 function createPeriodicSyncPoints($entryId, $interval, $duration)
 {
     $entryDc = substr($entryId, 0, 1);
     if ($entryDc != kDataCenterMgr::getCurrentDcId()) {
         $remoteDCHost = kDataCenterMgr::getRemoteDcExternalUrlByDcId($entryDc);
         kFileUtils::dumpApiRequest($remoteDCHost, true);
     }
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry || $dbEntry->getType() != KalturaEntryType::LIVE_STREAM || !in_array($dbEntry->getSource(), array(KalturaSourceType::LIVE_STREAM, KalturaSourceType::LIVE_STREAM_ONTEXTDATA_CAPTIONS))) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     /* @var $dbEntry LiveStreamEntry */
     $mediaServers = $dbEntry->getMediaServers();
     if (!count($mediaServers)) {
         throw new KalturaAPIException(KalturaErrors::NO_MEDIA_SERVER_FOUND, $entryId);
     }
     foreach ($mediaServers as $key => $kMediaServer) {
         if ($kMediaServer && $kMediaServer instanceof kLiveMediaServer) {
             $mediaServer = $kMediaServer->getMediaServer();
             $mediaServerCuePointsService = $mediaServer->getWebService(MediaServer::WEB_SERVICE_CUE_POINTS);
             KalturaLog::debug("Sending sync points for DC [" . $mediaServer->getDc() . "] ");
             if ($mediaServerCuePointsService && $mediaServerCuePointsService instanceof KalturaMediaServerCuePointsService) {
                 KalturaLog::debug("Call createTimeCuePoints on DC [" . $mediaServer->getDc() . "] ");
                 $mediaServerCuePointsService->createTimeCuePoints($entryId, $interval, $duration);
             } else {
                 KalturaLog::debug("Media server service not found on DC: [" . $mediaServer->getDc() . "] ");
             }
         }
     }
 }
 public function toObject($object_to_fill = null, $props_to_skip = array())
 {
     $this->validateForUsage($object_to_fill, $props_to_skip);
     $dbUploadToken = UploadTokenPeer::retrieveByPK($this->token);
     if (is_null($dbUploadToken)) {
         throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_NOT_FOUND);
     }
     if (!$object_to_fill) {
         $object_to_fill = new kUploadedFileTokenResource();
     }
     $object_to_fill->setToken($this->token);
     if ($dbUploadToken->getStatus() != UploadToken::UPLOAD_TOKEN_FULL_UPLOAD) {
         $object_to_fill->setIsReady(false);
         return $object_to_fill;
     }
     try {
         $entryFullPath = kUploadTokenMgr::getFullPathByUploadTokenId($this->token);
     } catch (kCoreException $ex) {
         if ($ex->getCode() == kUploadTokenException::UPLOAD_TOKEN_INVALID_STATUS) {
         }
         throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_INVALID_STATUS_FOR_ADD_ENTRY);
         throw $ex;
     }
     if (!file_exists($entryFullPath)) {
         $remoteDCHost = kUploadTokenMgr::getRemoteHostForUploadToken($this->token, kDataCenterMgr::getCurrentDcId());
         if ($remoteDCHost) {
             kFileUtils::dumpApiRequest($remoteDCHost);
         } else {
             throw new KalturaAPIException(KalturaErrors::UPLOADED_FILE_NOT_FOUND_BY_TOKEN);
         }
     }
     $object_to_fill->setLocalFilePath($entryFullPath);
     return $object_to_fill;
 }
 function dumpApiRequest($entryId, $onlyIfAvailable = true)
 {
     $entryDc = substr($entryId, 0, 1);
     if ($entryDc != kDataCenterMgr::getCurrentDcId()) {
         $remoteDCHost = kDataCenterMgr::getRemoteDcExternalUrlByDcId($entryDc);
         kFileUtils::dumpApiRequest($remoteDCHost, $onlyIfAvailable);
     }
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $ui_conf_id = $this->getRequestParameter("ui_conf_id");
     if (!is_numeric($ui_conf_id)) {
         throw new Exception("Illegal Input was supplied");
     }
     $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_{$ui_conf_id}.swf";
     if (!file_exists($preloader_path)) {
         $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_2.swf";
     }
     kFileUtils::dumpFile($preloader_path);
 }
 public function validateForUsage($sourceObject, $propertiesToSkip = array())
 {
     parent::validateForUsage($sourceObject, $propertiesToSkip);
     $dc = $this->getDc();
     if ($dc == kDataCenterMgr::getCurrentDcId()) {
         return;
     }
     $remoteDCHost = kDataCenterMgr::getRemoteDcExternalUrlByDcId($dc);
     if ($remoteDCHost) {
         kFileUtils::dumpApiRequest($remoteDCHost);
     }
     throw new KalturaAPIException(KalturaErrors::REMOTE_DC_NOT_FOUND, $dc);
 }
 /**
  * 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);
     }
 }
Example #8
0
 /**
  * Upload a file using the upload token id, returns an error on failure (an exception will be thrown when using one of the Kaltura clients) 
  * 
  * @action upload
  * @param string $uploadTokenId
  * @param file $fileData
  * @param bool $resume
  * @param bool $finalChunk
  * @param float $resumeAt
  * @return KalturaUploadToken
  */
 function uploadAction($uploadTokenId, $fileData, $resume = false, $finalChunk = true, $resumeAt = -1)
 {
     $this->restrictPeerToCurrentUser();
     $uploadTokenDb = UploadTokenPeer::retrieveByPK($uploadTokenId);
     if (is_null($uploadTokenDb)) {
         throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_NOT_FOUND);
     }
     // if the token was generated on another datacenter, proxy the upload action there
     $remoteDCHost = kUploadTokenMgr::getRemoteHostForUploadToken($uploadTokenId, kDataCenterMgr::getCurrentDcId());
     if ($remoteDCHost) {
         kFileUtils::dumpApiRequest($remoteDCHost);
     }
     $uploadTokenMgr = new kUploadTokenMgr($uploadTokenDb);
     try {
         $uploadTokenMgr->uploadFileToToken($fileData, $resume, $finalChunk, $resumeAt);
     } catch (kUploadTokenException $ex) {
         switch ($ex->getCode()) {
             case kUploadTokenException::UPLOAD_TOKEN_INVALID_STATUS:
                 throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_INVALID_STATUS_FOR_UPLOAD);
             case kUploadTokenException::UPLOAD_TOKEN_FILE_NAME_IS_MISSING_FOR_UPLOADED_FILE:
             case kUploadTokenException::UPLOAD_TOKEN_UPLOAD_ERROR_OCCURRED:
             case kUploadTokenException::UPLOAD_TOKEN_FILE_IS_NOT_VALID:
                 throw new KalturaAPIException(KalturaErrors::UPLOAD_ERROR);
             case kUploadTokenException::UPLOAD_TOKEN_FILE_NOT_FOUND_FOR_RESUME:
                 throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_CANNOT_RESUME);
             case kUploadTokenException::UPLOAD_TOKEN_RESUMING_NOT_ALLOWED:
                 throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_RESUMING_NOT_ALLOWED);
             case kUploadTokenException::UPLOAD_TOKEN_RESUMING_INVALID_POSITION:
                 throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_RESUMING_INVALID_POSITION);
             default:
                 throw $ex;
         }
     }
     $uploadToken = new KalturaUploadToken();
     $uploadToken->fromObject($uploadTokenDb, $this->getResponseProfile());
     return $uploadToken;
 }
Example #9
0
 /**
  * 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)
 }
Example #10
0
 public static function serveFileToRemoteDataCenter($file_sync, $file_hash, $file_name)
 {
     $file_sync_id = $file_sync->getId();
     KalturaLog::log("File sync id [{$file_sync_id}], file_hash [{$file_hash}], file_name [{$file_name}]");
     // TODO - verify security
     $current_dc = self::getCurrentDc();
     $current_dc_id = $current_dc["id"];
     if ($file_sync->getDc() != $current_dc_id) {
         $error = "DC[{$current_dc_id}]: FileSync with id [{$file_sync_id}] does not belong to this DC";
         KalturaLog::err($error);
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY);
     }
     // resolve if file_sync is link
     $file_sync_resolved = $file_sync;
     $file_sync_resolved = kFileSyncUtils::resolve($file_sync);
     // check if file sync path leads to a file or a directory
     $resolvedPath = $file_sync_resolved->getFullPath();
     $fileSyncIsDir = is_dir($resolvedPath);
     if ($fileSyncIsDir && $file_name) {
         $resolvedPath .= '/' . $file_name;
     }
     if (!file_exists($resolvedPath)) {
         $file_name_msg = $file_name ? "file name [{$file_name}] " : '';
         $error = "DC[{$current_dc_id}]: Path for fileSync id [{$file_sync_id}] " . $file_name_msg . "does not exist, resolved path [{$resolvedPath}]";
         KalturaLog::err($error);
         KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
     }
     // validate the hash
     $expected_file_hash = md5($current_dc["secret"] . $file_sync_id);
     // will be verified on the other side to make sure not some attack or external invalid request
     if ($file_hash != $expected_file_hash) {
         $error = "DC[{$current_dc_id}]: FileSync with id [{$file_sync_id}] - invalid hash";
         KalturaLog::err($error);
         KExternalErrors::dieError(KExternalErrors::INVALID_TOKEN);
     }
     if ($fileSyncIsDir && is_dir($resolvedPath)) {
         KalturaLog::log("Serving directory content from [" . $resolvedPath . "]");
         $contents = kFile::listDir($resolvedPath);
         sort($contents, SORT_STRING);
         $contents = serialize($contents);
         header("file-sync-type: dir");
         echo $contents;
         KExternalErrors::dieGracefully();
     } else {
         KalturaLog::log("Serving file from [" . $resolvedPath . "]");
         kFileUtils::dumpFile($resolvedPath);
     }
 }
Example #11
0
<?php

require_once __DIR__ . "/../../bootstrap.php";
KalturaLog::setContext("CLIENTS");
KalturaLog::debug(__FILE__ . " start");
$requestedName = isset($_GET["name"]) ? $_GET['name'] : null;
if (!$requestedName) {
    die("File not found");
}
$generatorOutputPath = KAutoloader::buildPath(KALTURA_ROOT_PATH, "generator", "output");
$generatorConfigPath = KAutoloader::buildPath(KALTURA_ROOT_PATH, "generator", "config.ini");
$config = new Zend_Config_Ini($generatorConfigPath);
foreach ($config as $name => $item) {
    if ($name === $requestedName && $item->get("public-download")) {
        $fileName = $name . ".tar.gz";
        $outputFilePath = KAutoloader::buildPath($generatorOutputPath, $fileName);
        $outputFilePath = realpath($outputFilePath);
        header("Content-disposition: attachment; filename={$fileName}");
        kFileUtils::dumpFile($outputFilePath, "application/gzip");
        die;
    }
}
die("File not found");
KalturaLog::debug(__FILE__ . " end");
 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 getCaseDiagram($caseId, $filename)
 {
     kFileUtils::fullMkdir($filename);
     file_put_contents($filename, $this->client->processInstances->getDiagramForProcessInstance($caseId));
 }
 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();
 }
Example #15
0
 /**
  * @action generate
  * @param string $entryId
  * @param KalturaThumbParams $thumbParams
  * @param string $sourceAssetId id of the source asset (flavor or thumbnail) to be used as source for the thumbnail generation
  * @return KalturaThumbAsset
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @throws KalturaErrors::ENTRY_TYPE_NOT_SUPPORTED
  * @throws KalturaErrors::ENTRY_MEDIA_TYPE_NOT_SUPPORTED
  * @throws KalturaErrors::THUMB_ASSET_PARAMS_ID_NOT_FOUND
  * @throws KalturaErrors::INVALID_ENTRY_STATUS
  * @throws KalturaErrors::THUMB_ASSET_IS_NOT_READY
  * @validateUser entry entryId edit
  */
 public function generateAction($entryId, KalturaThumbParams $thumbParams, $sourceAssetId = null)
 {
     $entry = entryPeer::retrieveByPK($entryId);
     if (!$entry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     if (!in_array($entry->getType(), $this->getEnabledMediaTypes())) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_TYPE_NOT_SUPPORTED, $entry->getType());
     }
     if ($entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_VIDEO) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_MEDIA_TYPE_NOT_SUPPORTED, $entry->getMediaType());
     }
     $validStatuses = array(entryStatus::ERROR_CONVERTING, entryStatus::PRECONVERT, entryStatus::READY);
     if (!in_array($entry->getStatus(), $validStatuses)) {
         throw new KalturaAPIException(KalturaErrors::INVALID_ENTRY_STATUS);
     }
     $destThumbParams = new thumbParams();
     $thumbParams->toUpdatableObject($destThumbParams);
     $srcAsset = kBusinessPreConvertDL::getSourceAssetForGenerateThumbnail($sourceAssetId, $destThumbParams->getSourceParamsId(), $entryId);
     if (is_null($srcAsset)) {
         throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_IS_NOT_READY);
     }
     $sourceFileSyncKey = $srcAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($sourceFileSyncKey, true);
     /* @var $fileSync FileSync */
     if (is_null($fileSync)) {
         throw new KalturaAPIException(KalturaErrors::THUMB_ASSET_IS_NOT_READY);
     }
     if ($fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) {
         throw new KalturaAPIException(KalturaErrors::SOURCE_FILE_REMOTE);
     }
     if (!$local) {
         kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrl($fileSync));
     }
     $dbThumbAsset = kBusinessPreConvertDL::decideThumbGenerate($entry, $destThumbParams, null, $sourceAssetId, true, $srcAsset);
     if (!$dbThumbAsset) {
         return null;
     }
     $thumbAsset = new KalturaThumbAsset();
     $thumbAsset->fromObject($dbThumbAsset, $this->getResponseProfile());
     return $thumbAsset;
 }
Example #16
0
 /**
 Will allow creation of multiple entries
 ASSUME - the prefix of the entries is entryX_ where X is the index starting at 1
 */
 public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser)
 {
     //        $logger = sfLogger::getInstance();
     self::$escape_text = true;
     /*		if ( !$puser_kuser )
             {
                 $this->addError( "No such user ..." );
                 return;
     
             }
         */
     // TODO - validate if the user can add entries to this kshow
     $kshow_id = $this->getP("kshow_id");
     $show_entry_id = $this->getP("show_entry_id");
     $conversion_quality = $this->getP("conversionquality");
     // must be all lower case
     // for now - by default use quick_edit
     $partner = PartnerPeer::retrieveByPK($partner_id);
     for ($i = 0; $i <= $partner->getAddEntryMaxFiles(); ++$i) {
         if ($i == 0) {
             $prefix = $this->getObjectPrefix() . "_";
         } else {
             $prefix = $this->getObjectPrefix() . "{$i}" . "_";
         }
         $source = $this->getP($prefix . "source");
         $filename = $this->getP($prefix . "filename");
         if ($source != entry::ENTRY_MEDIA_SOURCE_WEBCAM || !$filename) {
             continue;
         }
         $content = myContentStorage::getFSContentRootPath();
         $entryFullPath = "{$content}/content/webcam/{$filename}.flv";
         if (!file_exists($entryFullPath)) {
             $remoteDCHost = kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId());
             if ($remoteDCHost) {
                 kFileUtils::dumpApiRequest($remoteDCHost);
             }
             $this->addError(APIErrors::INVALID_FILE_NAME, $filename);
             return;
         }
     }
     if (strpos($kshow_id, 'entry-') !== false && !$show_entry_id) {
         $show_entry_id = substr($kshow_id, 6);
     }
     $screen_name = $this->getP("screen_name");
     $site_url = $this->getP("site_url");
     $null_kshow = true;
     if ($show_entry_id) {
         // in this case we have the show_entry_id (of the relevant roughcut) - it suppresses the kshow_id
         $show_entry = entryPeer::retrieveByPK($show_entry_id);
         if ($show_entry) {
             $kshow_id = $show_entry->getKshowId();
         } else {
             $kshow_id = null;
         }
     }
     if ($kshow_id === kshow::SANDBOX_ID) {
         $this->addError(APIErrors::SANDBOX_ALERT);
         return;
     }
     $default_kshow_name = $this->getP("entry_name", null);
     if (!$default_kshow_name) {
         $default_kshow_name = $this->getP("entry1_name", null);
     }
     if ($kshow_id == kshow::KSHOW_ID_USE_DEFAULT) {
         // see if the partner has some default kshow to add to
         $kshow = myPartnerUtils::getDefaultKshow($partner_id, $subp_id, $puser_kuser, null, false, $default_kshow_name);
         $null_kshow = false;
         if ($kshow) {
             $kshow_id = $kshow->getId();
         }
     } elseif ($kshow_id == kshow::KSHOW_ID_CREATE_NEW) {
         // if the partner allows - create a new kshow
         $kshow = myPartnerUtils::getDefaultKshow($partner_id, $subp_id, $puser_kuser, null, true, $default_kshow_name);
         $null_kshow = false;
         if ($kshow) {
             $kshow_id = $kshow->getId();
         }
     } else {
         $kshow = kshowPeer::retrieveByPK($kshow_id);
     }
     if (!$kshow) {
         // the partner is attempting to add an entry to some invalid or non-existing kwho
         $this->addError(APIErrors::INVALID_KSHOW_ID, $kshow_id);
         return;
     }
     // find permissions from kshow
     $permissions = $kshow->getPermissions();
     $kuser_id = $puser_kuser->getKuserId();
     // TODO - once the CW
     $quick_edit = myPolicyMgr::getPolicyFor("allowQuickEdit", $kshow, $partner);
     // let the user override the quick_edit propery
     if ($this->getP("quick_edit") == '0' || $this->getP("quick_edit") == "false") {
         $quick_edit = false;
     }
     if ($quick_edit == '0' || $quick_edit === "false" || !$quick_edit || $quick_edit == false) {
         KalturaLog::err('$quick_edit: [' . $quick_edit . ']');
         $quick_edit = false;
         //$quick_edit = true;
     }
     // works in one of 2 ways:
     // 1. get no requested name - will create a new kshow and return its details
     // 2. get some name - tries to fetch by name. if already exists - return it
     $new_entry_count = 0;
     $entries = array();
     $notification_ids = array();
     $notifications = array();
     $field_level = $this->isAdmin() ? 2 : 1;
     $updateable_fields = null;
     $imported_entries_count = 0;
     for ($i = 0; $i <= $partner->getAddEntryMaxFiles(); ++$i) {
         if ($i == 0) {
             $prefix = $this->getObjectPrefix() . "_";
         } else {
             $prefix = $this->getObjectPrefix() . "{$i}" . "_";
         }
         $file_name = $this->getP($prefix . "realFilename");
         if (!($this->getP($prefix . "name") || $file_name)) {
             continue;
         }
         // get the new properties for the kuser from the request
         $entry = new entry();
         $obj_wrapper = objectWrapperBase::getWrapperClass($entry, 0);
         if (!$updateable_fields) {
             $updateable_fields = $obj_wrapper->getUpdateableFields($field_level);
         }
         // fill the entry from request
         $fields_modified = baseObjectUtils::fillObjectFromMap($this->getInputParams(), $entry, $prefix, $updateable_fields);
         // check that mandatory fields were set
         // TODO
         KalturaLog::err("addentry: fields_modified: " . print_r($fields_modified, true));
         $entry_source = $entry->getSource();
         if (!$entry->getType()) {
             // this is the default for backward compatiblity
             $entry->setType(entryType::MEDIA_CLIP);
         }
         $token = $this->getKsUniqueString();
         $entry_full_path = "";
         if ($entry_source == entry::ENTRY_MEDIA_SOURCE_FILE) {
             $entry->setSourceLink($file_name);
             $file_alias = $this->getP($prefix . "filename");
             $file_extension = strtolower(pathinfo($this->getP($prefix . "realFilename"), PATHINFO_EXTENSION));
             $entry_full_path = myUploadUtils::getUploadPath($token, $file_alias, null, $file_extension);
             if (!file_exists($entry_full_path)) {
                 KalturaLog::err("Invalid UPLOAD PATH [" . $entry_full_path . "] while trying to add entry for partner id [" . $partner_id . "] with token [" . $token . "] & original name [" . $this->getP($prefix . "name") . "]");
                 $this->addError(APIErrors::INVALID_FILE_NAME);
                 continue;
             }
             myEntryUtils::setEntryTypeAndMediaTypeFromFile($entry, $entry_full_path);
         }
         //            No reason to rais the error
         //            Remarked by Tan-Tan
         //
         //            // when we reached this point the type and media type must be set
         //            if ($entry->getType() == entryType::AUTOMATIC || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUTOMATIC)
         //            {
         //				$this->addError ( APIErrors::CANNOT_USE_ENTRY_TYPE_AUTO_IN_IMPORT );
         //            	continue;
         //            }
         // limit two kinds of media
         // 1. not images - video/audio which are big files
         // 2. media which wasnt directly uploaded by the owner (the owner real content)
         if ($entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_IMAGE && $entry_source != entry::ENTRY_MEDIA_SOURCE_FILE) {
             if ($imported_entries_count >= 4) {
                 continue;
             }
             ++$imported_entries_count;
         }
         // the conversion_quality is set once for the whole list of entries
         if ($conversion_quality) {
             $entry->setConversionQuality($conversion_quality);
         } else {
             // HACK - if the conversion_quality was not set in the proper way -
             // see if the partner_data holds a hack - string that starts with conversionQuality= - this is set when the CW is opened in the KMC
             // the conversionQuality is of format conversionQuality=XXX;<the rest of the text>
             //
             if (kString::beginsWith($entry->getPartnerData(), "conversionQuality:")) {
                 $partner_data_arr = explode(";", $entry->getPartnerData(), 2);
                 $conversion_quality_arr = explode(":", $partner_data_arr[0]);
                 $conversion_quality = @$conversion_quality_arr[1];
                 // the value of the conversion_quality
                 $entry->setPartnerData(@$partner_data_arr[1]);
                 // the rest of the string
                 $entry->setConversionQuality($conversion_quality);
             }
         }
         $insert = true;
         $entry_modified = false;
         $create_entry = true;
         // I don't remember why we set the kshow to null every time ...
         // but when we fetched it automatically - hang on to it !
         if ($null_kshow) {
             $kshow = null;
         }
         if ($entry_source == entry::ENTRY_MEDIA_SOURCE_KALTURA_USER_CLIPS || $entry_source == "100") {
             if ($entry_source == "100") {
                 $entry_id = $this->getP("media{$i}_id");
             } else {
                 $entry_id = $this->getP($prefix . "id");
             }
             // $this->getP ( $prefix . "url" );
             if ($entry_id === null) {
                 $entry_id = $entry->getMediaId();
             }
             if ($entry_id) {
                 $entry = entryPeer::retrieveByPK($entry_id);
                 if ($entry) {
                     $create_entry = false;
                     $insert = false;
                 } else {
                     $this->addError(APIErrors::INVALID_ENTRY_ID, $this->getObjectPrefix(), $entry_id);
                     return;
                 }
             }
         }
         $new_entry_count++;
         if ($create_entry) {
             $entry->setPartnerId($partner_id);
             $entry->setSubpId($subp_id);
             $entry->setKuserId($kuser_id);
             $entry->setCreatorKuserId($kuser_id);
             $entry->setKshowId($kshow_id);
             $entry->setSiteUrl($site_url);
             $entry->setScreenName($screen_name);
             if ($this->getGroup()) {
                 $entry->setGroupId($this->getGroup());
             }
             if ($entry->getPermissions() === null) {
                 $entry->setPermissions($permissions);
             }
             // inherited from the enclosing kshow
             $entry->setDefaultModerationStatus();
             $entry->save();
             $entry_modified = true;
             if (!$entry->getName()) {
                 if ($file_name) {
                     // TODO - fix the file_name to fit
                     $entry->setName($file_name);
                 } else {
                     $entry->setName($partner_prefix . $entry->getId());
                 }
                 $entry_modified = true;
             }
             // TODO - decide on file naming mechanism !!
             // there are 3 types of insert:
             // 1. upload - the file is assumed to be in the upload directory and it's name is explicitly set in the fname$i param
             // 2. webcam - the file is assumed to be in the webcam directory and it's name is explicitly set in the fname$i param
             // 3. URL - the url is given in the entry_url$i param
             /*
                         $media_source = $this->getParam('entry_media_source');
                         $media_type = $this->getParam('entry_media_type');
                         $entry_url = $this->getParam('entry_url');
                         $entry_source_link = $this->getParam('entry_source_link');
                         $entry_fileName = $this->getParam('entry_data');
                         $entry_thumbNum = $this->getParam('entry_thumb_num', 0);
                         $entry_thumbUrl  = $this->getParam('entry_thumb_url', '');
                         $entry_from_time  = $this->getParam('entry_from_time', 0);
                         $entry_to_time  = $this->getParam('entry_to_time', 0);
             
                         $should_copy = $this->getParam('should_copy' , false );
                         $skip_conversion = $this->getParam('skip_conversion' , false );
             */
             $paramsArray = array('entry_media_source' => $entry->getSource(), 'entry_media_type' => $entry->getMediaType());
             //			$entry_source = $entry->getSource() ;
             if ($entry_source == entry::ENTRY_MEDIA_SOURCE_FILE) {
                 $paramsArray["entry_full_path"] = $entry_full_path;
             } elseif ($entry_source == entry::ENTRY_MEDIA_SOURCE_WEBCAM) {
                 $file_alias = $this->getP($prefix . "filename");
                 $paramsArray["webcam_suffix"] = $file_alias;
                 $paramsArray['entry_from_time'] = $this->getP($prefix . "fromTime", 0);
                 $paramsArray['entry_to_time'] = $this->getP($prefix . "toTime", 0);
             } elseif ($entry_source == entry::ENTRY_MEDIA_SOURCE_KALTURA || $entry_source == entry::ENTRY_MEDIA_SOURCE_KALTURA_PARTNER || $entry_source == entry::ENTRY_MEDIA_SOURCE_KALTURA_PARTNER_KSHOW || $entry_source == entry::ENTRY_MEDIA_SOURCE_KALTURA_KSHOW || $entry_source == entry::ENTRY_MEDIA_SOURCE_KALTURA_USER_CLIPS) {
                 // optimize - no need to actually go through the import and conversion phase
                 // find the source entry_id from the url
                 /*
                                     $entry_url = $this->getP ( $prefix . "url" );
                                     $entry_thumb_url = $this->getP ( $prefix .  "thumbUrl" );
                 
                                     if ( myEntryUtils::copyData( $entry_url , $entry_thumb_url , $entry ) )
                 */
                 $source_entry_id = $this->getP("media{$i}_id");
                 // $this->getP ( $prefix . "url" );
                 if ($source_entry_id === null) {
                     $source_entry_id = $entry->getMediaId();
                 }
                 if (myEntryUtils::copyData($source_entry_id, $entry)) {
                     // copy worked ok - no need to use insertEntryHelper
                     //$entry->setStatus ( entryStatus::READY );
                     // force the data to be ready even if the policy is to moderate - this is kaltura's content and was already approved
                     // (roman) true argument removed, so kaltura's content will be moderated according to partner's moderation settings
                     $entry->setStatusReady();
                     $insert = false;
                     $entry_modified = true;
                     $entry->save();
                 }
             } elseif ($entry_source == entry::ENTRY_MEDIA_SOURCE_URL || in_array($entry_source, myMediaSourceFactory::getAllMediaSourceProvidersIds())) {
                 // the URL is relevant
                 $paramsArray["entry_url"] = $this->getP($prefix . "url");
                 $paramsArray["entry_thumb_url"] = $this->getP($prefix . "thumbUrl");
                 // TODO - these fields are already set in the entry -
                 // the code in myInsertEntryHelper is redundant
                 $paramsArray["entry_license"] = $entry->getLicenseType();
                 $paramsArray["entry_credit"] = $entry->getCredit();
                 $paramsArray["entry_source_link"] = $entry->getSourceLink();
                 $paramsArray["entry_tags"] = $entry->getTags();
             } else {
                 $this->addError(APIErrors::UNKNOWN_MEDIA_SOURCE, $entry->getSource());
                 $insert = false;
             }
             if ($insert) {
                 KalturaLog::err("paramsArray" . print_r($paramsArray, true));
                 $insert_entry_helper = new myInsertEntryHelper($this, $kuser_id, $kshow_id, $paramsArray);
                 $insert_entry_helper->setPartnerId($partner_id, $subp_id);
                 $insert_entry_helper->insertEntry($token, $entry->getType(), $entry->getId(), $entry->getName(), $entry->getTags(), $entry);
                 $insert_entry_helper->getEntry();
                 $this->addDebug("added_entry{$i}", $entry->getName());
             }
         }
         // create_entry = true
         KalturaLog::err('id: ' . $entry->getId() . ' $quick_edit:' . $quick_edit);
         if ($quick_edit) {
             KalturaLog::info("quick edit with kshow_id [{$kshow_id}]");
             if (!$kshow) {
                 $kshow = kshowPeer::retrieveByPK($kshow_id);
             }
             // this i
             if (!$kshow) {
                 // BAD - this shount not be !
                 $this->addError(APIErrors::INVALID_KSHOW_ID, $kshow_id);
                 return;
             }
             $metadata = $kshow->getMetadata();
             if ($metadata !== null) {
                 KalturaLog::info("Having metadata");
                 $relevant_kshow_version = 1 + $kshow->getVersion();
                 // the next metadata will be the first relevant version for this new entry
                 $version_info = array();
                 $version_info["KuserId"] = $puser_kuser->getKuserId();
                 $version_info["PuserId"] = $puser_id;
                 $version_info["ScreenName"] = $puser_kuser->getPuserName();
                 $new_metadata = myMetadataUtils::addEntryToMetadata($metadata, $entry, $relevant_kshow_version, $version_info);
                 $entry_modified = true;
                 if ($new_metadata) {
                     // TODO - add thumbnail only for entries that are worthy - check they are not moderated !
                     $thumb_modified = myKshowUtils::updateThumbnail($kshow, $entry, false);
                     if ($thumb_modified) {
                         $new_metadata = myMetadataUtils::updateThumbUrlFromMetadata($new_metadata, $entry->getThumbnailUrl());
                     }
                     // it is very important to increment the version count because even if the entry is deferred
                     // it will be added on the next version
                     if (!$kshow->getHasRoughcut()) {
                         // make sure the kshow now does have a roughcut
                         $kshow->setHasRoughcut(true);
                         $kshow->save();
                     }
                     $kshow->setMetadata($new_metadata, true);
                 }
                 // no need to save kshow - the modification of the metadata was done to the show_entry which will propagate any chages to the kshow in it's own save method
             }
         }
         if ($entry_modified) {
             $entry->save();
         }
         $not_id = null;
         // send a synch notification
         @(list($not_id, $not, $url, $params, $serialized_params) = myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_ADD, $entry, null, null));
         if ($not_id) {
             $notification_ids[] = $not_id;
             $notifications[] = array("url" => $url, "params" => $serialized_params);
         }
         $wrapper = objectWrapperBase::getWrapperClass($entry, objectWrapperBase::DETAIL_LEVEL_REGULAR);
         $entries[$prefix] = $wrapper;
         //$this->addMsg ( $prefix , $wrapper);
         // because the kshow's entrys field was changes do to this update, we have to remove object from cahce
         // TODO - think of some reverse way to automatically remove from the cache from within the wrapper
         // call some - update cache where the kshow_id plays a part in the update
         $wrapper->removeFromCache("kshow", $kshow_id, "entrys");
         $this->addDebug("added_fields", $fields_modified, $prefix);
     }
     $this->addMsg("entries", $entries);
     if (count($notification_ids) > 0) {
         $this->addMsg("notifications", $notifications);
     }
     if ($new_entry_count < 1) {
         $this->addError(APIErrors::NO_ENTRIES_ADDED);
         $this->addDebug("no_new_entries", "You have to have at least one new entry with a field called 'entry1_name'");
     }
     $this->addMsg("new_entry_count", $new_entry_count);
 }
Example #17
0
 /**
  * @param UploadToken $uploadToken
  */
 public static function handleUploadFinished(UploadToken $uploadToken)
 {
     if (!is_subclass_of($uploadToken->getObjectType(), assetPeer::OM_CLASS) && $uploadToken->getObjectType() != FileAssetPeer::OM_CLASS && $uploadToken->getObjectType() != entryPeer::OM_CLASS) {
         KalturaLog::info("Class [" . $uploadToken->getObjectType() . "] not supported");
         return;
     }
     $fullPath = kUploadTokenMgr::getFullPathByUploadTokenId($uploadToken->getId());
     if (!file_exists($fullPath)) {
         KalturaLog::info("File path [{$fullPath}] not found");
         $remoteDCHost = kUploadTokenMgr::getRemoteHostForUploadToken($uploadToken->getId(), kDataCenterMgr::getCurrentDcId());
         if (!$remoteDCHost) {
             KalturaLog::err("File path [{$fullPath}] could not be redirected");
             return;
         }
         kFileUtils::dumpApiRequest($remoteDCHost);
     }
     if ($uploadToken->getObjectType() == FileAssetPeer::OM_CLASS) {
         $dbFileAsset = FileAssetPeer::retrieveByPK($uploadToken->getObjectId());
         if (!$dbFileAsset) {
             KalturaLog::err("File asset id [" . $uploadToken->getObjectId() . "] not found");
             return;
         }
         if (!$dbFileAsset->getFileExt()) {
             $dbFileAsset->setFileExt(pathinfo($fullPath, PATHINFO_EXTENSION));
         }
         $dbFileAsset->incrementVersion();
         $dbFileAsset->save();
         $syncKey = $dbFileAsset->getSyncKey(FileAsset::FILE_SYNC_ASSET);
         try {
             kFileSyncUtils::moveFromFile($fullPath, $syncKey, true);
         } catch (Exception $e) {
             $dbFileAsset->setStatus(FileAssetStatus::ERROR);
             $dbFileAsset->save();
             throw $e;
         }
         if ($dbFileAsset->getStatus() == FileAssetStatus::UPLOADING) {
             $finalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
             $dbFileAsset->setSize(kFile::fileSize($finalPath));
             $dbFileAsset->setStatus(FileAssetStatus::READY);
             $dbFileAsset->save();
         }
         $uploadToken->setStatus(UploadToken::UPLOAD_TOKEN_CLOSED);
         $uploadToken->save();
         KalturaLog::info("File asset [" . $dbFileAsset->getId() . "] handled");
         return;
     }
     if (is_subclass_of($uploadToken->getObjectType(), assetPeer::OM_CLASS)) {
         $dbAsset = assetPeer::retrieveById($uploadToken->getObjectId());
         if (!$dbAsset) {
             KalturaLog::err("Asset id [" . $uploadToken->getObjectId() . "] not found");
             return;
         }
         $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
         $dbAsset->setFileExt($ext);
         $dbAsset->incrementVersion();
         $dbAsset->save();
         $syncKey = $dbAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         try {
             kFileSyncUtils::moveFromFile($fullPath, $syncKey, true);
         } catch (Exception $e) {
             if ($dbAsset instanceof flavorAsset) {
                 kBatchManager::updateEntry($dbAsset->getEntryId(), entryStatus::ERROR_IMPORTING);
             }
             $dbAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
             $dbAsset->save();
             throw $e;
         }
         if ($dbAsset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_IMPORTING) {
             $finalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
             $dbAsset->setSize(kFile::fileSize($finalPath));
             if ($dbAsset instanceof flavorAsset) {
                 if ($dbAsset->getIsOriginal()) {
                     $dbAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_QUEUED);
                 } else {
                     $dbAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_VALIDATING);
                 }
             } else {
                 $dbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_READY);
             }
             if ($dbAsset instanceof thumbAsset) {
                 list($width, $height, $type, $attr) = getimagesize($finalPath);
                 $dbAsset->setWidth($width);
                 $dbAsset->setHeight($height);
             }
             $dbAsset->save();
             kEventsManager::raiseEvent(new kObjectAddedEvent($dbAsset));
         }
         $uploadToken->setStatus(UploadToken::UPLOAD_TOKEN_CLOSED);
         $uploadToken->save();
     }
     if ($uploadToken->getObjectType() == entryPeer::OM_CLASS) {
         $dbEntry = entryPeer::retrieveByPK($uploadToken->getObjectId());
         if (!$dbEntry) {
             KalturaLog::err("Entry id [" . $uploadToken->getObjectId() . "] not found");
             return;
         }
         //Keep original extention
         $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
         // increments version
         $dbEntry->setData('100000.' . $ext);
         $dbEntry->save();
         $syncKey = $dbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         try {
             kFileSyncUtils::moveFromFile($fullPath, $syncKey, true);
         } catch (Exception $e) {
             if ($dbAsset instanceof flavorAsset) {
                 kBatchManager::updateEntry($dbEntry->getId(), entryStatus::ERROR_IMPORTING);
             }
             throw $e;
         }
         $dbEntry->setStatus(entryStatus::READY);
         $dbEntry->save();
         $uploadToken->setStatus(UploadToken::UPLOAD_TOKEN_CLOSED);
         $uploadToken->save();
     }
 }
Example #18
0
 /**
  * @param ISyncableFile $syncable
  * @param int $fileSubType
  * @param string $fileName
  * @param bool $forceProxy
  * @throws KalturaErrors::FILE_DOESNT_EXIST
  */
 protected function serveFile(ISyncableFile $syncable, $fileSubType, $fileName, $entryId = null, $forceProxy = false)
 {
     /* @var $fileSync FileSync */
     $syncKey = $syncable->getSyncKey($fileSubType);
     if (!kFileSyncUtils::fileSync_exists($syncKey)) {
         throw new KalturaAPIException(KalturaErrors::FILE_DOESNT_EXIST);
     }
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
     if ($local) {
         $filePath = $fileSync->getFullPath();
         $mimeType = kFile::mimeType($filePath);
         return $this->dumpFile($filePath, $mimeType);
     } else {
         if (in_array($fileSync->getDc(), kDataCenterMgr::getDcIds())) {
             $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
             KalturaLog::info("Redirecting to [{$remoteUrl}]");
             if ($forceProxy) {
                 kFileUtils::dumpApiRequest($remoteUrl);
             } else {
                 //TODO find or build function which redurects the API request with all its parameters without using curl.
                 // or redirect if no proxy
                 header("Location: {$remoteUrl}");
                 die;
             }
         } else {
             $remoteUrl = $fileSync->getExternalUrl($entryId);
             header("Location: {$remoteUrl}");
             die;
         }
     }
 }
Example #19
0
 /**
  * Add and convert new Flavor Asset for Entry with specific Flavor Params
  * 
  * @action convert
  * @param string $entryId
  * @param int $flavorParamsId
  * @param int $priority
  * @validateUser entry entryId edit
  */
 public function convertAction($entryId, $flavorParamsId, $priority = 0)
 {
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $flavorParamsDb = assetParamsPeer::retrieveByPK($flavorParamsId);
     assetParamsPeer::setUseCriteriaFilter(false);
     if (!$flavorParamsDb) {
         throw new KalturaAPIException(KalturaErrors::FLAVOR_PARAMS_ID_NOT_FOUND, $flavorParamsId);
     }
     $validStatuses = array(entryStatus::ERROR_CONVERTING, entryStatus::PRECONVERT, entryStatus::READY);
     if (!in_array($dbEntry->getStatus(), $validStatuses)) {
         throw new KalturaAPIException(KalturaErrors::INVALID_ENTRY_STATUS);
     }
     $conversionProfile = $dbEntry->getconversionProfile2();
     if (!$conversionProfile) {
         throw new KalturaAPIException(KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND, $dbEntry->getConversionProfileId());
     }
     $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($entryId);
     if (is_null($originalFlavorAsset) || !$originalFlavorAsset->isLocalReadyStatus()) {
         throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING);
     }
     $srcSyncKey = $originalFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     // if the file sync isn't local (wasn't synced yet) proxy request to other datacenter
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($srcSyncKey, true, false);
     /* @var $fileSync FileSync */
     if (!$fileSync) {
         throw new KalturaAPIException(KalturaErrors::FILE_DOESNT_EXIST);
     }
     if (!$local && $fileSync->getFileType() != FileSync::FILE_SYNC_FILE_TYPE_URL) {
         kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrl($fileSync));
     }
     $err = "";
     $dynamicFlavorAttributes = $dbEntry->getDynamicFlavorAttributesForAssetParams($flavorParamsDb->getId());
     kBusinessPreConvertDL::decideAddEntryFlavor(null, $dbEntry->getId(), $flavorParamsId, $err, null, $dynamicFlavorAttributes, $priority);
 }
 /**
  * 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();
 }
Example #21
0
 private function dumpFile($file_path, $file_name, $limit_file_size = 0)
 {
     $file_name = str_replace("\n", ' ', $file_name);
     $relocate = $this->getRequestParameter("relocate");
     $directServe = $this->getRequestParameter("direct_serve");
     if (!$relocate) {
         $url = $_SERVER["REQUEST_URI"];
         if (strpos($url, "?") !== false) {
             $url .= "&relocate=";
         } else {
             $url .= "/relocate/";
         }
         $url .= kString::stripInvalidUrlChars($file_name);
         kFile::cacheRedirect($url);
         header("Location: {$url}");
         KExternalErrors::dieGracefully();
     } else {
         if (!$directServe) {
             header("Content-Disposition: attachment; filename=\"{$file_name}\"");
         }
         $mime_type = kFile::mimeType($file_path);
         kFileUtils::dumpFile($file_path, $mime_type, null, $limit_file_size);
     }
 }
Example #22
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;
         }
     }
 }
Example #23
0
 /**
  * Update media entry. Only the properties that were set will be updated.
  *
  * @action update
  * @param string $entryId Media entry id to update
  * @param KalturaMediaEntry $mediaEntry Media entry metadata to update
  * @return KalturaMediaEntry The updated media entry
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @validateUser entry entryId edit
  */
 function updateAction($entryId, KalturaMediaEntry $mediaEntry)
 {
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry) {
         $dcIndex = kDataCenterMgr::getDCByObjectId($entryId, true);
         if ($dcIndex != kDataCenterMgr::getCurrentDcId()) {
             KalturaLog::debug("EntryID [{$entryId}] wasn't found on current DC. dumping the request to DC id [{$dcIndex}]");
             kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId($dcIndex));
         }
     }
     if (!$dbEntry || $dbEntry->getType() != KalturaEntryType::MEDIA_CLIP) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $mediaEntry = $this->updateEntry($entryId, $mediaEntry, KalturaEntryType::MEDIA_CLIP);
     return $mediaEntry;
 }
Example #24
0
 /**
  *
  * Will serve a requested report
  * @action serveReport
  *
  *
  * @param string $id - the requested id
  * @return string
  */
 public function serveReportAction($id)
 {
     $fileNameRegex = "/^(?<dc>[01]+)_(?<fileName>\\d+_Export_[a-zA-Z0-9]+_[\\w\\-]+.csv)\$/";
     // KS verification - we accept either admin session or download privilege of the file
     $ks = $this->getKs();
     if (!$ks || !($ks->isAdmin() || $ks->verifyPrivileges(ks::PRIVILEGE_DOWNLOAD, $id))) {
         KExternalErrors::dieError(KExternalErrors::ACCESS_CONTROL_RESTRICTED);
     }
     if (!preg_match($fileNameRegex, $id, $matches)) {
         KalturaLog::err("Report Id Format doesn't match the file name format");
         throw new KalturaAPIException(KalturaErrors::REPORT_NOT_FOUND, $id);
     }
     // Check if the request should be handled by the other DC
     $curerntDc = kDataCenterMgr::getCurrentDcId();
     if ($matches['dc'] == 1 - $curerntDc) {
         kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - $curerntDc));
     }
     // Serve report
     $filePath = $this->getReportDirectory($this->getPartnerId()) . DIRECTORY_SEPARATOR . $matches['fileName'];
     return $this->dumpFile($filePath, 'text/csv');
 }
Example #25
0
 /**
  * Convert entry
  * 
  * @param string $entryId Media entry id
  * @param int $conversionProfileId
  * @param KalturaConversionAttributeArray $dynamicConversionAttributes
  * @return bigint job id
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @throws KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND
  * @throws KalturaErrors::FLAVOR_PARAMS_NOT_FOUND
  */
 protected function convert($entryId, $conversionProfileId = null, KalturaConversionAttributeArray $dynamicConversionAttributes = null)
 {
     $entry = entryPeer::retrieveByPK($entryId);
     if (!$entry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $srcFlavorAsset = assetPeer::retrieveOriginalByEntryId($entryId);
     if (!$srcFlavorAsset) {
         throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING);
     }
     if (is_null($conversionProfileId) || $conversionProfileId <= 0) {
         $conversionProfile = myPartnerUtils::getConversionProfile2ForEntry($entryId);
         if (!$conversionProfile) {
             throw new KalturaAPIException(KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND, $conversionProfileId);
         }
         $conversionProfileId = $conversionProfile->getId();
     } else {
         //The search is with the entry's partnerId. so if conversion profile wasn't found it means that the
         //conversionId is not exist or the conversion profileId does'nt belong to this partner.
         $conversionProfile = conversionProfile2Peer::retrieveByPK($conversionProfileId);
         if (is_null($conversionProfile)) {
             throw new KalturaAPIException(KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND, $conversionProfileId);
         }
     }
     $srcSyncKey = $srcFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     // if the file sync isn't local (wasn't synced yet) proxy request to other datacenter
     list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($srcSyncKey, true, false);
     if (!$fileSync) {
         throw new KalturaAPIException(KalturaErrors::FILE_DOESNT_EXIST);
     } else {
         if (!$local) {
             kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrl($fileSync));
         }
     }
     // even if it null
     $entry->setConversionQuality($conversionProfileId);
     $entry->save();
     if ($dynamicConversionAttributes) {
         $flavors = assetParamsPeer::retrieveByProfile($conversionProfileId);
         if (!count($flavors)) {
             throw new KalturaAPIException(KalturaErrors::FLAVOR_PARAMS_NOT_FOUND);
         }
         $srcFlavorParamsId = null;
         $flavorParams = $entry->getDynamicFlavorAttributes();
         foreach ($flavors as $flavor) {
             if ($flavor->hasTag(flavorParams::TAG_SOURCE)) {
                 $srcFlavorParamsId = $flavor->getId();
             }
             $flavorParams[$flavor->getId()] = $flavor;
         }
         $dynamicAttributes = array();
         foreach ($dynamicConversionAttributes as $dynamicConversionAttribute) {
             if (is_null($dynamicConversionAttribute->flavorParamsId)) {
                 $dynamicConversionAttribute->flavorParamsId = $srcFlavorParamsId;
             }
             if (is_null($dynamicConversionAttribute->flavorParamsId)) {
                 continue;
             }
             $dynamicAttributes[$dynamicConversionAttribute->flavorParamsId][trim($dynamicConversionAttribute->name)] = trim($dynamicConversionAttribute->value);
         }
         if (count($dynamicAttributes)) {
             $entry->setDynamicFlavorAttributes($dynamicAttributes);
             $entry->save();
         }
     }
     $srcFilePath = kFileSyncUtils::getLocalFilePathForKey($srcSyncKey);
     $job = kJobsManager::addConvertProfileJob(null, $entry, $srcFlavorAsset->getId(), $srcFilePath);
     if (!$job) {
         return null;
     }
     return $job->getId();
 }
 public function execute()
 {
     requestUtils::handleConditionalGet();
     $entry_id = $this->getRequestParameter("entry_id");
     $ks_str = $this->getRequestParameter("ks");
     $base64_referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64_referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $clip_from = $this->getRequestParameter("clip_from", 0);
     // milliseconds
     $clip_to = $this->getRequestParameter("clip_to", 2147483647);
     // milliseconds
     if ($clip_to == 0) {
         $clip_to = 2147483647;
     }
     $request = $_SERVER["REQUEST_URI"];
     // remove dynamic fields from the url so we'll request a single url from the cdn
     $request = str_replace("/referrer/{$base64_referrer}", "", $request);
     $request = str_replace("/ks/{$ks_str}", "", $request);
     $entry = null;
     if ($ks_str) {
         try {
             kCurrentContext::initKsPartnerUser($ks_str);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entry_id);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     // workaround the filter which hides all the deleted entries -
     // now that deleted entries are part of xmls (they simply point to the 'deleted' templates), we should allow them here
     if (!$entry) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     if (!$entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     KalturaMonitorClient::initApiMonitor(false, 'keditorservices.flvclipper', $entry->getPartnerId());
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_BLOCK_FLVCLIPPER_ACTION, $entry->getPartnerId())) {
         KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED);
     }
     // set the memory size to be able to serve big files in a single chunk
     ini_set("memory_limit", "64M");
     // set the execution time to be able to serve big files in a single chunk
     ini_set("max_execution_time", 240);
     if ($entry->getType() == entryType::MIX && $entry->getStatus() == entryStatus::DELETED) {
         // because the fiter was turned off - a manual check for deleted entries must be done.
         KExternalErrors::dieGracefully();
     } else {
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
             $version = $this->getRequestParameter("version", null);
             $width = $this->getRequestParameter("width", -1);
             $height = $this->getRequestParameter("height", -1);
             $crop_provider = $this->getRequestParameter("crop_provider", null);
             $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
             $type = $this->getRequestParameter("type", 1);
             $quality = $this->getRequestParameter("quality", 0);
             $src_x = $this->getRequestParameter("src_x", 0);
             $src_y = $this->getRequestParameter("src_y", 0);
             $src_w = $this->getRequestParameter("src_w", 0);
             $src_h = $this->getRequestParameter("src_h", 0);
             $vid_sec = $this->getRequestParameter("vid_sec", -1);
             $vid_slice = $this->getRequestParameter("vid_slice", -1);
             $vid_slices = $this->getRequestParameter("vid_slices", -1);
             if ($width == -1 && $height == -1) {
                 $width = 640;
                 $height = 480;
             } else {
                 if ($width == -1) {
                     // if only either width or height is missing reset them to zero, and convertImage will handle them
                     $width = 0;
                 } else {
                     if ($height == -1) {
                         $height = 0;
                     }
                 }
             }
             $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices);
             kFileUtils::dumpFile($tempThumbPath, null, strpos($tempThumbPath, "_NOCACHE_") === false ? null : 0);
         }
     }
     $audio_only = $this->getRequestParameter("audio_only");
     // milliseconds
     $flavor = $this->getRequestParameter("flavor", 1);
     //
     $flavor_param_id = $this->getRequestParameter("flavor_param_id", null);
     //
     $streamer = $this->getRequestParameter("streamer");
     //
     if (substr($streamer, 0, 4) == "rtmp") {
         // the fms may add .mp4 to the end of the url
         $streamer = "rtmp";
     }
     // grab seek_from_bytes parameter and normalize url
     $seek_from_bytes = $this->getRequestParameter("seek_from_bytes", -1);
     $request = str_replace("/seek_from_bytes/{$seek_from_bytes}", "", $request);
     if ($seek_from_bytes <= 0) {
         $seek_from_bytes = -1;
     }
     // grab seek_from parameter and normalize url
     $seek_from = $this->getRequestParameter("seek_from", -1);
     $request = str_replace("/seek_from/{$seek_from}", "", $request);
     if ($seek_from <= 0) {
         $seek_from = -1;
     }
     $this->dump_from_byte = 0;
     // reset accurate seek from timestamp
     $seek_from_timestamp = -1;
     // backward compatibility
     if ($flavor === "0") {
         // for edit version
         $flavor = "edit";
     }
     if ($flavor === "1" || $flavor === 1) {
         // for play version
         $flavor = null;
     }
     // when flavor is null, we will get a default flavor
     if ($flavor == "edit") {
         $flavorAsset = assetPeer::retrieveBestEditByEntryId($entry->getId());
     } elseif (!is_null($flavor)) {
         $flavorAsset = assetPeer::retrieveById($flavor);
         // when specific asset was request, we don't validate its tags
         if ($flavorAsset && ($flavorAsset->getEntryId() != $entry->getId() || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY)) {
             $flavorAsset = null;
         }
         // we will throw an error later
     } elseif (is_null($flavor) && !is_null($flavor_param_id)) {
         $flavorAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $flavor_param_id);
         if ($flavorAsset && $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             $flavorAsset = null;
         }
         // we will throw an error later
     } else {
         if ($entry->getSource() == entry::ENTRY_MEDIA_SOURCE_WEBCAM) {
             $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
         } else {
             $flavorAsset = assetPeer::retrieveBestPlayByEntryId($entry->getId());
         }
         if (!$flavorAsset) {
             $flavorAssets = assetPeer::retrieveReadyFlavorsByEntryIdAndTag($entry->getId(), flavorParams::TAG_WEB);
             if (count($flavorAssets) > 0) {
                 $flavorAsset = $flavorAssets[0];
             }
         }
     }
     if (is_null($flavorAsset)) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     if (kFileSyncUtils::file_exists($syncKey, false)) {
         $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     } else {
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if (is_null($fileSync)) {
             KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]");
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
         if ($fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) {
             $urlManager = DeliveryProfilePeer::getRemoteDeliveryByStorageId(DeliveryProfileDynamicAttributes::init($fileSync->getDc(), $flavorAsset->getEntryId()), null, $flavorAsset);
             if (!$urlManager) {
                 KalturaLog::log("Error - failed to find an HTTP delivery for storage profile [" . $fileSync->getDc() . "]");
                 KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
             }
             $url = rtrim($urlManager->getUrl(), '/') . '/' . ltrim($urlManager->getFileSyncUrl($fileSync), '/');
             header('location: ' . $url);
             die;
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         $this->redirect($remoteUrl);
     }
     $flv_wrapper = new myFlvHandler($path);
     $isFlv = $flv_wrapper->isFlv();
     // scrubbing is not allowed within mp4 files
     if (!$isFlv) {
         $seek_from = $seek_from_bytes = -1;
     }
     if ($seek_from !== -1 && $seek_from !== 0) {
         if ($audio_only === '0') {
             // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations
         } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) {
             $audio_only = true;
         }
         list($bytes, $duration, $first_tag_byte, $to_byte) = $flv_wrapper->clip(0, -1, $audio_only);
         list($bytes, $duration, $from_byte, $to_byte, $seek_from_timestamp) = $flv_wrapper->clip($seek_from, -1, $audio_only);
         $seek_from_bytes = myFlvHandler::FLV_HEADER_SIZE + $flv_wrapper->getMetadataSize($audio_only) + $from_byte - $first_tag_byte;
     }
     // the direct path without a cdn is "http://s3kaltura.s3.amazonaws.com".$entry->getDataPath();
     $extStorageUrl = $entry->getExtStorageUrl();
     if ($extStorageUrl && substr_count($extStorageUrl, 's3kaltura')) {
         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
         if ($seek_from_timestamp == -1) {
             $seek_from_timestamp = $seek_from;
         }
         $request_host = parse_url($extStorageUrl, PHP_URL_HOST);
         $akamai_url = str_replace($request_host, "cdns3akmi.kaltura.com", $extStorageUrl);
         $akamai_url .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000);
         header("Location: {$akamai_url}");
         KExternalErrors::dieGracefully();
     } elseif ($extStorageUrl) {
         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
         if ($seek_from_timestamp == -1) {
             $seek_from_timestamp = $seek_from;
         }
         $extStorageUrl .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000);
         header("Location: {$extStorageUrl}");
         KExternalErrors::dieGracefully();
     }
     // use headers to detect cdn
     $cdn_name = "";
     $via_header = @$_SERVER["HTTP_VIA"];
     if (strpos($via_header, "llnw.net") !== false) {
         $cdn_name = "limelight";
     } else {
         if (strpos($via_header, "akamai") !== false) {
             $cdn_name = "akamai";
         } else {
             if (strpos($via_header, "Level3") !== false) {
                 $cdn_name = "level3";
             }
         }
     }
     // setting file extension - first trying frrom flavor asset
     $ext = $flavorAsset->getFileExt();
     // if failed, set extension according to file type (isFlv)
     if (!$ext) {
         $ext = $isFlv ? "flv" : "mp4";
     }
     $flv_extension = $streamer == "rtmp" ? "?" : "/a.{$ext}?novar=0";
     // dont check for rtmp / and for an already redirect url
     if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) {
         // check security using ks
         $securyEntryHelper = new KSecureEntryHelper($entry, $ks_str, $referrer, ContextType::PLAY);
         if ($securyEntryHelper->shouldPreview()) {
             $this->checkForPreview($securyEntryHelper, $clip_to);
         } else {
             $securyEntryHelper->validateForPlay($entry, $ks_str);
         }
     } else {
         // if needs security check using cdn authentication mechanism
         // for now assume this is a cdn request and don't check for security
     }
     // use limelight mediavault if either security policy requires it or if we're trying to seek within the video
     if ($entry->getSecurityPolicy() || $seek_from_bytes !== -1) {
         // we have three options:
         // arrived through limelight mediavault url - the url is secured
         // arrived directly through limelight (not secured through mediavault) - enforce ks and redirect to mediavault url
         // didnt use limelight - enforce ks
         // the cdns are configured to authenticate request for /s/....
         // check if we're already in a redirected secure link using the "/s/" prefix
         $secure_request = substr($request, 0, 3) == "/s/";
         if ($secure_request && ($cdn_name == "limelight" || $cdn_name == "level3")) {
             // request was validated by cdn let it through
         } else {
             // extract ks
             $ks_str = $this->getRequestParameter("ks", "");
             if ($entry->getSecurityPolicy()) {
                 if (!$ks_str) {
                     $this->logMessage("flvclipper - no KS");
                     KExternalErrors::dieGracefully();
                 }
                 $ks = kSessionUtils::crackKs($ks_str);
                 if (!$ks) {
                     $this->logMessage("flvclipper - invalid ks [{$ks_str}]");
                     KExternalErrors::dieGracefully();
                 }
                 $matched_privs = $ks->verifyPrivileges("sview", $entry_id);
                 $this->logMessage("flvclipper - verifyPrivileges name [sview], priv [{$entry_id}] [{$matched_privs}]");
                 if (!$matched_privs) {
                     $this->logMessage("flvclipper - doesnt not match required privlieges [{$ks_str}]");
                     KExternalErrors::dieGracefully();
                 }
             }
             if ($cdn_name == "limelight") {
                 $ll_url = requestUtils::getCdnHost() . "/s{$request}" . $flv_extension;
                 $secret = kConf::get("limelight_madiavault_password");
                 $expire = "&e=" . (time() + 120);
                 $ll_url .= $expire;
                 $fs = $seek_from_bytes == -1 ? "" : "&fs={$seek_from_bytes}";
                 $ll_url .= "&h=" . md5("{$secret}{$ll_url}") . $fs;
                 //header("Location: $ll_url");
                 $this->redirect($ll_url);
             } else {
                 if ($cdn_name == "level3") {
                     $level3_url = $request . $flv_extension;
                     if ($entry->getSecurityPolicy()) {
                         $level3_url = "/s{$level3_url}";
                         // set expire time in GMT hence the date("Z") offset
                         $expire = "&nva=" . strftime("%Y%m%d%H%M%S", time() - date("Z") + 30);
                         $level3_url .= $expire;
                         $secret = kConf::get("level3_authentication_key");
                         $hash = "0" . substr(self::hmac('sha1', $secret, $level3_url), 0, 20);
                         $level3_url .= "&h={$hash}";
                     }
                     $level3_url .= $seek_from_bytes == -1 ? "" : "&start={$seek_from_bytes}";
                     header("Location: {$level3_url}");
                     KExternalErrors::dieGracefully();
                 } else {
                     if ($cdn_name == "akamai") {
                         $akamai_url = $request . $flv_extension;
                         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
                         if ($seek_from_timestamp == -1) {
                             $seek_from_timestamp = $seek_from;
                         }
                         $akamai_url .= $seek_from_bytes == -1 ? "" : "&aktimeoffset=" . floor($seek_from_timestamp / 1000);
                         header("Location: {$akamai_url}");
                         KExternalErrors::dieGracefully();
                     }
                 }
             }
             // a seek request without a supporting cdn - we need to send the answer from our server
             if ($seek_from_bytes !== -1 && $via_header === null) {
                 $this->dump_from_byte = $seek_from_bytes;
             }
         }
     }
     // always add the file suffix to the request (needed for scrubbing by some cdns,
     // and also breaks without extension on some corporate antivirus).
     // we add the the novar paramter since a leaving a trailing "?" will be trimmed
     // and then the /seek_from request will result in another url which level3
     // will try to refetch from the origin
     // note that for streamer we dont add the file extension
     if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) {
         // a seek request without a supporting cdn - we need to send the answer from our server
         if ($seek_from_bytes !== -1 && $via_header === null) {
             $request .= "/seek_from_bytes/{$seek_from_bytes}";
         }
         requestUtils::sendCdnHeaders("flv", 0);
         header("Location: {$request}" . $flv_extension);
         KExternalErrors::dieGracefully();
     }
     // mp4
     if (!$isFlv) {
         $limit_file_size = 0;
         if ($clip_to != 2147483647) {
             $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId());
             if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) {
                 $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration());
                 $limit_file_size = floor(@kFile::fileSize($path) * ($clip_to / $duration) * 1.2);
             }
         }
         KalturaLog::info("serving file [{$path}] entry id [{$entry_id}] limit file size [{$limit_file_size}] clip_to [{$clip_to}]");
         kFileUtils::dumpFile($path, null, null, $limit_file_size);
     }
     $this->logMessage("flvclipperAction: serving file [{$path}] entry_id [{$entry_id}] clip_from [{$clip_from}] clip_to [{$clip_to}]", "warning");
     if ($audio_only === '0') {
         // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations
     } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) {
         $audio_only = true;
     }
     //$start = microtime(true);
     list($bytes, $duration, $from_byte, $to_byte, $from_ts, $cuepoint_pos) = myFlvStaticHandler::clip($path, $clip_from, $clip_to, $audio_only);
     $metadata_size = $flv_wrapper->getMetadataSize($audio_only);
     $this->from_byte = $from_byte;
     $this->to_byte = $to_byte;
     //$end1 = microtime(true);
     //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" );
     //$this->logMessage( "flvclipperAction: serving file [$path] t1 [" . ( $end1-$start) . "]");
     $data_offset = $metadata_size + myFlvHandler::getHeaderSize();
     // if we're returning a partial file adjust the total size:
     // substract the metadata and bytes which are not delivered
     if ($this->dump_from_byte >= $data_offset && !$audio_only) {
         $bytes -= $metadata_size + max(0, $this->dump_from_byte - $data_offset);
     }
     $this->total_length = $data_offset + $bytes;
     //echo " $bytes , $duration ,$from_byte , $to_byte, $cuepoint_pos\n"; die;
     $this->cuepoint_time = 0;
     $this->cuepoint_pos = 0;
     if ($streamer == "chunked" && $clip_to != 2147483647) {
         $this->cuepoint_time = $clip_to - 1;
         $this->cuepoint_pos = $cuepoint_pos;
         $this->total_length += myFlvHandler::CUEPOINT_TAG_SIZE;
     }
     //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes with header & md [" . $this->total_length . "] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" );
     $this->flv_wrapper = $flv_wrapper;
     $this->audio_only = $audio_only;
     try {
         Propel::close();
     } catch (Exception $e) {
         $this->logMessage("flvclipperAction: error closing db {$e}");
     }
     KExternalErrors::terminateDispatch();
     return sfView::SUCCESS;
 }
Example #27
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;
         }
     }
 }
Example #28
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;
 }
Example #29
0
 /**
  * will create thumbnail according to the entry type
  * @return the thumbnail path.
  */
 public function getLocalThumbFilePath($version, $width, $height, $type, $bgcolor = "ffffff", $crop_provider = null, $quality = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $vid_sec = -1, $vid_slice = 0, $vid_slices = -1, $density = 0, $stripProfiles = false, $flavorId = null, $fileName = null)
 {
     $contentPath = myContentStorage::getFSContentRootPath();
     // if entry type is audio - serve generic thumb:
     if ($this->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) {
         if ($this->getStatus() == entryStatus::DELETED || $this->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK) {
             KalturaLog::log("rejected audio entry - not serving thumbnail");
             KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
         }
         $audioEntryExist = false;
         $audioThumbEntry = null;
         $audioThumbEntryId = null;
         $partner = $this->getPartner();
         if ($partner) {
             $audioThumbEntryId = $partner->getAudioThumbEntryId();
         }
         if ($audioThumbEntryId) {
             $audioThumbEntry = entryPeer::retrieveByPK($audioThumbEntryId);
         }
         if ($audioThumbEntry && $audioThumbEntry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
             $fileSyncVersion = $partner->getAudioThumbEntryVersion();
             $audioEntryKey = $audioThumbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $fileSyncVersion);
             $contentPath = kFileSyncUtils::getLocalFilePathForKey($audioEntryKey);
             if ($contentPath) {
                 $msgPath = $contentPath;
                 $audioEntryExist = true;
             } else {
                 KalturaLog::err('no local file sync for entry id');
             }
         }
         if (!$audioEntryExist) {
             $msgPath = $contentPath . "content/templates/entry/thumbnail/audio_thumb.jpg";
         }
         return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $msgPath, $density, $stripProfiles);
     } elseif ($this->getMediaType() == entry::ENTRY_MEDIA_TYPE_SHOW) {
         // roughcut without any thumbnail, probably just created
         $msgPath = $contentPath . "content/templates/entry/thumbnail/auto_edit.jpg";
         return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $msgPath, $density, $stripProfiles);
     } elseif ($this->getType() == entryType::MEDIA_CLIP) {
         try {
             return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices);
         } catch (Exception $ex) {
             if ($ex->getCode() == kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 // get original flavor asset
                 $origFlavorAsset = assetPeer::retrieveOriginalByEntryId($this->getId());
                 if ($origFlavorAsset) {
                     $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                     list($readyFileSync, $isLocal) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, TRUE, FALSE);
                     if ($readyFileSync) {
                         if ($isLocal) {
                             KalturaLog::err('Trying to redirect to myself - stop here.');
                             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                         }
                         //Ready fileSync is on the other DC - dumping
                         kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
                     }
                     KalturaLog::err('No ready fileSync found on any DC.');
                     KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                 }
             }
         }
     }
 }
Example #30
0
 /**
  * Generic add entry using an uploaded file, should be used when the uploaded entry type is not known.
  *
  * @action addFromUploadedFile
  * @param KalturaBaseEntry $entry
  * @param string $uploadTokenId
  * @param KalturaEntryType $type
  * @return KalturaBaseEntry
  */
 function addFromUploadedFileAction(KalturaBaseEntry $entry, $uploadTokenId, $type = -1)
 {
     try {
         // check that the uploaded file exists
         $entryFullPath = kUploadTokenMgr::getFullPathByUploadTokenId($uploadTokenId);
     } catch (kCoreException $ex) {
         if ($ex->getCode() == kUploadTokenException::UPLOAD_TOKEN_INVALID_STATUS) {
         }
         throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_INVALID_STATUS_FOR_ADD_ENTRY);
         throw $ex;
     }
     if (!file_exists($entryFullPath)) {
         // Backward compatability - support case in which the required file exist in the other DC
         kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
         /*
         $remoteDCHost = kUploadTokenMgr::getRemoteHostForUploadToken($uploadTokenId, kDataCenterMgr::getCurrentDcId());
         if($remoteDCHost)
         {
         	kFileUtils::dumpApiRequest($remoteDCHost);
         }
         else
         {
         	throw new KalturaAPIException(KalturaErrors::UPLOADED_FILE_NOT_FOUND_BY_TOKEN);
         }
         */
     }
     // validate the input object
     //$entry->validatePropertyMinLength("name", 1);
     if (!$entry->name) {
         $entry->name = $this->getPartnerId() . '_' . time();
     }
     // first copy all the properties to the db entry, then we'll check for security stuff
     $dbEntry = $entry->toInsertableObject(new entry());
     $dbEntry->setType($type);
     $dbEntry->setMediaType(entry::ENTRY_MEDIA_TYPE_AUTOMATIC);
     $this->checkAndSetValidUserInsert($entry, $dbEntry);
     $this->checkAdminOnlyInsertProperties($entry);
     $this->validateAccessControlId($entry);
     $this->validateEntryScheduleDates($entry, $dbEntry);
     $dbEntry->setPartnerId($this->getPartnerId());
     $dbEntry->setSubpId($this->getPartnerId() * 100);
     $dbEntry->setSourceId($uploadTokenId);
     $dbEntry->setSourceLink($entryFullPath);
     myEntryUtils::setEntryTypeAndMediaTypeFromFile($dbEntry, $entryFullPath);
     $dbEntry->setDefaultModerationStatus();
     // hack due to KCW of version  from KMC
     if (!is_null(parent::getConversionQualityFromRequest())) {
         $dbEntry->setConversionQuality(parent::getConversionQualityFromRequest());
     }
     $dbEntry->save();
     $kshow = $this->createDummyKShow();
     $kshowId = $kshow->getId();
     // setup the needed params for my insert entry helper
     $paramsArray = array("entry_media_source" => KalturaSourceType::FILE, "entry_media_type" => $dbEntry->getMediaType(), "entry_full_path" => $entryFullPath, "entry_license" => $dbEntry->getLicenseType(), "entry_credit" => $dbEntry->getCredit(), "entry_source_link" => $dbEntry->getSourceLink(), "entry_tags" => $dbEntry->getTags());
     $token = $this->getKsUniqueString();
     $insert_entry_helper = new myInsertEntryHelper(null, $dbEntry->getKuserId(), $kshowId, $paramsArray);
     $insert_entry_helper->setPartnerId($this->getPartnerId(), $this->getPartnerId() * 100);
     $insert_entry_helper->insertEntry($token, $dbEntry->getType(), $dbEntry->getId(), $dbEntry->getName(), $dbEntry->getTags(), $dbEntry);
     $dbEntry = $insert_entry_helper->getEntry();
     kUploadTokenMgr::closeUploadTokenById($uploadTokenId);
     myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_ADD, $dbEntry);
     $entry->fromObject($dbEntry, $this->getResponseProfile());
     return $entry;
 }