// Add uploader to products controller

This commit is contained in:
Jerome Nadaud
2013-11-08 16:29:07 +01:00
parent 034565bc6a
commit bf67bd56a3
5 changed files with 386 additions and 141 deletions
@@ -0,0 +1,180 @@
{*
* 2007-2013 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 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/afl-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 <contact@prestashop.com>
* @copyright 2007-2013 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*}
<div class="form-group">
<div class="col-lg-12">
<input id="{$id}" type="file" name="{$name}[]"{if isset($url)} data-url="{$url}"{/if}{if isset($multiple) && $multiple} multiple="multiple"{/if} class="hide" />
<button class="btn btn-default" data-style="expand-right" data-size="s" type="button" id="{$id}-add-button">
<i class="icon-plus-sign"></i> {if isset($multiple) && $multiple}{l s='Add files'}{else}{l s='Add file'}{/if}
</button>
<button class="ladda-button" data-style="expand-right" data-size="s" type="button" id="{$id}-upload-button" style="display:none;">
<i class="icon-cloud-upload"></i> <span class="ladda-label">{if isset($multiple) && $multiple}{l s='Upload files'}{else}{l s='Upload file'}{/if}</span>
</button>
</div>
</div>
<div class="row" style="display:none">
<div class="alert alert-info" id="{$id}-files-list"></div>
</div>
<div class="row" style="display:none">
<div class="alert alert-success" id="{$id}-success"></div>
</div>
<div class="row" style="display:none">
<div class="alert alert-danger" id="{$id}-errors"></div>
</div>
<script type="text/javascript">
function humanizeSize(bytes)
{
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
}
$( document ).ready(function() {
{if isset($multiple) && isset($max_files)}
var {$id}_max_files = {$max_files - $files|count};
{/if}
{if isset($files) && $files}
$('#{$id}-images-thumbnails').parent().show();
{/if}
var {$id}_upload_button = Ladda.create( document.querySelector('#{$id}-upload-button' ));
var {$id}_total_files = 0;
$('#{$id}').fileupload({
dataType: 'json',
autoUpload: false,
singleFileUploads: true,
maxFileSize: {$post_max_size},
start: function (e) {
{$id}_upload_button.start();
$('#{$id}-upload-button').unbind('click'); //Important as we bind it for every elements in add function
},
fail: function (e, data) {
$('#{$id}-errors').html(data.errorThrown.message).parent().show();
},
done: function (e, data) {
if (data.result) {
if (typeof data.result.{$name} !== 'undefined') {
for (var i=0; i<data.result.{$name}.length; i++) {
if (data.result.{$name}[i] !== null && data.result.{$name}[i].status == 'ok') {
var response = data.result.{$name}[i];
var cover = "icon-check-empty";
if (response.cover == "1")
cover = "icon-check-sign";
imageLine(response.id, response.path, response.position, cover, response.shops,
response.legend[{$default_language|intval}])
$("#countImage").html(parseInt($("#countImage").html()) + 1);
$("#img" + id).remove();
$("#imageTable").tableDnDUpdate();
}
}
}
$(data.context).find('button').remove();
$(data.context).appendTo($('#{$id}-success'));
$('#{$id}-success').parent().show();
}
},
}).on('fileuploadalways', function (e, data) {
{$id}_total_files--;
if ({$id}_total_files == 0)
{
{$id}_upload_button.stop();
$('#{$id}-upload-button').unbind('click');
$('#{$id}-files-list').parent().hide();
}
}).on('fileuploadadd', function(e, data) {
if (typeof {$id}_max_files !== 'undefined') {
if ({$id}_total_files >= {$id}_max_files) {
e.preventDefault();
alert('{l s='You can upload a maximum of %s files'|sprintf:$max_files}');
return;
}
}
data.context = $('<div/>').addClass('row').appendTo($('#{$id}-files-list'));
var file_name = $('<span/>').append('<strong>'+data.files[0].name+'</strong> ('+humanizeSize(data.files[0].size)+')').appendTo(data.context);
var button = $('<button/>').addClass('btn btn-default pull-right').prop('type', 'button').html('<i class="icon-trash"></i> {l s='Remove file'}').appendTo(data.context).on('click', function() {
{$id}_total_files--;
data.files = null;
var total_elements = $(this).parent().siblings('div.row').length;
$(this).parent().remove();
if (total_elements == 0) {
$('#{$id}-files-list').html('').parent().hide();
}
});
$('#{$id}-files-list').parent().show();
$('#{$id}-upload-button').show().bind('click', function () {
if (data.files != null)
data.submit();
});
{$id}_total_files++;
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index, file = data.files[index];
if (file.error) {
$('#{$id}-errors').append('<div class="row"><strong>'+file.name+'</strong> ('+humanizeSize(file.size)+') : '+file.error+'</div>').parent().show();
$(data.context).find('button').trigger('click');
}
}).on('fileuploadsubmit', function (e, data) {
var params = new Object();
$('input[id^="legend_"]').each(function()
{
id = $(this).prop("id").replace("legend_", "legend[") + "]";
params[id] = $(this).val();
});
data.formData = params;
});
$('#{$id}-add-button').on('click', function() {
$('#{$id}-success').html('').parent().hide();
$('#{$id}-errors').html('').parent().hide();
$('#{$id}-files-list').html('').parent().hide();
{$id}_total_files = 0;
$('#{$id}').trigger('click');
});
});
</script>
@@ -0,0 +1,35 @@
<?php
/*
* 2007-2013 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 <contact@prestashop.com>
* @copyright 2007-2013 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../../../../../../../../');
exit;
@@ -35,40 +35,52 @@
<div class="row">
<div class="form-group">
<label class="control-label col-lg-3 file_upload_label">
<span class="label-tooltip" data-toggle="tooltip"
title="{l s='Format:'} JPG, GIF, PNG. {l s='Filesize:'} {$max_image_size|string_format:"%.2f"} {l s='MB max.'}">
{if isset($id_image)}{l s='Edit this product image'}{else}{l s='Add a new image to this product'}{/if}
{if isset($id_image)}{l s='Edit this product image:'}{else}{l s='Add a new image to this product:'}{/if}
</span>
</label>
<div class="col-lg-9">
{l s='File:'}
<div id="file-uploader">
<noscript>
<p>{l s='Please enable JavaScript to use file uploader:'}</p>
</noscript>
</div>
<div id="progressBarImage" class="progressBarImage"></div>
<div id="showCounter" style="display:none;">
<span id="imageUpload">0</span><span id="imageTotal">0</span>
</div>
<input type="hidden" name="resizer" value="auto" />
{if Tools::getValue('id_image')}
<input type="hidden" name="id_image" value="{Tools::getValue('id_image')|intval}" />
{/if}
{$image_uploader}
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-3">
{l s='Legend:'}
<span class="label-tooltip" data-toggle="tooltip"
title="{l s='Invalid characters:'} <>;=#{}">
{l s='Legend:'}
</span>
</label>
<div class="col-lg-9 translatable">
{foreach from=$languages item=language}
<div class="lang_{$language.id_lang}" style="{if !$language.is_default}display: none;{/if} float: left;">
<input class="updateCurrentText" type="text" {if !$product->id}disabled="disabled"{/if} id="legend_{$language.id_lang}" name="legend_{$language.id_lang}" value="{$product->name[$language.id_lang]|escape:'htmlall':'UTF-8'}"/>
<div class="help-block">{l s='Invalid characters:'} <>;=#{}</div>
{foreach from=$languages item=language}
{if $languages|count > 1}
<div class="translatable-field row lang-{$language.id_lang}">
<div class="col-lg-6">
{/if}
<input type="text"
id="legend_{$language.id_lang}"
{if isset($input_class)}class="{$input_class}"{/if}
name="legend_{$language.id_lang}"
value="{$product->name[$language.id_lang]|escape:'htmlall':'UTF-8'}"
{if !$product->id}disabled="disabled"{/if} />
{if $languages|count > 1}
</div>
<div class="col-lg-2">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" tabindex="-1">
{$language.iso_code}
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
{foreach from=$languages item=language}
<li>
<a href="javascript:hideOtherLanguage({$language.id_lang});">{$language.name}</a>
</li>
{/foreach}
</ul>
</div>
</div>
{/foreach}
</div>
{/if}
{/foreach}
</div>
</div>
@@ -95,7 +107,7 @@
<tr id="image_id">
<td>
<a href="{$smarty.const._THEME_PROD_DIR_}image_path.jpg" class="fancybox">
<img src="{$smarty.const._THEME_PROD_DIR_}{$iso_lang}-default-{$imageType}.jpg" alt="image_id" title="image_id" />
<img src="{$smarty.const._THEME_PROD_DIR_}{$iso_lang}-default-{$imageType}.jpg" alt="legend" title="legend" />
</a>
</td>
<td>legend</td>
@@ -129,6 +141,28 @@
var current_shop_id = {$current_shop_id|intval};
{literal}
//Ready Function
function imageLine(id, path, position, cover, shops, legend)
{
line = $("#lineType").html();
line = line.replace(/image_id/g, id);
line = line.replace(/[a-z]{0,2}-default-small_default/g, path+'-small_default');
line = line.replace(/image_path/g, path);
line = line.replace(/image_position/g, position);
line = line.replace(/legend/g, legend);
line = line.replace(/icon-check-empty/g, cover);
line = line.replace(/<tbody>/gi, "");
line = line.replace(/<\/tbody>/gi, "");
if (shops != false)
{
$.each(shops, function(key, value){
if (value == 1)
line = line.replace('id="' + key + '' + id + '"','id="' + key + '' + id + '" checked=checked');
});
}
$("#imageList").append(line);
}
$(document).ready(function(){
{/literal}
{foreach from=$images item=image}
@@ -165,66 +199,6 @@
updateImagePosition(image_up);
}
});
var filecheck = 1;
var params = new Array;
params['id_product'] = {/literal}{$id_product|intval}{literal};
params['id_category'] = {/literal}{$id_category_default|intval}{literal};
params['token'] = "{/literal}{$token}{literal}";
params['tab'] = "AdminProducts";
params['action'] = "addImage";
params['ajax'] = 1;
uploader = new qq.FileUploader(
{
element: document.getElementById("file-uploader"),
action: "ajax-tab.php",
debug: false,
onComplete: function(id, fileName, responseJSON)
{
var percent = ((filecheck * 100) / nbfile);
$("#progressBarImage").progressbar({value: percent});
if (percent != 100)
{
$("#imageUpload").html(parseInt(filecheck));
$("#imageTotal").html(" / " + parseInt(nbfile) + " {/literal}{l s='Images'}{literal}");
$("#progressBarImage").show();
$("#showCounter").show();
}
else
{
$("#progressBarImage").progressbar({value: 0});
$("#progressBarImage").hide();
$("#showCounter").hide();
nbfile = 0;
filecheck = 0;
}
if (responseJSON.status == 'ok')
{
cover = "icon-check-empty";
if (responseJSON.cover == "1")
cover = "icon-check-sign";
imageLine(responseJSON.id, responseJSON.path, responseJSON.position, cover, responseJSON.shops, responseJSON.legend[{/literal}{$default_language|intval}{literal}])
$("#imageTable tr:last").after(responseJSON.html);
$("#countImage").html(parseInt($("#countImage").html()) + 1);
$("#img" + id).remove();
$("#imageTable").tableDnDUpdate();
showSuccessMessage(responseJSON.name + " " + success_add);
}
else
showErrorMessage(responseJSON.error);
filecheck++;
},
onSubmit: function(id, filename)
{
$('input[id^="legend_"]').each(function()
{
id = $(this).prop("id").replace("legend_", "legend[") + "]";
params[id] = $(this).val();
});
uploader.setParams(params);
$("#imageTable").show();
$("#listImage").append("<li id='img"+id+"'><div>" + filename + "</div></div><a href=\"javascript:delQueue(" + id +");\"><img src=\"../img/admin/disabled.gif\" ></a><p class=\"errorImg\"></p></li>");
}
});
/**
* on success function
@@ -327,28 +301,11 @@
$("#img" + id).remove();
}
function imageLine(id, path, position, cover, shops, legend)
{
line = $("#lineType").html();
line = line.replace(/image_id/g, legend);
line = line.replace(/[a-z]{0,2}-default-small_default/g, path+'-small_default');
line = line.replace(/image_path/g, path);
line = line.replace(/image_position/g, position);
line = line.replace(/legend/g, legend);
line = line.replace(/icon-check-empty/g, cover);
line = line.replace(/<tbody>/gi, "");
line = line.replace(/<\/tbody>/gi, "");
if (shops != false)
{
$.each(shops, function(key, value){
if (value == 1)
line = line.replace('id="' + key + '' + id + '"','id="' + key + '' + id + '" checked=checked');
});
}
$("#imageList").append(line);
}
$('.fancybox').fancybox();
});
hideOtherLanguage(default_language);
{/literal}
</script>
</div>
+2
View File
@@ -366,6 +366,8 @@
'HelperFormCore' => 'classes/helper/HelperForm.php',
'HelperHelpAccess' => '',
'HelperHelpAccessCore' => 'classes/helper/HelperHelpAccess.php',
'HelperImageUploader' => '',
'HelperImageUploaderCore' => 'classes/helper/HelperImageUploader.php',
'HelperKpi' => '',
'HelperKpiCore' => 'classes/helper/HelperKpi.php',
'HelperKpiRow' => '',
+108 -37
View File
@@ -1331,42 +1331,6 @@ class AdminProductsControllerCore extends AdminController
}
}
/* @todo rename to processaddproductimage */
public function ajaxProcessAddImage()
{
self::$currentIndex = 'index.php?tab=AdminProducts';
$allowedExtensions = array('jpeg', 'gif', 'png', 'jpg');
// max file size in bytes
$uploader = new FileUploader($allowedExtensions, $this->max_image_size);
$result = $uploader->handleUpload();
if (isset($result['success']))
{
$obj = new Image((int)$result['success']['id_image']);
// Associate image to shop from context
$shops = Shop::getContextListShopID();
$obj->associateTo($shops);
$json_shops = array();
foreach ($shops as $id_shop)
$json_shops[$id_shop] = true;
$json = array(
'name' => $result['success']['name'],
'status' => 'ok',
'id'=>$obj->id,
'path' => $obj->getExistingImgPath(),
'position' => $obj->position,
'legend' => $obj->legend,
'cover' => $obj->cover,
'shops' => $json_shops,
);
@unlink(_PS_TMP_IMG_DIR_.'product_'.(int)$obj->id_product.'.jpg');
@unlink(_PS_TMP_IMG_DIR_.'product_mini_'.(int)$obj->id_product.'_'.$this->context->shop->id.'.jpg');
die(Tools::jsonEncode($json));
}
else
die(Tools::jsonEncode($result));
}
public function ajaxProcessDeleteProductAttribute()
{
if (!Combination::isFeatureActive())
@@ -3650,6 +3614,108 @@ class AdminProductsControllerCore extends AdminController
}
}
public function ajaxProcessaddProductImage()
{
self::$currentIndex = 'index.php?tab=AdminProducts';
$product = new Product((int)Tools::getValue('id_product'));
$legends = Tools::getValue('legend');
if (!is_array($legends))
$legends = (array)$legends;
if (!Validate::isLoadedObject($product))
{
$files = array();
$files[0]['error'] = Tools::displayError('Cannot add image because product creation failed.');
}
$image_uploader = new HelperImageUploader('file');
$image_uploader->setAcceptTypes(array('jpeg', 'gif', 'png', 'jpg'))->setMaxSize($this->max_image_size);
$files = $image_uploader->process();
foreach ($files as &$file)
{
$image = new Image();
$image->id_product = (int)($product->id);
$image->position = Image::getHighestPosition($product->id) + 1;
foreach ($legends as $key => $legend)
if (!empty($legend))
$image->legend[(int)$key] = $legend;
if (!Image::getCover($image->id_product))
$image->cover = 1;
else
$image->cover = 0;
if (!$image->add())
$file['error'] = Tools::displayError('Error while creating additional image');
else
{
if (!$new_path = $image->getPathForCreation())
{
$file['error'] = Tools::displayError('An error occurred during new folder creation');
continue;
}
if (!ImageManager::resize($file['save_path'], $new_path.'.'.$image->image_format))
{
$file['error'] = Tools::displayError('An error occurred while copying image.');
continue;
}
else
{
$imagesTypes = ImageType::getImagesTypes('products');
foreach ($imagesTypes as $imageType)
{
/*
$theme = (Shop::isFeatureActive() ? '-'.$imageType['id_theme'] : '');
if (!ImageManager::resize($tmpName, $new_path.'-'.stripslashes($imageType['name']).$theme.'.'.$image->image_format, $imageType['width'], $imageType['height'], $image->image_format))
return array('error' => Tools::displayError('An error occurred while copying image:').' '.stripslashes($imageType['name']));
*/
if (!ImageManager::resize($file['save_path'], $new_path.'-'.stripslashes($imageType['name']).'.'.$image->image_format, $imageType['width'], $imageType['height'], $image->image_format))
{
$file['error'] = Tools::displayError('An error occurred while copying image:').' '.stripslashes($imageType['name']);
continue;
}
}
}
unlink($file['save_path']);
//Necesary to prevent hacking
unset($file['save_path']);
Hook::exec('actionWatermark', array('id_image' => $image->id, 'id_product' => $product->id));
if (!$image->update())
{
$file['error'] = Tools::displayError('Error while updating status');
continue;
}
// Associate image to shop from context
$shops = Shop::getContextListShopID();
$image->associateTo($shops);
$json_shops = array();
foreach ($shops as $id_shop)
$json_shops[$id_shop] = true;
$file['status'] = 'ok';
$file['id'] = $image->id;
$file['position'] = $image->position;
$file['cover'] = $image->cover;
$file['legend'] = $image->legend;
$file['path'] = $image->getExistingImgPath();
$file['shops'] = $json_shops;
@unlink(_PS_TMP_IMG_DIR_.'product_'.(int)$product->id.'.jpg');
@unlink(_PS_TMP_IMG_DIR_.'product_mini_'.(int)$product->id.'_'.$this->context->shop->id.'.jpg');
}
}
die(Tools::jsonEncode(array($image_uploader->getName() => $files)));
}
public function initFormImages($obj)
{
$data = $this->createTemplate($this->tpl_form);
@@ -3688,6 +3754,10 @@ class AdminProductsControllerCore extends AdminController
$current_shop_id = 0;
$languages = Language::getLanguages(true);
$image_uploader = new HelperImageUploader('file');
$image_uploader->setMultiple(true)->setUseAjax(true)->setUrl(
Context::getContext()->link->getAdminLink('AdminProducts').'&ajax=1&id_product='.(int)$obj->id
.'&action=addProductImage');
$data->assign(array(
'countImages' => $count_images,
@@ -3702,7 +3772,8 @@ class AdminProductsControllerCore extends AdminController
'currency' => $this->context->currency,
'current_shop_id' => $current_shop_id,
'languages' => $this->_languages,
'default_language' => (int)Configuration::get('PS_LANG_DEFAULT')
'default_language' => (int)Configuration::get('PS_LANG_DEFAULT'),
'image_uploader' => $image_uploader->render()
));
$type = ImageType::getByNameNType('%', 'products', 'height');