From a78e7ecdb048ba0ae3980deae4014ce0284b914f Mon Sep 17 00:00:00 2001 From: rMontagne Date: Mon, 12 Sep 2011 15:46:36 +0000 Subject: [PATCH] [+] BO : Add Multiple Ajax Upload Image on AdminProduct --- admin-dev/ajax.php | 11 - admin-dev/tabs/AdminCatalog.php | 11 +- admin-dev/tabs/AdminProducts.php | 514 +++++++------- classes/FileUploader.php | 196 ++++++ css/admin.css | 43 ++ js/fileuploader.js | 1133 ++++++++++++++++++++++++++++++ translations/fr/errors.php | 20 +- 7 files changed, 1644 insertions(+), 284 deletions(-) create mode 100755 classes/FileUploader.php create mode 100755 js/fileuploader.js diff --git a/admin-dev/ajax.php b/admin-dev/ajax.php index a3a387c3e..d58755762 100644 --- a/admin-dev/ajax.php +++ b/admin-dev/ajax.php @@ -678,17 +678,6 @@ if (Tools::isSubmit('getChildrenCategories') && Tools::getValue('id_category_par die(Tools::jsonEncode($children_categories)); } -if (Tools::isSubmit('updateProductImageShopAsso')) -{ - if ($id_image = (int)Tools::getValue('id_image') AND $id_shop = (int)Tools::getValue('id_shop')) - { - if ((int)Tools::getValue('active')) - Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'image_shop (`id_image`, `id_shop`) VALUES('.(int)$id_image.', '.(int)$id_shop.')'); - else - Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'image_shop WHERE `id_image`='.(int)$id_image.' AND `id_shop`='.(int)$id_shop); - } -} - if (Tools::isSubmit('getNotifications')) { $notification = new Notification; diff --git a/admin-dev/tabs/AdminCatalog.php b/admin-dev/tabs/AdminCatalog.php index 2a914c49d..ab0b59475 100644 --- a/admin-dev/tabs/AdminCatalog.php +++ b/admin-dev/tabs/AdminCatalog.php @@ -68,7 +68,6 @@ class AdminCatalog extends AdminTab $id_category = $shop->getCategory(); } } - self::$_category = new Category($id_category); if (!Validate::isLoadedObject(self::$_category)) die('Category cannot be loaded'); @@ -113,6 +112,16 @@ class AdminCatalog extends AdminTab } $this->adminProducts->postProcess($this->token); } + public function ajaxProcess() + { + if (Tools::getValue('addImage') !== false) + $this->adminProducts->ajaxProcess(); + if (Tools::getValue('updateProductImageShopAsso')) + $this->adminProducts->ajaxProcess(); + if (Tools::getValue('deleteImage')) + $this->adminProducts->ajaxProcess(); + + } public function displayErrors() { diff --git a/admin-dev/tabs/AdminProducts.php b/admin-dev/tabs/AdminProducts.php index 863944407..46a9292ed 100644 --- a/admin-dev/tabs/AdminProducts.php +++ b/admin-dev/tabs/AdminProducts.php @@ -28,13 +28,13 @@ include_once(PS_ADMIN_DIR.'/tabs/AdminProfiles.php'); class AdminProducts extends AdminTab { - protected $maxFileSize = 20000000; + protected $maxFileSize = 20000000; private $_category; public function __construct() { - + $this->table = 'product'; $this->className = 'Product'; $this->lang = true; @@ -68,7 +68,6 @@ class AdminProducts extends AdminTab parent::__construct(); } - private function _cleanMetaKeywords($keywords) { if (!empty($keywords) && $keywords != '') @@ -416,28 +415,8 @@ class AdminProducts extends AdminTab { if ($this->tabAccess['edit'] === '1') { - /* Delete product image */ - if (isset($_GET['deleteImage'])) - { - $image->delete(); - - if (!Image::getCover($image->id_product)) - { - $first_img = Db::getInstance()->getRow(' - SELECT `id_image` FROM `'._DB_PREFIX_.'image` - WHERE `id_product` = '.(int)($image->id_product)); - Db::getInstance()->Execute(' - UPDATE `'._DB_PREFIX_.'image` - SET `cover` = 1 - WHERE `id_image` = '.(int)($first_img['id_image'])); - } - @unlink(_PS_TMP_IMG_DIR_.'/product_'.$image->id_product.'.jpg'); - @unlink(_PS_TMP_IMG_DIR_.'/product_mini_'.$image->id_product.'.jpg'); - Tools::redirectAdmin(self::$currentIndex.'&id_product='.$image->id_product.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&add'.$this->table.'&tabs=1'.'&token='.($token ? $token : $this->token)); - } - /* Update product image/legend */ - elseif (isset($_GET['editImage'])) + if (isset($_GET['editImage'])) { if ($image->cover) $_POST['cover'] = 1; @@ -856,6 +835,61 @@ class AdminProducts extends AdminTab parent::postProcess(true); } + public function ajaxProcess() + { + if (Tools::getValue('addImage') !== false) + { + self::$currentIndex = 'index.php?tab=AdminCatalog'; + $allowedExtensions = array("jpeg", "gif", "png", "jpg"); + // max file size in bytes + $sizeLimit = $this->maxFileSize; + $uploader = new FileUploader($allowedExtensions, $sizeLimit); + $result = $uploader->handleUpload(); + if (isset($result['success'])) + { + $shops = false; + if (Shop::isMultiShopActivated()) + $shops = Shop::getShops(); + $obj = new Product((int)Tools::getValue('id_product')); + $countImages = (int)Db::getInstance()->getValue('SELECT COUNT(*) FROM '._DB_PREFIX_.'image WHERE id_product = '.(int)$obj->id); + $images = Image::getImages($this->context->language->id, $obj->id); + $imagesTotal = Image::getImagesTotal($obj->id); + $html = $this->getLineTableImage($result['success'], $imagesTotal + 1, $this->token, $shops); + die(Tools::jsonEncode(array("success" => $html))); + } + else + die(Tools::jsonEncode($result)); + } + + if (Tools::getValue('updateProductImageShopAsso')) + { + if ($id_image = (int)Tools::getValue('id_image') AND $id_shop = (int)Tools::getValue('id_shop')) + if (Tools::getValue('active') == "true") + die(Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'image_shop (`id_image`, `id_shop`) VALUES('.(int)$id_image.', '.(int)$id_shop.')')); + else + die(Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'image_shop WHERE `id_image`='.(int)$id_image.' AND `id_shop`='.(int)$id_shop)); + } + + if (Tools::getValue('deleteImage')) + { + $image = new Image((int)Tools::getValue('id_image')); + $image->delete(); + if (!Image::getCover($image->id_product)) + { + $first_img = Db::getInstance()->getRow(' + SELECT `id_image` FROM `'._DB_PREFIX_.'image` + WHERE `id_product` = '.(int)($image->id_product)); + Db::getInstance()->Execute(' + UPDATE `'._DB_PREFIX_.'image` + SET `cover` = 1 + WHERE `id_image` = '.(int)($first_img['id_image'])); + } + @unlink(_PS_TMP_IMG_DIR_.'/product_'.$image->id_product.'.jpg'); + @unlink(_PS_TMP_IMG_DIR_.'/product_mini_'.$image->id_product.'.jpg'); + die(true); + } + + } protected function _validateSpecificPrice($id_shop, $id_currency, $id_country, $id_group, $price, $from_quantity, $reduction, $reduction_type, $from, $to) { if (!Validate::isUnsignedId($id_shop) OR !Validate::isUnsignedId($id_currency) OR !Validate::isUnsignedId($id_country) OR !Validate::isUnsignedId($id_group)) @@ -923,41 +957,6 @@ class AdminProducts extends AdminTab $this->copyImage($product->id, $image->id, $method); } } - - /* Adding a new product image */ - elseif (isset($_FILES['image_product']['name']) && $_FILES['image_product']['name'] != NULL ) - { - if ($error = checkImageUploadError($_FILES['image_product'])) - $this->_errors[] = $error; - - if (!sizeof($this->_errors) AND isset($_FILES['image_product']['tmp_name']) AND $_FILES['image_product']['tmp_name'] != NULL) - { - if (!Validate::isLoadedObject($product)) - $this->_errors[] = Tools::displayError('Cannot add image because product add failed.'); - elseif (substr($_FILES['image_product']['name'], -4) == '.zip') - return $this->uploadImageZip($product); - else - { - $image = new Image(); - $image->id_product = (int)($product->id); - $_POST['id_product'] = $image->id_product; - $image->position = Image::getHighestPosition($product->id) + 1; - if (($cover = Tools::getValue('cover')) == 1) - Image::deleteCover($product->id); - $image->cover = !$cover ? !sizeof($product->getImages(Configuration::get('PS_LANG_DEFAULT'))) : true; - $this->validateRules('Image', 'image'); - $this->copyFromPost($image, 'image'); - if (!sizeof($this->_errors)) - { - if (!$image->add()) - $this->_errors[] = Tools::displayError('Error while creating additional image'); - else - $this->copyImage($product->id, $image->id, $method); - $id_image = $image->id; - } - } - } - } if (isset($image) AND Validate::isLoadedObject($image) AND !file_exists(_PS_PROD_IMG_DIR_.$image->getExistingImgPath().'.'.$image->image_format)) $image->delete(); if (sizeof($this->_errors)) @@ -966,86 +965,6 @@ class AdminProducts extends AdminTab @unlink(_PS_TMP_IMG_DIR_.'/product_mini_'.$product->id.'.jpg'); return ((isset($id_image) AND is_int($id_image) AND $id_image) ? $id_image : true); } - - public function uploadImageZip($product) - { - // Move the ZIP file to the img/tmp directory - if (!$zipfile = tempnam(_PS_TMP_IMG_DIR_, 'PS') OR !move_uploaded_file($_FILES['image_product']['tmp_name'], $zipfile)) - { - $this->_errors[] = Tools::displayError('An error occurred during the ZIP file upload.'); - return false; - } - - // Unzip the file to a subdirectory - $subdir = _PS_TMP_IMG_DIR_.uniqid().'/'; - try - { - if (!Tools::ZipExtract($zipfile, $subdir)) - throw new Exception(Tools::displayError('An error occurred while unzipping your file.')); - - $types = array('.gif' => 'image/gif', '.jpeg' => 'image/jpeg', '.jpg' => 'image/jpg', '.png' => 'image/png'); - $_POST['id_product'] = (int)$product->id; - $imagesTypes = ImageType::getImagesTypes('products'); - $highestPosition = Image::getHighestPosition($product->id); - foreach (scandir($subdir) as $file) - { - if ($file[0] == '.') - continue; - - // Create image object - $image = new Image(); - $image->id_product = (int)$product->id; - $image->position = ++$highestPosition; - $image->cover = ($highestPosition == 1 ? true : false); - - // Call automated copy function - $this->validateRules('Image', 'image'); - $this->copyFromPost($image, 'image'); - - if (sizeof($this->_errors)) - throw new Exception(''); - - if (!$image->add()) - throw new Exception(Tools::displayError('Error while creating additional image')); - - $ext = substr($file, -4); - $type = (isset($types[$ext]) ? $types[$ext] : ''); - if (!isPicture(array('tmp_name' => $subdir.$file, 'type' => $type))) - { - $image->delete(); - throw new Exception(Tools::displayError('Image format not recognized, allowed formats are: .gif, .jpg, .png')); - } - - if (!$new_path = $image->getPathForCreation()) - throw new Exception(Tools::displayError('An error occurred during new folder creation')); - if (!imageResize($subdir.$file, $new_path.'.'.$image->image_format)) - { - $image->delete(); - throw new Exception(Tools::displayError('An error occurred while resizing image.')); - } - - foreach ($imagesTypes AS $k => $imageType) - if (!imageResize($subdir.$file, _PS_PROD_IMG_DIR_.$image->getImgPath().'-'.stripslashes($imageType['name']).'.jpg', $imageType['width'], $imageType['height'])) - { - $image->delete(); - throw new Exception(Tools::displayError('An error occurred while copying image.').' '.stripslashes($imageType['name'])); - } - - Module::hookExec('watermark', array('id_image' => $image->id, 'id_product' => $image->id_product)); - } - } - catch (Exception $e) - { - if ($error = $e->getMessage()); - $this->_errors[] = $error; - Tools::deleteDirectory($subdir); - return false; - } - - Tools::deleteDirectory($subdir); - return true; - } - /** * Copy a product image * @@ -1118,7 +1037,7 @@ class AdminProducts extends AdminTab /* Check description short size without html */ $limit = (int)Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT'); - if ($limit <= 0) $limit = 800; + if ($limit <= 0) $limit = 400; foreach ($languages AS $language) if ($value = Tools::getValue('description_short_'.$language['id_lang'])) if (Tools::strlen(strip_tags($value)) > $limit) @@ -2967,11 +2886,20 @@ class AdminProducts extends AdminTab function displayFormImages($obj, $token = NULL) { + if(!Tools::getValue('id_product')) + return ''; global $attributeJs, $images; + $shops = false; + if (Shop::isMultiShopActivated()) + $shops = Shop::getShops(); + $countImages = (int)Db::getInstance()->getValue('SELECT COUNT(*) FROM '._DB_PREFIX_.'image WHERE id_product = '.(int)$obj->id); + $images = Image::getImages($this->context->language->id, $obj->id); + $imagesTotal = Image::getImagesTotal($obj->id); + echo '
-

2. '.$this->l('Images').' ('.$countImages.')

+

2. '.$this->l('Images').' ('.$countImages.')

@@ -2982,92 +2910,152 @@ class AdminProducts extends AdminTab - - - - - - - - '; /* DEPRECATED FEATURE - - - - */ - echo ' - - - - '; - if (!sizeof($images) OR !isset($obj->id)) - echo ' - '; - else - { - echo ' - + + '.(Tools::getValue('id_image') ? '' : '').' + + + + + + + '; + if (Shop::isMultiShopActivated()) + foreach ($shops AS $shop) + $html .= ' + '; + $html .= ' + + + '; + return $html; + } + public function initCombinationImagesJS() { if (!($obj = $this->loadObject(true))) @@ -3881,6 +3878,5 @@ class AdminProducts extends AdminTab $this->displayErrors(); } - } diff --git a/classes/FileUploader.php b/classes/FileUploader.php new file mode 100755 index 000000000..711f57e22 --- /dev/null +++ b/classes/FileUploader.php @@ -0,0 +1,196 @@ + +* @copyright 2007-2011 PrestaShop SA +* @version Release: $Revision: 7331 $ +* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) +* International Registered Trademark & Property of PrestaShop SA +*/ + +/** + * Handle file uploads via XMLHttpRequest + */ +class qqUploadedFileXhr +{ + /** + * Save the file to the specified path + * @return boolean TRUE on success + */ + function upload($path) + { + $input = fopen("php://input", "r"); + $temp = tmpfile(); + $realSize = stream_copy_to_stream($input, $temp); + fclose($input); + if ($realSize != $this->getSize()) + return false; + $target = fopen($path, "w"); + fseek($temp, 0, SEEK_SET); + stream_copy_to_stream($temp, $target); + fclose($target); + + return true; + } + + function save() + { + $product = new Product($_GET['id_product']); + if (!Validate::isLoadedObject($product)) + return array('error' => Tools::displayError('Cannot add image because product add failed.')); + else + { + $image = new Image(); + $image->id_product = (int)($product->id); + $image->position = Image::getHighestPosition($product->id) + 1; + if (!Image::getCover($image->id_product)) + $image->cover = 1; + else + $image->cover = 0; + if (!$image->add()) + return array('error' => Tools::displayError('Error while creating additional image')); + else + { + return $this->copyImage($product->id, $image->id); + } + } + } + + public function copyImage($id_product, $id_image, $method = 'auto') + { + $image = new Image($id_image); + $p = new Product($id_product); + if (!$new_path = $image->getPathForCreation()) + return array('error' => Tools::displayError('An error occurred during new folder creation')); + if (!$tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS') OR !$this->upload($tmpName)) + return array('error' => Tools::displayError('An error occurred during the image upload')); + elseif (!imageResize($tmpName, $new_path.'.'.$image->image_format)) + return array('error' => Tools::displayError('An error occurred while copying image.')); + elseif($method == 'auto') + { + $imagesTypes = ImageType::getImagesTypes('products'); + foreach ($imagesTypes AS $k => $imageType) + if (!imageResize($tmpName, $new_path.'-'.stripslashes($imageType['name']).'.'.$image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) + return array('error' => Tools::displayError('An error occurred while copying image:').' '.stripslashes($imageType['name'])); + } + unlink($tmpName); + Module::hookExec('watermark', array('id_image' => $id_image, 'id_product' => $id_product)); + $lang = Context::getContext()->employee->id_lang; + + foreach (Language::getLanguages(false) as $l) + $image->legend[$l['id_lang']] = $id_image." ".$p->name[$l['id_lang']]." ".$p->reference; + if (!$image->update()) + return array('error' => Tools::displayError('Error while updating status')); + $img = array('id_image' => $image->id, 'legend' => $image->legend[$lang], 'position' => $image->position, 'cover' => $image->cover); + return array("success" => $img); + } + + function getName() + { + return $_GET['qqfile']; + } + function getSize() + { + if (isset($_SERVER["CONTENT_LENGTH"])) + return (int)$_SERVER["CONTENT_LENGTH"]; + else + throw new Exception('Getting content length is not supported.'); + } +} + +class FileUploaderCore +{ + + private $allowedExtensions = array(); + private $sizeLimit = 10485760; + private $file; + + function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760) + { + $allowedExtensions = array_map("strtolower", $allowedExtensions); + + $this->allowedExtensions = $allowedExtensions; + $this->sizeLimit = $sizeLimit; + + $this->checkServerSettings(); + + if (isset($_GET['qqfile'])) + $this->file = new qqUploadedFileXhr(); + else + $this->file = false; + } + + private function checkServerSettings() + { + $postSize = $this->toBytes(ini_get('post_max_size')); + $uploadSize = $this->toBytes(ini_get('upload_max_filesize')); + + if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) + { + $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M'; + die("{'error':".Tools::displayError('increase post_max_size and upload_max_filesize to $size')."}"); + } + } + + private function toBytes($str) + { + $val = trim($str); + $last = strtolower($str[strlen($str)-1]); + switch($last) { + case 'g': $val *= 1024; + case 'm': $val *= 1024; + case 'k': $val *= 1024; + } + return $val; + } + + /** + * Returns array('success'=>true) or array('error'=>'error message') + */ + function handleUpload() + { + if (!$this->file){ + return array('error' => Tools::displayError('No files were uploaded.')); + } + + $size = $this->file->getSize(); + + if ($size == 0) { + return array('error' => Tools::displayError('File is empty')); + } + + if ($size > $this->sizeLimit) { + return array('error' => Tools::displayError('File is too large')); + } + + $pathinfo = pathinfo($this->file->getName()); + $filename = $pathinfo['filename']; + $these = implode(', ', $this->allowedExtensions); + if (!isset($pathinfo['extension'])) + return array('error' => Tools::displayError('File has an invalid extension, it should be one of '). $these . '.'); + $ext = $pathinfo['extension']; + if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) + return array('error' => Tools::displayError('File has an invalid extension, it should be one of '). $these . '.'); + + + return $this->file->save(); + + } +} diff --git a/css/admin.css b/css/admin.css index 7bf1a9bcd..71b7804e6 100644 --- a/css/admin.css +++ b/css/admin.css @@ -1647,4 +1647,47 @@ p.preference_description{ input.disable_me[disabled=disabled]{ background-color: red; +} + +div.progressBarImage +{ + float: left; + height: 15px; + margin-left: 3px; + width: 233px; +} +#showCounter +{ + font-weight: bold; + float: left; + margin-left: 25px; + margin-top: 1px; +} +#listImage +{ + list-style: none outside none; + margin-bottom: 10px; + margin-top: 10px; +} + +#listImage li +{ + clear: both; + float: left; + font-weight: bold; + margin-top: 10px; +} + +#listImage li p.errorImg +{ + background: none repeat scroll 0 0 #FAE2E3; + border: 1px solid #EC9B9B; + clear: both; + margin-bottom: 18px; + padding: 6px; + display: none; +} +#progressBarImage div.ui-progressbar-value +{ + height: 100%; } \ No newline at end of file diff --git a/js/fileuploader.js b/js/fileuploader.js new file mode 100755 index 000000000..5684ddd7e --- /dev/null +++ b/js/fileuploader.js @@ -0,0 +1,1133 @@ +/* +* 2007-2011 PrestaShop +* +* NOTICE OF LICENSE +* +* This source file is subject to the Open Software License (OSL 3.0) +* that is bundled with this package in the file LICENSE.txt. +* It is also available through the world-wide-web at this URL: +* http://opensource.org/licenses/osl-3.0.php +* If you did not receive a copy of the license and are unable to +* obtain it through the world-wide-web, please send an email +* to license@prestashop.com so we can send you a copy immediately. +* +* DISCLAIMER +* +* Do not edit or add to this file if you wish to upgrade PrestaShop to newer +* versions in the future. If you wish to customize PrestaShop for your +* needs please refer to http://www.prestashop.com for more information. +* +* @author PrestaShop SA +* @copyright 2007-2011 PrestaShop SA +* @version Release: $Revision: 7331 $ +* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) +* International Registered Trademark & Property of PrestaShop SA +*/ + +var qq = qq || {}; + +/** + * Adds all missing properties from second obj to first obj + */ +qq.extend = function(first, second){ + for (var prop in second){ + first[prop] = second[prop]; + } +}; + +/** + * Searches for a given element in the array, returns -1 if it is not present. + * @param {Number} [from] The index at which to begin the search + */ +qq.indexOf = function(arr, elt, from){ + if (arr.indexOf) return arr.indexOf(elt, from); + + from = from || 0; + var len = arr.length; + + if (from < 0) from += len; + + for (; from < len; from++){ + if (from in arr && arr[from] === elt){ + return from; + } + } + return -1; +}; + +qq.getUniqueId = (function(){ + var id = 0; + return function(){ return id++; }; +})(); + +// +// Events + +qq.attach = function(element, type, fn){ + if (element.addEventListener){ + element.addEventListener(type, fn, false); + } else if (element.attachEvent){ + element.attachEvent('on' + type, fn); + } +}; +qq.detach = function(element, type, fn){ + if (element.removeEventListener){ + element.removeEventListener(type, fn, false); + } else if (element.attachEvent){ + element.detachEvent('on' + type, fn); + } +}; + +qq.preventDefault = function(e){ + if (e.preventDefault){ + e.preventDefault(); + } else{ + e.returnValue = false; + } +}; + +// +// Node manipulations + +/** + * Insert node a before node b. + */ +qq.insertBefore = function(a, b){ + b.parentNode.insertBefore(a, b); +}; +qq.remove = function(element){ + element.parentNode.removeChild(element); +}; + +qq.contains = function(parent, descendant){ + // compareposition returns false in this case + if (parent == descendant) return true; + + if (parent.contains){ + return parent.contains(descendant); + } else { + return !!(descendant.compareDocumentPosition(parent) & 8); + } +}; + +/** + * Creates and returns element from html string + * Uses innerHTML to create an element + */ +qq.toElement = (function(){ + var div = document.createElement('div'); + return function(html){ + div.innerHTML = html; + var element = div.firstChild; + div.removeChild(element); + return element; + }; +})(); + +// +// Node properties and attributes + +/** + * Sets styles for an element. + * Fixes opacity in IE6-8. + */ +qq.css = function(element, styles){ + if (styles.opacity != null){ + if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){ + styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')'; + } + } + qq.extend(element.style, styles); +}; +qq.hasClass = function(element, name){ + var re = new RegExp('(^| )' + name + '( |$)'); + return re.test(element.className); +}; +qq.addClass = function(element, name){ + if (!qq.hasClass(element, name)){ + element.className += ' ' + name; + } +}; +qq.removeClass = function(element, name){ + var re = new RegExp('(^| )' + name + '( |$)'); + element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, ""); +}; +qq.setText = function(element, text){ + element.innerText = text; + element.textContent = text; +}; + +// +// Selecting elements + +qq.children = function(element){ + var children = [], + child = element.firstChild; + + while (child){ + if (child.nodeType == 1){ + children.push(child); + } + child = child.nextSibling; + } + + return children; +}; + +qq.getByClass = function(element, className){ + if (element.querySelectorAll){ + return element.querySelectorAll('.' + className); + } + + var result = []; + var candidates = element.getElementsByTagName("*"); + var len = candidates.length; + + for (var i = 0; i < len; i++){ + if (qq.hasClass(candidates[i], className)){ + result.push(candidates[i]); + } + } + return result; +}; + +/** + * obj2url() takes a json-object as argument and generates + * a querystring. pretty much like jQuery.param() + * + * how to use: + * + * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');` + * + * will result in: + * + * `http://any.url/upload?otherParam=value&a=b&c=d` + * + * @param Object JSON-Object + * @param String current querystring-part + * @return String encoded querystring + */ +var nbfile = 0; +qq.obj2url = function(obj, temp, prefixDone){ + var uristrings = [], + prefix = '&', + add = function(nextObj, i){ + var nextTemp = temp + ? (/\[\]$/.test(temp)) // prevent double-encoding + ? temp + : temp+'['+i+']' + : i; + if ((nextTemp != 'undefined') && (i != 'undefined')) { + uristrings.push( + (typeof nextObj === 'object') + ? qq.obj2url(nextObj, nextTemp, true) + : (Object.prototype.toString.call(nextObj) === '[object Function]') + ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj()) + : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj) + ); + } + }; + + if (!prefixDone && temp) { + prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?'; + uristrings.push(temp); + uristrings.push(qq.obj2url(obj)); + } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) { + // we wont use a for-in-loop on an array (performance) + for (var i = 0, len = obj.length; i < len; ++i){ + add(obj[i], i); + } + } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){ + // for anything else but a scalar, we will use for-in-loop + for (var i in obj){ + add(obj[i], i); + } + } else { + uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj)); + } + + return uristrings.join(prefix) + .replace(/^&/, '') + .replace(/%20/g, '+'); +}; + +// +// +// Uploader Classes +// +// + +var qq = qq || {}; + +/** + * Creates upload button, validates upload, but doesn't create file list or dd. + */ +qq.FileUploaderBasic = function(o){ + this._options = { + // set to true to see the server response + debug: false, + action: '/server/upload', + params: {}, + button: null, + multiple: true, + maxConnections: 3, + // validation + allowedExtensions: [], + sizeLimit: 0, + minSizeLimit: 0, + // events + // return false to cancel submit + onSubmit: function(id, fileName){}, + onProgress: function(id, fileName, loaded, total){}, + onComplete: function(id, fileName, responseJSON){}, + onCancel: function(id, fileName){}, + // messages + messages: { + typeError: "{file} has invalid extension. Only {extensions} are allowed.", + sizeError: "{file} is too large, maximum file size is {sizeLimit}.", + minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.", + emptyError: "{file} is empty, please select files again without it.", + onLeave: "The files are being uploaded, if you leave now the upload will be cancelled." + }, + showMessage: function(message){ + + } + }; + qq.extend(this._options, o); + + // number of files being uploaded + this._filesInProgress = 0; + this._handler = this._createUploadHandler(); + + if (this._options.button){ + this._button = this._createUploadButton(this._options.button); + } + + this._preventLeaveInProgress(); +}; + +qq.FileUploaderBasic.prototype = { + setParams: function(params){ + this._options.params = params; + }, + getInProgress: function(){ + return this._filesInProgress; + }, + _createUploadButton: function(element){ + var self = this; + + return new qq.UploadButton({ + element: element, + multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(), + onChange: function(input){ + self._onInputChange(input); + } + }); + }, + _createUploadHandler: function(){ + var self = this, + handlerClass; + + if(qq.UploadHandlerXhr.isSupported()){ + handlerClass = 'UploadHandlerXhr'; + } else { + handlerClass = 'UploadHandlerForm'; + } + + var handler = new qq[handlerClass]({ + debug: this._options.debug, + action: this._options.action, + maxConnections: this._options.maxConnections, + onProgress: function(id, fileName, loaded, total){ + self._onProgress(id, fileName, loaded, total); + self._options.onProgress(id, fileName, loaded, total); + }, + onComplete: function(id, fileName, result){ + self._onComplete(id, fileName, result); + self._options.onComplete(id, fileName, result); + }, + onCancel: function(id, fileName){ + self._onCancel(id, fileName); + self._options.onCancel(id, fileName); + } + }); + + return handler; + }, + _preventLeaveInProgress: function(){ + var self = this; + + qq.attach(window, 'beforeunload', function(e){ + if (!self._filesInProgress){return;} + + var e = e || window.event; + // for ie, ff + e.returnValue = self._options.messages.onLeave; + // for webkit + return self._options.messages.onLeave; + }); + }, + _onSubmit: function(id, fileName){ + this._filesInProgress++; + }, + _onProgress: function(id, fileName, loaded, total){ + }, + _onComplete: function(id, fileName, result){ + this._filesInProgress--; + if (result.error){ + this._options.showMessage(result.error); + } + }, + _onCancel: function(id, fileName){ + this._filesInProgress--; + }, + _onInputChange: function(input){ + if (this._handler instanceof qq.UploadHandlerXhr){ + this._uploadFileList(input.files); + } else { + if (this._validateFile(input)){ + this._uploadFile(input); + } + } + this._button.reset(); + }, + _uploadFileList: function(files){ + nbfile = files.length; + for (var i=0; i this._options.sizeLimit){ + this._error('sizeError', name); + return false; + + } else if (size && size < this._options.minSizeLimit){ + this._error('minSizeError', name); + return false; + } + + return true; + }, + _error: function(code, fileName){ + var message = this._options.messages[code]; + function r(name, replacement){ message = message.replace(name, replacement); } + + r('{file}', this._formatFileName(fileName)); + r('{extensions}', this._options.allowedExtensions.join(', ')); + r('{sizeLimit}', this._formatSize(this._options.sizeLimit)); + r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit)); + + this._options.showMessage(message); + }, + _formatFileName: function(name){ + if (name.length > 33){ + name = name.slice(0, 19) + '...' + name.slice(-13); + } + return name; + }, + _isAllowedExtension: function(fileName){ + var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : ''; + var allowed = this._options.allowedExtensions; + + if (!allowed.length){return true;} + + for (var i=0; i 99); + + return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i]; + } +}; + + +/** + * Class that creates upload widget with drag-and-drop and file list + * @inherits qq.FileUploaderBasic + */ +qq.FileUploader = function(o){ + // call parent constructor + qq.FileUploaderBasic.apply(this, arguments); + + // additional options + qq.extend(this._options, { + element: null, + // if set, will be used instead of qq-upload-list in template + listElement: null, + + template: '
' + + '
' + upbutton +'
' + + '' + + '
', + + // template for one item in file list + fileTemplate: '
  • ' + + '' + + '' + + '' + + 'Cancel' + + 'Failed' + + '
  • ', + + classes: { + // used to get elements from templates + button: 'qq-upload-button', + list: 'qq-upload-list', + + file: 'qq-upload-file', + spinner: 'qq-upload-spinner', + size: 'qq-upload-size', + cancel: 'qq-upload-cancel', + + // added to list item when upload completes + // used in css to hide progress spinner + success: 'qq-upload-success', + fail: 'qq-upload-fail' + } + }); + // overwrite options with user supplied + qq.extend(this._options, o); + + this._element = this._options.element; + this._element.innerHTML = this._options.template; + this._listElement = this._options.listElement || this._find(this._element, 'list'); + + this._classes = this._options.classes; + + this._button = this._createUploadButton(this._find(this._element, 'button')); + + this._bindCancelEvent(); +}; + +// inherit from Basic Uploader +qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype); + +qq.extend(qq.FileUploader.prototype, { + /** + * Gets one of the elements listed in this._options.classes + **/ + _find: function(parent, type){ + var element = qq.getByClass(parent, this._options.classes[type])[0]; + if (!element){ + throw new Error('element not found ' + type); + } + + return element; + }, + + _onSubmit: function(id, fileName){ + qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments); + this._addToList(id, fileName); + }, + _onProgress: function(id, fileName, loaded, total){ + qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments); + + var item = this._getItemByFileId(id); + var size = this._find(item, 'size'); + size.style.display = 'inline'; + + var text; + if (loaded != total){ + text = Math.round(loaded / total * 100) + '% from ' + this._formatSize(total); + } else { + text = this._formatSize(total); + } + + qq.setText(size, text); + }, + _onComplete: function(id, fileName, result){ + qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments); + + // mark completed + var item = this._getItemByFileId(id); + qq.remove(this._find(item, 'cancel')); + qq.remove(this._find(item, 'spinner')); + + if (result.success){ + qq.addClass(item, this._classes.success); + } else { + qq.addClass(item, this._classes.fail); + } + }, + _addToList: function(id, fileName){ + var item = qq.toElement(this._options.fileTemplate); + item.qqFileId = id; + + var fileElement = this._find(item, 'file'); + qq.setText(fileElement, this._formatFileName(fileName)); + this._find(item, 'size').style.display = 'none'; + + this._listElement.appendChild(item); + }, + _getItemByFileId: function(id){ + var item = this._listElement.firstChild; + + // there can't be txt nodes in dynamically created list + // and we can use nextSibling + while (item){ + if (item.qqFileId == id) return item; + item = item.nextSibling; + } + }, + /** + * delegate click event for cancel link + **/ + _bindCancelEvent: function(){ + var self = this, + list = this._listElement; + + qq.attach(list, 'click', function(e){ + e = e || window.event; + var target = e.target || e.srcElement; + + if (qq.hasClass(target, self._classes.cancel)){ + qq.preventDefault(e); + + var item = target.parentNode; + self._handler.cancel(item.qqFileId); + qq.remove(item); + } + }); + } +}); + + +qq.UploadButton = function(o){ + this._options = { + element: null, + // if set to true adds multiple attribute to file input + multiple: false, + // name attribute of file input + name: 'file', + onChange: function(input){}, + hoverClass: 'qq-upload-button-hover', + focusClass: 'qq-upload-button-focus' + }; + + qq.extend(this._options, o); + + this._element = this._options.element; + + // make button suitable container for input + qq.css(this._element, { + position: 'relative', + overflow: 'hidden', + // Make sure browse button is in the right side + // in Internet Explorer + direction: 'ltr' + }); + + this._input = this._createInput(); +}; + +qq.UploadButton.prototype = { + /* returns file input element */ + getInput: function(){ + return this._input; + }, + /* cleans/recreates the file input */ + reset: function(){ + if (this._input.parentNode){ + qq.remove(this._input); + } + + qq.removeClass(this._element, this._options.focusClass); + this._input = this._createInput(); + }, + _createInput: function(){ + var input = document.createElement("input"); + + if (this._options.multiple){ + input.setAttribute("multiple", "multiple"); + } + + input.setAttribute("type", "file"); + input.setAttribute("name", this._options.name); + + qq.css(input, { + position: 'absolute', + // in Opera only 'browse' button + // is clickable and it is located at + // the right side of the input + right: 0, + top: 0, + fontFamily: 'Arial', + // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118 + fontSize: '118px', + margin: 0, + padding: 0, + cursor: 'pointer', + opacity: 0 + }); + + this._element.appendChild(input); + + var self = this; + qq.attach(input, 'change', function(){ + self._options.onChange(input); + }); + + qq.attach(input, 'mouseover', function(){ + qq.addClass(self._element, self._options.hoverClass); + }); + qq.attach(input, 'mouseout', function(){ + qq.removeClass(self._element, self._options.hoverClass); + }); + qq.attach(input, 'focus', function(){ + qq.addClass(self._element, self._options.focusClass); + }); + qq.attach(input, 'blur', function(){ + qq.removeClass(self._element, self._options.focusClass); + }); + + // IE and Opera, unfortunately have 2 tab stops on file input + // which is unacceptable in our case, disable keyboard access + if (window.attachEvent){ + // it is IE or Opera + input.setAttribute('tabIndex', "-1"); + } + + return input; + } +}; + +/** + * Class for uploading files, uploading itself is handled by child classes + */ +qq.UploadHandlerAbstract = function(o){ + this._options = { + debug: false, + action: '/upload.php', + // maximum number of concurrent uploads + maxConnections: 999, + onProgress: function(id, fileName, loaded, total){}, + onComplete: function(id, fileName, response){}, + onCancel: function(id, fileName){} + }; + qq.extend(this._options, o); + + this._queue = []; + // params for files in queue + this._params = []; +}; +qq.UploadHandlerAbstract.prototype = { + log: function(str){ + if (this._options.debug && window.console) console.log('[uploader] ' + str); + }, + /** + * Adds file or file input to the queue + * @returns id + **/ + add: function(file){}, + /** + * Sends the file identified by id and additional query params to the server + */ + upload: function(id, params){ + var len = this._queue.push(id); + + var copy = {}; + qq.extend(copy, params); + this._params[id] = copy; + + // if too many active uploads, wait... + if (len <= this._options.maxConnections){ + this._upload(id, this._params[id]); + } + }, + /** + * Cancels file upload by id + */ + cancel: function(id){ + this._cancel(id); + this._dequeue(id); + }, + /** + * Cancells all uploads + */ + cancelAll: function(){ + for (var i=0; i= max && i < max){ + var nextId = this._queue[max-1]; + this._upload(nextId, this._params[nextId]); + } + } +}; + +/** + * Class for uploading files using form and iframe + * @inherits qq.UploadHandlerAbstract + */ +qq.UploadHandlerForm = function(o){ + qq.UploadHandlerAbstract.apply(this, arguments); + + this._inputs = {}; +}; +// @inherits qq.UploadHandlerAbstract +qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype); + +qq.extend(qq.UploadHandlerForm.prototype, { + add: function(fileInput){ + fileInput.setAttribute('name', 'qqfile'); + var id = 'qq-upload-handler-iframe' + qq.getUniqueId(); + + this._inputs[id] = fileInput; + + // remove file input from DOM + if (fileInput.parentNode){ + qq.remove(fileInput); + } + + return id; + }, + getName: function(id){ + // get input value and remove path to normalize + return this._inputs[id].value.replace(/.*(\/|\\)/, ""); + }, + _cancel: function(id){ + this._options.onCancel(id, this.getName(id)); + + delete this._inputs[id]; + + var iframe = document.getElementById(id); + if (iframe){ + // to cancel request set src to something else + // we use src="javascript:false;" because it doesn't + // trigger ie6 prompt on https + iframe.setAttribute('src', 'javascript:false;'); + + qq.remove(iframe); + } + }, + _upload: function(id, params){ + var input = this._inputs[id]; + + if (!input){ + throw new Error('file with passed id was not added, or already uploaded or cancelled'); + } + + var fileName = this.getName(id); + + var iframe = this._createIframe(id); + var form = this._createForm(iframe, params); + form.appendChild(input); + + var self = this; + this._attachLoadEvent(iframe, function(){ + self.log('iframe loaded'); + + var response = self._getIframeContentJSON(iframe); + + self._options.onComplete(id, fileName, response); + self._dequeue(id); + + delete self._inputs[id]; + // timeout added to fix busy state in FF3.6 + setTimeout(function(){ + qq.remove(iframe); + }, 1); + }); + + form.submit(); + qq.remove(form); + + return id; + }, + _attachLoadEvent: function(iframe, callback){ + qq.attach(iframe, 'load', function(){ + // when we remove iframe from dom + // the request stops, but in IE load + // event fires + if (!iframe.parentNode){ + return; + } + + // fixing Opera 10.53 + if (iframe.contentDocument && + iframe.contentDocument.body && + iframe.contentDocument.body.innerHTML == "false"){ + // In Opera event is fired second time + // when body.innerHTML changed from false + // to server response approx. after 1 sec + // when we upload file with iframe + return; + } + + callback(); + }); + }, + /** + * Returns json object received by iframe from server. + */ + _getIframeContentJSON: function(iframe){ + // iframe.contentWindow.document - for IE<7 + var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document, + response; + + this.log("converting iframe's innerHTML to JSON"); + this.log("innerHTML = " + doc.body.innerHTML); + + try { + response = eval("(" + doc.body.innerHTML + ")"); + } catch(err){ + response = {}; + } + + return response; + }, + /** + * Creates iframe with unique name + */ + _createIframe: function(id){ + // We can't use following code as the name attribute + // won't be properly registered in IE6, and new window + // on form submit will open + // var iframe = document.createElement('iframe'); + // iframe.setAttribute('name', id); + + var iframe = qq.toElement('
    '.(Tools::getValue('id_image')?$this->l('Edit this product image'):$this->l('Add a new image to this product')).'
    '.$this->l('File:').' - -

    - '.$this->l('Format:').' JPG, GIF, PNG. '.$this->l('Filesize:').' '.(Tools::getMaxUploadSize() / 1024).''.$this->l('Kb max.').' -
    '.$this->l('You can also upload a ZIP file containing several images. Thumbnails will be resized automatically.').' +

    + +
    +
    + +
      + + + + + +

      + '.$this->l('Format:').' JPG, GIF, PNG. '.$this->l('Filesize:').' '.($this->maxImageSize / 1000).''.$this->l('Kb max.').'

      '.$this->l('Caption:').''; - foreach ($this->_languages as $language) - { - if (!Tools::getValue('legend_'.$language['id_lang'])) - $legend = $this->getFieldValue($obj, 'name', $language['id_lang']); - else - $legend = Tools::getValue('legend_'.$language['id_lang']); - echo ' -
      - - * - '.$this->l('Forbidden characters:').' <>;=#{}
      '.$this->l('Forbidden characters will be automatically erased.').' 
      -
      '; - } - echo ' -

      '.$this->l('Short description of the image').'

      -
      '.$this->l('Cover:').' - -

      '.$this->l('If you want to select this image as a product cover').'

      -
      '.$this->l('Thumbnails resize method:').' - -

      '.$this->l('Method you want to use to generate resized thumbnails').'

      -
      '; - echo ''; - $images = Image::getImages($this->context->language->id, $obj->id); - $imagesTotal = Image::getImagesTotal($obj->id); - - if (isset($obj->id) AND sizeof($images)) - { - echo ''; - echo '

      '; - } - echo (Tools::getValue('id_image') ? '' : '').' -

      - - '.(Tools::isSubmit('id_category') ? '' : '').' -  

      - + +
      '; - if (Shop::isMultiShopActivated()) + if ($shops) { - $shops = Shop::getShops(); echo ''; @@ -3079,50 +3067,10 @@ class AdminProducts extends AdminTab '; + echo $this->_positionJS(); foreach ($images AS $k => $image) - { - if (Shop::isMultiShopActivated()) - $imgObj = new Image((int)$image['id_image']); - $image_obj = new Image($image['id_image']); - $img_path = $image_obj->getExistingImgPath(); - - echo $this->_positionJS().' - - - - '; - if (Shop::isMultiShopActivated()) - foreach ($shops AS $shop) - echo ''; - echo ' - - - '; - } - } + echo $this->getLineTableImage($image, $imagesTotal, $token, $shops); + echo '
      '.$this->l('Image').'   '.$this->l('Position').''.$this->l('Action').'
      - '.htmlentities(stripslashes($image['legend']), ENT_COMPAT, 'UTF-8').''.(int)($image['position']).''; - - if ($image['position'] == 1) - { - echo '[ ]'; - if ($image['position'] == $imagesTotal) - echo '[ ]'; - else - echo '[ ]'; - } - elseif ($image['position'] == $imagesTotal) - echo ' - [ ] - [ ]'; - else - echo ' - [ ] - [ ]'; - echo 'isAssociatedToShop($shop['id_shop']) ? 'checked="1"' : '').' /> - '.$this->l('Modify this image').' - '.$this->l('Delete this image').' -
      @@ -3154,7 +3102,56 @@ class AdminProducts extends AdminTab echo ' '; } - + + public function getLineTableImage($image, $imagesTotal, $token, $shops) + { + if (Shop::isMultiShopActivated()) + $imgObj = new Image((int)$image['id_image']); + $image_obj = new Image($image['id_image']); + $img_path = $image_obj->getExistingImgPath(); + + $html = ' +
      + '.htmlentities(stripslashes($image['legend']), ENT_COMPAT, 'UTF-8').' + '.(int)($image['position']).''; + if ($image['position'] == 1) + { + $html .= ' + [ ]'; + if ($image['position'] == $imagesTotal) + $html .= ' + [ ]'; + else + $html .= ' + [ ]'; + } + elseif ($image['position'] == $imagesTotal) + $html .= ' + [ ] + [ ]'; + else + $html .= ' + [ ] + [ ]'; + $html .= ' + isAssociatedToShop($shop['id_shop']) ? 'checked="1"' : '').' /> + '.$this->l('Delete this image').' +