public function saveImages($filearray, $controllername, $uid)
 {
     $time = time();
     $saveFilename = '';
     foreach ($filearray as $file) {
         $nameArray = explode('.', $file->getName());
         $filetype = $nameArray[count($nameArray) - 1];
         $tmpFile = '../app/cache/tmp/' . $time . '_' . $file->getName();
         $file->moveTo($tmpFile);
         $thumbFilenameS = '../public/media/' . $controllername . '_' . $uid . '_S.' . $filetype;
         $thumbFilenameL = '../public/media/' . $controllername . '_' . $uid . '_L.' . $filetype;
         $saveFilename = 'public/media/' . $controllername . '_' . $uid . '_L.' . $filetype;
         $imageS = new GDAdapter($tmpFile);
         $imageS->resize(300, 1000);
         $imageS->save($thumbFilenameS);
         $imageL = new GDAdapter($tmpFile);
         $imageL->resize(600, 1000);
         $imageL->save($thumbFilenameL);
         unlink($tmpFile);
     }
     return $saveFilename;
 }
Example #2
0
 public function zipAction($product_id = null, $flip = null)
 {
     $this->view->disable();
     // Create tmp directory if it doesn't exist
     if (!file_exists(ROOT . "/public/tmp")) {
         mkdir(ROOT . "/public/tmp", 0777);
     }
     $random = rand(111111, 999999);
     $zip_name = "tmp/{$product_id}_{$random}.zip";
     $zip = new ZipArchive();
     $zip->open($zip_name, ZIPARCHIVE::CREATE);
     //        $zip->open($zip_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
     $photos = PProdPhoto::find(["product_id = {$product_id}", 'order' => 'ordered ASC']);
     $num = 1;
     $list_of_photos = [];
     foreach ($photos as $photo) {
         $img_name = "{$product_id}_{$num}";
         $jpg_name = "tmp/{$img_name}.{$photo->ext}";
         $img_dest = ROOT . "/public/tmp/{$random}_{$random}.{$photo->ext}";
         // Copy img to disk
         copy("http://madeheart.com/media/productphoto/{$photo->folder}{$photo->uri}.{$photo->ext}", $img_dest);
         $image_flip = new GD($img_dest);
         if ($flip == 'mirror') {
             $image_flip->flip(2);
         }
         $image_flip->save($jpg_name);
         // Delete temp file
         unlink($img_dest);
         $zip->addFile($jpg_name, basename($jpg_name));
         $list_of_photos[] = $jpg_name;
         $num++;
     }
     $zip->close();
     // Delete all jpg files in tmp folder
     foreach ($list_of_photos as $p) {
         unlink(ROOT . "/public/{$p}");
     }
     //        array_map('unlink', glob(ROOT."/public/tmp/*.jpg"));
     header('Content-Type: application/zip');
     header('Content-Length: ' . filesize($zip_name));
     header('Content-Disposition: attachment; filename="' . $product_id . '_' . $random . '.zip"');
     readfile($zip_name);
     // Delete zip file
     unlink(ROOT . "/public/{$zip_name}");
 }
Example #3
0
 /**
  * Start Import Product Queue action.
  *
  * @return void
  */
 public function importAction($param1 = null, $param2 = null)
 {
     $redis = new \Redis();
     $redis->connect('127.0.0.1', 6379);
     $queue = $this->getDI()->get('queue');
     $queue->watch('haraapp.import');
     $config = $this->getDI()->get('config');
     $filefive = $this->getDI()->get('filefive');
     while ($job = $queue->reserve()) {
         $message = $job->getBody();
         $data = $message[0];
         // Get offline product data from mysql db
         $myProductQueue = ProductQueue::findFirst(['pid = :haravanProductId: AND status = :status: AND sid = :storeId:', 'bind' => ['haravanProductId' => $data['haravanProductId'], 'status' => ProductQueue::STATUS_QUEUE, 'storeId' => $data['storeId']]]);
         if ($myProductQueue) {
             $pass = false;
             $myStore = Store::findFirstById($data['storeId']);
             // get content, image and import to five.vn db
             $product = json_decode($myProductQueue->pdata);
             $cleanData = strip_tags($product->body_html);
             // insert table ADS
             $myAds = new Ads();
             $myAds->assign(['uid' => $myStore->uid, 'udid' => "", 'rid' => $product->id, 'cid' => $myProductQueue->fcid, 'title' => $product->title, 'slug' => Utils::slug($product->title), 'description' => $cleanData, 'price' => $product->variants[0]->price, 'instock' => 1, 'cityid' => 0, 'districtid' => 0, 'status' => 1, 'isdeleted' => 0, 'seokeyword' => $product->tags, 'lastpostdate' => time()]);
             if ($myAds->create()) {
                 $pass = true;
                 if (isset($product->images)) {
                     // Insert table IMAGES
                     foreach ($product->images as $img) {
                         $response = \Requests::get($img->src);
                         if ($response->status_code == 200) {
                             // Download image to local
                             $filePart = explode('.', $img->filename);
                             $namePart = $filePart[0];
                             $extPart = $filePart[1];
                             $path = rtrim($config->global->product->directory, '/\\') . '/' . date('Y') . '/' . date('m') . DIRECTORY_SEPARATOR;
                             $fullPath = $config->global->staticFive . $path;
                             $uploadOK = $filefive->put($path . $namePart . '.' . $extPart, (string) $response->body);
                             // Resise image
                             $myResize = new PhImage($fullPath . $namePart . '.' . $extPart);
                             $orig_width = $myResize->getWidth();
                             $orig_height = $myResize->getHeight();
                             $height = $orig_height * 1200 / $orig_width;
                             $mediumHeight = $orig_height * 600 / $orig_width;
                             $smallHeight = $orig_height * 200 / $orig_width;
                             $myResize->resize(1200, $height)->crop(1200, $height)->save($fullPath . $namePart . '.' . $extPart);
                             $myResize->resize(600, $mediumHeight)->crop(600, $mediumHeight)->save($fullPath . $namePart . '-medium' . '.' . $extPart);
                             $myResize->resize(200, $smallHeight)->crop(200, $smallHeight)->save($fullPath . $namePart . '-small' . '.' . $extPart);
                             if ($uploadOK) {
                                 // Save to db
                                 $myImage = new Images();
                                 $myImage->assign(['aid' => $myAds->id, 'name' => $myAds->title, 'path' => $path . $namePart . '.' . $extPart, 'status' => Images::STATUS_ENABLE, 'orderNo' => $img->position]);
                                 if ($myImage->save()) {
                                     // Update first image to ads table
                                     if ($img->position == 1) {
                                         $myAds->image = $path . $namePart . '.' . $extPart;
                                         $myAds->update();
                                     }
                                 } else {
                                     echo "cannot save image!";
                                 }
                             } else {
                                 echo "cannot download image!";
                             }
                         } else {
                             echo "cannot get image url!";
                         }
                     }
                 }
                 $imageName = strlen($myAds->image) > 0 ? $myAds->image : "";
                 // Save to product_map table
                 $myProduct = new ProductMap();
                 $myProduct->assign(['sid' => $myStore->id, 'uid' => $myStore->uid, 'hid' => $data['haravanProductId'], 'aid' => $myAds->id, 'cid' => $myAds->cid, 'title' => $myAds->title, 'price' => $myAds->price, 'image' => $imageName, 'slug' => $myAds->slug, 'status' => $myAds->status]);
                 $myProduct->create();
                 // Delete queued data. (Production)
                 // $myProductQueue->delete();
             } else {
                 $pass = false;
             }
             if ($pass) {
                 $myProductLog = new ProductLog();
                 $myProductLog->assign(['sid' => $myStore->id, 'message' => 'Ads name ' . $myAds->title . ' has been created!', 'type' => ProductLog::TYPE_IMPORT, 'status' => ProductLog::STATUS_COMPLETED, 'class' => 'succcess']);
                 $myProductLog->create();
                 // update okie
                 $myCategoryMap = CategoryMap::findFirst(['hid = :haravanId: AND fid = :fid: AND sid = :storeId:', 'bind' => ['haravanId' => $data['haravanId'], 'fid' => $myProductQueue->fcid, 'storeId' => $data['storeId']]]);
                 $myCategoryMap->totalItemSync++;
                 $myCategoryMap->totalItemQueue--;
                 $myCategoryMap->update();
                 // generate total process, when import a product success
                 $totalItem = CategoryMap::sum(['column' => 'totalItem', 'conditions' => 'hid = ' . $data['haravanId'] . ' AND sid = ' . $data['storeId']]);
                 $totalItemSync = CategoryMap::sum(['column' => 'totalItemSync', 'conditions' => 'hid = ' . $data['haravanId'] . ' AND sid = ' . $data['storeId']]);
                 $process = $totalItemSync * 100 / $totalItem;
                 // Push process
                 $meta = ['shopName' => $myStore->name, 'record' => $process];
                 $redis->publish('notification', json_encode($meta));
                 // send message.
                 // When process all products in category map, update store mapped to OK
                 if ($process == 100) {
                     $myStore->mapped = Store::MAPPED;
                     $myStore->update();
                     $myProductLog = ProductLog::findFirst('status = ' . ProductLog::STATUS_CURRENT_PROCESSING . ' AND type = ' . ProductLog::TYPE_IMPORT . ' AND sid = ' . $myStore->id);
                     $myProductLog->status = ProductLog::STATUS_COMPLETED;
                     $myProductLog->update();
                 }
             }
         }
         $job->delete();
     }
 }
 public function addofferformAction()
 {
     $this->view->disable();
     function valid_form_offer()
     {
         $sub_mess = '';
         if (!isset($_POST['model']) || strlen($_POST['model']) < 3) {
             $sub_mess['model'] = 'Не корректно заполнено поле Модель:';
         }
         if (!isset($_POST['cat_id'])) {
             $sub_mess['cat_id'] = 'Не корректно заполнено поле Класс:';
         }
         if (!isset($_POST['city']) || strlen($_POST['city']) < 3) {
             $sub_mess['city'] = 'Не корректно заполнено поле Город:';
         }
         if (!isset($_POST['price']) || strlen($_POST['price']) < 2) {
             $sub_mess['price'] = 'Не корректно заполнено поле Цена:';
         }
         if (!isset($_POST['text_offer']) || strlen($_POST['text_offer']) < 5) {
             $sub_mess['text_offer'] = 'Не корректно заполнено поле Характеристики техники: ';
         }
         if (is_array($sub_mess)) {
             echo json_encode($sub_mess);
             return false;
         } else {
             return true;
         }
     }
     if (valid_form_offer()) {
         //// Обработчик формы предложения
         $user_id = $this->session->get('user_id');
         $cat_id = $this->session->get('cat_id');
         $el = new Elements();
         $el->dir_valid($user_id);
         if ($this->request->hasPost('offer_id')) {
             $offer = Offers::findFirst($this->request->getPost('offer_id'));
         } else {
             $offer = new Offers();
         }
         $offer->name = $this->request->getPost('model');
         $md = new Model();
         $md->name = $this->request->getPost('model');
         $this->modelsCache->delete("md");
         $md->save();
         $offer->user_id = $user_id;
         if ($this->request->hasPost('sub_cat_id')) {
             $offer->category_id = $this->request->getPost('sub_cat_id');
         } else {
             if ($this->request->hasPost('cat_id')) {
                 $offer->category_id = $this->request->getPost('cat_id');
             }
         }
         $offer->creation_date = date("Y-m-d-H-i-s");
         $offer->text = $this->request->getPost('text_offer');
         if ($this->request->hasPost('public') && $this->request->getPost('public') == 'y') {
             $offer->status = 1;
         }
         $offer->save();
         if ($offer->save() == false) {
             foreach ($offer->getMessages() as $message) {
             }
         } else {
         }
         // Поля
         if ($this->request->hasPost('offer_id')) {
             foreach ($offer->dannoffers as $dann) {
                 $dann->delete();
             }
         }
         if ($this->request->hasPost('city')) {
             $dann = new DannOffers();
             $dann->dann = $this->request->getPost('city');
             $dann->field_type_id = 4;
             $dann->offers_id = $offer->id;
             $dann->active = 1;
             $dann->save();
         }
         if ($this->request->hasPost('price')) {
             $dann = new DannOffers();
             $dann->dann = $this->request->getPost('price');
             $dann->field_type_id = 5;
             $dann->offers_id = $offer->id;
             $dann->active = 1;
             $dann->save();
         }
         if ($this->request->hasPost('oper')) {
             $dann = new DannOffers();
             $dann->dann = $this->request->getPost('oper');
             $dann->field_type_id = 14;
             $dann->offers_id = $offer->id;
             $dann->active = 1;
             $dann->save();
         }
         if ($this->request->hasPost('gsm-act')) {
             $dann = new DannOffers();
             $dann->dann = $this->request->getPost('gsm-act');
             $dann->field_type_id = 7;
             $dann->offers_id = $offer->id;
             $dann->active = 1;
             $dann->save();
         }
         if ($this->request->hasPost('rad-dost')) {
             $dann = new DannOffers();
             $dann->dann = $this->request->getPost('rad-dost');
             $dann->field_type_id = 15;
             $dann->offers_id = $offer->id;
             $dann->active = 1;
             $dann->save();
         }
         if ($this->request->hasPost('dost-act')) {
             $dann = new DannOffers();
             $dann->dann = $this->request->getPost('dost-act');
             $dann->field_type_id = 6;
             $dann->offers_id = $offer->id;
             $dann->active = 1;
             $dann->save();
         }
         foreach ($_POST as $key => $fil) {
             if (stripos($key, 'fil_cat') !== false) {
                 $dann = new DannOffers();
                 $dann->dann = $this->request->getPost($key);
                 $dann->field_type_id = intval(str_replace('fil_cat-', '', $key));
                 $dann->offers_id = $offer->id;
                 $dann->active = 1;
                 $dann->save();
             }
         }
         /// Фото
         if ($this->request->hasFiles() == true) {
             $i = 0;
             // Выводим имя и размер файла
             foreach ($this->request->getUploadedFiles() as $file) {
                 $i++;
                 // Перемещаем в приложение
                 if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/public/upload/users/user-' . $user_id . '/offers/offer-' . $offer->id)) {
                 } else {
                     mkdir($_SERVER['DOCUMENT_ROOT'] . '/public/upload/users/user-' . $user_id . '/offers/offer-' . $offer->id);
                 }
                 $file->moveTo('upload/users/user-' . $user_id . '/offers/offer-' . $offer->id . '/' . $file->getName());
                 $gd = new GdAdapter('upload/users/user-' . $user_id . '/offers/offer-' . $offer->id . '/' . $file->getName());
                 $gd->resize(600, 430)->save('upload/users/user-' . $user_id . '/offers/offer-' . $offer->id . '/image-big-' . $i . '.jpg');
                 $gd->resize(280, 201)->save('upload/users/user-' . $user_id . '/offers/offer-' . $offer->id . '/image-medium-' . $i . '.jpg');
                 $gd->resize(120, 86)->save('upload/users/user-' . $user_id . '/offers/offer-' . $offer->id . '/image-small-' . $i . '.jpg');
                 unlink('upload/users/user-' . $user_id . '/offers/offer-' . $offer->id . '/' . $file->getName());
                 $image['image-big-' . $i] = 'upload/users/user-' . $user_id . '/offers/offer-' . $offer->id . '/image-big-' . $i . '.jpg';
                 $image['image-medium-' . $i] = 'upload/users/user-' . $user_id . '/offers/offer-' . $offer->id . '/image-medium-' . $i . '.jpg';
                 $image['image-small-' . $i] = 'upload/users/user-' . $user_id . '/offers/offer-' . $offer->id . '/image-small-' . $i . '.jpg';
             }
             $offer->image = serialize($image);
             $offer->save();
         }
         echo json_encode(array('success' => "Предложение " . $offer->name . " добавлено", 'offer_id' => $offer->id));
         ////Конец Обработчика формы предложения
     }
 }
Example #5
0
 /**
  * Resize of image uploaded
  * @param  string  $source
  * @param  string  $dest
  * @param  integer $new_width
  * @param  integer $new_height
  * @return   boolean
  */
 private function resizeImage($source, $dest, $new_width, $new_height)
 {
     $image = new GD($source);
     $source_height = $image->getHeight();
     $source_width = $image->getWidth();
     $source_aspect_ratio = $source_width / $source_height;
     $desired_aspect_ratio = $new_width / $new_height;
     if ($source_aspect_ratio > $desired_aspect_ratio) {
         $temp_height = $new_height;
         $temp_width = (int) ($new_height * $source_aspect_ratio);
     } else {
         $temp_width = $new_width;
         $temp_height = (int) ($new_width / $source_aspect_ratio);
     }
     $x0 = ($temp_width - $new_width) / 2;
     $y0 = ($temp_height - $new_height) / 2;
     $image->resize($temp_width, $temp_height)->crop($new_width, $new_height, $x0, $y0);
     return $image->save($dest);
 }
Example #6
0
 protected function processUpload($model = '')
 {
     $error = 0;
     /** @var \Phalcon\Http\Request $request */
     if ($model == '') {
         $owner = $this->getOwner();
     } else {
         $owner = $model;
     }
     $request = $owner->getDI()->getRequest();
     if (true == $request->hasFiles(true)) {
         foreach ($request->getUploadedFiles() as $key => $file) {
             // NOTE!!!
             // Nothing was validated here!
             // Any validations must be are made in a appropriate validator
             $key = $file->getKey();
             $type = $file->getType();
             if (!in_array($type, $this->allowedFormats)) {
                 $error = self::ERROR_FILETYPE;
             }
             if (!$this->checkMaxsize($file, $this->allowedMaximunSize)) {
                 $error = self::ERROR_FILESIZE;
             }
             if (!$this->checkMinsize($file, $this->allowedMinimumSize)) {
                 $error = self::ERROR_FILESIZE;
             }
             if ($error == 0) {
                 $fileName = $file->getName();
                 if ($this->customName != '') {
                     $fileName = $this->customName;
                 }
                 //find namepart and extension part
                 $pos = strrpos($fileName, '.');
                 if ($pos === false) {
                     $pos = strlen($fileName);
                 }
                 $namePart = substr($fileName, 0, $pos);
                 if (isset($this->sanitize) === true && $this->sanitize == true) {
                     $namePart = Format::toLatinVN($namePart, true, true);
                 }
                 if (isset($this->isoverwrite) === true && $this->isoverwrite == false) {
                     while (file_exists(PUBLIC_PATH . rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $namePart . '.' . $file->getExtension())) {
                         $namePart .= '-' . time();
                     }
                 }
                 if (isset($filename) === false) {
                     $filename = $namePart . '.' . $file->getExtension();
                 }
                 $path = rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $filename;
                 $fullPath = PUBLIC_PATH . $path;
                 if ($file->moveTo($fullPath)) {
                     if ($this->imageField != null) {
                         $owner->writeAttribute($this->imageField, $filename);
                     }
                     $this->setInfo($key, ['path' => $path, 'size' => $file->getSize(), 'extension' => $file->getExtension()]);
                     // Resize image
                     $myResize = new PhImage($fullPath);
                     $myResize->resize(540, 1000)->crop(540, 1000)->save(PUBLIC_PATH . rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $namePart . '-medium' . '.' . $file->getExtension());
                     $myResize->resize(300, 200)->crop(300, 200)->save(PUBLIC_PATH . rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $namePart . '-thumb' . '.' . $file->getExtension());
                     // Delete old file
                     $this->processDelete();
                     $error = self::ERROR_UPLOAD_OK;
                 }
             }
         }
     }
     $this->errorCode = $error;
     return $error;
 }
 public function viewAction()
 {
     $this->view->disable();
     // echo $this->params->filename;
     $image = new Phalcon\Image\Adapter\GD($this->params->filename);
     $realWidth = $image->getWidth();
     $realHeight = $image->getHeight();
     // $image->resize(100, 100)->rotate(90)->crop(100, 100);
     // echo $realWidth . "x". $realHeight;
     $cropSize = $realWidth;
     if ($realWidth > $realHeight) {
         $cropSize = $realHeight;
     }
     // echo $cropSize;
     if (!isset($this->params->width)) {
         $final_width = $realWidth;
     } else {
         $final_width = $this->params->width;
     }
     if (!isset($this->params->height)) {
         $final_height = $realHeight;
     } else {
         $final_height = $this->params->height;
     }
     if (!isset($this->params->crop_mode)) {
         $crop_mode = "default";
     } else {
         $crop_mode = $this->params->crop_mode;
     }
     if (!isset($this->params->crop) and $crop_mode != "default") {
         $final_width = 100;
         $final_height = 100;
     } elseif (isset($this->params->crop) and $crop_mode != "default") {
         $final_width = $this->params->crop;
         $final_height = $this->params->crop;
     } else {
     }
     switch ($crop_mode) {
         case 'center':
             $offset_x = $final_width / 4;
             $offset_y = $final_height / 4;
             break;
         case 'left':
             $offset_x = 0;
             $offset_y = $final_width / 4;
             break;
         case 'right':
             $offset_x = $final_width / 2;
             $offset_y = $final_height / 4;
             break;
         case 'top':
             $offset_x = 0;
             $offset_y = $final_height / 4;
             break;
         case 'bottom':
             $offset_x = $final_width / 2;
             $offset_y = $final_height / 4;
             break;
         case 'top-left':
             $offset_x = 0;
             $offset_y = 0;
             break;
         case 'top-right':
             $offset_x = $final_width / 2;
             $offset_y = 0;
             break;
         case 'bottom-left':
             $offset_x = $final_width / 2;
             $offset_y = 0;
             break;
         case 'bottom-right':
             $offset_x = $final_width / 2;
             $offset_y = $final_height / 2;
             break;
         default:
             $offset_x = 0;
             $offset_y = 0;
             break;
     }
     if (!isset($this->params->mode)) {
         $mode = "preview";
     } else {
         $mode = $this->params->mode;
     }
     if ($mode == "thumbnail") {
         $image->crop($cropSize, $cropSize, $offset_x, $offset_y)->resize($final_width, $final_height);
     }
     $this->response->setContentType('image/jpeg');
     echo $image->render();
     // echo "CROP MODE: ".$crop_mode."=>".$offset_x ."x". $offset_y. " - ".$final_width."x".$final_height;
 }