<?php

// to use this function to scan a directory and filter the results, write:
// $fileselection = scan_directory_recursively('directory', 'extension');
function scan_directory_recursively($directory, $filter=FALSE) {
    // if the path has a slash at the end we remove it here
    if (substr($directory, -1) == '/') {
        $directory = substr($directory, 0, -1);
    }

    // if the path is not valid or is not a directory ...
    if (!file_exists($directory) || !is_dir($directory)) {
        // ... we return false and exit the function
        return FALSE;

        // ... else if the path is readable
    } elseif (is_readable($directory)) {
        // we open the directory
        $directory_list = opendir($directory);

        // and scan through the items inside
        while (FALSE !== ($file = readdir($directory_list))) {
            // if the filepointer is not the current directory
            // or the parent directory
            if ($file != '.' && $file != '..') {
                // we build the new path to scan
                $path = $directory . '/' . $file;

                // if the path is readable
                if (is_readable($path)) {
                    // we split the new path by directories
                    $subdirectories = explode('/', $path);

                    // if the new path is a directory
                    if (is_dir($path)) {
                        // add the directory details to the file list
                        $directory_tree[] = array(
                            'path' => $path,
                            'name' => end($subdirectories),
                            'kind' => 'directory',
                            // we scan the new path by calling this function
                            'content' => scan_directory_recursively($path, $filter));

                        // if the new path is a file
                    } elseif (is_file($path)) {
                        // get the file extension by taking everything after the last dot
                        $extension = end(explode('.', end($subdirectories)));

                        // if there is no filter set or the filter is set and matches
                        if ($filter === FALSE || $filter == $extension) {
                            // add the file details to the file list
                            $directory_tree[] = array(
                                'path' => $path,
                                'name' => end($subdirectories),
                                'extension' => $extension,
                                'size' => filesize($path),
                                'kind' => 'file');
                        }
                    }
                }
            }
        }
        // close the directory
        closedir($directory_list);

        // return file list
        return $directory_tree;

        // if the path is not readable ...
    } else {
        // ... we return false
        return FALSE;
    }
}

// ------------------------------------------------------------
function scanDirectories($rootDir, $allowext, $allData=array()) {
    $dirContent = scandir($rootDir);
    foreach ($dirContent as $key => $content) {
        $path = $rootDir . '/' . $content;
        $ext = substr($content, strrpos($content, '.') + 1);

        if (in_array($ext, $allowext)) {
            if (is_file($path) && is_readable($path)) {
                $allData[] = $path;
            } elseif (is_dir($path) && is_readable($path)) {
                // recursive callback to open new directory
                $allData = scanDirectories($path, $allData);
            }
        }
    }
    return $allData;
}

// ------------------------------------------------------------
#http://forums.tizag.com/showthread.php?p=50393&posted=1#post50393
#Thanks
function replace_in_file($file, $search_var, $replace) {
    $data = file($file);
    $new_data = array();
    $found = false;
    foreach ($data AS $line) {
        if (strstr($line, $search_var)) {
            $new_data[] = str_replace($line, $search_var . ' = "' . $replace . '";' . "\n", $line);
            $found = true;
        } else {
            $new_data[] = $line;
        }
    }

    if (!$found) {
        return 2;
    }

    $data_set = implode("", $new_data);
    $fo = fopen($file, 'w');
    if (!$fo) {
        return 3;
    }
    fwrite($fo, $data_set);
    fclose($fo);
    return 1;
}

// ------------------------------------------------------------
##http://www.dynamicdrive.com/forums/showthread.php?t=11054
function replaceLineInTextFile($file, $pattern, $replacement) {
    if (!file_exists($file)) { // if file doesn't exist...
        print "The specified file doesn't seem to exist."; // ...stop executing code.
    } else { // if file exists...
        $f = file($file); // ...make new variable...
        $content; // ...and another...

        for ($i = 0; $i < count($f); $i++) { // ...run through the loop...
            if (preg_match($pattern, $f[$i])) { // and
                $content .= $replacement . ""; // get
            } else { // the
                $content .= $f[$i]; // content.
            }
        }
        $fi = fopen($file, "w"); // open specified file...
        fwrite($fi, $content); // and rewrite it's content.
        fclose($fi); // close file.
    }
}

// ------------------------------------------------------------
#http://www.codewalkers.com/c/a/File-Manipulation-Code/delete-lines-from-a-file/
#DeadlySin3
function cutline($filename, $line_no=-1) {

    $strip_return = FALSE;

    $data = file($filename);
    $pipe = fopen($filename, 'w');
    $size = count($data);

    if ($line_no == -1)
        $skip = $size - 1;
    else
        $skip=$line_no - 1;

    for ($line = 0; $line < $size; $line++)
        if ($line != $skip)
            fputs($pipe, $data[$line]);
        else
            $strip_return=TRUE;

    return $strip_return;
}

// ------------------------------------------------------------

function registerUser($user, $pass1, $pass2) {
    $errorText = '';

    // Check passwords
    if ($pass1 != $pass2)
        $errorText = "Passwords are not identical!";
    elseif (strlen($pass1) < 6)
        $errorText = "Password is to short!";

    // Check user existance	
    if (!file_exists('../data/' . md5($user . '%poop%') . '.php')) {
        $oFH = fopen('../data/' . md5($user . '%poop%') . '.php', 'w') or die("cannot create password file!");
        fclose($oFH);
    }

    $pfile = fopen('../data/' . md5($user . '%poop%') . '.php', "r+");
    rewind($pfile);

    while (!feof($pfile)) {
        $Zline = fgets($pfile);
        $tmp = explode(':', $Zline);
        if ($tmp[0] == $user) {
            $errorText = "The selected user name is taken!";
            break;
        }
    }

    // If everything is OK -> store user data
    if ($errorText == '') {
        // Secure password string
        $userpass = md5($pass1 . '%salt%');

        fwrite($pfile, "\r\n$user:$userpass");
    }

    fclose($pfile);


    return $errorText;
}

///--------
function loginUser($user, $pass) {
    $errorText = '';
    $validUser = false;

    // Check user existance	
    $pfile = fopen("./data/" . md5($user . '%poop%') . ".php", "r");
    rewind($pfile);

    while (!feof($pfile)) {
        $Zline = fgets($pfile);
        $tmp = explode(':', $Zline);
        if ($tmp[0] == $user) {
            // User exists, check password
            if (trim($tmp[1]) == trim(md5($pass . '%salt%'))) {
                $validUser = true;
                $_SESSION['userName'] = $user;
            }
            break;
        }
    }
    fclose($pfile);

    if ($validUser != true)
        $errorText = "Invalid username or password!";

    if ($validUser == true)
        $_SESSION['validUser'] = true;
    else
        $_SESSION['validUser'] = false;

    return $errorText;
}

function logoutUser() {
    unset($_SESSION['validUser']);
    unset($_SESSION['userName']);
}

function checkUser() {
    if ((!isset($_SESSION['validUser'])) || ($_SESSION['validUser'] != true)) {
        header('Location: login.php');
    }
}

//----------------------
function files_deep($dir, $ext, $showDir = true) {
    $newItems = array();
    $items = scandir($dir);
    foreach ($items as $i) {
        if (is_dir($dir . $i) && $i != '.' && $i != '..') {
            $newItems = array_merge(files_deep($dir . $i . '/', $ext, $showDir), $newItems);
        } else {
            if (substr($i, strlen($ext) * -1) == $ext)
                $newItems[] = ($showDir == true) ? $dir . $i : $i;
        }
    }
    return $newItems;
}

//--------
?>