Joomla custom user extension - php

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

Related

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.

Associate customizationFile to a client_id

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.

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.

image upload error in php codeigniter [The upload path does not appear to be valid.]

I was using php codeigniter 2.x now i updated it to 3.x, after that my upload code is not working.
this is my code. please go though it.
when this code is working always getting the error
The upload path does not appear to be valid.
$this->load->library('upload');
$session = $this->ifisSession();
$uploadfolder = 'profileImgs';
$fullPath = 'abc';
$imageconfig['upload_path'] = $fullPath;
$imageconfig['max_size'] = (1024); // 1mb file size
$imageconfig['allowed_types'] = 'gif|jpg|png';
$imageconfig['max_width'] = (1024 );
$imageconfig['max_height'] = (1024);
$fieldName = 'profileimage';
//$uploadfilename = $_FILES[$fieldName];
$uploadfilename = $_FILES[$fieldName]['name'];
// printv($uploadfilename, 'this ihere');
$fileinfo = pathinfo($uploadfilename);
if (isset($fileinfo['extension'])) {
$ext = $fileinfo['extension'];
$imageconfig['file_name'] = $session['firstname'] . '_' . $session['user_id_pk'] . '_' . uniqid() . '.' . $ext;
}
$this->load->library('upload', $imageconfig);
if (!$this->upload->do_upload('profileimage')) {
$error = $this->upload->display_errors();
$data['data']['profileUpdate_error'] = $error;
// move to profile page with erro message
} else {
$profileUploadinfo = array('upload_data' => $this->upload->data());
$profileimgurl = '';
$res = $this->Model_userinfo->updateProfileImg($session['user_id_pk'], $profileimgurl);
if($res > 0){
$data['data']['profileUpdate_success'] = 'Profile Updated';
}else{
$data['data']['profileUpdate_error'] = 'Profile Not updated';
}
}

Saving Multiple File path to mysql using PHP

Good Day. I have a php script that move multiple file in my directory..
$filepath = 'uploads/';
if (isset($_FILES['file'])) {
$file_id = $_POST['file_id'];
$count = 0;
foreach($_FILES['file']['tmp_name'] as $k => $tmp_name){
$name = $_FILES['file']['name'][$k];
$size = $_FILES['file']['size'][$k];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array(strtolower($extension), $file_formats)) { // check it if it's a valid format or not
if ($size < (2048 * 1024)) { // check it if it's bigger than 2 mb or no
$filename = uniqid()."-00000-". $name;=
$tmp = $_FILES['file']['tmp_name'][$k];
if (move_uploaded_file($tmp_name, $filepath . $filename)) {
$id = $file_id;
$file_path_array = array();
$files_path = $filepath . $filename;
$file_extension = $extension;
foreach($file_name as $k_file_path => $v_file_path){
$file_path_array[] = $v_file_path;
}
foreach($file_extension as $k_file_extension){
$file_extension_array[] = $v_file_extension;
}
$file_path = json_encode($files_path);
$file_name = str_replace("\/", "/",$file_path);
var_dump($file_name);
$update = $mysqli->query("UPDATE detail SET file_path='$file_name' WHERE id='$id'");
} else {
echo "Could not move the file.";
}
} else {
echo "Your file is more than 2MB.";
}
} else {
echo "Invalid file format PLEASE CHECK YOU FILE EXTENSION.";
}
} else {
echo "Please select FILE";
}
}
exit();
}
this is my php script that move file to 'uploads/' directory and i want to save the path to my database. i try to dump the $file_name and this is my example path how to save that to my database.. ? any suggestions ?
NOTE: i already move the file to uploads/ directory and i only want to save the path to my database
string(46) "uploads/5638067602b48-00000-samplePDF.pdf"
string(46) "uploads/5638067602dee-00000-samplePDF1.pdf"
string(46) "uploads/5638067602f8d-00000-samplePDF2.pdf"
if you must store them in one field..
inside the loop
$file_name_for_db[]=$file_name;
outside the loop:
$update = $mysqli->query("UPDATE detail SET file_path='".json_encode($file_name_for_db)."' WHERE id='$id'");
there is serialize() instead of json_encode() if you prefer

Categories