/** * upload files */ protected function create($model, $form) { // check rights if (!Acl::instance()->allowed($this->_controller, 'create')) { throw HTTP_Exception::factory(403, 'Create not allowed on :controller', array(':controller' => $this->_controller)); } $hash = FALSE; Event::raise($this, Event::BEFORE_CREATE_FORM_PARSE, array('model' => NULL, 'form' => $form)); if ($form->valid()) { $hash = Upload::process('file', $this->_settings->get('path_temp'), $this->_settings->get('extensions'), $this->_settings->get('unzip')); } if ($hash !== FALSE) { return $hash; } else { if ($form->submitted()) { // set error in form $form->element('file', 0)->error('not_empty'); } // create viewer $viewer = Viewer::factory('Form', $form)->text(Text::instance()); // render form $view = View::factory($this->_settings->get('view.create'), array('viewer' => $viewer)); // event Event::raise($this, Event::BEFORE_CREATE_RENDER, array('model' => NULL, 'form' => $form, 'viewer' => $viewer, 'view' => $view)); // render $this->response->body($view->render()); return FALSE; } }
function beforeSave() { if (!$this->isFolder()) { # se guarda el archivo original $path = WWW_ROOT . Configure::read("Media.Upload.dir") . $this->data['Upload']['path']; //$this->data['Upload']['name']=$this->Uploader->file_dst_name_body; //$this->Uploader->file_dst_name_body=Inflector::slug($this->Uploader->file_src_name_body); $this->Uploader->process($path); $num = str_replace(str_replace(' ', '_', $this->data['Upload']['name']), "", $this->Uploader->file_dst_name_body); if ($num) { $this->data['Upload']['name'] .= "{$num}"; } if (!$this->isFolder() && $this->isImage()) { # se crea la miniatura $this->copy(array('width' => 100, 'height' => 100), $path, 'thumb_' . $this->data['Upload']['name']); # se guarda la foto grande if ($this->data['Upload']['width'] >= 1200) { $width = 1024; $height = round($width / $this->data['Upload']['width'] * $this->data['Upload']['height']); $this->copy(array('width' => $width, 'height' => $height), $path, $width . "x" . $height . "_" . $this->data['Upload']['name']); } # se guarda la foto mediana if ($this->data['Upload']['width'] >= 400) { $width = 300; $height = round($width / $this->data['Upload']['width'] * $this->data['Upload']['height']); $this->copy(array('width' => $width, 'height' => $height), $path, $width . "x" . $height . "_" . $this->data['Upload']['name']); } } } return true; }
public function post_parse_payments() { $config = array('path' => DOCROOT . 'uploads/csv', 'randomize' => true, 'ext_whitelist' => array('csv')); Upload::process($config); if (Upload::is_valid()) { //Upload::save(); $file = Upload::get_files(); $uploaded_file = $file[0]['file']; Package::load("excel"); $excel = PHPExcel_IOFactory::createReader('CSV')->setDelimiter(',')->setEnclosure('"')->setLineEnding("\n")->setSheetIndex(0)->load($uploaded_file); $objWorksheet = $excel->setActiveSheetIndex(0); $highestRow = $objWorksheet->getHighestRow(); $highestColumn = $objWorksheet->getHighestColumn(); $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); //read from file for ($row = 1; $row <= $highestRow; ++$row) { $file_data = array(); for ($col = 0; $col <= $highestColumnIndex; ++$col) { $value = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); $file_data[$col] = trim($value); } $result[] = $file_data; } print_r($result); } else { print "Invalid uploads"; } }
/** * Stores new upload * */ public function store() { $file = Input::file('file'); $upload = new Upload(); try { $upload->process($file); } catch (Exception $exception) { // Something went wrong. Log it. Log::error($exception); $error = array('name' => $file->getClientOriginalName(), 'size' => $file->getSize(), 'error' => $exception->getMessage()); // Return error return Response::json($error, 400); } // If it now has an id, it should have been successful. if ($upload->id) { $newurl = URL::asset($upload->publicpath() . $upload->filename); // this creates the response structure for jquery file upload $success = new stdClass(); $success->name = $upload->filename; $success->size = $upload->size; $success->url = $newurl; $success->thumbnailUrl = $newurl; $success->deleteUrl = action('UploadController@delete', $upload->id); $success->deleteType = 'DELETE'; $success->fileID = $upload->id; return Response::json(array('files' => array($success)), 200); } else { return Response::json('Error', 400); } }
/** * Register * * @access public * @author Dao Anh Minh */ public function action_register() { $view = View::forge('admin/gallery/register'); $view->err = array(); $view->data = array('description' => ''); if (Input::method() == 'POST') { Upload::process($this->config); if (Upload::is_valid()) { Upload::save(); $file_name = Upload::get_files(0)['saved_as']; if (!empty($file_name)) { $img = Model_Img::forge(); $img->name = $file_name; $img->active = Input::post('active', false); $img->type = IMG_GALLERY; $img->info = serialize(array('info' => Input::post('description', ''))); $img->save(); Session::set_flash('success', 'Đăng ký hình thành công'); Response::redirect('admin/gallery'); } else { Session::set_flash('error', 'Chỉ chấp nhận file hình'); Response::redirect('admin/gallery/register'); } } else { Session::set_flash('error', 'Hình bạn chọn không phù hợp, vui lòng thử lại'); $view->data = Input::post(); } } $this->template->title = 'Đăng ký hình'; $this->template->content = $view; }
public function action_create() { if (Input::method() == 'POST') { $config = array('path' => DOCROOT . DS . 'files', 'randomize' => true, 'ext_whitelist' => array('txt')); Upload::process($config); if (Upload::is_valid()) { $file = Upload::get_files(0); $contents = File::read($file['file'], true); foreach (explode("\n", $contents) as $line) { if (preg_match('/record [0-9]+ BAD- PHONE: ([0-9]+) ROW: \\|[0-9]+\\| DUP: [0-9] [0-9]+/i', $line, $matches)) { $all_dupes[] = $matches[1]; } } $dupe_check = \Goautodial\Insert::duplicate_check($all_dupes); foreach ($dupe_check as $dupe_number => $dupe_details) { $new_duplicate = new Model_Data_Supplier_Campaign_Lists_Duplicate(); $new_duplicate->list_id = Input::post('list_id'); $new_duplicate->database_server_id = Input::post('database_server_id'); $new_duplicate->duplicate_number = $dupe_number; $new_duplicate->dialler = $dupe_details['dialler']; $new_duplicate->lead_id = $dupe_details['data']['lead_id']; $new_duplicate->save(); } } else { print "No Uploads"; } } $this->template->title = "Data_Supplier_Campaign_Lists_Duplicates"; $this->template->content = View::forge('data/supplier/campaign/lists/duplicates/create'); }
/** * アップロードファイルを指定のフォルダに移動する * * @access public * @param array $config アップロードの設定 * @return void * @author kobayashi * @author ida */ public static function moveUploadedFile($config) { $default = array('ext_whitelist' => array('jpg'), 'randomize' => true); $config = array_merge($default, $config); \Upload::process($config); $is_upload = false; $result = array(); if (\Upload::is_valid()) { \Upload::save(); $files = \Upload::get_files(); foreach ($files as $file) { $result[$file['field']] = $file; } $is_upload = true; } else { $error_files = \Upload::get_errors(); foreach ($error_files as $file) { foreach ($file['errors'] as $error) { if ($error['error'] != \Upload::UPLOAD_ERR_NO_FILE) { $result[$file['field']] = $file; $is_upload = false; } } } if (empty($result)) { $is_upload = true; } } return array($is_upload, $result); }
public function action_commit() { $item = new Model_Item(); $item->name = $_POST['item_name']; $item->phonetic = $_POST['phonetic']; $item->category = $_POST['category']; if ($_POST['category'] == 'ピザ') { $item->unit_price_s = $_POST['s_money']; $item->unit_price_m = $_POST['m_money']; $item->unit_price_l = $_POST['l_money']; } else { $item->unit_price = $_POST['money']; } $item->explanatory = $_POST['explanation']; $item_img = new Model_Itemimg(); // 初期設定 $config = array('path' => DOCROOT . DS . 'assets/img', 'randomize' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')); // アップロード基本プロセス実行 Upload::process($config); // 検証 if (Upload::is_valid()) { // 設定を元に保存 Upload::save(); $uploadfile = Upload::get_files(0); // 情報をデータベースに保存する場合 $item_img->path = $uploadfile["name"]; } foreach (Upload::get_errors() as $file) { // $file['errors']の中にエラーが入っているのでそれを処理 } $item_img->save(); $item->img_id = $item_img->id; $item->save(); return View::forge('top/top'); }
public function action_index() { $is_chenged = false; if ($this->user->bank == null) { $this->user->bank = Model_Bank::forge(); $this->user->bank->user_id = $this->user->id; $this->user->bank->save(); } if (Input::post("firstname", null) != null and Security::check_token()) { $email = Input::post("email", null); if ($email != $this->user->email) { $check_user = Model_User::find("first", ["where" => [["email" => $email]]]); if ($check_user == null) { $this->email = $email; } else { $data["error"] = "This email is already in use."; } } $config = ["path" => DOCROOT . "assets/img/pictures/", 'randomize' => true, 'auto_rename' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')]; Upload::process($config); if (Upload::is_valid()) { Upload::save(); $saved_result = Upload::get_files(); $file_name = $saved_result[0]['saved_as']; $image = Image::load($config["path"] . $file_name); $image->crop_resize(200, 200)->save($config["path"] . "m_" . $file_name); $image->crop_resize(86, 86)->save($config["path"] . "s_" . $file_name); $this->user->img_path = $file_name; } else { $error = Upload::get_errors(); } if (!isset($data["error"])) { $this->user->firstname = Input::post("firstname", ""); $this->user->middlename = Input::post("middlename", ""); $this->user->lastname = Input::post("lastname", ""); $this->user->google_account = Input::post("google_account", ""); $this->user->pr = Input::post("pr", ""); $this->user->educational_background = Input::post("educational_background", ""); $this->user->enchantJS = Input::post("enchantJS", 0); $this->user->trial = Input::post("trial", 0); $this->user->save(); $this->user->bank->name = Input::post("bank_name", ""); $this->user->bank->branch = Input::post("bank_branch", ""); $this->user->bank->account = Input::post("bank_account", ""); $this->user->bank->number = Input::post("bank_number", ""); $this->user->bank->etc = Input::post("bank_etc", ""); $this->user->bank->type = Input::post("bank_type", 0); $this->user->bank->save(); $is_chenged = true; } } $data["user"] = $this->user; $data["is_chenged"] = $is_chenged; $view = View::forge("teachers/profile", $data); $this->template->content = $view; }
/** * Действие для редактирования данных игрока * * @param int $id */ public function action_edit($id = null) { is_null($id) and \Response::redirect_back('admin/players'); if (!($player = \Model_Player::find($id))) { \Session::set_flash('error', 'Игрок не найден.'); \Response::redirect_back('admin/players'); } $val = \Model_Player::validate('edit'); if ($val->run()) { // Валидация для фото $config = array('path' => DOCROOT . 'assets/img/players', 'randomize' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')); \Upload::process($config); if (\Upload::is_valid() or \Upload::get_errors()[0]['errors'][0]['error'] == 4) { $player->player_name = \Input::post('player_name'); $player->is_core_player = \Input::post('is_core_player', 0); $player->position_id = \Input::post('position_id'); $player->birthdate = strtotime(\Input::post('birthdate')); $player->data = \Input::post('data'); if (!\Upload::get_errors()) { // Сохраняем файл на диск \Upload::save(); // Меняем размер изображения на 350px * 466px $files = \Upload::get_files(); $path = $files[0]['saved_to'] . $files[0]['saved_as']; \Image::load($path)->resize(350, 466, true)->save($path); // Удаляем старый файл if ($player->image_uri) { unlink(DOCROOT . 'assets/img/players/' . $player->image_uri); } $player->image_uri = $files[0]['saved_as']; } if ($player->save()) { \Session::set_flash('success', 'Игрок обновлён.'); \Response::redirect('admin/players'); } else { Session::set_flash('error', 'Could not update Player #' . $id); } } } else { if (\Input::method() == 'POST') { $player->player_name = $val->validated('player_name'); $player->is_core_player = $val->validated('is_core_player'); $player->position_id = $val->validated('position_id'); $player->birthdate = strtotime($val->validated('birthdate')); $player->data = $val->validated('data'); \Session::set_flash('error', $val->error()); } $this->template->set_global('player', $player, false); } $this->template->content = \View::forge('players/edit'); }
/** * Действие для редактирования слайдера * * @param int $id */ public function action_edit($id = null) { is_null($id) and \Response::redirect('sliders'); if (!($slider = \Model_Slider::find($id))) { \Session::set_flash('error', 'Невозможно найти слайдер'); \Response::redirect('admin/sliders/index'); } $val = \Model_Slider::validate('edit'); if ($val->run()) { // Загружаем файл $config = array('path' => DOCROOT . 'assets/img/slider', 'randomize' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')); \Upload::process($config); if (\Upload::is_valid()) { // Сохраняем файл на диск \Upload::save(); // Меняем размер изображения на 650px * 435px $files = \Upload::get_files(); $path = $files[0]['saved_to'] . $files[0]['saved_as']; \Image::load($path)->resize(650, 435, false)->save($path); // Удаляем старый файл unlink(DOCROOT . 'assets/img/slider/' . $slider->img_path); // Пишем инфу в БД $slider->img_path = $files[0]['saved_as']; $slider->description = \Input::post('description'); $slider->uri = \Input::post('uri'); if ($slider->save()) { \Session::set_flash('success', 'Слайд отредактировано.'); \Response::redirect('admin/sliders/index'); } else { \Session::set_flash('error', 'Ошибка при редактировании слайда.'); } } else { // Если есть ошибки при сохранении файла foreach (\Upload::get_errors() as $file) { if (isset($file['errors'][0])) { \Session::set_flash('error', $file['errors'][0]['message']); } } } } else { if (\Input::method() == 'POST') { $slider->uri = $val->validated('uri'); $slider->description = $val->validated('description'); \Session::set_flash('error', $val->error()); } } $this->template->set_global('slider', $slider, false); $this->template->title = "Слайды"; $this->template->content = \View::forge('sliders/edit'); }
function processImg($img) { $upload = new Upload($img['picture']); $upload->file_new_name_body = time(); foreach ($this->img_config['picture'] as $key => $value) { $upload->{$key} = $value; } $upload->process($this->img_config['target_path']['picture']); if (!$upload->processed) { $msg = $this->generateError($upload->error); return $this->redirect('create'); } $return['file_dst_name'] = $upload->file_dst_name; return $return; }
public function action_add_letterhead() { $validation = Validation::forge(); if ($validation->run()) { $config = array('path' => \Subpackage\Subconfig::get(static::$_configFile . '.letterhead_directory'), 'randomize' => true, 'ext_whitelist' => array('pdf')); Upload::process($config); if (Upload::is_valid()) { Upload::save(); $filename = Upload::get_files(); $insertID = Model_Letterhead::create(Input::post('letterhead_title'), Input::post('letterhead_description'), Input::post('letterhead_company'), $filename[0]['saved_as'], array('top' => Input::post('letterhead_margin_top'), 'bottom' => Input::post('letterhead_margin_bottom'), 'left' => Input::post('letterhead_margin_left'), 'right' => Input::post('letterhead_margin_right')), Input::post('letterhead_product')); print "Added Letterhead with ID: " . $insertID; } } $this->template->title = 'Add Letterhead : Letter Management'; $this->template->content = View::forge(static::$_viewPath . 'manage/add_letterhead.php', array('companies' => \Crm\Company\Company_model::companyList())); }
function processAttachment($img) { $upload = new Upload($img['attachment']); $upload->file_new_name_body = time(); foreach ($this->img_config['attachment'] as $key => $value) { $upload->{$key} = $value; } $upload->process($this->img_config['target_path']['attachment']); if (!$upload->processed) { $msg = $this->generateError($upload->error); $this->Session->setFlash($msg); return $this->redirect($this->referer()); } $return['file_dst_name'] = $upload->file_dst_name; return $return; }
public function __construct($arrParam = null, $options = null) { $this->_arrData = $arrParam; $this->_validate = \Validation::forge('validate'); //$this->_validate->add_field('file_process_data', 'File Data', 'required'); /*======================================================= * Start - validate file_process_data *=======================================================*/ if (!empty($_FILES['file_process_data']['name'])) { $this->_upload = \Upload::process(array('path' => DOCROOT . 'files' . DS . 'sony_payment' . DS . 'file_data', 'ext_whitelist' => array('csv'), 'max_size' => '1024000000', 'suffix' => '_' . strtotime('now'), 'normalize' => true, 'auto_rename' => true)); if (!\Upload::is_valid()) { $error = \Upload::get_errors('file_process_data'); $this->_arrError['file_process_data'] = $error['errors'][0]['message']; } } else { $this->_arrError['file_process_data'] = 'アップロード名 は必須入力です。'; } }
public function action_update($Pid = 0) { $username = Auth::get_screen_name(); $this->data['token_key'] = Config::get('security.csrf_token_key'); $this->data['token'] = Security::fetch_token(); if (Security::check_token()) { $val = Model_Post::validate(); if ($val->run()) { $post = Model_Post::find($Pid); $post->class = Input::post('cla'); $post->Title = Input::post('title'); $post->Pcontent = Input::post('Pcontent'); $post->Kid = Input::post('category'); Upload::process(); if (Upload::is_valid()) { //設定を元に保存をする Upload::save(); foreach (Upload::get_files() as $file) { $post->image = $file['saved_as']; } } $post->save(); $this->action_categorize(); $this->data['users'] = Model_Users::query()->where('username', '=', $username)->get(); $this->data['posts'] = Model_Post::query()->where('username', '=', $username)->order_by('Ptime', 'desc')->get(); $message = '投稿内容を変更しました。'; $view = View::forge('mypage/mypage', $this->data); $view->username = $username; $view->set_global('message', $message, false); $view->set_global('error', $this->error, false); //バリデーションエラー } else { $this->action_categorize(); $Pid and $this->data['posts'] = DB::select()->from('Post')->where('Pid', '=', $Pid)->execute(); $view = View::forge('post/PostEdit', $this->data); $this->error = $val->error(); $view->username = $username; $view->set_global('error', $this->error, false); } } else { Profiler::mark('CSRFだー!'); } return $view; }
/** * Редактирование команды * * @param int $id */ public function action_edit($id = null) { is_null($id) and \Response::redirect('teams'); if (!($team = \Model_Team::find($id))) { \Session::set_flash('error', 'Команда не найдена.'); \Response::redirect_back('admin/competitions/teams'); } $val = \Model_Team::validate('edit'); if ($val->run()) { // Валидация для фото $config = array('path' => DOCROOT . 'assets/img/teams', 'randomize' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')); \Upload::process($config); if (\Upload::is_valid() or \Upload::get_errors()[0]['errors'][0]['error'] == 4) { $team->value = \Input::post('value'); if (!\Upload::get_errors()) { // Сохраняем файл на диск \Upload::save(); // Меняем размер изображения на 50px * 50px $files = \Upload::get_files(); $path = $files[0]['saved_to'] . $files[0]['saved_as']; \Image::load($path)->resize(50, 50, true)->save($path); // Удаляем старый файл if ($team->logo_uri) { unlink(DOCROOT . 'assets/img/teams/' . $team->logo_uri); } $team->logo_uri = $files[0]['saved_as']; } if ($team->save()) { \Session::set_flash('success', 'Команда обновлена.'); \Response::redirect_back('admin/competitions/teams'); } else { Session::set_flash('error', 'Could not update Team #' . $id); } } } else { if (\Input::method() == 'POST') { $team->value = $val->validated('value'); \Session::set_flash('error', $val->error()); } $this->template->set_global('team', $team, false); } $this->template->content = \View::forge('competitions/teams/edit'); }
public function action_do_upload() { logger('1', 'Starting upload'); \Upload::process(array('path' => './uploads', 'normalize' => true, 'change_case' => 'lower')); logger('1', 'Finished upload'); echo "<pre>"; print_r(\Upload::get_files()); print_r(\Upload::get_errors()); logger('1', 'Errors: ' . serialize(\Upload::get_errors())); echo \Upload::is_valid() ? "<span style='color: green; font-weight: bold;'>VALID</span>" : "<span style='color: red; font-weight: bold;'>ERROR</span>"; echo '<br><br><br>'; \Upload::save(); echo 'Valid:<br>'; print_r(\Upload::get_files()); logger('1', 'Valid uploads: ' . serialize(\Upload::get_files())); echo '<br>Errors:<br>'; print_r(\Upload::get_errors()); echo "</pre>"; }
public function action_upload($folder, $sub = null) { if (\Fuel\Core\Input::method() == 'POST') { try { \Fuel\Core\DB::start_transaction(); $val = Model_Filemanager::validate('create'); if ($val->run()) { $config = array('path' => "/var/www/html/" . $this->_dir . "/" . $folder . "/" . $sub . DS, 'ext_whitelist' => array('jpg', 'jpeg', 'png'), 'file_chmod' => 0777, 'auto_rename' => true, 'overwrite' => true, 'randomize' => true, 'create_path' => true); Upload::process($config); $img = ''; if (Upload::is_valid()) { Upload::save(); $img = Upload::get_files()[0]; } if (!\Fuel\Core\Input::post('id')) { $file = Model_Filemanager::forge(array('folder' => $folder, 'key' => Input::post('key'), 'value' => $img['saved_as'], 'photographer' => \Fuel\Core\Input::post('photographer'), 'price' => \Fuel\Core\Input::post('price'), 'usage' => \Fuel\Core\Input::post('usage'), 'source' => \Fuel\Core\Input::post('source'))); } else { $file = Model_Filemanager::find_by_id(\Fuel\Core\Input::post('id')); if ($img == '') { $img = $file->value; } if ($file) { $file->set(array('folder' => $folder, 'key' => Input::post('key'), 'value' => $img, 'photographer' => \Fuel\Core\Input::post('photographer'), 'price' => \Fuel\Core\Input::post('price'), 'usage' => \Fuel\Core\Input::post('usage'), 'source' => \Fuel\Core\Input::post('source'))); } else { throw new Exception('File not found!'); } } if ($file and $file->save()) { DB::commit_transaction(); \Fuel\Core\Session::set_flash('success', 'Upload success'); } else { throw new Exception('Cannot save into database!'); } } else { throw new Exception($val->show_errors()); } } catch (Exception $e) { DB::rollback_transaction(); \Fuel\Core\Session::set_flash('error', $e->getMessage()); } } \Fuel\Core\Response::redirect(\Fuel\Core\Uri::create('filemanager/folder/' . $folder)); }
public function action_index() { $is_chenged = false; if (Input::post("firstname", null) != null and Security::check_token()) { $email = Input::post("email", null); if ($email != $this->user->email) { $check_user = Model_User::find("first", ["where" => [["email" => $email]]]); if ($check_user == null) { $this->email = $email; } else { $data["error"] = "This email is already in use."; } } $config = ["path" => DOCROOT . "assets/img/pictures/", 'randomize' => true, 'auto_rename' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')]; Upload::process($config); if (Upload::is_valid()) { Upload::save(); $saved_result = Upload::get_files(); $file_name = $saved_result[0]['saved_as']; $image = Image::load($config["path"] . $file_name); $image->crop_resize(200, 200)->save($config["path"] . "m_" . $file_name); $image->crop_resize(86, 86)->save($config["path"] . "s_" . $file_name); $this->user->img_path = $file_name; } else { $error = Upload::get_errors(); } if (!isset($data["error"])) { $this->user->firstname = Input::post("firstname", ""); $this->user->middlename = Input::post("middlename", ""); $this->user->lastname = Input::post("lastname", ""); $this->user->save(); $is_chenged = true; } } $data['pasts'] = Model_Lessontime::find("all", ["where" => [["student_id", $this->user->id], ["status", 2], ["language", Input::get("course", 0)], ["deleted_at", 0]]]); $data["donetrial"] = Model_Lessontime::find("all", ["where" => [["student_id", $this->user->id], ["status", 2], ["language", Input::get("course", -1)], ["deleted_at", 0]]]); $data["user"] = $this->user; $data["is_chenged"] = $is_chenged; $view = View::forge("students/profile", $data); $this->template->content = $view; }
public function action_register() { if (Input::method() == 'POST') { $val = Model_User::validate('create'); if ($val->run()) { $user = Model_User::forge(array('username' => Input::post('username'), 'password' => Auth::instance()->hash_password(Input::post('password')), 'group' => 1, 'email' => Input::post('email'), 'fname' => Input::post('fname'), 'mname' => Input::post('mname'), 'lname' => Input::post('lname'), 'contact_num' => Input::post('contact_num'), 'address' => Input::post('address'), 'profile_pic' => Input::post('profile_pic'), 'last_login' => Input::post('last_login'), 'login_hash' => Input::post('login_hash'), 'profile_fields' => Input::post('profile_fields'))); Upload::process(Config::get('upload_profile_picture')); $user->profile = Model_Student::forge(['year_level' => 0, 'course_id' => 0]); if (Upload::is_valid()) { Upload::save(); $value = Upload::get_files(); foreach ($value as $files) { $user->profile_pic = $value[0]['saved_as']; } if ($user and $user->save()) { Session::set_flash('success', e('Succesfully Added user #' . $user->id . '.')); Response::redirect('site/login'); } else { Session::set_flash('error', e('Could not save user.')); } } else { Session::set_flash('error', e('Uploaded photo is invalid.')); } // if ($user and $user->save()) // { // Session::set_flash('success', e('Succesfully Added user #'.$user->id.'.')); // Response::redirect('site/login'); // } // else // { // Session::set_flash('error', e('Could not save user.')); // } } else { Session::set_flash('error', $val->error()); } } // $this->template->title = "Users"; // $this->template->content = View::forge('admin/users/create'); $this->template->title = 'Register'; $this->template->content = View::forge('site/register'); }
public function action_file($table_name) { // Find class name and metadata etc $class_name = \Admin::getClassForTable($table_name); if ($class_name === false) { return $this->show404(null, "type"); } // Don't continue if no files have been uploaded if (!count(\Upload::get_files())) { \Session::set_flash('main_alert', array('attributes' => array('class' => 'alert-danger'), 'msg' => \Lang::get('admin.errors.upload.no_files'))); \Response::redirect_back("/admin/{$table_name}"); } // Ensure directory exists $path = DOCROOT . 'uploads/imports'; if (!is_dir($path)) { @mkdir($path, 0775, true); } if (!is_dir($path)) { \Session::set_flash('main_alert', array('attributes' => array('class' => 'alert-danger'), 'msg' => \Lang::get('admin.errors.upload.directory_not_created'))); return; } // Process the uploaded file \Upload::process(array('path' => $path, 'auto_rename' => false, 'overwrite' => true, 'normalize' => true, 'ext_whitelist' => array('xlsx', 'xls', 'xml', 'csv', 'json'))); // Save it to the filesystem if valid if (\Upload::is_valid()) { \Upload::save(); } // Import the file $file = \Upload::get_files(0); $file_path = \Arr::get($file, 'saved_to') . \Arr::get($file, 'saved_as'); $this->import_result = \CMF\Utils\Importer::importFile($file_path, $class_name); // If success, redirect back with message if (isset($this->import_result['success']) && $this->import_result['success']) { \Session::set_flash('main_alert', array('attributes' => array('class' => 'alert-success'), 'msg' => isset($this->import_result['message']) ? $this->import_result['message'] : \Lang::get('admin.messages.import_success'))); \Response::redirect("/admin/{$table_name}", 'location'); } // No success, damn! \Session::set_flash('main_alert', array('attributes' => array('class' => 'alert-danger'), 'msg' => isset($this->import_result['message']) ? $this->import_result['message'] : \Lang::get('admin.errors.actions.import'))); \Response::redirect_back("/admin/{$table_name}"); }
/** * Crop and save file to filesystem at the inputted folder * * @param sfValidatedFile $file * @param <string> $path * @param <integer> $width * @param <integer> $height * @param <boolean> $crop * @return <boolean> false | <string> saved file location */ public static function savePicture(sfValidatedFile $file, $path, $width, $height, $crop) { $filename = $file->getOriginalName(); $img = new Upload($file->getTempName()); $pos = strrpos($filename, '.') + 1; $type = substr($filename, $pos); $newName = $basename = md5(substr($filename, 0, --$pos) . rand(1111, 9999)); $img->file_new_name_body = $newName; $img->file_new_name_ext = $type; $img->file_is_image = true; $img->image_resize = true; $img->image_src_type = strtolower($type); // check for resize x if ($img->image_src_x > $width) { $img->image_x = $width; } else { $img->image_x = $img->image_src_x; } // check for resize y if ($img->image_src_y > $height) { $img->image_y = $height; } else { $img->image_y = $img->image_src_y; } $img->image_ratio_crop = $crop; $img->file_auto_rename = false; $img->file_overwrite = true; // execution $img->process($path); if (!file_exists($path . '/' . $img->file_dst_name)) { return false; } if (!chmod($path . '/' . $img->file_dst_name, 0777)) { return false; } else { return $path . '/' . $img->file_dst_name; } }
public function index() { $this->load->library('upload'); $handle = new Upload($_FILES['upload']); $filename = time() . rand(0, 999); $handle->file_new_name_body = md5($filename); if ($handle->uploaded) { $dir = date('/Y/m/d/'); $path = DIR_UPLOAD . 'images' . $dir; $handle->process($path); if ($handle->processed) { $handle->clean(); $response['status'] = true; $response['data'] = array('path' => '/upload/images' . $dir . $handle->file_dst_name, 'name' => $handle->file_src_name); $response['message'] = 'success'; } else { $response['status'] = false; $response['data'] = ''; $response['message'] = $handle->error; } } $this->response->outputJson($response); }
public function action_base64_encode_image() { if ($_POST) { $asciiFormat = Inflector::ascii(Input::post('filename')); $webSafeName = Inflector::friendly_title($asciiFormat, '_', true); $uploadLocation = 'assets/img/upload/'; $config = array('auto_process' => 'false', 'path' => DOCROOT . $uploadLocation, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'), 'new_name' => $webSafeName, 'normalize' => true, 'change_case' => 'lower', 'auto_rename' => false, 'overwrite' => true); // process the uploaded files in $_FILES Upload::process($config); // if there are any valid files if (Upload::is_valid()) { // save them according to the config Upload::save(); // Grab the file extension $uploadedFile = Upload::get_files(0); $filename = $webSafeName . '.' . $uploadedFile['extension']; $input_file = $uploadedFile['saved_to'] . $uploadedFile['saved_as']; $image64Encoded = $this->_base64_encode_image($input_file, $uploadedFile['extension']); $asset = Model_Asset::forge(array('name' => $uploadedFile['saved_as'], 'uri' => $uploadLocation, 'type' => $uploadedFile['extension'])); $asset->save(); return '<img src="' . $image64Encoded . '" />'; } else { // and process any errors foreach (Upload::get_errors() as $key => $file) { // $file is an array with all file information, // $file['errors'] contains an array of all error occurred // each array element is an an array containing 'error' and 'message' // Session::set_flash('error', $file['errors'] ); echo 'Error ' . $key . ' - '; print_r($file['errors']); echo ' <br />'; } die; } } return; }
} // No errors, attemp to do the upload process if (!$error) { require_once __CHV_PATH_CLASSES__ . 'class.upload.php'; $api_upload = new Upload($to_upload); if ($api_remote_upload) { $api_upload->is_remote = true; } $api_upload->img_upload_path = __CHV_PATH_IMAGES__; $api_upload->storage = chevereto_config('storage'); $api_upload->resize_width = $to_resize; $api_upload->thumb_width = chevereto_config('thumb_width'); $api_upload->thumb_height = chevereto_config('thumb_height'); $api_upload->max_size = return_bytes(chevereto_config('max_filesize')); /*** Do the thing? ***/ if ($api_upload->process()) { $api_status_code = 200; $api_status_txt = 'OK'; // Build the data array $api_data_array = $api_upload->image_info; if ($api_upload->is_remote) { $api_data_array['source'] = $to_upload; } else { $api_data_array['source'] = 'base64 image string'; } $api_data_array['resized'] = check_value($to_resize) ? '1' : '0'; $api_txt_output = $api_upload->image_info['image_url']; // Short URL generation if (is_config_short_url()) { require __CHV_PATH_INCLUDES__ . 'shorturl.php'; $api_data_array['shorturl'] = $ShortURL->get_ShortURL($api_upload->image_info['image_url']);
$handle->image_y = 50; $handle->image_x = 50; $handle->image_background_color = '#FFFFFF'; $handle->image_convert = 'png'; $handle->file_new_name_body = 'avatar'; $handle->file_safe_name = false; $handle->file_force_extension = false; $handle->file_new_name_ext = ''; $handle->allowed = 'image/*'; $handle->file_overwrite = true; if ($handle->uploaded && Config::get('sys_enable_avatars', true)) { $csrf->check(); $user_id = (string) $user->getId(); $avatar_path = Config::get('sys_avatar_path', Config::get('sys_data_dir') . '/user/avatar/'); $path = "{$avatar_path}/" . substr($user_id, -2, 1) . '/' . substr($user_id, -1, 1) . "/{$user_id}"; $handle->process($path); if ($handle->processed) { $user->sethasAvatar(); $user_manager->updateDb($user); $GLOBALS['Response']->addFeedback('info', $GLOBALS['Language']->getText('account_change_avatar', 'success')); $GLOBALS['Response']->redirect('/account/'); } else { $GLOBALS['Response']->addFeedback('error', $handle->error); } } } $title = $Language->getText('account_change_avatar', 'title'); $HTML->header(array('title' => $title)); echo '<h2>' . $title . '</h2>'; echo '<form action="/account/change_avatar.php" method="POST" enctype="multipart/form-data">'; echo '<input type="hidden" name="MAX_FILE_SIZE" value="300000" />';
public static function resizeImageWidth($image, $width = 1600) { $imageFullPath = trim(JPATH_ROOT . DIRECTORY_SEPARATOR . preg_replace('/.*images\\//', 'images/', $image)); if (!file_exists($imageFullPath)) { return $image; } $image_base_name = strstr(basename($imageFullPath), '.', true); $image_base_dir = dirname($imageFullPath); $newImageName = $image_base_name . '_' . $width; $handle = new Upload($image); $handle->allowed = array('image/*'); $height = $handle->image_src_y; // if the original size is smaller/equal to the the resize width, don't waste cpu cycles in resizing if ($handle->image_src_y <= $width) { return str_replace(JPATH_ROOT . DIRECTORY_SEPARATOR, '', $image_base_dir) . DIRECTORY_SEPARATOR . basename($imageFullPath); } if (file_exists($image_base_dir . DIRECTORY_SEPARATOR . $newImageName . '.jpg')) { // file already exists, however if the original is newer than cached. we should resize again. $image_time = filemtime($imageFullPath); $newImage_time = filemtime($image_base_dir . DIRECTORY_SEPARATOR . $newImageName . '.jpg'); if ($newImage_time >= $image_time) { return str_replace(JPATH_ROOT . DIRECTORY_SEPARATOR, '', $image_base_dir) . DIRECTORY_SEPARATOR . $newImageName . '.jpg'; } // else continue to resize } $handle->image_convert = 'jpg'; $handle->jpeg_quality = 70; $handle->file_new_name_body = $newImageName; $handle->file_overwrite = true; $handle->image_resize = true; $handle->image_x = $width; $handle->image_y = $height; $handle->image_ratio = true; $handle->process($image_base_dir); if (!$handle->processed) { error_log("Error Processing Image upload " . $handle->error); throw new EXception("Error Processing Image upload " . $handle->error); return false; } return str_replace(JPATH_ROOT . DIRECTORY_SEPARATOR, '', $image_base_dir) . DIRECTORY_SEPARATOR . $newImageName . '.jpg'; }
// $handle->image_ratio_crop = true; // $handle->image_y = 458; // $handle->jpeg_quality = 100; // $handle->image_unsharp = false; // $handle->process($root.'/img/g/1000/'.$f_id); // echo $root.'/img/g/1000/'.$f_id.'/'.$namephoto.'->'; // превью $handle->file_new_name_body = $namephoto; $handle->image_convert = "jpg"; $handle->image_resize = true; $handle->image_x = $handle->image_src_x > $handle->image_src_y ? 329 : 246; $handle->image_ratio_crop = true; $handle->image_y = $handle->image_src_x > $handle->image_src_y ? 219 : 369; $handle->jpeg_quality = 100; $handle->image_unsharp = false; $handle->process($root . '/img/g/' . $f_id); echo $root . '/img/g/' . $f_id . '/' . $namephoto . '->'; } // if($_POST['id']) // { // $db -> query("INSERT INTO menuphoto SET dtcreate='".date('Y-m-d H:i:s')."', name = '".$namephoto."', temp = 0, parent = ".$_POST['id']); // } // else // { // $db -> query("INSERT INTO menuphoto SET dtcreate='".date('Y-m-d H:i:s')."', name = '".$namephoto."', temp = 0, parent = ".$_POST['id_code']); // } // $img=$namephoto_img; // $arr=array(); // $arr=array_merge($arr,array('img'=>$img),array('id'=>$id)); // echo json_encode($arr); // }
public function action_create() { try { if (Input::method() == 'POST') { $file = Input::file('news_photo_file'); $val = Model_News::validate('create'); if ($val->run()) { $config = array('path' => "/var/www/html/uploads/news_photo/", 'ext_whitelist' => array('jpg', 'jpeg', 'png'), 'file_chmod' => 0777, 'auto_rename' => true, 'overwrite' => true, 'randomize' => true, 'create_path' => true); // $allowList = array(".jpeg", ".jpg", ".png"); // $error = false; // $path = realpath(DOCROOT."/../../uploads/news_photo/").DS; $news_photo = ""; Upload::process($config); if (Upload::is_valid()) { Upload::save(); $news_photo = Upload::get_files()[0]; $news = Model_News::forge(array('news_title' => Input::post('news_title'), 'news_short_detail' => Input::post('news_short_detail'), 'news_detail' => Input::post('news_detail'), 'news_photo' => $news_photo['saved_as'], 'news_published' => Input::post('news_published'), 'created_at' => time(), 'published_at' => Input::post('news_published') == 1 ? time() : 0)); if ($news and $news->save()) { Session::set_flash('success', 'Added news #' . $news->id . '.'); Response::redirect('news/edit/' . $news->id); } else { Session::set_flash('error', 'Could not save news.'); } if ($file and $file->save()) { DB::commit_transaction(); \Fuel\Core\Session::set_flash('success', 'Upload success'); } } /*if($file['size'] > 0){ $ext = strtolower(substr($file['name'],strrpos($file['name'],"."))); if(!in_array($ext,$allowList)){ Session::set_flash('error', 'ชนิดของไฟล์ภาพไม่ถูกต้อง'); $error = true; } $filename = md5(time()); if(@copy($file['tmp_name'],$path.$filename.$ext)){ $news_photo = $filename.$ext; /* small thumbnail */ # parent::create_cropped_thumbnail($path.$filename.$ext,64,64,"-s"); # parent::create_cropped_thumbnail($path.$filename.$ext,128,128,"-s@2x"); /* */ /* medium thumbnail */ # parent::create_cropped_thumbnail($path.$filename.$ext,360,240,"-m"); # parent::create_cropped_thumbnail($path.$filename.$ext,720,480,"-m@2x"); /* } else { Session::set_flash('error', 'ไม่สามารถอัพโหลดไฟล์ภาพได้ โปรดลองใหม่อีกครั้ง'); $error = true; } }*/ /*if(!$error){ $news = Model_News::forge(array( 'news_title' => Input::post('news_title'), 'news_short_detail' => Input::post('news_short_detail'), 'news_detail' => Input::post('news_detail'), 'news_photo' => $news_photo, 'news_published' => Input::post('news_published'), 'created_at' => time(), 'published_at' => (Input::post('news_published')==1)?time():0 )); if ($news and $news->save()){ Session::set_flash('success', 'Added news #' . $news->id . '.'); Response::redirect('news/edit/'.$news->id); } else { Session::set_flash('error', 'Could not save news.'); } }*/ } else { $msg = '<ul>'; foreach ($val->error() as $field => $error) { $msg .= '<li>' . $error->get_message() . '</li>'; } $msg .= '</ul>'; Session::set_flash('error', $msg); } } $this->theme->set_template('edit'); $this->theme->get_template()->set_global('current_menu', "News", false); $this->theme->get_template()->set_global('current_menu_desc', "จัดการข่าวทั้งหมดในระบบ", false); $this->theme->get_template()->set('breadcrumb', array(array('title' => "Home", 'icon' => "fa-home", 'link' => Uri::create('home'), 'active' => false), array('title' => "News", 'icon' => "eicon-newspaper", 'link' => Uri::create('news/index'), 'active' => false), array('title' => "Create", 'icon' => "", 'link' => "", 'active' => true))); $this->theme->get_template()->set_global('mode', "create", false); $this->theme->get_template()->set('page_specific_js', "form_news.js"); $this->theme->set_partial('sidebar', 'common/sidebar'); $this->theme->set_partial('left', 'news/create'); } catch (Exception $e) { die($e->getMessage()); } }