Files
bio-concept-pharma/web/modules/magic360/magic360.php
2019-11-17 19:14:07 +01:00

1624 lines
74 KiB
PHP

<?php
/**
* 2005-2017 Magic Toolbox
*
* NOTICE OF LICENSE
*
* This file is licenced under the Software License Agreement.
* With the purchase or the installation of the software in your application
* you accept the licence agreement.
*
* You must not modify, adapt or create derivative works of this source code
*
* @author Magic Toolbox <support@magictoolbox.com>
* @copyright Copyright (c) 2017 Magic Toolbox <support@magictoolbox.com>. All rights reserved
* @license https://www.magictoolbox.com/license/
*/
if (!defined('_PS_VERSION_')) {
exit;
}
if (!isset($GLOBALS['magictoolbox'])) {
$GLOBALS['magictoolbox'] = array();
$GLOBALS['magictoolbox']['filters'] = array();
$GLOBALS['magictoolbox']['isProductScriptIncluded'] = false;
$GLOBALS['magictoolbox']['standardTool'] = '';
$GLOBALS['magictoolbox']['selectorImageType'] = '';
$GLOBALS['magictoolbox']['isProductBlockProcessed'] = false;
}
if (!isset($GLOBALS['magictoolbox']['magic360'])) {
$GLOBALS['magictoolbox']['magic360'] = array();
$GLOBALS['magictoolbox']['magic360']['headers'] = false;
$GLOBALS['magictoolbox']['magic360']['scripts'] = '';
}
class Magic360 extends Module
{
/* PrestaShop v1.5 or above */
public $isPrestaShop15x = false;
/* PrestaShop v1.5.5.0 or above */
public $isPrestaShop155x = false;
/* PrestaShop v1.6 or above */
public $isPrestaShop16x = false;
/* PrestaShop v1.7 or above */
public $isPrestaShop17x = false;
/* Smarty v3 template engine */
public $isSmarty3 = false;
/* Smarty 'getTemplateVars' function name */
public $getTemplateVars = 'getTemplateVars';
/* Suffix was added to default images types since version 1.5.1.0 */
public $imageTypeSuffix = '';
/* To display 'product.js' file inline */
public $displayInlineProductJs = false;
/* Ajax request flag */
public $isAjaxRequest = false;
/* Featured Products module name */
public $featuredProductsModule = 'homefeatured';
/* Top-sellers block module name */
public $topSellersModule = 'blockbestsellers';
/* New Products module name */
public $newProductsModule = 'blocknewproducts';
/* Specials Products module name */
public $specialsProductsModule = 'blockspecials';
private $startTime = 0;
private $maxExecutionTime = 7200;
private $yAlign = '';
private $xAlign = '';
private $transparency = 60;
/* NOTE: identifying PrestaShop version class */
public $psVersionClass = 'mt-ps-old';
public function __construct()
{
$this->name = 'magic360';
$this->tab = 'Tools';
$this->version = '5.9.13';
$this->author = 'Magic Toolbox';
$this->module_key = 'f66a94ae198cc968e88c91c514af95a0';
//NOTE: to link bootstrap css for settings page in v1.6
$this->bootstrap = true;
parent::__construct();
$this->displayName = 'Magic 360';
$this->description = 'Spin products round in 360 degrees and zoom them.';
$this->confirmUninstall = 'All magic360 settings would be deleted. Do you really want to uninstall this module ?';
$this->isPrestaShop15x = version_compare(_PS_VERSION_, '1.5', '>=');
$this->isPrestaShop155x = version_compare(_PS_VERSION_, '1.5.5', '>=');
$this->isPrestaShop16x = version_compare(_PS_VERSION_, '1.6', '>=');
$this->isPrestaShop17x = version_compare(_PS_VERSION_, '1.7', '>=');
$this->displayInlineProductJs = version_compare(_PS_VERSION_, '1.6.0.3', '>=') && version_compare(_PS_VERSION_, '1.6.0.7', '<');
if ($this->isPrestaShop16x) {
$this->tab = 'others';
}
$this->isSmarty3 = $this->isPrestaShop15x || Configuration::get('PS_FORCE_SMARTY_2') === '0';
if ($this->isSmarty3) {
//Smarty v3 template engine
$this->getTemplateVars = 'getTemplateVars';
} else {
//Smarty v2 template engine
$this->getTemplateVars = 'get_template_vars';
}
$this->imageTypeSuffix = version_compare(_PS_VERSION_, '1.5.1.0', '>=') ? '_default' : '';
$this->isAjaxRequest = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
if ($this->isPrestaShop17x) {
$this->featuredProductsModule = 'ps_featuredproducts';
$this->topSellersModule = 'ps_bestsellers';
$this->newProductsModule = 'ps_newproducts';
$this->specialsProductsModule = 'ps_specials';
}
if (version_compare(_PS_VERSION_, '1.4.5.1', '>=')) {
$this->psVersionClass = 'mt-ps-1451x';
if ($this->isPrestaShop15x) {
$this->psVersionClass = 'mt-ps-15x';
if ($this->isPrestaShop16x) {
$this->psVersionClass = 'mt-ps-16x';
if ($this->isPrestaShop17x) {
$this->psVersionClass = 'mt-ps-17x';
}
}
}
}
}
protected function _generateConfigXml($need_instance = 1)
{
//NOTE: this fix an issue with description in PrestaShop 1.4
$description = htmlentities($this->description, ENT_COMPAT, 'UTF-8');
$this->description = htmlentities($description);
return parent::_generateConfigXml($need_instance);
}
public function install()
{
if (!parent::install()
|| !$this->registerHook($this->isPrestaShop15x ? 'displayHeader' : 'header')
|| !$this->registerHook($this->isPrestaShop15x ? 'displayFooterProduct' : 'productFooter')
|| !$this->registerHook($this->isPrestaShop15x ? 'displayFooter' : 'footer')
|| !$this->registerHook($this->isPrestaShop15x ? 'displayAdminProductsExtra' : 'backOfficeFooter')
|| !$this->installDB()
|| !$this->fixCSS()
|| !$this->createImageFolder('magic360')
|| !$this->resize360Icon()
/**/) {
return false;
}
return true;
}
private function createImageFolder($imageFolderName)
{
if (!is_dir(_PS_IMG_DIR_.$imageFolderName)) {
if (!mkdir(_PS_IMG_DIR_.$imageFolderName, 0755)) {
return false;
}
}
return true;
}
private function resize360Icon($icon = 'modules/magic360/views/img/360icon.png')
{
$result = true;
if (!file_exists(_PS_ROOT_DIR_.DIRECTORY_SEPARATOR.$icon)) {
return false;
}
preg_match('/^.*?\/([^\/]*)\.([^\.]*)$/is', $icon, $matches);
list(, $imageFileName, $imageFileExt) = $matches;
$imagesTypes = ImageType::getImagesTypes();
$imageResizeMethod = 'imageResize';
//NOTE: __autoload function in Prestashop 1.3.x leads to PHP fatal error because ImageManager class does not exists
// can not use class_exists('ImageManager', false) because ImageManager class will not load where it is needed
// so check version before
if ($this->isPrestaShop15x && class_exists('ImageManager') && method_exists('ImageManager', 'resize')) {
$imageResizeMethod = array('ImageManager', 'resize');
}
$result = $result && call_user_func(
$imageResizeMethod,
_PS_ROOT_DIR_.DIRECTORY_SEPARATOR.$icon,
_PS_IMG_DIR_.'magic360'.DIRECTORY_SEPARATOR.$imageFileName.'.'.$imageFileExt,
null,
null,
$imageFileExt
);
foreach ($imagesTypes as $k => $imageType) {
$result = $result && call_user_func(
$imageResizeMethod,
_PS_ROOT_DIR_.DIRECTORY_SEPARATOR.$icon,
_PS_IMG_DIR_.'magic360'.DIRECTORY_SEPARATOR.$imageFileName.'-'.Tools::stripslashes($imageType['name']).'.'.$imageFileExt,
$imageType['width'],
$imageType['height'],
$imageFileExt
);
}
return $result;
}
private function installDB()
{
if (!Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'magic360_settings` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`block` VARCHAR(32) NOT NULL,
`name` VARCHAR(32) NOT NULL,
`value` TEXT,
`default_value` TEXT,
`enabled` TINYINT(1) UNSIGNED NOT NULL,
`default_enabled` TINYINT(1) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;')
|| !$this->fillDB()
|| !$this->fixDefaultValues()
|| !Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'magic360_images` (
`id_image` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_product` INT(10) UNSIGNED NOT NULL,
`position` SMALLINT(2) UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id_image`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;')
|| !Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'magic360_columns` (
`id_product` INT(10) UNSIGNED NOT NULL,
`columns` SMALLINT(2) UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id_product`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;')
/**/) {
return false;
}
return true;
}
private function fixCSS()
{
//fix url's in css files
$path = dirname(__FILE__);
$list = glob($path.'/*');
$files = array();
if (is_array($list)) {
$listLength = count($list);
for ($i = 0; $i < $listLength; $i++) {
if (is_dir($list[$i])) {
if (!in_array(basename($list[$i]), array('.svn', '.git'))) {
$add = glob($list[$i].'/*');
if (is_array($add)) {
$list = array_merge($list, $add);
$listLength += count($add);
}
}
} elseif (preg_match('#\.css$#i', $list[$i])) {
$files[] = $list[$i];
}
}
}
foreach ($files as $file) {
$cssPath = dirname($file);
$cssRelPath = str_replace($path, '', $cssPath);
$toolPath = _MODULE_DIR_.'magic360'.$cssRelPath;
$pattern = '#url\(\s*(\'|")?(?!data:|mhtml:|http(?:s)?:|/)([^\)\s\'"]+?)(?(1)\1)\s*\)#is';
$replace = 'url($1'.$toolPath.'/$2$1)';
$fileContents = Tools::file_get_contents($file);
$fixedFileContents = preg_replace($pattern, $replace, $fileContents);
//preg_match_all($pattern, $fileContents, $matches, PREG_SET_ORDER);
//debug_log($matches);
if ($fixedFileContents != $fileContents) {
$fp = fopen($file, 'w+');
if ($fp) {
fwrite($fp, $fixedFileContents);
fclose($fp);
}
}
}
return true;
}
public function fixDefaultValues()
{
$result = true;
if (version_compare(_PS_VERSION_, '1.5.1.0', '>=')) {
$sql = 'UPDATE `'._DB_PREFIX_.'magic360_settings` SET `value`=CONCAT(value, \'_default\'), `default_value`=CONCAT(default_value, \'_default\') WHERE (`name`=\'thumb-image\' OR `name`=\'selector-image\' OR `name`=\'large-image\') AND `value`!=\'original\'';
$result = Db::getInstance()->Execute($sql);
}
if ($this->isPrestaShop16x) {
}
if ($this->isPrestaShop17x) {
$sql = 'UPDATE `'._DB_PREFIX_.'magic360_settings` SET `enabled`=1, `value`=\'large_default\', `default_value`=\'large_default\' WHERE `name`=\'large-image\'';
$result = Db::getInstance()->Execute($sql);
$sql = 'UPDATE `'._DB_PREFIX_.'magic360_settings` SET `enabled`=1, `value`=\'medium_default\', `default_value`=\'medium_default\' WHERE `name`=\'thumb-image\' AND `block`=\'product\'';
$result = Db::getInstance()->Execute($sql);
$sql = 'UPDATE `'._DB_PREFIX_.'magic360_settings` SET `enabled`=1, `value`=\'home_default\', `default_value`=\'home_default\' WHERE `name`=\'thumb-image\' AND (`block`=\'category\' OR `block`=\'manufacturer\' OR `block`=\'newproductpage\' OR `block`=\'bestsellerspage\' OR `block`=\'specialspage\')';
$result = Db::getInstance()->Execute($sql);
$sql = 'UPDATE `'._DB_PREFIX_.'magic360_settings` SET `enabled`=1, `value`=\'home_default\', `default_value`=\'home_default\' WHERE `name`=\'thumb-image\' AND (`block`=\'blocknewproducts_home\' OR `block`=\'blockbestsellers_home\' OR `block`=\'blockspecials_home\' OR `block`=\'homefeatured\')';
$result = Db::getInstance()->Execute($sql);
$sql = 'UPDATE `'._DB_PREFIX_.'magic360_settings` SET `enabled`=1, `value`=\'small_default\', `default_value`=\'small_default\' WHERE `name`=\'thumb-image\' AND (`block`=\'blocknewproducts\' OR `block`=\'blockbestsellers\' OR `block`=\'blockspecials\' OR `block`=\'blockviewed\')';
$result = Db::getInstance()->Execute($sql);
}
return $result;
}
public function uninstall()
{
if (!parent::uninstall() || !$this->uninstallDB()) {
return false;
}
return true;
}
private function uninstallDB()
{
return Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'magic360_settings`;');
}
public function disable($forceAll = false)
{
return parent::disable($forceAll);
}
public function enable($forceAll = false)
{
return parent::enable($forceAll);
}
public function getImagesTypes()
{
if (!isset($GLOBALS['magictoolbox']['imagesTypes'])) {
$GLOBALS['magictoolbox']['imagesTypes'] = array('original');
//NOTE: get image type values
$sql = 'SELECT name FROM `'._DB_PREFIX_.'image_type` ORDER BY `id_image_type` ASC';
$result = Db::getInstance()->ExecuteS($sql);
foreach ($result as $row) {
$GLOBALS['magictoolbox']['imagesTypes'][] = $row['name'];
}
}
return $GLOBALS['magictoolbox']['imagesTypes'];
}
public function getContent()
{
if ($this->needUpdateDb()) {
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'magic360_settings`');
$this->fillDB();
$this->fixDefaultValues();
}
$action = Tools::getValue('magic360-submit-action', false);
$activeTab = Tools::getValue('magic360-active-tab', false);
if ($action == 'reset' && $activeTab) {
Db::getInstance()->Execute(
'UPDATE `'._DB_PREFIX_.'magic360_settings` SET `value`=`default_value`, `enabled`=`default_enabled` WHERE `block`=\''.pSQL($activeTab).'\''
);
}
$tool = $this->loadTool();
$paramsMap = $this->getParamsMap();
$_imagesTypes = array(
'large',
'thumb'
);
foreach ($_imagesTypes as $name) {
foreach ($this->getBlocks() as $blockId => $blockLabel) {
if ($tool->params->paramExists($name.'-image', $blockId)) {
$tool->params->setValues($name.'-image', $this->getImagesTypes(), $blockId);
}
}
}
//debug_log($_GET);
//debug_log($_POST);
$params = Tools::getValue('magic360', false);
//NOTE: save settings
if ($action == 'save' && $params) {
$productIcon = isset($params['default']['icon']) ? $params['default']['icon'] : '';
if (!empty($productIcon)) {
$this->resize360Icon($productIcon);
}
foreach ($paramsMap as $blockId => $groups) {
foreach ($groups as $group) {
foreach ($group as $param => $required) {
if (isset($params[$blockId][$param])) {
$valueToSave = $value = trim($params[$blockId][$param]);
switch ($tool->params->getType($param)) {
case 'num':
$valueToSave = $value = (int)$value;
break;
case 'array':
if (!in_array($value, $tool->params->getValues($param))) {
$valueToSave = $value = $tool->params->getDefaultValue($param);
}
$valueToSave = pSQL($valueToSave);
break;
case 'text':
$valueToSave = $value = str_replace('"', '&quot;', $value);//NOTE: fixed issue with "
$valueToSave = pSQL($value);
break;
}
Db::getInstance()->Execute(
'UPDATE `'._DB_PREFIX_.'magic360_settings` SET `value`=\''.$valueToSave.'\', `enabled`=1 WHERE `block`=\''.pSQL($blockId).'\' AND `name`=\''.pSQL($param).'\''
);
$tool->params->setValue($param, $value, $blockId);
} else {
Db::getInstance()->Execute(
'UPDATE `'._DB_PREFIX_.'magic360_settings` SET `enabled`=0 WHERE `block`=\''.pSQL($blockId).'\' AND `name`=\''.pSQL($param).'\''
);
if ($tool->params->paramExists($param, $blockId)) {
$tool->params->removeParam($param, $blockId);
}
}
}
}
}
}
if ($action == 'regenerate') {
$errors = array();
$this->startTime = time();
ini_set('max_execution_time', $this->maxExecutionTime);
$this->maxExecutionTime = (int)ini_get('max_execution_time');
switch ($this->regenerateThumbnails()) {
case 'timeout':
$errors[] = 'Only part of the images have been regenerated, server timed out before finishing.';
// no break
case 'done':
// no break
}
$productIcon = isset($params['default']['icon']) ? $params['default']['icon'] : '';
if (!empty($productIcon)) {
$this->resize360Icon($productIcon);
}
}
include(dirname(__FILE__).'/admin/magictoolbox.settings.editor.class.php');
$settings = new MagictoolboxSettingsEditorClass(dirname(__FILE__).DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'js');
$settings->paramsMap = $this->getParamsMap();
$settings->core = $this->loadTool();
$settings->profiles = $this->getBlocks();
$settings->pathToJS = dirname(__FILE__).DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'js';
$settings->action = htmlentities($_SERVER['REQUEST_URI']);
$settings->setResourcesURL(_MODULE_DIR_.'magic360/admin/resources/');
$settings->setResourcesURL(_MODULE_DIR_.'magic360/views/js/', 'js');
$settings->setResourcesURL(_MODULE_DIR_.'magic360/views/css/', 'css');
$settings->namePrefix = 'magic360';
$settings->languagesData = Db::getInstance()->ExecuteS('SELECT id_lang as id, iso_code as code, active FROM `'._DB_PREFIX_.'lang` ORDER BY `id_lang` ASC');
if ($activeTab) {
$settings->activeTab = $activeTab;
}
$settings->setAdditionalButton('regenerate', 'Regenerate thumbnails');
$html = $settings->getHTML();
return $html;
}
public function needUpdateDb()
{
//NOTE: check if all new params are present in DB
$params = array();
$sql = 'SELECT `name`, `value`, `block` FROM `'._DB_PREFIX_.'magic360_settings`';
$result = Db::getInstance()->ExecuteS($sql);
foreach ($result as $row) {
if (!isset($params[$row['block']])) {
$params[$row['block']] = array();
}
$params[$row['block']][$row['name']] = $row['value'];
}
$needUpdate = false;
$paramsMap = $this->getParamsMap();
foreach ($paramsMap as $blockId => $groups) {
foreach ($groups as $group) {
foreach ($group as $param => $required) {
if (!isset($params[$blockId][$param])) {
$needUpdate = true;
break 3;
}
}
}
}
return $needUpdate;
}
private function regenerateThumbnails()
{
$imagesData = Db::getInstance()->ExecuteS('SELECT id_product, id_image FROM `'._DB_PREFIX_.'magic360_images`');
$imagesCount = count($imagesData);
if (!$imagesCount) {
return;
}
$imagesPath = _PS_IMG_DIR_.'magic360/';
$imagesTypes = ImageType::getImagesTypes();
$isWatermarkActive = false;
$watermarkSuffix = '';
if (Module::isInstalled('watermark')) {
$isWatermarkActive = Module::getInstanceByName('watermark')->active;
if ($this->isPrestaShop15x && Shop::getContext() == Shop::CONTEXT_SHOP) {
$str_shop = '-'.(int)$this->context->shop->id;
} else {
$str_shop = '';
}
$watermarkGif = _PS_MODULE_DIR_.'watermark/watermark'.$str_shop.'.gif';
if (!file_exists($watermarkGif)) {
$watermarkGif = _PS_MODULE_DIR_.'watermark/watermark.gif';
}
$config = Configuration::getMultiple(array('WATERMARK_Y_ALIGN', 'WATERMARK_X_ALIGN', 'WATERMARK_TRANSPARENCY'));
$this->yAlign = isset($config['WATERMARK_Y_ALIGN']) ? $config['WATERMARK_Y_ALIGN'] : '';
$this->xAlign = isset($config['WATERMARK_X_ALIGN']) ? $config['WATERMARK_X_ALIGN'] : '';
$this->transparency = isset($config['WATERMARK_TRANSPARENCY']) ? $config['WATERMARK_TRANSPARENCY'] : 60;
}
$imageResizeMethod = 'imageResize';
//NOTE: __autoload function in Prestashop 1.3.x leads to PHP fatal error because ImageManager class does not exists
// can not use class_exists('ImageManager', false) because ImageManager class will not load where it is needed
// so check version before
if ($this->isPrestaShop15x && class_exists('ImageManager') && method_exists('ImageManager', 'resize')) {
$imageResizeMethod = array('ImageManager', 'resize');
}
foreach ($imagesData as $data) {
$baseName = $data['id_product'].'-'.$data['id_image'];
$files = glob($imagesPath.$baseName.'-*.jpg');
if ($files !== false && !empty($files)) {
foreach ($files as $file) {
if (is_file($file)) {
@unlink($file);
}
}
}
if (file_exists($imagesPath.$baseName.'.jpg')) {
if ($isWatermarkActive) {
$watermarkedImage = $imagesPath.$baseName.'-watermark.jpg';
if (is_file($watermarkedImage)) {
@unlink($watermarkedImage);
}
if ($this->watermarkByImage($imagesPath.$baseName.'.jpg', $watermarkGif, $watermarkedImage)) {
$watermarkSuffix = '-watermark';
}
}
foreach ($imagesTypes as $k => $imageType) {
call_user_func(
$imageResizeMethod,
$imagesPath.$baseName.$watermarkSuffix.'.jpg',
$imagesPath.$baseName.'-'.Tools::stripslashes($imageType['name']).'.jpg',
$imageType['width'],
$imageType['height'],
'jpg'
);
}
}
if ($this->maxExecutionTime && (time() - $this->startTime > $this->maxExecutionTime - 4)) {
return 'timeout';
}
}
return 'done';
}
private function watermarkByImage($imagepath, $watermarkpath, $outputpath)
{
$Xoffset = $Yoffset = $xpos = $ypos = 0;
if (!$image = imagecreatefromjpeg($imagepath)) {
return false;
}
if (!$imagew = imagecreatefromgif($watermarkpath)) {
die($this->l('The watermark image is not a real gif, please CONVERT the image.'));
}
list($watermarkWidth, $watermarkHeight) = getimagesize($watermarkpath);
list($imageWidth, $imageHeight) = getimagesize($imagepath);
if ($this->xAlign == 'middle') {
$xpos = $imageWidth / 2 - $watermarkWidth / 2 + $Xoffset;
}
if ($this->xAlign == 'left') {
$xpos = 0 + $Xoffset;
}
if ($this->xAlign == 'right') {
$xpos = $imageWidth - $watermarkWidth - $Xoffset;
}
if ($this->yAlign == 'middle') {
$ypos = $imageHeight / 2 - $watermarkHeight / 2 + $Yoffset;
}
if ($this->yAlign == 'top') {
$ypos = 0 + $Yoffset;
}
if ($this->yAlign == 'bottom') {
$ypos = $imageHeight - $watermarkHeight - $Yoffset;
}
if (!imagecopymerge($image, $imagew, $xpos, $ypos, 0, 0, $watermarkWidth, $watermarkHeight, $this->transparency)) {
return false;
}
return imagejpeg($image, $outputpath, 100);
}
public function loadTool($profile = false, $force = false)
{
if (!isset($GLOBALS['magictoolbox']['magic360']['class']) || $force) {
require_once(dirname(__FILE__).'/magic360.module.core.class.php');
$GLOBALS['magictoolbox']['magic360']['class'] = new Magic360ModuleCoreClass();
$tool = &$GLOBALS['magictoolbox']['magic360']['class'];
// load current params
$sql = 'SELECT `name`, `value`, `block` FROM `'._DB_PREFIX_.'magic360_settings` WHERE `enabled`=1';
$result = Db::getInstance()->ExecuteS($sql);
//NOTE: get data without cache
//$result = Db::getInstance()->ExecuteS($sql, true, false);
foreach ($result as $row) {
$tool->params->setValue($row['name'], $row['value'], $row['block']);
//NOTE: spike for copy values to 'product' profile
$tool->params->setValue($row['name'], $row['value'], 'product');
}
// load translates
$GLOBALS['magictoolbox']['magic360']['translates'] = $this->getMessages();
$translates = & $GLOBALS['magictoolbox']['magic360']['translates'];
foreach ($this->getBlocks() as $block => $label) {
if ($translates[$block]['message']['title'] != $translates[$block]['message']['translate']) {
$tool->params->setValue('message', $translates[$block]['message']['translate'], $block);
//NOTE: spike for translate 'message' option
$tool->params->setValue('message', $translates[$block]['message']['translate'], 'product');
}
//NOTE: copy values to general profile because lang options can be setted in the headers only
if ($translates[$block]['loading-text']['title'] != $translates[$block]['loading-text']['translate']) {
$tool->params->setValue('loading-text', $translates[$block]['loading-text']['translate'], $tool->params->generalProfile);
}
if ($translates[$block]['fullscreen-loading-text']['title'] != $translates[$block]['fullscreen-loading-text']['translate']) {
$tool->params->setValue('fullscreen-loading-text', $translates[$block]['fullscreen-loading-text']['translate'], $tool->params->generalProfile);
}
if ($translates[$block]['hint-text']['title'] != $translates[$block]['hint-text']['translate']) {
$tool->params->setValue('hint-text', $translates[$block]['hint-text']['translate'], $tool->params->generalProfile);
}
if ($translates[$block]['mobile-hint-text']['title'] != $translates[$block]['mobile-hint-text']['translate']) {
$tool->params->setValue('mobile-hint-text', $translates[$block]['mobile-hint-text']['translate'], $tool->params->generalProfile);
}
//NOTE: prepare image types
foreach (array('large', 'selector', 'thumb') as $name) {
if ($tool->params->checkValue($name.'-image', 'original', $block)) {
$tool->params->setValue($name.'-image', false, $block);
$tool->params->setValue($name.'-image', false, 'product');
}
}
}
}
$tool = &$GLOBALS['magictoolbox']['magic360']['class'];
if ($profile) {
$tool->params->setProfile($profile);
}
return $tool;
}
public function hookBackOfficeFooter($params)
{
$pid = Tools::getValue('id_product');
$theme = '';
if (version_compare(_PS_VERSION_, '1.4.0', '>=')) {
//global $employee;
$employee = &$GLOBALS['employee'];
$theme = $employee->bo_theme;
}
$url = _MODULE_DIR_."magic360/magic360.images.settings.php?id_product={$pid}&theme={$theme}";
$js = <<<JS
<script type="text/javascript">
//<![CDATA[
var magic360TabNumber = $('.tab-page').length+1;
$('.tab-page:last').after('<div class="tab-page" id="step'+magic360TabNumber+'"><h4 class="tab"><a href="#">'+magic360TabNumber+'. Magic 360</a></h4><iframe id="magic360ImagesFrame" name="magic360ImagesFrame" src="{$url}" style="width: 100%;border: 0;min-height: 400px;"></iframe></div>');
//]]>
</script>
JS;
return $js;
}
public function hookDisplayAdminProductsExtra($params)
{
if ($this->isPrestaShop17x) {
$pid = $params['id_product'];
} else {
$pid = Tools::getValue('id_product');
}
$theme = '';
//global $employee;
$employee = &$GLOBALS['employee'];
$theme = $employee->bo_theme.'%2Fcss';
$shopId = $this->context->shop->id;
$url = _MODULE_DIR_."magic360/magic360.images.settings.php?id_product={$pid}&theme={$theme}&id_shop={$shopId}";
if ($this->isPrestaShop17x) {
$linkSelector = '$(\'a[href=\\\\#hooks]\')';
} else {
$linkSelector = '$(\'#link-ModuleMagic360\').parent()';
}
$html = <<<HTML
<script type="text/javascript">
//<![CDATA[
{$linkSelector}.click(function() {
var contentWindow = document.getElementById('magic360ImagesFrame').contentWindow;
if (typeof(contentWindow.magicToolboxFixFrameHeight) != 'undefined') {
contentWindow.magicToolboxFixFrameHeight();
} else {
setTimeout(function() {
document.getElementById('magic360ImagesFrame').contentWindow.magicToolboxFixFrameHeight();
}, 500);
}
});
//]]>
</script>
<iframe id="magic360ImagesFrame" name="magic360ImagesFrame" src="{$url}" style="width: 100%;border: 0;min-height: 400px;"></iframe>
HTML;
return $html;
}
public function hookHeader($params)
{
//global $smarty;
$smarty = &$GLOBALS['smarty'];
if (!$this->isPrestaShop15x) {
ob_start();
}
$headers = '';
$tool = $this->loadTool();
$tool->params->resetProfile();
if ($this->isPrestaShop17x) {
$page = $smarty->{$this->getTemplateVars}('page');
if (is_array($page) && isset($page['page_name'])) {
$page = $page['page_name'];
}
} else {
$page = $smarty->{$this->getTemplateVars}('page_name');
}
switch ($page) {
case 'product':
break;
default:
$page = '';
}
if ($tool->params->checkValue('include-headers-on-all-pages', 'Yes', 'default') && ($GLOBALS['magictoolbox']['magic360']['headers'] = true)
|| $tool->params->profileExists($page) && !$tool->params->checkValue('enable-effect', 'No', $page)
/**/) {
// include headers
$headers = $tool->getHeadersTemplate(_MODULE_DIR_.'magic360/views/js', _MODULE_DIR_.'magic360/views/css');
if (!$this->isPrestaShop17x) {
//NOTE: if we need this on product page!?
$headers .= '<script type="text/javascript" src="'._MODULE_DIR_.'magic360/views/js/common.js"></script>';
}
if ($page == 'product' && !$tool->params->checkValue('enable-effect', 'No', 'product')) {
$headers .= '
<script type="text/javascript">
</script>';
if (!$this->isPrestaShop17x && !$GLOBALS['magictoolbox']['isProductScriptIncluded']) {
$imagesCount = 0;
if ($id_product = (int)Tools::getValue('id_product')) {
$images = Db::getInstance()->ExecuteS('SELECT id_image FROM `'._DB_PREFIX_.'magic360_images` WHERE id_product='.$id_product.' ORDER BY position');
$imagesCount = count($images);
}
if ($imagesCount) {
if ($this->displayInlineProductJs || (bool)Configuration::get('PS_JS_DEFER')) {
//NOTE: include product.js as inline because it has to be called after previous inline scripts
$productJsCContents = Tools::file_get_contents(_PS_ROOT_DIR_.'/modules/magic360/views/js/product.js');
$headers .= "\n".'<script type="text/javascript">'.$productJsCContents.'</script>'."\n";
} else {
$headers .= "\n".'<script type="text/javascript" src="'._MODULE_DIR_.'magic360/views/js/product.js"></script>'."\n";
}
$GLOBALS['magictoolbox']['isProductScriptIncluded'] = true;
}
}
}
$domNotAvailable = extension_loaded('dom') ? false : true;
if ($this->displayInlineProductJs && $domNotAvailable) {
$scriptsPattern = '#(?:\s*+<script\b[^>]*+>.*?<\s*+/script\b[^>]*+>)++#Uims';
if (preg_match($scriptsPattern, $headers, $scripts)) {
$GLOBALS['magictoolbox']['magic360']['scripts'] =
'<!-- MAGIC360 HEADERS START -->'.$scripts[0].'<!-- MAGIC360 HEADERS END -->';
$headers = preg_replace($scriptsPattern, '', $headers);
}
}
if ($this->isSmarty3) {
//Smarty v3 template engine
if (isset ($GLOBALS['magictoolbox']['filters']['magicslideshow'])) {
$smarty->unregisterFilter('output', array(Module::getInstanceByName('magicslideshow'), 'parseTemplateCategory'));
}
if (isset($GLOBALS['magictoolbox']['filters']['magicscroll'])) {
$smarty->unregisterFilter('output', array(Module::getInstanceByName('magicscroll'), 'parseTemplateCategory'));
}
$smarty->registerFilter('output', array(Module::getInstanceByName('magic360'), 'parseTemplateCategory'));
if (isset($GLOBALS['magictoolbox']['filters']['magicslideshow'])) {
$smarty->registerFilter('output', array(Module::getInstanceByName('magicslideshow'), 'parseTemplateCategory'));
}
if (isset($GLOBALS['magictoolbox']['filters']['magicscroll'])) {
$smarty->registerFilter('output', array(Module::getInstanceByName('magicscroll'), 'parseTemplateCategory'));
}
} else {
//Smarty v2 template engine
if (isset($GLOBALS['magictoolbox']['filters']['magicslideshow'])) {
$smarty->unregister_outputfilter(array(Module::getInstanceByName('magicslideshow'), 'parseTemplateCategory'));
}
if (isset($GLOBALS['magictoolbox']['filters']['magicscroll'])) {
$smarty->unregister_outputfilter(array(Module::getInstanceByName('magicscroll'), 'parseTemplateCategory'));
}
$smarty->register_outputfilter(array(Module::getInstanceByName('magic360'), 'parseTemplateCategory'));
if (isset($GLOBALS['magictoolbox']['filters']['magicslideshow'])) {
$smarty->register_outputfilter(array(Module::getInstanceByName('magicslideshow'), 'parseTemplateCategory'));
}
if (isset($GLOBALS['magictoolbox']['filters']['magicscroll'])) {
$smarty->register_outputfilter(array(Module::getInstanceByName('magicscroll'), 'parseTemplateCategory'));
}
}
$GLOBALS['magictoolbox']['filters']['magic360'] = 'parseTemplateCategory';
// presta create new class every time when hook called
// so we need save our data in the GLOBALS
$GLOBALS['magictoolbox']['magic360']['cookie'] = $params['cookie'];
$GLOBALS['magictoolbox']['magic360']['productsViewedIds'] = (isset($params['cookie']->viewed) && !empty($params['cookie']->viewed)) ? explode(',', $params['cookie']->viewed) : array();
$headers = '<!-- MAGIC360 HEADERS START -->'.$headers.'<!-- MAGIC360 HEADERS END -->';
}
return $headers;
}
public function hookActionDispatcher($params)
{
//NOTE: registered for 1.7.x
if (!$this->isAjaxRequest) {
return;
}
switch ($params['controller_class']) {
case 'CategoryController':
$page = 'category';
break;
case 'SearchController':
$page = 'search';
break;
default:
return;
}
$smarty = &$GLOBALS['smarty'];
$smarty->assign('page', array(
'page_name' => $page
));
$this->hookHeader($params);
}
public function hookProductFooter($params)
{
//NOTE: we need save this data in the GLOBALS for compatible with some Prestashop modules which reset the $product smarty variable
if ($this->isPrestaShop17x && is_array($params['product'])) {
$GLOBALS['magictoolbox']['magic360']['product'] = array(
'id' => $params['product']['id'],
'name' => $params['product']['name'],
'link_rewrite' => $params['product']['link_rewrite']
);
} else {
$GLOBALS['magictoolbox']['magic360']['product'] = array(
'id' => $params['product']->id,
'name' => $params['product']->name,
'link_rewrite' => $params['product']->link_rewrite
);
}
return '';
}
public function hookFooter($params)
{
if (!$this->isPrestaShop15x) {
$contents = ob_get_contents();
ob_end_clean();
if ($GLOBALS['magictoolbox']['magic360']['headers'] == false) {
$contents = preg_replace('/<\!-- MAGIC360 HEADERS START -->.*?<\!-- MAGIC360 HEADERS END -->/is', '', $contents);
} else {
//NOTE: spike to place magic360 headers before magiczoom(plus) headers
$matches360 = array();
$matches = array();
$magic360HeadersPattern =
'<!-- MAGIC360 HEADERS START -->.*?<!-- MAGIC360 HEADERS END -->'.
'|'.
'<link\b[^>]*?\bhref="[^"]*?/magic360\.css"[^>]*+>[^<]*+'.
'<link\b[^>]*?\bhref="[^"]*?/magic360\.module\.css"[^>]*+>[^<]*+'.
'<script\b[^>]*?\bsrc="[^"]*?/magic360\.js"[^>]*+>(?:[^<]|<!)*?</script>[^<]*+'.
'(?:<script\b[^>]*+>(?:[^<]|<!)*?</script>[^<]*+){2}'.
'<script\b[^>]*?\bsrc="[^"]*?/magic360/views/js/common\.js"[^>]*+>(?:[^<]|<!)*?</script>';
$magiczoomHeadersPattern = '#<!-- Magic Zoom(?: Plus)? Prestashop module|<link\b[^>]*?\bhref="[^"]*?/magiczoom(?:plus)?/views/css/magic(?:scroll|zoom)(?:plus)?\.css"[^>]*+>#i';
$magicthumbHeadersPattern = '#(?:<!-- Magic Thumb Prestashop module[^>]*+>[^<]*+)?<link\b[^>]*?href="[^"]*?/magicthumb/views/css/magicscroll\.css"[^>]*+>#i';
if (preg_match($magiczoomHeadersPattern, $contents, $matches)) {
if (preg_match("#{$magic360HeadersPattern}#is", $contents, $matches360)) {
$contents = str_replace($matches360[0], '', $contents);
$contents = preg_replace($magiczoomHeadersPattern, $matches360[0].'$0', $contents, 1);
}
} elseif (preg_match($magicthumbHeadersPattern, $contents, $matches)) {
//NOTE: spike to place magic360 headers before magicscroll headers (that comes with magicthumb)
if (preg_match("#{$magic360HeadersPattern}#is", $contents, $matches360)) {
$contents = str_replace($matches360[0], '', $contents);
$contents = preg_replace($magicthumbHeadersPattern, $matches360[0].'$0', $contents, 1);
}
}
$contents = preg_replace('/<\!-- MAGIC360 HEADERS (START|END) -->/is', '', $contents);
//NOTE: add class for identifying PrestaShop version
if (preg_match('#(<body\b[^>]*?\sclass\s*+=\s*+"[^"]*+)("[^>]*+>)#is', $contents)) {
$contents = preg_replace('#(<body\b[^>]*?\sclass\s*+=\s*+"[^"]*+)("[^>]*+>)#is', '$1 '.$this->psVersionClass.'$2', $contents);
} else {
$contents = preg_replace('#(<body\s[^>]*+)>#is', '$1 class="'.$this->psVersionClass.'">', $contents);
}
}
echo $contents;
}
return '';
}
private static $outputMatches = array();
public function prepareOutput($output, $index = 'DEFAULT')
{
if (!isset(self::$outputMatches[$index])) {
$regExp = '<div\b[^>]*?\sclass\s*+=\s*+"[^"]*?(?<=\s|")MagicToolboxContainer(?=\s|")[^"]*+"[^>]*+>'.
'('.
'(?:'.
'[^<]++'.
'|'.
'<(?!/?div\b|!--)'.
'|'.
'<!--.*?-->'.
'|'.
'<div\b[^>]*+>'.
'(?1)'.
'</div\s*+>'.
')*+'.
')'.
'</div\s*+>';
preg_match_all('#'.$regExp.'#is', $output, self::$outputMatches[$index]);
foreach (self::$outputMatches[$index][0] as $key => $match) {
$output = str_replace($match, 'MAGIC360_MATCH_'.$index.'_'.$key.'_', $output);
}
} else {
foreach (self::$outputMatches[$index][0] as $key => $match) {
$output = str_replace('MAGIC360_MATCH_'.$index.'_'.$key.'_', $match, $output);
}
unset(self::$outputMatches[$index]);
}
return $output;
}
public function parseTemplateCategory($output, $smarty)
{
if ($this->isSmarty3) {
//Smarty v3 template engine
$currentTemplate = Tools::substr(basename($smarty->template_resource), 0, -4);
if ($currentTemplate == 'breadcrumb') {
$currentTemplate = 'product';
} elseif ($currentTemplate == 'pagination') {
$currentTemplate = 'category';
}
} else {
//Smarty v2 template engine
$currentTemplate = $smarty->currentTemplate;
}
if ($this->isPrestaShop17x && ($currentTemplate == 'index' || $currentTemplate == 'page') ||
$this->isPrestaShop15x && $currentTemplate == 'layout') {
if (version_compare(_PS_VERSION_, '1.5.5.0', '>=')) {
//NOTE: because we do not know whether the effect is applied to the blocks in the cache
$GLOBALS['magictoolbox']['magic360']['headers'] = true;
}
//NOTE: full contents in prestashop 1.5.x
if ($GLOBALS['magictoolbox']['magic360']['headers'] == false) {
$output = preg_replace('/<\!-- MAGIC360 HEADERS START -->.*?<\!-- MAGIC360 HEADERS END -->/is', '', $output);
} else {
//NOTE: spike to place magic360 headers before magiczoom(plus) headers
$matches360 = array();
$matches = array();
$magic360HeadersPattern =
'<!-- MAGIC360 HEADERS START -->.*?<!-- MAGIC360 HEADERS END -->'.
'|'.
'<link\b[^>]*?\bhref="[^"]*?/magic360\.css"[^>]*+>[^<]*+'.
'<link\b[^>]*?\bhref="[^"]*?/magic360\.module\.css"[^>]*+>[^<]*+'.
'<script\b[^>]*?\bsrc="[^"]*?/magic360\.js"[^>]*+>(?:[^<]|<!)*?</script>[^<]*+'.
'(?:<script\b[^>]*+>(?:[^<]|<!)*?</script>[^<]*+){2}'.
'<script\b[^>]*?\bsrc="[^"]*?/magic360/views/js/common\.js"[^>]*+>(?:[^<]|<!)*?</script>';
$magiczoomHeadersPattern = '#<!-- Magic Zoom(?: Plus)? Prestashop module|<link\b[^>]*?\bhref="[^"]*?/magiczoom(?:plus)?/views/css/magic(?:scroll|zoom)(?:plus)?\.css"[^>]*+>#i';
$magicthumbHeadersPattern = '#(?:<!-- Magic Thumb Prestashop module[^>]*+>[^<]*+)?<link\b[^>]*?href="[^"]*?/magicthumb/views/css/magicscroll\.css"[^>]*+>#i';
if (preg_match($magiczoomHeadersPattern, $output, $matches)) {
if (preg_match("#{$magic360HeadersPattern}#is", $output, $matches360)) {
$output = str_replace($matches360[0], '', $output);
$output = preg_replace($magiczoomHeadersPattern, $matches360[0].'$0', $output, 1);
}
} elseif (preg_match($magicthumbHeadersPattern, $output, $matches)) {
//NOTE: spike to place magic360 headers before magicscroll headers (that comes with magicthumb)
if (preg_match("#{$magic360HeadersPattern}#is", $output, $matches360)) {
$output = str_replace($matches360[0], '', $output);
$output = preg_replace($magicthumbHeadersPattern, $matches360[0].'$0', $output, 1);
}
}
$output = preg_replace('/<\!-- MAGIC360 HEADERS (START|END) -->/is', '', $output);
}
return $output;
}
switch ($currentTemplate) {
case 'search':
case 'manufacturer':
//$currentTemplate = 'manufacturer';
break;
case 'best-sales':
$currentTemplate = 'bestsellerspage';
break;
case 'new-products':
$currentTemplate = 'newproductpage';
break;
case 'prices-drop':
$currentTemplate = 'specialspage';
break;
case 'blockbestsellers-home':
$currentTemplate = 'blockbestsellers_home';
break;
case 'blockspecials-home':
$currentTemplate = 'blockspecials_home';
break;
case 'product-list'://for 'Layered navigation block'
if (strpos($_SERVER['REQUEST_URI'], 'blocklayered-ajax.php') !== false) {
$currentTemplate = 'category';
}
break;
//NOTE: just in case (issue 88975)
case 'ProductController':
$currentTemplate = 'product';
break;
case 'products':
if ($this->isPrestaShop17x && $this->isAjaxRequest) {
$page = $smarty->{$this->getTemplateVars}('page');
if (is_array($page) && isset($page['page_name'])) {
$currentTemplate = $page['page_name'];
}
}
break;
case 'ps_featuredproducts':
if ($this->isPrestaShop17x) {
$currentTemplate = 'homefeatured';
}
break;
case 'ps_bestsellers':
if ($this->isPrestaShop17x) {
$currentTemplate = 'blockbestsellers_home';
}
break;
case 'ps_newproducts':
if ($this->isPrestaShop17x) {
$currentTemplate = 'blocknewproducts_home';
}
break;
case 'ps_specials':
if ($this->isPrestaShop17x) {
$currentTemplate = 'blockspecials_home';
}
break;
}
$tool = $this->loadTool();
if (!$tool->params->profileExists($currentTemplate) || $tool->params->checkValue('enable-effect', 'No', $currentTemplate)) {
return $output;
}
$tool->params->setProfile($currentTemplate);
//global $link;
$link = &$GLOBALS['link'];
$cookie = &$GLOBALS['magictoolbox']['magic360']['cookie'];
if (method_exists($link, 'getImageLink')) {
$_link = &$link;
} else {
/* for Prestashop ver 1.1 */
$_link = &$this;
}
switch ($currentTemplate) {
case 'product':
//debug_log('Magic360 parseTemplateCategory product');
if (!isset($GLOBALS['magictoolbox']['magic360']['product'])) {
//for skip loyalty module product.tpl
break;
}
//NOTE: get some data from $GLOBALS for compatible with Prestashop modules which reset the $product smarty variable
//$product = &$GLOBALS['magictoolbox']['magic360']['product'];
$product = new Product((int)$GLOBALS['magictoolbox']['magic360']['product']['id'], true, (int)$cookie->id_lang);
$lrw = $product->link_rewrite;
$pid = (int)$product->id;
$images = Db::getInstance()->ExecuteS('SELECT id_image FROM `'._DB_PREFIX_.'magic360_images` WHERE id_product='.$pid.' ORDER BY position');
if (!count($images)) {
break;
}
$columns = Db::getInstance()->getValue('SELECT columns FROM `'._DB_PREFIX_.'magic360_columns` WHERE id_product='.$pid);
if (!$columns) {
//NOTE: To prevent division by zero
$columns = 1;
}
$tool->params->setValue('columns', $columns, 'product');
$productImagesData = array();
foreach ($images as $image) {
$id_image = (int)$image['id_image'];
$productImagesData[$id_image]['medium'] = $this->getMagic360ImageLink($lrw, $pid.'-'.$id_image, $tool->params->getValue('thumb-image'));
$productImagesData[$id_image]['img'] = $this->getMagic360ImageLink($lrw, $pid.'-'.$id_image, $tool->params->getValue('large-image'));
}
$GLOBALS['magictoolbox']['magic360']['headers'] = true;
$html = $tool->getMainTemplate($productImagesData, array('id' => 'productMagic360'));
if ($GLOBALS['magictoolbox']['standardTool']) {
$icon = $tool->params->getValue('icon');
$script = '';
if (!empty($icon)) {
preg_match('/^.*?\/([^\/]*)\.([^\.]*)$/is', $icon, $matches);
list(, $imageFileName, $imageFileExt) = $matches;
$icon = $imageFileName.'-'.Tools::stripslashes($GLOBALS['magictoolbox']['selectorImageType']).'.'.$imageFileExt;
if (file_exists(_PS_IMG_DIR_.'magic360'.DIRECTORY_SEPARATOR.$icon)) {
$aClasses = array(
'magictoolbox-selector',
'zoom-with-360',
'm360-selector',
);
$standardTool = $GLOBALS['magictoolbox'][$GLOBALS['magictoolbox']['standardTool']]['class'];
$originalLayout = $standardTool->params->checkValue('template', 'original', 'product');
if ($this->isPrestaShop17x) {
if ($originalLayout) {
$aClasses[] = 'thumb';
}
}
if ($standardTool->params->checkValue('360-as-primary-image', 'Yes', 'product')) {
$aClasses[] = 'active-selector';
if ($originalLayout) {
if ($this->isPrestaShop17x) {
$aClasses[] = 'selected';
} else {
$aClasses[] = 'shown';
}
}
}
$magic360Selector = '<a data-magic-slide-id="360" class="'.implode(' ', $aClasses).'" title="360" href="#" onclick="return false;"><img id="thumb_9999999999" src="'._PS_IMG_.'magic360/'.$icon.'" alt="360" /></a>';
$output = str_replace('<!-- MAGIC360SELECTOR -->', $magic360Selector, $output);
if ($this->isPrestaShop17x) {
$output = str_replace('<!-- MAGIC360SELECTOR_ESCAPED -->', str_replace('"', '\"', $magic360Selector), $output);
} else {
$script = '
<script type="text/javascript">
//NOTE: to display magic360 icon
//combinationImages[0][combinationImages[0].length] = 9999999999;
if (typeof(combinationImages) != "undefined") {
for (var combId in combinationImages) {
combinationImages[combId][combinationImages[combId].length] = 9999999999;
}
}
</script>';
}
} else {
$output = preg_replace('/<li id="thumbnail_9999999999"><!-- MAGIC360SELECTOR --><\/li>|<!-- MAGIC360SELECTOR -->/', '', $output);
}
}
$output = str_replace('<!-- MAGIC360 -->', $html.$script, $output);
$output = preg_replace('/<\!-- MAGIC360 HEADERS (START|END) -->/is', '', $output);
break;
}
$html = '<div class="MagicToolboxContainer">'.$html.'</div>';
//NOTE: append main container
if ($this->isPrestaShop17x) {
$mainImagePattern = '<div\b[^>]*?\bclass\s*+=\s*+"[^"]*?\bimages-container\b[^"]*+"[^>]*+>'.
'('.
'(?:'.
'[^<]++'.
'|'.
'<(?!/?div\b|!--)'.
'|'.
'<!--.*?-->'.
'|'.
'<div\b[^>]*+>'.
'(?1)'.
'</div\s*+>'.
')*+'.
')'.
'</div\s*+>';
} else {
//NOTE: 'image' class added to support custom theme #53897
$mainImagePattern = '(<div\b[^>]*?(?:\bid\s*+=\s*+"image-block"|\bclass\s*+=\s*+"[^"]*?\bimage\b[^"]*+")[^>]*+>)'.
'('.
'(?:'.
'[^<]++'.
'|'.
'<(?!/?div\b|!--)'.
'|'.
'<!--.*?-->'.
'|'.
'<div\b[^>]*+>'.
'(?2)'.
'</div\s*+>'.
')*+'.
')'.
'</div\s*+>';
}
$matches = array();
//preg_match_all('#'.$mainImagePattern.'#is', $output, $matches, PREG_SET_ORDER);
//debug_log($matches);
if (!preg_match('#'.$mainImagePattern.'#is', $output, $matches)) {
break;
}
if ($this->isPrestaShop17x) {
//NOTE: div.hidden-important can be replaced with ajax contents
$output = str_replace(
$matches[0],
'<div class="hidden-important">'.$matches[0].'</div>'.$html,
$output
);
//NOTE: cut arrows
$arrowsPattern = '<div\b[^>]*?\bclass\s*+=\s*+"[^"]*?\bscroll-box-arrows\b[^"]*+"[^>]*+>'.
'('.
'(?:'.
'[^<]++'.
'|'.
'<(?!/?div\b|!--)'.
'|'.
'<!--.*?-->'.
'|'.
'<div\b[^>]*+>'.
'(?1)'.
'</div\s*+>'.
')*+'.
')'.
'</div\s*+>';
$output = preg_replace('#'.$arrowsPattern.'#', '', $output);
$output = preg_replace('/<\!-- MAGIC360 HEADERS (START|END) -->/is', '', $output);
} else {
$iconsPattern = '<span\b[^>]*?\bclass\s*+=\s*+"[^"]*?\b(?:new-box|sale-box|discount)\b[^"]*+"[^>]*+>'.
'('.
'(?:'.
'[^<]++'.
'|'.
'<(?!/?span\b|!--)'.
'|'.
'<!--.*?-->'.
'|'.
'<span\b[^>]*+>'.
'(?1)'.
'</span\s*+>'.
')*+'.
')'.
'</span\s*+>';
$iconMatches = array();
if (preg_match_all('%'.$iconsPattern.'%is', $matches[2], $iconMatches, PREG_SET_ORDER)) {
foreach ($iconMatches as $key => $iconMatch) {
$matches[2] = str_replace($iconMatch[0], '', $matches[2]);
$iconMatches[$key] = $iconMatch[0];
}
}
$icons = implode('', $iconMatches);
$output = str_replace($matches[0], "{$matches[1]}{$icons}<div class=\"hidden-important\">{$matches[2]}</div>{$html}</div>", $output);
//NOTE: hide selectors from contents
//NOTE: 'image-additional' added to support custom theme #53897
//NOTE: div#views_block is parent for div#thumbs_list
$thumbsPattern = '(<div\b[^>]*?(?:\bid\s*+=\s*+"(?:views_block|thumbs_list)"|\bclass\s*+=\s*+"[^"]*?\bimage-additional\b[^"]*+")[^>]*+>)'.
'('.
'(?:'.
'[^<]++'.
'|'.
'<(?!/?div\b|!--)'.
'|'.
'<!--.*?-->'.
'|'.
'<div\b[^>]*+>'.
'(?2)'.
'</div\s*+>'.
')*+'.
')'.
'</div\s*+>';
$matches = array();
if (preg_match("#{$thumbsPattern}#is", $output, $matches)) {
if (strpos($matches[1], 'class')) {
$replace = preg_replace('#\bclass\s*+=\s*+"#i', '$0hidden-important ', $matches[1]);
} else {
$replace = preg_replace('#<div\b#i', '$0 class="hidden-important"', $matches[1]);
}
$output = str_replace($matches[1], $replace, $output);
}
//NOTE: remove "View full size" link (in old PrestaShop)
$output = preg_replace('/<li[^>]*+>[^<]*+<span[^>]*?id="view_full_size"[^>]*+>[^<]*<\/span>[^<]*+<\/li>/is', '', $output);
//NOTE: hide span#wrapResetImages or a#resetImages
$matches = array();
if (preg_match('#(?:<span\b[^>]*?\bid\s*+=\s*+"wrapResetImages"[^>]*+>|<a\b[^>]*?\bid\s*+=\s*+"resetImages"[^>]*+>)#is', $output, $matches)) {
if (strpos($matches[0], 'class')) {
$replace = preg_replace('#\bclass\s*+=\s*+"#i', '$0hidden-important ', $matches[0]);
} else {
$replace = preg_replace('#<span\b#i', '$0 class="hidden-important"', $matches[0]);
}
$output = str_replace($matches[0], $replace, $output);
}
}
$GLOBALS['magictoolbox']['isProductBlockProcessed'] = true;
break;
}
return $output;
}
public function getAllSpecial($id_lang, $beginning = false, $ending = false)
{
$currentDate = date('Y-m-d');
$result = Db::getInstance()->ExecuteS('
SELECT p.*, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, p.`ean13`,
i.`id_image`, il.`legend`, t.`rate`
FROM `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'tax` t ON t.`id_tax` = p.`id_tax`
WHERE (`reduction_price` > 0 OR `reduction_percent` > 0)
'.((!$beginning && !$ending) ?
'AND (`reduction_from` = `reduction_to` OR (`reduction_from` <= \''.pSQL($currentDate).'\' AND `reduction_to` >= \''.pSQL($currentDate).'\'))'
:
($beginning ? 'AND `reduction_from` <= \''.pSQL($beginning).'\'' : '').($ending ? 'AND `reduction_to` >= \''.pSQL($ending).'\'' : '')).'
AND p.`active` = 1
ORDER BY RAND()');
if (!$result) {
return false;
}
$rows = array();
foreach ($result as $row) {
$rows[] = Product::getProductProperties($id_lang, $row);
}
return $rows;
}
/* for Prestashop ver 1.1 */
public function getImageLink($name, $ids, $type = null)
{
return _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').'.jpg';
}
public function getMagic360ImageLink($name, $ids, $type = null)
{
return _PS_IMG_.'magic360/'.$ids.($type ? '-'.$type : '').'.jpg';
}
public function getProductDescription($id_product, $id_lang)
{
$sql = 'SELECT `description` FROM `'._DB_PREFIX_.'product_lang` WHERE `id_product` = '.(int)($id_product).' AND `id_lang` = '.(int)($id_lang);
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
return isset($result[0]['description'])? $result[0]['description'] : '';
}
public function setImageSizes()
{
static $sizes = array();
$tool = $this->loadTool();
$profile = $tool->params->getProfile();
if (!isset($sizes[$profile])) {
$thumbImageType = $tool->params->getValue('thumb-image');
$selectorImageType = $tool->params->getValue('selector-image');
$sql = 'SELECT name, width, height FROM `'._DB_PREFIX_.'image_type` WHERE name in (\''.pSQL($thumbImageType).'\', \''.pSQL($selectorImageType).'\')';
$result = Db::getInstance()->ExecuteS($sql);
$result[$result[0]['name']] = $result[0];
$result[$result[1]['name']] = $result[1];
$tool->params->setValue('thumb-max-width', $result[$thumbImageType]['width']);
$tool->params->setValue('thumb-max-height', $result[$thumbImageType]['height']);
$tool->params->setValue('selector-max-width', $result[$selectorImageType]['width']);
$tool->params->setValue('selector-max-height', $result[$selectorImageType]['height']);
$sizes[$profile] = true;
}
}
public function fillDB()
{
$sql = 'INSERT INTO `'._DB_PREFIX_.'magic360_settings` (`block`, `name`, `value`, `default_value`, `enabled`, `default_enabled`) VALUES
(\'default\', \'include-headers-on-all-pages\', \'No\', \'No\', 1, 1),
(\'default\', \'product-ids\', \'all\', \'all\', 1, 1),
(\'default\', \'columns\', \'36\', \'36\', 1, 1),
(\'default\', \'magnify\', \'Yes\', \'Yes\', 1, 1),
(\'default\', \'magnifier-width\', \'80%\', \'80%\', 1, 1),
(\'default\', \'magnifier-shape\', \'inner\', \'inner\', 1, 1),
(\'default\', \'fullscreen\', \'Yes\', \'Yes\', 1, 1),
(\'default\', \'spin\', \'drag\', \'drag\', 1, 1),
(\'default\', \'autospin-direction\', \'clockwise\', \'clockwise\', 1, 1),
(\'default\', \'sensitivityX\', \'50\', \'50\', 1, 1),
(\'default\', \'sensitivityY\', \'50\', \'50\', 1, 1),
(\'default\', \'mousewheel-step\', \'1\', \'1\', 1, 1),
(\'default\', \'autospin-speed\', \'3600\', \'3600\', 1, 1),
(\'default\', \'smoothing\', \'Yes\', \'Yes\', 1, 1),
(\'default\', \'autospin\', \'once\', \'once\', 1, 1),
(\'default\', \'autospin-start\', \'load,hover\', \'load,hover\', 1, 1),
(\'default\', \'autospin-stop\', \'click\', \'click\', 1, 1),
(\'default\', \'initialize-on\', \'load\', \'load\', 1, 1),
(\'default\', \'start-column\', \'1\', \'1\', 1, 1),
(\'default\', \'start-row\', \'auto\', \'auto\', 1, 1),
(\'default\', \'loop-column\', \'Yes\', \'Yes\', 1, 1),
(\'default\', \'loop-row\', \'No\', \'No\', 1, 1),
(\'default\', \'reverse-column\', \'No\', \'No\', 1, 1),
(\'default\', \'reverse-row\', \'No\', \'No\', 1, 1),
(\'default\', \'column-increment\', \'1\', \'1\', 1, 1),
(\'default\', \'row-increment\', \'1\', \'1\', 1, 1),
(\'default\', \'thumb-image\', \'large\', \'large\', 1, 1),
(\'default\', \'large-image\', \'thickbox\', \'thickbox\', 1, 1),
(\'default\', \'icon\', \'modules/magic360/views/img/360icon.png\', \'modules/magic360/views/img/360icon.png\', 1, 1),
(\'default\', \'show-message\', \'Yes\', \'Yes\', 1, 1),
(\'default\', \'message\', \'Drag image to spin\', \'Drag image to spin\', 1, 1),
(\'default\', \'loading-text\', \'Loading...\', \'Loading...\', 1, 1),
(\'default\', \'fullscreen-loading-text\', \'Loading large spin...\', \'Loading large spin...\', 1, 1),
(\'default\', \'hint\', \'Yes\', \'Yes\', 1, 1),
(\'default\', \'hint-text\', \'Drag to spin\', \'Drag to spin\', 1, 1),
(\'default\', \'mobile-hint-text\', \'Swipe to spin\', \'Swipe to spin\', 1, 1)';
if (!$this->isPrestaShop16x) {
$sql = preg_replace('/\r\n\s*..(?:blockbestsellers_home|blocknewproducts_home|blockspecials_home)\b[^\r]*+/i', '', $sql);
$sql = rtrim($sql, ',');
}
return Db::getInstance()->Execute($sql);
}
public function getBlocks()
{
$blocks = array(
'default' => 'Default settings'
);
if (!$this->isPrestaShop16x) {
unset($blocks['blockbestsellers_home'], $blocks['blocknewproducts_home'], $blocks['blockspecials_home']);
}
if ($this->isPrestaShop17x) {
unset($blocks['blocknewproducts'], $blocks['manufacturer'], $blocks['blockspecials'], $blocks['blockbestsellers'], $blocks['blockviewed']);
}
return $blocks;
}
public function getMessages()
{
return array(
'default' => array(
'loading-text' => array(
'title' => 'Default settings loading text',
'translate' => $this->l('Default settings loading text')
),
'fullscreen-loading-text' => array(
'title' => 'Default settings fullscreen loading text',
'translate' => $this->l('Default settings fullscreen loading text')
),
'hint-text' => array(
'title' => 'Default settings text of the hint on desktop',
'translate' => $this->l('Default settings text of the hint on desktop')
),
'mobile-hint-text' => array(
'title' => 'Default settings text of the hint on iOS/Android devices',
'translate' => $this->l('Default settings text of the hint on iOS/Android devices')
),
'message' => array(
'title' => 'Default settings message (under Magic 360)',
'translate' => $this->l('Default settings message (under Magic 360)')
)
)
);
}
public function getParamsMap()
{
$map = array(
'default' => array(
'General' => array(
'include-headers-on-all-pages' => true
),
'Magic 360' => array(
'magnify' => true,
'magnifier-width' => true,
'magnifier-shape' => true,
'fullscreen' => true,
'spin' => true,
'autospin-direction' => true,
'sensitivityX' => true,
'sensitivityY' => true,
'mousewheel-step' => true,
'autospin-speed' => true,
'smoothing' => true,
'autospin' => true,
'autospin-start' => true,
'autospin-stop' => true,
'initialize-on' => true,
'start-column' => true,
'start-row' => true,
'loop-column' => true,
'loop-row' => true,
'reverse-column' => true,
'reverse-row' => true,
'column-increment' => true,
'row-increment' => true
),
'Image type' => array(
'thumb-image' => true,
'large-image' => true
),
'Miscellaneous' => array(
'icon' => true,
'show-message' => true,
'message' => true,
'loading-text' => true,
'fullscreen-loading-text' => true,
'hint' => true,
'hint-text' => true,
'mobile-hint-text' => true
)
)
);
if (!$this->isPrestaShop16x) {
unset($map['blockbestsellers_home'], $map['blocknewproducts_home'], $map['blockspecials_home']);
}
if ($this->isPrestaShop17x) {
unset($map['blocknewproducts'], $map['manufacturer'], $map['blockspecials'], $map['blockbestsellers'], $map['blockviewed']);
}
return $map;
}
public function gebugVars($smarty = null)
{
if ($smarty === null) {
$smarty = &$GLOBALS['smarty'];
}
$result = array();
$vars = $smarty->{$this->getTemplateVars}();
if (is_array($vars)) {
foreach ($vars as $key => $value) {
$result[$key] = gettype($value);
}
} else {
$result = gettype($vars);
}
return $result;
}
}