Jump to content

Generate tree directory for Fancytree


Go to solution Solved by ScottMeyer,

Recommended Posts

Hello,

I am using Fancytree, I want to generate a file / folder tree but excluding all folders that are not from the current user.

Example:
BOLD= FOLDER

I want to create a tree structure with the user "Peter"

[Tree]
├─PERSONNAL (take)
│ ├─PAN (not take)
│ │   └─GAMES (not take)
│ │      └─list (not take)
│ └─PETER (take)
│      └─GUITAR (take)
│           └─tabs (take)
└─TEAM (take)
     ├─CONTACT (take)
     │      └─phone (take)
     └─INFORMATION (take)
             └─technique (take)

I have several problems:
1) I don't understand the "listFolders" function, I can't give it a parameter (like $ name_user) otherwise it doesn't work.
2) the lines >> print_r ('TAKE THIS'. $ Dir); << show what I want to take, but it is "foreach" which does not work
3) my code is duplicated because I can't create a function inside a function ...

Here is my code:

<?php
$name_user = 'Peter'; // actualy not user :-( 
print_r(listFolders());

function listFolders($dir = __DIR__ . '/datausers') {
    $dh = scandir($dir);
    $name_user = "Peter";
    $return = [];

    if (strpos($dir, "/datausers/PERSONNAL") !== false){ // PERSONNAL found !
        if ($dir === __DIR__ . '/datausers/PERSONNAL') {  
            print_r($dir);
            echo '</br>';

            foreach ($dh as $item) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir . '/' . $item)) { // it's a folder
                        $return[] = array(
                            'title' => $item,
                            'folder' => true,
                            'expanded'=> true,
                            'children' => listFolders($dir . '/' . $item, $key)
                        );
                    } else { // it's a file
                        $return[] = [
                            'title' => $item,
                        ];
                    }
                }
            }
        }
        if (strpos($dir, "/datausers/PERSONNAL/" . $name_user) !== false){ // Peter found
            print_r($dir);
            echo '</br>';

            foreach ($dh as $item) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir . '/' . $item)) { // it's a folder
                        $return[] = array(
                            'title' => $item,
                            'folder' => true,
                            'expanded'=> true,
                            'children' => listFolders($dir . '/' . $item, $key)
                        );
                    } else { // it's a file
                        $return[] = [
                            'title' => $item,
                        ];
                    }
                }
            }
        }
    } 
    else {
        print_r($dir);
        echo '</br>';

        foreach ($dh as $item) {
            if ($item != '.' && $item != '..') {
                if (is_dir($dir . '/' . $item)) { // it's a folder
                    $return[] = array(
                        'title' => $item,
                        'folder' => true,
                        'expanded'=> true,
                        'children' => listFolders($dir . '/' . $item, $key)
                    );
                } else { // it's a file
                    $return[] = [
                        'title' => $item,
                    ];
                }
            }
        }
    }
    return $return;
}
?>

Please help me I'm desperate ...

Edited by ScottMeyer
Link to comment
https://forums.phpfreaks.com/topic/313052-generate-tree-directory-for-fancytree/
Share on other sites

hi, thank you for your answer.

I am using a POST AJAX request to find out the name of the user. This part works, here the ajax request is simulate with "$name_user".

I would have liked to do:

$user_name = "Peter";
echo json_encode (listFolders ($user_name));
function listFolders ($path_user, $dir = __DIR__. '/datausers') {

i compare, if $_SESSION['username'] = $name_user for sécurity
The goal is to use as return with "echo json_encode (listFolders ());" to put in Fancytree.

Edited by ScottMeyer

I give you my original code. it is currently returning all folders and files.

<?php
if(session_status() != 2) {	session_start(); } else { header('Location: deco.php'); } // (2 = session active) if don't active session
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {header('Location: deco.php');} // redirection si pas de session ouverte
if (time() > $_SESSION['expire']) {
    session_destroy();
    header('Location: deco.php');
}
$e1 = isset($_POST['e1']) ? $_POST['e1'] : null;
$e2 = isset($_POST['e2']) ? $_POST['e2'] : null;
if (empty($e1) || empty($e2)) {
    $return_data['key1'] = 'error';
    echo json_encode($return_data);
    return;
}

if ($e1 == 'read'){
    $e2 = str_replace('<','',$e2); // just for prevent html injection
    $e2 = str_replace('?','',$e2); // just for prevent php injection
    $return_data['key1'] = 'read';
    $return_data['key2'] = $e2;
    echo json_encode($return_data);
    return;

    $e2 = str_replace('}','',$e2); 
    $e2 = str_replace('"','',$e2); 
    $e2 = explode(":", $e2);        // take only name node 
}

if ($e1 == 'tree'){ 
    if ($_SESSION['username'] !== $e2){ // verification right name user
        $return_data['key1'] = 'error';
        $return_data['key2'] = ' tree authentication problem';
        echo json_encode($return_data);
        return;
    }
    echo json_encode(listFolders()); // here i want put $e2 = name user
    return ;
}

function listFolders($dir = __DIR__ . '/datausers_tmp/tree_ckeditor') {
    $dh = scandir($dir);
    $return = [];
    
    foreach ($dh as $folder) {
        if ($folder != '.' && $folder != '..') {
            $Folder_data = "/datausers/tree_ckeditor";
            
            if (is_dir($dir . '/' . $folder)) { // it's a folder
                $return[] = array(
                    'title' => $folder,
                    'folder' => true,
                    'expanded'=> true,
                    'children' => listFolders($dir . '/' . $folder, $key)
                );
            } else { // it's a file
                $return[] = [
                    'title' => $folder,
                    'title' => $folder,
                ];
            }
        }
    }
    return $return;
}
?>

currently the best result gives me this, with code in my firts post :

/volume1/web/allforone/datausers
/volume1/web/allforone/datausers/PERSONNAL
/volume1/web/allforone/datausers/PERSONNAL/Peter
/volume1/web/allforone/datausers/PERSONNAL/Peter/guitar
/volume1/web/allforone/datausers/TEAM
/volume1/web/allforone/datausers/TEAM/contact
/volume1/web/allforone/datausers/TEAM/information
Array ( [0] => Array ( [title] => PERSONNAL [folder] => 1 [expanded] => 1 [children] => Array ( [0] => Array ( [title] => Pan [folder] => 1 [expanded] => 1 [children] => Array ( ) ) [1] => Array ( [title] => Peter [folder] => 1 [expanded] => 1 [children] => Array ( [0] => Array ( [title] => guitar [folder] => 1 [expanded] => 1 [children] => Array ( [0] => Array ( [title] => tabs ) ) ) ) ) ) ) [1] => Array ( [title] => TEAM [folder] => 1 [expanded] => 1 [children] => Array ( [0] => Array ( [title] => contact [folder] => 1 [expanded] => 1 [children] => Array ( [0] => Array ( [title] => Phone ) ) ) [1] => Array ( [title] => information [folder] => 1 [expanded] => 1 [children] => Array ( [0] => Array ( [title] => technique ) ) ) ) ) ) 

 

Edited by ScottMeyer

ok now it almost works. My output (checked with http://jsonviewer.stack.hu/ - click to expand all)

[{"title":"PERSONNAL","folder":true,"expanded":true,"children":[{"title":"Peter","folder":true,"expanded":true,"children":[{"title":"guitar","folder":true,"expanded":true,"children":[{"title":"tabs"}]}]}]},{"title":"TEAM","folder":true,"expanded":true,"children":[{"title":"contact","folder":true,"expanded":true,"children":[{"title":"Phone"}]},{"title":"information","folder":true,"expanded":true,"children":[{"title":"technique"}]}]}]

I added this line to take that one user:
if ($ item === $name_user) {// Take only a user

now, how to give in the function the variable $name_user and avoid repetitions ?

my last code : 

<?php
$name_user = 'Peter'; // currently not used :-( 
echo json_encode(listFolders());

function listFolders($dir = __DIR__ . '/datausers') {
    $dh = scandir($dir);
    $name_user = "Peter";
    $return = [];

    if (strpos($dir, "/datausers/PERSONNAL") !== false){ // PERSONNAL found !
        if ($dir === __DIR__ . '/datausers/PERSONNAL') {  
            foreach ($dh as $item) {
                if ($item != '.' && $item != '..') {
                    if ($item === $name_user){ // Take only a user
                        if (is_dir($dir . '/' . $item)) { // it's a folder
                            $return[] = array(
                                'title' => $item,
                                'folder' => true,
                                'expanded'=> true,
                                'children' => listFolders($dir . '/' . $item, $key)
                            );
                        } else { // it's a file
                            $return[] = [
                                'title' => $item,
                            ];
                        }
                    }
                }
            }
        }

        if (strpos($dir, "/datausers/PERSONNAL/" . $name_user) !== false){ // Peter found
            foreach ($dh as $item) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir . '/' . $item)) { // it's a folder
                        $return[] = array(
                            'title' => $item,
                            'folder' => true,
                            'expanded'=> true,
                            'children' => listFolders($dir . '/' . $item, $key)
                        );
                    } else { // it's a file
                        $return[] = [
                            'title' => $item,
                        ];
                    }
                }
            }
        }
    } 
    else {
        foreach ($dh as $item) {
            if ($item != '.' && $item != '..') {
                if (is_dir($dir . '/' . $item)) { // it's a folder
                    $return[] = array(
                        'title' => $item,
                        'folder' => true,
                        'expanded'=> true,
                        'children' => listFolders($dir . '/' . $item, $key)
                    );
                } else { // it's a file
                    $return[] = [
                        'title' => $item,
                    ];
                }
            }
        }
    }
    return $return;
}
?>

 

Edited by ScottMeyer
  • Solution

Ok I found the solution.
It's crazy I spent the day yesterday on this problem.
and today I finally find the solution. Thank you requinix for answering me.

I put here my solution (not perfect) but it works.

<?php
if(session_status() != 2) {	session_start(); } else { header('Location: deco.php'); } // (2 = session active) if don't active session
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {header('Location: deco.php');} // redirection si pas de session ouverte
if (time() > $_SESSION['expire']) {
    session_destroy();
    header('Location: deco.php');
}
$e1 = isset($_POST['e1']) ? $_POST['e1'] : null;
$e2 = isset($_POST['e2']) ? $_POST['e2'] : null;
if (empty($e1) || empty($e2)) {
    $return_data['key1'] = 'error';
    echo json_encode($return_data);
    return;
}

if ($e1 == 'read'){
    $e2 = str_replace('<','',$e2); // just for prevent html injection
    $e2 = str_replace('?','',$e2); // just for prevent php injection
    $return_data['key1'] = 'read';
    $return_data['key2'] = $e2;
    echo json_encode($return_data);
    return;

    $e2 = str_replace('}','',$e2); 
    $e2 = str_replace('"','',$e2); 
    $e2 = explode(":", $e2);        // take only name node 
}

if ($e1 == 'tree'){ 
    if ($_SESSION['username'] !== $e2){ // verification right name user
        $return_data['key1'] = 'error';
        $return_data['key2'] = ' tree authentication problem';
        echo json_encode($return_data);
        return;
    }
    echo json_encode(listFolders($e2, __DIR__ . '/datausers')); // $e2 = name user
    return ;
}

function listFolders($path_user, $dir) {
    $dh = scandir($dir);
    $name_user = $path_user;
    $return_data = [];

    if (strpos($dir, "/datausers/PERSONNAL") !== false){ // PERSONNAL found !
        if ($dir === __DIR__ . '/datausers/PERSONNAL') {  
            foreach ($dh as $item) {
                if ($item != '.' && $item != '..') {
                    if ($item === $name_user){ // Take only a user
                        if (is_dir($dir . '/' . $item)) { // it's a folder
                            $return_data[] = array(
                                'title' => $item,
                                'folder' => true,
                                'expanded'=> true,
                                'children' => listFolders($name_user, $dir . '/' . $item, $key) 
                            );
                        } else { // it's a file
                            $return_data[] = [
                                'title' => $item,
                            ];
                        }
                    }
                }
            }
        }

        if (strpos($dir, "/datausers/PERSONNAL/" . $name_user) !== false){ // Peter found
            foreach ($dh as $item) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir . '/' . $item)) { // it's a folder
                        $return_data[] = array(
                            'title' => $item,
                            'folder' => true,
                            'expanded'=> true,
                            'children' => listFolders($name_user, $dir . '/' . $item, $key) 
                        );
                    } else { // it's a file
                        $return_data[] = [
                            'title' => $item,
                        ];
                    }
                }
            }
        }
    } 
    else {
        foreach ($dh as $item) {
            if ($item != '.' && $item != '..') {
                if (is_dir($dir . '/' . $item)) { // it's a folder
                    $return_data[] = array(
                        'title' => $item,
                        'folder' => true,
                        'expanded'=> true,
                        'children' => listFolders($name_user, $dir . '/' . $item, $key)
                    );
                } else { // it's a file
                    $return_data[] = [
                        'title' => $item,
                    ];
                }
            }
        }
    }
    return $return_data;
}
?>

 

Edited by ScottMeyer

Otherwise build a tree structure with a different directory level and a filter of the directories to be taken.
if it can help someone :)

Root
--Admin [here PHP script]
--Datauser [here tree structure to take]

$e2 = "name folder";
$path_array = explode('/', __DIR__); // put path to array
$path_shortcut_array = array_slice($path_array,0,(count($path_array)-1)); // rebuild array path without the last 
$path_base_string = implode("/", $path_shortcut_array); // rebuild with '/'

echo json_encode(listFolders($e2, $path_base_string . '/datausers')); // $e2 = name user

function listFolders($path_user, $dir) {
    $dh = scandir($dir);
    $name_user = $path_user;
    $return_data = [];

    if (strpos($dir, "/datausers/PERSONNAL") !== false){ // PERSONNAL found !
        $path_array = explode('/', __DIR__);
        $path_shortcut_array = array_slice($path_array,0,(count($path_array)-1));
        $path_base_string = implode("/", $path_shortcut_array);
        
        if ($dir === $path_base_string . '/datausers/PERSONNAL') {  
            foreach ($dh as $item) {
                if ($item != '.' && $item != '..') {
                    if ($item === $name_user){ // Take only a user
                        if (is_dir($dir . '/' . $item)) { // it's a folder
                            $return_data[] = array(
                                'title' => $item,
                                'folder' => true,
                                'expanded'=> true,
                                'children' => listFolders($name_user, $dir . '/' . $item, $key) 
                            );
                        } 
                    }
                }
            }
        }

        if (strpos($dir, "/datausers/PERSONNAL/" . $name_user) !== false){ // user found
            foreach ($dh as $item) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir . '/' . $item)) { // it's a folder
                        $return_data[] = array(
                            'title' => $item,
                            'folder' => true,
                            'expanded'=> true,
                            'children' => listFolders($name_user, $dir . '/' . $item, $key) 
                        );
                    } else { // it's a file
                        $return_data[] = [
                            'title' => $item,
                        ];
                    }
                }
            }
        }
    } 
    else {
        foreach ($dh as $item) {
            if ($item != '.' && $item != '..') {
                if (is_dir($dir . '/' . $item)) { // it's a folder
                    $return_data[] = array(
                        'title' => $item,
                        'folder' => true,
                        'expanded'=> true,
                        'children' => listFolders($name_user, $dir . '/' . $item, $key)
                    );
                } else { // it's a file
                    $return_data[] = [
                        'title' => $item,
                    ];
                }
            }
        }
    }
    return $return_data;
}


 

On 7/7/2021 at 3:34 AM, ScottMeyer said:
<?php
if(session_status() != 2) {	session_start(); } else { header('Location: deco.php'); } // (2 = session active) if don't active session
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {header('Location: deco.php');} // redirection si pas de session ouverte
if (time() > $_SESSION['expire']) {
    session_destroy();
    header('Location: deco.php');
}

On an unrelated note, if you're trying to redirect a user away because they do not have permission to access the page, you need to exit; after your call to header() otherwise the script will keep going and still do whatever it is they are not supposed to be doing.

 

On a more related note, you code could probably be cleaned up a lot if you switched to using RecursiveDirectoryIterator / RecursiveFilterIteratorFor example:

<?php

class PrefixFilter extends RecursiveFilterIterator {
    private $prefixList;

    public function __construct(RecursiveIterator $iterator, array $prefixList){
        parent::__construct($iterator);
        $this->prefixList = $prefixList;
    }

    public function accept() : bool{
        /** @var SplFileInfo $current */
        $current = $this->current();
        $path = $current->getPathname();
        $path = strtr($path, '\\', '/');

        $pathLength = strlen($path);
        foreach ($this->prefixList as $prefix){
            $length = min(strlen($prefix), $pathLength);
            if (strncmp($path, $prefix, $length) === 0){
                return true;
            }
        }

        return false;
    }

    public function getChildren() : RecursiveFilterIterator{
        return new self($this->getInnerIterator()->getChildren(), $this->prefixList);
    }
}


header('Content-type: text/plain');
$root = './datausers';
$prefixList = [
  $root . '/TEAM',
  $root . '/PERSONAL/' . strtoupper($_GET['user'])
];

echo 'Found the following files for the selected user:', PHP_EOL;
$iter = new RecursiveDirectoryIterator($root);
$iter = new PrefixFilter($iter, $prefixList);
$iter = new RecursiveIteratorIterator($iter);
foreach ($iter as $item){
  if ($item->isDir() && $item->getFilename() === '.'){
    echo 'Directory: ', $item->getPath(), PHP_EOL;
  } else if ($item->isFile()){
    echo 'File: ', $item->getPathname(), PHP_EOL;
  }
}

The directory iterator takes care of scanning the directories and you can choose what you want/don't want with the filter class.  Here it's based on a simple prefix filter but you could make it more complex if needed.  Once all that's setup getting the list of files and folders is a simple foreach loop over the iterator.

 

Edited by kicken
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.