/** * @param array $params * @param array $files * @return array */ public function run($params = array(), $files = array()) { // Siga esse modelo para retornar erros $error = array("error" => false, "errorInfo" => "", "errorDesc" => "", "errorFields" => array()); // Roda validação de campos simples foreach ($this->postRules as $field => $rule) { $data = array(); $data[$field] = $rule; $validated = \GUMP::is_valid($params, $data); if ($validated !== true) { $error['errorFields'][] = $field; } } foreach ($this->fileRules as $field => $rule) { if (isset($files[$field]['name']) && !empty($files[$field]['name'])) { $storage = new FileSystem('public/uploads', BASEPATH); $file = new File($field, $storage); $file->setName(uniqid()); $file->addValidations(array(new \Upload\Validation\Extension($rule['extension']), new \Upload\Validation\Size($rule['size']))); $name = $file->getNameWithExtension(); try { $file->upload(); $params[$field] = $name; } catch (\Exception $e) { $error['errorFields'][] = $field; } } else { if (!isset($params[$field]) || empty($params[$field])) { $error['errorFields'][] = $field; } } } if (!empty($error['errorFields'])) { $error['error'] = true; $error['errorInfo'] = "Erro ao salvar registro."; $error['errorDesc'] = "Preencha todos os campos corretamente"; return array_merge_recursive($error, $params); } else { // Roda os tratamentos return $this->treatment($params, $files); } }
/** * Редактирование */ public function anyEdit() { $id = (int) $this->getRequestParam('id') ?: null; $model = PlayerModel::find($id); $firstNameModel = $model->firstNameModel()->first(); $lastNameModel = $model->lastNameModel()->first(); if (empty($model)) { throw new HttpException(404, json_encode(['errorMessage' => 'Incorrect Player'])); } if (Arr::get($this->getPostData(), 'submit') !== null) { $data = Arr::extract($this->getPostData(), ['slug', 'image', 'country', 'position', 'status', 'number', 'team', 'first_name', 'last_name', 'content']); // Транзакция для Записание данных в базу try { Capsule::connection()->transaction(function () use($data, $model, $firstNameModel, $lastNameModel) { // Загрузка картинки $file = new UploadFile('image', new FileSystem('uploads/images')); // Optionally you can rename the file on upload $file->setName(uniqid()); // // Validate file upload // $file->addValidations(array( // // Ensure file is of type image // new UploadMimeType(['image/png','image/jpg','image/gif']), // // // Ensure file is no larger than 5M (use "B", "K", M", or "G") // new UploadSize('50M') // )); // Try to upload file try { // Success! $file->upload(); $image = '/' . static::IMAGE_PATH . '/' . $file->getNameWithExtension(); } catch (UploadException $e) { // Fail! $image = null; Message::instance()->warning($file->getErrors()); } catch (Exception $e) { // Fail! $image = null; Message::instance()->warning($file->getErrors()); } $firstNameModel->updateOrCreate(['id' => $firstNameModel->id], ['text' => $data['first_name']]); $lastNameModel->updateOrCreate(['id' => $lastNameModel->id], ['text' => $data['last_name']]); foreach ($data['content'] as $iso => $d) { $lang_id = Lang::instance()->getLang($iso)['id']; EntityTranslationModel::updateOrCreate(['id' => $d['first_name_id']], ['text' => $d['first_name'], 'lang_id' => $lang_id, 'entity_id' => $firstNameModel->id]); EntityTranslationModel::updateOrCreate(['id' => $d['last_name_id']], ['text' => $d['last_name'], 'lang_id' => $lang_id, 'entity_id' => $lastNameModel->id]); } Event::fire('Admin.entitiesUpdate'); // если нету нового изображения оставить прежний if ($image) { $imageId = PhotoModel::create(['path' => $image, 'is_bound' => 1])->id; $model->update(['image_id' => $imageId]); } $model->update(['team_id' => $data['team'], 'slug' => $data['slug'], 'number' => $data['number'], 'status' => $data['status'], 'country_id' => $data['country'], 'position_id' => $data['position'], 'first_name_id' => $firstNameModel->id, 'last_name_id' => $lastNameModel->id]); }); Message::instance()->success('Player was successfully saved'); } catch (Exception $e) { Message::instance()->warning('Player was don\'t saved'); } } $model = PlayerModel::find($id); $firstNameModel = $model->firstNameModel()->first(); $lastNameModel = $model->lastNameModel()->first(); // Загрузка контента для каждово языка $contents = []; foreach (Lang::instance()->getLangsExcept(Lang::DEFAULT_LANGUAGE) as $iso => $lang) { $contents[$iso]['firstName'] = $firstNameModel->translations()->whereLang_id($lang['id'])->first(); $contents[$iso]['lastName'] = $lastNameModel->translations()->whereLang_id($lang['id'])->first(); } //echo "<pre>"; //print_r($contents); //die; $this->layout->content = View::make('back/players/edit')->with('item', $model)->with('contents', $contents); }
/** * @param Application $app * @param Request $request * @return Response */ public function fileUploadAction(Application $app, Request $request) { $uploadDir = __DIR__ . '/../../../web' . $app['config']['upload_dir']; $file = new File('file', new FileSystem($uploadDir)); $file->addValidations(array(new Mimetype(array('image/png', 'image/gif', 'image/jpeg')), new Size('5M'))); // Upload file to server try { $file->setName($app['slug']->slugify($file->getName())); $file->upload(); $app['monolog']->addDebug(sprintf("File uploaded: %s", json_encode($file->getNameWithExtension()))); } catch (\Exception $exception) { $errorMessage = join('<br />', $file->getErrors()); $app['monolog']->addError(sprintf("Error during file upload: %s", $errorMessage)); return new Response(sprintf("Erreur : %s", $errorMessage), 400); } // Save file to db try { $photo = $app['photos']->add($file->getNameWithExtension()); } catch (\Exception $exception) { $app['monolog']->addError(sprintf("Error during file insertion: %s", $exception->getMessage())); // Remove file from upload dir unlink($uploadDir . $file->getNameWithExtension()); return new Response(sprintf("Erreur : %s", $exception->getMessage()), 400); } // Generate thumbnails $app['photos']->generateThumbnails($photo); return new Response($photo->id); }
/** * Main media upload API */ protected function postMedia($mediaType = 'user', $item_id = 0) { // Get corresponding item switch ($mediaType) { case 'message': $item = Alert::find($item_id); $allowedTypes = array('alert_picture'); break; case 'user': $item = User::find($item_id); $allowedTypes = array('profile_picture', 'cover_picture'); break; case 'brand': $item = Brand::find($item_id); $allowedTypes = array('logo_picture', 'cover_picture'); break; default: throw new Exception('Invalid media type:' . $mediaType); break; } if (!$item) { App::abort(404); } // Gathering and validate upload information $uploadFiles = Input::file(); $uploadType = key($uploadFiles); if (!Input::hasFile($uploadType)) { array_shift($uploadFiles); $uploadType = key($uploadFiles); } if (!in_array($uploadType, $allowedTypes)) { return Redirect::back()->with('warning', 'Invalid upload name : ' . $uploadType); } // Early mime validation $validType = false; if ($mime = Input::file($uploadType)->getMimetype()) { $validType = strpos($mime, 'image') === 0; } if (!$validType) { return Redirect::back()->with('warning', 'Invalid mime type : ' . $mime); } // Prepare uploader $fs = new Filesystem(); $storage = new UploadFileSystem($this->media_directory); $file = new UploadFile($uploadType, $storage); // Set to item's media slug $mediaName = $uploadType . '_' . $mediaType . '_' . $item->id; $file->setName($mediaName); // Validate file upload // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml $file->addValidations(array(new UploadMimetype($mime), new UploadSize('5M'))); // Access data about the file that has been uploaded $data = array('path' => $this->media_directory . '/' . $file->getNameWithExtension(), 'name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions()); // Try to upload file try { // If it already there, remove if ($fs->exists($data['path'])) { $fs->delete($data['path']); } $file->upload(); chmod($data['path'], 0777); //why not 0644 or 0664 $attachment = Attachment::create(array('mime' => $data['mime'], 'path' => $data['path'], 'url' => URL::to('/media/' . $mediaType . '/' . $uploadType . '/' . $item->id))); foreach ($item->attachments as $previousAttachment) { if ($previousAttachment->pivot->type == $uploadType) { $item->attachments()->detach($previousAttachment->id); } } $item->attachments()->save($attachment, array('type' => $uploadType)); return Redirect::back(); } catch (Exception $e) { // Fail! $error = $file->getErrors(); return Redirect::back()->with('warning', current($error)); } }