/** * * @param integer $size */ public function set_max_size($size) { if (empty($size)) { $size = Num::bytes('1MiB'); } $this->max_size = (int) $size; }
public function validate(Jam_Validated $model, $attribute, $value) { if ($value and !$value->is_empty() and $value->source()) { if ($error = $value->source()->error()) { $model->errors()->add($attribute, 'uploaded_native', array(':message' => $error)); } elseif (!is_file($value->file())) { $model->errors()->add($attribute, 'uploaded_is_file'); } if ($this->only and !in_array(strtolower(pathinfo($value->filename(), PATHINFO_EXTENSION)), $this->valid_extensions())) { $model->errors()->add($attribute, 'uploaded_extension', array(':extension' => join(', ', $this->valid_extensions()))); } if ($this->minimum_size or $this->maximum_size or $this->exact_size) { $size = @filesize($value->file()); if ($this->minimum_size and $minimum_size = Num::bytes($this->minimum_size) and (int) $size < (int) $minimum_size) { $model->errors()->add($attribute, 'uploaded_minimum_size', array(':minimum_size' => $this->minimum_size)); } if ($this->maximum_size and $maximum_size = Num::bytes($this->maximum_size) and (int) $size > (int) $maximum_size) { $model->errors()->add($attribute, 'uploaded_maximum_size', array(':maximum_size' => $this->maximum_size)); } if ($this->exact_size and $exact_size = Num::bytes($this->exact_size) and (int) $size !== (int) $exact_size) { $model->errors()->add($attribute, 'uploaded_exact_size', array(':exact_size' => $this->exact_size)); } } if ($this->minimum_width or $this->minimum_height or $this->maximum_width or $this->maximum_height or $this->exact_width or $this->exact_height) { $dims = @getimagesize($value->file()); if ($dims) { list($width, $height) = $dims; if ($this->exact_width and (int) $width !== (int) $this->exact_width) { $model->errors()->add($attribute, 'uploaded_exact_width', array(':exact_width' => $this->exact_width)); } if ($this->exact_height and (int) $height !== (int) $this->exact_height) { $model->errors()->add($attribute, 'uploaded_exact_height', array(':exact_height' => $this->exact_height)); } if ($this->minimum_width and (int) $width < (int) $this->minimum_width) { $model->errors()->add($attribute, 'uploaded_minimum_width', array(':minimum_width' => $this->minimum_width)); } if ($this->minimum_height and (int) $height < (int) $this->minimum_height) { $model->errors()->add($attribute, 'uploaded_minimum_height', array(':minimum_height' => $this->minimum_height)); } if ($this->maximum_width and (int) $width > (int) $this->maximum_width) { $model->errors()->add($attribute, 'uploaded_maximum_width', array(':maximum_width' => $this->maximum_width)); } if ($this->maximum_height and (int) $height > (int) $this->maximum_height) { $model->errors()->add($attribute, 'uploaded_maximum_height', array(':maximum_height' => $this->maximum_height)); } } } } }
/** * Загрузка файла и сохранение в папку TMPPATH * * try * { * $filename = Upload::file($_FILES['file'], NULL, NULL, array('jpg', 'jpeg', 'gif', 'png')); * $path = TMPPATH . $filename; * } * catch (Validation_Exception $e) * { * echo debug::vars($e->errors('validation')); * } * * При указании строки в качестве параметра $file, будет произведена * попытка загрузить файл по URL * * @param string|array $file * @param string $directory Путь к каталогу, куда загружать файл * @param string $filename Название файла (filename.ext) * @param array $types Разрешенные типы файлов (При указании пустой строки, разрешены все файлы) array('jpg', '...') * @param integer $max_size Максимальный размер загружаемого файла * @return string|NULL Название файла. * @throws Validation_Exception */ public static function file($file, $directory = NULL, $filename = NULL, array $types = array('jpg', 'jpeg', 'gif', 'png'), $max_size = NULL) { if (!is_array($file)) { return Upload::from_url($file, $directory, $filename, $types); } if ($directory === NULL) { $directory = TMPPATH; } if ($filename === NULL) { $filename = uniqid(); } else { if ($filename === TRUE) { $filename = $file['name']; } } $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); $filename_ext = pathinfo($filename, PATHINFO_EXTENSION); if (empty($filename_ext)) { $filename .= '.' . $ext; } if ($max_size === NULL) { $max_size = Num::bytes('20MiB'); } $validation = Validation::factory(array('file' => $file))->rules('file', array(array('Upload::valid'), array('Upload::size', array(':value', $max_size)))); if (!empty($types)) { $validation->rule('file', 'Upload::type', array(':value', $types)); } if (!$validation->check()) { throw new Validation_Exception($validation); } if (!is_dir($directory)) { mkdir($directory, 0777); chmod($directory, 0777); } Upload::save($file, $filename, $directory, 0777); return $filename; }
/** * Provides data for test_post_max_size_exceeded() * * @return array */ public function provider_post_max_size_exceeded() { // Get the post max size $post_max_size = Num::bytes(ini_get('post_max_size')); return array(array($post_max_size + 200000, TRUE), array($post_max_size - 20, FALSE), array($post_max_size, FALSE)); }
/** * save_base64_image upload images with given path * * @param string $image [base64 encoded image] * @return bool */ public function save_base64_image($image) { if (!$this->loaded()) { return FALSE; } // Temporary save image $image_data = base64_decode(preg_replace('#^data:image/\\w+;base64,#i', '', $image)); $image_tmp = tmpfile(); $image_tmp_uri = stream_get_meta_data($image_tmp)['uri']; file_put_contents($image_tmp_uri, $image_data); $image = Image::factory($image_tmp_uri); if (!in_array($image->mime, explode(',', 'image/' . str_replace(",", ",image/", core::config('image.allowed_formats'))))) { Alert::set(Alert::ALERT, $image->mime . ' ' . sprintf(__('Is not valid format, please use one of this formats "%s"'), core::config('image.allowed_formats'))); return FALSE; } if (filesize($image_tmp_uri) > Num::bytes(core::config('image.max_image_size') . 'M')) { Alert::set(Alert::ALERT, $image->mime . ' ' . sprintf(__('Is not of valid size. Size is limited to %s MB per image'), core::config('image.max_image_size'))); return FALSE; } if (core::config('image.disallow_nudes') and $image->is_nude_image()) { Alert::set(Alert::ALERT, $image->mime . ' ' . __('Seems a nude picture so you cannot upload it')); return FALSE; } return $this->save_image_file($image_tmp_uri, $this->has_images + 1); }
/** * Determines if a file larger than the post_max_size has been uploaded. PHP * does not handle this situation gracefully on its own, so this method * helps to solve that problem. * * @return boolean * @uses Num::bytes * @uses Arr::get */ public static function post_max_size_exceeded() { // Make sure the request method is POST if (Request::$initial->method() !== HTTP_Request::POST) { return FALSE; } // Get the post_max_size in bytes $max_bytes = Num::bytes(ini_get('post_max_size')); // Error occurred if method is POST, and content length is too long return Arr::get($_SERVER, 'CONTENT_LENGTH') > $max_bytes; }
/** * @see Num::bytes */ public function test_bytes() { $output = Num::bytes('200K'); $expected = '204800'; $this->assertEquals($expected, $output); }
/** * Tests Num::bytes() * * @test * @covers Num::bytes * @dataProvider provider_bytes * @param integer Expected Value * @param string Input value */ public function test_bytes($expected, $size) { $this->assertSame($expected, Num::bytes($size)); }
/** * Get PHP memory_limit * * It can be used to obtain a human-readable form * of a PHP memory_limit. * * [!!] Note: If ini_get('memory_limit') returns 0, -1, NULL or FALSE * returns [System::MIN_MEMORY_LIMIT] * * @since 1.4.0 * * @return int|string * * @uses Num::bytes * @uses Text::bytes */ public static function get_memory_limit() { $memory_limit = Num::bytes(ini_get('memory_limit')); return Text::bytes((int) $memory_limit <= 0 ? self::MIN_MEMORY_LIMIT : $memory_limit, 'MiB'); }
/** * * @see Num::bytes @expectedException Exception */ public function test_bytes_exception() { $output = Num::bytes('invalid'); }
/** * Validation rule to test if an uploaded file is allowed by file size. * File sizes are defined as: SB, where S is the size (1, 8.5, 300, etc.) * and B is the byte unit (K, MiB, GB, etc.). All valid byte units are * defined in Num::$byte_units * * $array->rule('file', 'Upload::size', array(':value', '1M')) * $array->rule('file', 'Upload::size', array(':value', '2.5KiB')) * * @param array $file $_FILES item * @param string $size maximum file size allowed * @return bool */ public static function size(array $file, $size) { if ($file['error'] === UPLOAD_ERR_INI_SIZE) { // Upload is larger than PHP allowed size (upload_max_filesize) return FALSE; } if ($file['error'] !== UPLOAD_ERR_OK) { // The upload failed, no size to check return TRUE; } // Convert the provided size to bytes for comparison $size = Num::bytes($size); // Test that the file is under or equal to the max size return $file['size'] <= $size; }
/** * @expectedException Kohana_Exception */ public function testBytes2() { $bytes = Num::bytes('60.00 kB'); }
public static function get_accepted_filesize($member_id = null, $is_return_byte = true) { $value = conf('upload.accepted_filesize.small.limit'); if ($is_return_byte) { $value = Num::bytes($value); } return $value; }
/** * Gets POST max size in bytes * * @link http://php.net/post-max-size * * @return float * * @uses Config::get * @uses Config::set * @uses Num::bytes * @uses Request::DEFAULT_POST_MAX_SIZE */ public static function get_post_max_size() { $max_size = Config::get('media.post_max_size', NULL); // Set post_max_size default value if it not exists if (is_null($max_size)) { Config::set('media', 'post_max_size', Request::DEFAULT_POST_MAX_SIZE); } // Get the post_max_size in bytes from php.ini $php_settings = Num::bytes(ini_get('post_max_size')); // Get the post_max_size in bytes from `config/media` $gleez_settings = Num::bytes($max_size); return $gleez_settings <= $php_settings ? $gleez_settings : $php_settings; }
/** * Gets POST max size in bytes * * @link http://php.net/post-max-size * * @return float * * @uses Config::get * @uses Config::set * @uses Num::bytes * @uses Request::DEFAULT_POST_MAX_SIZE */ public static function get_post_max_size() { $max_size = Config::get('media.post_max_size', NULL); // Set post_max_size default value if it not exists if (is_null($max_size)) { Config::set('media', 'post_max_size', $max_size = static::DEFAULT_POST_MAX_SIZE); } if (static::isHHVM()) { //$php_settings = ini_get('post_max_size'); $php_settings = ini_get('hhvm.server.max_post_size'); } else { // Get the post_max_size in bytes from php.ini $php_settings = Num::bytes(ini_get('post_max_size')); } // Get the post_max_size in bytes from `config/media` $gleez_settings = Num::bytes($max_size); return min($gleez_settings, $php_settings); }
/** * Render view. * * @return string */ public function content() { ob_start(); // Upload form echo Form::open(null, array('id' => 'form-multiple-upload', 'method' => 'post', 'enctype' => 'multipart/form-data')); ?> <div> <div class="droparea hero-unit"><i class="icon-arrow-down"></i> <strong><?php echo __('Drag and drop files here'); ?> </strong></div> <span class="btn btn-success fileinput-button"> <i class="icon-plus icon-white"></i> <?php echo __('Add files...'); ?> <?php echo Form::file('file[]', array('multiple' => 'multiple', 'accept' => 'image/*')); ?> </span> <?php echo Form::button('upload', '<i class="icon-upload icon-white"></i> ' . __('Start upload'), array('type' => 'submit', 'class' => 'btn btn-primary start')); ?> <div class="progress progress-success progress-striped active fade"> <div class="bar" style="width: 0%;"></div> </div> </div> <div class="fileupload-loading"></div> <table class="table table-striped"> <tbody class="files"></tbody> </table> <?php echo Form::csrf(); echo Form::close(); // jQuery file upload $base = URL::base(!Request::current()->is_initial()); ?> <!-- The template to display files available for upload --> <script id="template-upload" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-upload fade"> <td class="preview"><span class="fade"></span></td> <td class="name"><span>{%=file.name%}</span></td> <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td> {% if (file.error) { %} <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td> {% } else if (o.files.valid && !i) { %} <td> <div class="progress progress-success progress-striped active"><div class="bar" style="width: 0%;"></div></div> </td> <td class="start">{% if (!o.options.autoUpload) { %} <button class="btn btn-primary"> <i class="icon-upload icon-white"></i> {%=locale.fileupload.start%} </button> {% } %}</td> {% } else { %} <td colspan="2"></td> {% } %} <td class="cancel">{% if (!i) { %} <button class="btn btn-warning"> <i class="icon-ban-circle icon-white"></i> {%=locale.fileupload.cancel%} </button> {% } %}</td> </tr> {% } %} </script> <!-- The template to display files available for download --> <script id="template-download" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-download fade"> {% if (file.error) { %} <td></td> <td class="name"><span>{%=file.name%}</span></td> <td class="size">{%=o.formatFileSize(file.size)%}</td> <td class="error" colspan="3"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td> {% } else { %} <td class="preview">{% if (file.thumbnail_url) { %} <a href="{%=file.gallery_url%}" target="_blank"><img src="{%=file.thumbnail_url%}" /></a> {% } %}</td> <td class="name"> <a href="{%=file.url%}" title="{%=file.name%}" target="_blank">{%=file.name%}</a> </td> <td class="size">{%=o.formatFileSize(file.size)%}</td> <td class="delete" colspan="3">{% if (file.delete_url) { %} <button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}"> <i class="icon-trash icon-white"></i> {%=locale.fileupload.destroy%} </button>{% } %} </td> {% } %} </tr> {% } %} </script> <script> head.ready('jquery-ui', function fileUpload() { head.js( { 'jquery-template': '<?php echo $base; ?> static/js/tmpl.js' }, { 'jquery-load-image': '<?php echo $base; ?> static/js/load-image.js' }, { 'jquery-iframe-transport': '<?php echo $base; ?> static/js/jquery.iframe-transport.js' }, { 'jquery-fileupload': '<?php echo $base; ?> static/js/jquery.fileupload.js' }, { 'jquery-fileupload-ui': '<?php echo $base; ?> static/js/jquery.fileupload-ui.js' }, { 'jquery-xdr-transport': '<?php echo $base; ?> static/js/jquery.xdr-transport.js' }, function fileUploadLoaded() { // Localization window.locale = { 'fileupload': { 'errors': { 'maxFileSize': 'File is too big', 'minFileSize': 'File is too small', 'acceptFileTypes': 'Filetype not allowed', 'maxNumberOfFiles': 'Max number of files exceeded', 'uploadedBytes': 'Uploaded bytes exceed file size', 'emptyResult': 'Empty file upload result' }, 'cancel': 'Cancel', 'destroy': 'Delete', 'error': 'Error', 'start': 'Start' } }; // Initialize fileupload $('#form-multiple-upload').fileupload({ acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, //autoUpload: true, maxFileSize: <?php echo Num::bytes(Kohana::$config->load('image.filesize')); ?> , dropZone: $('.droparea'), formData: { token: $('input[name=token]').val(), multiple: true } }); $(document).on('drop dragover', function disableDrop(e) { e.preventDefault(); }); $('#form-multiple-upload').on('submit', function upload(e) { e.preventDefault(); $('.files .start button').click(); // $(this).fileupload('send'); }) } ); }); </script> <!--[if gte IE 8]><!--<script src="<?php echo $base; ?> static/js/jquery.xdr-transport.js"></script>--><![endif]--> <?php return ob_get_clean(); }