示例#1
0
 /**
  * Upload user avatar
  *
  * @param Request $request
  * @return mixed
  */
 public function avatar(Request $request)
 {
     $this->authenticated_only();
     // Avatar uploading settings
     $upload_to = ROOT . S . 'static' . S . 'user' . S . $this->user->id;
     $static_url = '/static/user/' . $this->user->id . '/';
     $allowed_formats = ['png', 'jpeg', 'jpg'];
     $max_size = 1;
     // MB
     $naming_handler = function ($filename, $ext) {
         return 'avatar.' . $ext;
     };
     $image_max = ['w' => 512, 'h' => 512];
     // Delete avatar
     if ($request->get('delete')) {
         if (file_exists(ROOT . $this->user->avatar)) {
             @unlink(ROOT . $this->user->avatar);
             $this->user->avatar = '';
             $this->user->save();
             return static::redirect_response($this->map->reverse('user.avatar'));
         }
     }
     // Uploadint avatar
     if ($request->isMethod('post')) {
         // Configure uploader
         $fileuploader = new FileUploader(['avatar'], $allowed_formats, $max_size);
         $fileuploader->set_naming_handler($naming_handler);
         $fileuploader->replace_mode(true);
         // Upload file
         $status = $fileuploader->upload($upload_to, 1)['avatar'];
         // Change user
         $old_file = $this->user->avatar;
         $this->user->avatar = $static_url . $fileuploader->get_name('avatar');
         // Response
         if ($fileuploader->is_uploaded('avatar') && $this->user->save() && $fileuploader->resize('avatar', $image_max['w'], $image_max['h'])) {
             if (file_exists(ROOT . $old_file) && $old_file != $this->user->avatar) {
                 @unlink(ROOT . $old_file);
             }
             $this->view->assign('user', $this->user->to_array());
             $this->view->assign('message', $this->lang->translate('form.saved'));
         } else {
             $this->view->assign('error', $this->lang->translate('form.file.' . $status[0], $status[1]));
         }
     } else {
         $this->view->assign('message', $this->lang->translate('form.file.extension', implode(', ', $allowed_formats)));
     }
     return $this->view->render('user/avatar.twig', ['title' => $this->lang->translate('user.profile.avatar_upload'), 'max_size' => $max_size, 'formats' => implode(', ', $allowed_formats)]);
 }