<?php

class MyFilesScan2 {

    private $in_root;
    private $in_file;
    private $options = array('Что получаем: array', 
                             array('Поиск файла: false', 
                                   'Пропускать пустые строки: false'));    
      function __construct() { }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Сканирование файлов и папок в дер
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function File_list($dir, $bool) {

        $dir = $this -> dopRes($dir);

        $arr = array_diff(scandir($_SERVER['DOCUMENT_ROOT'].'/'.$dir), array('..', '.'));
        if ($bool=='is_dir') {
            foreach($arr as $k => $v){
                if(is_file($dir.$arr[$k])){
                    unset($arr[$k]);
                }
            }
            
        } elseif ($bool=='is_file') {
            foreach($arr as $k => $v){
                if(is_dir($dir.$arr[$k])){
                    unset($arr[$k]);
                }
            }
        }
        $arr = array_values($arr);
        return  $arr;
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Удаление файла
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function File_delit($fils, $all) {

        $fils = $this -> dopRes($fils);

        $fils = $_SERVER['DOCUMENT_ROOT'].'/'.$fils;
        if ($all == 'all') {
            if (file_exists($fils)) {
 
                foreach (glob($fils.'/*.php') as $file){
                    unlink($file);
                }
            } else {
            }
        } else {
            if (!unlink($fils)) {
                die('Не удалось удалить фаил.');
            }
        }
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Поиск и чтение файла
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function File_who($file, $arst, $options) {

        if ($arst == 'Что получаем: str') {

            if ($options[0] == 'Поиск файла: true') {

                return $file = file_get_contents($file, FILE_USE_INCLUDE_PATH);

            } 

            $file = self::dopRes($file); // удаление слеша
            $file = self::dopUrl($file); // получить поть от корня
            return $file = file_get_contents($file);
            
        } elseif ($arst == 'Что получаем: array') {

            if ($options[0] == 'Поиск файла: true' and 
                $options[1] == 'Пропускать пустые строки: true') {

                return $file = file($file, 
                    FILE_USE_INCLUDE_PATH | 
                    FILE_IGNORE_NEW_LINES | 
                    FILE_SKIP_EMPTY_LINES);

            } elseif ($options[0] == 'Поиск файла: false' and 
                      $options[1] == 'Пропускать пустые строки: true') {

                $file = self::dopRes($file); // удаление слеша
                $file = self::dopUrl($file); // получить поть от корня
                return $file = file($file, 
                    FILE_IGNORE_NEW_LINES | 
                    FILE_SKIP_EMPTY_LINES);

            } elseif ($options[0] == 'Поиск файла: true' and 
                      $options[1] == 'Пропускать пустые строки: false') {

                return $file = file($file, 
                    FILE_USE_INCLUDE_PATH | 
                    FILE_IGNORE_NEW_LINES);

            } elseif ($options[0] == 'Поиск файла: false' and 
                      $options[1] == 'Пропускать пустые строки: false') {
                
                $file = self::dopRes($file); // удаление слеша
                $file = self::dopUrl($file); // получить поть от корня
                return $file = file($file, FILE_IGNORE_NEW_LINES);
            }
        }
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// перезаписать файл
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function SetFile($file, $array)
    {
        $s = 1;

        foreach ($array as $value) {
            if ($s === 1) {
                file_put_contents($file, $value."\r\n");
                $s++;
            } else {
                file_put_contents($file, $value."\r\n", FILE_APPEND | LOCK_EX);
            }
        }
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// работа со строками
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // строка (найти, получить, заменить, добавить)
    public function JobFileStr($file, $content, $options = 'r', $array)
    {
        if ($array == false) $array = $this -> options;

        $this -> in_root = self::dopUrl(self::dopRes($file));
        $this -> in_file = self::File_who($file, $array[0], $array[1]);
        $this -> in_file_clon = $this -> in_file;

        //////////////////////////////
        // найти / получить строку
        //////////////////////////////
        $GetStr = function ($Search_str) {

            foreach ($this -> in_file as $key => $value) {

                if (is_string($Search_str) and $value == $Search_str) {
                    return array('строка' => $key, 'текст' => $value);
                }

                if (is_int($Search_str) and $key == $Search_str) {
                    return array('строка' => $key, 'текст' => $value);
                }
            }

            return false;
        };

        //////////////////////////////
        // заменить строку
        //////////////////////////////
        $SetStr = function ($Search_str) {

            foreach ($this -> in_file as $key => $value) {

                if (is_array($Search_str[1]) and is_int($Search_str[0]) and $key === $Search_str[0]) {
                    
                    unset($this -> in_file_clon[$key]);
                    array_splice($this -> in_file_clon, $Search_str[0], 0, $Search_str[1]);

                    self::SetFile($this -> in_root, $this -> in_file_clon);

                    return $this -> in_file_clon;

                } else {

                    if (is_string($Search_str[0]) and $value == $Search_str[0]) {

                        $this -> in_file_clon[$key] = $Search_str[1];
                        return array('строка' => $key, 'текст' => $value);
                    }

                    if (is_int($Search_str[0]) and $key == $Search_str[0]) {

                        $this -> in_file_clon[$key] = $Search_str[1];
                        return $this -> in_file_clon;
                    }
                }


            }

            return false;
        };

        //////////////////////////////
        // заменить строки
        //////////////////////////////
        $SetStrArr = function ($Search_str, $bool) {

            $i = 0;
            $array_old_str = array();

            foreach ($this -> in_file as $key => $value) {

                if (is_int($Search_str[0][0]) and is_int($Search_str[0][1]) and $key >= $Search_str[0][0]) {

                    if ($key == $Search_str[0][1]) {

                        if ($bool) {

                            $array_old_str[] = $this -> in_file_clon[$key];
                            self::dopCube($Search_str, $key, $i);
                            array_splice($this -> in_file_clon, $Search_str[0][0], 0, $Search_str[1]);

                        } elseif($bool === 'key') {

                            $array_old_str[$key] = $this -> in_file_clon[$key];

                        } else {

                            $array_old_str[] = $this -> in_file_clon[$key];
                        }

                        return array($this -> in_file_clon, $array_old_str);
                        exit();

                    } else {

                        if ($bool) {

                            $array_old_str[] = $this -> in_file_clon[$key];
                            self::dopCube($Search_str, $key, $i);

                        } elseif($bool === 'key') {

                            $array_old_str[$key] = $this -> in_file_clon[$key];

                        } else {

                            $array_old_str[] = $this -> in_file_clon[$key];
                        }
                    }
                }
            }

            return false;
        };


        if (is_writable($this -> in_root) and $options === 'r') {

            return $this -> in_file;
            exit();
        }

        if (is_writable($this -> in_root) and $options === 'a') {

            $count = count($this -> in_file_clon);

            array_splice($this -> in_file_clon, $count, 0, $content);
            return array($this -> in_file, $this -> in_file_clon);
            exit();
        }

        if (is_writable($this -> in_root) or $options === 'w') {

            // запись, содание, изменение
            if ($options === 'w') {

                if (is_array($content)) {

                    if (is_array($content[0]) and is_array($content[1])) {

                        return $SetStrArr($content, true);
                    }

                    if (is_string($content[0]) and is_string($content[1]) or 
                        is_int($content[0]) and is_string($content[1]) or 
                        is_int($content[0]) and is_array($content[1])) {

                        return $SetStr($content);
                    }

                    if (is_array($content[0]) and $content[1] === false) {
                        
                        return $SetStrArr($content, false);
                    }

                } else {

                    return $GetStr($content);
                }               
            }
        }
    } 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Переименование файлов (работает для директорий) 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function File_rename($file_old, $file_new) {
        $file_old = $this -> dopRes($file_old);
        $file_new = $this -> dopRes($file_new);
        rename($file_old, $file_new);
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Создание файла
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function File_great($file, $text, $options = 'r') {

        $file = $_SERVER['DOCUMENT_ROOT'].'/'.$file;

        if (!file_exists($file)) {
            $fp = fopen($file, $options);

            if (!$text == '') {
                fwrite($fp, $text);

            }   fclose($fp);
        } else {
            $fp = fopen($file, $options);

            if (!$text == '') {
                fwrite($fp, $text);

            }   fclose($fp);
        }
    }
    
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Создание директории
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function Dir_great($dir, $glob) {
        $dir = $this -> dopRes($dir);
        $structure = $_SERVER['DOCUMENT_ROOT'].'/'.$dir;

        if ($glob == true) {
            if (@!mkdir($structure, 0777, true)) {
                // die('Не удалось создать путь из директорий.');
                return false;
            }
        } else {
            if (@!mkdir($structure, 0777)) {
                // die('Не удалось создать директорию.');
                return false;
            }
        }
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Удаление директории
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function Dir_delit($dir) {
        $dir = $this -> dopRes($dir);
        $dir = $_SERVER['DOCUMENT_ROOT'].'/'.$dir;
        if ($objs = glob($dir."/*")) {
            foreach($objs as $obj) {
                is_dir($obj) ? Dir_delit($obj) : unlink($obj);
            }
        }   rmdir($dir);
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Рекурсивное слияние и - или копирование дерикотрии с файлами внутри
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function recurCopy($from, $to) {
        $from = $this -> dopRes($from);
        $to = $this -> dopRes($to);
        $structure = $_SERVER['DOCUMENT_ROOT'].'/'.$from;
        $structure2 = $_SERVER['DOCUMENT_ROOT'].'/'.$to;
        if(!file_exists($structure2)){
            mkdir($structure2);
        }
        if ($objs = glob($structure."/*")) {
            foreach($objs as $obj) {
                $forto=$structure2.str_replace($structure, '', $obj);
                if(is_dir($obj)){
                    recurCopy($obj, $forto);
                } else {
                    copy($obj, $forto);
                }
            }
        } return true;
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// считает колличество файлов в указанной дериктории
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function CountFile($value)
    {
        $value = $this -> dopRes($value);
        $dir = opendir($_SERVER['DOCUMENT_ROOT'].'/'.$value);
        $count = 0;
        while($file = readdir($dir)){
            if($file == '.' || $file == '..' || is_dir($_SERVER['DOCUMENT_ROOT'] .'/'. $value . $file)){
                continue;
            }
            $count++;
        }
        return $count;
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// вспомогательная функция для внутреннего использования внутри класса (удаляет слешь в начале - если есть)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    private function dopRes($dir)
    {
        if ($dir{0} == '/') {
            $dir = mb_substr($dir, 1);
        }

        return $dir;
    }

    private function dopUrl($dir)
    {
        $dir = $_SERVER['DOCUMENT_ROOT'].'/'.$dir;
        return $dir;
    }

    private function dopCube($Search_str, $key, $i) 
    {
        unset($this -> in_file_clon[$key]);
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Иницилизация класса файлового менеджера
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$fladmin2 = new MyFilesscan2();