示例#1
0
	public function Action_GetProduct()
	{
		if(empty($this->router->request->details->productId)) {
			$this->BadRequest('The details->productId node is missing');
		}

		$image = new ISC_PRODUCT_IMAGE(); // autoload helper so we can use exceptions defined in the product image class file
		unset($image);

		$productId = (int)$this->router->request->details->productId;
		$productClass = new ISC_PRODUCT($productId);
		$product = $productClass->_product;

		// stuff that comes directly from the database may be incomplete -- use the image library to make sure
		try {
			if (!$product['imageid']) {
				// no image present in data so throw an exception just to force the removal of data below in the catch{} block
				throw new ISC_PRODUCT_IMAGE_EXCEPTION();
			}

			$image = new ISC_PRODUCT_IMAGE();
			$image->populateFromDatabaseRow($product);

			// call the image library to make sure resized images are present and then add full urls so they're useful for remote users
			$product['imagefiletiny'] = $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_TINY, true, true, false);
			$product['imagefilethumb'] = $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, true, true, false);
			$product['imagefilestd'] = $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_STANDARD, true, true, false);
			$product['imagefilezoom'] = $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true, true, false);

			// call the image library to make sure resized images are present and the sizes are correct
			$product['imagefiletinysize'] = implode('x', $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_TINY));
			$product['imagefilethumbsize'] = implode('x', $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL));
			$product['imagefilestdsize'] = implode('x', $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_STANDARD));
			$product['imagefilezoomsize'] = implode('x', $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_ZOOM));

		} catch (Exception $exception) {
			// some sort of problem when dealing with product images - remove image info from the response
			unset(
				$product['imagefiletiny'],
				$product['imagefilethumb'],
				$product['imagefilestd'],
				$product['imagefilezoom'],
				$product['imagefiletinysize'],
				$product['imagefilethumbsize'],
				$product['imagefilestdsize'],
				$product['imagefilezoomsize'],
				$product['imagedesc'],
				$product['imagedateadded']
			);
		}

		// direct data feed also includes some fields that are irrelevant or unwanted
		unset(
			$product['imagefile'],	// don't provide a link to the non-water-marked image
			$product['imageprodid'],
			$product['imageprodhash'],
			$product['imageisthumb'],
			$product['imagesort']
		);

		if(empty($product)) {
			return array();
		}

		$product['prodlink'] = ProdLink($product['prodname']);

		// Fetch any images for the product

		$images = new ISC_PRODUCT_IMAGE_ITERATOR(ISC_PRODUCT_IMAGE::generateGetProductImagesFromDatabaseSql((int)$productId));
		foreach ($images as $image) {
			/** @var $image ISC_PRODUCT_IMAGE */
			$imageisthumb = 0;
			if ($image->getIsThumbnail()) {
				$imageisthumb = 1;
			}

			try {
				$product['images']['item'][] = array(
					'imageid' => $image->getProductImageId(),
					'imagefiletiny' => $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_TINY, true, true, false),
					'imagefilethumb' => $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, true, true, false),
					'imagefilestd' => $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_STANDARD, true, true, false),
					'imagefilezoom' => $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true, true, false),
					'imagefiletinysize' => implode('x', $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_TINY)),
					'imagefilethumbsize' => implode('x', $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL)),
					'imagefilestdsize' => implode('x', $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_STANDARD)),
					'imagefilezoomsize' => implode('x', $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_ZOOM)),
					'imageisthumb' => $imageisthumb,
					'imagesort' => $image->getSort(),
					'imagedesc' => $image->getDescription(),
					'imagedateadded' => $image->getDateAdded(),
				);
			} catch (Exception $exception) {
				// skip this image and bring down the count of product images obtained from ISC_PRODUCT
				$product['numimages']--;
			}
		}

		// Fetch the categories this product belongs to
		$trailCategories = array();
		$crumbList = array();
		$query = "
			SELECT c.categoryid, c.catparentlist
			FROM [|PREFIX|]categoryassociations ca
			JOIN [|PREFIX|]categories c ON (c.categoryid=ca.categoryid)
			WHERE ca.productId='".(int)$productId."'
		";
		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
		while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			if ($row['catparentlist'] == '') {
				$row['catparentlist'] = $row['categoryid'];
			}
			$cats = explode(",", $row['catparentlist']);
			$trailCategories = array_merge($trailCategories, $cats);
			$crumbList[$row['categoryid']] = $row['catparentlist'];
		}

		$trailCategories = implode(",", array_unique($trailCategories));
		$categories = array();
		if ($trailCategories != '') {
			// Now load the names for the parent categories from the database
			$query = "
				SELECT categoryid, catname
				FROM [|PREFIX|]categories
				WHERE categoryid IN (".$trailCategories.")
			";
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
				$categories[$row['categoryid']] = $row['catname'];
			}
		}

		// Now we have all of the information we need to build the trails, lets actually build them
		foreach ($crumbList as $productcatid => $trail) {
			$cats = explode(',', $trail);
			$catName = '';
			$catLink = CatLink($productcatid, $categories[$productcatid]);
			foreach ($cats as $categoryid) {
				if(isset($categories[$categoryid])) {
					if($catName) {
						$catName .= ' » ';
					}
					$catName .= $categories[$categoryid];
				}
			}
			$product['categories']['item'][] = array(
				'name' => $catName,
				'link' => $catLink,
				'id' => $productcatid
			);
		}

		if($product['prodvariationid'] > 0) {
			if ($product['prodsaleprice'] != 0) {
				$variationBasePrice = $product['prodsaleprice'];
			}
			else {
				$variationBasePrice = $product['prodprice'];
			}

			$vop = $productClass->_prodvariationoptions;
			$vval = $productClass->_prodvariationvalues;
			foreach($productClass->_prodvariationcombinations as $variation) {
				$variationPrice = CurrencyConvertFormatPrice(CalcProductVariationPrice($variationBasePrice, $variation['vcpricediff'], $variation['vcprice'], $product));
				$variationWeight = FormatWeight(CalcProductVariationWeight($product['prodweight'], $variation['vcweightdiff'], $variation['vcweight']), true);

				$variationName = array();
				$options = explode(',', $variation['vcoptionids']);
				foreach($options as $k => $optionId) {
					$label = $vop[$k];
					$variationName[] = $label.': '.$vval[$label][$optionId];
				}
				$variationName = implode(', ', $variationName);
				$variationRow = array(
					'name' => $variationName,
					'id' => $variation['combinationid'],
					'price' => $variationPrice,
					'sku' => $variation['vcsku'],
					'weight' => $variationWeight,
				);

				if($product['prodinvtrack'] == 2) {
					$variationRow['stock'] = $variation['vcstock'];
				}

				if ($variation['vcimage']) {
					try {
						$image = new ISC_PRODUCT_IMAGE;
						$image->setSourceFilePath($variation['vcimage']);

						if($variation['vcimagethumb']) {
							$image->setResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, $variation['vcimagethumb']);
							$variationRow['thumb'] = $image->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, true, false);
						}

						if($variation['vcimagestd']) {
							$image->setResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_STANDARD, $variation['vcimagestd']);
							$variationRow['standard'] = $image->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_STANDARD, true, false);
						}

						if($variation['vcimagezoom']) {
							$image->setResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_ZOOM, $variation['vcimagezoom']);
							$variationRow['image'] = $image->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true, false);
						}
					} catch (Exception $exception) {
						// nothing
					}
				}

				$product['variations']['item'][] = $variationRow;
			}
		}

		return $product;
	}
示例#2
0
		/**
		 * Build the array of searched item results for the AJAX request
		 *
		 * Method will build an array of searched item results for the AJAX request. Method will work with the ISC_SEARCH
		 * class to get the results so make sure that the object is initialised and the DoSearch executed.
		 *
		 * Each key in the array will be the 'score' value (as a string) so it can be merged in with other results and can
		 * then be further sorted using any PHP array sorting functions, so output would be something like this:
		 *
		 * EG: return = array(10, // result count
		 *                    array(
		 *                        "12.345" => array(
		 *                                          0 => [product HTML]
		 *                                          1 => [product HTML]
		 *                                          2 => [product HTML]
		 *                                    ),
		 *                        "2.784" => array(
		 *                                          0 => [product HTML]
		 *                                    ),
		 *                        "6.242" => array(
		 *                                          0 => [product HTML]
		 *                                          1 => [product HTML]
		 *                                   )
		 *                    )
		 *              );
		 *
		 * @access public
		 * @return array An array with two values, first is total number of search results. Other is the search item results AJAX array on success, empty array on error
		 */
		static public function buildSearchResultsAJAX()
		{
			if (!isset($GLOBALS["ISC_CLASS_SEARCH"]) || !is_object($GLOBALS["ISC_CLASS_SEARCH"])) {
				return array(0, array());
			}

			$totalRecords = $GLOBALS["ISC_CLASS_SEARCH"]->GetNumResults("product");

			if ($totalRecords == 0) {
				return array(0, array());
			}

			$results = $GLOBALS["ISC_CLASS_SEARCH"]->GetResults("product");
			$ajaxArray = array();

			if (!array_key_exists("results", $results) || !is_array($results["results"])) {
				return array();
			}

			$products = $results["results"];

			foreach ($products as $product) {
				if (!isset($product["score"])) {
					$product["score"] = 0;
				}

				$GLOBALS["ProductName"] = $product["prodname"];
				$GLOBALS["ProductURL"] = ProdLink($product["prodname"]);
				$GLOBALS['ProductPrice'] = '';
				if (GetConfig('ShowProductPrice') && !$product['prodhideprice']) {
					$GLOBALS['ProductPrice'] = formatProductCatalogPrice($product);
				}

				if(getProductReviewsEnabled()) {
					$ratingURL = $GLOBALS["IMG_PATH"] . "/IcoRating" . (int)$product["prodavgrating"] . ".gif";
					$GLOBALS["ProductRatingImage"] = "<img src=\"" . $ratingURL . "\" class=\"RatingIMG\" />";
				} else {
					$GLOBALS["ProductRatingImage"] = "";
				}

				$GLOBALS["ProductNoImageClassName"] = "";

				if (isset($product["imageid"]) && $product["imageid"] !== "") {
					$image = new ISC_PRODUCT_IMAGE();
					$image->populateFromDatabaseRow($product);
					$productImageSize = $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_TINY, true);
					if ($productImageSize[0] > 70) {
						// ISCFIVEFIVEBETA-89 - cap to 70px wide
						// note: will need to adjust height by proper ratio if we want the height output to html
						$productImageSize[0] = 70;
					}
					$GLOBALS["ProductImage"] = "<img src=\"" . isc_html_escape($image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_TINY, true)) . "\" alt=\"" . isc_html_escape($product["prodname"]) . "\" title=\"" . isc_html_escape($product["prodname"]) . "\" width=\"" . $productImageSize[0] . "\" />";
				} else {
					$GLOBALS["ProductNoImageClassName"] = "QuickSearchResultNoImage";
					$GLOBALS["ProductImage"] = "<span>" . GetLang("QuickSearchNoImage") . "</span>";
				}

				$sortKey = (string)$product["score"];

				if (!array_key_exists($sortKey, $ajaxArray) || !is_array($ajaxArray[$sortKey])) {
					$ajaxArray[$sortKey] = array();
				}

				$ajaxArray[$sortKey][] = $GLOBALS["ISC_CLASS_TEMPLATE"]->GetSnippet("SearchResultAJAXProduct");
			}

			return array($totalRecords, $ajaxArray);
		}
示例#3
0
		public function ManageProductsGrid(&$numProducts)
		{
			// Show a list of products in a table
			$page = 0;
			$start = 0;
			$numProducts = 0;
			$GLOBALS['ProductGrid'] = "";
			$max = 0;

			// Is this a custom search?
			if(isset($_GET['searchId'])) {
				// Override custom search sort fields if we have a requested field
				if(isset($_GET['sortField'])) {
					$_REQUEST['sortField'] = $_GET['sortField'];
				}
				if(isset($_GET['sortOrder'])) {
					$_REQUEST['sortOrder'] = $_GET['sortOrder'];
				}
			}

			if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
				$featuredColumn = 'prodvendorfeatured';
			}
			else {
				$featuredColumn = 'prodfeatured';
			}

			$validSortFields = array('productid', 'prodcode', 'currentinv', 'prodname', 'prodcalculatedprice', 'prodvisible', $featuredColumn, '_calc_prodstatus');

			if(isset($_REQUEST['sortOrder']) && $_REQUEST['sortOrder'] == "asc") {
				$sortOrder = "asc";
			}
			else {
				$sortOrder = "desc";
			}

			if(isset($_REQUEST['sortField']) && in_array($_REQUEST['sortField'], $validSortFields)) {
				$sortField = $_REQUEST['sortField'];
				SaveDefaultSortField("ManageProducts", $_REQUEST['sortField'], $sortOrder);
			} else {
				list($sortField, $sortOrder) = GetDefaultSortField("ManageProducts", "productid", $sortOrder);
			}


			if(isset($_GET['page'])) {
				$page = (int)$_GET['page'];
			}
			else {
				$page = 1;
			}

			if (isset($_GET['perpage'])) {
				$perPage = (int)$_GET['perpage'];
				SaveDefaultPerPage("ManageProducts", $perPage);
			}
			else {
				$perPage = GetDefaultPerPage("ManageProducts", ISC_PRODUCTS_PER_PAGE);
			}

			if(isset($_GET['filterCategory']) && $_GET['filterCategory'] == "-1") {
				$GLOBALS['FilterLow'] = "selected=\"selected\"";
			}

			if(isset($_GET['filterCategory'])) {
				$filterCat = (int)$_GET['filterCategory'];
			}
			else {
				$filterCat = 0;
			}

			if(!gzte11(ISC_MEDIUMPRINT)) {
				$GLOBALS['ProductNameSpan'] = 3;
				$GLOBALS['HideInventoryOptions'] = 'none';
			}
			else {
				$GLOBALS['HideInventoryOptions'] = '';
			}

			// Build the search and sort URL
			$searchURL = $this->buildSearchUrlData($_GET, $sortField, $sortOrder);
			$this->buildLetterSearchUrlData($searchURL);

			$sortURL = $searchURL;
			unset($sortURL['sortField'], $sortURL['sortOrder']);

			// Limit the number of questions returned
			if($page == 1) {
				$start = 1;
			}
			else {
				$start = ($page * $perPage) - ($perPage-1);
			}

			$start = $start-1;

			// Get the results for the query
			$product_result = $this->_GetProductList($start, $sortField, $sortOrder, $numProducts, '', $perPage);

			$GLOBALS['perPage'] = $perPage;
			$GLOBALS['numProducts'] = $numProducts;
			$GLOBALS['pageURL'] = "index.php?ToDo=viewProducts&" . http_build_query($searchURL);
			$GLOBALS['currentPage'] = $page;

			if (isset($_REQUEST['searchQuery'])) {
				$query = $_REQUEST['searchQuery'];
			} else {
				$query = '';
			}

			$GLOBALS['EscapedQuery'] = isc_html_escape($query);
			$GLOBALS['SearchQuery'] = isc_html_escape($query);
			$GLOBALS['SortField'] = $sortField;
			$GLOBALS['SortOrder'] = $sortOrder;


			if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
				$featuredColumn = 'prodvendorfeatured';
			}
			else {
				$featuredColumn = 'prodfeatured';
			}

			$sortLinks = array(
				"Code" => "prodcode",
				"Stock" => "currentinv",
				"Name" => "prodname",
				"Price" => "prodcalculatedprice",
				"Status" => "_calc_prodstatus",
				"Visible" => "prodvisible",
				"Featured" => $featuredColumn
			);

			BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewProducts&amp;".http_build_query($sortURL)."&amp;page=".$page, $sortField, $sortOrder);


			// Workout the maximum size of the array
			$max = $start + $perPage;

			if ($max > $numProducts) {
				$max = $numProducts;
			}

			if($numProducts > 0) {
				// Display the products
				while($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($product_result)) {
					if ($row['prodcode'] == "") {
						$GLOBALS['SKU'] = GetLang('NA');
					} else {
						$GLOBALS['SKU'] = isc_html_escape($row['prodcode']);
					}

					$GLOBALS['ProductId'] = (int)$row['productid'];
					$GLOBALS['Name'] = sprintf("<a title='%s' class='Action' href='%s' target='_blank'>%s</a>", GetLang('ProductView'), ProdLink($row['prodname']), isc_html_escape($row['prodname']));

					// Do we need to show product thumbnails?
					if(GetConfig('ShowThumbsInControlPanel')) {
						if ($row['imageid'] !== null) {
							$image = new ISC_PRODUCT_IMAGE();
							$image->populateFromDatabaseRow($row);
							try {
								$imageThumbnailUrl = $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_TINY, true);
								$imageDimensions = $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_TINY);
								$GLOBALS['ProductImage'] = sprintf('<img src="%1$s" width="%2$d" height="%3$d" />', isc_html_escape($imageThumbnailUrl), $imageDimensions[0], $imageDimensions[1]);
							} catch (Exception $exception) {
								// source image is not readable, show the no image placeholder
								$GLOBALS['ProductImage'] = sprintf("<div class='NoThumb'>%s<br />%s<br />%s</div>", GetLang('NoImage1'), GetLang('NoImage2'), GetLang('NoImage3'));
							}
						} else {
							$GLOBALS['ProductImage'] = sprintf("<div class='NoThumb'>%s<br />%s<br />%s</div>", GetLang('NoImage1'), GetLang('NoImage2'), GetLang('NoImage3'));
						}
					}
					else {
						// Use JavaScript to hide the thumbnail field
						$GLOBALS['HideThumbnailField'] = "1";
					}

					$GLOBALS['Price'] = FormatPrice($row['prodcalculatedprice']);
					$GLOBALS['StockExpand'] = "&nbsp;";
					$GLOBALS['LowStockStyle'] = "";

					if ($row['prodinvtrack'] == 0) {
						$GLOBALS['StockInfo'] = GetLang('NA');
					} else if($row['prodinvtrack'] > 0) {

						$GLOBALS['StockExpand'] = sprintf("<a href=\"#\" onclick=\"ShowStock('%d', '%d', '%d'); return false;\"><img id=\"expand%d\" src=\"images/plus.gif\" align=\"left\"  class=\"ExpandLink\" width=\"19\" height=\"16\" title=\"%s\" border=\"0\"></a>", $row['productid'], $row['prodinvtrack'], $row['prodvariationid'], $row['productid'], GetLang('ClickToViewStock'));

						$percent = 0;
						if($row['prodlowinv'] > 0) {
							$percent = ceil(($row['currentinv'] / ($row['prodlowinv'] * 2)) * 100);
						} elseif ($row['currentinv'] > 0) {
							$percent = 100;
						}

						if($percent > 100) {
							$percent = 100;
						}

						if($percent > 75) {
							$stockClass = 'InStock';
							$orderMore = GetLang('SNo');
						}
						else if($percent > 50) {
							$stockClass = 'StockWarning';
							$orderMore = GetLang('Soon');
						}
						else {
							$stockClass = 'LowStock';
							$orderMore = GetLang('SYes');
						}
						$width = ceil(($percent/100)*72);

						$stockInfo = sprintf(GetLang('CurrentStockLevel').': %s<br />'.GetLang('LowStockLevel1').': %s<br />'.GetLang('OrderMore').': '.$orderMore, $row['currentinv'], $row['prodlowinv'], $orderMore);

						$GLOBALS['StockInfo'] = sprintf("<div class=\"StockLevelIndicator\" onmouseover=\"ShowQuickHelp(this, '%s', '%s')\" onmouseout=\"HideQuickHelp(this)\"><span class=\"%s\" style=\"width: %spx\"></span></div>", GetLang('StockLevel'), $stockInfo, $stockClass, $width);
					}

					// If they have permission to edit products, they can change
					// the visibility status of a product by clicking on the icon

					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) {
						if ($row['prodvisible'] == 1) {
							$GLOBALS['Visible'] = sprintf("<a title='%s' href='index.php?ToDo=editProductVisibility&amp;prodId=%d&amp;visible=0' onclick=\"quickToggle(this, 'visible'); return false;\"><img border='0' src='images/tick.gif' alt='tick'></a>", GetLang('ClickToHide'), $row['productid']);
						} else {
							$GLOBALS['Visible'] = sprintf("<a title='%s' href='index.php?ToDo=editProductVisibility&amp;prodId=%d&amp;visible=1' onclick=\"quickToggle(this, 'visible'); return false;\"><img border='0' src='images/cross.gif' alt='cross'></a>", GetLang('ClickToShow'), $row['productid']);
						}
					} else {
						if ($row['prodvisible'] == 1) {
							$GLOBALS['Visible'] = '<img border="0" src="images/tick.gif" alt="tick">';
						} else {
							$GLOBALS['Visible'] = '<img border="0" src="images/cross.gif" alt="cross">';
						}
					}

					// If they have permission to edit products, they can change
					// the featured status of a product by clicking on the icon

					if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
						$featuredColumn = 'prodvendorfeatured';
					}
					else {
						$featuredColumn = 'prodfeatured';
					}

					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) {
						if ($row[$featuredColumn] == 1) {
							$GLOBALS['Featured'] = sprintf("<a title='%s' href='index.php?ToDo=editProductFeatured&amp;prodId=%d&amp;featured=0' onclick=\"quickToggle(this, 'featured'); return false;\"><img border='0' src='images/tick.gif' alt='tick'></a>", GetLang('ClickToHide'), $row['productid']);
						} else {
							$GLOBALS['Featured'] = sprintf("<a title='%s' href='index.php?ToDo=editProductFeatured&amp;prodId=%d&amp;featured=1' onclick=\"quickToggle(this, 'featured'); return false;\"><img border='0' src='images/cross.gif' alt='cross'></a>", GetLang('ClickToShow'), $row['productid']);
						}
					} else {
						if ($row[$featuredColumn] == 1) {
							$GLOBALS['Featured'] = '<img border="0" src="images/tick.gif" alt="tick">';
						} else {
							$GLOBALS['Featured'] = '<img border="0" src="images/cross.gif" alt="cross">';
						}
					}

					// Workout the edit link -- do they have permission to do so?
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) {
						$GLOBALS['EditProductLink'] = sprintf("<a title='%s' class='Action' href='index.php?ToDo=editProduct&amp;productId=%d'>%s</a>", GetLang('ProductEdit'), $row['productid'], GetLang('Edit'));
					} else {
						$GLOBALS['EditProductLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('Edit'));
					}

					$allowpurchases = (int)$row['prodallowpurchases'];
					$prodpreorder = (int)$row['prodpreorder'];

					$status = GetLang('CatalogueOnly');
					if ($allowpurchases) {
						if ($prodpreorder) {
							$status= GetLang('PreOrder');
						} else {
							$status = GetLang('Selling');
						}
					}

					$GLOBALS['Status'] = $status;

					$GLOBALS['CopyProductLink'] = "<a title='".GetLang('ProductCopy')."' class='Action' href='index.php?ToDo=copyProduct&amp;productId=".$row['productid']."'>".GetLang('Copy')."</a>";

					$GLOBALS['ProductGrid'] .= $this->template->render('product.manage.row.tpl');
				}

			}
			if($GLOBALS['ProductGrid'] == '') {
				if(isset($_REQUEST['letter'])) {
					$GLOBALS['ProductGrid'] = sprintf('<tr>
						<td colspan="11" style="padding:10px"><em>%s</em></td>
					</tr>', sprintf(GetLang('LetterSortNoResults'), isc_strtoupper($_REQUEST['letter'])));
				}
			}
			return $this->template->render('products.manage.grid.tpl');
		}
示例#4
0
	/**
	* Imports a temporary image file on the server to the given product. Performs validation, moves the file to it's final location and filename and returns an instance of ISC_PRODUCT_IMAGE.
	*
	* It is up to the method calling this to delete any temporary file if something goes wrong.
	*
	* @param string $temporaryPath Absolute path to the temporary image file stored on the server to be imported -- this file will need to be read so if it is an uploaded file and is in the tmp folder you should move it to the cache directory first since open_basedir restrictions may prevent the file being read from the tmp folder
	* @param string $originalFilename Original intended filename (such as the name provided by the browser when uploading a file) which may differ from the temporary file at $temporaryPath -- this should not include any directory components
	* @param int|string|bool $productId The id (or hash when $hash is true) of the product to import to, or supply as false to not save any info to the database but still return an instance of ISC_PRODUCT_IMAGE
	* @param bool $hash If true, $productId will be treated as a hash of a product in the process of being added
	* @param bool $moveTemporaryFile If true, the provided temporary file will be moved to it's new location, otherwise it will be copied
	* @param bool $generateImages If true, when importing, will attempt to generate thumbnail images -- may not be desirable if importing many images at once
	* @throws ISC_PRODUCT_IMAGE_IMPORT_INVALIDIMAGEFILE_EXCEPTION If the file is not a valid image
	* @throws ISC_PRODUCT_IMAGE_IMPORT_NOPHPSUPPORT_EXCEPTION If the image could not be processed by any installed php extensions
	* @throws ISC_PRODUCT_IMAGE_IMPORT_EMPTYIMAGE_EXCEPTION If the image is 'empty' - has 0 width or 0 height
	* @throws ISC_PRODUCT_IMAGE_IMPORT_CANTCREATEDIR_EXCEPTION If an error prevented the image's destination directory from being created (usually lack of write permissions on parent directory)
	* @throws ISC_PRODUCT_IMAGE_IMPORT_CANTMOVEFILE_EXCEPTION If an error prevented the image from being moved to the destination directory (usually lack of write permissions on parent directory)
	* @return ISC_PRODUCT_IMAGE If everything went OK
	*/
	public static function importImage($temporaryPath, $originalFilename, $productId, $hash = false, $moveTemporaryFile = true, $generateImages = true)
	{
		if (!file_exists($temporaryPath)) {
			throw new ISC_PRODUCT_IMAGE_SOURCEFILEDOESNTEXIST_EXCEPTION($temporaryPath);
		}

		try {
			$library = ISC_IMAGE_LIBRARY_FACTORY::getImageLibraryInstance($temporaryPath);
		} catch (ISC_IMAGE_LIBRARY_FACTORY_INVALIDIMAGEFILE_EXCEPTION $ex) {
			throw new ISC_PRODUCT_IMAGE_IMPORT_INVALIDIMAGEFILE_EXCEPTION();
		} catch (ISC_IMAGE_LIBRARY_FACTORY_NOPHPSUPPORT_EXCEPTION $ex) {
			throw new ISC_PRODUCT_IMAGE_IMPORT_NOPHPSUPPORT_EXCEPTION();
		}

		if ($library->getWidth() < 1 || $library->getHeight() < 1) {
			throw new ISC_PRODUCT_IMAGE_IMPORT_EMPTYIMAGE_EXCEPTION();
		}

		$finalName = $originalFilename;


		$finalName = basename($finalName); // remove any path components from the filename
		$finalName = self::sanitiseFilename($finalName);

		if (!self::isValidFilename($finalName, false)) {
			throw new ISC_PRODUCT_IMAGE_IMPORT_INVALIDFILENAME_EXCEPTION($finalName);
		}

		// correct the uploaded extension
		$correctExtension = $library->getImageTypeExtension(false);
		if (strtolower(pathinfo($finalName, PATHINFO_EXTENSION)) != $correctExtension) {
			// remove existing extension and trailing . if any
			$finalName = preg_replace('#\.[^\.]*$#', '', $finalName);
			// add correct extension
			$finalName .= '.' . $correctExtension;
		}

		// generate a path for storing in the product_images directory
		$finalRelativePath = self::generateSourceImageRelativeFilePath($finalName);

		$image = new ISC_PRODUCT_IMAGE();
		$image->setSourceFilePath($finalRelativePath);

		$finalAbsolutePath = $image->getAbsoluteSourceFilePath();
		$finalDirectory = dirname($finalAbsolutePath);

		if (!file_exists($finalDirectory)) {
			if (!isc_mkdir($finalDirectory, ISC_WRITEABLE_DIR_PERM, true)) {
				throw new ISC_PRODUCT_IMAGE_IMPORT_CANTCREATEDIR_EXCEPTION($finalDirectory);
			}
		}

		if ($moveTemporaryFile) {
			if (!@rename($temporaryPath, $finalAbsolutePath)) {
				throw new ISC_PRODUCT_IMAGE_IMPORT_CANTMOVEFILE_EXCEPTION($finalAbsolutePath);
			}
		} else {
			if (!@copy($temporaryPath, $finalAbsolutePath)) {
				throw new ISC_PRODUCT_IMAGE_IMPORT_CANTMOVEFILE_EXCEPTION($finalAbsolutePath);
			}
		}

		// check to see if the uploaded image exceeds our internal maximum image size: ISC_PRODUCT_IMAGE_MAXLONGEDGE
		if ($library->getWidth() > ISC_PRODUCT_IMAGE_MAXLONGEDGE || $library->getHeight() > ISC_PRODUCT_IMAGE_MAXLONGEDGE) {
			// if it is, resize it and overwrite the uploaded source image because we only want to store images to a maximum size of ISC_PRODUCT_IMAGE_MAXLONGEDGE x ISC_PRODUCT_IMAGE_MAXLONGEDGE
			$library->setFilePath($finalAbsolutePath);
			$library->loadImageFileToScratch();
			$library->resampleScratchToMaximumDimensions(ISC_PRODUCT_IMAGE_MAXLONGEDGE, ISC_PRODUCT_IMAGE_MAXLONGEDGE);
			$library->saveScratchToFile($finalAbsolutePath, self::getWriteOptionsForImageType($library->getImageType()));
		}

		if ($productId === false) {
			// do not assign product hash, id or save to database if $productId is false
			if ($generateImages) {
				// manually generate images since, normally, a call to saveToDatabase would do it
				$image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_TINY, true, false);
				$image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, true, false);
				$image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_STANDARD, true, false);
				$image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true, false);
			}

			return $image;
		}

		if ($hash) {
			$image->setProductHash($productId);
		} else {
			$image->setProductId($productId);
		}

		// ISC_PRODUCT_IMAGE_SOURCEFILEDOESNTEXIST_EXCEPTION should never really happen at this point with all the checks above so, if it does, let the exception go unhandled to bubble up to a fatal error
		$image->saveToDatabase($generateImages);

		return $image;
	}