function UploadToCloud($file_source, $model_id, $model_name, $type, $mime_type, $file_ext = null) { App::import('Vendor', 'S3', array('file' => 'S3.php')); $s3 = new S3($this->awsAccessKey, $this->awsSecretKey, true, "s3-ap-southeast-1.amazonaws.com"); $input = $s3->inputFile($file_source, false); $ext = pathinfo($file_source, PATHINFO_EXTENSION); if ($file_ext != null) { $obj = $s3->putObject($input, $this->bucketName, "contents/" . $model_name . "/" . $model_id . "/" . $model_id . "_" . $type . "." . $file_ext, S3::ACL_PUBLIC_READ, array(), array("Content-Type" => $mime_type)); } else { $obj = $s3->putObject($input, $this->bucketName, "contents/" . $model_name . "/" . $model_id . "/" . $model_id . "_" . $type . "." . $ext, S3::ACL_PUBLIC_READ, array(), array("Content-Type" => $mime_type)); } return $obj; }
public function upload_image() { $config = array('allowed_types' => 'jpg|jpeg|gif|png', 'upload_path' => './temp', 'max_size' => 3072, 'overwrite' => true); $this->load->library('upload', $config); $this->upload->overwrite = true; $response['responseStatus'] = "Not OK"; if (!$this->upload->do_upload()) { $response['responseStatus'] = "Your image could not be uploaded"; } else { $data = $this->upload->data(); //instantiate the class $s3 = new S3(awsAccessKey, awsSecretKey); $ext = pathinfo($data['full_path'], PATHINFO_EXTENSION); $imgName = (string) time() . "." . $ext; $input = S3::inputFile($data['full_path'], FALSE); if ($s3->putObject(file_get_contents($data['full_path']), "tlahui-content", $imgName, S3::ACL_PUBLIC_READ)) { $response['responseStatus'] = "OK"; $response['url'] = "https://s3.amazonaws.com/tlahui-content/" . $imgName; unlink($data['full_path']); } else { $response['responseStatus'] = "Your image could not be uploaded"; unlink($data['full_path']); } } echo json_encode($response); }
/** * Execute the controller. * * @return mixed Return executed result. * * @throws \LogicException * @throws \RuntimeException */ public function execute() { $files = $this->input->files; $field = $this->input->get('field', 'file'); $type = $this->input->get('type', 'post'); try { $src = $files->getByPath($field . '.tmp_name', null, InputFilter::STRING); $name = $files->getByPath($field . '.name', null, InputFilter::STRING); if (!$src) { throw new \Exception('File not upload'); } $dest = $this->getDest($name, $type); $s3 = new \S3($this->app->get('amazon.access_key'), $this->app->get('amazon.secret_key')); $result = $s3::putObject(\S3::inputFile($src, false), 'windspeaker', $dest, \S3::ACL_PUBLIC_READ); if (!$result) { throw new \Exception('Upload fail.'); } } catch (\Exception $e) { $response = new Response(); $response->setBody(json_encode(['error' => $e->getMessage()])); $response->setMimeType('text/json'); $response->respond(); exit; } $return = new Registry(); $return['filename'] = 'https://windspeaker.s3.amazonaws.com/' . $dest; $return['file'] = 'https://windspeaker.s3.amazonaws.com/' . $dest; $response = new Response(); $response->setBody((string) $return); $response->setMimeType('text/json'); $response->respond(); exit; }
/** * upload * * @param \JInput $input */ public static function upload(\JInput $input) { try { $editorPlugin = \JPluginHelper::getPlugin('editors', 'akmarkdown'); if (!$editorPlugin) { throw new \Exception('Editor Akmarkdown not exists'); } $params = new Registry($editorPlugin->params); $files = $input->files; $field = $input->get('field', 'file'); $type = $input->get('type', 'post'); $allows = $params->get('Upload_AllowExtension', ''); $allows = array_map('strtolower', array_map('trim', explode(',', $allows))); $file = $files->getVar($field); $src = $file['tmp_name']; $name = $file['name']; $tmp = new \SplFileInfo(JPATH_ROOT . '/tmp/ak-upload/' . $name); if (empty($file['tmp_name'])) { throw new \Exception('File not upload'); } $ext = pathinfo($name, PATHINFO_EXTENSION); if (!in_array($ext, $allows)) { throw new \Exception('File extension now allowed.'); } // Move file to tmp if (!is_dir($tmp->getPath())) { \JFolder::create($tmp->getPath()); } if (is_file($tmp->getPathname())) { \JFile::delete($tmp->getPathname()); } \JFile::upload($src, $tmp->getPathname()); $src = $tmp; $dest = static::getDest($name, $params->get('Upload_S3_Subfolder', 'ak-upload')); $s3 = new \S3($params->get('Upload_S3_Key'), $params->get('Upload_S3_SecretKey')); $bucket = $params->get('Upload_S3_Bucket'); $result = $s3::putObject(\S3::inputFile($src->getPathname(), false), $bucket, $dest, \S3::ACL_PUBLIC_READ); if (is_file($tmp->getPathname())) { \JFile::delete($tmp->getPathname()); } if (!$result) { throw new \Exception('Upload fail.'); } } catch (\Exception $e) { $response = new Response(); $response->setBody(json_encode(['error' => $e->getMessage()])); $response->setMimeType('text/json'); $response->respond(); exit; } $return = new \JRegistry(); $return['filename'] = 'https://' . $bucket . '.s3.amazonaws.com/' . $dest; $return['file'] = 'https://' . $bucket . '.s3.amazonaws.com/' . $dest; $response = new Response(); $response->setBody((string) $return); $response->setMimeType('text/json'); $response->respond(); }
function create($localpath, $remotepath) { $localpath = realpath($localpath); if (S3::putObject(S3::inputFile($localpath), $this->backupBucket, $remotepath, S3::ACL_PRIVATE)) { return TRUE; } else { return FALSE; } }
function save_sized_image($original, $key, $size, $folder) { $file = $folder . "/" . $key . ".jpg"; $file_path = IMAGES_DIR . "/" . $file; resize_image($original, $size, $file_path); if (STORAGE_STRATEGY == 's3') { $input = S3::inputFile($file_path); S3::putObject($input, S3_BUCKET, $file, S3::ACL_PUBLIC_READ); } }
/** * CRUD controller: CREATE */ public function action_create() { $this->auto_render = FALSE; $this->template = View::factory('js'); if (!isset($_FILES['image'])) { $this->template->content = json_encode('KO'); return; } $image = $_FILES['image']; if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); } if (!Upload::valid($image) or !Upload::not_empty($image) or !Upload::type($image, explode(',', core::config('image.allowed_formats'))) or !Upload::size($image, core::config('image.max_image_size') . 'M')) { if (Upload::not_empty($image) and !Upload::type($image, explode(',', core::config('image.allowed_formats')))) { $this->template->content = json_encode(array('msg' => $image['name'] . ' ' . sprintf(__('Is not valid format, please use one of this formats "%s"'), core::config('image.allowed_formats')))); return; } if (!Upload::size($image, core::config('image.max_image_size') . 'M')) { $this->template->content = json_encode(array('msg' => $image['name'] . ' ' . sprintf(__('Is not of valid size. Size is limited to %s MB per image'), core::config('image.max_image_size')))); return; } $this->template->content = json_encode(array('msg' => $image['name'] . ' ' . __('Image is not valid. Please try again.'))); return; } elseif ($image != NULL) { // saving/uploading img file to dir. $path = 'images/cms/'; $root = DOCROOT . $path; //root folder $image_name = URL::title(pathinfo($image['name'], PATHINFO_FILENAME)); $image_name = Text::limit_chars(URL::title(pathinfo($image['name'], PATHINFO_FILENAME)), 200); $image_name = time() . '.' . $image_name; // if folder does not exist, try to make it if (!file_exists($root) and !@mkdir($root, 0775, true)) { // mkdir not successful ? $this->template->content = json_encode(array('msg' => __('Image folder is missing and cannot be created with mkdir. Please correct to be able to upload images.'))); return; // exit function } // save file to root folder, file, name, dir if ($file = Upload::save($image, $image_name, $root)) { // put image to Amazon S3 if (core::config('image.aws_s3_active')) { $s3->putObject($s3->inputFile($file), core::config('image.aws_s3_bucket'), $path . $image_name, S3::ACL_PUBLIC_READ); } $this->template->content = json_encode(array('link' => Core::config('general.base_url') . $path . $image_name)); return; } else { $this->template->content = json_encode(array('msg' => $image['name'] . ' ' . __('Image file could not been saved.'))); return; } $this->template->content = json_encode(array('msg' => $image['name'] . ' ' . __('Image is not valid. Please try again.'))); } }
function gsUpload($file, $bucket, $remoteFile) { $ret = false; $key = 'GOOGT4X7CFTWS2VWN2HT'; $secret = 'SEWZTyKZH6dNbjbT2CHg5Q5pUh5Y5+iinj0yBFB4'; $server = 'storage.googleapis.com'; $s3 = new S3($key, $secret, false, $server); $metaHeaders = array(); $requestHeaders = array(); if ($s3->putObject($s3->inputFile($file, false), $bucket, $remoteFile, S3::ACL_PUBLIC_READ, $metaHeaders, $requestHeaders)) { $ret = true; } return $ret; }
private function S3copy($file) { $fileok = true; $s3 = new S3($this->AccessKey, $this->SecretKey); $list = $s3->getBucket($this->AWSFolder); foreach ($list as $existing) { if ($existing['name'] === $file) { $fileok = false; } } if ($fileok) { $put = $s3->putObject($s3->inputFile(ASSETS_PATH . DIRECTORY_SEPARATOR . $file), $this->AWSFolder, $file, S3::ACL_PRIVATE); if ($put) { echo $file . " transferred to S3<br>" . "\r\n"; } else { echo $file . " unable to be transferred to S3<br>" . "\r\n"; } } else { echo $file . " already in S3<br>" . "\r\n"; } }
function upload($path) { $access = DB::get()->assoc("SELECT name, value FROM options WHERE grouping = 'Amazon Web Services'"); $s3 = new S3($access['AWS Access Key ID'], $access['AWS Secret Access Key']); $bucketname = $access['S3 Bucket Name']; $filename = $_FILES['uploaded']['name']; $s3filename = $this->_safestring(Auth::user()->username) . '/' . date('YmdHis') . '/' . $filename; preg_match('%\\.(\\w+)$%', $filename, $matches); $filetype = $matches[1]; $s3->putObject(S3::inputFile($_FILES['uploaded']['tmp_name']), $bucketname, $s3filename, S3::ACL_PUBLIC_READ, array(), array("Content-Type" => "application/octet-stream", "Content-Disposition" => "attachment; filename=" . urlencode($filename) . ';')); //echo "Put {$filename} to {$bucketname} at {$s3filename}\n"; $url = "http://{$bucketname}.s3.amazonaws.com/{$s3filename}"; DB::get()->query("INSERT INTO files (user_id, filename, filesize, filetype, url) VALUES (:user_id, :filename, :filesize, :filetype, :url);", array('user_id' => Auth::user_id(), 'filename' => $filename, 'filesize' => $_FILES['uploaded']['size'], 'filetype' => $filetype, 'url' => $url)); $filenumber = DB::get()->lastInsertId(); echo <<<RELOAD_FILES atbottom = isVisible(\$('#notices tr:last-child')); \$('#filelisting').load('/files/filelist', function(){ \t\$('body').css('margin-bottom', \$('#command').height() + 15); \tdo_scroll(); }); send('/file {$filenumber}'); RELOAD_FILES; }
$height = "512"; $isAudio = true; $mediaType = 3; } } } } $md5filename = md5(str_replace(" ", "_", str_replace(".", "", $filename)) . "cometchat" . time()); if ($isImage || $isVideo) { $md5filename .= "." . strtolower($path['extension']); } $unencryptedfilename = rawurlencode($filename); if (defined('AWS_STORAGE') && AWS_STORAGE == '1' && !empty($_FILES['Filedata'])) { include_once dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . "functions" . DIRECTORY_SEPARATOR . "storage" . DIRECTORY_SEPARATOR . "s3.php"; $s3 = new S3(AWS_ACCESS_KEY, AWS_SECRET_KEY); if (!$s3->putObject($s3->inputFile($_FILES['Filedata']['tmp_name'], false), AWS_BUCKET, $bucket_path . 'filetransfer/' . $md5filename, S3::ACL_PUBLIC_READ)) { $error = 1; } $linkToFile = '//' . $aws_bucket_url . '/' . $bucket_path . 'filetransfer/' . $md5filename; $server_url = BASE_URL; } else { if (!empty($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name'])) { if (!move_uploaded_file($_FILES['Filedata']['tmp_name'], dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'writable' . DIRECTORY_SEPARATOR . 'filetransfer' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $md5filename)) { $error = 1; } $linkToFile = BASE_URL . "writable/filetransfer/uploads/" . $md5filename; $server_url = '//' . $_SERVER['SERVER_NAME'] . BASE_URL; if (filter_var(BASE_URL, FILTER_VALIDATE_URL)) { $server_url = BASE_URL; } }
function cache_me($params, $content_type) { global $PREFS, $TMPL; // Set URL constants if (is_readable($params['full_src']) || strstr($params['full_src'], 'http://') || strstr($params['full_src'], 'https://')) { $original = file_get_contents($params['full_src']); } else { $file_url = "http"; if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") { $file_url .= "s"; } $file_url .= "://www." . $_SERVER['HTTP_HOST'] . $params['src']; file_get_contents($file_url); } $filename = basename($params['src']); $cache_structure = pathinfo($params['cache_src']); $cache_dirname = $cache_structure['dirname']; $cache_basename = $cache_structure['basename']; $cache_filename = $cache_structure['filename']; // Create Cache Dir if it does not exist if (!is_dir($cache_dirname)) { if (!mkdir($cache_dirname, 0777, true)) { error_log("I did not write the cache dir"); } } if (!defined("FILE_PUT_CONTENTS_ATOMIC_TEMP")) { define("FILE_PUT_CONTENTS_ATOMIC_TEMP", $cache_dirname); } if (!defined("FILE_PUT_CONTENTS_ATOMIC_MODE")) { define("FILE_PUT_CONTENTS_ATOMIC_MODE", 0777); } if (!defined("FILE_PUT_CONTENTS_ATOMIC_OWN")) { define("FILE_PUT_CONTENTS_ATOMIC_OWN", 'deploy'); } $temp = tempnam(FILE_PUT_CONTENTS_ATOMIC_TEMP, 'temp'); if (!($f = @fopen($temp, 'wb'))) { $temp = FILE_PUT_CONTENTS_ATOMIC_TEMP . DIRECTORY_SEPARATOR . uniqid('temp'); if (!($f = @fopen($temp, 'wb'))) { trigger_error("file_put_contents_atomic() : error writing temporary file '{$temp}'", E_USER_WARNING); return false; } } // Check to see if its a parsed CSS file, if so write the parsed data if (!empty($params['cssfile_content'])) { fwrite($f, $params['cssfile_content']); } else { fwrite($f, $original); } fclose($f); if (!@rename($temp, $params['cache_src'])) { @unlink($params['cache_src']); @rename($temp, $params['cache_src']); } //AWS access info - Make sure to add this to your config.php file $s3assetsConfig = $PREFS->core_ini['s3assets']; if (isset($s3assetsConfig['user'])) { if (!defined("FILE_PUT_CONTENTS_ATOMIC_OWN")) { define("FILE_PUT_CONTENTS_ATOMIC_OWN", $s3assetsConfig['user']); } chown($params['cache_src'], FILE_PUT_CONTENTS_ATOMIC_OWN); } chmod($params['cache_src'], FILE_PUT_CONTENTS_ATOMIC_MODE); // Initiate S3 class and upload the file if ($params['s3bucket'] != "") { if (!class_exists('S3')) { require_once 'pi.s3assets/S3.php'; } $awsAccessKey = $s3assetsConfig['awsAccessKey']; $awsSecretKey = $s3assetsConfig['awsSecretKey']; if (!defined('awsAccessKey')) { define('awsAccessKey', $awsAccessKey); } if (!defined('awsSecretKey')) { define('awsSecretKey', $awsSecretKey); } $s3 = new S3(awsAccessKey, awsSecretKey, false); if (isset($params['s3assetname'])) { $src = preg_replace("/^\\//", "", $params['s3assetname']); } else { $src = preg_replace("/^\\//", "", $params['src']); } S3::putObject(S3::inputFile($params['cache_src']), $params['s3bucket'], $src, S3::ACL_PUBLIC_READ, array(), array("Content-Type" => $content_type, "Cache-Control" => "max-age=315360000", "Expires" => gmdate("D, d M Y H:i:s T", strtotime("+5 years")))); } }
function cron_aws($aws_accesskey, $aws_secretkey, $aws_bucket, $aws_directory, $file, $delete_after_int = 0) { $details = ''; $details .= "AWS Access Key: " . $aws_accesskey . "\n"; if ($this->_debug) { $details .= "AWS Secret Key: " . $aws_secretkey . "\n"; } else { $details .= "AWS Secret Key: *hidden*\n"; } $details .= "AWS Bucket: " . $aws_bucket . "\n"; $details .= "AWS Directory: " . $aws_directory . "\n"; $details .= "Local File & Path: " . $this->_options['backup_directory'] . '/' . basename($file) . "\n"; $details .= "Filename: " . basename($file) . "\n"; $this->log('Starting Amazon S3 cron. Details: ' . $details); require_once dirname(__FILE__) . '/lib/s3/s3.php'; $s3 = new S3($aws_accesskey, $aws_secretkey); if ($this->_options['aws_ssl'] != '1') { S3::$useSSL = false; } $this->log('About to put bucket to Amazon S3 cron.'); $s3->putBucket($aws_bucket, S3::ACL_PUBLIC_READ); $this->log('About to put object (the file) to Amazon S3 cron.'); if ($s3->putObject(S3::inputFile($file), $aws_bucket, $aws_directory . '/' . basename($file), S3::ACL_PRIVATE)) { // success $this->log('SUCCESS sending to Amazon S3!'); } else { $this->mail_notice('ERROR #9002! Failed sending file to Amazon S3. Details:' . "\n\n" . $details); $this->log('FAILURE sending to Amazon S3! Details: ' . $details, 'error'); } if ($delete_after_int == 1) { $this->log('Deleting backup file after Amazon S3 cron.'); unlink($file); $this->log('Done deleting backup file after Amazon S3 cron.'); } }
function file_handleInput($Field, $Input, $FieldType, $Config, $predata) { if (strtolower($Config['Content']['_ViewMode']) == 'api') { if (!empty($_FILES[$Field]['size'])) { $_FILES['dataForm']['name'][$Config['ID']][$Field] = $_FILES[$Field]['name']; $_FILES['dataForm']['size'][$Config['ID']][$Field] = $_FILES[$Field]['size']; $_FILES['dataForm']['tmp_name'][$Config['ID']][$Field] = $_FILES[$Field]['tmp_name']; } } if ($FieldType == 'multi') { return $Input; } if (!empty($_POST['deleteImage'][$Field])) { $FileInfo = explode('?', $predata[$Field]); if (file_exists($FileInfo[0])) { unlink($FileInfo[0]); } return ''; } if (empty($_FILES['dataForm']['name'][$Config['ID']][$Field])) { return $predata[$Field]; } // Create Directorys if (!empty($_FILES['dataForm']['size'][$Config['ID']][$Field])) { $path = wp_upload_dir(); // set filename and paths $Ext = pathinfo($_FILES['dataForm']['name'][$Config['ID']][$Field]); $newFileName = uniqid($Config['ID'] . '_') . '.' . $Ext['extension']; $newLoc = $path['path'] . '/' . $newFileName; //$urlLoc = $path['url'].'/'.$newFileName; $GLOBALS['UploadedFile'][$Field] = $newLoc; $upload = wp_upload_bits($_FILES['dataForm']['name'][$Config['ID']][$Field], null, file_get_contents($_FILES['dataForm']['tmp_name'][$Config['ID']][$Field])); if (!empty($Config['Content']['_filesToLibrary'])) { global $user_ID; $type = wp_check_filetype($upload['file']); $new_post = array('post_title' => $Ext['filename'], 'post_status' => 'inherit', 'post_date' => date('Y-m-d H:i:s'), 'post_author' => $user_ID, 'post_type' => 'attachment', 'post_mime_type' => $type['type'], 'guid' => $upload['url']); // This should never be set as it would then overwrite an existing attachment. if (isset($attachment['ID'])) { unset($attachment['ID']); } // Save the data //$id = wp_insert_attachment($new_post, $upload['file']); //if ( !is_wp_error($id) ) { // if(!function_exists('wp_generate_attachment_metadata')){ //require_once('includes/image.php'); // } //wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) ); //} } //move_uploaded_file($_FILES['dataForm']['tmp_name'][$Config['ID']][$Field], $newLoc); //return $newLoc; if ($FieldType == 'image') { $imageWidth = $Config['Content']['_ImageSizeX'][$Field] == 'auto' ? '0' : $Config['Content']['_ImageSizeX'][$Field]; $imageHeight = $Config['Content']['_ImageSizeY'][$Field] == 'auto' ? '0' : $Config['Content']['_ImageSizeY'][$Field]; $iconWidth = $Config['Content']['_IconSizeX'][$Field] == 'auto' ? '0' : $Config['Content']['_IconSizeX'][$Field]; $iconHeight = $Config['Content']['_IconSizeY'][$Field] == 'auto' ? '0' : $Config['Content']['_IconSizeY'][$Field]; // crunch sizes $image = image_resize($upload['file'], $imageWidth, $imageHeight, true); $icon = image_resize($upload['file'], $iconWidth, $iconHeight, true); } //vardump($upload); //vardump($Config['Content']['_AWSBucket']); //die; if (!empty($Config['Content']['_enableS3'][$Field]) && !empty($Config['Content']['_AWSAccessKey'][$Field]) && !empty($Config['Content']['_AWSSecretKey'][$Field])) { include_once DB_TOOLKIT . 'data_form/fieldtypes/file/s3.php'; $s3 = new S3($Config['Content']['_AWSAccessKey'][$Field], $Config['Content']['_AWSSecretKey'][$Field]); $input = $s3->inputFile($upload['file']); $fileName = date('Y') . '/' . date('m') . '/' . $newFileName; if ($s3->putObject($input, $Config['Content']['_AWSBucket'][$Field], $fileName, 'public-read')) { unlink($upload['file']); return $fileName; } } return $upload['url']; } }
public static function s3Upload($source_filename, $dest_filename, $public = true, $title) { S3::setAuth(S3_ACCESS_KEY, S3_SECRET_KEY); if (S3::putObject(S3::inputFile($source_filename), S3_BUCKET, $dest_filename, $public ? S3::ACL_PUBLIC_READ : '', array(), array('Content-Disposition' => 'attachment; filename="' . $title . '"'))) { return true; } else { throw new Exception("S3 upload failed ({$source_filename})"); } }
/** * Publish to AWS S3 bucket * * @return boolean|WP_Error */ public function publish_to_s3($bucket, $aws_access_key_id, $aws_secret_access_key) { $directory_iterator = new RecursiveDirectoryIterator($this->archive_dir, RecursiveDirectoryIterator::SKIP_DOTS); $recursive_iterator = new RecursiveIteratorIterator($directory_iterator, RecursiveIteratorIterator::SELF_FIRST); S3::$useExceptions = true; $s3 = new S3($aws_access_key_id, $aws_secret_access_key, false, 's3-eu-west-1.amazonaws.com'); foreach ($recursive_iterator as $item) { if (!$item->isDir()) { $path = $recursive_iterator->getSubPathName(); try { $s3->putObject(S3::inputFile($item->getRealPath()), $bucket, $path, S3::ACL_PUBLIC_READ); } catch (any $err) { return new WP_Error('cannot_publish_to_s3', sprintf(__("Could not publish file to S3: %s: %s", $this->slug, $err), $path)); } } } return true; }
public static function uploadFile(Zotero_StorageFileInfo $info, $file, $contentType) { Zotero_S3::requireLibrary(); S3::setAuth(Z_CONFIG::$S3_ACCESS_KEY, Z_CONFIG::$S3_SECRET_KEY); if (!file_exists($file)) { throw new Exception("File '{$file}' does not exist"); } $success = S3::putObject(S3::inputFile($file), Z_CONFIG::$S3_BUCKET, self::getPathPrefix($info->hash, $info->zip) . $info->filename, S3::ACL_PRIVATE, array(), array("Content-Type" => $contentType)); if (!$success) { return false; } return self::addFile($info); }
/** * Puts an object from a file (legacy function) * * @param string $file Input file path * @param string $bucket Bucket name * @param string $uri Object URI * @param constant $acl ACL constant * @param array $metaHeaders Array of x-amz-meta-* headers * @param string $contentType Content type * @return boolean */ public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) { return self::putObject(S3::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType); }
$fileName = $_FILES['upload']['name']; $extension_explode = explode('.', $fileName); $extension = $extension_explode[count($extension_explode) - 1]; $time = time(); $allowed = array("jpeg", "jpg", "gif", "png"); $content_type = $_FILES['upload']['type']; if (in_array($extension, $allowed)) { $awsAccessKey = get_app_info('s3_key'); $awsSecretKey = get_app_info('s3_secret'); $bucketName = 'rime-sendy'; //Change accordingly $endpoint = 's3-us-west-2.amazonaws.com'; //Change accordingly $s3 = new S3($awsAccessKey, $awsSecretKey, false, $endpoint); $s3Filename = date('Ymd-His', $time) . '.' . $extension; if ($s3->putObject($s3->inputFile($file), $bucketName, $s3Filename, S3::ACL_PUBLIC_READ, array(), array('Content-Type' => $content_type))) { $array = array('filelink' => 'http://' . $endpoint . '/' . $bucketName . '/' . $s3Filename); // echo stripslashes(json_encode($array)); // Required: anonymous function reference number as explained above. $funcNum = $_GET['CKEditorFuncNum']; // Optional: instance name (might be used to load a specific configuration file or anything else). $CKEditor = $_GET['CKEditor']; // Optional: might be used to provide localized messages. $langCode = $_GET['langCode']; // Check the $_FILES array and save the file. Assign the correct path to a variable ($url). // $url = APP_PATH.'/uploads/'.$time.'.'.$extension; $url = 'http://' . $endpoint . '/' . $bucketName . '/' . $s3Filename; // Usually you will only assign something here if the file could not be uploaded. $message = ''; echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction({$funcNum}, '{$url}', '{$message}');</script>"; } else {
public function createFromFile($type, $file) { $directory = dirname($file); $arr = array_reverse(explode("/", $file)); $fileName = $arr[0]; $uri = "{$type}/{$fileName}"; if (S3::putObject(S3::inputFile("{$file}"), S3Voota::getBucketOri(), "{$type}/{$fileName}", S3::ACL_PRIVATE)) { $img = new sfImage($file); $img->voota(); $this->putObjectCached(S3::inputFile("/tmp/cc_{$fileName}"), S3Voota::getBucketPub(), "{$type}/cc_{$fileName}", S3::ACL_PUBLIC_READ); unlink("/tmp/cc_{$fileName}"); $this->putObjectCached(S3::inputFile("/tmp/bw_{$fileName}"), S3Voota::getBucketPub(), "{$type}/bw_{$fileName}", S3::ACL_PUBLIC_READ); unlink("/tmp/bw_{$fileName}"); $this->putObjectCached(S3::inputFile("/tmp/cc_s_{$fileName}"), S3Voota::getBucketPub(), "{$type}/cc_s_{$fileName}", S3::ACL_PUBLIC_READ); unlink("/tmp/cc_s_{$fileName}"); $this->putObjectCached(S3::inputFile("/tmp/bw_s_{$fileName}"), S3Voota::getBucketPub(), "{$type}/bw_s_{$fileName}", S3::ACL_PUBLIC_READ); unlink("/tmp/bw_s_{$fileName}"); } }
/** * push a file to a location on S3 based on a path from the local server that this plugin * is running on. * @param string $filePathToUpload - absolute path to local file that needs to be uploaded * @param string $locationOnS3 - path the file should have on S3 relative to the current bucket * @param string $permission - the access permissions the file should have, defaults to Public Read Acess * @param string $mimeType - set the mime type of the object in S3, defaults to autodetect * @return mixed - returns an array with details of the uploaded file on S3 for success, FALSE on failure */ public function putObject($filePathToUpload, $locationOnS3, $permission = self::ACL_PUBLIC_READ, $mimeType = null) { S3::putObject(S3::inputFile($filePathToUpload), $this->bucket, $locationOnS3, $permission, array(), $mimeType); $info = $this->getObjectInfo($locationOnS3); return array('name' => basename($locationOnS3), 'url' => $this->buildUrlToFile($locationOnS3), 'size' => $info['size']); }
/** * Put an object from a file. * * @param string $file Input data * @param string $uri Object URI * @param string $acl ACL constant * @param array $metaHeaders Array of x-amz-meta-* headers * @param string $contentType Content type * * @return boolean */ public static function upload($file, $uri, $acl = \S3::ACL_PUBLIC_READ, $metaHeaders = array()) { $uri = ltrim(static::getSubfolder() . '/' . $uri, '/'); return static::putObject(\S3::inputFile($file, false), static::getBucketName(), $uri, $acl, $metaHeaders); }
function remote_send_s3($accesskey, $secretkey, $bucket, $directory = '', $ssl, $file) { $this->log('Starting Amazon S3 transfer.'); require_once dirname(__FILE__) . '/lib/s3/s3.php'; $s3 = new S3($accesskey, $secretkey); if ($ssl != '1') { S3::$useSSL = false; } $this->log('About to put bucket to Amazon S3 cron.'); $s3->putBucket($bucket, S3::ACL_PUBLIC_READ); $this->log('About to put object (the file) to Amazon S3 cron.'); if (!empty($directory)) { $directory = $directory . '/'; } if ($s3->putObject(S3::inputFile($file), $bucket, $directory . basename($file), S3::ACL_PRIVATE)) { $this->log('SUCCESS sending to Amazon S3!'); return true; } else { $this->mail_error('ERROR #9002! Failed sending file to Amazon S3.'); $this->log('FAILURE sending to Amazon S3!', 'error'); return false; } }
/** * put * * @param string $src * @param string $dest * * @return boolean */ public static function put($src, $dest) { return static::putObject(\S3::inputFile($src, false), 'windspeaker', $dest, \S3::ACL_PUBLIC_READ); }
/** * save_image upload images with given path * * @param [array] $image [image $_FILE-s ] * @param [string] $seotitle [unique id, and folder name] * @return [bool] [return true if 1 or more images uploaded, false otherwise] */ public function save_image($image) { if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); } if (!Upload::valid($image) or !Upload::not_empty($image) or !Upload::type($image, explode(',', core::config('image.allowed_formats'))) or !Upload::size($image, core::config('image.max_image_size') . 'M')) { if (Upload::not_empty($image) && !Upload::type($image, explode(',', core::config('image.allowed_formats')))) { return Alert::set(Alert::ALERT, $image['name'] . ': ' . sprintf(__('This uploaded image is not of a valid format. Please use one of these formats: %s'), core::config('image.allowed_formats'))); } if (!Upload::size($image, core::config('image.max_image_size') . 'M')) { return Alert::set(Alert::ALERT, $image['name'] . ': ' . sprintf(__("This uploaded image exceeds the allowable limit. Uploaded images cannot be larger than %s MB per image"), core::config('image.max_image_size'))); } } if ($image !== NULL) { $id = $this->id_product; $seotitle = $this->seotitle; $obj_product = new self($id); if ($obj_product->loaded()) { $created = $obj_product->created; } else { $created = NULL; } $path = $this->image_path($id, $created); $docroot = DOCROOT; $directory = $docroot . $path; $image_quality = core::config('image.quality'); $width = core::config('image.width'); $width_thumb = core::config('image.width_thumb'); $height_thumb = core::config('image.height_thumb'); $height = core::config('image.height'); if (!is_numeric($height)) { // when installing this field is empty, to avoid crash we check here $height = NULL; } if (!is_numeric($height_thumb)) { $height_thumb = NULL; } // how many files are saved $counter = $this->has_images > 0 ? $this->has_images + 1 : 1; if ($file = Upload::save($image, NULL, $directory)) { $filename_thumb = 'thumb_' . $seotitle . '_' . $counter . '.jpg'; $filename_original = $seotitle . '_' . $counter . '.jpg'; //if original image is bigger that our constants we resize $image_size_orig = getimagesize($file); if ($image_size_orig[0] > $width || $image_size_orig[1] > $height) { Image::factory($file)->orientate()->resize($width, $height, Image::AUTO)->save($directory . $filename_original, $image_quality); } else { Image::factory($file)->orientate()->save($directory . $filename_original, $image_quality); } //creating the thumb and resizing using the the biggest side INVERSE Image::factory($directory . $filename_original)->resize($width_thumb, $height_thumb, Image::INVERSE)->save($directory . $filename_thumb, $image_quality); //check if the height or width of the thumb is bigger than default then crop if ($height_thumb !== NULL) { $image_size_orig = getimagesize($directory . $filename_thumb); if ($image_size_orig[1] > $height_thumb || $image_size_orig[0] > $width_thumb) { Image::factory($directory . $filename_thumb)->crop($width_thumb, $height_thumb)->save($directory . $filename_thumb); } } if (core::config('image.aws_s3_active')) { // put image to Amazon S3 $s3->putObject($s3->inputFile($directory . $filename_original), core::config('image.aws_s3_bucket'), $path . $filename_original, S3::ACL_PUBLIC_READ); // put thumb to Amazon S3 $s3->putObject($s3->inputFile($directory . $filename_thumb), core::config('image.aws_s3_bucket'), $path . $filename_thumb, S3::ACL_PUBLIC_READ); } // Delete the temporary file @unlink($file); return TRUE; } } }
/** * upload an image to the user * @param file $image * @return bool/message */ public function upload_image($image) { if (!$this->loaded()) { return FALSE; } if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); } if (!Upload::valid($image) or !Upload::not_empty($image) or !Upload::type($image, explode(',', core::config('image.allowed_formats'))) or !Upload::size($image, core::config('image.max_image_size') . 'M')) { if (Upload::not_empty($image) && !Upload::type($image, explode(',', core::config('image.allowed_formats')))) { return $image['name'] . ' ' . sprintf(__('Is not valid format, please use one of this formats "%s"'), core::config('image.allowed_formats')); } if (!Upload::size($image, core::config('image.max_image_size') . 'M')) { return $image['name'] . ' ' . sprintf(__('Is not of valid size. Size is limited to %s MB per image'), core::config('image.max_image_size')); } return $image['name'] . ' ' . __('Image is not valid. Please try again.'); } else { if ($image != NULL) { // saving/uploading zip file to dir. $path = 'images/users/'; //root folder $root = DOCROOT . $path; //root folder $image_name = $this->id_user . '.png'; $width = core::config('image.width'); // @TODO dynamic !? $height = core::config('image.height'); // @TODO dynamic !? $image_quality = core::config('image.quality'); // if folder does not exist, try to make it if (!file_exists($root) and !@mkdir($root, 0775, true)) { // mkdir not successful ? return __('Image folder is missing and cannot be created with mkdir. Please correct to be able to upload images.'); } // save file to root folder, file, name, dir if ($file = Upload::save($image, $image_name, $root)) { // resize uploaded image Image::factory($file)->orientate()->resize($width, $height, Image::AUTO)->save($root . $image_name, $image_quality); // put image to Amazon S3 if (core::config('image.aws_s3_active')) { $s3->putObject($s3->inputFile($file), core::config('image.aws_s3_bucket'), $path . $image_name, S3::ACL_PUBLIC_READ); } // update user info $this->has_image = 1; $this->last_modified = Date::unix2mysql(); try { $this->save(); return TRUE; } catch (Exception $e) { return $e->getMessage(); } } else { return $image['name'] . ' ' . __('Icon file could not been saved.'); } } } }
/** * saves image in the disk * @param string $file * @param integer $num number of the image * @return bool success? */ public function save_image_file($file, $num = 0) { if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); } $path = $this->image_path(); if ($path === FALSE) { Alert::set(Alert::ERROR, 'model\\ad.php:save_image(): ' . __('Image folder is missing and cannot be created with mkdir. Please correct to be able to upload images.')); return FALSE; } $directory = DOCROOT . $path; $image_quality = core::config('image.quality'); $width = core::config('image.width'); $width_thumb = core::config('image.width_thumb'); $height_thumb = core::config('image.height_thumb'); $height = core::config('image.height'); if (!is_numeric($height)) { // when installing this field is empty, to avoid crash we check here $height = NULL; } if (!is_numeric($height_thumb)) { $height_thumb = NULL; } $filename_thumb = 'thumb_' . $this->seotitle . '_' . $num . '.jpg'; $filename_original = $this->seotitle . '_' . $num . '.jpg'; /*WATERMARK*/ if (core::config('image.watermark') == TRUE and is_readable(core::config('image.watermark_path'))) { $mark = Image::factory(core::config('image.watermark_path')); // watermark image object $size_watermark = getimagesize(core::config('image.watermark_path')); // size of watermark if (core::config('image.watermark_position') == 0) { $wm_left_x = $width / 2 - $size_watermark[0] / 2; // x axis , from left $wm_top_y = $height / 2 - $size_watermark[1] / 2; // y axis , from top } elseif (core::config('image.watermark_position') == 1) { $wm_left_x = $width / 2 - $size_watermark[0] / 2; // x axis , from left $wm_top_y = $height - 10; // y axis , from top } elseif (core::config('image.watermark_position') == 2) { $wm_left_x = $width / 2 - $size_watermark[0] / 2; // x axis , from left $wm_top_y = 10; // y axis , from top } } /*end WATERMARK variables*/ //if original image is bigger that our constants we resize try { $image_size_orig = getimagesize($file); } catch (Exception $e) { return FALSE; } if ($image_size_orig[0] > $width || $image_size_orig[1] > $height) { if (core::config('image.watermark') and is_readable(core::config('image.watermark_path'))) { Image::factory($file)->orientate()->resize($width, $height, Image::AUTO)->watermark($mark, $wm_left_x, $wm_top_y)->save($directory . $filename_original, $image_quality); } else { Image::factory($file)->orientate()->resize($width, $height, Image::AUTO)->save($directory . $filename_original, $image_quality); } } else { if (core::config('image.watermark') and is_readable(core::config('image.watermark_path'))) { Image::factory($file)->orientate()->watermark($mark, $wm_left_x, $wm_top_y)->save($directory . $filename_original, $image_quality); } else { Image::factory($file)->orientate()->save($directory . $filename_original, $image_quality); } } //creating the thumb and resizing using the the biggest side INVERSE Image::factory($file)->orientate()->resize($width_thumb, $height_thumb, Image::INVERSE)->save($directory . $filename_thumb, $image_quality); //check if the height or width of the thumb is bigger than default then crop if ($height_thumb !== NULL) { $image_size_orig = getimagesize($directory . $filename_thumb); if ($image_size_orig[1] > $height_thumb || $image_size_orig[0] > $width_thumb) { Image::factory($directory . $filename_thumb)->crop($width_thumb, $height_thumb)->save($directory . $filename_thumb); } } // put image and thumb to Amazon S3 if (core::config('image.aws_s3_active')) { $s3->putObject($s3->inputFile($directory . $filename_original), core::config('image.aws_s3_bucket'), $path . $filename_original, S3::ACL_PUBLIC_READ); $s3->putObject($s3->inputFile($directory . $filename_thumb), core::config('image.aws_s3_bucket'), $path . $filename_thumb, S3::ACL_PUBLIC_READ); } // Delete the temporary file @unlink($file); $this->has_images++; try { $this->save(); return TRUE; } catch (Exception $e) { return FALSE; } }
$adapter->open($image); $adapter->resize($dimension['width'], $dimension['height']); $adapter->save($thumb); } catch (Exception $e) { echo 'Can\'t resize ', $image, ' (', $e->getMessage(), ')', "\n"; continue; } } if (file_exists($thumb)) { if ($compareThumbsBySize && $thumbInfo && filesize($thumb) == $thumbInfo['size']) { echo 'Thumb ', $thumb, ' has same size on S3. Ignoring', "\n"; continue; } for ($i = 1; $i <= MAX_TRIES; $i++) { //Upload thumb to the bucket $result = $s3->putObject($s3->inputFile($thumb), $bucket, $thumb, S3::ACL_PUBLIC_READ); if ($result) { break; } if ($i == MAX_TRIES) { echo 'Failed to upload ', $thumb, "\n"; } } } } } function parseDimensions($dimensions, $website) { $_dimensions = explode(',', str_replace(', ', ',', $dimensions)); $result = array(); foreach ($_dimensions as $_dimension) {
public function action_icon() { //get icon if (isset($_FILES['category_icon'])) { $icon = $_FILES['category_icon']; } else { $this->redirect(Route::get($this->_route_name)->uri(array('controller' => Request::current()->controller(), 'action' => 'index'))); } $category = new Model_Category($this->request->param('id')); if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); } if (core::post('icon_delete') and $category->delete_icon() == TRUE) { Alert::set(Alert::SUCCESS, __('Icon deleted.')); $this->redirect(Route::get($this->_route_name)->uri(array('controller' => Request::current()->controller(), 'action' => 'update', 'id' => $category->id_category))); } // end of icon delete if (!Upload::valid($icon) or !Upload::not_empty($icon) or !Upload::type($icon, explode(',', core::config('image.allowed_formats'))) or !Upload::size($icon, core::config('image.max_image_size') . 'M')) { if (Upload::not_empty($icon) && !Upload::type($icon, explode(',', core::config('image.allowed_formats')))) { Alert::set(Alert::ALERT, $icon['name'] . ' ' . sprintf(__('Is not valid format, please use one of this formats "%s"'), core::config('image.allowed_formats'))); $this->redirect(Route::get($this->_route_name)->uri(array('controller' => Request::current()->controller(), 'action' => 'update', 'id' => $category->id_category))); } if (!Upload::size($icon, core::config('image.max_image_size') . 'M')) { Alert::set(Alert::ALERT, $icon['name'] . ' ' . sprintf(__('Is not of valid size. Size is limited to %s MB per image'), core::config('image.max_image_size'))); $this->redirect(Route::get($this->_route_name)->uri(array('controller' => Request::current()->controller(), 'action' => 'update', 'id' => $category->id_category))); } Alert::set(Alert::ALERT, $icon['name'] . ' ' . __('Image is not valid. Please try again.')); $this->redirect(Route::get($this->_route_name)->uri(array('controller' => Request::current()->controller(), 'action' => 'update', 'id' => $category->id_category))); } else { if ($icon != NULL) { // saving/uploading img file to dir. $path = 'images/categories/'; $root = DOCROOT . $path; //root folder $icon_name = $category->seoname . '.png'; // if folder does not exist, try to make it if (!file_exists($root) and !@mkdir($root, 0775, true)) { // mkdir not successful ? Alert::set(Alert::ERROR, __('Image folder is missing and cannot be created with mkdir. Please correct to be able to upload images.')); return; // exit function } // save file to root folder, file, name, dir if ($file = Upload::save($icon, $icon_name, $root)) { // put icon to Amazon S3 if (core::config('image.aws_s3_active')) { $s3->putObject($s3->inputFile($file), core::config('image.aws_s3_bucket'), $path . $icon_name, S3::ACL_PUBLIC_READ); } // update category info $category->has_image = 1; $category->last_modified = Date::unix2mysql(); $category->save(); Alert::set(Alert::SUCCESS, $icon['name'] . ' ' . __('Icon is uploaded.')); } else { Alert::set(Alert::ERROR, $icon['name'] . ' ' . __('Icon file could not been saved.')); } $this->redirect(Route::get($this->_route_name)->uri(array('controller' => Request::current()->controller(), 'action' => 'update', 'id' => $category->id_category))); } } }
/** * shortcut to upload files to S3 * @param file $file * @param string $destination */ public static function S3_upload($file, $destination) { if (core::config('image.aws_s3_active') and is_readable($file)) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); $s3->putObject($s3->inputFile($file), core::config('image.aws_s3_bucket'), $destination, S3::ACL_PUBLIC_READ); } }