Author: lhe (helin16@gmail.com)
Inheritance: extends BaseEntityAbstract
    /**
     * when doing the first dev/build, the record will be added as testing product
     */
    function requireDefaultRecords()
    {
        parent::requireDefaultRecords();
        $product1 = DataObject::get_one('ProductObject', "\"Title\" = 'Daft Robot'");
        if (!($product1 && $product1->exists())) {
            $product1 = new ProductObject();
            $product1->Title = 'Daft Robot';
            $product1->Description = <<<HTML
\t\t\t<p>DVD, 2010<br />Striped Silver Pictures</p>
\t\t\t<p>A stellar example of the type of product you might want to sell on your site.</p>
HTML;
            $productImage1 = DataObject::get_one('ProductImage', "\"Name\" = 'daft-robot.png'");
            if (!($productImage1 && $productImage1->exists())) {
                $uploadfolder = Folder::findOrMake("Uploads");
                $command = "cp ../payment-test/templates/Images/daft-robot.png ../" . $uploadfolder->Filename;
                `{$command}`;
                $productImage1 = new ProductImage(array('ClassName' => 'ProductImage'));
                $productImage1->Name = 'daft-robot.png';
                $productImage1->Title = 'daft-robot';
                $productImage1->Filename = 'assets/Uploads/daft-robot.png';
                $productImage1->ParentID = $uploadfolder->ID;
                $productImage1->OwnerID = Member::currentUserID();
                $productImage1->write();
            }
            $product1->ImageID = $productImage1->ID;
            $product1->Amount->Amount = '8.99';
            $product1->Amount->Currency = 'USD';
            $product1->write();
            DB::alteration_message('product example \'Daft Robot\'', 'created');
        }
        $product2 = DataObject::get_one('ProductObject', "\"Title\" = 'Bloody Knife'");
        if (!($product2 && $product2->exists())) {
            $product2 = new ProductObject();
            $product2->Title = 'Bloody Knife';
            $product2->Description = <<<HTML
\t\t\t<p>DVD, 1978<br />SilverSplatter Films</p>
\t\t\t<p>A terrifying cult classic that has inspired many horror movies.</p>
HTML;
            $productImage2 = DataObject::get_one('ProductImage', "\"Name\" = 'bloody-knife.png'");
            if (!($productImage2 && $productImage2->exists())) {
                $uploadfolder = Folder::findOrMake("Uploads");
                $command = "cp ../payment-test/templates/Images/bloody-knife.png ../" . $uploadfolder->Filename;
                `{$command}`;
                $productImage2 = new ProductImage(array('ClassName' => 'ProductImage'));
                $productImage2->Name = 'bloody-knife.png';
                $productImage2->Title = 'bloody-knife';
                $productImage2->Filename = 'assets/Uploads/bloody-knife.png';
                $productImage2->ParentID = $uploadfolder->ID;
                $productImage2->OwnerID = Member::currentUserID();
                $productImage2->write();
            }
            $product2->ImageID = $productImage2->ID;
            $product2->Amount->Amount = '19.99';
            $product2->Amount->Currency = 'NZD';
            $product2->write();
            DB::alteration_message('product example \'Blood Knife\'', 'created');
        }
    }
Exemplo n.º 2
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;
 }
Exemplo 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;
 }
 public function loadModel($id)
 {
     if (($model = ProductImage::model()->findByPk($id)) === null) {
         throw new CHttpException(404, 'Страница не найдена');
     }
     return $model;
 }
Exemplo n.º 5
0
 public function run()
 {
     ProductImage::truncate();
     $image = array('lib/images/products/product-gallery-01.jpg', 'lib/images/products/product-gallery-02.png', 'lib/images/products/product-gallery-03.jpg', 'lib/images/products/product-gallery-04.jpg');
     $image_thumb = array('lib/images/products/gallery-thumb-01.jpg', 'lib/images/products/gallery-thumb-02.jpg', 'lib/images/products/gallery-thumb-03.jpg', 'lib/images/products/gallery-thumb-04.jpg');
     for ($i = 1; $i <= 30; $i++) {
         for ($j = 0; $j < 4; $j++) {
             ProductImage::create(array('image' => $image[$j], 'image_small' => $image_thumb[$j], 'product_id' => $i));
         }
     }
 }
 public function actionDeleteImage()
 {
     if (Yii::app()->getRequest()->getIsPostRequest() && Yii::app()->getRequest()->getIsAjaxRequest()) {
         $id = (int) Yii::app()->getRequest()->getPost('id');
         $model = ProductImage::model()->findByPk($id);
         if (null !== $model) {
             $model->delete();
             Yii::app()->ajax->success();
         }
     }
     throw new CHttpException(404);
 }
Exemplo n.º 7
0
 public static function getImageSizes()
 {
     if (!self::$imageSizes) {
         $config = self::getApplication()->getConfig();
         $sizes = array();
         $k = 0;
         while ($config->isValueSet('IMG_P_W_' . ++$k)) {
             $sizes[$k] = array($config->get('IMG_P_W_' . $k), $config->get('IMG_P_H_' . $k));
         }
         self::$imageSizes = $sizes;
     }
     return self::$imageSizes;
 }
Exemplo n.º 8
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;
             }
         }
     }
 }
 public function run()
 {
     ProductImage::create(['product_id' => '1', 'image_url' => '01.jpg']);
     ProductImage::create(['product_id' => '1', 'image_url' => '02.jpg']);
     ProductImage::create(['product_id' => '1', 'image_url' => '03.jpg']);
     ProductImage::create(['product_id' => '2', 'image_url' => '11.jpg']);
     ProductImage::create(['product_id' => '3', 'image_url' => '21.jpg']);
     ProductImage::create(['product_id' => '4', 'image_url' => '31.jpg']);
     ProductImage::create(['product_id' => '5', 'image_url' => '41.jpg']);
     ProductImage::create(['product_id' => '6', 'image_url' => '51.jpg']);
     ProductImage::create(['product_id' => '7', 'image_url' => '61.jpg']);
     ProductImage::create(['product_id' => '8', 'image_url' => '71.jpg']);
     ProductImage::create(['product_id' => '9', 'image_url' => '81.jpg']);
     ProductImage::create(['product_id' => '10', 'image_url' => '91.jpg']);
 }
Exemplo n.º 10
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index($id)
 {
     $input = Input::all();
     $product = Product::find($id);
     $data = null;
     if (isset($product)) {
         if ($input['user_id'] == $product->user_id || $product->status == ACTIVE) {
             $images = ProductImage::where('product_id', $id)->get();
             foreach ($images as $key => $value) {
                 $value->image_url = url(PRODUCT_UPLOAD . '/' . $product->user_id . '/' . $value->image_url);
             }
             $data = array('id' => $id, 'phone' => User::find($product->user_id)->phone, 'name' => $product->name, 'description' => $product->description, 'avatar' => url(PRODUCT_UPLOAD . '/' . $product->user_id . '/' . $product->avatar), 'category_id' => $product->category_id, 'category_name' => Category::find($product->category_id)->name, 'type_id' => $product->type_id, 'type_name' => getProductType($product->type_id), 'price' => getFullPriceInVnd($product->price) . ' đ', 'address' => $product->address, 'city' => $product->city, 'city_id' => $product->city_id, 'lat' => $product->lat, 'long' => $product->long, 'position' => $product->position, 'status' => $product->status, 'status_name' => getProductStatus($product->status), 'start_time' => date('d-m-Y H:i', strtotime($product->start_time)), 'user_id' => $product->user_id, 'user_name' => User::find($product->user_id)->username, 'user_avatar' => url(USER_AVATAR . '/' . $product->user_id . '/' . User::find($product->user_id)->avatar), 'image_list' => $images, 'block' => Common::checkBlackList($input['user_id'], $product->user_id), 'favorite' => CommonFavorite::checkFavoriteLike('User', $product->user_id, TYPE_FAVORITE_LIKE, $input['user_id']), 'product_saved' => CommonProduct::checkProductSaved($product->id, $input['user_id']));
         }
     }
     return Common::returnData(200, SUCCESS, $input['user_id'], $input['session_id'], $data);
 }
Exemplo n.º 11
0
 public function post()
 {
     $input = Input::all();
     $sessionId = Common::checkSessionLogin($input);
     //check user active
     $checkUser = User::find($input['user_id'])->status;
     if (isset($checkUser) && $checkUser == INACTIVE) {
         throw new Prototype\Exceptions\UserStatusErrorException();
     }
     // create product
     $inputSubmit = ['name' => $input['name'], 'user_id' => $input['user_id'], 'category_id' => $input['category_id'], 'type_id' => $input['type_id'], 'price_id' => CommonProduct::getPriceId($input['price']), 'price' => $input['price'], 'lat' => $input['lat'], 'long' => $input['long'], 'description' => $input['description'], 'avatar' => $input['avatar'], 'address' => $input['address'], 'city_id' => $input['city_id'], 'city' => Common::getModelField($input['city_id'], 'City', 'name'), 'position' => 1, 'status' => INACTIVE, 'start_time' => Carbon\Carbon::now()];
     $id = Product::create($inputSubmit)->id;
     // images product
     if (isset($input['image_url']) && count($input['image_url']) > 0) {
         foreach ($input['image_url'] as $key => $value) {
             $inputImage = array('product_id' => $id, 'image_url' => $value);
             ProductImage::create($inputImage);
         }
     }
     return Common::returnData(200, SUCCESS, $input['user_id'], $sessionId);
 }
Exemplo n.º 12
0
<?php

// check if value was posted
if ($_POST) {
    // include classes
    include_once '../config/database.php';
    include_once '../objects/product.php';
    include_once '../objects/product_image.php';
    include_once '../objects/product_pdf.php';
    // get database connection
    $database = new Database();
    $db = $database->getConnection();
    // initialize objects
    $product = new Product($db);
    $productImage = new ProductImage($db);
    $productPdf = new ProductPdf($db);
    // set product id to be deleted
    $product_id = $_POST['object_id'];
    // delete the product
    $product->id = $product_id;
    if ($product->delete()) {
        // delete all related images in database & directory
        $productImage->product_id = $product_id;
        $productImage->deleteAll();
        // delete all related pdf in database & directory
        $productPdf->product_id = $product_id;
        $productPdf->deleteAll();
        echo "Object was deleted.";
    } else {
        echo "Unable to delete object.";
    }
Exemplo n.º 13
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getProductImages()
 {
     return $this->hasMany(ProductImage::className(), ['product_id' => 'id']);
 }
Exemplo n.º 14
0
	/**
	 * Loads a list of products for the category
	 * 
	 * @since 1.0
	 * @version 1.1
	 *
	 * @param array $loading Loading options for the category
	 * @return void
	 **/
	function load_products ($loading=false) {
		global $Ecart,$wp;
		$db = DB::get();

		$catalogtable = DatabaseObject::tablename(Catalog::$table);
		$producttable = DatabaseObject::tablename(Product::$table);
		$pricetable = DatabaseObject::tablename(Price::$table);
		$discounttable = DatabaseObject::tablename(Discount::$table);
		$promotable = DatabaseObject::tablename(Promotion::$table);
		$imagetable = DatabaseObject::tablename(ProductImage::$table);

		$this->paged = false;
		$this->pagination = $Ecart->Settings->get('catalog_pagination');
		$this->page = (get_query_var('paged') > 0)?get_query_var('paged'):1;

		if (empty($this->page)) $this->page = 1;

		$limit = 1000; // Hard product limit per category to keep resources "reasonable"

		if (!$loading) $loading = $this->loading;
		else $loading = array_merge($this->loading,$loading);

		if (!empty($loading['columns'])) $loading['columns'] = ", ".$loading['columns'];
		else $loading['columns'] = '';

		// Allow override for loading unpublished products
		if (isset($loading['published'])) $this->published = value_is_true($loading['published']);

		$where = array();
		if (!empty($loading['where'])) $where[] = "({$loading['where']})";

		$having = array();
		if (!empty($loading['having'])) $having[] = "({$loading['having']})";

		// Handle default WHERE clause matching this category id
		if (empty($loading['where']) && !empty($this->id))
			$where[] = "p.id in (SELECT product FROM $catalogtable WHERE (parent=$this->id AND type='category'))";

		if (!isset($loading['nostock']) && ($Ecart->Settings->get('outofstock_catalog') == "off"))
			$where[] = "p.id in (SELECT product FROM $pricetable WHERE type != 'N/A' AND inventory='off' OR (inventory='on' AND stock > 0))";
		else $where[] = "p.id in (SELECT product FROM $pricetable WHERE type != 'N/A')";

		if (!isset($loading['joins'])) $loading['joins'] = '';
		if (!empty($Ecart->Flow->Controller->browsing[$this->slug])) {
			$spectable = DatabaseObject::tablename(Spec::$table);

			$f = 1;
			$filters = "";
			foreach ($Ecart->Flow->Controller->browsing[$this->slug] as $facet => $value) {
				if (empty($value)) continue;
				$specalias = "spec".($f++);

				// Handle Number Range filtering
				$match = "";
				if (!is_array($value) &&
						preg_match('/^.*?(\d+[\.\,\d]*).*?\-.*?(\d+[\.\,\d]*).*$/',$value,$matches)) {
					if ($facet == "Price") { // Prices require complex matching on price line entries
						$min = floatvalue($matches[1]);
						$max = floatvalue($matches[2]);
						if ($matches[1] > 0) $match .= " ((onsale=0 AND (minprice >= $min OR maxprice >= $min)) OR (onsale=1 AND (minsaleprice >= $min OR maxsaleprice >= $min)))";
						if ($matches[2] > 0) $match .= (empty($match)?"":" AND ")." ((onsale=0 AND (minprice <= $max OR maxprice <= $max)) OR (onsale=1 AND (minsaleprice <= $max OR maxsaleprice <= $max)))";
					} else { // Spec-based numbers are somewhat more straightforward
						if ($matches[1] > 0) $match .= "$specalias.numeral >= {$matches[1]}";
						if ($matches[2] > 0) $match .= (empty($match)?"":" AND ")."$specalias.numeral <= {$matches[2]}";
					}
				} else $match = "$specalias.value='$value'"; // No range, direct value match

				// Use HAVING clause for filtering by pricing information
				// because of data aggregation
				if ($facet == "Price") {
					$having[] = $match;
					continue;
				}

				$loading['joins'] .= " LEFT JOIN $spectable AS $specalias ON $specalias.parent=p.id AND $specalias.context='product' AND $specalias.type='spec' AND $specalias.name='$facet'";
				$filters .= (empty($filters))?$match:" AND ".$match;
			}
			if (!empty($filters)) $where[] = $filters;

		}

		// WP TZ setting based time - (timezone offset:[PHP UTC adjusted time - MySQL UTC adjusted time])
		$now = time()."-(".(time()-date("Z",time()))."-UNIX_TIMESTAMP(UTC_TIMESTAMP()))";

		if ($this->published) $where[] = "(p.status='publish' AND $now >= UNIX_TIMESTAMP(p.publish))";
		else $where[] = "(p.status!='publish' OR $now < UNIX_TIMESTAMP(p.publish))";

		$defaultOrder = $Ecart->Settings->get('default_product_order');
		if (empty($defaultOrder)) $defaultOrder = "";
		$ordering = isset($Ecart->Flow->Controller->browsing['orderby'])?
						$Ecart->Flow->Controller->browsing['orderby']:$defaultOrder;
		if (!empty($loading['order'])) $ordering = $loading['order'];
		switch ($ordering) {
			case "bestselling":
				$purchasedtable = DatabaseObject::tablename(Purchased::$table);
				$loading['columns'] .= ',count(DISTINCT pur.id) AS sold';
				$loading['joins'] .= " LEFT JOIN $purchasedtable AS pur ON p.id=pur.product";
				$loading['order'] = "sold DESC,p.name ASC";
				break;
			case "highprice": $loading['order'] = "highprice DESC"; break;
			case "lowprice": $loading['order'] = "lowprice ASC"; break;
			case "newest": $loading['order'] = "p.publish DESC,p.name ASC"; break;
			case "oldest": $loading['order'] = "p.publish ASC,p.name ASC"; break;
			case "random": $loading['order'] = "RAND(".crc32($Ecart->Shopping->session).")"; break;
			case "title": $loading['order'] = "p.name ASC"; break;
			default:
				// Need to add the catalog table for access to category-product priorities
				if (!isset($this->smart)) {
					$loading['joins'] .= " LEFT JOIN $catalogtable AS c ON c.product=p.id AND c.parent = '$this->id'";
					$loading['order'] = "c.priority ASC,p.name ASC";
				} else $loading['order'] = "p.name ASC";
				break;
		}
		if (!empty($loading['orderby'])) $loading['order'] = $loading['orderby'];

		if (isset($loading['adjacent']) && isset($loading['product'])) {

			$product = $loading['product'];
			$field = substr($loading['order'],0,strpos($loading['order'],' '));
			$op = $loading['adjacent'] != "next"?'<':'>';

			// Flip the sort order for previous
			if ($op == '<') {
				$loading['order'] = str_replace(array('ASC','DESC'),array('DSC','ACE'),$loading['order']);
				$loading['order'] = str_replace(array('DSC','ACE'),array('DESC','ASC'),$loading['order']);
			}

			switch ($field) {
				case "sold":
					if ($product->sold() == 0) {
						$field = 'p.name';
						$target = "'".$db->escape($product->name)."'";
					} else $target = $product->sold();
					$where[] = "$field $op $target";
					break;
				case "highprice":
					if (empty($product->prices)) $product->load_data(array('prices'));
					$target = !empty($product->max['saleprice'])?$product->max['saleprice']:$product->max['price'];
					$where[] = "$target $op IF (pd.sale='on' OR pr.discount>0,pd.saleprice,pd.price) AND p.id != $product->id";
					break;
				case "lowprice":
					if (empty($product->prices)) $product->load_data(array('prices'));
					$target = !empty($product->max['saleprice'])?$product->max['saleprice']:$product->max['price'];
					$where[] = "$target $op= IF (pd.sale='on' OR pr.discount>0,pd.saleprice,pd.price) AND p.id != $product->id";
					break;
				case "p.name": $where[] = "$field $op '".$db->escape($product->name)."'"; break;
				default:
					if ($product->priority == 0) {
						$field = 'p.name';
						$target = "'".$db->escape($product->name)."'";
					} else $target = $product->priority;
					$where[] = "$field $op $target";
					break;
			}

		}

		if (!empty($having)) $loading['having'] = "HAVING ".join(" AND ",$having);
		else $loading['having'] = '';
		$loading['where'] = join(" AND ",$where);

		if (empty($loading['limit'])) {
			if ($this->pagination > 0 && is_numeric($this->page)) {
				if( !$this->pagination || $this->pagination < 0 )
					$this->pagination = $limit;
				$start = ($this->pagination * ($this->page-1));

				$loading['limit'] = "$start,$this->pagination";
			} else $loading['limit'] = $limit;
		} else $limit = (int)$loading['limit'];

		$columns = "p.*,
					img.id AS image,img.value AS imgmeta,MAX(pr.status) as promos,
					SUM(DISTINCT IF(pr.type='Percentage Off',pr.discount,0))AS percentoff,
					SUM(DISTINCT IF(pr.type='Amount Off',pr.discount,0)) AS amountoff,
					if (pr.type='Free Shipping',1,0) AS freeshipping,
					if (pr.type='Buy X Get Y Free',pr.buyqty,0) AS buyqty,
					if (pr.type='Buy X Get Y Free',pr.getqty,0) AS getqty,
					MAX(pd.price) AS maxprice,MIN(pd.price) AS minprice,
					IF(pd.sale='on',1,IF (pr.discount > 0,1,0)) AS onsale,
					MAX(pd.saleprice) as maxsaleprice,MIN(pd.saleprice) AS minsaleprice,
					IF (pd.sale='on' AND MIN(pd.saleprice) > 0,MIN(pd.saleprice),MIN(pd.price)) AS lowprice,
					IF (pd.sale='on' AND MIN(pd.saleprice) > 0,MAX(pd.saleprice),MAX(pd.price)) AS highprice,
					IF(pd.inventory='on',1,0) AS inventory,
					SUM(pd.stock) as stock";

		// Query without promotions for MySQL servers prior to 5
		if (version_compare($db->mysql,'5.0','<')) {
			$columns = "p.*,
						img.id AS image,img.value AS imgmeta,
						MAX(pd.price) AS maxprice,MIN(pd.price) AS minprice,
						IF(pd.sale='on',1,0) AS onsale,
						MAX(pd.saleprice) as maxsaleprice,MIN(pd.saleprice) AS minsaleprice,
						IF(pd.inventory='on',1,0) AS inventory,
						SUM(pd.stock) as stock";
		}

		// Handle alphabetic page requests
		if ((!isset($Ecart->Category->controls) ||
				(isset($Ecart->Category->controls) && $Ecart->Category->controls !== false)) &&
				((isset($loading['pagination']) && $loading['pagination'] == "alpha") ||
				!is_numeric($this->page))) {

			$alphanav = range('A','Z');

			$ac = "SELECT count(DISTINCT p.id) AS total,IF(LEFT(p.name,1) REGEXP '[0-9]',LEFT(p.name,1),LEFT(SOUNDEX(p.name),1)) AS letter,AVG(IF(pd.sale='on',pd.saleprice,pd.price)) as avgprice
						FROM $producttable AS p
						LEFT JOIN $pricetable AS pd ON pd.product=p.id AND pd.type != 'N/A'
						LEFT JOIN $discounttable AS dc ON dc.product=p.id AND dc.price=pd.id
						LEFT JOIN $promotable AS pr ON pr.id=dc.promo
						LEFT JOIN $imagetable AS img ON img.parent=p.id AND img.context='product' AND img.type='image' AND img.sortorder=0
						{$loading['joins']}
						WHERE {$loading['where']}
						GROUP BY letter";
			$alpha = $db->query($ac);

			$existing = current($alpha);
			if (!isset($this->alpha['0-9'])) {
				$this->alpha['0-9'] = new stdClass();
				$this->alpha['0-9']->letter = '0-9';
				$this->alpha['0-9']->total = 0;
				$this->alpha['0-9']->avg = 0;
			}
			while (is_numeric($existing->letter)) {
				$this->alpha['0-9']->total += $existing->total;
				$this->alpha['0-9']->avg = ($this->alpha['0-9']->avg+$existing->avg)/2;
				$this->alpha['0-9']->letter = '0-9';
				$existing = next($alpha);
			}

			foreach ($alphanav as $letter) {
				if ($existing->letter == $letter) {
					$this->alpha[$letter] = $existing;
					$existing = next($alpha);
				} else {
					$entry = new stdClass();
					$entry->letter = $letter;
					$entry->total = 0;
					$entry->avg = 0;
					$this->alpha[$letter] = $entry;
				}
			}
			$this->paged = true;
			if (!is_numeric($this->page)) {
				$alphafilter = $this->page == "0-9"?
					"(LEFT(p.name,1) REGEXP '[0-9]') = 1":
					"IF(LEFT(p.name,1) REGEXP '[0-9]',LEFT(p.name,1),LEFT(SOUNDEX(p.name),1))='$this->page'";
				$loading['where'] .= (empty($loading['where'])?"":" AND ").$alphafilter;
			}

		}

		$query = "SELECT SQL_CALC_FOUND_ROWS $columns{$loading['columns']}
					FROM $producttable AS p
					LEFT JOIN $pricetable AS pd ON pd.product=p.id AND pd.type != 'N/A'
					LEFT JOIN $discounttable AS dc ON dc.product=p.id AND dc.price=pd.id
					LEFT JOIN $promotable AS pr ON pr.id=dc.promo
					LEFT JOIN $imagetable AS img ON img.parent=p.id AND img.context='product' AND img.type='image' AND img.sortorder=0
					{$loading['joins']}
					WHERE {$loading['where']}
					GROUP BY p.id {$loading['having']}
					ORDER BY {$loading['order']}
					LIMIT {$loading['limit']}";

		// Execute the main category products query
		$products = $db->query($query,AS_ARRAY);

		$total = $db->query("SELECT FOUND_ROWS() as count");
		$this->total = $total->count;

		if ($this->pagination > 0 && $limit > $this->pagination) {
			$this->pages = ceil($this->total / $this->pagination);
			if ($this->pages > 1) $this->paged = true;
		}

		// if ($this->pagination == 0 || $limit < $this->pagination)
		// 	$this->total = count($this->products);

		$this->pricing['min'] = 0;
		$this->pricing['max'] = 0;

		$prices = array();
		foreach ($products as $i => &$product) {
			if ($product->maxsaleprice == 0) $product->maxsaleprice = $product->maxprice;
			if ($product->minsaleprice == 0) $product->minsaleprice = $product->minprice;

			$prices[] = $product->onsale?$product->minsaleprice:$product->minprice;

			if (!empty($product->percentoff)) {
				$product->maxsaleprice = $product->maxsaleprice - ($product->maxsaleprice * ($product->percentoff/100));
				$product->minsaleprice = $product->minsaleprice - ($product->minsaleprice * ($product->percentoff/100));
			}

			if (!empty($product->amountoff)) {
				$product->maxsaleprice = $product->maxsaleprice - $product->amountoff;
				$product->minsaleprice = $product->minsaleprice - $product->amountoff;
			}

			$this->pricing['max'] = max($this->pricing['max'],$product->maxsaleprice);
			$this->pricing['min'] = min($this->pricing['min'],$product->minsaleprice);

			$this->products[$product->id] = new Product();
			$this->products[$product->id]->populate($product);

			if (isset($product->score))
				$this->products[$product->id]->score = $product->score;

			// Special property for Bestseller category
			if (isset($product->sold) && $product->sold)
				$this->products[$product->id]->sold = $product->sold;

			// Special property Promotions
			if (isset($product->promos))
				$this->products[$product->id]->promos = $product->promos;

			if (!empty($product->image)) {
				$image = new ProductImage();
				$image->id = $product->image;
				$image->value = unserialize($product->imgmeta);
				$image->expopulate();
				$this->products[$product->id]->images = array($image);
			}

		}
		$this->pricing['average'] = 0;
		if (count($prices) > 0) $this->pricing['average'] = array_sum($prices)/count($prices);

		if (!isset($loading['load'])) $loading['load'] = array('prices');

		if (count($this->products) > 0) {
			$Processing = new Product();
			$Processing->load_data($loading['load'],$this->products);
		}

		$this->loaded = true;

	}
Exemplo n.º 15
0
 public function getPrintableOrderItemsArray()
 {
     $dataProvider = new CActiveDataProvider('OrderHasProduct', array('criteria' => array('condition' => 'order_id=' . $this->id, 'with' => array('product')), 'pagination' => false));
     $output_array = array();
     foreach ($dataProvider->getData() as $item) {
         $cartitem = array('quantity' => $item->quantity, 'price_paid' => $item->price_paid, 'product_id' => $item->product_id);
         $product = $item->product;
         $localization = $product->localizationForLanguage(Yii::app()->language, $accept_substitute = true);
         $image = $localization->getMainImage();
         $cartitem['name'] = $localization->name;
         $cartitem['slug'] = $localization->slug;
         $cartitem['thumbnail'] = $image ? $image->getImageURL(50, 50) : ProductImage::placehoderForSize(50, 50);
         $cartitem['thumbnail_lg'] = $image ? $image->getImageURL(120, 160) : ProductImage::placehoderForSize(120, 160);
         $cartitem['link'] = Yii::app()->createUrl('product/view', array('slug' => $localization->slug));
         $output_array[] = $cartitem;
     }
     return $output_array;
 }
Exemplo n.º 16
0
 public function uploadProductImage()
 {
     ClassLoader::import('application.model.product.ProductImage');
     ClassLoader::import('library.image.ImageManipulator');
     $field = 'upload_' . $this->request->get('field');
     $dir = ClassLoader::getRealPath('public.upload.tmpimage.');
     // delete old tmp files
     chdir($dir);
     $dh = opendir($dir);
     $threshold = strtotime("-1 day");
     while (($dirent = readdir($dh)) != false) {
         if (is_file($dirent)) {
             if (filemtime($dirent) < $threshold) {
                 unlink($dirent);
             }
         }
     }
     closedir($dh);
     // create tmp file
     $file = $_FILES[$field];
     $tmp = 'tmp_' . $field . md5($file['tmp_name']) . '__' . $file['name'];
     if (!file_exists($dir)) {
         mkdir($dir, 0777, true);
         chmod($dir, 0777);
     }
     $path = $dir . $tmp;
     move_uploaded_file($file['tmp_name'], $path);
     if (@getimagesize($path)) {
         $thumb = 'tmp_thumb_' . $tmp;
         $thumbPath = $dir . $thumb;
         $thumbDir = dirname($thumbPath);
         if (!file_exists($thumbDir)) {
             mkdir($thumbDir, 0777, true);
             chmod($thumbDir, 0777);
         }
         $conf = self::getApplication()->getConfig();
         $img = new ImageManipulator($path);
         $thumbSize = ProductImage::getImageSizes();
         $thumbSize = $thumbSize[2];
         // 1 is too small, cant see a thing.
         $img->resize($thumbSize[0], $thumbSize[1], $thumbPath);
         $thumb = 'upload/tmpimage/' . $thumb;
     } else {
         return new JSONResponse(null, 'failure', $this->translate('_error_uploading_image'));
     }
     return new JSONResponse(array('name' => $file['name'], 'file' => $tmp, 'thumb' => $thumb), 'success');
 }
Exemplo n.º 17
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();
		}

	}
Exemplo n.º 18
0
// import page header HTML
include_once "layout_head.php";
// read products button
echo "<div class='right-button-margin'>";
echo "<a href='read_products.php' class='btn btn-primary pull-right'>";
echo "<span class='glyphicon glyphicon-list'></span> Read Products";
echo "</a>";
echo "</div>";
// if the form was submitted
if ($_POST) {
    // instantiate product object
    include_once '../objects/product.php';
    include_once '../objects/product_image.php';
    include_once '../objects/product_pdf.php';
    $product = new Product($db);
    $productImage = new ProductImage($db);
    $productPdf = new ProductPdf($db);
    // set product property values
    $product->name = $_POST['name'];
    $product->price = $_POST['price'];
    $product->description = $_POST['description'];
    $product->category_id = $_POST['category_id'];
    $product->active_until = $_POST['active_until'];
    // create the product
    if ($product->create()) {
        // get last inserted id
        $product_id = $db->lastInsertId();
        // save the images
        $productImage->product_id = $product_id;
        $productImage->upload();
        // save the pdf files
Exemplo n.º 19
0
 public function afterDelete()
 {
     // delete dependencies
     ProductAttribute::model()->deleteAll("product_id={$this->cacheId}");
     ProductDescription::model()->deleteAll("product_id={$this->cacheId}");
     ProductDiscount::model()->deleteAll("product_id={$this->cacheId}");
     ProductFilter::model()->deleteAll("product_id={$this->cacheId}");
     ProductImage::model()->deleteAll("product_id={$this->cacheId}");
     ProductOption::model()->deleteAll("product_id={$this->cacheId}");
     ProductOptionValue::model()->deleteAll("product_id={$this->cacheId}");
     ProductRelated::model()->deleteAll("product_id={$this->cacheId}");
     ProductRelated::model()->deleteAll("related_id={$this->cacheId}");
     ProductReward::model()->deleteAll("product_id={$this->cacheId}");
     ProductSpecial::model()->deleteAll("product_id={$this->cacheId}");
     ProductToCategory::model()->deleteAll("product_id={$this->cacheId}");
     ProductToDownload::model()->deleteAll("product_id={$this->cacheId}");
     ProductToLayout::model()->deleteAll("product_id={$this->cacheId}");
     ProductToStore::model()->deleteAll("product_id={$this->cacheId}");
     Review::model()->deleteAll("product_id={$this->cacheId}");
     UrlAlias::model()->deleteAll("query='product_id={$this->cacheId}'");
     parent::afterDelete();
 }
Exemplo n.º 20
0
    $mainImage = $localization->getMainImage();
    if ($mainImage) {
        echo $mainImage->getImageURL(300, 280);
    } else {
        echo ProductImage::placehoderForSize(300, 280);
    }
    ?>
" alt="<?php 
    echo $localization->name;
    ?>
" class="img-responsive center-block hidden-xs hidden-sm">
				<img alt="" src="<?php 
    if ($mainImage) {
        echo $mainImage->getImageURL(600, 560);
    } else {
        echo ProductImage::placehoderForSize(600, 560);
    }
    ?>
" alt="<?php 
    echo $localization->name;
    ?>
" class="img-responsive center-block visible-xs-block visible-sm-block">
						</a>
            <?php 
    $brand = $product->brand;
    if ($brand) {
        ?>
<span class="date-over"><strong><?php 
        $brand_localization = $brand->localizationForLanguage(Yii::app()->language, $accept_substitute = true);
        echo CHtml::link($brand_localization->name, $this->createUrl("category/view", array("slug" => $brand_localization->slug)));
        ?>
Exemplo n.º 21
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();
     }
 }
Exemplo n.º 22
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));
	}
Exemplo n.º 23
0
 public function save()
 {
     ActiveRecordModel::beginTransaction();
     $parent = Product::getInstanceByID($this->request->get('id'), true);
     $items = json_decode($this->request->get('items'), true);
     $types = json_decode($this->request->get('types'), true);
     $variations = json_decode($this->request->get('variations'), true);
     $existingTypes = $existingVariations = $existingItems = array();
     $currency = $this->application->getDefaultCurrencyCode();
     // deleted types
     foreach ($types as $id) {
         if (is_numeric($id)) {
             $existingTypes[] = $id;
         }
     }
     $parent->deleteRelatedRecordSet('ProductVariationType', new ARDeleteFilter(new NotINCond(new ARFieldHandle('ProductVariationType', 'ID'), $existingTypes)));
     // deleted variations
     foreach ($variations as $type => $typeVars) {
         foreach ($typeVars as $id) {
             if (is_numeric($id)) {
                 $existingVariations[] = $id;
             }
         }
     }
     $f = new ARDeleteFilter(new INCond(new ARFieldHandle('ProductVariation', 'typeID'), $existingTypes));
     $f->mergeCondition(new NotINCond(new ARFieldHandle('ProductVariation', 'ID'), $existingVariations));
     ActiveRecordModel::deleteRecordSet('ProductVariation', $f);
     // deleted items
     foreach ($items as $id) {
         if (is_numeric($id)) {
             $existingItems[] = $id;
         }
     }
     $parent->deleteRelatedRecordSet('Product', new ARDeleteFilter(new NotINCond(new ARFieldHandle('Product', 'ID'), $existingItems)));
     // load existing records
     foreach (array('Types' => 'ProductVariationType', 'Variations' => 'ProductVariation', 'Items' => 'Product') as $arr => $class) {
         $var = 'existing' . $arr;
         $array = ${$var};
         if ($array) {
             ActiveRecordModel::getRecordSet($class, new ARSelectFilter(new INCond(new ARFieldHandle($class, 'ID'), $array)));
         }
     }
     $idMap = array();
     // save types
     $request = $this->request->toArray();
     foreach ($types as $index => $id) {
         if (!is_numeric($id)) {
             $type = ProductVariationType::getNewInstance($parent);
             $idMap[$id] = $type;
         } else {
             $type = ActiveRecordModel::getInstanceByID('ProductVariationType', $id);
         }
         $type->setValueByLang('name', null, $request['variationType'][$index]);
         $type->position->set($index);
         if (!empty($request['typeLang_' . $id])) {
             foreach ($request['typeLang_' . $id] as $field => $value) {
                 list($field, $lang) = explode('_', $field, 2);
                 $type->setValueByLang($field, $lang, $value);
             }
         }
         $type->save();
     }
     // save variations
     $tree = array();
     $typeIndex = -1;
     foreach ($variations as $typeID => $typeVars) {
         $type = is_numeric($typeID) ? ActiveRecordModel::getInstanceByID('ProductVariationType', $typeID) : $idMap[$typeID];
         $typeIndex++;
         foreach ($typeVars as $index => $id) {
             if (!is_numeric($id)) {
                 $variation = ProductVariation::getNewInstance($type);
                 $idMap[$id] = $variation;
             } else {
                 $variation = ActiveRecordModel::getInstanceByID('ProductVariation', $id);
             }
             $variation->position->set($index);
             $variation->setValueByLang('name', null, $request['variation'][$id]);
             if (!empty($request['variationLang_' . $id])) {
                 foreach ($request['variationLang_' . $id] as $field => $value) {
                     list($field, $lang) = explode('_', $field, 2);
                     $variation->setValueByLang($field, $lang, $value);
                 }
             }
             $variation->save();
             $tree[$typeIndex][] = $variation;
         }
     }
     $images = array();
     // save items
     foreach ($items as $index => $id) {
         if (!is_numeric($id)) {
             $item = $parent->createChildProduct();
             $idMap[$id] = $item;
         } else {
             $item = ActiveRecordModel::getInstanceByID('Product', $id);
         }
         $item->isEnabled->set(!empty($request['isEnabled'][$id]));
         if (!$request['sku'][$index]) {
             $request['sku'][$index] = $item->sku->get();
         }
         foreach (array('sku', 'stockCount', 'shippingWeight') as $field) {
             if ($item->{$field}->get() || $request[$field][$index]) {
                 $item->{$field}->set($request[$field][$index]);
             }
         }
         $item->setChildSetting('weight', $request['shippingWeightType'][$index]);
         $item->setChildSetting('price', $request['priceType'][$index]);
         if (!strlen($request['priceType'][$index])) {
             $request['price'][$index] = '';
         }
         $item->setPrice($currency, $request['price'][$index]);
         $item->save();
         // assign variations
         $currentVariationValues = $currentVariations = array();
         foreach ($item->getRelatedRecordSet('ProductVariationValue') as $variationValue) {
             $currentVariations[$variationValue->variation->get()->getID()] = $variationValue->variation->get();
             $currentVariationValues[$variationValue->variation->get()->getID()] = $variationValue;
         }
         foreach ($this->getItemVariations($tree, $index) as $variation) {
             if (!isset($currentVariations[$variation->getID()])) {
                 ProductVariationValue::getNewInstance($item, $variation)->save();
             }
             unset($currentVariations[$variation->getID()]);
         }
         foreach ($currentVariations as $deletedVariation) {
             $currentVariationValues[$deletedVariation->getID()]->delete();
         }
         // set image
         if ($_FILES['image']['tmp_name'][$index]) {
             if ($item->defaultImage->get()) {
                 $item->defaultImage->get()->load();
                 $image = $item->defaultImage->get();
             } else {
                 $image = ProductImage::getNewInstance($item);
             }
             $image->save();
             $image->setFile($_FILES['image']['tmp_name'][$index]);
             $image->save();
             $images[$item->getID()] = $image->toArray();
             unset($images[$item->getID()]['Product']);
         }
     }
     ActiveRecordModel::commit();
     // pass ID's for newly created records
     $ids = array();
     foreach ($idMap as $id => $instance) {
         $ids[$id] = $instance->getID();
     }
     $response = new ActionResponse('ids', $ids);
     $response->set('parent', $parent->getID());
     $response->set('images', $images);
     $response->set('variationCount', $parent->getRelatedRecordCount('Product', new ARSelectFilter(new EqualsCond(new ARFieldHandle('Product', 'isEnabled'), true))));
     return $response;
 }
Exemplo n.º 24
0
<?php

require_once __DIR__ . '/../common/autoload_cms.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entity = new ProductImage();
    $entity->setName($_POST['name'])->setProductId($_GET['product_id'])->setDateAdded(date('Y-m-d H:i:s'))->saveImage($_FILES['image']);
    $productImageCollection = new ProductImageCollection();
    $productImageCollection->save($entity);
    header('Location: product_image_list.php?product_id=' . $_GET['product_id']);
    exit;
}
require_once 'include/header.php';
?>

<div class="container">
    <form method="post" action="" enctype="multipart/form-data">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" class="form-control">
        </div>

        <div class="form-group">
            <label for="image">Image:</label>
            <input type="file" name="image" id="image" class="form-control">
        </div>

        <button type="submit" class="btn btn-default">Submit</button>
    </form>
</div>

<?php 
Exemplo n.º 25
0
 /**
  * Currently reduced products
  * When the output is set to iframe, styling will be added so the layout is self contained.
  */
 public function actionRebates($format = "html", $limit = 4, $offset = 0, $background = "default", $version = 1, $pretty = 0)
 {
     if (!is_numeric($limit) || !is_numeric($offset) || !is_numeric($version) || !is_numeric($pretty)) {
         throw new CHttpException(400, 'A numeric value was expected.');
     }
     if ($limit > 32 || $offset > 32) {
         throw new CHttpException(400, 'Offset and limit can\'t be larger than 32. If you need to retrieve a large amount of products efficiently, please refer to Boukem\'s API documentation.');
     }
     $cache_id = "WidgetController:[promotionsForLanguage] " . md5(Yii::app()->language . CHtml::encode($background) . CHtml::encode($format) . " " . $limit . " " . $offset);
     $cache_duration = 120;
     //10800;
     $content = Yii::app()->cache->get($cache_id);
     if (!$content) {
         $rebatesDataProvider = new CActiveDataProvider('ProductRebate', array('criteria' => array('order' => "valid_until", 'limit' => $limit, 'offset' => $offset, 'with' => array('product', 'product.productLocalization')), 'pagination' => false));
         if ($format === "html") {
             if ($background != "transparent" && $background != "default") {
                 $background = $this->validate_html_color($background);
             }
             $content = $this->renderPartial('_rebates', array('rebates' => $rebatesDataProvider, "background" => $background), true);
         } else {
             if ($format === "json") {
                 $content = array();
                 foreach ($rebatesDataProvider->getData() as $rebate) {
                     $product = $rebate->product;
                     $localization = $product->localizationForLanguage(Yii::app()->language, $accept_substitute = false);
                     if ($product && $localization && $product->visible && !$product->discontinued) {
                         $product_url = $this->createAbsoluteUrl("product/view", array('slug' => $localization->slug));
                         $currentPrice = $product->getCurrentPrice();
                         $regularPrice = $product->price;
                         if ($currentPrice == $regularPrice) {
                             $isOnSale = false;
                             $rebatePercent = 0;
                         } else {
                             $isOnSale = true;
                             $rebatePercent = round(($regularPrice - $currentPrice) / $regularPrice * 100, $precision = 0, $mode = PHP_ROUND_HALF_DOWN);
                         }
                         // Assemble a dictionary with the values
                         $main_image = $localization->getMainImage();
                         $image_dict = array();
                         if ($main_image) {
                             $image_dict["thumbnail_50"] = $main_image->getImageUrl(50, 50);
                             $image_dict["thumbnail_250"] = $main_image->getImageUrl(250, 250);
                             $image_dict["thumbnail_500"] = $main_image->getImageUrl(500, 500);
                             $image_dict["thumbnail_1000"] = $main_image->getImageUrl(1000, 1000);
                             $image_dict["is_placeholder"] = false;
                         } else {
                             $image_dict["thumbnail_50"] = ProductImage::placehoderForSize(50, 50);
                             $image_dict["thumbnail_250"] = ProductImage::placehoderForSize(250, 250);
                             $image_dict["thumbnail_350"] = ProductImage::placehoderForSize(350, 350);
                             $image_dict["thumbnail_500"] = ProductImage::placehoderForSize(500, 500);
                             $image_dict["thumbnail_1000"] = ProductImage::placehoderForSize(1000, 1000);
                             $image_dict["is_placeholder"] = true;
                         }
                         $product_dict = array("id" => $product->id, "image" => $image_dict, "name" => $localization->name, "description" => $localization->short_description, "url" => $product_url, "current_price" => $currentPrice, "regular_price" => $regularPrice, "is_on_sale" => $isOnSale, "rebate_percent" => $rebatePercent);
                         $content[] = $product_dict;
                     }
                 }
             } else {
                 $content = array();
             }
         }
         Yii::app()->cache->set($cache_id, $content, $cache_duration);
     }
     if ($format === "html") {
         echo $content;
     } else {
         if ($format === "json") {
             header('Access-Control-Allow-Origin: *');
             $this->renderJson($content, $pretty = $pretty);
         } else {
             throw new CHttpException(400, 'The format parameter is invalid.');
         }
     }
 }
Exemplo n.º 26
0
 /**
  * Returns a placeholder image url with the specified size 
  * @param int $width maximum width.
  * @param int $height maximum height.
  * @return str the image url (eg.: http://static.boutiquekem.com/img-1-2-3-0000.png)
  */
 public static function placehoderForSize($width, $height)
 {
     if ($width <= 300 && $height <= 280) {
         // We can display thumbnails without the store's watermark. Cleaner for end users and easier on the server.
         $url = ProductImage::getImageGeneratorBaseUrl() . $width . "-" . $height . "-0000.png";
     } else {
         $url = ProductImage::getImageGeneratorBaseUrl() . Yii::app()->params['outbound_api_user'] . "-" . $width . "-" . $height . "-0000.png";
     }
     return $url;
 }
Exemplo n.º 27
0
 /**
  *  Save the current values to the database.
  *  Appends error messages to the $Errors property.
  *
  *  @param  array   $A      Optional array of values from $_POST
  *  @return boolean         True if no errors, False otherwise
  */
 public function Save($A = '')
 {
     global $_TABLES, $_PP_CONF;
     USES_paypal_class_productimage();
     USES_paypal_class_ppFile();
     if (is_array($A)) {
         $this->SetVars($A);
     }
     // Zero out the shipping amount if a non-fixed value is chosen
     if ($this->shipping_type < 2) {
         $this->shipping_amt = 0;
     }
     // Handle file uploads.  This is done first so we know whether
     // there is a valid filename for a download product
     // No weight or shipping for downloads
     if (!empty($_FILES['uploadfile']['tmp_name'])) {
         $F = new ppFile('uploadfile');
         $filename = $F->uploadFiles();
         if ($F->areErrors() > 0) {
             $this->Errors[] = $F->printErrors(true);
         } elseif ($filename != '') {
             $this->file = $filename;
         }
         PAYPAL_debug('Uploaded file: ' . $this->file);
     }
     // For downloadable files, physical product options don't apply
     if ($this->prod_type == PP_PROD_DOWNLOAD) {
         $this->weight = 0;
         $this->shipping_type = 0;
         $this->shipping_amt = 0;
     }
     // Serialize the quantity discount array
     $qty_discounts = $this->qty_discounts;
     if (!is_array($qty_discounts)) {
         $qty_discounts = array();
     }
     $qty_discounts = DB_escapeString(@serialize($qty_discounts));
     // Insert or update the record, as appropriate
     if ($this->id > 0) {
         PAYPAL_debug('Preparing to update product id ' . $this->id);
         $sql1 = "UPDATE {$_TABLES['paypal.products']} SET ";
         $sql3 = " WHERE id='{$this->id}'";
     } else {
         PAYPAL_debug('Preparing to save a new product.');
         $sql1 = "INSERT INTO {$_TABLES['paypal.products']} SET \n                dt_add = '" . DB_escapeString($_PP_CONF['now']->toMySQL()) . "',";
         $sql3 = '';
     }
     $sql2 = "name='" . DB_escapeString($this->name) . "',\n                cat_id='" . (int) $this->cat_id . "',\n                short_description='" . DB_escapeString($this->short_description) . "',\n                description='" . DB_escapeString($this->description) . "',\n                keywords='" . DB_escapeString($this->keywords) . "',\n                price='" . (double) $this->price . "',\n                prod_type='" . (int) $this->prod_type . "',\n                weight='" . (double) $this->weight . "',\n                file='" . DB_escapeString($this->file) . "',\n                expiration='" . (int) $this->expiration . "',\n                enabled='" . (int) $this->enabled . "',\n                featured='" . (int) $this->featured . "',\n                views='" . (int) $this->views . "',\n                taxable='" . (int) $this->taxable . "',\n                shipping_type='" . (int) $this->shipping_type . "',\n                shipping_amt='" . (double) $this->shipping_amt . "',\n                comments_enabled='" . (int) $this->comments_enabled . "',\n                rating_enabled='" . (int) $this->rating_enabled . "',\n                show_random='" . (int) $this->show_random . "',\n                show_popular='" . (int) $this->show_popular . "',\n                onhand='{$this->onhand}',\n                track_onhand='{$this->track_onhand}',\n                oversell = '{$this->oversell}',\n                qty_discounts = '{$qty_discounts}',\n                options='{$options}',\n                custom='" . DB_escapeString($this->custom) . "',\n                sale_price={$this->sale_price},\n                sale_beg='" . DB_escapeString($this->sale_beg) . "',\n                sale_end='" . DB_escapeString($this->sale_end) . "',\n                avail_beg='" . DB_escapeString($this->avail_beg) . "',\n                avail_end='" . DB_escapeString($this->avail_end) . "',\n                buttons= '" . DB_escapeString($this->btn_type) . "'";
     $sql = $sql1 . $sql2 . $sql3;
     //echo $sql;die;
     DB_query($sql);
     if (!DB_error()) {
         if ($this->isNew) {
             $this->id = DB_insertID();
         }
         $status = true;
     } else {
         COM_errorLog("Paypal- SQL error in Product::Save: {$sql}", 1);
         $status = false;
     }
     PAYPAL_debug('Status of last update: ' . print_r($status, true));
     if ($status) {
         // Handle image uploads.  This is done last because we need
         // the product id to name the images filenames.
         if (!empty($_FILES['images'])) {
             $U = new ProductImage($this->id, 'images');
             $U->uploadFiles();
             if ($U->areErrors() > 0) {
                 $this->Errors[] = $U->printErrors(false);
             }
         }
         // Clear the button cache
         self::DeleteButtons($this->id);
     }
     // Update the category crossref
     /*DB_delete($_TABLES['paypal.prodXcat'], 'prod_id', $prod_id);
       foreach ($this->categories as $cat) {
           DB_query("INSERT INTO {$_TABLES['paypal.prodXcat']}
                   (prod_id, cat_id)
               VALUES
                   ({$prod_id}, " . (int)$cat . ")");
       }*/
     if (empty($this->Errors)) {
         PAYPAL_debug('Update of product ' . $this->id . ' succeeded.');
         return true;
     } else {
         PAYPAL_debug('Update of product ' . $this->id . ' failed.');
         return false;
     }
 }
Exemplo n.º 28
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();
         }
     }
 }
Exemplo n.º 29
0
    $main_image = $localization->getMainImage();
    ?>
				
	<div class="col-xs-12">
	                    <div class="aside-feature">
	                        <div class="row">
	                            <div class="col-md-2">
	                                <div class="img-feature">
	                                    <a href="<?php 
    echo $product_url;
    ?>
"><img src="<?php 
    if ($main_image) {
        echo $main_image->getImageUrl(120, 120);
    } else {
        echo ProductImage::placehoderForSize(120, 120);
    }
    ?>
" class=" img-thumbnail center-block" alt=""></a>
	                                </div>
	                            </div>
	                            <div class="col-md-10">
									<p><a href="<?php 
    echo $product_url;
    ?>
" class="strong"><?php 
    echo $localization->name;
    ?>
</a><span class="pull-right"><strong><i class="fa fa-star"></i> <?php 
    echo Yii::t("app", "En vedette");
    ?>
Exemplo n.º 30
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;
 }