PageRenderTime 81ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/app/code/core/Mage/ConfigurableSwatches/Helper/Productimg.php

https://gitlab.com/LisovyiEvhenii/ismextensions
PHP | 347 lines | 196 code | 43 blank | 108 comment | 37 complexity | 7c45bc60904625048daebe1ae6ee3426 MD5 | raw file
  1. <?php
  2. /**
  3. * Magento
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@magento.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade Magento to newer
  18. * versions in the future. If you wish to customize Magento for your
  19. * needs please refer to http://www.magento.com for more information.
  20. *
  21. * @category Mage
  22. * @package Mage_ConfigurableSwatches
  23. * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26. /**
  27. * Class Mage_ConfigurableSwatches_Helper_Productimg
  28. */
  29. class Mage_ConfigurableSwatches_Helper_Productimg extends Mage_Core_Helper_Abstract
  30. {
  31. /**
  32. * This array stores product images and separates them:
  33. * One group keyed by labels that match attribute values, another for all other images
  34. *
  35. * @var array
  36. */
  37. protected $_productImagesByLabel = array();
  38. /**
  39. * This array stores all possible labels and swatch labels used for associating gallery
  40. * images with swatches and main image swaps. It's use is for filtering the image gallery.
  41. *
  42. * @var array
  43. */
  44. protected $_productImageFilters = array();
  45. const SWATCH_LABEL_SUFFIX = '-swatch';
  46. const SWATCH_FALLBACK_MEDIA_DIR = 'wysiwyg/swatches';
  47. const SWATCH_CACHE_DIR = 'catalog/swatches';
  48. const SWATCH_FILE_EXT = '.png';
  49. const MEDIA_IMAGE_TYPE_BASE = 'base_image';
  50. const MEDIA_IMAGE_TYPE_SMALL = 'small_image';
  51. const SWATCH_DEFAULT_WIDTH = 21;
  52. const SWATCH_DEFAULT_HEIGHT = 21;
  53. /**
  54. * Determine if the passed text matches the label of any of the passed product's images
  55. *
  56. * @param string $text
  57. * @param Mage_Catalog_Model_Product $product
  58. * @param string $type
  59. * @return Varien_Object|null
  60. */
  61. public function getProductImgByLabel($text, $product, $type = null)
  62. {
  63. $this->indexProductImages($product);
  64. //Get the product's image array and prepare the text
  65. $images = $this->_productImagesByLabel[$product->getId()];
  66. $text = Mage_ConfigurableSwatches_Helper_Data::normalizeKey($text);
  67. $resultImages = array(
  68. 'standard' => isset($images[$text]) ? $images[$text] : null,
  69. 'swatch' => isset($images[$text . self::SWATCH_LABEL_SUFFIX]) ? $images[$text . self::SWATCH_LABEL_SUFFIX]
  70. : null,
  71. );
  72. if (!is_null($type) && array_key_exists($type, $resultImages)) {
  73. $image = $resultImages[$type];
  74. } else {
  75. $image = (!is_null($resultImages['swatch'])) ? $resultImages['swatch'] : $resultImages['standard'];
  76. }
  77. return $image;
  78. }
  79. /**
  80. * Create the separated index of product images
  81. *
  82. * @param Mage_Catalog_Model_Product $product
  83. * @param array|null $preValues
  84. * @return Mage_ConfigurableSwatches_Helper_Data
  85. */
  86. public function indexProductImages($product, $preValues = null)
  87. {
  88. if ($product->getTypeId() != Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
  89. return; // we only index images on configurable products
  90. }
  91. if (!isset($this->_productImagesByLabel[$product->getId()])) {
  92. $images = array();
  93. $searchValues = array();
  94. if (!is_null($preValues) && is_array($preValues)) { // If a pre-defined list of valid values was passed
  95. $preValues = array_map('Mage_ConfigurableSwatches_Helper_Data::normalizeKey', $preValues);
  96. foreach ($preValues as $value) {
  97. $searchValues[] = $value;
  98. }
  99. } else { // we get them from all config attributes if no pre-defined list is passed in
  100. $attributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);
  101. // Collect valid values of image type attributes
  102. foreach ($attributes as $attribute) {
  103. if (Mage::helper('configurableswatches')->attrIsSwatchType($attribute->getAttributeId())) {
  104. foreach ($attribute->getPrices() as $option) { // getPrices returns info on individual options
  105. $searchValues[] = Mage_ConfigurableSwatches_Helper_Data::normalizeKey($option['label']);
  106. }
  107. }
  108. }
  109. }
  110. $mapping = $product->getChildAttributeLabelMapping();
  111. $mediaGallery = $product->getMediaGallery();
  112. $mediaGalleryImages = $product->getMediaGalleryImages();
  113. if (empty($mediaGallery['images']) || empty($mediaGalleryImages)) {
  114. $this->_productImagesByLabel[$product->getId()] = array();
  115. return; //nothing to do here
  116. }
  117. $imageHaystack = array_map(function ($value) {
  118. return Mage_ConfigurableSwatches_Helper_Data::normalizeKey($value['label']);
  119. }, $mediaGallery['images']);
  120. foreach ($searchValues as $label) {
  121. $imageKeys = array();
  122. $swatchLabel = $label . self::SWATCH_LABEL_SUFFIX;
  123. $imageKeys[$label] = array_search($label, $imageHaystack);
  124. if ($imageKeys[$label] === false) {
  125. $imageKeys[$label] = array_search($mapping[$label]['default_label'], $imageHaystack);
  126. }
  127. $imageKeys[$swatchLabel] = array_search($swatchLabel, $imageHaystack);
  128. if ($imageKeys[$swatchLabel] === false) {
  129. $imageKeys[$swatchLabel] = array_search(
  130. $mapping[$label]['default_label'] . self::SWATCH_LABEL_SUFFIX, $imageHaystack
  131. );
  132. }
  133. foreach ($imageKeys as $imageLabel => $imageKey) {
  134. if ($imageKey !== false) {
  135. $imageId = $mediaGallery['images'][$imageKey]['value_id'];
  136. $images[$imageLabel] = $mediaGalleryImages->getItemById($imageId);
  137. }
  138. }
  139. }
  140. $this->_productImagesByLabel[$product->getId()] = $images;
  141. }
  142. }
  143. /**
  144. * Return the appropriate swatch URL for the given value (matches against product's image labels)
  145. *
  146. * @param Mage_Catalog_Model_Product $product
  147. * @param string $value
  148. * @param int $width
  149. * @param int $height
  150. * @param $swatchType
  151. * @param string $fallbackFileExt
  152. * @return string
  153. */
  154. public function getSwatchUrl($product, $value, $width = self::SWATCH_DEFAULT_WIDTH,
  155. $height = self::SWATCH_DEFAULT_HEIGHT, &$swatchType, $fallbackFileExt = null
  156. ) {
  157. $url = '';
  158. $swatchType = 'none';
  159. // Get the (potential) swatch image that matches the value
  160. $image = $this->getProductImgByLabel($value, $product, 'swatch');
  161. // Check in swatch directory if $image is null
  162. if (is_null($image)) {
  163. // Check if file exists in fallback directory
  164. $fallbackUrl = $this->getGlobalSwatchUrl($product, $value, $width, $height, $fallbackFileExt);
  165. if (!empty($fallbackUrl)) {
  166. $url = $fallbackUrl;
  167. $swatchType = 'media';
  168. }
  169. }
  170. // If we still don't have a URL or matching product image, look for one that matches just
  171. // the label (not specifically the swatch suffix)
  172. if (empty($url) && is_null($image)) {
  173. $image = $this->getProductImgByLabel($value, $product, 'standard');
  174. }
  175. if (!is_null($image)) {
  176. $filename = $image->getFile();
  177. $swatchImage = $this->_resizeSwatchImage($filename, 'product', $width, $height);
  178. $swatchType = 'product';
  179. $url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . $swatchImage;
  180. }
  181. return $url;
  182. }
  183. /**
  184. * Return URL for a matching swatch image from the global directory
  185. *
  186. * @param Mage_Catalog_Model_Product|Mage_Catalog_Model_Layer_Filter_Item $object
  187. * @param string $value
  188. * @param int $width
  189. * @param int $height
  190. * @param string $fileExt
  191. * @throws Mage_Core_Exception
  192. * @return string
  193. */
  194. public function getGlobalSwatchUrl($object, $value, $width = self::SWATCH_DEFAULT_WIDTH,
  195. $height = self::SWATCH_DEFAULT_HEIGHT, $fileExt = null
  196. ) {
  197. if (is_null($fileExt)) {
  198. $fileExt = self::SWATCH_FILE_EXT;
  199. }
  200. // normalize to all lower case so that value can be used as array key below
  201. $value = Mage_ConfigurableSwatches_Helper_Data::normalizeKey($value);
  202. $defaultValue = $value; // default to no fallback value
  203. if ($object instanceof Mage_Catalog_Model_Layer_Filter_Item) { // fallback for swatches loaded for nav filters
  204. $source = $object->getFilter()->getAttributeModel()->getFrontend()->getAttribute()->getSource();
  205. foreach ($source->getAllOptions(false, true) as $option) {
  206. if ($option['value'] == $object->getValue()) {
  207. $defaultValue = Mage_ConfigurableSwatches_Helper_Data::normalizeKey($option['label']);
  208. break;
  209. }
  210. }
  211. } elseif ($object instanceof Mage_Catalog_Model_Product) { // fallback for swatches loaded for product view
  212. $mapping = $object->getChildAttributeLabelMapping();
  213. if (isset($mapping[$value]['default_label'])) {
  214. $defaultValue = $mapping[$value]['default_label'];
  215. }
  216. }
  217. do {
  218. $filename = Mage::helper('configurableswatches')->getHyphenatedString($value) . $fileExt;
  219. $swatchImage = $this->_resizeSwatchImage($filename, 'media', $width, $height);
  220. if (!$swatchImage && $defaultValue == $value) {
  221. return ''; // no image found and no further fallback
  222. } elseif (!$swatchImage) {
  223. $value = $defaultValue; // fallback to default value
  224. } else {
  225. break; // we found an image
  226. }
  227. } while (true);
  228. return Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . $swatchImage;
  229. }
  230. /**
  231. * Performs the resize operation on the given swatch image file and returns a
  232. * relative path to the resulting image file
  233. *
  234. * @param string $filename
  235. * @param string $tag
  236. * @param int $width
  237. * @param int $height
  238. * @return string
  239. */
  240. protected function _resizeSwatchImage($filename, $tag, $width, $height)
  241. {
  242. // Form full path to where we want to cache resized version
  243. $destPathArr = array(
  244. self::SWATCH_CACHE_DIR,
  245. Mage::app()->getStore()->getId(),
  246. $width . 'x' . $height,
  247. $tag,
  248. trim($filename, '/'),
  249. );
  250. $destPath = implode('/', $destPathArr);
  251. // Check if cached image exists already
  252. if (!file_exists(Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . $destPath)) {
  253. // Check for source image
  254. if ($tag == 'product') {
  255. $sourceFilePath = Mage::getSingleton('catalog/product_media_config')->getBaseMediaPath() . $filename;
  256. } else {
  257. $sourceFilePath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA)
  258. . DS . self::SWATCH_FALLBACK_MEDIA_DIR . DS . $filename;
  259. }
  260. if (!file_exists($sourceFilePath)) {
  261. return false;
  262. }
  263. // Do resize and save
  264. $processor = new Varien_Image($sourceFilePath);
  265. $processor->resize($width, $height);
  266. $processor->save(Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . $destPath);
  267. Mage::helper('core/file_storage_database')->saveFile($destPath);
  268. }
  269. return $destPath;
  270. }
  271. /**
  272. * Cleans out the swatch image cache dir
  273. */
  274. public function clearSwatchesCache()
  275. {
  276. $directory = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . self::SWATCH_CACHE_DIR;
  277. $io = new Varien_Io_File();
  278. $io->rmdir($directory, true);
  279. Mage::helper('core/file_storage_database')->deleteFolder($directory);
  280. }
  281. /**
  282. * Determine whether to show an image in the product media gallery
  283. *
  284. * @param Mage_Catalog_Model_Product $product
  285. * @param Varien_Object $image
  286. * @return bool
  287. */
  288. public function filterImageInGallery($product, $image)
  289. {
  290. if (!Mage::helper('configurableswatches')->isEnabled()) {
  291. return true;
  292. }
  293. if (!isset($this->_productImageFilters[$product->getId()])) {
  294. $mapping = call_user_func_array("array_merge_recursive", $product->getChildAttributeLabelMapping());
  295. $filters = array_unique($mapping['labels']);
  296. $filters = array_merge($filters, array_map(function ($label) {
  297. return $label . Mage_ConfigurableSwatches_Helper_Productimg::SWATCH_LABEL_SUFFIX;
  298. }, $filters));
  299. $this->_productImageFilters[$product->getId()] = $filters;
  300. }
  301. return !in_array(Mage_ConfigurableSwatches_Helper_Data::normalizeKey($image->getLabel()),
  302. $this->_productImageFilters[$product->getId()]);
  303. }
  304. }