예제 #1
0
 public static function uploadFileByToken($file_data, $token, $filename, $extra_id = null, $create_thumb = false)
 {
     KalturaLog::log("Trace while uploading1 [{$filename}] [{$token}] [{$extra_id}] " . print_r($file_data, true));
     $origFilename = @$file_data['name'];
     if (!$origFilename) {
         KalturaLog::log("Error while uploading, file does not have a name. [{$filename}] [{$token}] [{$extra_id}] " . print_r($file_data, true) . "\nerror: [" . @$file_data["error"] . "]");
         return;
     }
     $parts = pathinfo($origFilename);
     $extension = @strtolower($parts['extension']);
     /*
     		$filename = $token .'_'. $filename;
     		// add the file extension after the "." character
     		$fullPath = myContentStorage::getFSUploadsPath().$filename . ( $extra_id ? "_" . $extra_id : "" ) .".".$extension;
     */
     list($fullPath, $fullUrl) = self::getUploadPathAndUrl($token, $filename, $extra_id, $extension);
     KalturaLog::log("Trace while uploading2 [{$filename}] [{$token}] [{$extra_id}] " . print_r($file_data, true) . "\n->[{$fullPath}]");
     // start tracking what will hopefully become an entry
     $te = new TrackEntry();
     $te->setTrackEventTypeId(TrackEntry::TRACK_ENTRY_EVENT_TYPE_UPLOADED_FILE);
     $te->setParam1Str($token);
     $te->setParam2Str($filename);
     $te->setParam3Str($fullPath);
     $te->setDescription(__METHOD__ . ":" . __LINE__);
     TrackEntry::addTrackEntry($te);
     myContentStorage::fullMkdir($fullPath);
     if (!move_uploaded_file($file_data['tmp_name'], $fullPath)) {
         KalturaLog::log("Error while uploading [{$token}] [{$filename}] [{$extra_id}] [{$create_thumb}] " . print_r($file_data, true) . "\n->[{$fullPath}]");
         $err = array("token" => $token, "filename" => $filename, "origFilename" => $origFilename, "error" => @$file_data["error"]);
         KalturaLog::log("Error while uploading [{$token}] [{$filename}] [{$extra_id}] [{$create_thumb}] " . print_r($file_data, true) . "\n->[{$fullPath}]" . "\n" . print_r($err, true));
         return $err;
     }
     chmod($fullPath, 0777);
     $upload_server_header = isset($_SERVER["HTTP_X_KALTURA_SERVER"]) ? $_SERVER["HTTP_X_KALTURA_SERVER"] : null;
     $thumb_created = false;
     // if the file originated from a kaltura upload server we dont need a thumbnail (kuploader)
     if ($create_thumb && !$upload_server_header) {
         $thumbFullPath = self::getThumbnailPath($fullPath, ".jpg");
         kFile::fullMkdir($thumbFullPath);
         KalturaLog::log("Thumbnail full path [{$thumbFullPath}]");
         if (myContentStorage::fileExtAccepted($extension)) {
             KalturaLog::log("Generating image thumbnail");
             myFileConverter::createImageThumbnail($fullPath, $thumbFullPath, "image2");
             $thumb_url = self::getThumbnailPath($fullUrl, ".jpg");
             $thumb_created = file_exists($thumbFullPath);
         } elseif (myContentStorage::fileExtNeedConversion($extension)) {
             KalturaLog::log("Generating media thumbnail");
             myFileConverter::captureFrame($fullPath, $thumbFullPath, 1, "image2", -1, -1, 3);
             if (!file_exists($thumbFullPath)) {
                 myFileConverter::captureFrame($fullPath, $thumbFullPath, 1, "image2", -1, -1, 0);
             }
         }
     }
     if (!$thumb_created) {
         KalturaLog::log("Thumbnail not generated");
         // in this case no thumbnail was created - don't extract false data
         $thumb_url = "";
     }
     return array("token" => $token, "filename" => $filename, "origFilename" => $origFilename, "thumb_url" => $thumb_url, "thumb_created" => $thumb_created);
 }
예제 #2
0
 public function myFileIndicator($file_name)
 {
     if (!self::$s_indicator_path) {
         self::$s_indicator_path = myContentStorage::getFSContentRootPath() . "/indicators/";
         kFile::fullMkdir(self::$s_indicator_path . "dummy.txt");
     }
     $this->file_name = $file_name;
     $this->pattern = "/" . $this->file_name . '\\..*/';
 }
예제 #3
0
 public function convert(kConversionCommand $conv_cmd, kConversionResult $conv_result, $start_params_index = 0, $end_params_index = -1)
 {
     if (!file_exists($conv_cmd->source_file)) {
         TRACE("File [{$conv_cmd->source_file} does not exist");
         return array(false, 0);
     }
     // make sure all the output directories exist - if not create
     kFile::fullMkdir($conv_cmd->target_file);
     kFile::fullMkdir($conv_cmd->log_file);
     self::fixConvParams($conv_cmd);
     $conv_params_list = $conv_cmd->conversion_params_list;
     if ($end_params_index == -1) {
         $end_params_index = count($conv_params_list);
     }
     $start_i = max($start_params_index, 0);
     $end_i = min($end_params_index, count($conv_params_list));
     for ($i = $start_i; $i < $end_i; ++$i) {
         $conv_res_info = new kConvResInfo();
         $conv_res_info->engine = $this->getName();
         $conv_res_info->index = $i;
         $conv_params = @$conv_cmd->conversion_params_list[$i];
         if ($conv_params) {
             $conv_res_info->conv_params_name = $conv_params->name;
         }
         $log_file = $conv_cmd->getLogFileWithSuffix($i);
         $conv_res_info->target = $conv_cmd->getTargetFileWithSuffix($i);
         list($execution_command_str, $conversion_str) = $this->getExecutionCommandAndConversionString($conv_cmd, $i);
         $conv_res_info->conv_str = $conversion_str;
         // assume there always will be this index
         self::logMediaInfo($conv_cmd->source_file);
         self::addToLogFile($log_file, $execution_command_str);
         self::addToLogFile($log_file, $conversion_str);
         $return_value = "";
         $conv_result->appendResult($this->getName() . ": " . $execution_command_str);
         TRACE($execution_command_str);
         $start = microtime(true);
         exec($execution_command_str, $output, $return_value);
         $end = microtime(true);
         TRACE($this->getName() . ": [{$return_value}]");
         // $return_value == 0 is success. if not - return the index of the failed conversion
         $conv_result->appendResult($this->getName() . ": [{$return_value}]");
         $conv_res_info->duration = $end - $start;
         $conv_res_info->res = $return_value;
         $conv_result->appendResInfo($conv_res_info);
         if ($return_value != 0) {
             return array(false, $i);
         }
         self::logMediaInfo($conv_cmd->getTargetFileWithSuffix($i));
     }
     return array(true, -1);
     // indicate all was converted properly
 }
 /**
  * Executes index action
  */
 protected function executeImpl(kshow $kshow)
 {
     $this->xml_content = "";
     $kshow_id = $this->kshow_id;
     if ($kshow_id == NULL || $kshow_id == 0) {
         return sfView::SUCCESS;
     }
     $metadata_creator = new myKshowMetadataCreator();
     $this->show_metadata = $metadata_creator->createMetadata($kshow_id);
     //		$kshow = kshowPeer:retrieveByPK( $kshow_id );
     $entry = entryPeer::retrieveByPK($kshow->getShowEntryId());
     // TODO - this should never happen
     if ($entry == NULL) {
         // there is no show entry for this show !
         $entry = $kshow->createEntry(entry::ENTRY_MEDIA_TYPE_SHOW, $kshow->getProducerId());
     }
     $content_path = myContentStorage::getFSContentRootPath();
     $file_path = $content_path . $entry->getDataPath();
     // check to see if the content of the file changed
     $current_metadata = kFile::getFileContent($file_path);
     $comp_result = strcmp($this->show_metadata, $current_metadata);
     if ($comp_result != 0) {
         $ext = pathinfo($file_path, PATHINFO_EXTENSION);
         if ($ext != "xml") {
             // this is for the first time - override the template path by setting the data to NULL
             $entry->setData(NULL);
             $file_path = pathinfo($file_path, PATHINFO_DIRNAME) . "/" . kFile::getFileNameNoExtension($file_path) . ".xml";
         }
         // this will increment the name if needed
         $entry->setData($file_path);
         $file_path = $content_path . $entry->getDataPath();
         $entry->save();
         kFile::fullMkdir($file_path);
         kFile::setFileContent($file_path, $this->show_metadata);
         $this->xml_content = $this->show_metadata;
     }
 }
예제 #5
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL2;
     requestUtils::handleConditionalGet();
     ignore_user_abort();
     $entry_id = $this->getRequestParameter("entry_id");
     $widget_id = $this->getRequestParameter("widget_id", 0);
     $upload_token_id = $this->getRequestParameter("upload_token_id");
     $version = $this->getRequestParameter("version", null);
     $width = $this->getRequestParameter("width", -1);
     $height = $this->getRequestParameter("height", -1);
     $type = $this->getRequestParameter("type", 1);
     $crop_provider = $this->getRequestParameter("crop_provider", null);
     $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);
     // 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->getRequestParameter("rel_width", -1);
     $rel_height = $this->getRequestParameter("rel_height", -1);
     if ($width == -1 && $height == -1) {
         $width = 120;
         $height = 90;
     } else {
         if ($width == -1) {
             // if only either width or height is missing reset them to zero, and convertImage will handle them
             $width = 0;
         } else {
             if ($height == -1) {
                 $height = 0;
             }
         }
     }
     $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
     if ($upload_token_id) {
         $upload_token = UploadTokenPeer::retrieveByPK($upload_token_id);
         if ($upload_token) {
             $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);
                 kFile::dumpFile($thumb_full_path);
             }
         }
     }
     $entry = entryPeer::retrieveByPKNoFilter($entry_id);
     // multiply the passed $src_* values so that they will relate to the original image size, according to $src_display_*
     if ($rel_width != -1) {
         $widthRatio = $entry->getWidth() / $rel_width;
         $src_x = $src_x * $widthRatio;
         $src_w = $src_w * $widthRatio;
     }
     if ($rel_height != -1) {
         $heightRatio = $entry->getHeight() / $rel_height;
         $src_y = $src_y * $heightRatio;
         $src_h = $src_h * $heightRatio;
     }
     if (!$entry) {
         // 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);
         }
     }
     $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB;
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA;
     }
     $dataKey = $entry->getSyncKey($subType);
     list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($dataKey, true, false);
     $tempThumbPath = null;
     $entry_status = $entry->getStatus();
     // both 640x480 and 0x0 requests are probably coming from the kdp
     // 640x480 - old kdp version requesting thumbnail
     // 0x0 - new kdp version requesting the thumbnail of an unready entry
     // we need to distinguish between calls from the kdp and calls from a browser: <img src=...>
     // that can't handle swf input
     if (($width == 640 && $height == 480 || $width == 0 && $height == 0) && ($entry_status == entryStatus::PRECONVERT || $entry_status == entryStatus::IMPORT || $entry_status == entryStatus::ERROR_CONVERTING || $entry_status == entryStatus::DELETED)) {
         $contentPath = myContentStorage::getFSContentRootPath();
         $msgPath = $contentPath . "content/templates/entry/bigthumbnail/";
         if ($entry_status == entryStatus::DELETED) {
             $msgPath .= $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK ? "entry_blocked.swf" : "entry_deleted.swf";
         } else {
             $msgPath .= $entry_status == entryStatus::ERROR_CONVERTING ? "entry_error.swf" : "entry_converting.swf";
         }
         kFile::dumpFile($msgPath, null, 0);
     }
     if (!$file_sync) {
         // if entry type is audio - serve generic thumb:
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) {
             if ($entry->getStatus() == entryStatus::DELETED && $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK) {
                 KalturaLog::log("rejected audio entry - not serving thumbnail");
                 KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
             }
             $contentPath = myContentStorage::getFSContentRootPath();
             $msgPath = $contentPath . "content/templates/entry/thumbnail/audio_thumb.jpg";
             $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, $msgPath);
             //kFile::dumpFile($tempThumbPath, null, 0);
         } elseif ($entry->getType() == entryType::LIVE_STREAM) {
             if ($entry->getStatus() == entryStatus::DELETED && $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK) {
                 KalturaLog::log("rejected live stream entry - not serving thumbnail");
                 KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
             }
             $contentPath = myContentStorage::getFSContentRootPath();
             $msgPath = $contentPath . "content/templates/entry/thumbnail/live_thumb.jpg";
             $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, $msgPath);
         } elseif ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_SHOW) {
             $contentPath = myContentStorage::getFSContentRootPath();
             $msgPath = $contentPath . "content/templates/entry/thumbnail/auto_edit.jpg";
             $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, $msgPath);
             //kFile::dumpFile($tempThumbPath, null, 0);
         } elseif ($entry->getType() == entryType::MEDIA_CLIP) {
             // commenting out the new behavior, in this case the thumbnail will be created in resizeEntryImage
             //$contentPath = myContentStorage::getFSContentRootPath();
             //$msgPath = $contentPath."content/templates/entry/thumbnail/broken_thumb.jpg";
             //header("Xkaltura-app: entry [$entry_id] in conversion, returning template broken thumb");
             //KalturaLog::log( "Entry in conversion, no thumbnail yet [$entry_id], created dynamic 1x1 jpg");
             //kFile::dumpFile($msgPath, null, 0);
             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);
             } catch (Exception $ex) {
                 if ($ex->getCode() == kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                     // get original flavor asset
                     $origFlavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entry_id);
                     if ($origFlavorAsset) {
                         $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);
                         }
                         $remote_url = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync, $_SERVER['REQUEST_URI']);
                         KalturaLog::log(__METHOD__ . ": redirecting to [{$remote_url}]");
                         $this->redirect($remote_url);
                     }
                 }
             }
         } else {
             // file does not exist on any DC - die
             KalturaLog::log("Error - no FileSync for entry [{$entry_id}]");
             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
         }
     }
     if (!$local && !$tempThumbPath) {
         $remote_url = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']);
         KalturaLog::log(__METHOD__ . ": redirecting to [{$remote_url}]");
         $this->redirect($remote_url);
     }
     // 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);
         } catch (Exception $ex) {
             if ($ex->getCode() == kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 // get original flavor asset
                 $origFlavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entry_id);
                 if ($origFlavorAsset) {
                     $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);
                     }
                     $remote_url = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync, $_SERVER['REQUEST_URI']);
                     KalturaLog::log(__METHOD__ . ": redirecting to [{$remote_url}]");
                     $this->redirect($remote_url);
                 }
             }
         }
     }
     $nocache = strpos($tempThumbPath, "_NOCACHE_") !== false;
     // notify external proxy, so it'll cache this url
     if (!$nocache && requestUtils::getHost() == kConf::get("apphome_url") && file_exists($tempThumbPath)) {
         self::notifyProxy($_SERVER["REQUEST_URI"]);
     }
     // cache result
     if (!$nocache) {
         $requestKey = $_SERVER["REQUEST_URI"];
         $cache = new myCache("thumb", 86400 * 30);
         // 30 days
         $cache->put($requestKey, $tempThumbPath);
     }
     kFile::dumpFile($tempThumbPath, null, $nocache ? 0 : null);
     // TODO - can delete from disk assuming we caneasily recreate it and it will anyway be cached in the CDN
     // however dumpfile dies at the end so we cant just write it here (maybe register a shutdown callback)
 }
예제 #6
0
 public static function resizeEntryImage(entry $entry, $version, $width, $height, $type, $bgcolor = "ffffff", $crop_provider = null, $quality = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $vid_sec = -1, $vid_slice = 0, $vid_slices = -1, $orig_image_path = null)
 {
     $contentPath = myContentStorage::getFSContentRootPath();
     $entry_status = $entry->getStatus();
     $tempThumbName = $entry->getId() . "_{$width}_{$height}_{$type}_{$crop_provider}_{$bgcolor}_{$quality}_{$src_x}_{$src_y}_{$src_w}_{$src_h}_{$vid_sec}_{$vid_slice}_{$vid_slices}_{$entry_status}";
     $entryThumbFilename = $entry->getThumbnail() ? $entry->getThumbnail() : "0.jpg";
     if ($entry->getStatus() != entryStatus::READY || @$entryThumbFilename[0] == '&') {
         $tempThumbName .= "_NOCACHE_";
     }
     // we remove the & from the template thumb otherwise getGeneralEntityPath will drop $tempThumbName from the final path
     $entryThumbFilename = str_replace("&", "", $entryThumbFilename);
     $basePath = myContentStorage::getGeneralEntityPath("entry/tempthumb", $entry->getIntId(), $tempThumbName, $entryThumbFilename, $version);
     $tempThumbPath = $contentPath . $basePath;
     $cachedTempThumbPath = myContentStorage::getFSCacheRootPath() . $basePath;
     if (file_exists($cachedTempThumbPath)) {
         header("X-Kaltura:cached-local-thumb-exists," . md5($cachedTempThumbPath));
         return $cachedTempThumbPath;
     }
     if (file_exists($tempThumbPath)) {
         header("X-Kaltura:cached-thumb-exists," . md5($tempThumbPath));
         return $tempThumbPath;
     }
     if ($orig_image_path === null || !file_exists($orig_image_path)) {
         $sub_type = $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE ? entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA : entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB;
         $orig_image_key = $entry->getSyncKey($sub_type, $version);
         $orig_image_path = kFileSyncUtils::getReadyLocalFilePathForKey($orig_image_key);
     }
     // remark added so ffmpeg will try to load the thumbnail from the original source
     //if (!file_exists($orig_image_path))
     //	KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
     // check a request for animated thumbs without a concrete vid_slice
     // in which case we'll create all the frames as one wide image
     $multi = $vid_slice == -1 && $vid_slices != -1;
     $count = $multi ? $vid_slices : 1;
     $im = null;
     if ($multi) {
         $vid_slice = 0;
     }
     while ($count--) {
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO && ($vid_sec != -1 || $vid_slices != -1) || !file_exists($orig_image_path)) {
             if ($vid_sec != -1) {
                 $calc_vid_sec = min($vid_sec, floor($entry->getLengthInMsecs() / 1000));
             } else {
                 if ($vid_slices != -1) {
                     $calc_vid_sec = floor($entry->getLengthInMsecs() / $vid_slices * min($vid_slice, $vid_slices) / 1000);
                 } else {
                     if ($entry->getStatus() != entryStatus::READY && $entry->getLengthInMsecs() == 0) {
                         $calc_vid_sec = $entry->getPartner() && $entry->getPartner()->getDefThumbOffset() ? $entry->getPartner()->getDefThumbOffset() : 3;
                     } else {
                         $calc_vid_sec = $entry->getBestThumbOffset();
                     }
                 }
             }
             $capturedThumbName = $entry->getId() . "_sec_{$calc_vid_sec}";
             $capturedThumbPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempthumb", $entry->getIntId(), $capturedThumbName, $entry->getThumbnail(), $version);
             $orig_image_path = $capturedThumbPath . "temp_1.jpg";
             // if we already captured the frame at that second, dont recapture, just use the existing file
             if (!file_exists($orig_image_path)) {
                 // creating the thumbnail is a very heavy operation
                 // prevent calling it in parallel for the same thubmnail for 5 minutes
                 $cache = new myCache("thumb-processing", 5 * 60);
                 // 5 minutes
                 $processing = $cache->get($orig_image_path);
                 if ($processing) {
                     KExternalErrors::dieError(KExternalErrors::PROCESSING_CAPTURE_THUMBNAIL);
                 }
                 $cache->put($orig_image_path, true);
                 $flavorAsset = flavorAssetPeer::retrieveOriginalReadyByEntryId($entry->getId());
                 if (is_null($flavorAsset) || !($flavorAsset->hasTag(flavorParams::TAG_MBR) || $flavorAsset->hasTag(flavorParams::TAG_WEB))) {
                     // try the best playable
                     $flavorAsset = flavorAssetPeer::retrieveHighestBitrateByEntryId($entry->getId());
                 }
                 if (is_null($flavorAsset)) {
                     // if no READY ORIGINAL entry is available, try to retreive a non-READY ORIGINAL entry
                     $flavorAsset = flavorAssetPeer::retreiveOriginalByEntryId($entry->getId());
                 }
                 if (is_null($flavorAsset)) {
                     KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
                 }
                 $flavorSyncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                 $entry_data_path = kFileSyncUtils::getReadyLocalFilePathForKey($flavorSyncKey);
                 if (!$entry_data_path) {
                     // since this is not really being processed on this server, and will probably cause redirect in thumbnailAction
                     // remove from cache so later requests will still get redirected and will not fail on PROCESSING_CAPTURE_THUMBNAIL
                     $cache->remove($orig_image_path);
                     throw new kFileSyncException('no ready filesync on current DC', kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC);
                 }
                 myFileConverter::autoCaptureFrame($entry_data_path, $capturedThumbPath . "temp_", $calc_vid_sec, -1, -1);
                 $cache->remove($orig_image_path);
             }
         }
         kFile::fullMkdir($tempThumbPath);
         if ($crop_provider) {
             $convertedImagePath = myFileConverter::convertImageUsingCropProvider($orig_image_path, $tempThumbPath, $width, $height, $type, $crop_provider, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h);
         } else {
             $convertedImagePath = myFileConverter::convertImage($orig_image_path, $tempThumbPath, $width, $height, $type, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h);
         }
         // die if resize operation failed
         if ($convertedImagePath === null) {
             KExternalErrors::dieError(KExternalErrors::IMAGE_RESIZE_FAILED);
         }
         if ($multi) {
             list($w, $h, $type, $attr, $srcIm) = myFileConverter::createImageByFile($tempThumbPath);
             if (!$im) {
                 $im = imagecreatetruecolor($w * $vid_slices, $h);
             }
             imagecopy($im, $srcIm, $w * $vid_slice, 0, 0, 0, $w, $h);
             imagedestroy($srcIm);
             ++$vid_slice;
         }
     }
     if ($multi) {
         imagejpeg($im, $tempThumbPath);
         imagedestroy($im);
     }
     return $tempThumbPath;
 }
예제 #7
0
파일: uiConf.php 프로젝트: DBezemer/server
 private function getCachedContent($kaltura_config, $confFilePath)
 {
     if (!file_exists($confFilePath)) {
         return null;
     }
     if (strpos($confFilePath, "://") != FALSE) {
         // remote file (http:// or ftp://) - store the cache in a directory near the base file
         //$cache_path = dirname( $kaltura_config ) . "cache/" . $confFilePath  . "_cache.xml" ;
         // for now - don't cache for remote files
         $cache_path = null;
     } else {
         // this is a local file - store the cache file in the same directory
         $cache_path = str_replace("/uiconf/", "/cacheuiconf/", $confFilePath) . "_cache.xml";
         kFile::fullMkdir($cache_path);
     }
     try {
         $s_time = microtime(true);
         $config = new kXmlConfig($kaltura_config, $confFilePath);
         $content = $config->getConfig($cache_path);
         $e_time = microtime(true);
         if ($config->createdCache()) {
             KalturaLog::log(__METHOD__ . " created config cache file [{$kaltura_config}]+[{$confFilePath}]->[{$cache_path}].\ntook [" . ($e_time - $s_time) . "] seconds");
         }
         return $content;
     } catch (Exception $ex) {
         KalturaLog::log(__METHOD__ . " Error creating config [{$kaltura_config}]+[{$confFilePath}]:" . $ex->getMessage());
         return null;
     }
 }
예제 #8
0
 public static function resizeEntryImage(entry $entry, $version, $width, $height, $type, $bgcolor = "ffffff", $crop_provider = null, $quality = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $vid_sec = -1, $vid_slice = 0, $vid_slices = -1, $orig_image_path = null, $density = 0, $stripProfiles = false, $thumbParams = null, $format = null)
 {
     if (is_null($thumbParams) || !$thumbParams instanceof kThumbnailParameters) {
         $thumbParams = new kThumbnailParameters();
     }
     $contentPath = myContentStorage::getFSContentRootPath();
     $entry_status = $entry->getStatus();
     $thumbName = $entry->getId() . "_{$width}_{$height}_{$type}_{$crop_provider}_{$bgcolor}_{$quality}_{$src_x}_{$src_y}_{$src_w}_{$src_h}_{$vid_sec}_{$vid_slice}_{$vid_slices}_{$entry_status}";
     if ($orig_image_path) {
         $thumbName .= '_oip_' . basename($orig_image_path);
     }
     if ($density) {
         $thumbName .= "_dns_{$density}";
     }
     if ($stripProfiles) {
         $thumbName .= "_stp_{$stripProfiles}";
     }
     $entryThumbFilename = $entry->getThumbnail() ? $entry->getThumbnail() : "0.jpg";
     if ($entry->getStatus() != entryStatus::READY || @$entryThumbFilename[0] == '&') {
         $thumbName .= "_NOCACHE_";
     }
     // we remove the & from the template thumb otherwise getGeneralEntityPath will drop $tempThumbName from the final path
     $entryThumbFilename = str_replace("&", "", $entryThumbFilename);
     //create final path for thumbnail created
     $finalBasePath = myContentStorage::getGeneralEntityPath("entry/tempthumb", $entry->getIntId(), $thumbName, $entryThumbFilename, $version);
     $finalThumbPath = $contentPath . $finalBasePath;
     //Add unique id to the proccesing file path to avoid file being overwritten when several identical (with same parameters) calls are made before the final thumbnail is created
     $thumbName .= "_" . uniqid() . "_";
     //create path for processing thumbnail request
     $processingBasePath = myContentStorage::getGeneralEntityPath("entry/tempthumb", $entry->getIntId(), $thumbName, $entryThumbFilename, $version);
     $processingThumbPath = $contentPath . $processingBasePath;
     if (!is_null($format)) {
         $finalThumbPath = kFile::replaceExt($finalThumbPath, $format);
         $processingThumbPath = kFile::replaceExt($processingThumbPath, $format);
     }
     if (file_exists($finalThumbPath) && @filesize($finalThumbPath)) {
         header("X-Kaltura:cached-thumb-exists," . md5($finalThumbPath));
         return $finalThumbPath;
     }
     if ($orig_image_path === null || !file_exists($orig_image_path)) {
         $orig_image_path = self::getLocalImageFilePathByEntry($entry, $version);
     }
     // remark added so ffmpeg will try to load the thumbnail from the original source
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE && !file_exists($orig_image_path)) {
         throw new kFileSyncException('no ready filesync on current DC', kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC);
     }
     // check a request for animated thumbs without a concrete vid_slice
     // in which case we'll create all the frames as one wide image
     $multi = $vid_slice == -1 && $vid_slices != -1;
     $count = $multi ? $vid_slices : 1;
     $im = null;
     if ($multi) {
         $vid_slice = 0;
     }
     while ($count--) {
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO && ($vid_sec != -1 || $vid_slices != -1) || !file_exists($orig_image_path)) {
             if ($vid_sec != -1) {
                 $calc_vid_sec = min($vid_sec, floor($entry->getLengthInMsecs() / 1000));
             } else {
                 if ($vid_slices != -1) {
                     $calc_vid_sec = floor($entry->getLengthInMsecs() / $vid_slices * min($vid_slice, $vid_slices) / 1000);
                 } else {
                     if ($entry->getStatus() != entryStatus::READY && $entry->getLengthInMsecs() == 0) {
                         $calc_vid_sec = $entry->getPartner() && $entry->getPartner()->getDefThumbOffset() ? $entry->getPartner()->getDefThumbOffset() : 3;
                     } else {
                         $calc_vid_sec = $entry->getBestThumbOffset();
                     }
                 }
             }
             $capturedThumbName = $entry->getId() . "_sec_{$calc_vid_sec}";
             $capturedThumbPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempthumb", $entry->getIntId(), $capturedThumbName, $entry->getThumbnail(), $version);
             $orig_image_path = $capturedThumbPath . "temp_1.jpg";
             // if we already captured the frame at that second, dont recapture, just use the existing file
             if (!file_exists($orig_image_path)) {
                 // limit creation of more than XX ffmpeg image extraction processes
                 if (kConf::hasParam("resize_thumb_max_processes_ffmpeg") && trim(exec("ps -e -ocmd|awk '{print \$1}'|grep -c " . kConf::get("bin_path_ffmpeg"))) > kConf::get("resize_thumb_max_processes_ffmpeg")) {
                     KExternalErrors::dieError(KExternalErrors::TOO_MANY_PROCESSES);
                 }
                 // creating the thumbnail is a very heavy operation
                 // prevent calling it in parallel for the same thubmnail for 5 minutes
                 $cache = new myCache("thumb-processing", 5 * 60);
                 // 5 minutes
                 $processing = $cache->get($orig_image_path);
                 if ($processing) {
                     KExternalErrors::dieError(KExternalErrors::PROCESSING_CAPTURE_THUMBNAIL);
                 }
                 $cache->put($orig_image_path, true);
                 $flavorAsset = assetPeer::retrieveHighestBitrateByEntryId($entry->getId(), flavorParams::TAG_THUMBSOURCE);
                 if (is_null($flavorAsset)) {
                     $flavorAsset = assetPeer::retrieveOriginalReadyByEntryId($entry->getId());
                     if ($flavorAsset) {
                         $flavorSyncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($flavorSyncKey, false, false);
                         if (!$fileSync) {
                             $flavorAsset = null;
                         }
                     }
                     if (is_null($flavorAsset) || !($flavorAsset->hasTag(flavorParams::TAG_MBR) || $flavorAsset->hasTag(flavorParams::TAG_WEB))) {
                         // try the best playable
                         $flavorAsset = assetPeer::retrieveHighestBitrateByEntryId($entry->getId(), null, flavorParams::TAG_SAVE_SOURCE);
                     }
                     if (is_null($flavorAsset)) {
                         // if no READY ORIGINAL entry is available, try to retrieve a non-READY ORIGINAL entry
                         $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
                     }
                 }
                 if (is_null($flavorAsset)) {
                     // if no READY ORIGINAL entry is available, try to retrieve a non-READY ORIGINAL entry
                     $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
                 }
                 if (is_null($flavorAsset)) {
                     KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
                 }
                 $flavorSyncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                 $entry_data_path = kFileSyncUtils::getReadyLocalFilePathForKey($flavorSyncKey);
                 if (!$entry_data_path) {
                     // since this is not really being processed on this server, and will probably cause redirect in thumbnailAction
                     // remove from cache so later requests will still get redirected and will not fail on PROCESSING_CAPTURE_THUMBNAIL
                     $cache->remove($orig_image_path);
                     throw new kFileSyncException('no ready filesync on current DC', kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC);
                 }
                 // close db connections as we won't be requiring the database anymore and capturing a thumbnail may take a long time
                 kFile::closeDbConnections();
                 myFileConverter::autoCaptureFrame($entry_data_path, $capturedThumbPath . "temp_", $calc_vid_sec, -1, -1);
                 $cache->remove($orig_image_path);
             }
         }
         // close db connections as we won't be requiring the database anymore and image manipulation may take a long time
         kFile::closeDbConnections();
         // limit creation of more than XX Imagemagick processes
         if (kConf::hasParam("resize_thumb_max_processes_imagemagick") && trim(exec("ps -e -ocmd|awk '{print \$1}'|grep -c " . kConf::get("bin_path_imagemagick"))) > kConf::get("resize_thumb_max_processes_imagemagick")) {
             KExternalErrors::dieError(KExternalErrors::TOO_MANY_PROCESSES);
         }
         // resizing (and editing)) an image file that failes results in a long server waiting time
         // prevent this waiting time (of future requests) in case the resizeing failes
         $cache = new myCache("thumb-processing-resize", 5 * 60);
         // 5 minutes
         $processing = $cache->get($orig_image_path);
         if ($processing) {
             KExternalErrors::dieError(KExternalErrors::PROCESSING_CAPTURE_THUMBNAIL);
         }
         kFile::fullMkdir($processingThumbPath);
         if ($crop_provider) {
             $convertedImagePath = myFileConverter::convertImageUsingCropProvider($orig_image_path, $processingThumbPath, $width, $height, $type, $crop_provider, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h, $density, $stripProfiles);
         } else {
             if (!file_exists($orig_image_path) || !filesize($orig_image_path)) {
                 KExternalErrors::dieError(KExternalErrors::IMAGE_RESIZE_FAILED);
             }
             $imageSizeArray = getimagesize($orig_image_path);
             if ($thumbParams->getSupportAnimatedThumbnail() && is_array($imageSizeArray) && $imageSizeArray[2] === IMAGETYPE_GIF) {
                 $processingThumbPath = kFile::replaceExt($processingThumbPath, "gif");
                 $finalThumbPath = kFile::replaceExt($finalThumbPath, "gif");
             }
             $convertedImagePath = myFileConverter::convertImage($orig_image_path, $processingThumbPath, $width, $height, $type, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h, $density, $stripProfiles, $thumbParams, $format);
         }
         // die if resize operation failed and add failed resizing to cache
         if ($convertedImagePath === null || !@filesize($convertedImagePath)) {
             $cache->put($orig_image_path, true);
             KExternalErrors::dieError(KExternalErrors::IMAGE_RESIZE_FAILED);
         }
         // if resizing secceded remove from cache of failed resizing
         if ($cache->get($orig_image_path)) {
             $cache->remove($orig_image_path, true);
         }
         if ($multi) {
             list($w, $h, $type, $attr, $srcIm) = myFileConverter::createImageByFile($processingThumbPath);
             if (!$im) {
                 $im = imagecreatetruecolor($w * $vid_slices, $h);
             }
             imagecopy($im, $srcIm, $w * $vid_slice, 0, 0, 0, $w, $h);
             imagedestroy($srcIm);
             ++$vid_slice;
         }
     }
     if ($multi) {
         imagejpeg($im, $processingThumbPath);
         imagedestroy($im);
     }
     kFile::fullMkdir($finalThumbPath);
     kFile::moveFile($processingThumbPath, $finalThumbPath);
     return $finalThumbPath;
 }
 public static function createFilePath($base_path, $file_name)
 {
     $id = self::getEntryIdFromFileName($file_name);
     // create a new path with the file name
     $entry = entryPeer::retrieveByPK($id);
     if ($entry) {
         KalturaLog::debug("Found entry for file_name [{$file_name}] -> entry_id [{$id}]");
         $int_id = $entry->getIntId();
         $path_name = myContentStorage::dirForId($int_id, $id) . "." . pathinfo($file_name, PATHINFO_EXTENSION);
     } else {
         KalturaLog::debug("Did NOT find entry for file_name [{$file_name}] -> entry_id [{$id}]");
         $path_name = "AZ/" . pathinfo($file_name, PATHINFO_BASENAME);
     }
     // make sure the separator exists between the 2 paths
     //		if ( ! kString::endsWith( $base_path , "/" ) ) $base_path .= "/";
     kFile::fullMkdir($base_path . "/" . $path_name);
     return $base_path . "/" . $path_name;
 }
 /**
  * @return string
  */
 protected static function getCachePath()
 {
     $path = kEnvironment::get("cache_root_path") . DIRECTORY_SEPARATOR . 'batch';
     if (!file_exists($path)) {
         kFile::fullMkdir($path);
     }
     return $path;
 }
예제 #11
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $uv_cookie = @$_COOKIE['uv'];
     if (strlen($uv_cookie) != 35) {
         $uv_cookie = "uv_" . md5(uniqid(rand(), true));
     }
     setrawcookie('uv', $uv_cookie, time() + 3600 * 24 * 365, '/');
     // check if this is a request for the kdp without a wrapper
     // in case of an application loading the kdp (e.g. kmc)
     $nowrapper = $this->getRequestParameter("nowrapper", false);
     // allow caching if either the cache start time (cache_st) parameter
     // wasn't specified or if it is past the specified time
     $cache_st = $this->getRequestParameter("cache_st");
     $allowCache = !$cache_st || $cache_st < time();
     $referer = @$_SERVER['HTTP_REFERER'];
     $externalInterfaceDisabled = strstr($referer, "bebo.com") === false && strstr($referer, "myspace.com") === false && strstr($referer, "current.com") === false && strstr($referer, "myyearbook.com") === false && strstr($referer, "facebook.com") === false && strstr($referer, "friendster.com") === false ? "" : "&externalInterfaceDisabled=1";
     // if there is no wrapper the loader is responsible for setting extra params to the kdp
     $noncached_params = "";
     if (!$nowrapper) {
         $noncached_params = $externalInterfaceDisabled . "&referer=" . urlencode($referer);
     }
     $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https" : "http";
     $requestKey = $protocol . $_SERVER["REQUEST_URI"];
     // check if we cached the redirect url
     $cache = new myCache("kwidget", 10 * 60);
     // 10 minutes
     $cachedResponse = $cache->get($requestKey);
     if ($allowCache && $cachedResponse) {
         header("X-Kaltura:cached-action");
         header("Expires: Sun, 19 Nov 2000 08:52:00 GMT");
         header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
         header("Pragma: no-cache");
         header("Location:{$cachedResponse}" . $noncached_params);
         die;
     }
     // check if we cached the patched swf with flashvars
     $cache_swfdata = new myCache("kwidgetswf", 10 * 60);
     // 10 minutes
     $cachedResponse = $cache_swfdata->get($requestKey);
     if ($allowCache && $cachedResponse) {
         header("X-Kaltura:cached-action");
         requestUtils::sendCdnHeaders("swf", strlen($cachedResponse), 60 * 10);
         echo $cachedResponse;
         die;
     }
     $widget_id = $this->getRequestParameter("wid");
     $show_version = $this->getRequestParameter("v");
     $debug_kdp = $this->getRequestParameter("debug_kdp", false);
     $widget = widgetPeer::retrieveByPK($widget_id);
     if (!$widget) {
         die;
     }
     // because of the routing rule - the entry_id & kmedia_type WILL exist. be sure to ignore them if smaller than 0
     $kshow_id = $widget->getKshowId();
     $entry_id = $widget->getEntryId();
     $gallery_widget = !$kshow_id && !$entry_id;
     if (!$entry_id) {
         $entry_id = -1;
     }
     if ($widget->getSecurityType() != widget::WIDGET_SECURITY_TYPE_TIMEHASH) {
         // try eid - if failed entry_id
         $eid = $this->getRequestParameter("eid", $this->getRequestParameter("entry_id"));
         // try kid - if failed kshow_id
         $kid = $this->getRequestParameter("kid", $this->getRequestParameter("kshow_id"));
         if ($eid != null) {
             $entry_id = $eid;
         } elseif ($kid != null) {
             $kshow_id = $kid;
         }
     }
     if ($widget->getSecurityType() == widget::WIDGET_SECURITY_TYPE_MATCH_IP) {
         $allowCache = false;
         // here we'll attemp to match the ip of the request with that from the customData of the widget
         $custom_data = $widget->getCustomData();
         $valid_country = false;
         if ($custom_data) {
             // in this case the custom_data should be of format:
             //  valid_county_1,valid_country_2,...,valid_country_n;falback_entry_id
             $arr = explode(";", $custom_data);
             $countries_str = $arr[0];
             $fallback_entry_id = isset($arr[1]) ? $arr[1] : null;
             $fallback_kshow_id = isset($arr[2]) ? $arr[2] : null;
             $current_country = "";
             $valid_country = requestUtils::matchIpCountry($countries_str, $current_country);
             if (!$valid_country) {
                 KalturaLog::log("kwidgetAction: Attempting to access widget [{$widget_id}] and entry [{$entry_id}] from country [{$current_country}]. Retrning entry_id: [{$fallback_entry_id}] kshow_id [{$fallback_kshow_id}]");
                 $entry_id = $fallback_entry_id;
                 $kshow_id = $fallback_kshow_id;
             }
         }
     } elseif ($widget->getSecurityType() == widget::WIDGET_SECURITY_TYPE_FORCE_KS) {
     }
     $kmedia_type = -1;
     // support either uiconf_id or ui_conf_id
     $uiconf_id = $this->getRequestParameter("uiconf_id");
     if (!$uiconf_id) {
         $uiconf_id = $this->getRequestParameter("ui_conf_id");
     }
     if ($uiconf_id) {
         $widget_type = $uiconf_id;
         $uiconf_id_str = "&uiconf_id={$uiconf_id}";
     } else {
         $widget_type = $widget->getUiConfId();
         $uiconf_id_str = "";
     }
     if (empty($widget_type)) {
         $widget_type = 3;
     }
     $kdata = $widget->getCustomData();
     $partner_host = myPartnerUtils::getHost($widget->getPartnerId());
     $partner_cdnHost = myPartnerUtils::getCdnHost($widget->getPartnerId());
     $host = $partner_host;
     if ($widget_type == 10) {
         $swf_url = $host . "/swf/weplay.swf";
     } else {
         $swf_url = $host . "/swf/kplayer.swf";
     }
     $partner_id = $widget->getPartnerId();
     $subp_id = $widget->getSubpId();
     if (!$subp_id) {
         $subp_id = 0;
     }
     $uiConf = uiConfPeer::retrieveByPK($widget_type);
     // new ui_confs which are deleted should stop the script
     // the check for >100000 is for supporting very old mediawiki and such players
     if (!$uiConf && $widget_type > 100000) {
         die;
     }
     if ($uiConf) {
         $ui_conf_swf_url = $uiConf->getSwfUrl();
         if (kString::beginsWith($ui_conf_swf_url, "http")) {
             $swf_url = $ui_conf_swf_url;
             // absolute URL
         } else {
             $use_cdn = $uiConf->getUseCdn();
             $host = $use_cdn ? $partner_cdnHost : $partner_host;
             $swf_url = $host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . $ui_conf_swf_url;
         }
         if ($debug_kdp) {
             $swf_url = str_replace("/kdp/", "/kdp_debug/", $swf_url);
         }
     }
     if ($show_version < 0) {
         $show_version = null;
     }
     $ip = requestUtils::getRemoteAddress();
     // to convert back, use long2ip
     // the widget log should change to reflect the new data, but for now - i used $widget_id instead of the widgget_type
     //		WidgetLog::createWidgetLog( $referer , $ip , $kshow_id , $entry_id , $kmedia_type , $widget_id );
     if ($entry_id == -1) {
         $entry_id = null;
     }
     $kdp3 = false;
     $base_wrapper_swf = myContentStorage::getFSFlashRootPath() . "/kdpwrapper/" . kConf::get('kdp_wrapper_version') . "/kdpwrapper.swf";
     $widgetIdStr = "widget_id={$widget_id}";
     $partnerIdStr = "partner_id={$partner_id}&subp_id={$subp_id}";
     if ($uiConf) {
         $ks_flashvars = "";
         $conf_vars = $uiConf->getConfVars();
         if ($conf_vars) {
             $conf_vars = "&" . $conf_vars;
         }
         $wrapper_swf = $base_wrapper_swf;
         $partner = PartnerPeer::retrieveByPK($partner_id);
         if ($partner) {
             $partner_type = $partner->getType();
         }
         if (version_compare($uiConf->getSwfUrlVersion(), "3.0", ">=")) {
             $kdp3 = true;
             // further in the code, $wrapper_swf is being used and not $base_wrapper_swf
             $wrapper_swf = $base_wrapper_swf = myContentStorage::getFSFlashRootPath() . '/kdp3wrapper/' . kConf::get('kdp3_wrapper_version') . '/kdp3wrapper.swf';
             $widgetIdStr = "widgetId={$widget_id}";
             $uiconf_id_str = "&uiConfId={$uiconf_id}";
             $partnerIdStr = "partnerId={$partner_id}&subpId={$subp_id}";
         }
         // if we are loaded without a wrapper (directly in flex)
         // 1. dont create the ks - keep url the same for caching
         // 2. dont patch the uiconf - patching is done only to wrapper anyway
         if ($nowrapper) {
             $dynamic_date = $widgetIdStr . "&host=" . str_replace("http://", "", str_replace("https://", "", $partner_host)) . "&cdnHost=" . str_replace("http://", "", str_replace("https://", "", $partner_cdnHost)) . $uiconf_id_str . $conf_vars;
             $url = "{$swf_url}?{$dynamic_date}";
         } else {
             // if kdp version >= 2.5
             if (version_compare($uiConf->getSwfUrlVersion(), "2.5", ">=")) {
                 // create an anonymous session
                 $ks = "";
                 $result = kSessionUtils::createKSessionNoValidations($partner_id, 0, $ks, 86400, false, "", "view:*");
                 $ks_flashvars = "&{$partnerIdStr}&uid=0&ts=" . microtime(true);
                 if ($widget->getSecurityType() != widget::WIDGET_SECURITY_TYPE_FORCE_KS) {
                     $ks_flashvars = "&ks={$ks}" . $ks_flashvars;
                 }
                 // patch kdpwrapper with getwidget and getuiconf
                 $root = myContentStorage::getFSContentRootPath();
                 $confFile_mtime = $uiConf->getUpdatedAt(null);
                 $new_swf_path = "widget_{$widget_id}_{$widget_type}_{$confFile_mtime}_" . md5($base_wrapper_swf . $swf_url) . ".swf";
                 $md5 = md5($new_swf_path);
                 $new_swf_path = "content/cacheswf/" . substr($md5, 0, 2) . "/" . substr($md5, 2, 2) . "/" . $new_swf_path;
                 $cached_swf = "{$root}/{$new_swf_path}";
                 if (!file_exists($cached_swf) || filemtime($cached_swf) < $confFile_mtime) {
                     kFile::fullMkdir($cached_swf);
                     require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "api_v3" . DIRECTORY_SEPARATOR . "bootstrap.php";
                     $dispatcher = KalturaDispatcher::getInstance();
                     try {
                         $widget_result = $dispatcher->dispatch("widget", "get", array("ks" => $ks, "id" => $widget_id));
                         $ui_conf_result = $dispatcher->dispatch("uiConf", "get", array("ks" => $ks, "id" => $widget_type));
                     } catch (Exception $ex) {
                         die;
                     }
                     $serializer = new KalturaXmlSerializer(false);
                     $serializer->serialize($widget_result);
                     $widget_xml = $serializer->getSerializedData();
                     $serializer = new KalturaXmlSerializer(false);
                     $serializer->serialize($ui_conf_result);
                     $ui_conf_xml = $serializer->getSerializedData();
                     $patcher = new kPatchSwf($root . $base_wrapper_swf);
                     $result = "<xml><result>{$widget_xml}</result><result>{$ui_conf_xml}</result></xml>";
                     $patcher->patch($result, $cached_swf);
                 }
                 if (file_exists($cached_swf)) {
                     $wrapper_swf = $new_swf_path;
                 }
             }
             $kdp_version_2 = strpos($swf_url, "kdp/v2.") > 0;
             if ($partner_host == "http://www.kaltura.com" && !$kdp_version_2 && !$kdp3) {
                 $partner_host = 1;
                 // otherwise the kdp will try going to cdnwww.kaltura.com
             }
             $track_wrapper = '';
             if (kConf::get('track_kdpwrapper') && kConf::get('kdpwrapper_track_url')) {
                 $track_wrapper = "&wrapper_tracker_url=" . urlencode(kConf::get('kdpwrapper_track_url') . "?activation_key=" . kConf::get('kaltura_activation_key') . "&package_version=" . kConf::get('kaltura_version'));
             }
             $dynamic_date = $widgetIdStr . $track_wrapper . "&kdpUrl=" . urlencode($swf_url) . "&host=" . str_replace("http://", "", str_replace("https://", "", $partner_host)) . "&cdnHost=" . str_replace("http://", "", str_replace("https://", "", $partner_cdnHost)) . ($show_version ? "&entryVersion={$show_version}" : "") . ($kshow_id ? "&kshowId={$kshow_id}" : "") . ($entry_id ? "&entryId={$entry_id}" : "") . $uiconf_id_str . $ks_flashvars . ($cache_st ? "&clientTag=cache_st:{$cache_st}" : "") . $conf_vars;
             // for now changed back to $host since kdp version prior to 1.0.15 didnt support loading by external domain kdpwrapper
             $url = $host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . "/{$wrapper_swf}?{$dynamic_date}";
             // patch wrapper with flashvars and dump to browser
             if (version_compare($uiConf->getSwfUrlVersion(), "2.6.6", ">=")) {
                 $patcher = new kPatchSwf($root . $wrapper_swf, "KALTURA_FLASHVARS_DATA");
                 ob_start();
                 $patcher->patch($dynamic_date . "&referer=" . urlencode($referer));
                 $wrapper_data = ob_get_contents();
                 ob_end_clean();
                 requestUtils::sendCdnHeaders("swf", strlen($wrapper_data), $allowCache ? 60 * 10 : 0);
                 echo $wrapper_data;
                 if ($allowCache) {
                     $cache_swfdata->put($requestKey, $wrapper_data);
                 }
                 die;
             }
         }
     } else {
         $dynamic_date = "kshowId={$kshow_id}" . "&host=" . requestUtils::getRequestHostId() . ($show_version ? "&entryVersion={$show_version}" : "") . ($entry_id ? "&entryId={$entry_id}" : "") . ($entry_id ? "&KmediaType={$kmedia_type}" : "");
         $dynamic_date .= "&isWidget={$widget_type}&referer=" . urlencode($referer);
         $dynamic_date .= "&kdata={$kdata}";
         $url = "{$swf_url}?{$dynamic_date}";
     }
     // if referer has a query string an IE bug will prevent out flashvars to propagate
     // when nowrapper is true we cant use /swfparams either as there isnt a kdpwrapper
     if (!$nowrapper && $uiConf && version_compare($uiConf->getSwfUrlVersion(), "2.6.6", ">=")) {
         // apart from the /swfparam/ format, add .swf suffix to the end of the stream in case
         // a corporate firewall looks at the file suffix
         $pos = strpos($url, "?");
         $url = substr($url, 0, $pos) . "/swfparams/" . urlencode(substr($url, $pos + 1)) . ".swf";
     }
     if ($allowCache) {
         $cache->put($requestKey, $url);
     }
     if (strpos($url, "/swfparams/") > 0) {
         $url = substr($url, 0, -4) . urlencode($noncached_params) . ".swf";
     } else {
         $url .= $noncached_params;
     }
     $this->redirect($url);
 }
예제 #12
0
        $schemaXmlPath = $value;
    }
    array_shift($argv);
}
//pass the name of the generator as the first argument of the command line to
//generate a single library. if this argument is empty or 'all', generator will create all libs.
$generateSingle = isset($argv[1]) ? $argv[1] : null;
//second command line argument specifies the output path, if not specified will default to
//<content root>/content/clientlibs
if (isset($argv[2])) {
    $outputPathBase = $argv[2];
} else {
    $root = myContentStorage::getFSContentRootPath();
    $outputPathBase = "{$root}/content/clientlibs";
}
kFile::fullMkdir($outputPathBase);
//pull the generator config ini
$config = new Zend_Config_Ini(__DIR__ . '/../configurations/generator.ini', null, array('allowModifications' => true));
$config = KalturaPluginManager::mergeConfigs($config, 'generator', false);
$libsToGenerate = null;
if (strtolower($generateSingle) == 'all') {
    $generateSingle = null;
} elseif (!$generateSingle) {
    $libsToGenerate = file(__DIR__ . '/../configurations/generator.defaults.ini');
    foreach ($libsToGenerate as $key => &$default) {
        $default = strtolower(trim($default, " \t\r\n"));
    }
}
//if we got specific generator request, tes if this requested generator does exist
if ($generateSingle != null) {
    $libsToGenerate = array_map('strtolower', array_intersect(explode(',', $generateSingle), array_keys($config->toArray())));
예제 #13
0
 protected static function fullMkdir($filePath)
 {
     $filePath = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $filePath);
     if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
         return kFile::fullMkdir($filePath, 0770);
     }
     $contentGroup = kConf::get('content_group');
     if (is_numeric($contentGroup)) {
         $contentGroup = intval($contentGroup);
     }
     $dirs = explode(DIRECTORY_SEPARATOR, dirname($filePath));
     $path = '';
     foreach ($dirs as $dir) {
         $path .= DIRECTORY_SEPARATOR . $dir;
         if (is_dir($path)) {
             continue;
         }
         if (!kFile::fullMkfileDir($path, 0770)) {
             return false;
         }
         chgrp($path, $contentGroup);
     }
     return true;
 }
예제 #14
0
 public static function getTemplateDir()
 {
     $dir = myContentStorage::getFSContentRootPath() . "/email_templates/";
     kFile::fullMkdir($dir);
     return $dir;
 }
예제 #15
0
 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();
 }
 public static function moveFromFile($temp_file_path, FileSyncKey $target_key, $strict = true, $copyOnly = false, $cacheOnly = false)
 {
     KalturaLog::log(__METHOD__ . " - move file: [{$temp_file_path}] to key [{$target_key}], ");
     $c = FileSyncPeer::getCriteriaForFileSyncKey($target_key);
     if ($cacheOnly) {
         $c->add(FileSyncPeer::FILE_TYPE, FileSync::FILE_SYNC_FILE_TYPE_CACHE);
     } else {
         $c->add(FileSyncPeer::FILE_TYPE, array(FileSync::FILE_SYNC_FILE_TYPE_FILE, FileSync::FILE_SYNC_FILE_TYPE_LINK), Criteria::IN);
     }
     $existsFileSync = FileSyncPeer::doSelectOne($c);
     if ($existsFileSync) {
         KalturaLog::log(__METHOD__ . " - file already exists");
         if ($strict) {
             throw new Exception("key [" . $target_key . "] already exists");
         }
     }
     $targetFullPath = self::getLocalFilePathForKey($target_key);
     if (!$targetFullPath) {
         $targetFullPath = kPathManager::getFilePath($target_key);
         KalturaLog::log(__METHOD__ . " - Generated new path [{$targetFullPath}]");
     }
     if (!file_exists(dirname($targetFullPath))) {
         KalturaLog::log(__METHOD__ . " - creating directory for file");
         kFile::fullMkdir($targetFullPath);
     }
     if (file_exists($temp_file_path)) {
         KalturaLog::log(__METHOD__ . " - {$temp_file_path} file exists");
     } else {
         KalturaLog::log(__METHOD__ . " - {$temp_file_path} file doesnt exist");
     }
     $wamsSupportedFormats = kWAMS::getSupportedFormats();
     $fileExtension = pathinfo($temp_file_path, PATHINFO_EXTENSION);
     if (in_array($fileExtension, $wamsSupportedFormats)) {
         $assetName = self::getWamsAssetNameForKey($target_key);
         if (empty($assetName)) {
             $assetName = pathinfo($temp_file_path, PATHINFO_BASENAME);
         }
         $wamsAssetId = kWAMS::getInstance($target_key->getPartnerId())->publishFileToWAMS($assetName, $temp_file_path);
         if (!empty($wamsAssetId)) {
             if (self::checkDeletedEntry($target_key, $wamsAssetId, $temp_file_path)) {
                 return;
             }
             self::addFromWAMS($wamsAssetId, $target_key, $strict, $cacheOnly);
             if (!self::isAttachment($target_key)) {
                 $wamsTempFilePath = kWAMS::getTempFilePathForAssetId($wamsAssetId, pathinfo($targetFullPath, PATHINFO_EXTENSION));
                 rename($temp_file_path, $wamsTempFilePath);
             } else {
                 unlink($temp_file_path);
             }
             return;
         } else {
             KalturaLog::err("File [{$temp_file_path}] not published to WAMS");
         }
     }
     if ($copyOnly) {
         $success = copy($temp_file_path, $targetFullPath);
     } else {
         $success = kFile::moveFile($temp_file_path, $targetFullPath);
     }
     if ($success) {
         if (!$existsFileSync) {
             self::createSyncFileForKey($target_key, $strict, false, $cacheOnly);
         }
     } else {
         KalturaLog::log(__METHOD__ . " - could not move file from [{$temp_file_path}] to [{$targetFullPath}]");
         throw new Exception("Could not move file from [{$temp_file_path}] to [{$targetFullPath}]");
     }
 }
예제 #17
0
 public function write()
 {
     $full_path = self::getMySpaceLogPath() . $this->file_name . "/" . time() . ".log";
     kFile::fullMkdir($full_path);
     file_put_contents($full_path, $this->content);
 }
예제 #18
0
 public static function moveToDeleted($original_path, $copy = false)
 {
     if (empty($original_path)) {
         return "";
     }
     if (strpos($original_path, "templates/") !== false) {
         return "";
     }
     // dont' delete or move template files
     $deleted_path = self::getFSDeletedContentRootPath($original_path);
     if ($deleted_path == null) {
         return "";
     }
     if (!file_exists($original_path)) {
         return "";
     }
     kFile::fullMkdir($deleted_path);
     self::moveFile($original_path, $deleted_path, true, $copy);
     return $deleted_path;
 }
예제 #19
0
 public static function createTeam2Image($kshow_id)
 {
     try {
         $kshow = kshowPeer::retrieveByPK($kshow_id);
         if (!$kshow) {
             return NULL;
         }
         $contentPath = myContentStorage::getFSContentRootPath();
         // TODO - maybe start from some kaltura background - so if image is not full - still interesting
         $im = imagecreatetruecolor(24 * 7 - 1, 24 * 2 - 1);
         $logo_path = kFile::fixPath(SF_ROOT_DIR . '/web/images/browse/contributorsBG.gif');
         $im = imagecreatefromgif($logo_path);
         // fetch as many different kusers as possible who contributed to the kshow
         // first entries will come up first
         $c = new Criteria();
         $c->add(entryPeer::KSHOW_ID, $kshow_id);
         $c->add(entryPeer::TYPE, entryType::MEDIA_CLIP, Criteria::EQUAL);
         //$c->add ( entryPeer::PICTURE, null, Criteria::NOT_EQUAL );
         $c->setLimit(14);
         // we'll need 14 images of contributers
         $c->addGroupByColumn(entryPeer::KUSER_ID);
         $c->addDescendingOrderByColumn(entryPeer::CREATED_AT);
         $entries = BaseentryPeer::doSelectJoinkuser($c);
         if ($entries == NULL || count($entries) == 0) {
             imagedestroy($im);
             return;
         }
         $entry_list_len = count($entries);
         reset($entries);
         if ($entry_list_len > 0) {
             for ($y = 0; $y <= 1; ++$y) {
                 for ($x = 0; $x <= 6; ++$x) {
                     self::addKuserPictureFromEntry($contentPath, $im, $entries, $x, $y, 1, 24, 24);
                 }
             }
         } else {
             // no contributers - need to create some other image
         }
         $path = kFile::fixPath($contentPath . $kshow->getTeam2PicturePath());
         kFile::fullMkdir($path);
         imagepng($im, $path);
         imagedestroy($im);
         $kshow->setHasTeamImage(true);
         $kshow->save();
     } catch (Exception $ex) {
         // nothing much we can do here !
     }
 }
 protected function executeImpl(kshow $kshow, entry &$entry)
 {
     $this->res = "";
     $likuser_id = $this->getLoggedInUserId();
     // if we allow multiple rouchcuts - there is no reason for one suer to override someone else's thumbnail
     if ($this->allowMultipleRoughcuts()) {
         if ($likuser_id != $entry->getKuserId()) {
             // ERROR - attempting to update an entry which doesnt belong to the user
             return "<xml>!!</xml>";
             //$this->securityViolation( $kshow->getId() );
         }
     }
     $debug = @$_GET["debug"];
     /*
     $kshow_id = @$_GET["kshow_id"];
     $debug = @$_GET["debug"];
     
     $this->kshow_id = $kshow_id;
     
     if ( $kshow_id == NULL || $kshow_id == 0 ) return;
     
     $kshow = kshowPeer::retrieveByPK( $kshow_id );
     
     if ( ! $kshow ) 
     {
     	$this->res = "No kshow " . $kshow_id ;
     	return;	
     }
     
     // is the logged-in-user is not an admin or the producer - check if show can be published	
     $likuser_id = $this->getLoggedInUserId();
     $viewer_type = myKshowUtils::getViewerType($kshow, $likuser_id);
     if ( $viewer_type != KshowKuser::KSHOWKUSER_VIEWER_PRODUCER && ( ! $kshow->getCanPublish() ) ) 
     {
     	// ERROR - attempting to publish a non-publishable show
     	return "<xml>!</xml>";//$this->securityViolation( $kshow->getId() );
     }
     
     
     // ASSUME - the kshow & roughcut already exist
     $show_entry_id = $kshow->getShowEntryId();
     $roughcut = entryPeer::retrieveByPK( $show_entry_id );
     
     $roughcut = entryPeer::retrieveByPK( $entry_id );
     
      
     if ( ! $roughcut)
     {
     	$this->res = "No roughcut for kshow " . $kshow->getId() ;
     	return;	
     }
     */
     //		echo "for entry: $show_entry_id current thumb path: " . $entry->getThumbnail() ;
     $entry->setThumbnail(".jpg");
     $entry->setCreateThumb(false);
     $entry->save();
     //$thumb_data = $_REQUEST["ThumbData"];
     if (isset($HTTP_RAW_POST_DATA)) {
         $thumb_data = $HTTP_RAW_POST_DATA;
     } else {
         $thumb_data = file_get_contents("php://input");
     }
     //		$thumb_data = $GLOBALS["HTTP_RAW_POST_DATA"];
     $thumb_data_size = strlen($thumb_data);
     $bigThumbPath = myContentStorage::getFSContentRootPath() . $entry->getBigThumbnailPath();
     kFile::fullMkdir($bigThumbPath);
     kFile::setFileContent($bigThumbPath, $thumb_data);
     $path = myContentStorage::getFSContentRootPath() . $entry->getThumbnailPath();
     kFile::fullMkdir($path);
     myFileConverter::createImageThumbnail($bigThumbPath, $path);
     $roughcutPath = myContentStorage::getFSContentRootPath() . $entry->getDataPath();
     $xml_doc = new KDOMDocument();
     $xml_doc->load($roughcutPath);
     if (myMetadataUtils::updateThumbUrl($xml_doc, $entry->getBigThumbnailUrl())) {
         $xml_doc->save($roughcutPath);
     }
     $this->res = $entry->getBigThumbnailUrl();
 }
예제 #21
0
 public function __construct($script_name)
 {
     $this->script_name = $script_name;
     $this->register($script_name);
     SET_CONTEXT("FS");
     $MAX_ITERATIONS_DUE_TO_PROPEL_MEMORY_LEAK = 10000000;
     self::initDb();
     list($sleep_between_cycles, $number_of_times_to_skip_writing_sleeping) = self::getSleepParams('app_flatten_');
     $last_worker_count = 0;
     $iteration = 0;
     $c = new Criteria();
     $currentDc = kDataCenterMgr::getCurrentDc();
     $c->add(BatchJobPeer::DC, kDataCenterMgr::getCurrentDcId());
     $c->add(BatchJobPeer::JOB_TYPE, BatchJobType::FLATTEN);
     $c->add(BatchJobPeer::STATUS, BatchJob::BATCHJOB_STATUS_PROCESSED);
     $temp_count = 0;
     while (1) {
         self::exitIfDone();
         try {
             sleep($sleep_between_cycles);
             $jobs = BatchJobPeer::doSelect($c);
             foreach ($jobs as $job) {
                 $data = json_decode($job->getData(true), true);
                 $entry_id = $data['entryId'];
                 $entry_int_id = $data['entryIntId'];
                 $entry_version = $data['entryVersion'];
                 $file_format = $data['fileFormat'];
                 $entry = entryPeer::retrieveByPK($entry_id);
                 if (!$entry) {
                     // entry is probably deleted if it is not returned from retrieveByPK
                     // close job as failed
                     $job->setStatus(BatchJob::BATCHJOB_STATUS_FAILED);
                     $job->setDescription("could not retrieve entry, probably deleted");
                     KalturaLog::debug("could not retrieve entry {$entry_id} , probably deleted");
                     $job->save();
                     continue;
                 }
                 $fileSyncKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $file_format);
                 $fullFinalPath = kFileSyncUtils::getLocalFilePathForKey($fileSyncKey);
                 $finalPathNoExt = substr($fullFinalPath, 0, strlen($fullFinalPath) - strlen($file_format));
                 kFile::fullMkdir($fullFinalPath);
                 $wildcardFinalPath = $finalPathNoExt . "*";
                 $older_files = glob($wildcardFinalPath);
                 foreach ($older_files as $older_file) {
                     KalturaLog::debug("removing old file: [{$older_file}]");
                     @unlink($older_file);
                 }
                 KalturaLog::debug("Downloading: {$fullFinalPath}");
                 KCurlWrapper::getDataFromFile($data["serverUrl"], $fullFinalPath);
                 if (!file_exists($fullFinalPath)) {
                     KalturaLog::debug("file doesnt exist: " . $data["serverUrl"]);
                     $job->setDescription("file doesnt exist: " . $data["serverUrl"]);
                     $job->setStatus(BatchJob::BATCHJOB_STATUS_FAILED);
                 } else {
                     if (filesize($fullFinalPath) < 100000) {
                         @unlink($fullFinalPath);
                         KalturaLog::debug("file too small: " . $data["serverUrl"]);
                         $job->setDescription("file too small: " . $data["serverUrl"]);
                         $job->setStatus(BatchJob::BATCHJOB_STATUS_FAILED);
                     } else {
                         if ($data['email']) {
                             $downloadLink = $entry->getDownloadUrl() . '/format/' . $file_format;
                             kJobsManager::addMailJob(null, $entry_id, $entry->getPartnerId(), self::KALTURAS_FLATTEN_READY, kMailJobData::MAIL_PRIORITY_NORMAL, kConf::get("batch_flatten_video_sender_email"), kConf::get("batch_flatten_video_sender_name"), $data['email'], array($data['email'], $downloadLink));
                         }
                         KalturaLog::debug("Deleting: " . $data["deleteUrl"]);
                         kFile::downloadUrlToString($data["deleteUrl"]);
                         myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_UPDATE, $entry);
                         $job->setStatus(BatchJob::BATCHJOB_STATUS_FINISHED);
                         list($rootPath, $filePath) = kFileSyncUtils::getLocalFilePathArrForKey($fileSyncKey);
                         $fileFullPath = $rootPath . $filePath;
                         if (file_exists($fileFullPath)) {
                             try {
                                 kFileSyncUtils::createSyncFileForKey($rootPath, $filePath, $fileSyncKey);
                             } catch (Exception $ex) {
                                 KalturaLog::debug("ignore ERROR: " . $ex->getMessage());
                             }
                         } else {
                             KalturaLog::debug("The file [{$fileFullPath}] doesn't exists, not creating FileSync");
                         }
                     }
                 }
                 $job->save();
             }
         } catch (Exception $ex) {
             KalturaLog::debug("ERROR: " . $ex->getMessage());
             self::initDb(true);
             self::failed();
         }
         if ($temp_count == 0) {
             KalturaLog::debug("Ended conversion. sleeping for a while (" . $sleep_between_cycles . " seconds). Will write to the log in (" . $sleep_between_cycles * $number_of_times_to_skip_writing_sleeping . ") seconds");
         }
         $temp_count++;
         if ($temp_count >= $number_of_times_to_skip_writing_sleeping) {
             $temp_count = 0;
         }
     }
 }
예제 #22
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::info("token_id [{$upload_token_id}] not found in DC [" . kDataCenterMgr::getCurrentDcId() . "]. dump url to romote DC");
                 $remoteUrl = kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()) . $_SERVER['REQUEST_URI'];
                 kFileUtils::dumpUrl($remoteUrl);
             }
         }
     }
     if ($entry_id) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             // problem could be due to replication lag
             kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
         }
     } else {
         // get the widget
         $widget = widgetPeer::retrieveByPK($widget_id);
         if (!$widget) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_AND_WIDGET_NOT_FOUND);
         }
         // get the kshow
         $kshow_id = $widget->getKshowId();
         $kshow = kshowPeer::retrieveByPK($kshow_id);
         if ($kshow) {
             $entry_id = $kshow->getShowEntryId();
         } else {
             $entry_id = $widget->getEntryId();
         }
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.thumbnail', $entry->getPartnerId());
     if ($nearest_aspect_ratio) {
         // Get the entry's default thumbnail path (if any)
         $defaultThumbnailPath = myEntryUtils::getLocalImageFilePathByEntry($entry, $version);
         // Get the file path of the thumbnail with the nearest
         $selectedThumbnailDescriptor = kThumbnailUtils::getNearestAspectRatioThumbnailDescriptorByEntryId($entry_id, $width, $height, $defaultThumbnailPath);
         if ($selectedThumbnailDescriptor) {
             $imageFilePath = $selectedThumbnailDescriptor->getImageFilePath();
             $thumbWidth = $selectedThumbnailDescriptor->getWidth();
             $thumbHeight = $selectedThumbnailDescriptor->getHeight();
             // The required width and height will serve as the final crop values
             $src_w = $width;
             $src_h = $height;
             // Base on the thumbnail's dimensions
             kThumbnailUtils::scaleDimensions($thumbWidth, $thumbHeight, $width, $height, kThumbnailUtils::SCALE_UNIFORM_SMALLER_DIM, $width, $height);
             // Set crop type
             $type = KImageMagickCropper::CROP_AFTER_RESIZE;
         }
     }
     $partner = $entry->getPartner();
     // not allow capturing frames if the partner has FEATURE_DISALLOW_FRAME_CAPTURE permission
     if ($vid_sec != -1 || $vid_slice != -1 || $vid_slices != -1) {
         if ($partner->getEnabledService(PermissionName::FEATURE_BLOCK_THUMBNAIL_CAPTURE)) {
             KExternalErrors::dieError(KExternalErrors::NOT_ALLOWED_PARAMETER);
         }
     }
     if ($partner) {
         if ($quality == 0) {
             $quality = $partner->getDefThumbQuality();
         }
         if ($density == 0) {
             $density = $partner->getDefThumbDensity();
         }
     }
     $thumbParams = new kThumbnailParameters();
     $thumbParams->setSupportAnimatedThumbnail($partner->getSupportAnimatedThumbnails());
     if (is_null($stripProfiles)) {
         $stripProfiles = $partner->getStripThumbProfile();
     }
     //checks whether the thumbnail display should be restricted by KS
     $base64Referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64Referrer);
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     if (!$referrer) {
         $referrer = kApiCache::getHttpReferrer();
     }
     $ksStr = $this->getRequestParameter("ks");
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, ContextType::THUMBNAIL);
     $securyEntryHelper->validateForPlay();
     // multiply the passed $src_* values so that they will relate to the original image size, according to $src_display_*
     if ($rel_width != -1 && $rel_width) {
         $widthRatio = $entry->getWidth() / $rel_width;
         $src_x = $src_x * $widthRatio;
         $src_w = $src_w * $widthRatio;
     }
     if ($rel_height != -1 && $rel_height) {
         $heightRatio = $entry->getHeight() / $rel_height;
         $src_y = $src_y * $heightRatio;
         $src_h = $src_h * $heightRatio;
     }
     $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB;
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA;
     }
     $dataKey = $entry->getSyncKey($subType);
     list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($dataKey, true, false);
     $tempThumbPath = null;
     $entry_status = $entry->getStatus();
     // both 640x480 and 0x0 requests are probably coming from the kdp
     // 640x480 - old kdp version requesting thumbnail
     // 0x0 - new kdp version requesting the thumbnail of an unready entry
     // we need to distinguish between calls from the kdp and calls from a browser: <img src=...>
     // that can't handle swf input
     if (($width == 640 && $height == 480 || $width == 0 && $height == 0) && ($entry_status == entryStatus::PRECONVERT || $entry_status == entryStatus::IMPORT || $entry_status == entryStatus::ERROR_CONVERTING || $entry_status == entryStatus::DELETED)) {
         $contentPath = myContentStorage::getFSContentRootPath();
         $msgPath = $contentPath . "content/templates/entry/bigthumbnail/";
         if ($entry_status == entryStatus::DELETED) {
             $msgPath .= $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK ? "entry_blocked.swf" : "entry_deleted.swf";
         } else {
             $msgPath .= $entry_status == entryStatus::ERROR_CONVERTING ? "entry_error.swf" : "entry_converting.swf";
         }
         kFileUtils::dumpFile($msgPath, null, 0);
     }
     if (!$file_sync) {
         $tempThumbPath = $entry->getLocalThumbFilePath($version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $density, $stripProfiles, $flavor_id, $file_name);
         if (!$tempThumbPath) {
             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
         }
     }
     if (!$local && !$tempThumbPath && $file_sync) {
         if (!in_array($file_sync->getDc(), kDataCenterMgr::getDcIds())) {
             $remoteUrl = $file_sync->getExternalUrl($entry->getId());
             header("Location: {$remoteUrl}");
             KExternalErrors::dieGracefully();
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']);
         kFileUtils::dumpUrl($remoteUrl);
     }
     // if we didnt return a template for the player die and dont return the original deleted thumb
     if ($entry_status == entryStatus::DELETED) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
     }
     if (!$tempThumbPath) {
         try {
             $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $imageFilePath, $density, $stripProfiles, $thumbParams, $format);
         } catch (Exception $ex) {
             if ($ex->getCode() != kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 KalturaLog::err("Resize image failed");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             // get original flavor asset
             $origFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry_id);
             if (!$origFlavorAsset) {
                 KalturaLog::err("No original flavor for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
             }
             $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
             $remoteFileSync = kFileSyncUtils::getOriginFileSyncForKey($syncKey, false);
             if (!$remoteFileSync) {
                 // file does not exist on any DC - die
                 KalturaLog::log("Error - no FileSync for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             if ($remoteFileSync->getDc() == kDataCenterMgr::getCurrentDcId()) {
                 KalturaLog::err("Trying to redirect to myself - stop here.");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             if (!in_array($remoteFileSync->getDc(), kDataCenterMgr::getDcIds())) {
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync);
             kFileUtils::dumpUrl($remoteUrl);
         }
     }
     $nocache = false;
     if ($securyEntryHelper->shouldDisableCache() || kApiCache::hasExtraFields() || !$securyEntryHelper->isKsWidget() && $securyEntryHelper->hasRules(ContextType::THUMBNAIL)) {
         $nocache = true;
     }
     $cache = null;
     if (!is_null($entry->getPartner())) {
         $partnerCacheAge = $entry->getPartner()->getThumbnailCacheAge();
     }
     if ($nocache) {
         $cacheAge = 0;
     } else {
         if ($partnerCacheAge) {
             $cacheAge = $partnerCacheAge;
         } else {
             if (strpos($tempThumbPath, "_NOCACHE_") !== false) {
                 $cacheAge = 60;
             } else {
                 $cacheAge = 3600;
                 $cache = new myCache("thumb", 2592000);
                 // 30 days, the max memcache allows
             }
         }
     }
     $lastModified = $entry->getAssetCacheTime();
     $renderer = kFileUtils::getDumpFileRenderer($tempThumbPath, null, $cacheAge, 0, $lastModified);
     $renderer->partnerId = $entry->getPartnerId();
     if ($cache) {
         $invalidationKey = $entry->getCacheInvalidationKeys();
         $invalidationKey = kQueryCache::CACHE_PREFIX_INVALIDATION_KEY . $invalidationKey[0];
         $cacheTime = time() - kQueryCache::CLOCK_SYNC_TIME_MARGIN_SEC;
         $cachedResponse = array($renderer, $invalidationKey, $cacheTime);
         $cache->put($_SERVER["REQUEST_URI"], $cachedResponse);
     }
     $renderer->output();
     KExternalErrors::dieGracefully();
     // TODO - can delete from disk assuming we caneasily recreate it and it will anyway be cached in the CDN
     // however dumpfile dies at the end so we cant just write it here (maybe register a shutdown callback)
 }
예제 #23
0
 public static function createWidgetImage($partner, $create)
 {
     $contentPath = myContentStorage::getFSContentRootPath();
     $path = kFile::fixPath($contentPath . $partner->getWidgetImagePath());
     // if the create flag is not set and the file doesnt exist exit
     // e.g. the roughcut name has change, we update the image only if it was already in some widget
     if (!$create && !file_exists($path)) {
         return;
     }
     $im = imagecreatetruecolor(400, 20);
     $green = imagecolorallocate($im, 188, 230, 99);
     $white = imagecolorallocate($im, 255, 255, 255);
     $font = SF_ROOT_DIR . '/web/ttf/arial.ttf';
     $fontSize = 9;
     $bottom = 15;
     $pos = imagettftext($im, $fontSize, 0, 10, $bottom, $green, $font, $partner->getPartnerName() . " Collaborative Video");
     $pos = imagettftext($im, $fontSize, 0, $pos[2], $bottom, $white, $font, " powered by ");
     imagettftext($im, $fontSize, 0, $pos[2], $bottom, $green, $font, "Kaltura");
     kFile::fullMkdir($path);
     imagegif($im, $path);
     imagedestroy($im);
 }
예제 #24
0
 /**
  * Move the uploaded file
  * @param unknown_type $fileData
  */
 protected function handleMoveFile($fileData)
 {
     // get the upload path
     $extension = strtolower(pathinfo($fileData['name'], PATHINFO_EXTENSION));
     // in firefox html5 upload the extension is missing (file name is "blob") so try fetching the extesion from
     // the original file name that was passed to the uploadToken
     if ($extension === "" || $extension == "tmp" && $this->_uploadToken->getFileName()) {
         $extension = strtolower(pathinfo($this->_uploadToken->getFileName(), PATHINFO_EXTENSION));
     }
     $uploadFilePath = $this->getUploadPath($this->_uploadToken->getId(), $extension);
     $this->_uploadToken->setUploadTempPath($uploadFilePath);
     kFile::fullMkdir($uploadFilePath, 0700);
     $moveFileSuccess = kFile::moveFile($fileData['tmp_name'], $uploadFilePath);
     if (!$moveFileSuccess) {
         $msg = "Failed to move uploaded file for token id [{$this->_uploadToken->getId()}]";
         KalturaLog::log($msg . ' ' . print_r($fileData, true));
         throw new kUploadTokenException($msg, kUploadTokenException::UPLOAD_TOKEN_FAILED_TO_MOVE_UPLOADED_FILE);
     }
     chmod($uploadFilePath, 0600);
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL2;
     requestUtils::handleConditionalGet();
     ignore_user_abort();
     $entry_id = $this->getRequestParameter("entry_id");
     $widget_id = $this->getRequestParameter("widget_id", 0);
     $upload_token_id = $this->getRequestParameter("upload_token_id");
     $version = $this->getIntRequestParameter("version", null, 0, 10000000);
     $type = $this->getIntRequestParameter("type", 1, 1, 5);
     //Hack: if KMS sends thumbnail request containing "!" char, the type should be treated as 5.
     $width = $this->getRequestParameter("width", -1);
     $height = $this->getRequestParameter("height", -1);
     if (strpos($width, "!") || strpos($height, "!")) {
         $type = 5;
     }
     $width = $this->getFloatRequestParameter("width", -1, -1, 10000);
     $height = $this->getFloatRequestParameter("height", -1, -1, 10000);
     $crop_provider = $this->getRequestParameter("crop_provider", null);
     $quality = $this->getIntRequestParameter("quality", 0, 0, 100);
     $src_x = $this->getFloatRequestParameter("src_x", 0, 0, 10000);
     $src_y = $this->getFloatRequestParameter("src_y", 0, 0, 10000);
     $src_w = $this->getFloatRequestParameter("src_w", 0, 0, 10000);
     $src_h = $this->getFloatRequestParameter("src_h", 0, 0, 10000);
     $vid_sec = $this->getFloatRequestParameter("vid_sec", -1, -1);
     $vid_slice = $this->getRequestParameter("vid_slice", -1);
     $vid_slices = $this->getRequestParameter("vid_slices", -1);
     $density = $this->getFloatRequestParameter("density", 0, 0);
     $stripProfiles = $this->getRequestParameter("strip", null);
     $flavor_id = $this->getRequestParameter("flavor_id", null);
     $file_name = $this->getRequestParameter("file_name", null);
     $file_name = basename($file_name);
     // actual width and height of image from which the src_* values were taken.
     // these will be used to multiply the src_* parameters to make them relate to the original image size.
     $rel_width = $this->getFloatRequestParameter("rel_width", -1, -1, 10000);
     $rel_height = $this->getFloatRequestParameter("rel_height", -1, -1, 10000);
     if ($width == -1 && $height == -1) {
         $width = 120;
         $height = 90;
     } else {
         if ($width == -1) {
             // if only either width or height is missing reset them to zero, and convertImage will handle them
             $width = 0;
         } else {
             if ($height == -1) {
                 $height = 0;
             }
         }
     }
     $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
     $partner = null;
     // validating the inputs
     if (!is_numeric($quality) || $quality < 0 || $quality > 100) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'quality must be between 20 and 100');
     }
     if (!is_numeric($src_x) || $src_x < 0 || $src_x > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_x must be between 0 and 10000');
     }
     if (!is_numeric($src_y) || $src_y < 0 || $src_y > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_y must be between 0 and 10000');
     }
     if (!is_numeric($src_w) || $src_w < 0 || $src_w > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_w must be between 0 and 10000');
     }
     if (!is_numeric($src_h) || $src_h < 0 || $src_h > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_h must be between 0 and 10000');
     }
     if (!is_numeric($width) || $width < 0 || $width > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'width must be between 0 and 10000');
     }
     if (!is_numeric($height) || $height < 0 || $height > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'height must be between 0 and 10000');
     }
     if (!is_numeric($density) || $density < 0) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'density must be positive');
     }
     if (!is_numeric($vid_sec) || $vid_sec < -1) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'vid_sec must be positive');
     }
     if (!preg_match('/^[0-9a-fA-F]{1,6}$/', $bgcolor)) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'bgcolor must be six hexadecimal characters');
     }
     if ($upload_token_id) {
         $upload_token = UploadTokenPeer::retrieveByPK($upload_token_id);
         if ($upload_token) {
             $partnerId = $upload_token->getPartnerId();
             $partner = PartnerPeer::retrieveByPK($partnerId);
             if ($density == 0) {
                 $density = $partner->getDefThumbDensity();
             }
             if (is_null($stripProfiles)) {
                 $stripProfiles = $partner->getStripThumbProfile();
             }
             $thumb_full_path = myContentStorage::getFSCacheRootPath() . myContentStorage::getGeneralEntityPath("uploadtokenthumb", $upload_token->getIntId(), $upload_token->getId(), $upload_token->getId() . ".jpg");
             kFile::fullMkdir($thumb_full_path);
             if (file_exists($upload_token->getUploadTempPath())) {
                 $src_full_path = $upload_token->getUploadTempPath();
                 $valid_image_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_WBMP);
                 $image_type = exif_imagetype($src_full_path);
                 if (!in_array($image_type, $valid_image_types)) {
                     // capture full frame
                     myFileConverter::captureFrame($src_full_path, $thumb_full_path, 1, "image2", -1, -1, 3);
                     if (!file_exists($thumb_full_path)) {
                         myFileConverter::captureFrame($src_full_path, $thumb_full_path, 1, "image2", -1, -1, 0);
                     }
                     $src_full_path = $thumb_full_path;
                 }
                 // and resize it
                 myFileConverter::convertImage($src_full_path, $thumb_full_path, $width, $height, $type, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h, $density, $stripProfiles);
                 kFile::dumpFile($thumb_full_path);
             } else {
                 KalturaLog::debug("token_id [{$upload_token_id}] not found in DC [" . kDataCenterMgr::getCurrentDcId() . "]. dump url to romote DC");
                 $remoteUrl = kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()) . $_SERVER['REQUEST_URI'];
                 kFile::dumpUrl($remoteUrl);
             }
         }
     }
     if ($entry_id) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             // problem could be due to replication lag
             kFile::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
         }
     } else {
         // get the widget
         $widget = widgetPeer::retrieveByPK($widget_id);
         if (!$widget) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_AND_WIDGET_NOT_FOUND);
         }
         // get the kshow
         $kshow_id = $widget->getKshowId();
         $kshow = kshowPeer::retrieveByPK($kshow_id);
         if ($kshow) {
             $entry_id = $kshow->getShowEntryId();
         } else {
             $entry_id = $widget->getEntryId();
         }
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     $partner = $entry->getPartner();
     if ($density == 0) {
         $density = $partner->getDefThumbDensity();
     }
     $thumbParams = new kThumbnailParameters();
     $thumbParams->setSupportAnimatedThumbnail($partner->getSupportAnimatedThumbnails());
     if (is_null($stripProfiles)) {
         $stripProfiles = $partner->getStripThumbProfile();
     }
     //checks whether the thumbnail display should be restricted by KS
     $base64Referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64Referrer);
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     if (!$referrer) {
         $referrer = kApiCache::getHttpReferrer();
     }
     $ksStr = $this->getRequestParameter("ks");
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, accessControlContextType::THUMBNAIL);
     $securyEntryHelper->validateForPlay();
     // multiply the passed $src_* values so that they will relate to the original image size, according to $src_display_*
     if ($rel_width != -1) {
         $widthRatio = $entry->getWidth() / $rel_width;
         $src_x = $src_x * $widthRatio;
         $src_w = $src_w * $widthRatio;
     }
     if ($rel_height != -1) {
         $heightRatio = $entry->getHeight() / $rel_height;
         $src_y = $src_y * $heightRatio;
         $src_h = $src_h * $heightRatio;
     }
     $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB;
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA;
     }
     KalturaLog::debug("get thumbnail filesyncs");
     $dataKey = $entry->getSyncKey($subType);
     list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($dataKey, true, false);
     $tempThumbPath = null;
     $entry_status = $entry->getStatus();
     // both 640x480 and 0x0 requests are probably coming from the kdp
     // 640x480 - old kdp version requesting thumbnail
     // 0x0 - new kdp version requesting the thumbnail of an unready entry
     // we need to distinguish between calls from the kdp and calls from a browser: <img src=...>
     // that can't handle swf input
     if (($width == 640 && $height == 480 || $width == 0 && $height == 0) && ($entry_status == entryStatus::PRECONVERT || $entry_status == entryStatus::IMPORT || $entry_status == entryStatus::ERROR_CONVERTING || $entry_status == entryStatus::DELETED)) {
         $contentPath = myContentStorage::getFSContentRootPath();
         $msgPath = $contentPath . "content/templates/entry/bigthumbnail/";
         if ($entry_status == entryStatus::DELETED) {
             $msgPath .= $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK ? "entry_blocked.swf" : "entry_deleted.swf";
         } else {
             $msgPath .= $entry_status == entryStatus::ERROR_CONVERTING ? "entry_error.swf" : "entry_converting.swf";
         }
         kFile::dumpFile($msgPath, null, 0);
     }
     if (!$file_sync) {
         $tempThumbPath = $entry->getLocalThumbFilePath($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $density, $stripProfiles, $flavor_id, $file_name);
         if (!$tempThumbPath) {
             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
         }
     }
     if (!$local && !$tempThumbPath && $file_sync) {
         if (!in_array($file_sync->getDc(), kDataCenterMgr::getDcIds())) {
             $remoteUrl = $file_sync->getExternalUrl($entry->getId());
             header("Location: {$remoteUrl}");
             die;
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']);
         kFile::dumpUrl($remoteUrl);
     }
     // if we didnt return a template for the player die and dont return the original deleted thumb
     if ($entry_status == entryStatus::DELETED) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
     }
     if (!$tempThumbPath) {
         try {
             $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, null, $density, $stripProfiles, $thumbParams);
         } catch (Exception $ex) {
             if ($ex->getCode() != kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 KalturaLog::log("Error - resize image failed");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             // get original flavor asset
             $origFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry_id);
             if (!$origFlavorAsset) {
                 KalturaLog::log("Error - no original flavor for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
             }
             $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
             $remoteFileSync = kFileSyncUtils::getOriginFileSyncForKey($syncKey, false);
             if (!$remoteFileSync) {
                 // file does not exist on any DC - die
                 KalturaLog::log("Error - no FileSync for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             if ($remoteFileSync->getDc() == kDataCenterMgr::getCurrentDcId()) {
                 KalturaLog::log("ERROR - Trying to redirect to myself - stop here.");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             if (!in_array($remoteFileSync->getDc(), kDataCenterMgr::getDcIds())) {
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync);
             kFile::dumpUrl($remoteUrl);
         }
     }
     $nocache = strpos($tempThumbPath, "_NOCACHE_") !== false;
     if ($securyEntryHelper->shouldDisableCache() || kApiCache::hasExtraFields() || !$securyEntryHelper->isKsWidget() && $securyEntryHelper->hasRules()) {
         $nocache = true;
     }
     // notify external proxy, so it'll cache this url
     if (!$nocache && requestUtils::getHost() == kConf::get("apphome_url") && file_exists($tempThumbPath)) {
         self::notifyProxy($_SERVER["REQUEST_URI"]);
     }
     // cache result
     if (!$nocache) {
         $requestKey = $_SERVER["REQUEST_URI"];
         $cache = new myCache("thumb", 86400 * 30);
         // 30 days
         $cache->put($requestKey, $tempThumbPath);
     }
     kFile::dumpFile($tempThumbPath, null, $nocache ? 0 : null);
     // TODO - can delete from disk assuming we caneasily recreate it and it will anyway be cached in the CDN
     // however dumpfile dies at the end so we cant just write it here (maybe register a shutdown callback)
 }
예제 #26
0
 public static function moveFromFile($temp_file_path, FileSyncKey $target_key, $strict = true, $copyOnly = false)
 {
     KalturaLog::log(__METHOD__ . " - move file: [{$temp_file_path}] to key [{$target_key}], ");
     $c = FileSyncPeer::getCriteriaForFileSyncKey($target_key);
     $existsFileSync = FileSyncPeer::doSelectOne($c);
     if ($existsFileSync) {
         KalturaLog::log(__METHOD__ . " - file already exists");
         if ($strict) {
             throw new Exception("key [" . $target_key . "] already exists");
         }
     }
     $targetFullPath = self::getLocalFilePathForKey($target_key);
     if (!$targetFullPath) {
         $targetFullPath = kPathManager::getFilePath($target_key);
         KalturaLog::log(__METHOD__ . " - Generated new path [{$targetFullPath}]");
     }
     if (!file_exists(dirname($targetFullPath))) {
         KalturaLog::log(__METHOD__ . " - creating directory for file");
         kFile::fullMkdir($targetFullPath);
     }
     if (file_exists($temp_file_path)) {
         KalturaLog::log(__METHOD__ . " - {$temp_file_path} file exists");
     } else {
         KalturaLog::log(__METHOD__ . " - {$temp_file_path} file doesnt exist");
     }
     if ($copyOnly) {
         $success = copy($temp_file_path, $targetFullPath);
     } else {
         $success = kFile::moveFile($temp_file_path, $targetFullPath);
     }
     if ($success) {
         if (!$existsFileSync) {
             self::createSyncFileForKey($target_key, $strict);
         }
     } else {
         KalturaLog::log(__METHOD__ . " - could not move file from [{$temp_file_path}] to [{$targetFullPath}]");
         throw new Exception("Could not move file from [{$temp_file_path}] to [{$targetFullPath}]");
     }
 }