I need to use jstree to display the directory structure of a ftp account's homedir.
I somehow got stuck at retrieving the full directory structure (and create a json object, xml file, html code, whatever). It is most likely something easy that is just slipping my mind, but anyway, here's what i tried so far:
function draw_tree($path)
{
global $con;
$list = ftp_nlist($con,$path);
$dirs = array(); $files = array();
foreach($list as $file)
{
if(ftp_is_dir($file))
{
$dir[] = array(
'attr' => array('data-path' => $path . '/' . $file,
'data' => $file,
'state' => 'closed',
'children' => // ??? some recursive function should
// probably go here
);
}
else {
$files[] = array(
'attr' => array('data-path' => $file)
);
}
}
return array_merge($dirs,$files);
}
Related
I'm trying to create an Admin Controller with a csv file uploader to process it like an array.
I can't find an efficient way to do it, I tried to use $this-> fields_form, but nothing is showing up.
Then I did a tpl file with an input file, called in initContent, but I don't know how to retrieve my file in the controller.
I need to create multiple object of different classes that I made, thanks to the csv file.
Does somebody have some documentation that could help me, I've already search through prestashop dev doc, stack overflow, ect but I've didn't see anything that could help me (maybe I didn't search the good way ?)
Waiting for your help guys !
Update :
Update :
Just found a way to upload my file, but it's upload as .tmp and can't be processed as a csv file, how can I convert a tmp file to a csv ?
Here is my code :
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_BULB_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_BULB_DATA'
),
),
'submit' => array('title' => $this->trans('Save', array(), 'Admin.Actions')),
),
);
if(isset($_FILES['DB_BULB_DATA'])){
$headers = fgetcsv(fopen($_FILES['DB_BULB_DATA']['tmp_name'], "r+"));
print_r($headers);
}
}
There is no file type name csvfile , you need to use filed type file and then hadel the csv file after upload, check file extension then process the data.
Just find out how to do it, I feel dummy 😅
I just needed to save my tmp file as a csv to be able to use it then.
Here is the full code :
<?php
class Admin<YourModuleName>Upload<YourThings>DatabaseController extends ModuleAdminController
{
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->name = "Admin<YourModuleName>Upload<YourThings>Database";
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_<YourThings>_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_<YourThings>_DATA'
),
),
'submit' => array('title' => $this->l('Save')),
),
);
}
public function initContent()
{
parent::initContent();
unset($_FILES);
}
public function postProcess()
{
$fileName = '<YourThings>Db.csv';
if (!file_exists(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName)) {
if (isset($_FILES['DB_<YourThings>_DATA'])) {
$tmpPath = $_FILES['DB_<YourThings>_DATA']["tmp_name"];
move_uploaded_file($tmpPath, _PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName);
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
} else {
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
unset($_FILES['DB_<YourThings>_DATA']);
}
}
I have this function to upload images to Amazon S3 and store the information about image inside my table "images".
Everything works perfectly on my localhost (uploads to amazon s3 and store the data inside table) and localhost has php 5.5.6, but on my webserver with PHP 5.5.2 I'm able to upload images to Amazon S3 but NOT inserting data into my table doing mass/bulk insertion:
/*
* HANDLES FILE UPLOAD
*/
public function fileUpload($user_id,$car_id) {
if (Input::hasFile('images')) {
# Initialize array for mass inserting into table
$insert = array();
# General info
date_default_timezone_set('America/Mexico_City');
$created_at = new DateTime;
$files = Input::file('images');
$main_img = Input::all()["image-upload"][0];
$countlimit = 0;
try {
foreach($files as $file) {
if($countlimit>=25 || in_array($file->guessClientExtension(), ['jpg','jpeg','png','gif'])==false) continue; $countlimit++;
# Image data
$image_id = mt_rand(1000000000,9999999999);
$extension= $file->guessClientExtension();
$filename = $user_id.'/'.$car_id.'/'.$image_id.".".$extension;
$path = $file->getRealPath();
$is_main = ($file->getClientOriginalName() == $main_img) ? 1 : NULL;
# UPLOAD TO AMAZON S3
$s3 = AWS::get('s3');
$obj = array(
'Bucket' => $_ENV['aws_bucket'],
'Key' => 'cars/'.$filename,
'SourceFile' => $path,
'ACL' => 'public-read',
);
$result = $s3->putObject($obj);
#ARRAY FOR STORING IMAGE DATA
$insert[] = array(
'car_id' => $car_id,
'image_id' => $image_id,
'image_extension' => $extension,
'is_main' => $is_main,
'url' => $filename, # $url, FOR IMGIX JUST STORE $FILENAME
'created_at' => $created_at
);
}
# Mass insertion
DB::table('images')->insert($insert);
} catch(Exception $e) { return false; }
return true;
} else {
return false;
}
}
Now when I try to mass insert to my database this way it doesn't store the images, curiously if I do a single query it works.
Other things I've tried are doing a query/insertion on each iteration but I get a 'Duplicate entry' error for the 'image_id'. What could it be? Thanks in advance
If you actually CATCH the exception that might be being thrown i.e. PDOException in your try/catch you may find some useful information that will allow you to identify the error all on your own.
I am assuming you have set PDO to throw exceptions
try {
foreach($files as $file) {
if($countlimit>=25 ||
in_array($file->guessClientExtension(), ['jpg','jpeg','png','gif'])==false)
continue;
$countlimit++;
# Image data
$image_id = mt_rand(1000000000,9999999999);
$extension= $file->guessClientExtension();
$filename = $user_id.'/'.$car_id.'/'.$image_id.".".$extension;
$path = $file->getRealPath();
$is_main = ($file->getClientOriginalName() == $main_img) ? 1 : NULL;
# UPLOAD TO AMAZON S3
$s3 = AWS::get('s3');
$obj = array(
'Bucket' => $_ENV['aws_bucket'],
'Key' => 'cars/'.$filename,
'SourceFile' => $path,
'ACL' => 'public-read',
);
$result = $s3->putObject($obj);
#ARRAY FOR STORING IMAGE DATA
$insert[] = array(
'car_id' => $car_id,
'image_id' => $image_id,
'image_extension' => $extension,
'is_main' => $is_main,
'url' => $filename, # $url, FOR IMGIX JUST STORE $FILENAME
'created_at' => $created_at
);
}
# Mass insertion
DB::table('images')->insert($insert);
}
// added catch of PDOException
catch(PDOException $e ) {
echo $e->getMessage();
}
catch(Exception $e) {
return false;
}
I am using elfinder and I have a problem. I want to get current directory in elfinder but I can not.
EDITED:
this is my connector. consist of my_function that called after upload, rename or mkdir commands and I want to get uploaded files path in specified place:
<?php
error_reporting(0); // Set E_ALL for debuging
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderConnector.class.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinder.class.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeDriver.class.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeLocalFileSystem.class.php';
function access($attr, $path, $data, $volume) {
return strpos(basename($path), '.') === 0 // if file/folder begins with '.' (dot)
? !($attr == 'read' || $attr == 'write') // set read+write to false, other (locked+hidden) set to true
: null; // else elFinder decide it itself
}
function my_function($cmd, $result, $args, $elfinder)
{
// how to get current path here?
}
$opts = array(
'bind' => array('upload rename mkdir' => 'my_function'),
// 'debug' => true,
'roots' => array(
array(
'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
'path' => '../files/', // path to files (REQUIRED)
'URL' => dirname($_SERVER['PHP_SELF']) . '/../files/', // URL to files (REQUIRED)
'accessControl' => 'access' // disable and hide dot starting files (OPTIONAL)
),
)
);
// run elFinder
$connector = new elFinderConnector(new elFinder($opts));
$connector->run();
You can get items URL.
function my_function($cmd, $result, $args, $elfinder)
{
// how to get current path here?
foreach ($result['added'] as $file) {
if (!empty($file['url']) && $file['url'] != 1) {
$url = $file['url'];
}
}
}
or Make inherent class ex elFinderVolumeMyLocalFileSystem
class elFinderVolumeMyLocalFileSystem extends elFinderVolumeLocalFileSystem
{
public function decode($hash) {
return parent::decode($hash);
}
}
function my_function($cmd, $result, $args, $elfinder)
{
// how to get current path here?
foreach ($result['added'] as $file) {
if ($volume = $elfinder->getVolume($file['hash'])) {
$dir = $volume->decode($file['phash']);
}
}
}
$opts = array(
'bind' => array('upload rename mkdir' => 'my_function'),
// 'debug' => true,
'roots' => array(
array(
'driver' => 'MyLocalFileSystem', // driver for accessing file system (REQUIRED)
'path' => '../files/', // path to files (REQUIRED)
'URL' => dirname($_SERVER['PHP_SELF']) . '/../files/', // URL to files (REQUIRED)
'accessControl' => 'access' // disable and hide dot starting files (OPTIONAL)
),
)
);
How to show the file upload name for jQuery Multiple File Upload Plugin v1.48?
After the users have uploaded the file, is there a way to show the file that they have uploaded under the profile?
1.if ( isset($_FILES['tb-documents']) ) {
$documents = $_FILES['tb-documents'];
foreach ( $documents['name'] as $key => $value ) {
if ( $documents['name'][$key]) {
$document = array(
'name' => $documents['name'][$key],
'type' => $documents['type'][$key],
'tmp_name' => $documents['tmp_name'][$key],
'error' => $documents['error'][$key],
'size' => $documents['size'][$key]
);
$status = wp_handle_upload($document, array('test_form' => false));
if( !isset($status['error']) ) {
$uploads = wp_upload_dir();
add_user_meta($user->ID, 'tb-documents', $uploads['url'].'/'.basename($status['file']));
}
}
}
}
The upload is working well on the user profile. However, I want to pull out the file name that they have uploaded and display all the uploaded file names to them.
Which variable should I use?
1.I tried this, $content .= '.$documents['name']'; but it doesn't work. It shows syntax error.
You have to combine results from this $documents['name'][$key] and show it to user.
For example:
if (isset($_FILES['tb-documents'])) {
$uploadedFiles = array();
$documents = $_FILES['tb-documents'];
foreach ($documents['name'] as $key => $value) {
if ($documents['name'][$key]) {
$document = array(
'name' => $documents['name'][$key],
'type' => $documents['type'][$key],
'tmp_name' => $documents['tmp_name'][$key],
'error' => $documents['error'][$key],
'size' => $documents['size'][$key]
);
$status = wp_handle_upload($document, array('test_form' => false));
if (!isset($status['error'])) {
$uploads = wp_upload_dir();
add_user_meta($user->ID, 'tb-documents', $uploads['url'] . '/' . basename($status['file']));
$uploadedFiles[] = $documents['name'][$key];
}
}
}
var_dump(implode(", ", $uploadedFiles));
}
If you want to show the uploaded files to the uploader, you can handle it easily in JQuery using the fileuploaddone callback provided by jQuery uploader
$('#fileupload')
.bind('fileuploaddone', function (e, data) {
console.log( data['result']['files'][0]['name'] );
console.log( data['result']['files'][0]['url'] );
});
If you have multiple files, you need to loop over data['result']['files'] array.
We have an application where in user can create his own webpages and host them.We are using S3 to store the pages as they are static.Here,as we have a limitation of 100 buckets per user,we decided to go with folders for each user inside a bucket.
Now,if a user wants to host his website on his domain,we ask him for the domain name(when he starts we publish it on our subdomain) and I have to rename the folder.
S3 being a flat file system I know there are actually no folders but just delimeter / separated values so I cannot go into the folder and check how many pages it contains.The API allows it one by one but for that we have to know the object names in the bucket.
I went through the docs and came across iterators,which I have not implemented yet.This uses guzzle of which I have no experience and facing challenges in implementing
Is there any other path I can take or I need to go this way.
You can create an iterator for the contents of a "folder" by doing the following:
$objects = $s3->getIterator('ListObjects', array(
'Bucket' => 'bucket-name',
'Prefix' => 'subfolder-name/',
'Delimiter' => '/',
));
foreach ($objects as $object) {
// Do things with each object
}
If you just need a count, you could this:
echo iterator_count($s3->getIterator('ListObjects', array(
'Bucket' => 'bucket-name',
'Prefix' => 'subfolder-name/',
'Delimiter' => '/',
)));
Bit of a learning curve with s3, eh? I spent about 2 hours and ended up with this codeigniter solution. I wrote a controller to loop over my known sub-folders.
function s3GetObjects($bucket) {
$CI =& get_instance();
$CI->load->library('aws_s3');
$prefix = $bucket.'/';
$objects = $CI->aws_s3->getIterator('ListObjects', array(
'Bucket' => $CI->config->item('s3_bucket'),
'Prefix' => $prefix,
'Delimiter' => '/',
));
foreach ($objects as $object) {
if ($object['Key'] == $prefix) continue;
echo $object['Key'].PHP_EOL;
if (!file_exists(FCPATH.$object['Key'])) {
try {
$r = $CI->aws_s3->getObject(array(
'Bucket' => $CI->config->item('s3_bucket'),
'Key' => $object['Key'],
'SaveAs' => FCPATH.$object['Key']
));
} catch (Exception $e) {
echo $e->getMessage().PHP_EOL;
//return FALSE;
}
echo PHP_EOL;
} else {
echo ' -- file exists'.PHP_EOL;
}
}
return TRUE;
}