/**
  * Copy a product image
  *
  * @param integer $id_product Product Id for product image filename
  * @param integer $id_image Image Id for product image filename
  */
 public function copyImage($id_product, $id_image, $method = 'auto')
 {
     if (!isset($_FILES['image_product']['tmp_name'])) {
         return false;
     }
     if ($error = checkImage($_FILES['image_product'], $this->maxImageSize)) {
         $this->_errors[] = $error;
     } else {
         $image = new Image($id_image);
         if (!($new_path = $image->getPathForCreation())) {
             $this->_errors[] = Tools::displayError('An error occurred during new folder creation');
         }
         if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) or !move_uploaded_file($_FILES['image_product']['tmp_name'], $tmpName)) {
             $this->_errors[] = Tools::displayError('An error occurred during the image upload');
         } elseif (!imageResize($tmpName, $new_path . '.' . $image->image_format)) {
             $this->_errors[] = Tools::displayError('An error occurred while copying image.');
         } elseif ($method == 'auto') {
             $imagesTypes = ImageType::getImagesTypes('products');
             foreach ($imagesTypes as $k => $imageType) {
                 if (!imageResize($tmpName, $new_path . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                     $this->_errors[] = Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']);
                 }
             }
         }
         @unlink($tmpName);
         Module::hookExec('watermark', array('id_image' => $id_image, 'id_product' => $id_product));
     }
 }
 /**
  * copyImg copy an image located in $url and save it in a path
  * according to $entity->$id_entity .
  * $id_image is used if we need to add a watermark
  *
  * @param int $id_entity id of product or category (set in entity)
  * @param int $id_image (default null) id of the image if watermark enabled.
  * @param string $url path or url to use
  * @param string $entity 'products' or 'categories'
  * @param bool $regenerate
  * @return bool
  */
 protected static function copyImg($id_entity, $id_image = null, $url = '', $entity = 'products', $regenerate = true)
 {
     $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
     $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
     switch ($entity) {
         default:
         case 'products':
             $image_obj = new Image($id_image);
             $path = $image_obj->getPathForCreation();
             break;
         case 'categories':
             $path = _PS_CAT_IMG_DIR_ . (int) $id_entity;
             break;
         case 'manufacturers':
             $path = _PS_MANU_IMG_DIR_ . (int) $id_entity;
             break;
         case 'suppliers':
             $path = _PS_SUPP_IMG_DIR_ . (int) $id_entity;
             break;
         case 'stores':
             $path = _PS_STORE_IMG_DIR_ . (int) $id_entity;
             break;
     }
     $url = urldecode(trim($url));
     $parced_url = parse_url($url);
     if (isset($parced_url['path'])) {
         $uri = ltrim($parced_url['path'], '/');
         $parts = explode('/', $uri);
         foreach ($parts as &$part) {
             $part = rawurlencode($part);
         }
         unset($part);
         $parced_url['path'] = '/' . implode('/', $parts);
     }
     if (isset($parced_url['query'])) {
         $query_parts = array();
         parse_str($parced_url['query'], $query_parts);
         $parced_url['query'] = http_build_query($query_parts);
     }
     if (!function_exists('http_build_url')) {
         require_once _PS_TOOL_DIR_ . 'http_build_url/http_build_url.php';
     }
     $url = http_build_url('', $parced_url);
     $orig_tmpfile = $tmpfile;
     if (Tools::copy($url, $tmpfile)) {
         // Evaluate the memory required to resize the image: if it's too much, you can't resize it.
         if (!ImageManager::checkImageMemoryLimit($tmpfile)) {
             @unlink($tmpfile);
             return false;
         }
         $tgt_width = $tgt_height = 0;
         $src_width = $src_height = 0;
         $error = 0;
         ImageManager::resize($tmpfile, $path . '.jpg', null, null, 'jpg', false, $error, $tgt_width, $tgt_height, 5, $src_width, $src_height);
         $images_types = ImageType::getImagesTypes($entity, true);
         if ($regenerate) {
             $previous_path = null;
             $path_infos = array();
             $path_infos[] = array($tgt_width, $tgt_height, $path . '.jpg');
             foreach ($images_types as $image_type) {
                 $tmpfile = self::get_best_path($image_type['width'], $image_type['height'], $path_infos);
                 if (ImageManager::resize($tmpfile, $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height'], 'jpg', false, $error, $tgt_width, $tgt_height, 5, $src_width, $src_height)) {
                     // the last image should not be added in the candidate list if it's bigger than the original image
                     if ($tgt_width <= $src_width && $tgt_height <= $src_height) {
                         $path_infos[] = array($tgt_width, $tgt_height, $path . '-' . stripslashes($image_type['name']) . '.jpg');
                     }
                     if ($entity == 'products') {
                         if (is_file(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $id_entity . '.jpg')) {
                             unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $id_entity . '.jpg');
                         }
                         if (is_file(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $id_entity . '_' . (int) Context::getContext()->shop->id . '.jpg')) {
                             unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $id_entity . '_' . (int) Context::getContext()->shop->id . '.jpg');
                         }
                     }
                 }
                 if (in_array($image_type['id_image_type'], $watermark_types)) {
                     Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
                 }
             }
         }
     } else {
         @unlink($orig_tmpfile);
         return false;
     }
     unlink($orig_tmpfile);
     return true;
 }
Example #3
0
    private function upsert($line) {
        $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
        $product = new Product($product);

        $product->reference = $line['reference'];
        $product->name = array(
            '1' => $line['name'],
            '2' => $line['name'],
            '3' => $line['name']
        );
        $product->description = array(
            '1' => $line['description'],
            '2' => $line['description'],
            '3' => $line['description']
        );
        $product->description_short = array(
            '1' => $line['description_short'],
            '2' => $line['description_short'],
            '3' => $line['description_short']
        );
        $product->link_rewrite = array(
            '1' => Tools::link_rewrite($line['name']),
            '2' => Tools::link_rewrite($line['name']),
            '3' => Tools::link_rewrite($line['name'])
        );
        $product->available_now = array(
            '1' => "Есть в наличии",
            '2' => "Есть в наличии",
            '3' => "Есть в наличии"
        );
        $product->id_category_default = $line['category'];
        $product->quantity = (int)$line['count'];

        $product->advanced_stock_management = 1; //использовать Advanced Stock management
        $product->depends_on_stock = 1; //1 - доступное количество на основе ASM. 0 - указывается вручную
        $product->out_of_stock = 1; //2 - как в Preferences product. 1 - allow (Как в Preferences - не дает заказать товар на сайте)

        $product->price = $line['price'];
        $product->weight = $line['weight'] / 1000;
        $product->id_tax_rules_group = $line['id_tax'];

        $product->save();

        $product->updateCategories(array($line['category']));

        $product->deleteFeatures();
        if ($line['author']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(9, $line['author'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 9, $id_feature_value);
        }

        if ($line['year']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(10, $line['year'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 10, $id_feature_value);
        }

        if ($line['paperback']) {
            Product::addFeatureProductImport($product->id, 11, 1); //1 - id значения "переплёт" у харакатеристики "Переплёт"
        }

        if ($line['pages']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(12, $line['pages'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 12, $id_feature_value);
        }

        /*
        if ($line['weight']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(4, $line['weight'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 4, $id_feature_value);
        }
        */

        if ($line['isbn']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(13, $line['isbn'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 13, $id_feature_value);
        }

        if ($line['publishing']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(14, $line['publishing'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 14, $id_feature_value);
        }

        $location = WarehouseProductLocation::getIdByProductAndWarehouse($product->id, 0, $line['warehouse']);
        $location = new WarehouseProductLocation($location);
        $location->id_product = $product->id;
        $location->id_product_attribute = 0;
        $location->id_warehouse = $line['warehouse'];
        $location->save();

        $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
        $stock = new Stock($stock);
        $stock->id_product = $product->id;
        $stock->id_product_attribute = 0;
        $stock->id_warehouse = $line['warehouse'];
        $stock->physical_quantity = $line['count'];
        $stock->usable_quantity = $line['count'];
        $stock->price_te = 0;
        $stock->save();

        $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
        $available = new StockAvailable($available);
        $available->id_product = $product->id;
        $available->id_product_attribute = 0;
        //$available->id_shop = Context::getContext()->shop->id;
        $available->quantity = StockManagerFactory::getManager()->getProductPhysicalQuantities($product->id, 0);
        $available->save();

        StockAvailable::setProductDependsOnStock($product->id, true, null);
        StockAvailable::setProductOutOfStock($product->id, 1, null); //allow

        while(strlen($line['reference']) < 9) {
            $line['reference'] = '0' . $line['reference'];
        }

        if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
            $product->deleteImages();

            $image = new Image();
            $image->id_product = $product->id;
            $image->cover = 1;
            $image->position = 0;
            $image->save();

            $name = $image->getPathForCreation();

            copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name.'.'.$image->image_format);

            $types = ImageType::getImagesTypes('products');
            foreach ($types as $type) {
                ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
            }
        }

        /*
        Db::getInstance()->update('stock_available', array(
           'depends_on_stock' => (int)1, //1 - доступное количество на основе ASM. 0 - указывается вручную
            'out_of_stock' => (int)1, //1-allow
        ), 'id_product='.$product->id.'');
         $affrows = Db::getInstance()->Affected_Rows();
         var_dump($affrows);
         */

        //var_dump($product->reference);
        //echo "<br/><br/><br/><br/>";
    }
Example #4
0
 $image_url = explode('/', $prd['images']);
 $url = _PS_IMG_MGT_DIR_ . end($image_url);
 $product_has_images = (bool) Image::getImages($id_lang, $product->id);
 $image = new Image();
 $image->id_product = (int) $product->id;
 $image->position = Image::getHighestPosition($product->id) + 1;
 $image->cover = !$product_has_images ? true : false;
 $field_error = $image->validateFields(UNFRIENDLY_ERROR, true);
 $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true);
 $id_shop_list = array();
 $errors = array();
 $warnings = array();
 $id_shop_list[] = $product->id_shop_default;
 if ($image->add()) {
     $image->associateTo($id_shop_list);
     $image->getPathForCreation();
     $image_final = $image->getPathForCreation() . '.jpg';
     if (Tools::copy($url, $image_final)) {
         $tgt_width = $tgt_height = 0;
         $src_width = $src_height = 0;
         $previous_path = null;
         $path_infos = array();
         $images_types = ImageType::getImagesTypes('products', true);
         foreach ($images_types as $image_type) {
             if (ImageManager::resize($image_final, $image->getPathForCreation() . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height'], 'jpg', false, $error, $tgt_width, $tgt_height, 5, $src_width, $src_height)) {
                 if (is_file(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '.jpg')) {
                     unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '.jpg');
                 }
                 if (is_file(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '_' . (int) Context::getContext()->shop->id . '.jpg')) {
                     unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '_' . (int) Context::getContext()->shop->id . '.jpg');
                 }
Example #5
0
 /**
  * copyImg copy an image located in $url and save it in a path
  * according to $entity->$id_entity .
  * $id_image is used if we need to add a watermark
  *
  * @param int $id_entity id of product or category (set in entity)
  * @param int $id_image (default null) id of the image if watermark enabled.
  * @param string $url path or url to use
  * @param string entity 'products' or 'categories'
  * @return void
  */
 private static function copyImg($id_entity, $id_image = NULL, $url, $entity = 'products')
 {
     $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
     $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
     switch ($entity) {
         default:
         case 'products':
             $imageObj = new Image($id_image);
             $path = $imageObj->getPathForCreation();
             break;
         case 'categories':
             $path = _PS_CAT_IMG_DIR_ . (int) $id_entity;
             break;
     }
     $url_source_file = str_replace(' ', '%20', trim($url));
     if (@copy($url_source_file, $tmpfile)) {
         imageResize($tmpfile, $path . '.jpg');
         $imagesTypes = ImageType::getImagesTypes($entity);
         foreach ($imagesTypes as $k => $imageType) {
             imageResize($tmpfile, $path . '-' . stripslashes($imageType['name']) . '.jpg', $imageType['width'], $imageType['height']);
         }
         if (in_array($imageType['id_image_type'], $watermark_types)) {
             Module::hookExec('watermark', array('id_image' => $id_image, 'id_product' => $id_entity));
         }
     } else {
         unlink($tmpfile);
         return false;
     }
     unlink($tmpfile);
     return true;
 }
Example #6
0
 public function loadImage($id_product, $images)
 {
     $images_array = $this->imagesToArray($images);
     $images_id = array();
     $product = new Product($id_product);
     $image_types = ImageType::getImagesTypes('product');
     if ($images_array) {
         foreach ($images_array as $img) {
             if (file_exists(_TM_ROOT_DIR_ . $img['url'])) {
                 //ajout de l'image au produit
                 $image = new Image();
                 $image->id_product = intval($product->id);
                 $image->position = Image::getHighestPosition($product->id) + 1;
                 if (!intval($product->id_image_default)) {
                     $image->cover = 1;
                 } else {
                     $image->cover = 0;
                 }
                 $image->legend = 0;
                 $image->add();
                 if ($image->cover) {
                     $product->id_image_default = (int) $image->id;
                 }
                 $id_image = $image->id;
                 $images_id[] = $id_image;
                 $path = $image->getPathForCreation();
                 //echo $imgDir.$img['url'];
                 @copy(_TM_ROOT_DIR_ . $img['url'], $path . '.jpg');
                 foreach ($image_types as $k => $image_type) {
                     ImageManager::resize(_TM_ROOT_DIR_ . $img['url'], $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
                 }
                 //@unlink($tmpName);
             } else {
                 $this->_output .= '<div class="alert error">Image not exists!</div>';
             }
             $product->update();
         }
     }
     return $images_id;
 }
Example #7
0
 public function copyImage($id_image, $type = 'product')
 {
     $image = new Image($id_image);
     if (!($new_path = $image->getPathForCreation())) {
         return array('error' => Tools::displayError('An error occurred during new folder creation'));
     }
     if (!($tmpName = tempnam(_TM_PRO_IMG_DIR, 'PS')) || !$this->upload($tmpName)) {
         return array('error' => Tools::displayError('An error occurred during the image upload'));
     } elseif (!ImageManager::resize($tmpName, $new_path . '.' . $image->image_format)) {
         return array('error' => Tools::displayError('An error occurred while copying image.'));
     } else {
         $imagesTypes = ImageType::getImagesTypes($type);
         foreach ($imagesTypes as $imageType) {
             if (!ImageManager::resize($tmpName, $new_path . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                 return array('error' => Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']));
             }
         }
     }
     unlink($tmpName);
     $img = array('id_image' => $image->id, 'name' => $this->getName());
     return array('success' => $img);
 }
Example #8
0
 public function ajaxProcessaddProductImage()
 {
     self::$currentIndex = 'index.php?tab=AdminProducts';
     $product = new Product((int) Tools::getValue('id_product'));
     $legends = Tools::getValue('legend');
     if (!is_array($legends)) {
         $legends = (array) $legends;
     }
     if (!Validate::isLoadedObject($product)) {
         $files = array();
         $files[0]['error'] = Tools::displayError('Cannot add image because product creation failed.');
     }
     $image_uploader = new HelperImageUploader('file');
     $image_uploader->setAcceptTypes(array('jpeg', 'gif', 'png', 'jpg'))->setMaxSize($this->max_image_size);
     $files = $image_uploader->process();
     foreach ($files as &$file) {
         $image = new Image();
         $image->id_product = (int) $product->id;
         $image->position = Image::getHighestPosition($product->id) + 1;
         foreach ($legends as $key => $legend) {
             if (!empty($legend)) {
                 $image->legend[(int) $key] = $legend;
             }
         }
         if (!Image::getCover($image->id_product)) {
             $image->cover = 1;
         } else {
             $image->cover = 0;
         }
         if (($validate = $image->validateFieldsLang(false, true)) !== true) {
             $file['error'] = Tools::displayError($validate);
         }
         if (isset($file['error']) && (!is_numeric($file['error']) || $file['error'] != 0)) {
             continue;
         }
         if (!$image->add()) {
             $file['error'] = Tools::displayError('Error while creating additional image');
         } else {
             if (!($new_path = $image->getPathForCreation())) {
                 $file['error'] = Tools::displayError('An error occurred during new folder creation');
                 continue;
             }
             $error = 0;
             if (!ImageManager::resize($file['save_path'], $new_path . '.' . $image->image_format, null, null, 'jpg', false, $error)) {
                 switch ($error) {
                     case ImageManager::ERROR_FILE_NOT_EXIST:
                         $file['error'] = Tools::displayError('An error occurred while copying image, the file does not exist anymore.');
                         break;
                     case ImageManager::ERROR_FILE_WIDTH:
                         $file['error'] = Tools::displayError('An error occurred while copying image, the file width is 0px.');
                         break;
                     case ImageManager::ERROR_MEMORY_LIMIT:
                         $file['error'] = Tools::displayError('An error occurred while copying image, check your memory limit.');
                         break;
                     default:
                         $file['error'] = Tools::displayError('An error occurred while copying image.');
                         break;
                 }
                 continue;
             } else {
                 $imagesTypes = ImageType::getImagesTypes('products');
                 foreach ($imagesTypes as $imageType) {
                     if (!ImageManager::resize($file['save_path'], $new_path . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                         $file['error'] = Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']);
                         continue;
                     }
                 }
             }
             unlink($file['save_path']);
             //Necesary to prevent hacking
             unset($file['save_path']);
             Hook::exec('actionWatermark', array('id_image' => $image->id, 'id_product' => $product->id));
             if (!$image->update()) {
                 $file['error'] = Tools::displayError('Error while updating status');
                 continue;
             }
             // Associate image to shop from context
             $shops = Shop::getContextListShopID();
             $image->associateTo($shops);
             $json_shops = array();
             foreach ($shops as $id_shop) {
                 $json_shops[$id_shop] = true;
             }
             $file['status'] = 'ok';
             $file['id'] = $image->id;
             $file['position'] = $image->position;
             $file['cover'] = $image->cover;
             $file['legend'] = $image->legend;
             $file['path'] = $image->getExistingImgPath();
             $file['shops'] = $json_shops;
             @unlink(_PS_TMP_IMG_DIR_ . 'product_' . (int) $product->id . '.jpg');
             @unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '_' . $this->context->shop->id . '.jpg');
         }
     }
     die(Tools::jsonEncode(array($image_uploader->getName() => $files)));
 }
 /**
  * From AdminImportController
  */
 protected static function copyImg($id_entity, $id_image = null, $url, $entity = 'products')
 {
     $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
     $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
     switch ($entity) {
         case 'products':
             $image_obj = new Image($id_image);
             $path = $image_obj->getPathForCreation();
             break;
         case 'categories':
             $path = _PS_CAT_IMG_DIR_ . (int) $id_entity;
             break;
         default:
             break;
     }
     $url = str_replace(' ', '%20', trim($url));
     if (version_compare(_PS_VERSION_, '1.5', '<')) {
         include_once 'class/ImageManager.php';
         $imgSg = new ImageManagerCore();
         if (!$imgSg->checkImageMemoryLimit($url)) {
             return false;
         }
         if (@copy($url, $tmpfile)) {
             $imgSg->resize($tmpfile, $path . '.jpg');
             $images_types = ImageType::getImagesTypes($entity);
             foreach ($images_types as $image_type) {
                 $imgSg->resize($tmpfile, $path . '-' . Tools::stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
             }
         } elseif ($content = Tools::file_get_contents($url)) {
             $fp = fopen($tmpfile, "w");
             fwrite($fp, $content);
             fclose($fp);
             $imgSg->resize($tmpfile, $path . '.jpg');
             $images_types = ImageType::getImagesTypes($entity);
             foreach ($images_types as $image_type) {
                 $imgSg->resize($tmpfile, $path . '-' . Tools::stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
             }
         } else {
             unlink($tmpfile);
             return false;
         }
     } else {
         if (!ImageManager::checkImageMemoryLimit($url)) {
             return false;
         }
         if (@copy($url, $tmpfile)) {
             ImageManager::resize($tmpfile, $path . '.jpg');
             $images_types = ImageType::getImagesTypes($entity);
             foreach ($images_types as $image_type) {
                 ImageManager::resize($tmpfile, $path . '-' . Tools::stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
             }
             if (in_array($image_type['id_image_type'], $watermark_types)) {
                 Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
             }
         } elseif ($content = Tools::file_get_contents($url)) {
             $fp = fopen($tmpfile, "w");
             fwrite($fp, $content);
             fclose($fp);
             ImageManager::resize($tmpfile, $path . '.jpg');
             $images_types = ImageType::getImagesTypes($entity);
             foreach ($images_types as $image_type) {
                 ImageManager::resize($tmpfile, $path . '-' . Tools::stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
             }
             if (in_array($image_type['id_image_type'], $watermark_types)) {
                 Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
             }
         } else {
             unlink($tmpfile);
             return false;
         }
     }
     unlink($tmpfile);
     return true;
 }
Example #10
0
 private function upsert($line)
 {
     $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
     $product = new Product($product);
     $product->reference = $line['reference'];
     $product->name = array('1' => $line['name'], '2' => $line['name'], '3' => $line['name']);
     $product->description = array('1' => $line['description'], '2' => $line['description'], '3' => $line['description']);
     $product->description_short = array('1' => $line['description_short'], '2' => $line['description_short'], '3' => $line['description_short']);
     $product->link_rewrite = array('1' => Tools::link_rewrite($line['name']), '2' => Tools::link_rewrite($line['name']), '3' => Tools::link_rewrite($line['name']));
     $product->available_now = array('1' => "Есть в наличии", '2' => "Есть в наличии", '3' => "Есть в наличии");
     $product->id_category_default = $line['category'];
     $product->quantity = (int) $line['count'];
     $product->advanced_stock_management = 1;
     //использовать Advanced Stock management
     $product->depends_on_stock = 1;
     //1 - доступное количество на основе ASM. 0 - указывается вручную
     $product->out_of_stock = 1;
     //2 - как в Preferences product. 1 - allow (Как в Preferences - не дает заказать товар на сайте)
     $product->price = $line['price'];
     $product->weight = $line['weight'] / 1000;
     $product->id_tax_rules_group = $line['id_tax'];
     $product->save();
     $product->updateCategories(array($line['category']));
     $product->deleteFeatures();
     if ($line['author']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(9, $line['author'], null, Configuration::get('PS_LANG_DEFAULT'));
         Product::addFeatureProductImport($product->id, 9, $id_feature_value);
     }
     if ($line['year']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(10, $line['year'], null, Configuration::get('PS_LANG_DEFAULT'));
         Product::addFeatureProductImport($product->id, 10, $id_feature_value);
     }
     if ($line['paperback']) {
         if ($line['paperback'] == 1) {
             $id_feature_value = 1;
         } else {
             $id_feature_value = 2;
         }
         //$id_feature_value = FeatureValue::addFeatureValueImport(11, $line['paperback'], null, Configuration::get('PS_LANG_DEFAULT'));
         Product::addFeatureProductImport($product->id, 11, $id_feature_value);
         //1 - id значения "твёрдый переплёт" у харакатеристики "Переплёт", 149226 - мягкая обложка
     }
     if ($line['pages']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(12, $line['pages'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 12, $id_feature_value);
     }
     /*
     if ($line['weight']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(4, $line['weight'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 4, $id_feature_value);
     }
     */
     if ($line['isbn']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(13, $line['isbn'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 13, $id_feature_value);
     }
     if ($line['publishing']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(14, $line['publishing'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 14, $id_feature_value);
     }
     $location = WarehouseProductLocation::getIdByProductAndWarehouse($product->id, 0, $line['warehouse']);
     $location = new WarehouseProductLocation($location);
     $location->id_product = $product->id;
     $location->id_product_attribute = 0;
     $location->id_warehouse = $line['warehouse'];
     $location->save();
     /*
     $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
     $stock = new Stock($stock);
     $stock->id_product = $product->id;
     $stock->id_product_attribute = 0;
     $stock->id_warehouse = $line['warehouse'];
     $stock->physical_quantity = $line['count'];
     $stock->usable_quantity = $line['count'];
     $stock->price_te = 0;
     $stock->save();
     */
     //установить зависимость количества товара от остатка на складе для каждого магазинеа
     //исходим из того, что в настройках Мультимагазина остаток НЕ единый на все магазины
     $id_product = $product->id;
     $depends_on_stock = true;
     $out_of_stock = 1;
     //2 - как в Preferences product. 1 - allow (ставь 1, т.к. 2 (как в Preferences) не дает заказать товар на сайте)
     for ($id_shop = 1; $id_shop <= 4; $id_shop++) {
         StockAvailable::setProductDependsOnStock($id_product, $depends_on_stock, $id_shop);
     }
     //разрешить или запретить продажу товара без остатка
     /*  для магазина 2,3 запретить продажу, если нет в наличии. out_of_stock = 0
             2   Second shop Gelikon 
             3   First shop Gelikon
         */
     $out_of_stock = 0;
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 2);
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 3);
     /*
         Для online и заказов по телефону разрешить заказ товара, которого нет в наличии
         1 Gelikon DE online
         4 Заказы по телефону
     */
     $out_of_stock = 1;
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 1);
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 4);
     //Добавить партию товара на склад с записью в журнал движения товаров
     $id_product = $product->id;
     $id_product_attribute = 0;
     $id_stock_mvt_reason = 1;
     $price = 1;
     $id_currency = 1;
     $id_warehouse = $line['warehouse'];
     $warehouse = new Warehouse($id_warehouse);
     $stock_manager = StockManagerFactory::getManager();
     if ($line['count'] != 0) {
         //echo "добавляем товар ";
         $is_usable = true;
         $quantity = $line['count'];
         // add stock
         if ($stock_manager->addProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $price, $is_usable)) {
             StockAvailable::synchronize($id_product);
         } else {
             $errors[] = Tools::displayError('An error occurred. No stock was added.');
         }
     }
     /*
             $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
             $available = new StockAvailable($available);
             $available->id_product = $product->id;
             $available->id_product_attribute = 0;
             //$available->id_shop = Context::getContext()->shop->id;
             $available->quantity = StockManagerFactory::getManager()->getProductPhysicalQuantities($product->id, 0);
             $available->save();
     
             StockAvailable::setProductDependsOnStock($product->id, true, null);
             StockAvailable::setProductOutOfStock($product->id, 1, null); //allow
     */
     while (strlen($line['reference']) < 9) {
         $line['reference'] = '0' . $line['reference'];
     }
     if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
         $product->deleteImages();
         $image = new Image();
         $image->id_product = $product->id;
         $image->cover = 1;
         $image->position = 0;
         $image->save();
         $name = $image->getPathForCreation();
         copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '.' . $image->image_format);
         $types = ImageType::getImagesTypes('products');
         foreach ($types as $type) {
             ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
         }
     }
     /*
             Db::getInstance()->update('stock_available', array(
       'depends_on_stock' => (int)1, //1 - доступное количество на основе ASM. 0 - указывается вручную
        'out_of_stock' => (int)1, //1-allow
             ), 'id_product='.$product->id.'');
     $affrows = Db::getInstance()->Affected_Rows();
     var_dump($affrows);
     */
     //var_dump($product->reference);
     //echo "<br/><br/><br/><br/>";
 }
Example #11
0
    private function upsert($line) {
        $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
        $product = new Product($product);

        $product->reference = $line['reference'];
        $product->name = array(
            '1' => $line['name'],
            '2' => $line['name'],
            '3' => $line['name']
        );
        $product->description = array(
            '1' => $line['description'],
            '2' => $line['description'],
            '3' => $line['description']
        );
        $product->description_short = array(
            '1' => $line['description_short'],
            '2' => $line['description_short'],
            '3' => $line['description_short']
        );
        $product->link_rewrite = array(
            '1' => Tools::link_rewrite($line['name']),
            '2' => Tools::link_rewrite($line['name']),
            '3' => Tools::link_rewrite($line['name'])
        );
        $product->available_now = array(
            '1' => "Есть в наличии",
            '2' => "Есть в наличии",
            '3' => "Есть в наличии"
        );
        $product->id_category_default = $line['category'];
        $product->quantity = $line['count'];
        $product->price = $line['price'];
        $product->weight = $line['weight'] / 1000;
        $product->id_tax_rules_group = $line['id_tax'];

        $product->save();

        $product->updateCategories(array($line['category']));

        $product->deleteFeatures();
        if ($line['author']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(9, $line['author'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 9, $id_feature_value);
        }

        if ($line['year']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(10, $line['year'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 10, $id_feature_value);
        }

        if ($line['paperback']) {
            Product::addFeatureProductImport($product->id, 11, 70);
        }

        if ($line['pages']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(12, $line['pages'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 12, $id_feature_value);
        }

        /*
        if ($line['weight']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(4, $line['weight'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 4, $id_feature_value);
        }
        */

        if ($line['isbn']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(13, $line['isbn'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 13, $id_feature_value);
        }

        if ($line['publishing']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(14, $line['publishing'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 14, $id_feature_value);
        }

        $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
        $stock = new Stock($stock);
        $stock->id_product = $product->id;
        $stock->id_product_attribute = 0;
        $stock->id_warehouse = $line['warehouse'];
        $stock->physical_quantity = $line['count'];
        $stock->usable_quantity = $line['count'];
        $stock->price_te = 0;
        $stock->save();

        $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
        $available = new StockAvailable($available);
        $available->id_product = $product->id;
        $available->id_product_attribute = 0;
        $available->id_shop = Context::getContext()->shop->id;
        $available->quantity = $line['count'];
        $available->save();

        $location = WarehouseProductLocation::getIdByProductAndWarehouse($product->id, 0, $line['warehouse']);
        $location = new WarehouseProductLocation($location);
        $location->id_product = $product->id;
        $location->id_product_attribute = 0;
        $location->id_warehouse = $line['warehouse'];
        $location->save();

        while(strlen($line['reference']) < 9) {
            $line['reference'] = '0' . $line['reference'];
        }

        if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
            $product->deleteImages();

            $image = new Image();
            $image->id_product = $product->id;
            $image->cover = 1;
            $image->position = 0;
            $image->save();

            $name = $image->getPathForCreation();

            copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name.'.'.$image->image_format);

            $types = ImageType::getImagesTypes('products');
            foreach ($types as $type) {
                ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
            }
        }
    }
Example #12
0
             }
             $imgFile = IMAGE_IMPORT_FOLDER . $filepath;
             $fileExists = file_exists($imgFile);
             if (!$fileExists && !$productHasImage) {
                 logResponse('Image not found ' . $imgFile);
             } else {
                 $image = new Image();
                 $image->id_product = (int) $id;
                 $image->cover = (int) $cover;
                 $image->id = $imageId;
                 $image->id_image = $imageId;
                 $image->save();
                 $db->update('image_lang', array('legend' => addslashes($imageDesc)), "id_image = '" . $db->escape($image->id_image) . "'");
                 $imgFolder = Image::getImgFolderStatic($imageId);
                 if ($fileExists && !is_dir(_PS_IMG_DIR_ . 'p' . DIRECTORY_SEPARATOR . $imgFolder)) {
                     $new_path = $image->getPathForCreation();
                     if (file_exists($imgFile)) {
                         $imagesTypes = ImageType::getImagesTypes('products');
                         foreach ($imagesTypes as $imageType) {
                             if (!ImageManager::resize($imgFile, $new_path . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                                 logResponse('An error occurred while copying image:' . ' ' . stripslashes($imageType['name']));
                             }
                         }
                     }
                 }
             }
         }
     }
     logResponse("Product {$id} saved");
 }
 logResponse("Total {$j} products imported");
 private function copyImg($item, $className)
 {
     require_once '../../images.inc.php';
     $identifier = $this->supportedImports[strtolower($className)]['identifier'];
     $matchId = $this->getMatchId(strtolower($className));
     $matchIdLang = $this->getMatchIdLang();
     switch ($className) {
         default:
         case 'Product':
             $path = _PS_PROD_IMG_DIR_;
             break;
         case 'Category':
             $path = _PS_CAT_IMG_DIR_;
             break;
         case 'Manufacturer':
             $path = _PS_MANU_IMG_DIR_;
             break;
         case 'Supplier':
             $path = _PS_SUPP_IMG_DIR_;
             break;
     }
     $cover = 1;
     if (array_key_exists($item[$identifier], $matchId)) {
         if (array_key_exists('images', $item) && !is_null($item['images'])) {
             foreach ($item['images'] as $key => $image) {
                 $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'import');
                 if (@copy(str_replace(' ', '%20', $image), $tmpfile)) {
                     if ($className == 'Product') {
                         $image = new Image();
                         $image->id_product = (int) $matchId[$item[$identifier]];
                         $image->cover = $cover;
                         $image->position = Image::getHighestPosition((int) $matchId[$item[$identifier]]) + 1;
                         $legend = array();
                         foreach ($item['name'] as $key => $val) {
                             if (array_key_exists($key, $matchIdLang)) {
                                 $legend[$matchIdLang[$key]] = Tools::link_rewrite($val);
                             } else {
                                 $legend[Configuration::get('PS_LANG_DEFAULT')] = Tools::link_rewrite($val);
                             }
                         }
                         $image->legend = $legend;
                         $image->add();
                         $path = $image->getPathForCreation();
                         ImageManager::resize($tmpfile, $path . '.jpg');
                     } else {
                         ImageManager::resize($tmpfile, $path . (int) $matchId[$item[$identifier]] . '.jpg');
                     }
                 } else {
                     @unlink($tmpfile);
                 }
                 @unlink($tmpfile);
                 $cover = 0;
             }
         }
     }
 }
Example #14
0
 private static function copyImg($id_entity, $id_image = null, $url, $entity = 'products')
 {
     $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
     $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
     switch ($entity) {
         default:
         case 'products':
             $image_obj = new Image($id_image);
             $path = $image_obj->getPathForCreation();
             break;
         case 'categories':
             $path = _PS_CAT_IMG_DIR_ . (int) $id_entity;
             break;
     }
     $url = str_replace(' ', '%20', trim($url));
     // Evaluate the memory required to resize the image: if it's too much, you can't resize it.
     if (!ImageManager::checkImageMemoryLimit($url)) {
         return false;
     }
     // 'file_exists' doesn't work on distant file, and getimagesize make the import slower.
     // Just hide the warning, the traitment will be the same.
     if (@copy($url, $tmpfile)) {
         ImageManager::resize($tmpfile, $path . '.jpg');
         $images_types = ImageType::getImagesTypes($entity);
         foreach ($images_types as $image_type) {
             ImageManager::resize($tmpfile, $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
         }
         if (in_array($image_type['id_image_type'], $watermark_types)) {
             Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
         }
     } else {
         unlink($tmpfile);
         return false;
     }
     unlink($tmpfile);
     return true;
 }
Example #15
0
 private function upsert($line)
 {
     $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
     $product = new Product($product);
     while (strlen($line['reference']) < 9) {
         $line['reference'] = '0' . $line['reference'];
     }
     if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
         $product->deleteImages();
         $image = new Image();
         $image->id_product = $product->id;
         $image->cover = 1;
         $image->position = 0;
         $image->save();
         $name = $image->getPathForCreation();
         copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '.' . $image->image_format);
         $types = ImageType::getImagesTypes('products');
         foreach ($types as $type) {
             ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
         }
     }
     /*
             Db::getInstance()->update('stock_available', array(
       'depends_on_stock' => (int)1, //1 - доступное количество на основе ASM. 0 - указывается вручную
        'out_of_stock' => (int)1, //1-allow
             ), 'id_product='.$product->id.'');
     $affrows = Db::getInstance()->Affected_Rows();
     var_dump($affrows);
     */
     //var_dump($product->reference);
     //echo "<br/><br/><br/><br/>";
 }
 /**
  * Copy a product image
  *
  * @param integer $id_product Product Id for product image filename
  * @param integer $id_image Image Id for product image filename
  */
 public function copyImage($id_product, $id_image, $method = 'auto')
 {
     if (!isset($_FILES['image_product']['tmp_name'])) {
         return false;
     }
     if ($error = ImageManager::validateUpload($_FILES['image_product'])) {
         $this->errors[] = $error;
     } else {
         $image = new Image($id_image);
         if (!($new_path = $image->getPathForCreation())) {
             $this->errors[] = Tools::displayError('An error occurred while attempting to create a new folder.');
         }
         if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($_FILES['image_product']['tmp_name'], $tmpName)) {
             $this->errors[] = Tools::displayError('An error occurred during the image upload process.');
         } elseif (!ImageManager::resize($tmpName, $new_path . '.' . $image->image_format)) {
             $this->errors[] = Tools::displayError('An error occurred while copying the image.');
         } elseif ($method == 'auto') {
             $imagesTypes = ImageType::getImagesTypes('products');
             foreach ($imagesTypes as $k => $image_type) {
                 if (!ImageManager::resize($tmpName, $new_path . '-' . stripslashes($image_type['name']) . '.' . $image->image_format, $image_type['width'], $image_type['height'], $image->image_format)) {
                     $this->errors[] = Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($image_type['name']);
                 }
             }
         }
         @unlink($tmpName);
         Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_product));
     }
 }
function copyImg15($id_entity, $id_image = null, $url, $entity = 'products')
{
    $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
    //fichier tempo vide
    $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
    switch ($entity) {
        default:
        case 'products':
            $image_obj = new Image($id_image);
            $path = $image_obj->getPathForCreation();
            break;
        case 'categories':
            $path = _PS_CAT_IMG_DIR_ . (int) $id_entity;
            break;
    }
    $url = str_replace(' ', '%20', trim($url));
    // Evaluate the memory required to resize the image: if it's too much, you can't resize it.
    if (!ImageManager::checkImageMemoryLimit($url)) {
        return false;
    }
    //Echo("in routine url, before the copy");
    // 'file_exists' doesn't work on distant file, and getimagesize make the import slower.
    // Just hide the warning, the traitment will be the same.
    //echo(" - Copy image to:".$tmpfile." and then resize in :".$path);
    echo " register_globals: " . ini_get('register_globals');
    echo " safe_mode: " . ini_get('safe_mode');
    echo " allow_url_fopen: " . ini_get('allow_url_fopen');
    //if(isset($sourceFile))
    //{
    //$array_img = explode('/',$sourceFile);
    //}
    //if(copy($_POST['source'],"img/".end($array_img))){
    //echo(" - Copy ".$sourceFile." image to:"._PS_IMG_DIR_.end($array_img)." and then resize in :".$path);
    //if(copy($sourceFile,_PS_IMG_DIR_.end($array_img)))
    if ($version < 16000) {
        if (@copy($url, $tmpfile)) {
            ImageManager::resize($tmpfile, $path . '.jpg');
            //ImageManager::resize(_PS_IMG_DIR_.end($array_img), $path.'.jpg');
            $images_types = ImageType::getImagesTypes($entity);
            foreach ($images_types as $image_type) {
                ImageManager::resize($tmpfile, $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
            }
            //ImageManager::resize(_PS_IMG_DIR_.end($array_img), $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'], $image_type['height']);
            if (in_array($image_type['id_image_type'], $watermark_types)) {
                Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
            }
        } else {
            echo " - @copy failed, please check Apache parameters like safe_mode=off, register_globals=off, allows_url_fopen=true and writting right in /img/tmp and img/p folders";
            unlink($tmpfile);
            return false;
        }
    } else {
        if (Tools::copy($url, $tmpfile)) {
            ImageManager::resize($tmpfile, $path . '.jpg');
            //ImageManager::resize(_PS_IMG_DIR_.end($array_img), $path.'.jpg');
            $images_types = ImageType::getImagesTypes($entity);
            foreach ($images_types as $image_type) {
                ImageManager::resize($tmpfile, $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
            }
            //ImageManager::resize(_PS_IMG_DIR_.end($array_img), $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'], $image_type['height']);
            if (in_array($image_type['id_image_type'], $watermark_types)) {
                Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
            }
        } else {
            echo " - @copy failed, please check Apache parameters like safe_mode=off, register_globals=off, allows_url_fopen=true and writting right in /img/tmp and img/p folders";
            unlink($tmpfile);
            return false;
        }
    }
    unlink($tmpfile);
    return true;
}
Example #18
0
 public function copyImage($id_product, $id_image, $method = 'auto')
 {
     $image = new Image($id_image);
     if (!($new_path = $image->getPathForCreation())) {
         return array('error' => Tools::displayError('An error occurred during new folder creation'));
     }
     if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !$this->upload($tmpName)) {
         return array('error' => Tools::displayError('An error occurred during the image upload'));
     } elseif (!ImageManager::resize($tmpName, $new_path . '.' . $image->image_format)) {
         return array('error' => Tools::displayError('An error occurred while copying image.'));
     } elseif ($method == 'auto') {
         $imagesTypes = ImageType::getImagesTypes('products');
         foreach ($imagesTypes as $imageType) {
             /*
             	$theme = (Shop::isFeatureActive() ? '-'.$imageType['id_theme'] : '');
             	if (!ImageManager::resize($tmpName, $new_path.'-'.stripslashes($imageType['name']).$theme.'.'.$image->image_format, $imageType['width'], $imageType['height'], $image->image_format))
             		return array('error' => Tools::displayError('An error occurred while copying image:').' '.stripslashes($imageType['name']));
             */
             if (!ImageManager::resize($tmpName, $new_path . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                 return array('error' => Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']));
             }
         }
     }
     unlink($tmpName);
     Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_product));
     if (!$image->update()) {
         return array('error' => Tools::displayError('Error while updating status'));
     }
     $img = array('id_image' => $image->id, 'position' => $image->position, 'cover' => $image->cover, 'name' => $this->getName(), 'legend' => $image->legend);
     return array('success' => $img);
 }
 /**
  * copyImg copy an image located in $url and save it in a path
  * according to $entity->$id_entity .
  * $id_image is used if we need to add a watermark
  *
  * @param int $id_entity id of product or category (set in entity)
  * @param int $id_image (default null) id of the image if watermark enabled.
  * @param string $url path or url to use
  * @param string entity 'products' or 'categories'
  * @return boolean
  */
 protected static function copyImg($id_entity, $id_image = null, $url, $entity = 'products', $regenerate = true)
 {
     $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
     $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
     switch ($entity) {
         default:
         case 'products':
             $image_obj = new Image($id_image);
             $path = $image_obj->getPathForCreation();
             break;
         case 'categories':
             $path = _PS_CAT_IMG_DIR_ . (int) $id_entity;
             break;
         case 'manufacturers':
             $path = _PS_MANU_IMG_DIR_ . (int) $id_entity;
             break;
         case 'suppliers':
             $path = _PS_SUPP_IMG_DIR_ . (int) $id_entity;
             break;
     }
     $url = str_replace(' ', '%20', trim($url));
     $url = urldecode($url);
     $parced_url = parse_url($url);
     if (isset($parced_url['path'])) {
         $uri = ltrim($parced_url['path'], '/');
         $parts = explode('/', $uri);
         foreach ($parts as &$part) {
             $part = urlencode($part);
         }
         unset($part);
         $parced_url['path'] = '/' . implode('/', $parts);
     }
     if (isset($parced_url['query'])) {
         $query_parts = array();
         parse_str($parced_url['query'], $query_parts);
         $parced_url['query'] = http_build_query($query_parts);
     }
     if (!function_exists('http_build_url')) {
         require_once _PS_TOOL_DIR_ . 'http_build_url/http_build_url.php';
     }
     $url = http_build_url('', $parced_url);
     // Evaluate the memory required to resize the image: if it's too much, you can't resize it.
     if (!ImageManager::checkImageMemoryLimit($url)) {
         return false;
     }
     // 'file_exists' doesn't work on distant file, and getimagesize makes the import slower.
     // Just hide the warning, the processing will be the same.
     if (Tools::copy($url, $tmpfile)) {
         ImageManager::resize($tmpfile, $path . '.jpg');
         $images_types = ImageType::getImagesTypes($entity);
         if ($regenerate) {
             foreach ($images_types as $image_type) {
                 ImageManager::resize($tmpfile, $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
                 if (in_array($image_type['id_image_type'], $watermark_types)) {
                     Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
                 }
             }
         }
     } else {
         unlink($tmpfile);
         return false;
     }
     unlink($tmpfile);
     return true;
 }
Example #20
0
 public function copyImagesImage($identifier)
 {
     $path = $this->img_path . 'p/';
     $image = new Image($this->retrieveId('image', $identifier));
     $dst_path = $image->getPathForCreation();
     if (!@copy($path . $identifier . '.jpg', $dst_path . '.' . $image->image_format)) {
         $this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier, 'product'));
         return;
     }
     @chmod($dst_path . '.' . $image->image_format, 0644);
     $types = ImageType::getImagesTypes('products');
     foreach ($types as $type) {
         $origin_file = $path . $identifier . '-' . $type['name'] . '.jpg';
         $target_file = $dst_path . '-' . $type['name'] . '.' . $image->image_format;
         // Test if dest folder is writable
         if (!is_writable(dirname($target_file))) {
             $this->setError($this->language->l('Cannot create image "%1$s" (bad permissions on folder "%2$s")', $identifier . '-' . $type['name'], dirname($target_file)));
         } elseif (file_exists($origin_file)) {
             if (!@copy($origin_file, $target_file)) {
                 $this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier . '-' . $type['name'], 'product'));
             }
             @chmod($target_file, 0644);
         } elseif (!ImageManager::resize($path . $identifier . '.jpg', $target_file, $type['width'], $type['height'])) {
             $this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier . '-' . $type['name'], 'product'));
         }
     }
 }
 public function createDummyDataForProject()
 {
     //delete privious products of prestashop
     $all_products = Product::getSimpleProducts(Configuration::get('PS_LANG_DEFAULT'));
     foreach ($all_products as $key_pro => $value_pro) {
         $obj_product = new Product($value_pro['id_product']);
         $obj_product->delete();
     }
     // first add a hotel.................
     $def_cont_id = Country::getDefaultCountryId();
     $obj_hotel_info = new HotelBranchInformation();
     $obj_hotel_info->active = 1;
     $obj_hotel_info->hotel_name = "The Hotel Prime";
     $obj_hotel_info->phone = 01234567;
     $obj_hotel_info->email = "*****@*****.**";
     $obj_hotel_info->check_in = '12:00';
     $obj_hotel_info->check_out = '12:00';
     $obj_hotel_info->short_description = $this->l('Nice place to stay');
     $obj_hotel_info->description = $this->l('Nice place to stay');
     $obj_hotel_info->rating = 3;
     $obj_hotel_info->city = 'Nainital';
     $states = State::getStatesByIdCountry($def_cont_id);
     $state_id = $states[0]['id_state'];
     $obj_hotel_info->state_id = $state_id;
     $obj_hotel_info->country_id = $def_cont_id;
     $obj_hotel_info->zipcode = 263001;
     $obj_hotel_info->policies = $this->l('1. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred. 2. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred. 3. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred. 4. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred.');
     $obj_hotel_info->address = 'Near post office, Mallital, Nainital';
     $obj_hotel_info->save();
     $htl_id = $obj_hotel_info->id;
     $grp_ids = array();
     $obj_grp = new Group();
     $data_grp_ids = $obj_grp->getGroups(1, $id_shop = false);
     foreach ($data_grp_ids as $key => $value) {
         $grp_ids[] = $value['id_group'];
     }
     $country_name = (new Country())->getNameById(Configuration::get('PS_LANG_DEFAULT'), $def_cont_id);
     $cat_country = $this->addCategory($country_name, false, $grp_ids);
     if ($cat_country) {
         $states = State::getStatesByIdCountry($def_cont_id);
         $state_name = $states[0]['name'];
         $cat_state = $this->addCategory($state_name, $cat_country, $grp_ids);
     }
     if ($cat_state) {
         $cat_city = $this->addCategory('DefCity', $cat_state, $grp_ids);
     }
     if ($cat_city) {
         $cat_hotel = $this->addCategory('The Hotel Prime', $cat_city, $grp_ids, 1, $htl_id);
     }
     if ($cat_hotel) {
         $obj_hotel_info = new HotelBranchInformation($htl_id);
         $obj_hotel_info->id_category = $cat_hotel;
         $obj_hotel_info->save();
     }
     $branch_ftr_ids = array(1, 2, 4, 7, 8, 9, 11, 12, 14, 16, 17, 18, 21);
     foreach ($branch_ftr_ids as $key_ftr => $value_ftr) {
         $htl_ftr_obj = new HotelBranchFeatures();
         $htl_ftr_obj->id_hotel = $htl_id;
         $htl_ftr_obj->feature_id = $value_ftr;
         $htl_ftr_obj->save();
     }
     $prod_arr = array('Delux Rooms', 'Executive Rooms', 'luxury Rooms');
     $img_num = 1;
     foreach ($prod_arr as $key_prod => $value_prod) {
         // Add Product
         $product = new Product();
         $product->name = array();
         $product->description = array();
         $product->description_short = array();
         $product->link_rewrite = array();
         foreach (Language::getLanguages(true) as $lang) {
             $product->name[$lang['id_lang']] = $value_prod;
             $product->description[$lang['id_lang']] = $this->l('Fashion axe kogi yuccie, ramps shabby chic direct trade before they sold out distillery bicycle rights. Slow-carb +1 quinoa VHS. +1 brunch trust fund, meggings chartreuse sustainable everyday carry tumblr hoodie tacos tilde ramps post-ironic fixie.');
             $product->description_short[$lang['id_lang']] = $this->l('Fashion axe kogi yuccie, ramps shabby chic direct trade before they sold out distillery bicycle rights. Slow-carb +1 quinoa VHS. +1 brunch trust fund, meggings chartreuse sustainable everyday carry tumblr hoodie tacos tilde ramps post-ironic fixie.');
             $product->link_rewrite[$lang['id_lang']] = Tools::link_rewrite('Super Delux Rooms');
         }
         $product->id_shop_default = Context::getContext()->shop->id;
         $product->id_category_default = 2;
         $product->price = 1000;
         $product->active = 1;
         $product->quantity = 99999999;
         $product->is_virtual = 1;
         $product->indexed = 1;
         $product->save();
         $product_id = $product->id;
         Search::indexation(Tools::link_rewrite($value_prod), $product_id);
         $product->addToCategories(2);
         StockAvailable::updateQuantity($product_id, null, 99999999);
         //image upload for products
         $count = 0;
         $have_cover = false;
         $old_path = _PS_MODULE_DIR_ . $this->name . '/views/img/prod_imgs/' . $img_num . '.png';
         $image_obj = new Image();
         $image_obj->id_product = $product_id;
         $image_obj->position = Image::getHighestPosition($product_id) + 1;
         if ($count == 0) {
             if (!$have_cover) {
                 $image_obj->cover = 1;
             }
         } else {
             $image_obj->cover = 0;
         }
         $image_obj->add();
         $new_path = $image_obj->getPathForCreation();
         $imagesTypes = ImageType::getImagesTypes('products');
         foreach ($imagesTypes as $image_type) {
             ImageManager::resize($old_path, $new_path . '-' . $image_type['name'] . '.jpg', $image_type['width'], $image_type['height']);
         }
         ImageManager::resize($old_path, $new_path . '.jpg');
         for ($k = 1; $k <= 5; $k++) {
             $htl_room_info_obj = new HotelRoomInformation();
             $htl_room_info_obj->id_product = $product_id;
             $htl_room_info_obj->id_hotel = $htl_id;
             $htl_room_info_obj->room_num = 'A' . $i . '-10' . $k;
             $htl_room_info_obj->id_status = 1;
             $htl_room_info_obj->floor = 'first';
             $htl_room_info_obj->save();
         }
         $htl_rm_type = new HotelRoomType();
         $htl_rm_type->id_product = $product_id;
         $htl_rm_type->id_hotel = $htl_id;
         $htl_rm_type->adult = 2;
         $htl_rm_type->children = 2;
         $htl_rm_type->save();
         $img_num++;
         // Add features to the product
         $ftr_arr = array(0 => 8, 1 => 9, 2 => 10, 3 => 11);
         $ftr_val_arr = array(0 => 34, 1 => 35, 2 => 36, 3 => 37);
         foreach ($ftr_arr as $key_htl_ftr => $val_htl_ftr) {
             $product->addFeaturesToDB($val_htl_ftr, $ftr_val_arr[$key_htl_ftr]);
         }
     }
     return true;
 }