public function product_imagePostAdd(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $files = $req->getUploadedFiles();
     foreach ($files["image"] as $file) {
         $name = $file->getClientFilename();
         $name = explode(".", $name);
         $ext = array_pop($name);
         $ext = strtolower($ext);
         if (!in_array($ext, ["jpeg", "jpg", "png"])) {
             continue;
         }
         $name = $this->genToken(12) . "." . $ext;
         $insertParams = [];
         $insertParams["product_id"] = $attr["product_id"];
         $insertParams["type"] = "image";
         $insertParams["image_path"] = $name;
         $insertParams["sort_order"] = $db->max("product_media", "sort_order", ["AND" => ["product_id" => $attr["product_id"]]]) + 1;
         if (!$db->insert("product_media", $insertParams)) {
             return $res->withStatus(500)->withHeader('Content-Type', 'application/json')->write(json_encode(["error" => true]));
         }
         $file->moveTo("../product_media/" . $name);
     }
     return $res->withStatus(200)->withHeader('Content-Type', 'application/json')->write(json_encode(["success" => true]));
 }
Example #2
0
 public function actionCreate(Request $request)
 {
     if ($request->isXhr()) {
         $model = Unit::find($request->getAttribute('id'));
         return $this->renderAjax('image/ajax/modal', ['model' => $model]);
     }
     $this->uploadFiles($request->getUploadedFiles(), $request->getParams(), $request->getAttribute('id'));
     return $this->goBack();
 }
Example #3
0
 public function updateProfileImage(Request $request, Response $response, array $args)
 {
     /* Directory to move the file to once processed */
     $destination = __DIR__ . "../../../../../images/";
     /* The uploaded file */
     /** @var $file UploadedFile */
     $file = $request->getUploadedFiles()['image'];
     /* If there is an error in the file, stop upload */
     if ($file->getError() != UPLOAD_ERR_OK) {
         return "Upload failed";
     }
     $currentLocation = $file->file;
     /* If the file is not a jpg, png, or gif, stop upload */
     $finfo = new \finfo(FILEINFO_MIME_TYPE);
     if (false === ($ext = array_search($finfo->file($currentLocation), array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'), true))) {
         return "Invalid File Format. Only .jpg, .gif, and .png accepted.";
     }
     $size = getimagesize($currentLocation);
     /* If the file is greater than 2MB in size, stop upload. */
     if ($size > 1024 * 1024 * 2) {
         return "Upload failed. Image is greater than 2MB.";
     }
     $givenName = $file->getClientFilename();
     /* Generate a unique name for this file from its SHA1 hash. */
     $fileHashName = sha1_file($currentLocation);
     /* Build the full path and extension of the file */
     $fullFilePath = $destination . $fileHashName . $ext;
     /* Replace uploaded file with recreated image and save */
     switch ($ext) {
         case 'jpg':
             $image = imagecreatefromjpeg($currentLocation);
             imagejpeg($image, $fullFilePath);
             break;
         case 'gif':
             $image = imagecreatefromgif($currentLocation);
             imagegif($image, $fullFilePath);
             break;
         case 'png':
             $image = imagecreatefrompng($currentLocation);
             imagealphablending($image, true);
             imagesavealpha($image, true);
             imagepng($image, $fullFilePath);
             break;
     }
     /* Remove original upload */
     unlink($currentLocation);
     /* Get user from route args */
     $user = $args['user'];
     /* Make change in Database */
     if ($this->dbService->updateUserImage($user['username'], $fullFilePath, $givenName, $size)) {
         return "Upload successful";
     } else {
         return "Upload failed";
     }
 }
 public function productPostEdit(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $postBody = $req->getParsedBody();
     $files = $req->getUploadedFiles();
     $editParams = $this->adapterParams($postBody, $files);
     if ($db->update("product", $editParams, ["id" => $attr["id"]]) !== false) {
         return $res->withHeader("Location", $req->getUri()->getBasePath() . "/product");
     }
     return $container->view->render($res, "product/form.twig", ["form" => $postBody]);
 }
 public function edit(Request $request, Response $response, array $args)
 {
     /** @var Users $users */
     $users = $this->data(Users::class);
     $user = $users->get(['email', 'username'], $this->session->get('user_id'))->fetch();
     $identityTypes = ['ktp' => 'KTP', 'sim' => 'SIM', 'ktm' => 'Kartu Mahasiswa'];
     $validator = $this->validator->rule('required', ['email', 'username', 'fullname', 'province_id', 'city_id', 'area', 'job_id']);
     $validator->addRule('assertEmailNotExists', function ($field, $value, array $params) use($users, $user) {
         return $user['email'] == $value || !$users->assertEmailExists($value);
     }, 'tersebut sudah terdaftar!');
     $validator->addRule('assertUsernameNotExists', function ($field, $value, array $params) use($users, $user) {
         return $user['username'] == $value || !$users->assertUsernameExists($value);
     }, 'tersebut sudah terdaftar!');
     $validator->rules(['regex' => [['fullname', ':^[A-z\\s]+$:'], ['username', ':^[A-z\\d\\-\\.\\_]+$:'], ['contact_phone', ':^[-\\+\\d]+$:'], ['identity_number', ':^[-\\+\\d]+$:']], 'email' => 'email', 'assertEmailNotExists' => 'email', 'assertUsernameNotExists' => 'username', 'dateFormat' => [['birth_date', 'Y-m-d']], 'equals' => [['repassword', 'password']], 'in' => [['identity_type', array_keys($identityTypes)]], 'lengthMax' => [['fullname', 32], ['username', 64], ['contact_phone', 16], ['area', 64], ['identity_number', 32], ['birth_place', 32]], 'lengthMin' => [['username', 6], ['password', 6]]]);
     if ($validator->validate()) {
         $input = $request->getParsedBody();
         /** @var MemberProfile $profile */
         $profile = $this->data(MemberProfile::class);
         /** @var MemberSocmeds $socmeds */
         $socmeds = $this->data(MemberSocmeds::class);
         $memberProfile = ['fullname' => $input['fullname'], 'contact_phone' => $input['contact_phone'], 'birth_place' => strtoupper($input['birth_place']), 'birth_date' => $input['birth_date'], 'identity_number' => $input['identity_number'], 'identity_type' => $input['identity_type'], 'religion_id' => $input['religion_id'], 'province_id' => $input['province_id'], 'city_id' => $input['city_id'], 'area' => $input['area'], 'job_id' => $input['job_id']];
         $this->db->beginTransaction();
         try {
             $userId = $this->session->get('user_id');
             if ($photo = $request->getUploadedFiles()['photo']) {
                 $memberProfile = $this->upload($photo, $memberProfile);
             }
             // Update profile data record
             $profile->update($memberProfile, ['user_id' => $userId]);
             $users->update(['email' => $input['email'], 'province_id' => $input['province_id'], 'city_id' => $input['city_id'], 'area' => $input['area']], ['user_id' => $userId]);
             // Handle social medias
             if ($input['socmeds']) {
                 $terms = ['user_id' => $userId, 'deleted' => 'N'];
                 foreach ($input['socmeds'] as $item) {
                     $terms = ['user_id' => $userId, 'deleted' => 'N', 'socmed_type' => $item['socmed_type']];
                     $socmedRow = $socmeds->get(['account_name', 'account_url'], $terms)->fetch();
                     if ($socmedRow['account_name'] != $item['account_name']) {
                         $socmedRow['account_name'] = $item['account_name'];
                     }
                     if ($socmedRow['account_url'] != $item['account_url']) {
                         $socmedRow['account_url'] = $item['account_url'];
                     }
                     $socmeds->update($socmedRow, $terms);
                 }
             }
             if (isset($input['socmeds_delete'])) {
                 foreach ($input['socmeds_delete'] as $item) {
                     $socmeds->delete(['user_id' => $userId, 'socmed_type' => $item]);
                 }
             }
             $this->db->commit();
             $this->addFormAlert('success', 'Profile information successfuly updated! Congratulation!');
         } catch (\PDOException $e) {
             $this->db->rollback();
             $this->addFormAlert('error', 'System failed<br>' . $e->getMessage());
         } catch (\Exception $e) {
             $this->db->rollback();
             $this->addFormAlert('error', 'System failed<br>' . $e->getMessage());
         }
     } else {
         $this->addFormAlert('warning', 'Some of mandatory fields is empty!', $validator->errors());
         return $response->withRedirect($this->router->pathFor('membership-account-edit', $args));
     }
     return $response->withRedirect($this->router->pathFor('membership-account'));
 }
Example #6
0
 private function submitAddAlbum(Request $request, Response $response)
 {
     /* @var \App\models\Album $album */
     $album = $this->model->load('Album');
     $newAlbum = ['user_id' => $this->user['id'], 'name' => $request->getParsedBody()['name'], 'description' => $request->getParsedBody()['description'], 'is_public' => $request->getParsedBody()['is_public']];
     $albumId = $album->insert($newAlbum);
     list($year, $month) = explode('-', date('Y-m'));
     // Create archive
     /* @var \App\models\Archive $archive */
     $archive = $this->model->load('Archive');
     $archive->create(Photo::ARCHIVE_CLASSES, $year, $month, $this->user['id']);
     /* @var \Slim\Http\UploadedFile $uploadedFile */
     $uploadedFile = $request->getUploadedFiles()['cover'];
     $fileInfo = ['name' => $uploadedFile->getClientFilename(), 'fullName' => $uploadedFile->getClientFilename()];
     /* @var \App\models\Photo $photo */
     $photo = $this->model->load('Photo');
     if ($pathInfo = $photo->getPathInfo($this->user['id'], $year, $month, $fileInfo)) {
         try {
             $uploadedFile->moveTo($pathInfo['moveTo']);
         } catch (\Exception $e) {
             $this->logger->info($e->getMessage());
             $this->flash->addError('admin_index', 'Uploaded fail.');
             return $response->withStatus(302)->withHeader('Location ', $this->router->pathFor('admin_index'));
         }
         if ($photoId = $photo->save($this->user['id'], $pathInfo, $request->getParsedBody()['description'], $request->getParsedBody()['is_public'], $albumId)) {
             $album->filter(['id' => $albumId])->update(['cover' => $photoId]);
             $this->flash->addSuccess('admin_index', 'Photo uploaded success.');
         } else {
             $this->flash->addError('admin_index', 'Photo uploaded falil.');
         }
     } else {
         $this->logger->error('Fail to initial path.');
         $this->flash->addError('admin_index', 'Uploaded fail.');
     }
     $comeFrom = ['action' => $request->getParsedBody()['photoAction'], 'photoId' => $request->getParsedBody()['photoId']];
     if ($comeFrom['action'] && $comeFrom['photoId']) {
         $queryParams = ['id' => $comeFrom['photoId']];
         return $response->withStatus(302)->withHeader('Location ', $this->router->pathFor('photo_action', ['action' => $comeFrom['action']], $queryParams));
     } else {
         return $response->withStatus(302)->withHeader('Location ', $this->router->pathFor('admin_index'));
     }
 }