Esempio n. 1
0
 protected function updateProductFromPayload($product, $payload)
 {
     $product->sku = $payload->sku;
     $product->barcode = $payload->barcode;
     $product->brand_id = $payload->brand;
     // We use the actual brand id as is
     $product->discontinued = $payload->discontinued;
     $product->visible = $payload->enabled;
     // Pay attention: small name change here
     $product->taxable = $payload->taxable;
     $product->price = $payload->price;
     $product->weight = $payload->weight;
     $product->parent_product_id = $payload->parent_product_id;
     $product->save();
     // We insert the images before the localization so we can save the localizations with an image for quick elasticsearch reference
     // Clean up all previous images
     foreach ($product->productImages as $image) {
         $image->delete();
     }
     foreach ($payload->images as $image) {
         $productimg = new ProductImage();
         $productimg->product_id = $product->id;
         $productimg->extension = $image->extension;
         $productimg->identifier = $image->id;
         $productimg->position = $image->position;
         $productimg->locale_id = Locale::localeIdFromLongCode($image->locale);
         $productimg->save();
     }
     // Clean up all previous localizations
     foreach ($product->productLocalizations as $localization) {
         $localization->delete();
     }
     foreach ($payload->localizations as $localization) {
         $productLocalization = new ProductLocalization();
         $productLocalization->product_id = $product->id;
         $productLocalization->locale_id = Locale::localeIdFromLongCode($localization->locale);
         $productLocalization->name = $localization->name;
         $productLocalization->short_description = $localization->short_description;
         $productLocalization->long_description = $localization->long_description;
         $productLocalization->visible = $localization->enabled;
         $productLocalization->save();
     }
     $previousRelationships = ProductHasCategory::model()->findAll("product_id=:product_id", array(':product_id' => $product->id));
     foreach ($previousRelationships as $relat) {
         $relat->delete();
     }
     foreach ($payload->categories as $category) {
         // Check for existing relationships... we encounter some duplicates sometimes
         $existingRelationship = ProductHasCategory::model()->find("product_id=:product_id AND category_id=:category_id", array(':product_id' => $product->id, ':category_id' => $category));
         if ($existingRelationship === null) {
             $catrel = new ProductHasCategory();
             $catrel->product_id = $product->id;
             $catrel->category_id = $category;
             $catrel->save();
         }
     }
     return $product;
 }
 public function updateProductImages(Product $product)
 {
     foreach (CUploadedFile::getInstancesByName('ProductImage') as $key => $image) {
         $productImage = new ProductImage();
         $productImage->product_id = $product->id;
         $productImage->attributes = $_POST['ProductImage'][$key];
         $productImage->addFileInstanceName('ProductImage[' . $key . '][name]');
         $productImage->save();
     }
 }
Esempio n. 3
0
 public static function saveImagePrduct($array, $product_id)
 {
     foreach ($array as $item) {
         $value = new ProductImage();
         $value->image = $item['image'];
         $value->image_small = $item['image_small'];
         $value->product_id = $product_id;
         $value->save();
     }
     return;
 }
Esempio n. 4
0
 protected function saveImages($images)
 {
     if (count($images) > 0) {
         foreach ($images as $key => $url) {
             $image_entity = ProductImageModel::findOneByUrl($url);
             if (!$image_entity) {
                 // save image to local HDD
                 $filename = 'p_' . $this->product->id . '_i_' . $key . '.jpg';
                 $filepath = 'd:\\workspace\\newhtf\\data\\images\\' . $filename;
                 $image_bin = file_get_contents($url);
                 file_put_contents($filepath, $image_bin);
                 // save image to DB
                 if (file_exists($filepath)) {
                     $image_entity = new ProductImage();
                     $image_entity->fromArray(['product_id' => $this->product->id, 'url' => $url, 'filename' => $filename]);
                     $image_entity->save();
                 }
             } else {
                 $image_entity->id;
             }
         }
     }
 }
 /**
  * @param Product $product
  */
 protected function updateProductImages(Product $product)
 {
     if (Yii::app()->getRequest()->getPost('ProductImage')) {
         foreach (Yii::app()->getRequest()->getPost('ProductImage') as $key => $val) {
             $productImage = ProductImage::model()->findByPk($key);
             if (null === $productImage) {
                 $productImage = new ProductImage();
                 $productImage->product_id = $product->id;
                 $productImage->addFileInstanceName('ProductImage[' . $key . '][name]');
             }
             $productImage->setAttributes($_POST['ProductImage'][$key]);
             if (false === $productImage->save()) {
                 Yii::app()->getUser()->setFlash(\yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('StoreModule.store', 'Error uploading some images...'));
             }
         }
     }
 }
Esempio n. 6
0
	function duplicate () {
		$db =& DB::get();

		$this->load_data(array('prices','specs','categories','tags','images','taxes'=>'false'));
		$this->id = '';
		$this->name = $this->name.' '.__('copy','Ecart');
		$this->slug = sanitize_title_with_dashes($this->name);

		// Check for an existing product slug
		$existing = $db->query("SELECT slug FROM $this->_table WHERE slug='$this->slug' LIMIT 1");
		if ($existing) {
			$suffix = 2;
			while($existing) {
				$altslug = substr($this->slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
				$existing = $db->query("SELECT slug FROM $this->_table WHERE slug='$altslug' LIMIT 1");
				$suffix++;
			}
			$this->slug = $altslug;
		}
		$this->created = '';
		$this->modified = '';

		$this->save();

		// Copy prices
		foreach ($this->prices as $price) {
			$Price = new Price();
			$Price->updates($price,array('id','product','created','modified'));
			$Price->product = $this->id;
			$Price->save();
		}

		// Copy sepcs
		foreach ($this->specs as $spec) {
			$Spec = new Spec();
			$Spec->updates($spec,array('id','parent','created','modified'));
			$Spec->parent = $this->id;
			$Spec->save();
		}

		// Copy categories
		$categories = array();
		foreach ($this->categories as $category) $categories[] = $category->id;
		$this->categories = array();
		$this->save_categories($categories);

		// Copy tags
		$taglist = array();
		foreach ($this->tags as $tag) $taglist[] = $tag->name;
		$this->tags = array();
		$this->save_tags($taglist);

		// Copy product images
		foreach ($this->images as $ProductImage) {
			$Image = new ProductImage();
			$Image->updates($ProductImage,array('id','parent','created','modified'));
			$Image->parent = $this->id;
			$Image->save();
		}

	}
Esempio n. 7
0
 private function importImage(ProductImage $image, $path)
 {
     if (!$path) {
         return false;
     }
     if (@parse_url($path, PHP_URL_SCHEME)) {
         $fetch = new NetworkFetch($path);
         $path = $fetch->fetch() ? $fetch->getTmpFile() : '';
     } else {
         if (!file_exists($path)) {
             foreach (array('/tmp/import/', ClassLoader::getRealPath('public.import.')) as $loc) {
                 $p = $loc . $path;
                 if (file_exists($p)) {
                     $path = $p;
                     break;
                 }
             }
         }
         if (!file_exists($path)) {
             $path = '';
         }
     }
     if ($path) {
         $man = new ImageManipulator($path);
         if ($man->isValidImage()) {
             $image->save();
             $image->resizeImage($man);
             $image->save();
         }
     }
 }
Esempio n. 8
0
 /**
  * AJAX behavior to process uploaded images
  *
  * @author Jonathan Davis
  * @return string JSON encoded result with thumbnail id and src
  **/
 public static function images()
 {
     $context = false;
     $error = false;
     $valid_contexts = array('product', 'category');
     if (isset($_FILES['Filedata']['error'])) {
         $error = $_FILES['Filedata']['error'];
     }
     if ($error) {
         die(json_encode(array('error' => Lookup::errors('uploads', $error))));
     }
     if (isset($_REQUEST['type']) && in_array(strtolower($_REQUEST['type']), $valid_contexts)) {
         $parent = $_REQUEST['parent'];
         $context = strtolower($_REQUEST['type']);
     }
     if (!$context) {
         die(json_encode(array('error' => Shopp::__('The file could not be saved because the server cannot tell whether to attach the asset to a product or a category.'))));
     }
     if (!@is_uploaded_file($_FILES['Filedata']['tmp_name'])) {
         die(json_encode(array('error' => Shopp::__('The file could not be saved because the upload was not found on the server.'))));
     }
     if (0 == $_FILES['Filedata']['size']) {
         die(json_encode(array('error' => Shopp::__('The file could not be saved because the uploaded file is empty.'))));
     }
     // Save the source image
     if ('category' == $context) {
         $Image = new CategoryImage();
     } else {
         $Image = new ProductImage();
     }
     $Image->parent = $parent;
     $Image->type = 'image';
     $Image->name = 'original';
     $Image->filename = $_FILES['Filedata']['name'];
     $context = 'upload';
     $tempfile = $_FILES['Filedata']['tmp_name'];
     if (!@is_readable($tempfile)) {
         $context = 'file';
         $tempfile = get_temp_dir() . $Image->filename;
         if (!@move_uploaded_file($_FILES['Filedata']['tmp_name'], $tempfile)) {
             die(json_encode(array('error' => Shopp::__('The file could not be saved because the web server does not have permission to read the upload.'))));
         }
     }
     list($Image->width, $Image->height, $Image->mime, $Image->attr) = getimagesize($tempfile);
     $Image->mime = image_type_to_mime_type($Image->mime);
     $Image->size = filesize($tempfile);
     if (!$Image->unique()) {
         die(json_encode(array('error' => Shopp::__('The image already exists, but a new filename could not be generated.'))));
     }
     $Image->store($tempfile, $context);
     if ('file' == $context) {
         unlink($tempfile);
     }
     $Error = ShoppErrors()->code('storage_engine_save');
     if (!empty($Error)) {
         die(json_encode(array('error' => $Error->message(true))));
     }
     $Image->save();
     if (empty($Image->id)) {
         die(json_encode(array('error' => Shopp::__('The image reference was not saved to the database.'))));
     }
     echo json_encode(array('id' => $Image->id));
     exit;
 }
Esempio n. 9
0
 /**
  * Updates image details for all cached images of the product
  *
  * @author Jonathan Davis
  * @since 1.0
  *
  * @param array image record ids
  * @return void
  **/
 public function update_images($images)
 {
     if (!is_array($images)) {
         return;
     }
     foreach ($images as $img) {
         $Image = new ProductImage($img['id']);
         $Image->title = stripslashes($img['title']);
         $Image->alt = stripslashes($img['alt']);
         if (!empty($img['cropping'])) {
             if (!class_exists('ImageProcessor')) {
                 require SHOPP_MODEL_PATH . "/Image.php";
             }
             foreach ($img['cropping'] as $id => $cropping) {
                 if (empty($cropping)) {
                     continue;
                 }
                 $Cropped = new ProductImage($id);
                 list($Cropped->settings['dx'], $Cropped->settings['dy'], $Cropped->settings['cropscale']) = explode(',', $cropping);
                 extract($Cropped->settings);
                 $Resized = new ImageProcessor($Image->retrieve(), $Image->width, $Image->height);
                 $scaled = $Image->scaled($width, $height, $scale);
                 $scale = ImageAsset::$defaults['scaling'][$scale];
                 $quality = $quality === false ? ImageAsset::$defaults['quality'] : $quality;
                 $Resized->scale($scaled['width'], $scaled['height'], $scale, $alpha, $fill, (int) $dx, (int) $dy, (double) $cropscale);
                 // Post sharpen
                 if ($sharpen !== false) {
                     $Resized->UnsharpMask($sharpen);
                 }
                 $Cropped->data = $Resized->imagefile($quality);
                 if (empty($Cropped->data)) {
                     return false;
                 }
                 $Cropped->size = strlen($Cropped->data);
                 if ($Cropped->store($Cropped->data) === false) {
                     return false;
                 }
                 $Cropped->save();
             }
         }
         $Image->save();
     }
 }
Esempio n. 10
0
	/**
	 * AJAX behavior to process uploaded images
	 *
	 * TODO: Find a better place for this code so products & categories can both use it
	 *	 
	 * @return string JSON encoded result with thumbnail id and src
	 **/
	function images () {
		$context = false;

		$error = false;
		if (isset($_FILES['Filedata']['error'])) $error = $_FILES['Filedata']['error'];
		if ($error) die(json_encode(array("error" => $this->uploadErrors[$error])));

		require(ECART_PATH."/core/model/Image.php");

		if (isset($_REQUEST['type'])) {
			$parent = $_REQUEST['parent'];
			switch (strtolower($_REQUEST['type'])) {
				case "product":
					$context = "product";
					break;
				case "category":
					$context = "category";
					break;
			}
		}

		if (!$context)
			die(json_encode(array("error" => __('The file could not be saved because the server cannot tell whether to attach the asset to a product or a category.','Ecart'))));

		if (!is_uploaded_file($_FILES['Filedata']['tmp_name']))
			die(json_encode(array("error" => __('The file could not be saved because the upload was not found on the server.','Ecart'))));

		if (!is_readable($_FILES['Filedata']['tmp_name']))
			die(json_encode(array("error" => __('The file could not be saved because the web server does not have permission to read the upload from the server\'s temporary directory.','Ecart'))));

		if ($_FILES['Filedata']['size'] == 0)
			die(json_encode(array("error" => __('The file could not be saved because the uploaded file is empty.','Ecart'))));

		// Save the source image
		if ($context == "category") $Image = new CategoryImage();
		else $Image = new ProductImage();

		$Image->parent = $parent;
		$Image->type = "image";
		$Image->name = "original";
		$Image->filename = $_FILES['Filedata']['name'];
		list($Image->width, $Image->height, $Image->mime, $Image->attr) = getimagesize($_FILES['Filedata']['tmp_name']);
		$Image->mime = image_type_to_mime_type($Image->mime);
		$Image->size = filesize($_FILES['Filedata']['tmp_name']);

		$Existing = new ImageAsset();
		$Existing->uri = $Image->filename;
		$limit = 100;
		while ($Existing->found()) { // Rename the filename of the image if it already exists
			list($name,$ext) = explode(".",$Existing->uri);
			$_ = explode("-",$name);
			$last = count($_)-1;
			$suffix = $last > 0?intval($_[$last])+1:1;
			if ($suffix == 1) $_[] = $suffix;
			else $_[$last] = $suffix;
			$Existing->uri = join("-",$_).'.'.$ext;
			if (!$limit--)
				die(json_encode(array("error" => __('The image already exists, but a new filename could not be generated.','Ecart'))));
		}
		if ($Existing->uri !== $Image->filename)
			$Image->filename = $Existing->uri;

		$Image->store($_FILES['Filedata']['tmp_name'],'upload');
		$Image->save();

		if (empty($Image->id))
			die(json_encode(array("error" => __('The image reference was not saved to the database.','Ecart'))));

		echo json_encode(array("id"=>$Image->id));
	}
Esempio n. 11
0
 public function actionUpdate($id = null, $type = null)
 {
     $model = Product::model()->findByPk($id);
     $flag = 0;
     $image_old = $model->attributes['image'];
     if (!empty($_POST['Product'])) {
         if (!empty(CUploadedFile::getInstance($model, 'image')->name)) {
             $image_old = $model->attributes['image'];
             $path = realpath(Yii::app()->basePath . '/../upload/images/' . $image_old);
             if (file_exists($path) && !empty($image_old)) {
                 unlink($path);
             }
             $model->attributes = $_POST['Product'];
             $model->image = CUploadedFile::getInstance($model, 'image');
             $image = $model->image;
             $imageType = explode('.', $model->image->name);
             $imageType = $imageType[count($imageType) - 1];
             $imageName = md5(uniqid()) . '.' . $imageType;
             $model->image = $imageName;
             $images_path = Yii::getPathOfAlias('webroot') . '/upload/images/' . $imageName;
             $flag = 1;
         } else {
             $model->attributes = $_POST['Product'];
             $model->image = $image_old;
         }
         $model->type = $id;
         $model->updated = time();
         $model->alias = alias($_POST['Product']['name']);
         if ($model->save()) {
             Yii::app()->user->setFlash('success', translate('Sửa sản phẩm thành công.'));
             if ($flag == 1) {
                 $image->saveAs($images_path);
             }
             // Them hinh anh
             $arrImage = CUploadedFile::getInstancesByName('images');
             foreach ($arrImage as $image) {
                 $modelImage = new ProductImage();
                 $modelImage->product_id = $model->id;
                 $nameImage = explode(".", $image->name);
                 $type = end($nameImage);
                 $modelImage->image = md5(uniqid()) . '.' . $type;
                 $modelImage->created = time();
                 $path = Yii::getPathOfAlias('webroot') . '/upload/images/' . $modelImage->image;
                 $image->saveAs($path);
                 $modelImage->save();
             }
             $this->redirect(PIUrl::createUrl('/admin/Product/', array('id' => $id)));
         }
     }
     $dataCategories = ProductCategory::model()->getDataCategories($type);
     $criteria = new CDBCriteria();
     $criteria->addCondition("product_id = {$id}");
     $arrProductImage = ProductImage::model()->findAll($criteria);
     $this->render('update', array('model' => $model, 'dataCategories' => $dataCategories, 'arrProductImage' => $arrProductImage));
 }
Esempio n. 12
0
 public function actionUploadImage()
 {
     try {
         $productId = intval(Yii::app()->request->getPost('product_id'));
         $file = CUploadedFile::getInstanceByName('Filedata');
         // 检查上传文件
         if ($file instanceof CUploadedFile == false) {
             throw new Exception('无法识别上传文件');
         }
         // 检查尺寸
         list($width, $height, $type, $attr) = getimagesize($file->tempName);
         if (empty($width) || empty($height)) {
             throw new Exception($file->name . ' 无法识别图片');
         }
         if ($width < 380) {
             throw new Exception($file->name . ' 尺寸不符合要求,请上传宽大于或等于 380 像素的图片');
         }
         // 保存原图
         $fileName = md5($file->tempName . uniqid()) . '.' . $file->extensionName;
         $filePath = Helper::mediaPath(Product::UPLOAD_ORIGINAL_IMAGE_PATH . $fileName, FRONTEND);
         $file->saveAs($filePath, false);
         // 裁切大图
         require_once 'Image.php';
         $image = new Image($filePath);
         $image->resize(380, 380)->save(Helper::mediaPath(Product::UPLOAD_LARGE_IMAGE_PATH . $fileName, FRONTEND));
         // 裁切缩略图
         $image = new Image($filePath);
         $image->resize(80, 80)->save(Helper::mediaPath(Product::UPLOAD_THUMBNAIL_IMAGE_PATH . $fileName, FRONTEND));
         // 入库
         $model = new ProductImage();
         $model->product_id = $productId;
         $model->file_name = $file->name;
         $model->image_path = $fileName;
         $model->sort_order = 0;
         $model->is_released = 1;
         $model->save();
         echo CJSON::encode(array('result' => true, 'product_image_id' => $model->primaryKey, 'product_id' => $productId, 'thumbnail_image_url' => $model->getThumbnailImageUrl(), 'file_name' => $model->file_name));
     } catch (Exception $e) {
         echo CJSON::encode(array('result' => false, 'message' => $e->getMessage()));
     }
 }
Esempio n. 13
0
 public function actionUpdate($id)
 {
     /**
      * @var $model Product
      */
     $model = $this->loadModel($id, 'Product');
     $img_path = $model->image;
     if (isset($_POST['Product'])) {
         $model->setAttributes($_POST['Product']);
         $img = CUploadedFile::getInstance($model, 'image');
         //var_dump($img);die;
         if ($img && (is_object($img) && get_class($img) === 'CUploadedFile')) {
             $model->image = $img;
             $dirImages = Yii::getPathOfAlias('webroot') . "/upload/images/";
             $ext = strtolower($model->image->getExtensionName());
             $fileName = "img_" . date("YmHis", time()) . "." . $ext;
             $uri = date("Y/m/d", time()) . '/' . $fileName;
             $des = $dirImages . $uri;
             if (!is_dir($des)) {
                 $list_dir = explode("/", date("Y/m/d", time()));
                 $temp_dir = Yii::getPathOfAlias('webroot') . "/upload/images";
                 foreach ($list_dir as $dr) {
                     $temp_dir .= "/" . $dr;
                     if (!is_dir($temp_dir)) {
                         mkdir($temp_dir);
                         chmod($temp_dir, 0755);
                     }
                 }
             }
             $model->image->saveAs($des);
             $model->image = "/upload/images/" . $uri;
         } else {
             $model->setAttribute('image', $img_path);
         }
         if ($model->save()) {
             $photos = CUploadedFile::getInstancesByName('photos');
             //var_dump($photos);die();
             // proceed if the images have been set
             if (isset($photos) && count($photos) > 0) {
                 $dirPhotos = Yii::getPathOfAlias('webroot') . "/upload/images/";
                 // go through each uploaded image
                 //var_dump($photos);die;
                 foreach ($photos as $pic) {
                     //echo $pic->name . '<br />';
                     $ext = strtolower($pic->getExtensionName());
                     $fileName = "img_" . date("YmHis", time()) . "." . $ext;
                     $uri = date("Y/m/d", time()) . '/' . $fileName;
                     $desPhotos = $dirPhotos . $uri;
                     if (!is_dir($desPhotos)) {
                         $list_dir = explode("/", date("Y/m/d", time()));
                         $temp_dir = Yii::getPathOfAlias('webroot') . "/upload/images";
                         foreach ($list_dir as $dr) {
                             $temp_dir .= "/" . $dr;
                             if (!is_dir($temp_dir)) {
                                 mkdir($temp_dir);
                                 chmod($temp_dir, 0755);
                             }
                         }
                     }
                     if ($pic->saveAs($desPhotos)) {
                         $tPhoto = new ProductImage();
                         $tPhoto->product_id = $model->id;
                         $tPhoto->file_path = '/upload/images/' . $uri;
                         $tPhoto->save();
                         // DONE
                     }
                 }
             }
             $this->redirect(array('admin'));
         }
     }
     $this->render('update', array('model' => $model));
 }
Esempio n. 14
0
 /**
  * 保存商品的图片信息
  */
 protected function saveProductImage($productId)
 {
     $imageConfig = Yii::app()->params['image']['product'];
     if (empty($imageConfig)) {
         throw new exception('缺少商品图片配置');
     }
     $image = CUploadedFile::getInstanceByName('Filedata');
     $image_extension = $image->getExtensionName();
     $path = $imageConfig['path'] . date('Ym') . '/';
     $this->createPath($path);
     $imageName = date('YmdHis') . rand(1, 1000);
     $imageNamePath = $path . $imageName . '.' . $image_extension;
     $flag = $image->saveAs($imageNamePath, true);
     if (!$flag) {
         throw new exception('原图保存失败!');
     }
     $images_arr = array();
     $image = Yii::app()->image->load($imageNamePath);
     foreach ($imageConfig['sizes'] as $row) {
         $newImagePath = $path . $imageName . '-' . $row . '.' . $image_extension;
         $flag = $image->resize($row, $row)->save($newImagePath);
         if (!$flag) {
             throw new exception('图片尺寸' . $row . '生成失败!');
         }
         $images_arr['image_' . $row] = str_replace(ROOT_PATH, '', $newImagePath);
     }
     //图片处理here
     $model = new ProductImage();
     $model->product_id = $productId;
     $model->img = str_replace(ROOT_PATH, '', $imageNamePath);
     $model->add_time = time();
     $flag = $model->save();
     if (!$flag) {
         throw new exception('保存记录失败!');
     }
     return array('imgid' => $model->id, 'img' => $images_arr);
 }
Esempio n. 15
0
 private static function saveImages($images, $product_id)
 {
     foreach ($images as $file) {
         $img = Image::make($file->getRealPath());
         // Get hash name
         $ext = $file->guessClientExtension();
         $fullname = $file->getClientOriginalName();
         $hash_name = date('d.m.Y.H.i.s') . '-' . md5($fullname) . '.' . $ext;
         // Save images
         $original = self::savePhysicalImage($img, $hash_name, 'original');
         $image = self::savePhysicalImage($img, $hash_name, 'image');
         $thumb = self::savePhysicalImage($img, $hash_name, 'thumb');
         // Create the product image record
         $product_image = new ProductImage();
         $product_image->product_id = $product_id;
         $product_image->orig = $original;
         $product_image->path = $image;
         $product_image->thumb = $thumb;
         $product_image->save();
     }
 }