public function uploadfile() { if ($_GET['from'] == 'swfupload') { $uid = intval($_GET['uid']); $username = trim($_GET['username']); $token = sha1($uid . $username . formhash()); if (!$uid || !$username || $token != $_GET['token']) { echo json_encode(array('state' => 0, 'info' => 'nologin')); exit; } } else { $this->_checkuser(); $uid = $this->uid; } $config = $GLOBALS['G']['config']['output']; $upload = new Upload(); $attachment = 'attach/' . date('Y') . '/' . date('m') . '/' . $upload->setfilename(); if ($upload->save(ROOT_PATH . '/' . $config['attachdir'] . '/' . $attachment)) { $attachdata = array('uid' => $uid, 'attachname' => $upload->oriname(), 'attachment' => $attachment, 'attachsize' => $upload->size(), 'attachtype' => $upload->type(), 'attachtime' => time()); $attachdata['attachid'] = $this->t('attachment')->insert($attachdata, true); echo json_encode(array('state' => 1, 'data' => $attachdata)); exit; } else { echo json_encode(array('state' => 0, 'info' => 'Upload Failed(' . $upload->error . ')')); exit; } }
public function action_image() { if (Core::post('photo_delete') and Auth::instance()->get_user()->delete_image() == TRUE) { Alert::set(Alert::SUCCESS, __('Photo deleted.')); $this->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } // end of photo delete //get image $image = $_FILES['profile_image']; //file post 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')))) { Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Is not valid format, please use one of this formats "jpg, jpeg, png"')); $this->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } if (!Upload::size($image, core::config('image.max_image_size') . 'M')) { Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Is not of valid size. Size is limited on ' . core::config('general.max_image_size') . 'MB per image')); $this->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Image is not valid. Please try again.')); $this->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } else { if ($image != NULL) { $user = Auth::instance()->get_user(); // saving/uploadng zip file to dir. $root = DOCROOT . 'images/users/'; //root folder $image_name = $user->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 (!is_dir($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 FALSE; // exit function } // 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); // update category info $user->has_image = 1; $user->last_modified = Date::unix2mysql(); $user->save(); Alert::set(Alert::SUCCESS, $image['name'] . ' ' . __('Image is uploaded.')); } else { Alert::set(Alert::ERROR, $image['name'] . ' ' . __('Icon file could not been saved.')); } $this->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } } }
/** * 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.'))); } }
public function action_add() { $user_id = $this->user->id; if (empty($user_id)) { $this->redirect('/'); } $article = new Model_Article(); $article->title = Arr::get($_POST, 'title'); $article->description = Arr::get($_POST, 'description'); $article->text = Arr::get($_POST, 'text'); $cover = Arr::get($_FILES, 'cover'); $errors = FALSE; $table_values = array(); if ($article->title != '') { $table_values['title'] = array('value' => $article->title); } else { $errors = TRUE; } if ($article->description != '') { $table_values['description'] = array('value' => $article->description); } else { $errors = TRUE; } if ($article->text != '') { $table_values['text'] = array('value' => $article->text); } else { $errors = TRUE; } if (!Upload::valid($cover) or !Upload::not_empty($cover) or !Upload::type($cover, array('jpg', 'jpeg', 'png')) or !Upload::size($cover, '10M')) { $table_values['cover'] = TRUE; $errors = TRUE; } if ($errors) { // $this->view["editor"] = View::factory('templates/articles/editor', array("storedNodes" => $table_values['text']['value'])); $content = View::factory('templates/articles/new', $this->view); $this->template->content = View::factory("templates/articles/wrapper", array("active" => "newArticle", "content" => $content)); return false; } // getting new name for cover $article->cover = $this->methods->save_cover($cover); $article->user_id = $user_id; $article->is_published = true; // FIXME изменить, когда будет доступны режимы публикации $article->insert(); // redirect to new article $this->redirect('/article/' . $article->id); }
public function action_image() { //get image $image = $_FILES['profile_image']; //file post 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')))) { Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Is not valid format, please use one of this formats "jpg, jpeg, png"')); $this->request->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } if (!Upload::size($image, core::config('image.max_image_size') . 'M')) { Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Is not of valid size. Size is limited on ' . core::config('general.max_image_size') . 'MB per image')); $this->request->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Image is not valid. Please try again.')); $this->request->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } else { if ($image != NULL) { $user_id = Auth::instance()->get_user()->id_user; // saving/uploadng zip file to dir. $root = DOCROOT . 'images/users/'; //root folder $image_name = $user_id . '.png'; $width = core::config('image.width'); // @TODO dynamic !? $height = core::config('image.height'); // @TODO dynamic !? $image_quality = core::config('image.quality'); // if folder doesnt exists if (!file_exists($root)) { mkdir($root, 775, true); } // save file to root folder, file, name, dir if ($file = Upload::save($image, $image_name, $root)) { // resize uploaded image Image::factory($file)->resize($width, $height, Image::AUTO)->save($root . $image_name, $image_quality); } Alert::set(Alert::SUCCESS, $image['name'] . ' ' . __('Image is uploaded.')); $this->request->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } } }
protected function _save_image($image, $directory) { if (!Upload::valid($image) || !Upload::not_empty($image) || !Upload::type($image, array('jpg', 'jpeg', 'png', 'gif')) || !Upload::size($image, '2M')) { return false; } if (!is_dir($directory)) { mkdir($directory, 0777, true); } if ($file = Upload::save($image, NULL, $directory)) { try { $filename = Text::random('alnum', 20) . '.jpg'; Image::factory($file)->save($directory . $filename); unlink($file); return $filename; } catch (ErrorException $e) { // ... } } return false; }
public function testUpload() { $this->instance->init(); $this->serverHandler->expects($this->once())->method('name')->willReturn('tests/samsonos.png'); $this->serverHandler->expects($this->once())->method('size')->willReturn('1003'); $this->serverHandler->expects($this->once())->method('file')->willReturn(file_get_contents('tests/samsonos.png')); $this->serverHandler->expects($this->once())->method('type')->willReturn('png'); $upload = new Upload(array(), null, $this->instance); $upload->upload($filePath, $uploadName, $fileName); $this->assertTrue($upload->extension('png')); $this->assertEquals($upload->extension(), 'png'); $this->assertEquals($upload->mimeType(), 'png'); $this->assertEquals($upload->size(), 1003); $this->assertEquals($fileName, 'tests/samsonos.png'); $this->assertEquals($upload->realName(), 'tests/samsonos.png'); $this->assertNotNull($filePath); $this->assertNotNull($uploadName); $this->assertNotNull($upload->path()); $this->assertNotNull($upload->name()); $this->assertNotNull($upload->fullPath()); }
public function action_add() { $file = $_FILES['image']; if (!Upload::valid($file)) { $ret = array('status' => 'error', 'msg' => '不是有效的文件'); $this->content = json_encode($ret, JSON_UNESCAPED_UNICODE); return; } elseif (!Upload::not_empty($file)) { $ret = array('status' => 'error', 'msg' => '上传文件为空'); $this->content = json_encode($ret, JSON_UNESCAPED_UNICODE); return; } elseif (!Upload::type($file, array('jpg', 'png'))) { $ret = array('status' => 'error', 'msg' => '文件格式只能为jpg,png'); $this->content = json_encode($ret, JSON_UNESCAPED_UNICODE); return; } elseif (!Upload::size($file, '8M')) { $ret = array('status' => 'error', 'msg' => '文件大小不能超过8M'); $this->content = json_encode($ret, JSON_UNESCAPED_UNICODE); return; } $this->_add($file); $this->redirect(Request::$referrer); }
/** * Creates or updates the current image * * If $key is passed, the record will be assumed to exist * and an update will be executed, even if the model isn't loaded(). * * @param mixed $key * @return $this */ public function save($key = null) { $new = !$this->loaded() && !$key; if ($new) { if (!$this->file || !Upload::not_empty($this->file)) { throw new Kohana_Exception(__('No image')); } else { if (!Upload::size($this->file, Kohana::config('image.filesize'))) { throw new Kohana_Exception(__('Image too big (limit :size)', array(':size' => Kohana::config('image.filesize')))); } else { if (!Upload::type($this->file, Kohana::config('image.filetypes'))) { throw new Kohana_Exception(__('Invalid image type (use :types)', array(':types' => implode(', ', Kohana::config('image.filetypes'))))); } } } } parent::save($key); // Some magic on created images only if ($new) { // Make sure we have the new target directory $new_path = Kohana::config('image.path') . URL::id($this->id); if (!is_dir($new_path)) { mkdir($new_path, 0777, true); chmod($new_path, 0777); } if (is_writable($new_path)) { $new_path = rtrim($new_path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } else { throw new Kohana_Exception(get_class($this) . ' can not write to directory'); } // New file name with some random postfix for hard to guess filenames !$this->postfix and $this->postfix = Text::random('alnum', 8); $new_file = $this->id . '_' . $this->postfix . Kohana::config('image.postfix_original') . '.jpg'; // Rename and move to correct directory using image id $old_path = Kohana::config('image.upload_path'); $old_file = $this->file; if (!rename($old_path . $old_file, $new_path . $new_file)) { throw new Kohana_Exception(get_class($this) . ' could not move uploaded image'); } $this->file = $new_file; // Start creating images $this->_generate_images($new_path . $new_file); parent::save(); } return $this; }
/** * size() should throw an exception of the supplied max size is invalid * * @test * @covers upload::size * @expectedException Kohana_Exception */ public function test_size_throws_exception_for_invalid_size() { $this->setEnvironment(array('_FILES' => array('unit_test' => array('error' => UPLOAD_ERR_OK, 'name' => 'Unit_Test File', 'type' => 'image/png', 'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'), 'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')))))); Upload::size($_FILES['unit_test'], '1DooDah'); }
public function copyFiles($settings, $gid) { //Допустимые типы $validTypes = array('image/jpg', 'image/jpeg', 'image/gif', 'image/wbmp'); //Поле с которого происходит выбор файлов Upload::$index = 'images'; //Максимальный размер в кб Upload::$size = 15000; //Передача типов в класс Upload::validType($validTypes); //Проверка валидности файлов $files = Upload::validate(); //Загрузка во временную директорию $result = Upload::uploadFiles($files, 'tmp', true); Bufer::add(array('result' => $result)); $dir_galery_pic = 'uploads/images/galery/' . $gid . '/pic'; $dir_galery_thumb = 'uploads/images/galery/' . $gid . '/thumb'; //Если есть файлы, прошедшие проверку if (!empty($result['valid'])) { foreach ($result['valid'] as $file) { $image = $file['hashname'] . '.' . $file['ext']; $preview_w = $settings['preview_w']; $preview_h = $settings['preview_h']; $quality = isset($settings['quality']) ? $settings['quality'] : 100; $imageInfo = getimagesize($file['fullpath'], $quality); $img = new Images($file['fullpath']); $resizeThumb = $img->resize($preview_w, $preview_h, $dir_galery_thumb, $image); $width = isset($settings['resize_w']) ? $settings['resize_w'] : $imageInfo[0]; $height = isset($settings['resize_h']) ? $settings['resize_h'] : $imageInfo[1]; $img = new Images($file['fullpath']); $resizeBig = $img->resize($width, $height, $dir_galery_pic, $image); if (isset($settings['watermark_text'])) { $alfa = $settings['water_set']['fontAlpha']; $position = $settings['water_set']['position']; $align = $settings['water_set']['align']; $font = $settings['water_set']['fontFamily']; $size = $settings['water_set']['fontSize']; $color = $settings['water_set']['fontColor']; $margin = $settings['water_set']['margin']; $text = $settings['watermark_text']; $img = new Images($dir_galery_pic . '/' . $image); $img->waterSettings(array('fontAlpha' => $alfa, 'fontSize' => $size, 'fontFamily' => $font, 'fontColor' => $color, 'position' => $position, 'align' => $align, 'margin' => 10)); $arrInfo = $img->waterMarkText($text, $dir_galery_pic, false); } if (isset($settings['watermark_image'])) { $alfa = $settings['water_set']['imgAlpha']; $position = $settings['water_set']['position']; $align = $settings['water_set']['align']; $margin = $settings['water_set']['margin']; $image = $settings['watermark_image']; $img = new Images($dir_galery_pic . '/' . $image); $img->waterSettings(array('imgAlpha' => $alfa, 'position' => $position, 'align' => $align, 'margin' => 10)); $arrInfo = $img->waterMarkImg($image, $dir_galery, false); } $images[] = array('pic' => $dir_galery_pic . '/' . $image, 'thumb' => $dir_galery_thumb . '/' . $image); Upload::deleteFile($file['fullpath']); } } if (isset($images) && isset($gid)) { $result = $this->addImagesOnDb($gid, $images); } }
/** * returns true if file is of valid type. * Its used to check file sent to user from advert usercontact * @param array file * @return BOOL */ public static function is_valid_file($file) { //catch file $file = $_FILES['file']; //validate file if ($file !== NULL) { if (!Upload::valid($file) or !Upload::not_empty($file) or !Upload::type($file, array('jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx')) or !Upload::size($file, '3M')) { return FALSE; } return TRUE; } }
/** * Tests Upload::size * * @test * @dataProvider provider_size * @covers upload::size * @param string $field the files field to test * @param string $bytes valid bite size * @param array $environment set the $_FILES array * @param $expected what to expect */ function test_size($field, $bytes, $environment, $expected) { $this->setEnvironment($environment); $this->assertSame($expected, Upload::size($_FILES[$field], $bytes)); }
public function action_uploadmarkimg() { $dir = SLINEDATA . '/mark'; //水印图片存储目录 if (!is_dir($dir)) { mkdir($dir); } $path_info = pathinfo($_FILES['Filedata']['name']); $filename = 'mark.' . $path_info['extension']; Upload::$default_directory = $dir; //默认保存文件夹 Upload::$remove_spaces = true; //上传文件删除空格 $file = $_FILES['Filedata']; $arr = array(); if (Upload::valid($file) && Upload::size($file, "500KB") && Upload::type($file, array('jpg', 'png', 'gif'))) { if (Upload::save($file, $filename)) { $arr['success'] = 'true'; $arr['bigpic'] = $GLOBALS['$cfg_basehost'] . '/data/mark/' . $filename; } } else { $arr['success'] = 'false'; $arr['msg'] = '上传失败,请检查图片大小,图片格式.'; } echo json_encode($arr); }
/** * returns true if file is of valid type. * Its used to check file sent to user from advert usercontact * @return BOOL */ public function is_valid_file($file) { //catch file $file = $_FILES['file']; //validate file if ($file !== NULL) { if (!Upload::valid($file) or !Upload::not_empty($file) or !Upload::type($file, array('jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx')) or !Upload::size($file, core::config('image.max_image_size') . 'M')) { return FALSE; } return TRUE; } }
/** * Creates or updates the current image. * * @param Validation $validation a manual validation object to combine the model properties with * @return integer * * @throws Kohana_Exception */ public function save(Validation $validation = null) { $new = !(bool) $this->id; // Validate new image if ($new) { $path = Kohana::$config->load('image.upload_path'); // Download remote files if ($this->remote && !$this->file) { $this->file = Request::factory($this->remote)->download(null, $path); } if (!$this->file || !$this->remote && !Upload::not_empty($this->file)) { throw new Kohana_Exception(__('No image')); } else { if (!Upload::size($this->file, Kohana::$config->load('image.filesize'))) { throw new Kohana_Exception(__('Image too big (limit :size)', array(':size' => Kohana::$config->load('image.filesize')))); } else { if (!Upload::type($this->file, Kohana::$config->load('image.filetypes')) && !in_array($this->file['type'], Kohana::$config->load('image.mimetypes'))) { throw new Kohana_Exception(__('Invalid image type (use :types)', array(':types' => implode(', ', Kohana::$config->load('image.filetypes'))))); } } } $upload = $this->file; if ($this->remote && !is_uploaded_file($upload['tmp_name'])) { // As a remote file is no actual file field, manually set the filename $this->file = basename($upload['tmp_name']); } else { if (is_uploaded_file($upload['tmp_name'])) { // Sanitize the filename $upload['name'] = preg_replace('/[^a-z0-9-\\.]/', '-', mb_strtolower($upload['name'])); // Strip multiple dashes $upload['name'] = preg_replace('/-{2,}/', '-', $upload['name']); // Try to save upload if (false !== ($this->file = Upload::save($upload, null, $path))) { // Get new filename $this->file = basename($this->file); } } } } try { parent::save(); } catch (Validation_Exception $e) { if ($new && $this->file) { unlink($path . $this->file); } throw $e; } // Some magic on created images only if ($new) { // Make sure we have the new target directory $new_path = Kohana::$config->load('image.path') . URL::id($this->id); if (!is_dir($new_path)) { mkdir($new_path, 0777, true); chmod($new_path, 0777); } if (is_writable($new_path)) { $new_path = rtrim($new_path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } else { throw new Kohana_Exception(get_class($this) . ' can not write to directory'); } // New file name with some random postfix for hard to guess filenames !$this->postfix and $this->postfix = Text::random('alnum', 8); $new_file = $this->id . '_' . $this->postfix . Kohana::$config->load('image.postfix_original') . '.jpg'; // Rename and move to correct directory using image id $old_file = $this->file; if (!rename($path . $old_file, $new_path . $new_file)) { unlink($path . $old_file); throw new Kohana_Exception(get_class($this) . ' could not move uploaded image'); } $this->file = $new_file; // Start creating images $this->_generate_images($new_path . $new_file); parent::save(); } return $this; }
public function is_smaller_than_filesize($file_path) { if (isset($_FILES[$this->key])) { return Upload::size($_FILES[$this->key], $this->filesize . 'B'); } else { return filesize($file_path); } }
/** * 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.'); } } } }
/** * save_product upload images with given path * * @param [array] $file [file $_FILE-s ] * @param [string] $seotitle [unique id, and folder name] * @return [bool] [return true if 1 or more files uploaded, false otherwise] */ public function save_product($file) { if (!Upload::valid($file) or !Upload::not_empty($file) or !Upload::type($file, explode(',', core::config('product.formats'))) or !Upload::size($file, core::config('product.max_size') . 'M')) { if (Upload::not_empty($file) && !Upload::type($file, explode(',', core::config('product.formats')))) { return Alert::set(Alert::ALERT, $file['name'] . ': ' . sprintf(__('This uploaded file is not of a valid format. Please use one of these formats: %s'), core::config('product.formats'))); } if (!Upload::size($file, core::config('product.max_size') . 'M')) { return Alert::set(Alert::ALERT, $file['name'] . ': ' . sprintf(__("This uploaded file exceeds the allowable limit. Uploaded files cannot be larger than %s MB per product"), core::config('product.max_size'))); } } if ($file !== NULL) { $directory = DOCROOT . '/data/'; // make dir if (!is_dir($directory)) { // check if directory exists mkdir($directory, 0755, TRUE); } $product_format = strrchr($file['name'], '.'); $encoded_name = md5($file['name'] . uniqid(mt_rand())) . $product_format; // d($product_format); if ($temp_file = Upload::save($file, $encoded_name, $directory, 775)) { return $encoded_name; } else { return FALSE; } // Delete the temporary file } }
/** * uploads the given image to S3 * @param $_FILE $image * @param boolean $favicon set to true if image is a favicon * @return FALSE/string url */ public static function upload_image($image, $favicon = FALSE) { if ($favicon) { $allowed_formats = array('ico'); } else { $allowed_formats = explode(',', core::config('image.allowed_formats')); } if (!Upload::valid($image) or !Upload::not_empty($image) or !Upload::type($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')))) { Alert::set(Alert::ALERT, $image['name'] . ' ' . sprintf(__('Is not valid format, please use one of this formats "%s"'), core::config('image.allowed_formats'))); return FALSE; } if (!Upload::size($image, core::config('image.max_image_size') . 'M')) { Alert::set(Alert::ALERT, $image['name'] . ' ' . sprintf(__('Is not of valid size. Size is limited to %s MB per image'), core::config('general.max_image_size'))); return FALSE; } if (!Upload::not_empty($image)) { return FALSE; } } if (!$favicon and core::config('image.disallow_nudes') and !Upload::not_nude_image($image)) { Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Seems a nude picture so you cannot upload it')); return FALSE; } if ($image !== NULL) { $directory = DOCROOT . 'images/'; if ($file = Upload::save($image, $image['name'], $directory)) { // put image to Amazon S3 Core::S3_upload($directory . $image['name'], 'images/' . $image['name']); } else { Alert::set(Alert::ALERT, __('Something went wrong uploading your logo')); return FALSE; } } //try s3, if not normal if (($base = Core::S3_domain()) === FALSE) { $base = URL::base(); } return $base . 'images/' . $image['name']; }
/** * save_image upload images with given path * * @param array image * @return bool */ public function save_image($image) { if (!$this->loaded()) { return FALSE; } $seotitle = $this->seotitle; 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')))) { Alert::set(Alert::ALERT, $image['name'] . ' ' . sprintf(__('Is not valid format, please use one of this formats "%s"'), core::config('image.allowed_formats'))); return FALSE; } if (!Upload::size($image, core::config('image.max_image_size') . 'M')) { Alert::set(Alert::ALERT, $image['name'] . ' ' . sprintf(__('Is not of valid size. Size is limited to %s MB per image'), core::config('image.max_image_size'))); return FALSE; } if (!Upload::not_empty($image)) { return FALSE; } } if (core::config('image.disallow_nudes') and !Upload::not_nude_image($image)) { Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Seems a nude picture so you cannot upload it')); return FALSE; } if ($image !== NULL) { $path = $this->image_path(); $directory = DOCROOT . $path; if ($file = Upload::save($image, NULL, $directory)) { return $this->save_image_file($file, $this->has_images + 1); } else { Alert::set(Alert::ALERT, __('Something went wrong with uploading pictures, please check format')); return FALSE; } } }
static function validFileSize($data, $max_size = NULL) { if (NULL === $data || !Upload::not_empty($data)) { return TRUE; } return NULL === $max_size || Upload::size($data, $max_size); }
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))); } } }
public function action_destination() { $action = $this->params['action']; if (empty($action)) { $typeid = $this->params['typeid']; $typeid = empty($typeid) ? 0 : $typeid; if (!empty($typeid)) { $moduleinfo = Model_Model::getModuleInfo($typeid); //$product_dest_table='sline_'.$this->product_arr[$typeid].'_kindlist'; $product_dest_table = $moduleinfo['pinyin'] . '_kindlist'; } $addmodule = ORM::factory('model')->where("id>13")->get_all(); //扩展模型 $allmodule = Model_Model::getAllModule(); //$position = $typeid==0 ? '全局目的地':$this->name_arr[$typeid].'目的地'; $position = $typeid == 0 ? '全局目的地' : $moduleinfo['modulename'] . '目的地'; $this->assign('typeid', $typeid); $this->assign('position', $position); $this->assign('addmodule', $addmodule); $this->assign('allmodule', $allmodule); $this->display('stourtravel/destination/destination'); } else { if ($action == 'read') { $node = Arr::get($_GET, 'node'); $typeid = Arr::get($_GET, 'typeid'); $node_arr = explode('_', $node); if (!empty($typeid)) { $moduleinfo = Model_Model::getModuleInfo($typeid); //$product_dest_table='sline_'.$this->product_arr[$typeid].'_kindlist'; $product_dest_table = 'sline_' . $moduleinfo['pinyin'] . '_kindlist'; } $pid = $node_arr[1] == 'root' ? 0 : $node_arr[1]; if (empty($typeid)) { $sql = "select * from sline_destinations where pid={$pid}"; } else { $bfields = 'b.kindid,b.seotitle,b.keyword,b.description,b.tagword,b.jieshao,b.isfinishseo,b.isnav,b.ishot,b.displayorder'; $sql = "select a.id,a.kindname,if(find_in_set({$typeid},opentypeids),1,0) as isopen,a.pinyin,a.iswebsite,{$bfields} from sline_destinations a left join {$product_dest_table} b on a.id=b.kindid where a.pid={$pid}"; } $list = DB::query(Database::SELECT, $sql)->execute()->as_array(); if ($typeid == 0) { $list[] = array('leaf' => true, 'id' => $pid . 'add', 'kindname' => '<button class="dest-add-btn df-add-btn" onclick="addSub(' . $pid . ')">添加</button>', 'allowDrag' => false, 'allowDrop' => false, 'displayorder' => 'add', 'isopen' => 'add', 'iswebsite' => 'add', 'isnav' => 'add', 'istopnav' => 'add', 'ishot' => 'add', 'pinyin' => 'add'); } echo json_encode(array('success' => true, 'text' => '', 'children' => $list)); } else { if ($action == 'update') { $id = Arr::get($_POST, 'id'); $field = Arr::get($_POST, 'field'); $val = Arr::get($_POST, 'val'); $typeid = Arr::get($_POST, 'typeid'); if ($typeid == 0) { $model = ORM::factory('destinations', $id); $model->{$field} = $val; if ($field == 'weburl') { $ar = explode('.', $val); $py = str_replace('http://', '', $ar[0]); $m = ORM::factory('destinations')->where("webprefix='{$py}' and id!={$id}")->find(); if (!$m->loaded()) { $model->webprefix = $py; } else { echo 'py_repeat'; exit; } } $model->save(); if ($model->saved()) { echo 'ok'; } else { echo 'no'; } } else { if ($field == 'isopen') { $result = Model_Destinations::setTypeidOpen($id, $typeid, $val); if ($result) { echo 'ok'; } else { echo 'no'; } } else { $moduleinfo = Model_Model::getModuleInfo($typeid); //$product_dest_table='sline_'.$this->product_arr[$typeid].'_kindlist'; $product_dest_table = $moduleinfo['pinyin'] . '_kindlist'; //$model=ORM::factory($this->product_arr[$typeid].'_kindlist')->where("kindid=$id")->find(); $model = new Model_Tongyong($product_dest_table); $model = $model->where("kindid={$id}")->find(); if (!$model->loaded()) { //$model = ORM::factory($this->product_arr[$typeid].'_kindlist'); $model->kindid = $id; } $model->{$field} = $val; $model->save(); if ($model->saved()) { echo 'ok'; } else { echo 'no'; } } } } else { if ($action == 'save') { $rawdata = file_get_contents('php://input'); $field = Arr::get($_GET, 'field'); $typeid = Arr::get($_GET, 'typeid'); $current_pinyin = Arr::get($_GET, 'pinyin'); $data = json_decode($rawdata); $dest_id_arr = explode('_', $data->id); $dest_id = $dest_id_arr[1]; if (!empty($typeid)) { $moduleinfo = Model_Model::getModuleInfo($typeid); //$product_dest_table='sline_'.$this->product_arr[$typeid].'_kindlist'; $product_dest_table = $moduleinfo['pinyin'] . '_kindlist'; } if (!is_numeric($dest_id_arr[1])) { echo json_encode(array('success' => false)); } if ($typeid == 0) { $dest = ORM::factory('destinations', $dest_id_arr[1]); if ($field) { if ($field == 'kindname') { $dest->pinyin = empty($current_pinyin) ? Common::getPinYin($data->{$field}) : $current_pinyin; } $dest->{$field} = $data->{$field}; } else { unset($data->id); unset($data->parentId); unset($data->leaf); unset($data->issel); unset($data->shownum); foreach ($data as $k => $v) { $dest->{$k} = $v; } } } else { //$dest=ORM::factory($this->product_arr[$typeid].'_kindlist')->where("kindid=$dest_id")->find(); $dest = new Model_Tongyong($product_dest_table); $dest = $dest->where("kindid={$dest_id}")->find(); if (!$dest->loaded()) { $dest->kindid = $dest_id; $dest->displayorder = $data->displayorder; } else { unset($data->id); unset($data->parentId); unset($data->leaf); unset($data->kindname); unset($data->isopen); unset($data->iswebsite); unset($data->istopnav); unset($data->pinyin); unset($data->pid); unset($data->kindtype); unset($data->litpic); unset($data->piclist); unset($data->issel); unset($data->shownum); unset($data->templet); unset($data->weburl); foreach ($data as $k => $v) { $dest->{$k} = $v; } $dest->displayorder = $data->displayorder; } } $dest->displayorder = empty($dest->displayorder) ? 9999 : $dest->displayorder; $dest->save(); if ($dest->saved()) { echo json_encode(array('success' => true)); } else { echo json_encode(array('success' => false)); } } else { if ($action == 'uploadfile') { $file = $_FILES['Filedata']; $rootpath = realpath(DOCROOT . '../'); $dir = $rootpath . "/uploads/main/" . date('Ymd'); if (!file_exists($dir)) { mkdir($dir); } $path_info = pathinfo($_FILES['Filedata']['name']); $filename = date('His') . '.' . $path_info['extension']; Upload::$default_directory = $dir; //默认保存文件夹 Upload::$remove_spaces = true; //上传文件删除空格 if (Upload::valid($file)) { if (Upload::size($file, "1M")) { if (Upload::type($file, array('jpg', 'png', 'gif'))) { if (Upload::save($file, $filename)) { $newfile = $dir . '/' . $filename; Image::factory($newfile)->resize(600, 400, Image::AUTO)->save($newfile); echo substr(substr($newfile, strpos($dir, '/uploads') - 1), 1); } else { echo "error_no"; } } else { echo "error_type"; } } else { echo "error_size"; } } else { echo "error_null"; } } else { if ($action == 'addsub') { $pid = Arr::get($_POST, 'pid'); $dest = ORM::factory('destinations'); $dest->pid = $pid; $dest->kindname = "未命名"; $dest->save(); if ($dest->saved()) { $dest->reload(); $dest->updateSibling('add'); echo json_encode($dest->as_array()); } } else { if ($action == 'drag') { $moveid = Arr::get($_POST, 'moveid'); $overid = Arr::get($_POST, 'overid'); $position = Arr::get($_POST, 'position'); $moveDest = ORM::factory('destinations', $moveid); $overDest = ORM::factory('destinations', $overid); if ($position == 'append') { $moveDest->pid = $overid; } else { $moveDest->pid = $overDest->pid; } $moveDest->save(); if ($moveDest->saved()) { echo 'ok'; } else { echo 'no'; } } else { if ($action == 'search') { $keyword = trim(Arr::get($_POST, 'keyword')); $list = DB::query(Database::SELECT, "select id,pid from sline_destinations where kindname like '%{$keyword}%'")->execute()->as_array(); $new_arr = array(); foreach ($list as $k => $v) { $temp_arr = array(); if ($v['pid'] != 0) { $temp_id = $v['pid']; $temp_arr = array($v['pid'], $v['id']); while (true) { $temp_dest = ORM::factory('destinations', $temp_id)->as_array(); if ($temp_dest['pid'] != 0) { array_unshift($temp_arr, $temp_dest['pid']); $temp_id = $temp_dest['pid']; } else { break; } } $new_arr[] = $temp_arr; } else { $new_arr[] = array($v['id']); } } if (empty($new_arr)) { echo 'no'; } else { echo json_encode($new_arr); } } else { if ($action == 'delete') { $rawdata = file_get_contents('php://input'); $field = Arr::get($_GET, 'field'); $data = json_decode($rawdata); $dest_id_arr = explode('_', $data->id); if (!is_numeric($dest_id_arr[1])) { echo json_encode(array('success' => false)); exit; } $dest = ORM::factory('destinations', $dest_id_arr[1]); $dest->deleteClear(); } } } } } } } } } }