コード例 #1
0
 /**
  * @Get("/{product_id:[0-9]+}/{params:[0-9a-zA-Z\-\_\.\:\,]+}", name="show-product")
  */
 public function indexAction()
 {
     $product_id = $this->filter->sanitize($this->dispatcher->getParam('product_id'), 'int');
     $lang = $this->filter->sanitize($this->dispatcher->getParam("lang"), 'string');
     // Selected product
     // Check if the product exists. Redirect to page 404 if not
     if (!($this->view->product = $product = PProductMain::findFirst($product_id))) {
         return $this->response->redirect('route404');
     }
     // Currency rate for selected currency
     $this->view->curr_rate = $curr_rate = PCrosscurrency::findFirst("title='{$this->currency}'")->currencyrate;
     // Delivery
     $expected_delivery = $product->oneProductTime + 25;
     $this->view->expected_delivery = date("d.m.Y", strtotime("now + {$expected_delivery} days"));
     //        $this->view->delivery = $delivery = $this->prodInfoService->deliveryCost($product, $delivery_zone);
     // List of categories to which the product belongs to
     $cat_tree = PCategory::getProductCatTree($product_id, $this->lang)->toArray();
     $cats = [];
     foreach ($cat_tree as $cat) {
         $cats[] = ['title' => $cat['title0'], 'catid' => $cat['catid0'], 'uri' => $cat['uri0']];
         $cats[] = ['title' => $cat['title1'], 'catid' => $cat['catid1'], 'uri' => $cat['uri1']];
         if (isset($cat['title2'])) {
             $cats[] = ['title' => $cat['title2'], 'catid' => $cat['catid2'], 'uri' => $cat['uri2']];
         }
         break;
     }
     $this->view->categories = $cats;
     // More from maker
     $params = ['index' => 'mhdev_' . $lang, 'type' => 'products', 'body' => ['query' => ['function_score' => ['query' => ['match' => ['maker_id' => $product->maker_id]], 'random_score' => new stdClass()]], 'size' => 6]];
     $this->view->maker_products = $this->elasticsearch->search($params)['hits']['hits'];
     // Most saleable
     $params = ['index' => 'mhdev_' . $lang, 'type' => 'products', 'body' => ['size' => 6, 'sort' => ['rating' => ['order' => 'desc']]]];
     $this->view->most_saleable = $this->elasticsearch->search($params)['hits']['hits'];
     $this->view->productId = "/" . $product_id;
     // Discount rate
     $this->view->discount = isset($product->productdiscount) ? $product->productdiscount : null;
     // URL of the page
     $this->view->current_url = $current_url = $this->request->getScheme() . '://' . $this->request->getHttpHost() . $this->request->getURI();
     // Shortened URL (goo.gl)
     $this->view->short_url = $this->prodInfoService->shortUrl($current_url);
     // Product title in respective language
     $this->view->prod_title = $product->getsingleInfo("lang='{$lang}'")->title;
     // Product availability (hold=1)
     $this->view->is_available = $product->hold == 1;
     //---------------------------------------------------------
     $router = $this->di['router'];
     $router->handle();
     //        var_dump($router->getMatchedRoute()->getpaths());
     $routeName = $router->getMatchedRoute()->getname();
     //        $langsAct = PLangs::find(["act=1 AND alias != '{$lang}'", 'order' => 'id']);
     $catUrls = PProdInfo::find("product_id={$product_id} AND coder_status=5 AND lang != '{$lang}'");
     $langsUrls = [];
     foreach ($catUrls as $l) {
         $langsUrls[$l->lang] = $this->url->get(array('for' => $routeName, 'lang' => $l->lang, 'product_id' => $product_id, 'params' => $l->url . '.html'));
     }
     $this->view->langs = $langsUrls;
     //---------------------------------------------------------
 }
コード例 #2
0
 public function indexAction($product_id = null)
 {
     if ($product_id != null) {
         if ($product = PProductMain::findFirst($product_id)) {
             $this->view->product = $product;
         } else {
             return $this->response->redirect('infopanel');
         }
     }
 }
コード例 #3
0
 public function addByIDAction()
 {
     $request = $this->request;
     $response = $this->response;
     $flash = $this->flash;
     if ($request->isPost()) {
         $product_id = $request->getPost('product_id', 'int');
         $mplace_id = $request->getPost('mplace_id', 'int');
         $lang = $request->getPost('lang', 'string');
         $product = PProductMain::findFirst($product_id);
         $mplace = Marketplace::findFirst($mplace_id);
         // Validations
         if (!$product) {
             $flash->error('Ошибка: товар не найден!');
             return $response->redirect('seller/addbyid');
         }
         if ($product->hold == 1) {
             $flash->error('Ошибка: товар на холде!');
             return $response->redirect('seller/addbyid');
         }
         if (!$mplace) {
             $flash->error('Ошибка: площадка не найдена!');
             return $response->redirect('seller/addbyid');
         }
         if (!preg_match("/{$lang}/", $mplace->prefs)) {
             $flash->error('Ошибка: язык не соответствует площадке!');
             return $response->redirect('seller/addbyid');
         }
         // Check for appropriate marketseller
         $marketseller = Marketseller::findFirst("user_id={$this->auth->id} AND marketplace_id={$mplace_id} AND tmaterial_id={$product->tmaterial_id} AND langcode LIKE '%{$lang}%'");
         // If there is no marketseller or if the product is already placed create a new marketseller
         if (!$marketseller or MPlacement::findFirst("marketseller_id={$marketseller->id} AND product_id={$product->id}")) {
             $mseller = new Marketseller();
             $mseller->id = $mseller->id();
             $mseller->created = time();
             $mseller->updated = time();
             $mseller->fio = "{$product->PCategoryGroup->title} на {$mplace->title}";
             $mseller->user_id = $this->auth->id;
             $mseller->marketplace_id = $mplace_id;
             $mseller->tmaterial_id = $product->tmaterial_id;
             $mseller->langcode = $mplace->prefs;
             if (!$mseller->create()) {
                 $flash->error('Ошибка при создании нового виртуального магазина!');
                 return $response->redirect('seller/addbyid');
             } else {
                 return $response->redirect("seller/product/{$mseller->id}/{$product_id}/{$lang}");
             }
         } else {
             return $response->redirect("seller/product/{$marketseller->id}/{$product_id}/{$lang}");
         }
     }
 }
コード例 #4
0
 public function revalInfoAction()
 {
     $this->view->disable();
     if ($this->request->isAjax()) {
         $product_id = $this->request->get('product_id');
         $product = PProductMain::findFirst($product_id);
         $product_title = isset($product->getsingleInfo("lang='ru'")->title) ? $product->getsingleInfo("lang='ru'")->title : $product->title;
         //            $curr_rate = PCrosscurrency::findFirst("title='{$product->maker->currencystr}'")->currencyrate;
         //            $maker_price_usd = round($product->oneProductPrice / $curr_rate, 2);
         // Price change history
         $history_list = [];
         if ($history = PTasks::find(["trole='priceMaker' AND tprodid={$product_id}", 'order' => 'tstart DESC'])) {
             foreach ($history as $hist) {
                 $prices = preg_split('/[\\s]/', $hist->tinfo);
                 $history_list[] = ['history_name' => $hist->Accounts->name, 'history_date' => date('d.m.Y H:i', $hist->tstart), 'history_maker_price' => $prices[0], 'history_maker_price_usd' => $prices[1], 'history_export_price' => $prices[2]];
             }
         }
         $info = ['product_id' => $product->id, 'product_title' => $product_title, 'maker_name' => $product->maker->name, 'price_maker' => $product->oneProductPrice, 'maker_curr' => $product->maker->currencystr, 'maker_price_usd' => $product->holdpriceusd, 'price_usd' => $product->priceUSD, 'history' => $history_list];
         echo json_encode($info);
     }
 }
コード例 #5
0
 /**
  * Main processing script
  *
  * @throws Exception
  */
 public function processAction()
 {
     $this->view->disable();
     if ($this->request->isAjax()) {
         // Set transaction manager
         $transactionManager = new TransactionManager();
         $transaction = $transactionManager->get();
         $root = $this->root;
         $upload_dir_full = $this->upload_dir_full;
         $processed_dir = $this->processed_dir;
         // Create processed folder if it doesn't exist
         if (!file_exists($processed_dir)) {
             mkdir($processed_dir, 0777, true);
         }
         $qrs = $this->persistent->qrs;
         $errors = $this->persistent->errors;
         $created_prods_counter = $this->persistent->created_prods_counter;
         $created_prods_ids = $this->persistent->created_prods_ids;
         $id = $this->request->get('id');
         $item = self::filter($upload_dir_full, "{$id}")[$id];
         // A product must have a minimum of 3 photos
         if (count($item, true) - 1 < 4) {
             $this->errorExit($errors, $id, "У товара должно быть минимум три фотографии!");
         }
         // Check for file name (should not contain alphabetic characters)
         foreach ($item as $i => $f) {
             if (preg_match_all('/[A-Za-z]+\\d*\\./', "{$upload_dir_full}/{$f}")) {
                 $this->errorExit($errors, $id, "Неправильное название файла ({$f})");
             }
         }
         // QR code image
         $qrcode_img = $item[0];
         // Get scanned QR code
         if ($qrs[$id] != false) {
             $code = $qrs[$id];
         } else {
             $this->errorExit($errors, $id, "Не удалось отсканировать QR код ({$qrcode_img})");
         }
         // Check for product existence
         if (PProductMain::findFirst($code)) {
             $this->errorExit($errors, $id, "Товар с таким QR кодом уже внесен в базу ({$code})");
         }
         // -----------------------------------------------------------
         // QR code processing
         $qrcode_info = pathinfo($qrcode_img);
         $qrcode_name = "{$qrcode_info['filename']}qr{$code}";
         $qrcode_folder = rand(111, 999) . "/" . rand(1111111, 99999999) . "/";
         $width = getimagesize("{$upload_dir_full}/{$qrcode_img}")[0];
         $height = getimagesize("{$upload_dir_full}/{$qrcode_img}")[1];
         $filesize = filesize("{$upload_dir_full}/{$qrcode_img}");
         // Create folders for a QR code
         mkdir($root . $this->config->upload->media_qrcodeimage_folder . "/" . $qrcode_folder, 0777, true);
         mkdir($root . $this->config->upload->media_qrcodeimage_nail_folder . "/" . $qrcode_folder, 0777, true);
         // Copy QR code image to the respective folder
         if (!copy("{$upload_dir_full}/{$qrcode_img}", $root . $this->config->upload->media_qrcodeimage_folder . "/" . $qrcode_folder . $qrcode_name . "." . $qrcode_info['extension'])) {
             $this->errorExit($errors, $id, "Ошибка при копировании изображения QR кода ({$qrcode_img})");
         }
         $qrimg = new SimpleImage("{$upload_dir_full}/{$qrcode_img}");
         // Resize QR code image for a thumbnail (100 px) and copy it to nail folder
         if (!$qrimg->fit_to_width(100)->save($root . $this->config->upload->media_qrcodeimage_nail_folder . "/" . $qrcode_folder . $qrcode_name . "." . $qrcode_info['extension'])) {
             $this->errorExit($errors, $id, "Ошибка при копировании изображения (nail) QR кода ({$qrcode_img})");
         }
         // Add QR code to the db
         $qrcode = new PProdQrcodeimage();
         $qrcode->setTransaction($transaction);
         $qrcode->product_id = $code;
         $qrcode->uri = $qrcode_name;
         $qrcode->ext = $qrcode_info['extension'];
         $qrcode->width = $width;
         $qrcode->height = $height;
         $qrcode->filesize = $filesize;
         $qrcode->folder = $qrcode_folder;
         $qrcode->thumbnail = "/thumb/qrcodeimage/nail/{$qrcode_folder}{$qrcode_name}.{$qrcode_info['extension']}";
         $qrcode->ordered = $qrcode->ordered();
         $qrcode->created = time();
         $qrcode->updated = time();
         if (!$qrcode->create()) {
             $transactionManager->collectTransactions();
             // Clear transactions
             $this->errorExit($errors, $id, "Ошибка при добавлении QR кода в базу данных ({$qrcode_img})");
         }
         // Remove QR code from the array
         array_shift($item);
         // -----------------------------------------------------------
         // Photos processing
         $photo_counter = 1;
         foreach ($item as $img) {
             // A product can have a maximum of 5 photos
             if ($photo_counter > 5) {
                 break;
             }
             // Change photo orientation if needed
             //                self::changeOrientation("$upload_dir_full/$img");
             $img_info = pathinfo($img);
             $rand = rand(1111, 9999);
             $width = getimagesize("{$upload_dir_full}/{$img}")[0];
             $height = getimagesize("{$upload_dir_full}/{$img}")[1];
             $filesize = filesize("{$upload_dir_full}/{$img}");
             $img_name = "IMG_{$rand}_{$height}";
             $img_folder = rand(111, 999) . "/" . rand(1111111, 99999999) . "/";
             // Create folders
             mkdir($root . $this->config->upload->media_productphoto_folder . "/" . $img_folder, 0777, true);
             mkdir($root . $this->config->upload->media_productphoto_thumb_folder . "/" . $img_folder, 0777, true);
             mkdir($root . $this->config->upload->media_productphoto_nail_folder . "/" . $img_folder, 0777, true);
             // Resave an image to remove EXIF data
             if (self::removeExif("{$upload_dir_full}/{$img}") == false) {
                 $this->errorExit($errors, $id, "Ошибка при обработке фотографии ({$img})");
             }
             // Copy an image to the respective folder
             if (!copy("{$upload_dir_full}/{$img}", $root . $this->config->upload->media_productphoto_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии ({$img})");
             }
             // Resize an image for a thumbnail (500 px) and copy it to thumb folder
             $thumb_img = new SimpleImage("{$upload_dir_full}/{$img}");
             if (!$thumb_img->fit_to_width(500)->save($root . $this->config->upload->media_productphoto_thumb_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии (thumb) ({$img})");
             }
             // Resize an image for a thumbnail (100 px) and copy it to nail folder
             $nail_img = new SimpleImage("{$upload_dir_full}/{$img}");
             if (!$nail_img->fit_to_width(100)->save($root . $this->config->upload->media_productphoto_nail_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии (nail) ({$img})");
             }
             // Add image to the db
             $imgdb = new PProdPhoto();
             $imgdb->setTransaction($transaction);
             $imgdb->uri = $img_name;
             $imgdb->ext = $img_info['extension'];
             $imgdb->width = $width;
             $imgdb->height = $height;
             $imgdb->filesize = $filesize;
             $imgdb->folder = $img_folder;
             $imgdb->thumbnail = "/thumb/productphoto/nail/{$img_folder}{$img_name}.{$img_info['extension']}";
             $imgdb->product_id = $code;
             $imgdb->ordered = $photo_counter;
             $imgdb->created = time();
             $imgdb->updated = time();
             if (!$imgdb->create()) {
                 $transactionManager->collectTransactions();
                 // Clear transactions
                 $this->errorExit($errors, $id, "Ошибка при добавлении фотографий в базу данных ({$img})");
             }
             $photo_counter++;
         }
         // Create a new product
         $product = new PProductMain();
         $product->setTransaction($transaction);
         $product->id = $code;
         $product->created = time();
         $product->updated = time();
         $product->new = 1;
         $product->hasphoto = 1;
         $product->qrcodeimage_id = $qrcode->id;
         $product->status = 0;
         if (!$product->create()) {
             $transactionManager->collectTransactions();
             // Clear transactions
             $this->errorExit($errors, $id, "Ошибка при создании товара (QR - {$code})");
         }
         // Complete the transaction
         if (!$transaction->commit()) {
             $this->errorExit($errors, $id, "Ошибка транзакции (QR - {$code})");
         }
         // Set stats
         $this->ProdInfoService->setStat('product_created', 'photoUploader', 'ru', $code);
         // Move QR code image
         rename("{$upload_dir_full}/{$qrcode_img}", "{$processed_dir}/{$qrcode_name}.{$qrcode_info['extension']}");
         // Clear thumb for QR code img
         //            if (file_exists("$upload_dir_full/thumbs/$qrcode_img")) unlink("$upload_dir_full/thumbs/$qrcode_img");
         foreach ($item as $img) {
             // Move images
             rename("{$upload_dir_full}/{$img}", "{$processed_dir}/{$img}");
             // Clear thumbs
             //                if (file_exists("$upload_dir_full/thumbs/$img")) unlink("$upload_dir_full/thumbs/$img");
         }
         // Remove the id from QRs list
         $qrs = $this->persistent->qrs;
         unset($qrs[$id]);
         // Update counter and list of ids
         $created_prods_counter++;
         $created_prods_ids[] = $code;
         $this->persistent->qrs = $qrs;
         $this->persistent->created_prods_counter = $created_prods_counter;
         $this->persistent->created_prods_ids = $created_prods_ids;
         // Hooray!
         echo "success";
     }
 }