Hy all,
I'm working on an import of more than 30.000 products from an old webshop system to my OpenCart application.
I've got the categories working, and the products, but there is only 1 thing that i can't fix. That is that there's no image.
I've uploaded all images in OpenCartRoot/image/data/old/tt_productsv2/images/
In the database, it is inserted:
image/old/tt_productsv2/images/greatest.jpg
I've confirmed that that image exist, but when i check the front-end page, there are no images. Also when i check the back-end, i don't see any image linked to the product.
So my question is, what wrong I have done? Why isn't the image linked to the product, although i inserted the link in the database...
The path to the image in the database should only be
old/tt_productsv2/images/greatest.jpg
as OpenCart will build the path like
DIR_IMAGE . 'old/tt_productsv2/images/greatest.jpg'
where DIR_IMAGE is defined like
define('DIR_IMAGE', '/path/to/web/root/image/');
Yes, this is a problem with GLOBAL_BRACE Constant.
Some servers do not support that constant value, so you can change the
server or change the code.
The code is in:
admin / controller / common/ filemanager.php
line No : 37 ===================================================================
<?php
class ControllerCommonFileManager extends Controller {
public function index() {
$this->load->language('common/filemanager');
if (isset($this->request->get['filter_name'])) {
$filter_name = rtrim(str_replace(array('../', '..\\', '..', '*'), '', $this->request->get['filter_name']), '/');
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$data['images'] = array();
$this->load->model('tool/image');
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
// $files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
$files1 = glob($directory . '/' . $filter_name . '*.jpg');
if (!$files1) {
$files1 = array();
}
$files2 = glob($directory . '/' . $filter_name . '*.jpeg');
if (!$files2) {
$files2 = array();
}
$files3 = glob($directory . '/' . $filter_name . '*.JPG');
if (!$files3) {
$files3 = array();
}
$files4 = glob($directory . '/' . $filter_name . '*.png');
if (!$files4) {
$files4 = array();
}
$files5 = glob($directory . '/' . $filter_name . '*.JPEG');
if (!$files5) {
$files5 = array();
}
$files6 = glob($directory . '/' . $filter_name . '*.PNG');
if (!$files6) {
$files6 = array();
}
$files7 = glob($directory . '/' . $filter_name . '*.GIF');
if (!$files7) {
$files7 = array();
}
$files8 = glob($directory . '/' . $filter_name . '*.gif');
if (!$files8) {
$files8 = array();
}
$files = array_merge($files1, $files2,$files3,$files4,$files5,$files6,$files7,$files8);
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
// Split the array based on current page number and max number of items per page of 10
$images = array_splice($images, ($page - 1) * 16, 16);
foreach ($images as $image) {
$name = str_split(basename($image), 14);
if (is_dir($image)) {
$url = '';
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
'href' => $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . '&directory=' . urlencode(utf8_substr($image, utf8_strlen(DIR_IMAGE . 'catalog/'))) . $url, true)
);
} elseif (is_file($image)) {
// Find which protocol to use to pass the full image link back
if ($this->request->server['HTTPS']) {
$server = HTTPS_CATALOG;
} else {
$server = HTTP_CATALOG;
}
$data['images'][] = array(
'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100),
'name' => implode(' ', $name),
'type' => 'image',
'path' => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
'href' => $server . 'image/' . utf8_substr($image, utf8_strlen(DIR_IMAGE))
);
}
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_confirm'] = $this->language->get('text_confirm');
$data['entry_search'] = $this->language->get('entry_search');
$data['entry_folder'] = $this->language->get('entry_folder');
$data['button_parent'] = $this->language->get('button_parent');
$data['button_refresh'] = $this->language->get('button_refresh');
$data['button_upload'] = $this->language->get('button_upload');
$data['button_folder'] = $this->language->get('button_folder');
$data['button_delete'] = $this->language->get('button_delete');
$data['button_search'] = $this->language->get('button_search');
$data['token'] = $this->session->data['token'];
if (isset($this->request->get['directory'])) {
$data['directory'] = urlencode($this->request->get['directory']);
} else {
$data['directory'] = '';
}
if (isset($this->request->get['filter_name'])) {
$data['filter_name'] = $this->request->get['filter_name'];
} else {
$data['filter_name'] = '';
}
// Return the target ID for the file manager to set the value
if (isset($this->request->get['target'])) {
$data['target'] = $this->request->get['target'];
} else {
$data['target'] = '';
}
// Return the thumbnail for the file manager to show a thumbnail
if (isset($this->request->get['thumb'])) {
$data['thumb'] = $this->request->get['thumb'];
} else {
$data['thumb'] = '';
}
// Parent
$url = '';
if (isset($this->request->get['directory'])) {
$pos = strrpos($this->request->get['directory'], '/');
if ($pos) {
$url .= '&directory=' . urlencode(substr($this->request->get['directory'], 0, $pos));
}
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['parent'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, true);
// Refresh
$url = '';
if (isset($this->request->get['directory'])) {
$url .= '&directory=' . urlencode($this->request->get['directory']);
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['refresh'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, true);
$url = '';
if (isset($this->request->get['directory'])) {
$url .= '&directory=' . urlencode(html_entity_decode($this->request->get['directory'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_name'])) {
$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$pagination = new Pagination();
$pagination->total = $image_total;
$pagination->page = $page;
$pagination->limit = 16;
$pagination->url = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);
$data['pagination'] = $pagination->render();
$this->response->setOutput($this->load->view('common/filemanager', $data));
}
public function upload() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->language->get('error_directory');
}
if (!$json) {
if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
// Sanitize the filename
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
// Validate the filename length
if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 255)) {
$json['error'] = $this->language->get('error_filename');
}
// Allowed file extension types
$allowed = array(
'jpg',
'jpeg',
'gif',
'png'
);
if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Allowed file mime types
$allowed = array(
'image/jpeg',
'image/pjpeg',
'image/png',
'image/x-png',
'image/gif'
);
if (!in_array($this->request->files['file']['type'], $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Return any upload error
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}
}
if (!$json) {
move_uploaded_file($this->request->files['file']['tmp_name'], $directory . '/' . $filename);
$json['success'] = $this->language->get('text_uploaded');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function folder() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->language->get('error_directory');
}
if (!$json) {
// Sanitize the folder name
$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($this->request->post['folder'], ENT_QUOTES, 'UTF-8')));
// Validate the filename length
if ((utf8_strlen($folder) < 3) || (utf8_strlen($folder) > 128)) {
$json['error'] = $this->language->get('error_folder');
}
// Check if directory already exists or not
if (is_dir($directory . '/' . $folder)) {
$json['error'] = $this->language->get('error_exists');
}
}
if (!$json) {
mkdir($directory . '/' . $folder, 0777);
chmod($directory . '/' . $folder, 0777);
$json['success'] = $this->language->get('text_directory');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function delete() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
if (isset($this->request->post['path'])) {
$paths = $this->request->post['path'];
} else {
$paths = array();
}
// Loop through each path to run validations
foreach ($paths as $path) {
$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');
// Check path exsists
if ($path == DIR_IMAGE . 'catalog') {
$json['error'] = $this->language->get('error_delete');
break;
}
}
if (!$json) {
// Loop through each path
foreach ($paths as $path) {
$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');
// If path is just a file delete it
if (is_file($path)) {
unlink($path);
// If path is a directory beging deleting each file and sub folder
} elseif (is_dir($path)) {
$files = array();
// Make path into an array
$path = array($path . '*');
// While the path array is still populated keep looping through
while (count($path) != 0) {
$next = array_shift($path);
foreach (glob($next) as $file) {
// If directory add to path array
if (is_dir($file)) {
$path[] = $file . '/*';
}
// Add the file to the files to be deleted array
$files[] = $file;
}
}
// Reverse sort the file array
rsort($files);
foreach ($files as $file) {
// If file just delete
if (is_file($file)) {
unlink($file);
// If directory use the remove directory function
} elseif (is_dir($file)) {
rmdir($file);
}
}
}
}
$json['success'] = $this->language->get('text_delete');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
Related
i'm working on a Joomla 3.x component, I'm trying to build an array with folders, files and filenames, I can get the Folders and Files , including paths, which I want, but have been unable to get it to return the names using "basename()" to get just the name.ext . I get an error regarding passing an array to "basename()" in lieu of a string, I've tried "foreach" but it only returns the last item in the array.
Below is the code
function getPathContents() {
$this->directory = 'some/directory';
$recursive = '1';
$this->recursive = ($recursive == 'true' || $recursive == 'recursive' || $recursive == '1');
$this->exclude_folders = '';
$this->exclude_files = '';
$options = array();
$filenames = array();
$filename = basename($filenames);
$path = $this->directory;
if (!is_dir($path))
{
if (is_dir(JPATH_ROOT . '/' . $path))
{
$path = JPATH_ROOT . '/' . $path;
}
else
{
return;
}
}
$path = JPath::clean($path);
$folders = JFolder::folders($path, $this->filter, $this->recursive, true);
// Build the options list from the list of folders.
if (is_array($folders))
{
foreach ($folders as $folder)
{
$options['folders'] = $folders;
$files = JFolder::files($folder, $this->filter, $this->recursive, true);
if (is_array($files))
{
foreach ($files as $file)
{
$options['files'] = $files;
}
$filenames = JFolder::files($folder, $this->filter, $this->recursive, true);
if (is_array($filenames))
{
foreach ($files as $filename)
{
$options['filenames'] = $filename;
}
}
}
}
return $options;
}
any help would be great
UPDATE: Below Code will provide list of Folders and additional arrays of files located in each folder. Each file array is labeled with the Folders name.
Code
function getFolersfiles() {
$this->directory = 'yourpath';
$recursive = '1';
$this->recursive = ($recursive == 'true' || $recursive == 'recursive' || $recursive == '1');
$this->exclude_folders = '';
$this->exclude_files = '';
$path = $this->directory;
if (!is_dir($path))
{
if (is_dir(JPATH_ROOT . '/' . $path))
{
$path = JPATH_ROOT . '/' . $path;
}
else
{
return;
}
}
$path = JPath::clean($path);
$options2['folders'] = JFolder::folders($path, $this->filter, $this->recursive, true);
// Build the options list from the list of folders.
if (is_array($options2))
{
foreach ($options2['folders'] as $option2)
{
$optionname = basename($option2);
$options2[$optionname] = JFolder::files($option2, $this->filter, $this->recursive, true);
//$options2['filepath'] = JFolder::files($option2, $this->filter, $this->recursive, true);
}
return $options2;
}
Thank you for the help
Got a situation with image import process, before asking here of course - tried many ways to solve it by myself, but without any luck yet.
I'm getting error in model file: trim() expects parameter 1 to be string, array given in file /.../file.php on line 3875. Have to mention that - when there's single image - importing that perfectly, as soon as getting multiple images (more than one) - getting this error, and doesn't importing any image, just skipping.
Line 387: $image = trim($image);
Whole function code:
protected function imageHandler($field, &$config, $multiple = false, $item_id = NULL) {
$image_array = array();
if (empty($config['columns'][$field])) {
if ($multiple) {
return $image_array;
} else {
return '';
}
}
$sort_order = 0;
foreach ((array) $config['columns'][$field] as $images) {
if (!empty($config['multiple_separator']) && is_string($images)) {
$images = explode(#html_entity_decode($config['multiple_separator']), $images);
}
//is_array($images) && reset($images);
if ($multiple && is_array($images) && $config['columns']['image'] == $images[key($images)]) {
array_shift($images);
}
foreach ((array) $images as $image) {
$image = trim($image);
if ($config['image_download'] && $image) {
// if (substr($image, 0, 2) == '//') {
// $image = 'http:' . $image;
// }
$file_info = pathinfo(parse_url(trim($image), PHP_URL_PATH));
// if no extension, get it by mime
if (empty($file_info['extension'])) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, trim($image));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
switch($contentType) {
case 'image/bmp': $file_info['extension'] = 'bmp'; break;
case 'image/gif': $file_info['extension'] = 'gif'; break;
case 'image/jpeg': $file_info['extension'] = 'jpg'; break;
case 'image/pipeg': $file_info['extension'] = 'jfif'; break;
case 'image/tiff': $file_info['extension'] = 'tif'; break;
case 'image/png': $file_info['extension'] = 'png'; break;
default: $file_info['extension'] = '';
}
}
if (substr_count($file_info['dirname'], 'http')) {
// incorrect array extract
if (!$multiple) {
return $image;
} else {
$image_array[] = $image;
continue;
}
}
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
$this->session->data['obui_log'][] = array(
'row' => $this->session->data['obui_current_line'],
'status' => 'error',
'title' => $this->language->get('warning'),
'msg' => $this->language->get('warning_incorrect_image_format') . ' ' . str_replace(' ', '%20', $image),
);
if (!$multiple) {
return $image;
} else {
$image_array[] = $image;
continue;
}
}
if ($this->simulation) {
if (!$multiple) {
/* Now handled before
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
return array('error_format', $image);
}*/
return $image;
} else {
/* Now handled before
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
$image_array[] = 'error_format';
continue;
}*/
$image_array[] = $image;
continue;
}
}
// detect if image is on actual server
if (strpos($image, 'http') === false) {
$filename = trim($image);
if (!$multiple) {
return $filename;
} else {
if (!empty($filename)) {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
}
continue;
}
}
if (version_compare(VERSION, '2', '>=')) {
$path = 'catalog/';
//$http_path = HTTP_CATALOG . 'image/catalog/';
} else {
$path = 'data/';
//$http_path = HTTP_CATALOG . 'image/data/';
}
if (trim($config['image_location'], '/\\')) {
$path .= trim($config['image_location'], '/\\') . '/';
}
if ($config['image_keep_path'] && trim($file_info['dirname'], '/\\')) {
$path .= trim($file_info['dirname'], '/\\') . '/';
}
if (!is_dir(DIR_IMAGE . $path)) {
mkdir(DIR_IMAGE . $path, 0777, true);
}
$filename = $path . urldecode($file_info['filename']) . '.' . $file_info['extension'];
if (($item_id === false && $this->config->get('mlseo_insertautoimgname')) || ($item_id && $this->config->get('mlseo_editautoimgname'))) {
$this->load->model('tool/seo_package');
$seo_image_name = $this->model_tool_seo_package->transformProduct($this->config->get('mlseo_product_image_name_pattern'), $this->config->get('config_language_id'), $config['columns']);
$seoPath = pathinfo($filename);
if (!empty($seoPath['filename'])) {
$seoFilename = $this->model_tool_seo_package->filter_seo($seo_image_name, 'image', '', '');
$filename = $seoPath['dirname'] . '/' . $seoFilename . '.' . $seoPath['extension'];
if (file_exists(DIR_IMAGE . $filename)) {
$x = 1;
while (file_exists(DIR_IMAGE . $filename)) {
$filename = $seoPath['dirname'] . '/' . $seoFilename . '-' . $x . '.' . $seoPath['extension'];
$x++;
}
}
}
}
if ($config['image_exists'] == 'rename') {
$x = 1;
while (file_exists(DIR_IMAGE . $filename)) {
$filename = $path . urldecode($file_info['filename']) . '-' . $x++ . '.' . $file_info['extension'];
}
} else if ($config['image_exists'] == 'keep' && file_exists(DIR_IMAGE . $filename)) {
// image skipped
if (!$multiple) {
return $filename;
} else {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
continue;
}
}
// copy image, replace space chars for compatibility with copy()
// if (!#copy(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename)) {
$copyError = $this->copy_image(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename);
if ($copyError !== true) {
if (defined('GKD_CRON')) {
$this->cron_log($this->session->data['obui_current_line'] . ' - ' . $copyError);
} else {
$this->session->data['obui_log'][] = array(
'row' => $this->session->data['obui_current_line'],
'status' => 'error',
'title' => $this->language->get('warning'),
'msg' => $copyError,
);
}
$filename = '';
}
} else {
// get direct value
$filename = trim($image);
if ($this->simulation) {
if (!$multiple) {
return $filename;
} else {
if (!empty($filename)) {
$image_array[] = $filename;
}
continue;
}
}
}
// one field only, directly return first value
if (!$multiple) {
return $filename;
}
if (!empty($filename)) {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
}
}
}
return $image_array;
}
Tried to use return $image; after that line, even that didn't helped. Was trying to find similar problem to this one to find a solution without posting here, but seems like I won't move anywhere withou help. Thanks in advance!
I write this element, but when I want to display the directory in dropown, I have the same directory twice.
LMy first dropdown work well:
blog
image
My second dropdown write the directory twice
blog
image
blog
image
<?php
//function
function osc_opendir($path) {
$path = rtrim($path, '/') . '/';
$exclude_array = array('.', '..', '.DS_Store', '.directory', '.htaccess', 'Thumbs.db','.php', '_note');
$result = array();
if ($handle = opendir($path)) {
while (false !== ($filename = readdir($handle))) {
if (!in_array($filename, $exclude_array)) {
$file = array('name' => $path . $filename,
'is_dir' => is_dir($path . $filename),
'writable' => is_writable($path . $filename)
);
$result[] = $file;
if ($file['is_dir'] == true) {
$result = array_merge($result, osc_opendir($path . $filename));
}
}
}
closedir($handle);
}
return $result;
// place allowed sub-dirs in array, non-recursive
// just only one image
$dir_array = array();
foreach (osc_opendir($root_images_dir) as $file) {
if ($file['is_dir']) {
$img_dir_products_image = substr($file['name'], strlen($root_images_dir));
$drop_array[] = array('id' => $img_dir_products_image,
'text' => $img_dir_products_image
);
}
}
echo HTML::selectMenu('directory_products_image', $drop_array);
// second dropdown
// for the image gallery
// gallery
// lecture des fichiers
$dir_array = array();
foreach (osc_opendir($root_images_dir) as $file1) {
if ($file1['is_dir']) {
$img_dir = substr($file1['name'], strlen($root_images_dir));
$drop_array[] = array('id' => $img_dir,
'text' => $img_dir
);
}
}
echo '<div class="row"><span class="col-xs-3">'.TEXT_PRODUCTS_IMAGE_DIRECTORY. ' ' . HTML::selectMenu('directory', $drop_array) . '</span></div>';
echo TEXT_PRODUCTS_IMAGE_NEW_FOLDER_GALLERY . HTML::inputField('new_directory','','class="input-small"') .'<br /><br />';
You're getting it twice, because you're ADDING it twice:
$result[] = $file;
^^---append filename to array
$result = array_merge($result, osc_opendir($path . $filename));
^^^^^^^--- add it yet again
I'm trying to upload several files with their names in different field.
example--- there are 3 form fields for inserting names and 3 fields for uploading files in there respective order.
this is image attached, fr what i'm trying to achieve --
http://imgur.com/pGAlsjF
Now what i want is, when a user enters name in "document name" label in first field and selects a file to upload in "document file" label first field, then data gets inserted. else shows an error.
user should enter file name select file in there respective order, else it should show error.
it should error when a user enters name in first field and selects a file in second field then it should display error.
this is being done opencart admin section.
currently this is the simple code for simple validation --
foreach ($this->request->post['document_description'] as $language_id => $value) {
if ((utf8_strlen($value['name']) < 3) || (utf8_strlen($value['name']) > 64)) {
$this->error['name'][$language_id] = $this->language->get('error_name');
}
}
One thing is common between file name field and form upload field is "language id".
code for documents.php are ---
protected function getForm() {
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['entry_name'] = $this->language->get('entry_name');
$this->data['entry_filename'] = $this->language->get('entry_filename');
$this->data['entry_mask'] = $this->language->get('entry_mask');
$this->data['entry_remaining'] = $this->language->get('entry_remaining');
$this->data['entry_update'] = $this->language->get('entry_update');
$this->data['button_save'] = $this->language->get('button_save');
$this->data['button_cancel'] = $this->language->get('button_cancel');
$this->data['button_upload'] = $this->language->get('button_upload');
if (isset($this->error['warning'])) {
$this->data['error_warning'] = $this->error['warning'];
} else {
$this->data['error_warning'] = '';
}
if (isset($this->error['name'])) {
$this->data['error_name'] = $this->error['name'];
} else {
$this->data['error_name'] = array();
}
if (isset($this->error['filename'])) {
$this->data['error_filename'] = $this->error['filename'];
} else {
$this->data['error_filename'] = '';
}
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('catalog/documents', 'token=' . $this->session->data['token'] . $url, 'SSL'),
'separator' => ' :: '
);
if (!isset($this->request->get['document_id'])) {
$this->data['action'] = $this->url->link('catalog/documents/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
} else {
$this->data['action'] = $this->url->link('catalog/documents/update', 'token=' . $this->session->data['token'] . '&document_id=' . $this->request->get['document_id'] . $url, 'SSL');
}
$this->data['cancel'] = $this->url->link('catalog/documents', 'token=' . $this->session->data['token'] . $url, 'SSL');
$this->load->model('localisation/language');
$this->data['languages'] = $this->model_localisation_language->getLanguages();
if (isset($this->request->get['document_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
$document_info = $this->model_catalog_documents->getDocument($this->request->get['document_id']);
}
$this->data['token'] = $this->session->data['token'];
if (isset($this->request->get['document_id'])) {
$this->data['document_id'] = $this->request->get['document_id'];
} else {
$this->data['document_id'] = 0;
}
if (isset($this->request->post['document_description'])) {
$this->data['document_description'] = $this->request->post['document_description'];
} elseif (isset($this->request->get['document_id'])) {
$this->data['document_description'] = $this->model_catalog_documents->getDocumentDescriptions($this->request->get['document_id']);
} else {
$this->data['document_description'] = array();
}
if (isset($this->request->post['filename'])) {
$this->data['filename'] = $this->request->post['filename'];
} elseif (!empty($document_info)) {
$this->data['filename'] = $document_info['filename'];
} else {
$this->data['filename'] = '';
}
if (isset($this->request->post['mask'])) {
$this->data['mask'] = $this->request->post['mask'];
} elseif (!empty($document_info)) {
$this->data['mask'] = $document_info['mask'];
} else {
$this->data['mask'] = '';
}
if (isset($this->request->post['remaining'])) {
$this->data['remaining'] = $this->request->post['remaining'];
} elseif (!empty($document_info)) {
$this->data['remaining'] = $document_info['remaining'];
} else {
$this->data['remaining'] = 1;
}
if (isset($this->request->post['update'])) {
$this->data['update'] = $this->request->post['update'];
} else {
$this->data['update'] = false;
}
$this->template = 'catalog/documents_form.tpl';
$this->children = array(
'common/header',
'common/footer'
);
$this->response->setOutput($this->render());
}
protected function validateForm() {
if (!$this->user->hasPermission('modify', 'catalog/documents')) {
$this->error['warning'] = $this->language->get('error_permission');
}
print_r($this->request->post['document_description']); echo "<br>";
print_r($this->request->files['document_files']); echo "<br>";
foreach ($this->request->files['document_files'] as $files => $value)
{
print_r($files.'==>'.print_r($value)); echo "<br>";
}die;
foreach ($this->request->post['document_description'] as $language_id => $value) {
foreach ($this->request->files['document_files'] as $selected => $filename)
{
if ((utf8_strlen($value['name']) < 3) || (utf8_strlen($value['name']) > 64))
{
$this->error['name'][$language_id] = $this->language->get('error_name');
}
if (empty($filename))
{
$this->error['name'][$language_id] = $this->language->get('error_name');
}
}
}
if (!$this->error) {
return true;
} else {
return false;
}
}
public function upload() {
$this->language->load('sale/order');
$json = array();
if (!$this->user->hasPermission('modify', 'catalog/documents')) {
$json['error'] = $this->language->get('error_permission');
}
if (!isset($json['error'])) {
if (!empty($this->request->files['file']['name'])) {
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
$json['error'] = $this->language->get('error_filename');
}
// Allowed file extension types
$allowed = array();
$filetypes = explode("\n", $this->config->get('config_file_extension_allowed'));
foreach ($filetypes as $filetype) {
$allowed[] = trim($filetype);
}
if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Allowed file mime types
$allowed = array();
$filetypes = explode("\n", $this->config->get('config_file_mime_allowed'));
foreach ($filetypes as $filetype) {
$allowed[] = trim($filetype);
}
if (!in_array($this->request->files['file']['type'], $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}
}
if (!isset($json['error'])) {
if (is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
$ext = md5(mt_rand());
$json['filename'] = $filename . '.' . $ext;
$json['mask'] = $filename;
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $filename . '.' . $ext);
}
$json['success'] = $this->language->get('text_upload');
}
$this->response->setOutput(json_encode($json));
}
Place the document name fields next to the document file field and hide it at first. Then display the document name fields when file is selected (jQuery - Detecting if a file has been selected in the file input).
In admin/controller/catalog/product.php, there is a function: validateForm where all validations are done. Within that function a foreach is used for language based validations:
foreach ($this->request->post['product_description'] as $language_id => $value) {
...........
//add your validation code here like:
if (trim($value['download_name']) == '' && $value['download_file'] == '' ) {
$this->error['downloadfile'][$language_id] = $this->language->get('error_ownloadfile');
}
...........
}// end of foreach
I need your help to mix two function in my site. My purpose is to upload and resize the image.
I ve got one function doing the job fine for User picture, and i ve got another one for uploading picture (list or ads picture) but this function does not create thumb picture. it just upload it. What i like to do is to upload and resize like the function dedicated userpic.
Hope you can help me.
Here is the function concerning user picture ( thumb resize working)
public function photo($id = "") {
$target_path = realpath(APPPATH . '../images/users');
//echo $target_path;
if (!is_writable(dirname($target_path))) {
$this->session->set_flashdata('flash_message', $this->Common_model->flash_message('error', 'Sorry! Destination folder is not writable.'));
redirect('users/edit', 'refresh');
} else {
if (!is_dir(realpath(APPPATH . '../images/users') . '/' . $id)) {
//echo $this->path.'/'.$id;
mkdir(realpath(APPPATH . '../images/users') . '/' . $id, 0777, true);
}
$target_path = $target_path . '/' . $id . '/userpic.jpg';
if ($_FILES['upload123']['name'] != '') {
move_uploaded_file($_FILES['upload123']['tmp_name'], $target_path);
$thumb1 = realpath(APPPATH . '../images/users') . '/' . $id . '/userpic_thumb.jpg';
GenerateThumbFile($target_path, $thumb1, 107, 78);
$thumb2 = realpath(APPPATH . '../images/users') . '/' . $id . '/userpic_profile.jpg';
GenerateThumbFile($target_path, $thumb2, 209, 209);
$thumb3 = realpath(APPPATH . '../images/users') . '/' . $id . '/userpic_micro.jpg';
GenerateThumbFile($target_path, $thumb3, 36, 36);
$this->session->set_flashdata('flash_message', $this->Common_model->flash_message('success', 'Your profile photo updated successfully.'));
redirect('users/edit', 'refresh');
} else {
$this->session->set_flashdata('flash_message', $this->Common_model->flash_message('error', 'Please browse your profile photo.'));
redirect('users/edit', 'refresh');
}
}
}
And here is the function i d like to implement the resize :
if ($this->input->post()) {
$listId = $param;
$images = $this->input->post('image');
$is_main = $this->input->post('is_main');
$fimages = $this->Gallery->get_imagesG($listId);
if ($is_main != '') {
foreach ($fimages->result() as $row) {
if ($row->id == $is_main)
$this->Common_model->updateTableData('list_photo', $row->id, NULL, array("is_featured" => 1));
else
$this->Common_model->updateTableData('list_photo', $row->id, NULL, array("is_featured" => 0));
}
}
if (!empty($images)) {
foreach ($images as $key => $value) {
$image_name = $this->Gallery->get_imagesG(NULL, array('id' => $value))->row()->name;
unlink($this->path . '/' . $listId . '/' . $image_name);
$conditions = array("id" => $value);
$this->Common_model->deleteTableData('list_photo', $conditions);
}
}
if (isset($_FILES["userfile"]["name"])) {
$insertData['list_id'] = $listId;
if (!is_dir($this->path . '/' . $listId)) {
//echo $this->path.'/'.$id;
mkdir($this->path . '/' . $listId, 0777, true);
$insertData['is_featured'] = 1;
}
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->path . '/' . $listId,
'encrypt_name' => TRUE,
'remove_spaces' => TRUE
);
//echo $this->path.'/'.$id;
$this->load->library('upload', $config);
$data = $this->upload->do_upload();
if ($data) {
$this->outputData['file'] = $this->upload->data();
$insertData['name'] = $this->outputData['file']['file_name'];
$insertData['created'] = local_to_gmt();
if ($this->outputData['file']['file_name'] != '')
$this->Common_model->insertData('list_photo', $insertData);
}
}
}
There's nothing in the lower piece of code to generate the thumb file.
You need something like this:
$this->thumb_path = realpath(APPPATH . '../directory/in/codeigniter/site/image/thumb');
Then after you have done the image upload in $this->upload->data() you will need to generate the thumb (adjust for your settings)
$thumb_config = array(
'source_image' => $data['full_path'],
'new_image' => $this->thumb_path,
'maintain_ratio' => true,
'width' => 200,
'height' => 200,
'quality' => '100%'
);
$this->load->library('image_lib', $thumb_config);
$this->image_lib->resize();
generate images thumb you need to use Image Processing (ImageMagick)
i provide below code to generate image thumbs.
function GenerateThumbnails($sourcePath1 = NULL, $destinationPath1 = NULL, $fileNames = NULL, $width = NULL, $height = NULL) {
try {
$sourcePath = $sourcePath1;
$destinationPath = $sourcePath . $destinationPath1 . "/";
if (isset($_POST['sourcePath'])) {
//$sourcePath = $_SERVER["DOCUMENT_ROOT"] . $_POST['sourcePath'];
$sourcePath = $_POST['sourcePath'];
}
if (isset($_POST['destinationPath'])) {
//$destinationPath = $_SERVER["DOCUMENT_ROOT"] . $_POST['destinationPath'];
$destinationPath = $_POST['destinationPath'];
}
if (isset($_POST['fileNames'])) {
$fileNames = json_decode($_POST['fileNames']);
}
if (isset($_POST['width'])) {
$width = $_POST['width'];
}
if (isset($_POST['height'])) {
$height = $_POST['height'];
}
foreach ($fileNames as $fileName) {
if (is_dir($sourcePath)) {
if (file_exists($sourcePath . $fileName)) {
$fetchFileExtension = array_values(array_filter(explode(".", $fileName)));
$fileExtension = end($fetchFileExtension);
$sourcePathFileName = $sourcePath . $fileName;
$destinationPathFileName = $destinationPath . $fileName;
$image = new Imagick();
$image->readImage($sourcePathFileName);
$image->scaleImage(1000, 0);
$image->setImageColorspace(255);
$image->setImageFormat('jpg');
$image = $image->flattenImages();
$image->thumbnailImage($width, $height, true);
(is_dir($destinationPath)) ? $image->writeImage($destinationPathFileName) : (createDirectory($destinationPath) AND $image->writeImage($destinationPathFileName));
chmod($destinationPathFileName, 0777);
$image->clear();
$image->destroy();
list($width1, $height1) = getimagesize($destinationPathFileName);
$data['orientation'] = ($width1 > $height1) ? 1 : 2;
$data['thumbnailChecksum'] = md5_file($destinationPathFileName);
$data['message'] = "Thumbnail created successfully .";
} else {
$data['message'] = "Thumbnail creation failed.";
}
}
}
return $data;
} catch (Exception $ex) {
print $ex->getMessage();
return false;
}
}