how to validate multiple file upload field in php? - php

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

Related

trim() expects parameter 1 to be string

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!

Limitting file upload on a User php

Im new to php please help me, I have a website and people can upload files like pdf, doc,xls and I want to limit the number of file upload. the user after login can see the upload page and upload his files but i want that the user can only upload files 3 times a day if he submitted 3 times in a day then it should not allow the user to upload more files it should give a message that you can not post more that 3 projects per day.
My files are: form.php and Uploadfile.php
<?php
use foundationphp\UploadFile;
session_start();
require_once 'src/foundationphp/UploadFile.php';
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
}
$max = 2000000;
$result = array();
if (isset($_POST['upload'])) {
$destination = __DIR__ . '/uploaded/';
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
// $upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
} catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Uploads</title>
<link href="styles/form.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Uploading Files</h1>
<?php if ($result || $error) { ?>
<ul class="result">
<?php
if ($error) {
echo "<li>{$error['message']}</li>";
}
if ($result) {
foreach ($result as $message) {
echo "<li>$message</li>";
}
}?>
</ul>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">
<label for="filename">Select File:</label>
<input type="file" name="filename[]" id="filename" multiple
data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
data-postmax="<?php echo $_SESSION['postmax'];?>"
data-displaymax="<?php echo $_SESSION['displaymax'];?>">
</p>
<ul>
<li>Up to <?php echo $_SESSION['maxfiles'];?> files can be uploaded simultaneously.</li>
<li>Each file should be no more than <?php echo UploadFile::convertFromBytes($max);?>.</li>
<li>Combined total should not exceed <?php echo $_SESSION ['displaymax'];?>.</li>
</ul>
<p>
<input type="submit" name="upload" value="Upload File">
</p>
</form>
<script src="js/checkmultiple.js"></script>
</body>
</html>
And uploadfile.php
<?php
namespace foundationphp;
class UploadFile
{
protected $destination;
protected $messages = array();
protected $maxSize = 2102400;//51200; //50 KB
protected $permittedTypes = array(
'image/jpeg',
'image/pjpeg',
'image/gif',
'image/png',
'image/webp',
'application/pdf',
'application/rar',
'application/zip',
'application/x-zip',
'application/x-zip-compressed',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.oasis.opendocument.text'
);
protected $newName;
protected $typeCheckingOn = true;
protected $notTrusted = array('bin', 'cgi', 'exe', 'dmg', 'js', 'pl', 'php', 'py', 'sh');
protected $suffix = '.upload';
protected $renameDuplicates;
public function __construct($uploadFolder)
{
if (!is_dir($uploadFolder) || !is_writable($uploadFolder)) {
throw new \Exception("$uploadFolder must be a valid, writable folder.");
}
if ($uploadFolder[strlen($uploadFolder)-1] != '/') {
$uploadFolder .= '/';
}
$this->destination = $uploadFolder;
}
public function setMaxSize($bytes)
{
$serverMax = self::convertToBytes(ini_get('upload_max_filesize'));
if ($bytes > $serverMax) {
throw new \Exception('Maximum size cannot exceed server limit for individual files: ' . self::convertFromBytes($serverMax));
}
if (is_numeric($bytes) && $bytes > 0) {
$this->maxSize = $bytes;
}
}
public static function convertToBytes($val)
{
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
if (in_array($last, array('g', 'm', 'k'))){
switch ($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
}
return $val;
}
public static function convertFromBytes($bytes)
{
$bytes /= 1024;
if ($bytes > 1024) {
return number_format($bytes/1024, 1) . ' MB';
} else {
return number_format($bytes, 1) . ' KB';
}
}
public function allowAllTypes($suffix = null)
{
$this->typeCheckingOn = false;
if (!is_null($suffix)) {
if (strpos($suffix, '.') === 0 || $suffix == '') {
$this->suffix = $suffix;
} else {
$this->suffix = ".$suffix";
}
}
}
public function upload($renameDuplicates = true)
{
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
}
public function getMessages()
{
return $this->messages;
}
protected function checkFile($file)
{
if ($file['error'] != 0) {
$this->getErrorMessage($file);
return false;
}
if (!$this->checkSize($file)) {
return false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
return false;
}
}
$this->checkName($file);
return true;
}
protected function getErrorMessage($file)
{
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
self::convertFromBytes($this->maxSize) . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' . $file['name'];
break;
}
}
protected function checkSize($file)
{
if ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is empty.';
return false;
} elseif ($file['size'] > $this->maxSize) {
$this->messages[] = $file['name'] . ' exceeds the maximum size for a file ('
. self::convertFromBytes($this->maxSize) . ').';
return false;
} else {
return true;
}
}
protected function checkType($file)
{
if (in_array($file['type'], $this->permittedTypes)) {
return true;
} else {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
protected function checkName($file)
{
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$nameparts = pathinfo($nospaces);
$extension = isset($nameparts['extension']) ? $nameparts['extension'] : '';
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
$i = 1;
do {
$this->newName = $nameparts['filename'] . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
if (in_array($extension, $this->notTrusted)) {
$this->newName .= $this->suffix;
}
} while (in_array($this->newName, $existing));
}
}
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$result .= '.';
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
Thanks/Regards,
Sam
You can use SQL to store the amount of files uploaded by each user. Then you can check in php if a user can upload another file or not with SQL queries.
EDIT:
Let's elaborate a little.
There can be 2 ways for achieving this:
a) server-side.
As you say, you have a login form. I suppose you have a database with usernames and passwords, right? So, you can add an 'uploads' table in your database with the timestamp of each upload and the username of the uploader.
Then, each time your PHP class is called, you can make a query to your database to see the amount of files the uploader has uploaded within the last 24 hours. If the number is <3 then your PHP class will allow him to upload another one. Else, your PHP class will echo the message you want.
b) client-side.
Each time a user uploads a file, the info about his uploads is stored in his localStorage. So, this info will be checked on 'upload' button click event and either he will be allowed to upload or not.
However, as I said, the info is stored in HIS localStorage, so, this method is bypassable by the user. I wouldn't recommend it.
Improve your upload function and add destination inside UploadFile class for better re-usability and security:
class UploadFile
{
protected $destination = __DIR__ . '/uploaded/';
protected $messages = array();
protected $maxSize = 2102400;//51200; //50 KB
protected $permittedTypes = array(
'image/jpeg',
'image/pjpeg',
'image/gif',
'image/png',
'image/webp',
'application/pdf',
'application/rar',
'application/zip',
'application/x-zip',
'application/x-zip-compressed',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.oasis.opendocument.text'
);
protected $newName;
protected $typeCheckingOn = true;
protected $notTrusted = array('bin', 'cgi', 'exe', 'dmg', 'js', 'pl', 'php', 'py', 'sh');
protected $suffix = '.upload';
protected $renameDuplicates;
public function __construct($uploadFolder)
{
if (!is_dir($uploadFolder) || !is_writable($uploadFolder)) {
throw new \Exception("$uploadFolder must be a valid, writable folder.");
}
if ($uploadFolder[strlen($uploadFolder)-1] != '/') {
$uploadFolder .= '/';
}
$this->destination = $uploadFolder;
}
public function setMaxSize($bytes)
{
$serverMax = self::convertToBytes(ini_get('upload_max_filesize'));
if ($bytes > $serverMax) {
throw new \Exception('Maximum size cannot exceed server limit for individual files: ' . self::convertFromBytes($serverMax));
}
if (is_numeric($bytes) && $bytes > 0) {
$this->maxSize = $bytes;
}
}
public static function convertToBytes($val)
{
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
if (in_array($last, array('g', 'm', 'k'))){
switch ($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
}
return $val;
}
public static function convertFromBytes($bytes)
{
$bytes /= 1024;
if ($bytes > 1024) {
return number_format($bytes/1024, 1) . ' MB';
} else {
return number_format($bytes, 1) . ' KB';
}
}
public function allowAllTypes($suffix = null)
{
$this->typeCheckingOn = false;
if (!is_null($suffix)) {
if (strpos($suffix, '.') === 0 || $suffix == '') {
$this->suffix = $suffix;
} else {
$this->suffix = ".$suffix";
}
}
}
public function upload($renameDuplicates = true)
{
$fi = new FilesystemIterator($this->destination, FilesystemIterator::SKIP_DOTS);
$totalFiles = iterator_count($fi);
if ($totalFiles <= 3){
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
} else {
die('You can not post more that 3 projects per day!'); //Improve this to a thrown or stuff;
}
}
public function getMessages()
{
return $this->messages;
}
protected function checkFile($file)
{
if ($file['error'] != 0) {
$this->getErrorMessage($file);
return false;
}
if (!$this->checkSize($file)) {
return false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
return false;
}
}
$this->checkName($file);
return true;
}
protected function getErrorMessage($file)
{
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
self::convertFromBytes($this->maxSize) . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' . $file['name'];
break;
}
}
protected function checkSize($file)
{
if ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is empty.';
return false;
} elseif ($file['size'] > $this->maxSize) {
$this->messages[] = $file['name'] . ' exceeds the maximum size for a file ('
. self::convertFromBytes($this->maxSize) . ').';
return false;
} else {
return true;
}
}
protected function checkType($file)
{
if (in_array($file['type'], $this->permittedTypes)) {
return true;
} else {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
protected function checkName($file)
{
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$nameparts = pathinfo($nospaces);
$extension = isset($nameparts['extension']) ? $nameparts['extension'] : '';
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
$i = 1;
do {
$this->newName = $nameparts['filename'] . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
if (in_array($extension, $this->notTrusted)) {
$this->newName .= $this->suffix;
}
} while (in_array($this->newName, $existing));
}
}
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$result .= '.';
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
I think you have a user table in you DB. just add a new attribute upload_day_count...
At every upload you check if the number is at 3 if not then you allow the upload and icrement the attribute value for this user. Day +1 at 00h01min you run a cron Job to reset all values for all users.

Combining PHP classes, not populating array

I've got 3 different classes (class Thumbnail in Thumbnail.php, class Upload in Upload.php and class ThumbnailUpload in ThumbnailUpload.php) all in the same namespace (PhotoProject). Currently, it will load an image, create a thumbnail and store both in selected directory, but it will not store the information requested into a database. If you look in the code snippet of blog_insert.php, once it gets to calling $loader->collectFilenames to be assigned to $names, nothing is ever stored in $names[]. I've did a var_dump, and $names is always empty. Any suggestions? Below are the code snippets.
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
...
public function collectFilenames() {
return $this->collectednames;
}
blog_insert.php
<?php
use PhotoProject\ThumbnailUpload;
require_once '../includes/connection.php';
$conn = dbConnect();
if (isset($_POST['insert'])) {
$OK = false;
$stmt = $conn->stmt_init();
// if a file has been uploaded, process it
if(isset($_POST['upload_new']) && $_FILES['image']['error'] == 0) {
$imageOK = false;
require_once '../PhotoProject/ThumbnailUpload.php';
$loader = new ThumbnailUpload('path to store images');
$loader->setThumbDestination('path to store thumbnail');
$loader->upload();
$names = $loader->collectFilenames();
// $names will be an empty array if the upload failed
if ($names) {
$sql = 'INSERT INTO images (filename, caption) VALUES (?, ?)';
Class Thumbnail
<?php
namespace PhotoProject;
class Thumbnail {
protected $original;
protected $originalwidth;
protected $originalheight;
protected $basename;
protected $thumbwidth;
protected $thumbheight;
protected $maxSize = 350;
protected $canProcess = false;
protected $imageType;
protected $destination;
protected $suffix = '_thb';
protected $messages = [];
public function __construct($image) {
if (is_file($image) && is_readable($image)) {
$details = getimagesize($image);
} else {
$details = null;
$this->messages[] = "Cannot open $image.";
}
// if getimagesize() returns an array, it looks like an image
if (is_array($details)) {
$this->original = $image;
$this->originalwidth = $details[0];
$this->originalheight = $details[1];
$this->basename = pathinfo($image, PATHINFO_FILENAME);
// check the MIME type
$this->checkType($details['mime']);
} else {
$this->messages[] = "$image doesn't appear to be an image.";
}
}
public function setDestination($destination) {
if (is_dir($destination) && is_writable($destination)) {
// get last character
$last = substr($destination, -1);
// add a trailing slash if missing
if ($last == '/' || $last == '\\') {
$this->destination = $destination;
} else {
$this->destination = $destination . DIRECTORY_SEPARATOR;
}
} else {
$this->messages[] = "Cannot write to $destination.";
}
}
public function setMaxSize($size) {
if (is_numeric($size) && $size > 0) {
$this->maxSize = abs($size);
} else {
$this->messages[] = 'The value for setMaxSize() must be a positive number.';
$this->canProcess = false;
}
}
public function setSuffix($suffix) {
if (preg_match('/^\w+$/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function create() {
if ($this->canProcess && $this->originalwidth != 0) {
$this->calculateSize($this->originalwidth, $this->originalheight);
$this->createThumbnail();
} elseif ($this->originalwidth == 0) {
$this->messages[] = 'Cannot determine size of ' . $this->original;
}
}
public function getMessages() {
return $this->messages;
}
protected function checkType($mime) {
$mimetypes = ['image/jpeg', 'image/png', 'image/gif'];
if (in_array($mime, $mimetypes)) {
$this->canProcess = true;
// extract the characters after 'image/'
$this->imageType = substr($mime, 6);
}
}
protected function calculateSize($width, $height) {
if ($width <= $this->maxSize && $height <= $this->maxSize) {
$ratio = 1;
} elseif ($width > $height) {
$ratio = $this->maxSize/$width;
} else {
$ratio = $this->maxSize/$height;
}
$this->thumbwidth = round($width * $ratio);
$this->thumbheight = round($height * $ratio);
}
protected function createImageResource() {
if ($this->imageType == 'jpeg') {
return imagecreatefromjpeg($this->original);
} elseif ($this->imageType == 'png') {
return imagecreatefrompng($this->original);
} elseif ($this->imageType == 'gif') {
return imagecreatefromgif($this->original);
}
}
protected function createThumbnail() {
$resource = $this->createImageResource();
$thumb = imagecreatetruecolor($this->thumbwidth, $this->thumbheight);
imagecopyresampled($thumb, $resource, 0, 0, 0, 0, $this->thumbwidth,
$this->thumbheight, $this->originalwidth, $this->originalheight);
$newname = $this->basename . $this->suffix;
if ($this->imageType == 'jpeg') {
$newname .= '.jpg';
$success = imagejpeg($thumb, $this->destination . $newname, 100);
} elseif ($this->imageType == 'png') {
$newname .= '.png';
$success = imagepng($thumb, $this->destination . $newname, 0);
} elseif ($this->imageType == 'gif') {
$newname .= '.gif';
$success = imagegif($thumb, $this->destination . $newname);
}
if ($success) {
$this->messages[] = "$newname created successfully.";
} else {
$this->messages[] = "Couldn't create a thumbnail for " .
basename($this->original);
}
imagedestroy($resource);
imagedestroy($thumb);
}
}
Class ThumbnailUpload
<?php
namespace PhotoProject;
use PhotoProject\Upload;
require_once 'Upload.php';
require_once 'Thumbnail.php';
class ThumbnailUpload extends Upload {
protected $thumbDestination;
protected $deleteOriginal;
protected $suffix = '_thb';
public function __construct($path, $deleteOriginal = false) {
parent::__construct($path);
$this->thumbDestination = $path;
$this->deleteOriginal = $deleteOriginal;
}
/*
** Setter method for the thumbnail destination
*/
public function setThumbDestination($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->thumbDestination = $path;
}
public function setThumbSuffix($suffix) {
if (preg_match('/\w+/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function allowAllTypes() {
$this->typeCheckingOn = true;
}
protected function createThumbnail($image) {
$thumb = new Thumbnail($image);
$thumb->setDestination($this->thumbDestination);
$thumb->setSuffix($this->suffix);
$thumb->create();
$messages = $thumb->getMessages();
$this->messages = array_merge($this->messages, $messages);
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add a message only if the original image is not deleted
if (!$this->deleteOriginal) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
}
// create a thumbnail from the uploaded image
$this->createThumbnail($this->destination . $filename);
// delete the uploaded image if required
if ($this->deleteOriginal) {
unlink($this->destination . $filename);
}
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
Class Upload
<?php
namespace PhotoProject;
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $renameDuplicates;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
public function __construct($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->destination = $path;
}
public function setMaxSize($num) {
if (is_numeric($num) && $num > 0) {
$this->max = (int) $num;
}
}
public function allowAllTypes() {
$this->typeCheckingOn = false;
if (!$suffix) {
$this->suffix = ''; // empty string
}
}
public function upload($renameDuplicates = true) {
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
// deal with multiple uploads
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
}
public function getMessages() {
return $this->messages;
}
public function collectFilenames() {
return $this->collectednames;
}
public function getMaxSize() {
return number_format($this->max/1024, 1) . ' KB';
}
protected function checkFile($file) {
$accept = true;
if ($file['error'] != 0) {
$this->getErrorMessage($file);
// stop checking if no file submitted
if ($file['error'] == 4) {
return false;
} else {
$accept = false;
}
}
if (!$this->checkSize($file)) {
$accept = false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
$accept = false;
}
}
if ($accept) {
$this->checkName($file);
}
return $accept;
return true;
}
protected function checkName($file) {
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$extension = pathinfo($nospaces, PATHINFO_EXTENSION);
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
// rename file
$basename = pathinfo($name, PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
do {
$this->newName = $basename . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
} while (in_array($this->newName, $existing));
}
}
}
protected function getErrorMessage($file) {
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
$this->getMaxSize() . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially
uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' .
$file['name'];
break;
}
}
protected function checkSize($file) {
if ($file['error'] == 1 || $file['error'] == 2 ) {
return false;
} elseif ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is an empty file.';
return false;
} elseif ($file['size'] > $this->max) {
$this->messages[] = $file['name'] . ' exceeds the maximum size
for a file (' . $this->getMaxSize() . ').';
return false;
} else {
return true;
}
}
protected function checkType($file) {
if (in_array($file['type'], $this->permitted)) {
return true;
} else {
if (!empty($file['type'])) {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add the amended filename to the array of uploaded files
$this->filenames[] = $filename;
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}

PHP uploading files using <input> multiple Attribute

I'm currently having several <input type="file" fields for uploading images. I want to convert the input fields to one single field using the html multiple attribute.
My working code with multiple input fields:
<input type="file" name="popup_images_1">
<input type="file" name="popup_images_2">
<input type="file" name="popup_images_3">...
for ($i = 1; $i <= 3; $i++) {
if (is_uploaded_file($_FILES['popup_images_' . $i]['tmp_name'])) {
$products_image = new upload('popup_images_' . $i);
$products_image->set_destination(DIR_FS_CATALOG_IMAGES);
if ($products_image->parse() && $products_image->save()) {
$products_image_name = $products_image->filename;
// do database stuff
}
}
}
My new code, which is not working, with a single input field:
<input type="file" name="popup_images[]" multiple="multiple">
$num_files = count($HTTP_POST_FILES['popup_images']['tmp_name']);
for ($i = 1; $i <= $num_files; $i++) {
if (is_uploaded_file($HTTP_POST_FILES['popup_images']['tmp_name'][$i])) {
$products_image = new upload('popup_images' . $i);
$products_image->set_destination(DIR_FS_CATALOG_IMAGES);
if ($products_image->parse() && $products_image->save()) {
$products_image_name = $products_image->filename;
// do database stuff
}
}
}
Things seems to go wrong at the line where new upload('popup_images' . $i) is set. Any ideas?
This is the upload class:
class upload {
var $file, $filename, $destination, $permissions, $extensions, $tmp_filename, $message_location;
function upload($file = '', $destination = '', $permissions = '777', $extensions = '') {
$this->set_file($file);
$this->set_destination($destination);
$this->set_permissions($permissions);
$this->set_extensions($extensions);
$this->set_output_messages('direct');
if (tep_not_null($this->file) && tep_not_null($this->destination)) {
$this->set_output_messages('session');
if ( ($this->parse() == true) && ($this->save() == true) ) {
return true;
} else {
return false;
}
}
}
function parse() {
global $HTTP_POST_FILES, $messageStack;
$file = array();
if (isset($_FILES[$this->file])) {
$file = array('name' => $_FILES[$this->file]['name'],
'type' => $_FILES[$this->file]['type'],
'size' => $_FILES[$this->file]['size'],
'tmp_name' => $_FILES[$this->file]['tmp_name']);
} elseif (isset($HTTP_POST_FILES[$this->file])) {
$file = array('name' => $HTTP_POST_FILES[$this->file]['name'],
'type' => $HTTP_POST_FILES[$this->file]['type'],
'size' => $HTTP_POST_FILES[$this->file]['size'],
'tmp_name' => $HTTP_POST_FILES[$this->file]['tmp_name']);
}
if ( tep_not_null($file['tmp_name']) && ($file['tmp_name'] != 'none') && is_uploaded_file($file['tmp_name']) ) {
if (sizeof($this->extensions) > 0) {
if (!in_array(strtolower(substr($file['name'], strrpos($file['name'], '.')+1)), $this->extensions)) {
if ($this->message_location == 'direct') {
$messageStack->add(ERROR_FILETYPE_NOT_ALLOWED, 'error');
} else {
$messageStack->add_session(ERROR_FILETYPE_NOT_ALLOWED, 'error');
}
return false;
}
}
$this->set_file($file);
$this->set_filename($file['name']);
$this->set_tmp_filename($file['tmp_name']);
return $this->check_destination();
} else {
if ($this->message_location == 'direct') {
$messageStack->add(WARNING_NO_FILE_UPLOADED, 'warning');
} else {
$messageStack->add_session(WARNING_NO_FILE_UPLOADED, 'warning');
}
return false;
}
}
function save() {
global $messageStack;
if (substr($this->destination, -1) != '/') $this->destination .= '/';
if (move_uploaded_file($this->file['tmp_name'], $this->destination . $this->filename)) {
chmod($this->destination . $this->filename, $this->permissions);
if ($this->message_location == 'direct') {
$messageStack->add(SUCCESS_FILE_SAVED_SUCCESSFULLY, 'success');
} else {
$messageStack->add_session(SUCCESS_FILE_SAVED_SUCCESSFULLY, 'success');
}
return true;
} else {
if ($this->message_location == 'direct') {
$messageStack->add(ERROR_FILE_NOT_SAVED, 'error');
} else {
$messageStack->add_session(ERROR_FILE_NOT_SAVED, 'error');
}
return false;
}
}

Opencart product import image is not working

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));
}
}

Categories