Associate customizationFile to a client_id - php

I have override the ProductController.php controller so that the customer can integrate a PDF into his order.
protected function pictureUpload()
{
if (!($field_ids = $this->product->getCustomizationFieldIds()))
return false;
$authorized_file_fields = array();
foreach ($field_ids AS $field_id) {
if ($field_id['type'] == Product::CUSTOMIZE_FILE)
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file' . (int)$field_id['id_customization_field'];
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES AS $field_name => $file_doc) {
if (in_array($field_name, $authorized_file_fields) AND isset($file_doc['tmp_name']) AND !empty($file_doc['tmp_name'])) {
/*if ($_POST[$field_name.'_filename'] != '' ) {
$testName = $_POST[$field_name . '_filename'];
} else if (isset($_FILES[$field_name]['name'])){
$testName = $_FILES[$field_name]['name'];
} else if ($_FILES['file5'['name']] != ''){
$testName = 'totop';
}*/
// If there is an upload error, let the parent handle it
if ($file_doc['error'] != UPLOAD_ERR_OK)
continue;
// If the file is not allowed, let the parent handle it
if (!$this->isUploadTypeAllowed($file_doc))
continue;
// Unset the PDF to prevent the parent to handle this file
unset($_FILES[$field_name]);
// Create dir
mkdir(_PS_UPLOAD_DIR_ . ProductController::CUSTOMIZATION_FILE_DIR . '/' . $this->context->cart->id, 0777, true);
// Mark the file as a custom upload
$file_name = ProductController::CUSTOMIZATION_FILE_DIR . '/' . $this->context->cart->id . '/P' . md5(uniqid(rand(), true)) . '.pdf';
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if (!move_uploaded_file($file_doc['tmp_name'], $tmp_name)) {
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Copy file to the upload dir
if (!copy($tmp_name, _PS_UPLOAD_DIR_ . $file_name)) {
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Chmod the new file
if (!chmod(_PS_UPLOAD_DIR_ . $file_name, 0777)) {
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Create a fake thumb to avoid error on delete, this hack avoids lots of core method override
file_put_contents(_PS_UPLOAD_DIR_ . $file_name . '_small', '');
chmod(_PS_UPLOAD_DIR_ . $file_name . '_small', 0777);
// Register the file
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
// Parsing file
exec('/usr/bin/pdfinfo ' . _PS_UPLOAD_DIR_ . $file_name, $output);
$arrayValue = preg_grep('/\b(Pages)\b/i', $output);
$arrayKey = count($arrayValue) > 0 ? key($arrayValue) : false;
// Size file
$fileSize = fileSize(_PS_UPLOAD_DIR_ . $file_name);
// Name file
$nameFile = explode(".", $file_doc['name']);
$this->context->smarty->assign('customizationParsingFile', (int)substr($arrayValue[$arrayKey], -5));
$this->context->smarty->assign('customizationFileSize', $this->fileSizeUpload($fileSize));
$this->context->smarty->assign('customizationNameFile', $nameFile[0]);
// Remove tmp file
unlink($tmp_name);
}
}
return parent::pictureUpload();
}
I would like this PDF to be associated with the client. Do you have any idea how I could do that?
Thank you.

In Admin Order page you can get Cart ID associated with current Order.
Customization is associated with Cart ID (check Customization.php).
So from Cart ID you can get your Customization and the PDF of that customer.

Related

[PHP][SLIM] move_uploaded_file never ends with larger files in Hosting24

I have a question.
I'm trying to upload files to a server, this server is hosted by 'Hosting24', i don't know if that matters, anyway, if I try to move files larger than 70mb It never ends to load and never send a response, my server config is okay, it has these values: {"post_max_size":"512M","memory_limit":"1024M"}
I has tryed with $_FILES and ftp transfer and it doesnt works, it never ends of load.
I'm using Slim framework and this is the function:
public function testCode($request, $response, $args)
{
$data = $request->getParsedBody();
$uploadedFiles = $request->getUploadedFiles();
//here take files
$uploadedFile = $uploadedFiles['file_user'];
$nameC = $data['nombre_curso'];
//here set path
$path = "../../scorm/temp/" . $nameC . '/';
//Creating folders
if (!#mkdir($path, 0777, true)) {
$error = error_get_last();
echo $error['message'];
}
$file_name = $uploadedFile->getClientFilename();
$array = explode(".", $file_name);
$ext = $array[1];
//if is a zip file
if ($ext == 'zip') {
$location = $path . "/" . $file_name;
//here move the uploaded file to my selected directory
if (move_uploaded_file($uploadedFile->file, $location)) {
$obj = (object) array("response" => 'works', 'post_max_size' => ini_get('post_max_size'), 'memory_limit' => ini_get('memory_limit'));
$response->withStatus(200);
$response->getBody()->write(json_encode($obj));
return $response;
} else {
$error = error_get_last();
echo $error['message'] . " it couldn't be moved";
}
} else {
echo "no zip";
}
}

How to remove sanitize from Opencart downloads

I am developing a module for my client to upload and browse file in Opencart.
when I am uploading file from my back-end server I am getting the output as file.zip.xyzasdf. Where I just want to remove this .xyzasdf
Can any one suggest me how to remove sanitize from the following code...
public function upload() {
$this->load->language('catalog/download');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'catalog/download')) {
$json['error'] = $this->language->get('error_permission');
}
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) > 128)) {
$json['error'] = $this->language->get('error_filename');
}
// Allowed file extension types
$allowed = array();
$extension_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_ext_allowed'));
$filetypes = explode("\n", $extension_allowed);
foreach ($filetypes as $filetype) {
$allowed[] = trim($filetype);
}
if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Allowed file mime types
$allowed = array();
$mime_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_mime_allowed'));
$filetypes = explode("\n", $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');
}
// Check to see if any PHP files are trying to be uploaded
$content = file_get_contents($this->request->files['file']['tmp_name']);
if (preg_match('/\<\?php/i', $content)) {
$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) {
$file = $filename . '.' . token(32);
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_FOLDER . $file);
$json['filename'] = $file;
$json['mask'] = $filename;
$json['success'] = $this->language->get('text_upload');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Any help would be greatly appreciated...
Thanks
Removing the random string that is added to the filename is simple. Just change
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $file);
to:
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $filename);
But keep in mind that this will bring problems.
OpenCart saves the random string in the database at the time of file upload, so it will later use it to identify the file.
If you delete this feature, the uploaded files in the admin panel will not be available.

Count page PDF with Imagick (Prestashop)

I use Imagick to count the number of pages in my PDF which is uploaded by the client except that my var_dump does not return any results.
Here is my prestashop code from my ProductController.php controller for uploading files.
class ProductController extends ProductControllerCore
{
const CUSTOMIZATION_FILE_DIR = 'customizations';
protected function pictureUpload()
{
if (!($field_ids = $this->product->getCustomizationFieldIds()))
return false;
$authorized_file_fields = array();
foreach ($field_ids AS $field_id)
{
if ($field_id['type'] == Product::CUSTOMIZE_FILE)
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file' . (int)$field_id['id_customization_field'];
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES AS $field_name => $file)
{
if (in_array($field_name, $authorized_file_fields) AND isset($file['tmp_name']) AND !empty($file['tmp_name']))
{
// If there is an upload error, let the parent handle it
if ($file['error'] != UPLOAD_ERR_OK)
continue;
// If the file is not allowed, let the parent handle it
if (!$this->isUploadTypeAllowed($file))
continue;
// Unset the PDF to prevent the parent to handle this file
unset($_FILES[$field_name]);
// Create dir
mkdir(_PS_UPLOAD_DIR_ . ProductController::CUSTOMIZATION_FILE_DIR.'/'.$this->context->cart->id, 0777, true);
// Mark the file as a custom upload
$file_name = ProductController::CUSTOMIZATION_FILE_DIR.'/'.$this->context->cart->id.'/P'. md5(uniqid(rand(), true)).'.pdf';
$doc = exec("identify -format %n $file_name");
var_dump($doc);
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if (!move_uploaded_file($file['tmp_name'], $tmp_name))
{
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Copy file to the upload dir
if (!copy($tmp_name, _PS_UPLOAD_DIR_.$file_name))
{
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Chmod the new file
if (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777))
{
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Create a fake thumb to avoid error on delete, this hack avoids lots of core method override
file_put_contents(_PS_UPLOAD_DIR_ . $file_name . '_small', '');
chmod(_PS_UPLOAD_DIR_ . $file_name . '_small', 0777);
// Register the file
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
// Remove tmp file
unlink($tmp_name);
}
}
return parent::pictureUpload();
}
protected function isUploadTypeAllowed($file)
{
/* Detect mime content type */
$mime_type = false;
$types = array('application/pdf', 'application/zip'); // Extra mime types can be added here
if (function_exists('finfo_open'))
{
$finfo = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
}
elseif (function_exists('mime_content_type'))
{
$mime_type = mime_content_type($file['tmp_name']);
}
elseif (function_exists('exec'))
{
$mime_type = trim(exec('file -b --mime-type '.escapeshellarg($file['tmp_name'])));
}
if (empty($mime_type) || $mime_type == 'regular file')
{
$mime_type = $file['type'];
}
if (($pos = strpos($mime_type, ';')) !== false)
$mime_type = substr($mime_type, 0, $pos);
// is it allowed?
return $mime_type && in_array($mime_type, $types);
}
}
Thank you.

PHP file upload is creating filenames starting with "PHP" and with .tmp extension

I am using PHP (Symfony2) in my project which has image upload feature. Inside controller:
if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
$index=(int)$request->request->get('index');
$image_file = $request->files->get('shop_bundle_managementbundle_posttype')['images'][$index]['file'];
$image= new Image();
$image->setFile($image_file);
$image->setSubDir('hg');
$image->upload();
$em->persist($image);
$em->flush();
}
I use a class UploadFileMover that handle the file upload. I didn't write the following code but as I understand, an MD5 hash will be created from the original file name and used as filename. But the instance of UploadedFile contains a file name like "PHP"+number.tmp, not the original as stored in computer filesystem.
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath,$relativePath)
{
$originalName = $file->getFilename();
$targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
$targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
$ext = $file->getExtension();
$i=1;
while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
if ($ext) {
$prev = $i == 1 ? "" : $i;
$targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
} else {
$targetFilePath = $targetFilePath . $i++;
}
}
$targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
if (!is_dir($targetDir)) {
$ret = mkdir($targetDir, umask(), true);
if (!$ret) {
throw new \RuntimeException("Could not create target directory to move temporary file into.");
}
}
$file->move($targetDir, basename($targetFilePath));
return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
}
}
This class is instanciated when an image is uploaded. In other words, I have an Entity Image that has a method upload. Inside entity class:
public function upload()
{
if (null === $this->getFile()) {
return;
}
$uploadFileMover = new UploadFileMover();
$this->path = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDir(),$this->subDir);
$this->file = null;
}
I var_dumped the filename all across the different steps but I cannot figure out where it is transformed to PHP16653.tmp.
Can it be related to an APACHE related configuration? Your help is appreciated. I really did a lot of research for similar issue in the web to no avail.
The problem was created by the line:
$originalName = $file->getFilename();
Use:
$originalName = $file->getClientOriginalName();
instead.

Joomla custom user extension

I'm writing a Joomla 1.5 extension for an advanced frontend user interface.
Now I have to add a function so the users can upload a picture in the frontend and it will be added to their account.
Is there a standard Joomla picture upload available or something?
Thanks
I have this is my code: (and some more I can not paste everything in here)
function deleteLogo($logo)
{
// define path to file to delete
$filePath = 'images/stories/members/' . $logo;
$imagePath = 'images/stories/members/image/' . $image;
// check if files exists
$fileExists = JFile::exists($filePath);
$imageExists = JFile::exists($imagePath);
if($fileExists)
{
// attempt to delete file
$fileDeleted = JFile::delete($filePath);
}
if($imageExists)
{
// attempt to delete file
$fileDeleted = JFile::delete($imagePath);
}
}
function saveLogo($files, $data)
{
$uploadFile = JRequest::getVar('logo', null, 'FILES', 'ARRAY');
$uploadImage = JRequest::getVar('image', null, 'FILES', 'ARRAY');
$save = true;
$saveImage = true;
if (!is_array($uploadFile)) {
// #todo handle no upload present
$save = false;
}
if ($uploadFile['error'] || $uploadFile['size'] < 1) {
// #todo handle upload error
$save = false;
}
if (!is_uploaded_file($uploadFile['tmp_name'])) {
// #todo handle potential malicious attack
$save = false;
}
if (!is_array($uploadImage)) {
// #todo handle no upload present
$saveImage = false;
}
if ($uploadImage['error'] || $uploadImage['size'] < 1) {
// #todo handle upload error
$saveImage = false;
}
if (!is_uploaded_file($uploadImage['tmp_name'])) {
// #todo handle potential malicious attack
$saveImage = false;
}
// Prepare the temporary destination path
//$config = & JFactory::getConfig();
//$fileDestination = $config->getValue('config.tmp_path'). DS . JFile::getName($uploadFile['tmp_name']);
// Move uploaded file
if($save)
{
$this->deleteLogo($data['oldLogo']);
$fileDestination = 'images/stories/members/' . $data['id'] . '-' . $uploadFile['name'];
$uploaded = JFile::upload($uploadFile['tmp_name'], $fileDestination);
}
if($saveImage)
{
$this->deleteLogo($data['oldImage']);
$fileDestination = 'images/stories/members/image/' . $data['id'] . '-' . $uploadImage['name'];
$uploadedImage = JFile::upload($uploadImage['tmp_name'], $fileDestination);
}
}

Categories