Exemplo n.º 1
0
 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');
 }
 /**
  * アップロードファイルを指定のフォルダに移動する
  *
  * @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);
 }
Exemplo n.º 3
0
 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;
 }
Exemplo n.º 4
0
 public function update_item($post_data)
 {
     $upload_type = $this->def('upload_type', 'image');
     $upload_dir = \Config::get($upload_type . '_dir', 'files');
     $files = \Upload::get_files();
     $clean_class = str_replace('\\', '', $this->class);
     foreach ($files as $key => $params) {
         if ($params['field'] == $clean_class . '-' . ($this->item->id ? $this->item->id : 'new') . "-{$this->field}") {
             $idx = $key;
             break;
         }
     }
     if (isset($idx)) {
         \Upload::save(array($idx), $this->def('secure') ? realpath(\Config::get('secure_dir', 'secure') . $upload_dir) : DOCROOT . $upload_dir);
         $errors = \Upload::get_errors();
         if (!isset($errors[$idx])) {
             $files = \Upload::get_files();
             $name = $files[$idx]['saved_as'];
             $path = $files[$idx]['saved_to'];
             if ($upload_type == 'image') {
                 if ($dimensions = $this->def('dimension')) {
                     // resize image
                     $image = \Image::load($path . $name);
                     foreach ($dimensions as $dim) {
                         if (preg_match("/^(?P<width>[0-9]+)x(?P<height>[0-9]+)\$/i", $dim, $matches)) {
                             $image->resize($matches['width'], $matches['height'])->save_pa(null, strtolower("_{$dim}"));
                         }
                     }
                 }
             } elseif ($upload_type == 'audio') {
                 if ($lengths = $this->def('truncate')) {
                     if ($ffmpeg = \Config::get('ffmpeg')) {
                         foreach ($lengths as $len) {
                             // truncate audio track
                             $sample = preg_replace("/^(.+)\\.([^\\.]+)\$/", '$1_sample_' . $len . '.$2', $name);
                             // TODO: make an ffmpeg wrapper class
                             shell_exec("{$ffmpeg} -i " . escapeshellarg($path . $name) . " -t {$length} -acodec copy " . escapeshellarg(DOCROOT . $upload_dir . DS . $sample));
                         }
                     } else {
                         error_log("could not truncate audio: ffmpeg not configured.");
                     }
                 }
             }
             $this->item->{$this->field} = $name;
         } else {
             error_log(print_r($errors, true));
             return array('upload_error' => $this->def('desc') . ' failed to save. Error No. ' . $errors[$idx]['error']);
         }
     }
     return true;
 }
Exemplo n.º 5
0
 /**
  * Действие для редактирования данных игрока
  * 
  * @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');
 }
Exemplo n.º 6
0
 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'] = 'アップロード名 は必須入力です。';
     }
 }
Exemplo n.º 7
0
 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>";
 }
Exemplo n.º 8
0
 /**
  * Редактирование команды
  * 
  * @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');
 }
Exemplo n.º 9
0
 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;
 }
Exemplo n.º 10
0
 protected function get_upload_file($config)
 {
     try {
         Upload::process($config);
     } catch (Exception $e) {
         return null;
         // 未ログイン = アップロードなし = なにもしない
     }
     if (!Upload::is_valid()) {
         $files = Upload::get_errors();
         foreach ($files as $f) {
             foreach ($f['errors'] as $e) {
                 if ($e['error'] == 4) {
                     // no upload
                     continue;
                 } else {
                     $this->set_error([$f['field'] => 'ファイル形式が不正です'], true);
                 }
             }
         }
         if ($this->has_error()) {
             return false;
         }
     }
     return Upload::get_files();
 }
Exemplo n.º 11
0
 /**
  * ファイルアップロード<br>
  * 失敗した場合はfalseを返します。
  */
 private static function file_upload($shop_id)
 {
     if (is_null($shop_id)) {
         Log::error("parameter's shpo_id is null.");
         return false;
     }
     # ファイルアップロード設定
     $config = self::file_upload_config($shop_id);
     # アップロード実行
     Upload::process($config);
     # 検証
     if (Upload::is_valid()) {
         # アップロードファイルを保存(最初の1つを指定)
         Upload::save(0);
         foreach (Upload::get_files() as $file) {
             return $file['saved_as'];
         }
     }
     # エラー有り
     foreach (Upload::get_errors() as $file) {
         foreach ($file['errors'] as $error) {
             Log::error("file upload is fail. => {$error}", "file_upload");
         }
     }
     return false;
 }
Exemplo n.º 12
0
 public function action_discuss_brief()
 {
     if (\Input::post()) {
         // check for a valid CSRF token
         if (!\Security::check_token()) {
             \Messages::error('CSRF attack or expired CSRF token.');
             \Response::redirect(\Input::referrer(\Uri::create('/')));
         }
         $file = null;
         // Send autoresponder
         $autoresponder = \Autoresponder\Autoresponder::forge();
         $autoresponder->view_custom = 'discuss_brief';
         $autoresponder->view_admin = 'discuss_brief';
         $post = \Input::post();
         if ($product = \Product\Model_Product::find_one_by_id(\Input::post('product'))) {
             $post['product'] = $product;
         }
         $content['content'] = $post;
         $config = array('path' => APPPATH . 'tmp', 'normalize' => true, 'max_size' => 5242880);
         // Check if file uploaded
         if (isset($_FILES['fileUpload']['name']) && $_FILES['fileUpload']['name'] != '') {
             // 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();
                 $file = \Upload::get_files(0);
             }
             // Upload errors
             if (\Upload::get_errors() !== array()) {
                 foreach (\Upload::get_errors() as $file) {
                     foreach ($file['errors'] as $key => $value) {
                         \Messages::error($value['message']);
                     }
                 }
                 \Response::redirect(\Input::referrer(\Uri::create('/')));
             }
         }
         $attachment = array();
         if (isset($file['saved_to']) && is_file($file['saved_to'] . $file['saved_as'])) {
             $attachment = array($file['saved_to'] . $file['saved_as']);
         }
         // echo 'test';
         // die;
         $content['subject'] = 'Thanks for contacting Evan Evans';
         $autoresponder->autoresponder_custom($content, \Input::post('email'), $attachment);
         $content['subject'] = 'Autoresponder Discuss Brief for Admin';
         $autoresponder->autoresponder_admin($content, \Config::get('auto_response_emails.discuss_brief'), $attachment);
         if ($autoresponder->send()) {
             \Messages::success('Thank You for sending request.');
         } else {
             \Messages::error('There was an error while trying to submit request.');
         }
         // Delete uploaded files
         if (!empty($attachment)) {
             foreach ($attachment as $file) {
                 if (is_file($file)) {
                     unlink($file);
                 }
             }
         }
         \Response::redirect(\Input::referrer(\Uri::create('/')));
     }
     if (\Input::is_ajax()) {
         $products = \Product\Model_Product::fetch_pair('id', 'title', array('order_by' => array('title' => 'asc')));
         echo \Theme::instance()->view('views/_partials/discuss_brief')->set('products', $products, false);
         exit;
     }
     throw new \HttpNotFoundException();
 }
Exemplo n.º 13
0
 public function action_edit($id = null)
 {
     $val = Model_shop::validate('create');
     if (Input::method() == 'POST') {
         $config = array('path' => 'files/temp/', 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'));
         Upload::process($config);
         $image_path = '';
         if (Upload::is_valid()) {
             Upload::save();
             $file = Upload::get_files(0);
             $image_path = $file['name'];
             Session::set_flash('success', $file['name'] . " has been uploaded successfully.");
         } else {
             $error_file = Upload::get_errors(0);
             Session::set_flash('error', $error_file["errors"][0]["message"]);
         }
         if ($val->run()) {
             Session::set('id', Input::post('id'));
             Session::set('name', Input::post('name'));
             Session::set('postal_code', Input::post('postal_code'));
             Session::set('address', Input::post('address'));
             Session::set('pref', Input::post('pref'));
             Session::set('detail', Input::post('detail'));
             Session::set('category', Input::post('category'));
             Session::set('catchphrase', Input::post('catchphrase'));
             Session::set('hp_url', Input::post('hp_url'));
             Session::set('tel', Input::post('tel'));
             Session::set('image_path', $image_path);
             Session::set('holiday', Input::post('holiday'));
             Session::set('open_hh', Input::post('open_hh'));
             Session::set('open_mm', Input::post('open_mm'));
             Session::set('close_hh', Input::post('close_hh'));
             Session::set('close_mm', Input::post('close_mm'));
             Response::redirect('shop/confirm.php');
         } else {
             // バリデーションNGの場合
             Session::set_flash('error', $val->show_errors());
         }
     } else {
         $data['shop'] = Model_shop::find($id);
         $this->template->header = View::forge('docs-header-simple.php');
         $this->template->error = View::forge('error.php');
         $this->template->content = View::forge('shop/edit.php', $data);
         $this->template->sns = "";
         $this->template->footer = View::forge('footer.php');
         $this->template->daialog = View::forge('daialog.php');
     }
 }
Exemplo n.º 14
0
 /**
  * Edit background of category
  *
  * @param int $id cat. ID
  *
  * @author Nguyen Van Hiep
  * @access public
  *
  * @version 1.0
  * @since 1.0
  */
 public function action_img($id = null)
 {
     $cat = Model_Categories::get_cat_with_expected_size($id);
     if (!$cat or $id < 4) {
         Session::set_flash('error', __('message.cat_not_exists'));
         Response::redirect('admin/categories');
     }
     $this->add_js('img_preparation.js');
     $up_dir = DOCROOT . 'assets/img/cat/temp/';
     $img_dir = DOCROOT . 'assets/img/cat/';
     $view = View::forge('admin/categories/img');
     $view->cat = $cat;
     $view->error = array();
     $view->img = '';
     $view->width = 0;
     $view->height = 0;
     $view->pw = 0;
     $view->ph = 0;
     $view->rat = $cat['sizes'];
     if (Input::post('submit') == 'upload') {
         // Custom configuration for this upload
         $config = array('path' => $up_dir, 'randomize' => false, 'ext_whitelist' => array('jpg', 'jpeg', 'gif', 'png'), 'max_size' => MAX_IMG_SIZE, 'auto_rename' => true, 'overwrite' => false, 'prefix' => 'c' . $id . '_');
         Upload::process($config);
         if (Upload::is_valid()) {
             File::delete_dir($up_dir, true, false);
             Upload::save();
             $info = Upload::get_files(0);
             $filepath = $info['saved_to'] . $info['saved_as'];
             $view->img = $info['saved_as'];
             list($view->width, $view->height) = getimagesize($filepath);
             list($view->pw, $view->ph) = explode(':', $cat['sizes']);
             Session::set_flash('success', __('message.slider_uploaded'));
         } else {
             $err = Upload::get_errors()[0]['errors'][0];
             $view->error['img'] = $err['message'];
         }
     }
     if (Input::post('submit') == 'save') {
         $x1 = Input::post('x1');
         $y1 = Input::post('y1');
         $x2 = Input::post('x2');
         $y2 = Input::post('y2');
         $w = Input::post('w');
         $h = Input::post('h');
         $img = Input::post('img');
         $scale = 1;
         $this->resize_img($img_dir . $img, $up_dir . $img, $w, $h, $x1, $y1, $scale);
         Model_Categories::save_bg($id, $img, $cat['bg']);
         Session::set_flash('success', __('message.img_resized'));
         Response::redirect('admin/categories');
     }
     $this->template->title = __('cat.edit');
     $this->template->content = $view;
 }
Exemplo n.º 15
0
 /**
  * Tries to get attachments from uploaded files
  * @param type $event
  * @return array list of errors
  */
 private function try_get_attachments($event = null)
 {
     //first we check if there is probably a file
     //already stored from previous submissions.
     $old_file = Session::get("uploaded_file_" . Input::post("form_key"), null);
     if ($old_file != null and $event != null) {
         $event->poster = $old_file;
         $event->save();
         return array();
     }
     //no "old files" exist, let's catch the new ones!
     $config = array('path' => APPPATH . 'files', 'randomize' => false, 'auto_rename' => true, 'ext_whitelist' => array('pdf'));
     // 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();
         //call a model method to update the database
         $newfile = Upload::get_files(0);
         if ($event != null) {
             $event->poster = $newfile["saved_as"];
             $event->save();
             return array();
             //done, no errors
         } else {
             //there is no event yet (validation problems)
             //but there are uploaded files.
             //We store this information in the session
             //so that the next time user submits the form
             //with validation errors fixed, we can attach the "old" file
             Session::set("uploaded_file_" . Input::post("form_key"), $newfile["saved_as"]);
             return array();
             //no errors here!
         }
     } else {
         if (count(Upload::get_errors()) > 0) {
             //there was some problem with the files
             return array("The uploaded file could not be saved");
         } else {
             return array();
         }
     }
 }
Exemplo n.º 16
0
 protected function file_upload()
 {
     // File upload configuration
     $this->file_upload_config = array('path' => \Config::get('details.file.location.root'), 'normalize' => true, 'ext_whitelist' => array('pdf', 'xls', 'xlsx', 'doc', 'docx', 'txt'));
     // process the uploaded files in $_FILES
     \Upload::process($this->file_upload_config);
     // if there are any valid files
     if (\Upload::is_valid()) {
         // save them according to the config
         \Upload::save();
         \Messages::success('File successfully uploaded.');
         $this->uploaded_files = \Upload::get_files();
         return true;
     } else {
         // FILE ERRORS
         if (\Upload::get_errors() !== array()) {
             foreach (\Upload::get_errors() as $file) {
                 foreach ($file['errors'] as $key => $value) {
                     \Messages::error($value['message']);
                 }
             }
             \Response::redirect(\Uri::admin('current'));
         }
     }
     return false;
 }
Exemplo n.º 17
0
 /**
  * Действие для редактирования слайдера
  * 
  * @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');
 }
Exemplo n.º 18
0
 /**
  * Upload all contet files to local directory defined in $this->file_upload_config
  * 
  */
 public function upload_file()
 {
     $return['is_valid'] = true;
     $return['exists'] = false;
     $return['errors'] = false;
     // Check if there are selected files
     foreach (\Input::file() as $file) {
         if ($file['name'] != '') {
             $return['exists'] = true;
         }
     }
     // No files selected, so no errors too
     if (!$return['exists']) {
         return $return;
     }
     // File upload configuration
     $this->file_upload_config = array('path' => \Config::get('details.file.location.root'), 'normalize' => true, 'ext_whitelist' => array('pdf', 'xls', 'xlsx', 'doc', 'docx', 'txt'));
     \Upload::process($this->file_upload_config);
     // if there are any valid files
     if (\Upload::is_valid()) {
         // Save file
         \Upload::save();
         $this->_file_data = \Upload::get_files();
         return $return;
     } else {
         // FILE ERRORS
         if (\Upload::get_errors() !== array()) {
             foreach (\Upload::get_errors() as $file) {
                 foreach ($file['errors'] as $key => $value) {
                     $return['is_valid'] = false;
                     $return['errors'][] = $value['message'];
                 }
             }
         }
     }
     // If we got up to here, file is not uploaded
     return $return;
 }
Exemplo n.º 19
0
 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;
 }
Exemplo n.º 20
0
Arquivo: bbs.php Projeto: katsuwo/bbs
 /**
  * 投稿実行コントローラ
  * @return
  */
 public function action_post()
 {
     $result = false;
     //掲示板を得る
     $board = Model_Board::find(Input::post('bbsId_'));
     if ($board == null) {
         $log = new Logging();
         $log->writeLog_Warning('Invalid parameters at post(Board is missing) BBSID=' . $bbsId, __FILE__, __LINE__);
         return Response::forge('パラメータ異常');
     }
     //2ch型掲示板の場合は、バリデーションルールを変える
     $val = $this->doValidate($board);
     //コメントの場合、スレッド番号を求める
     if (isset($_POST['commentOf_'])) {
         $threadNum = $_POST['commentOf_'];
     } else {
         $threadNum = 0;
     }
     $out = '';
     //CSRFチェック
     if (!CSRFCheck::chkCSRFToken(__FILE__, __LINE__)) {
         // CSRF 攻撃または CSRF トークンの期限切れ
         $out = 'ページロードから時間が経過している為、投稿失敗しました。<BR>リロードして再投稿して下さい。';
         goto INVALIDPOST;
     }
     //添付ファイルを検証
     // エラーを処理する
     $out = '';
     $aReasult = true;
     try {
         foreach (Upload::get_errors() as $file) {
             if ($file['size'] != 0) {
                 foreach ($file['errors'] as $error) {
                     $out .= $error['message'] . '<br>';
                 }
                 $aReasult = false;
             }
         }
     } catch (Exception $ex) {
         $aReasult = false;
     }
     if ($val->run()) {
         $bbsId = $val->validated('bbsId_');
         $article = Model_Article::forge();
         $article->bbsId = $bbsId;
         $article->authorName = $val->validated('authorName');
         $article->authorAge = $val->validated('authorAge');
         $article->authorPrefecture = $val->validated('authorPrefecture');
         $article->authorIsMale = $val->validated('authorIsMale');
         $article->authorProfile = $val->validated('authorProfile');
         $article->authorEmail = $val->validated('authorEmail');
         $article->commentOf = $threadNum;
         $article->title = $val->validated('title');
         $article->body = $val->validated('body');
         $article->password = $val->validated('password');
         $article->numberOfLike = 0;
         $article->numberOfView = 0;
         $article->authorAgent = $_SERVER['HTTP_USER_AGENT'];
         $article->authorIP = Input::ip();
         $article->reserve1 = -1;
         $article->isDeleted = 0;
         if ($board->allowXvideos == true) {
             $article->xvideosURL = $val->validated('xvideosURL');
         }
         $article->save();
         //新規投稿ではUpdate_atが付かないため、一度修正して再度保存
         $article->reserve1 = 0;
         $article->save();
         if ($aReasult == true) {
             if (Upload::is_valid()) {
                 $image = Image::forge();
                 $files = Upload::get_Files();
                 $tmpDir = DOCROOT . 'assets/img/tmp';
                 foreach ($files as $file) {
                     $fileName = $file['file'];
                     $img_file = file_get_contents($fileName);
                     if ($img_file) {
                         //一時ファイルを拡張子付きにリネーム
                         $fileWithExt = $fileName . '.' . $file['extension'];
                         rename($fileName, $fileWithExt);
                         //PC用としても大きすぎる場合はリサイズ
                         $imgInfo = getimagesize($fileWithExt);
                         if ($imgInfo[0] > FULL_SIZE_X) {
                             $image->load($fileWithExt);
                             $image->config('bgcolor', '#FFF')->resize(FULL_SIZE_X, FULL_SIZE_X, true, false);
                             $image->save($fileWithExt);
                             $img_file = file_get_contents($fileWithExt);
                         }
                         //サムネイル作成
                         $thumbName = $tmpDir . DS . date('_ymdhis') . $this->random() . $file['name'];
                         $image->load($fileWithExt);
                         $image->config('bgcolor', '#FFF')->resize(THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y, true, false);
                         $image->save($thumbName);
                         $attach = Model_Attach::forge();
                         $attach->bbsId = $bbsId;
                         $attach->mime = $file['mimetype'];
                         $attach->attachOf = $article->id;
                         $attach->rawData = $img_file;
                         if ($threadNum != 0) {
                             $attach->threadId = $threadNum;
                         } else {
                             $attach->threadId = $article->id;
                         }
                         $thumb_file = file_get_contents($thumbName);
                         if ($thumb_file) {
                             $attach->thumbData = $thumb_file;
                             $attach->save();
                             unlink($thumbName);
                             unlink($fileWithExt);
                         } else {
                             $attach->save();
                             unlink($fileWithExt);
                         }
                     }
                 }
             }
         }
         //掲示板のupdate_at更新
         $bd = Model_Board::find($bbsId);
         $bd->postCount = $bd->postCount + 1;
         $bd->save();
         //スレッド元のupdated_at更新
         $query = Model_Article::query();
         $query->where('id', '=', $threadNum);
         $query->and_where_open();
         $query->where('bbsId', $bbsId);
         $query->and_where_close();
         $th = $query->get_one();
         if ($th != null) {
             $th->commentCount = $th->commentCount + 1;
             $th->save();
         }
         //新しいスレッドをTweet
         if ($bd->type != 3 && $bd->twitter) {
             $tw = new Twitter();
             $tw->tweet_newArticleBuild($board, $article);
         }
         $out = '投稿完了しました。';
         $result = true;
     } else {
         foreach ($val->error() as $error) {
             $out .= $error . '<br>';
         }
         $result = false;
     }
     //正常系
     if ($result == true) {
         $this->showPostSucessPage($bbsId, $threadNum);
         return;
     }
     //異常系
     INVALIDPOST:
     //Boardを取得
     $board = Model_Board::find($_POST['bbsId_']);
     if ($threadNum == 0) {
         //新規スレッド投稿
         $redirectURL = 'bbs/index/' . $board->shortName;
     } else {
         //コメント投稿
         $redirectURL = 'bbs/thread/' . $board->shortName . DS . $threadNum;
     }
     //エラーメッセージと、POSTをsessionで渡す
     Session::set('errorMsg', $out);
     Session::set('oldPost', $_POST);
     Response::redirect($redirectURL);
 }
Exemplo n.º 21
0
 /**
  * Upload all infotab images to local directory defined in $this->image_upload_config
  * 
  * @param $content_type 	= Content type to pull config from (Image, Video)
  * 
  */
 public function upload_infotab_image($content_type = 'image')
 {
     $return['is_valid'] = true;
     $return['exists'] = false;
     $return['errors'] = false;
     // Check if there are selected files
     foreach (\Input::file() as $file) {
         if ($file['name'] != '') {
             $return['exists'] = true;
         }
     }
     // No files selected, so no errors too
     if (!$return['exists']) {
         return $return;
     }
     // Image upload configuration
     $this->infotab_image_upload_config = array('path' => \Config::get('infotab.' . $content_type . '.location.root'), 'normalize' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'));
     \Upload::process($this->infotab_image_upload_config);
     // if there are any valid files
     if (\Upload::is_valid()) {
         // Save image
         \Upload::save();
         $this->_infotab_image_data = \Upload::get_files();
         // Resize images to desired dimensions defined in config file
         try {
             foreach ($this->_infotab_image_data as $image_data) {
                 $image = \Image::forge(array('presets' => \Config::get('infotab.' . $content_type . '.resize', array())));
                 $image->load($image_data['saved_to'] . $image_data['saved_as']);
                 foreach (\Config::get('infotab.' . $content_type . '.resize', array()) as $preset => $options) {
                     $image->preset($preset);
                 }
             }
             return $return;
         } catch (\Exception $e) {
             $return['is_valid'] = false;
             $return['errors'][] = $e->getMessage();
         }
     } else {
         // IMAGE ERRORS
         if (\Upload::get_errors() !== array()) {
             foreach (\Upload::get_errors() as $file) {
                 foreach ($file['errors'] as $key => $value) {
                     $return['is_valid'] = false;
                     $return['errors'][] = $value['message'];
                 }
             }
         }
     }
     // If we got up to here, image is not uploaded
     return $return;
 }
Exemplo n.º 22
0
 /**
  * Edit article
  *
  * @param int $id article-ID
  *
  * @author Nguyen Van Hiep
  * @access public
  *
  * @version 1.0
  * @since 1.0
  */
 public function action_edit($id = null, $current_cat_view = '', $current_lang_view = '')
 {
     $a = Model_Article::find($id);
     if (!$a) {
         Session::set_flash('error', __('message.art_not_exists'));
         Response::redirect('admin/article');
     }
     $view = View::forge('admin/article/edit');
     $view->a = $a;
     $view->err = array();
     $view->sel_cats = Model_ArtCat::get_cat_from_art($id);
     $view->langs = $this->langs;
     $view->cats = Model_Categories::get_cat_list();
     if ($current_cat_view != 'cat' and $current_lang_view != 'lang') {
         $view->current_cat_view = "cat={$current_cat_view}&lang={$current_lang_view}";
     } elseif ($current_cat_view != 'cat') {
         $view->current_cat_view = "cat={$current_cat_view}&lang=";
     } elseif ($current_lang_view != 'lang') {
         $view->current_cat_view = "cat=&lang={$current_lang_view}";
     } else {
         $view->current_cat_view = "cat=&lang=";
     }
     if (Input::method() == 'POST') {
         if (count(Input::file()) == 0) {
             Session::set_flash('error', __('message.upload_files_error'));
             Response::redirect('admin/articLe/edit');
         }
         $a->title = Input::post('title');
         $a->slug = Input::post('slug');
         $a->title_search = str_replace('-', ' ', Input::post('slug'));
         $a->desc = Input::post('desc');
         $a->content = Input::post('content');
         $content_search = strip_tags(Input::post('content'));
         $a->content_search = preg_replace('/[\\s]+/mu', ' ', $content_search);
         // remove all tab, new line
         $content_no_mark = Input::vn_str_filter(strip_tags(Input::post('content')));
         $a->content_search_no_mark = preg_replace('/[\\s]+/mu', ' ', $content_no_mark);
         $a->lang = Input::post('lang');
         $a->updated_at = date('Y-m-d h:i:s', time());
         $val = Model_Article::validate('edit', $a);
         Upload::process($this->config);
         $upload_errs = Upload::get_errors();
         $up_err = reset($upload_errs);
         $input_file = Input::file();
         $upthumb = $input_file['thumbnail']['name'];
         $is_upthumb = true;
         // Check if upload new thumbnail or not
         if ($up_err['field'] == 'thumbnail' and strlen($upthumb) == 0) {
             $upload_errs = array();
             $is_upthumb = false;
         }
         if ($val->run() and count($upload_errs) == 0) {
             //save account
             if ($a->save()) {
                 // Save Article-Category
                 Model_ArtCat::save_art_cat($a->id, Input::post('cat') ? Input::post('cat') : array(), true);
                 //Save images
                 $this->save_thumb($a->id, $is_upthumb);
                 //redirect to index page
                 Session::set_flash('success', __('message.art_edited'));
                 Response::redirect("admin/article?{$view->current_cat_view}");
             } else {
                 //fail in transaction
                 Session::set_flash('error', __('message.registration_failed'));
             }
         } else {
             $view->err = $val->error_message();
             $err = $this->upload_errors($upload_errs);
             $view->err = array_merge($view->err, $err);
         }
     }
     $this->template->title = __('prod.edit');
     $this->template->content = $view;
 }
Exemplo n.º 23
0
 private function validate()
 {
     if (!Upload::is_valid()) {
         $errors = Upload::get_errors();
         if (!empty($errors[0]['errors'][0]['message'])) {
             throw new FuelException($errors[0]['errors'][0]['message']);
         }
     }
     if (count(Upload::get_files()) > 1) {
         throw new FuelException('File upload error.');
     }
 }
Exemplo n.º 24
0
 public function action_add()
 {
     $id = Input::get("id", 0);
     $user = Model_User::find($id);
     //add or edit
     if (Input::post("firstname", null) != null and Security::check_token()) {
         if ($user == null) {
             $email = Input::post("email", null);
             $password = Input::post("password", null);
             try {
                 Auth::create_user($email, $password, $email, 1);
                 $user = Model_User::find("first", ["where" => [["email" => $email]]]);
             } catch (Exception $e) {
                 $data["error"] = "This email is already in use.";
             }
         } else {
             $email = Input::post("email", null);
             if ($email != $user->email) {
                 $check_user = Model_User::find("first", ["where" => [["email" => $email]]]);
                 if ($check_user == null) {
                     $user->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);
             $user->img_path = $file_name;
         } else {
             $error = Upload::get_errors();
         }
         if (!isset($data["error"])) {
             $user->firstname = Input::post("firstname", "");
             $user->middlename = Input::post("middlename", "");
             $user->lastname = Input::post("lastname", "");
             $user->google_account = Input::post("google_account", "");
             $user->sex = Input::post("sex", 0);
             $user->need_reservation_email = Input::post("need_reservation_email", 1);
             $user->need_news_email = Input::post("need_news_email", 1);
             $user->birthday = Input::post("year", 0) . "-" . Input::post("month", 0) . "-" . Input::post("day", 0);
             $user->timezone = Input::post("timezone", "");
             $user->place = Input::post("place", "");
             $user->save();
             Response::redirect("/admin/students");
         }
     }
     if ($user == null) {
         $user = Model_User::forge();
     }
     $data["user"] = $user;
     $view = View::forge("admin/students/add", $data);
     $this->template->content = $view;
 }