Advertisement
petschko

File Class

Dec 2nd, 2015
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 16.95 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Author: Peter Dragicevic [peter-91@hotmail.de]
  4.  * Authors-Website: http://petschko.org/
  5.  * Date: 23.09.2015
  6.  * Time: 09:54
  7.  * Update: 09.04.2016
  8.  * Version: 1.0.4 (Changed Class-Name & Website)
  9.  * 1.0.3 (ReFormat code - renaming variables functions change them all to camelCase - Finished documentation)
  10.  *
  11.  * Licence: http://creativecommons.org/licenses/by-sa/4.0/
  12.  */
  13.  
  14. // Check if constance is defined - if not define
  15. if(! defined('DS'))
  16.     define('DS', DIRECTORY_SEPARATOR);
  17.  
  18. /**
  19.  * Class File
  20.  */
  21. class File {
  22.     private static $defaultPerm = '0755';
  23.     private $filename;
  24.     private $name;
  25.     private $path;
  26.     private $fileType;
  27.     private $dir;
  28.     private $fullPath;
  29.  
  30.     /**
  31.      * Creates a new file object
  32.      *
  33.      * @param string $filePath - Path to the file
  34.      * @param bool $new - create a new file? true creates a new | false do not create a new
  35.      * @param bool $overwrite - overwrite existing file? true overwrite existing files | false do not overwrite existing files (only affect on create new)
  36.      * @param bool $newDir - create a file or a directory? true creates a new directory | false creates a new file (only affect on create new)
  37.      * @throws Exception - File/directory not found
  38.      */
  39.     public function __construct($filePath, $new = false, $overwrite = false, $newDir = false) {
  40.         if($new)
  41.             $this->create($filePath, $overwrite, $newDir);
  42.         else
  43.             $this->updateFileInfo($filePath);
  44.     }
  45.  
  46.     /**
  47.      * Clears Memory
  48.      */
  49.     public function __destruct() {
  50.         unset($this->filename);
  51.         unset($this->name);
  52.         unset($this->path);
  53.         unset($this->fileType);
  54.         unset($this->dir);
  55.         unset($this->fullPath);
  56.     }
  57.  
  58.     /**
  59.      * Get the Path from a File path (but not get the last end of it) E.g /var/www/myFile.php will return /var/www/
  60.      *
  61.      * @param string $path - The File path + file
  62.      * @return string - The Path to the file (without the file at the end) if there is not a DIRECTORY SEPARATOR in the string return DIRECTORY SEPARATOR
  63.      */
  64.     public static function getPathFromString($path) {
  65.         $lastSlash = strrpos($path, DS);
  66.  
  67.         if($lastSlash !== false)
  68.             return substr($path, 0, $lastSlash);
  69.         return DS;
  70.     }
  71.  
  72.     /**
  73.      * Ensure, that the last character is a DIRECTORY SEPARATOR
  74.      *
  75.      * @param string $path - Path to check
  76.      * @return string - Path with ensured DIRECTORY SEPARATOR at the end
  77.      */
  78.     private static function checkDirPath($path) {
  79.         $lastChar = substr($path, -1);
  80.         if($lastChar != DS)
  81.             $path .= DS;
  82.  
  83.         return $path;
  84.     }
  85.  
  86.     /**
  87.      * Creates a new file or directory
  88.      *
  89.      * @param string $path - The file path
  90.      * @param bool $overwrite - Overwrite the file if exists? true overwrite | false don't overwrite (Only affected on create a file)
  91.      * @param bool $newDir - Create a new directory? true creates a new dir | false creates a new file
  92.      * @throws Exception - File/Directory not found
  93.      */
  94.     public function create($path, $overwrite = false, $newDir = false) {
  95.         if($newDir)
  96.             if(! file_exists($path))
  97.                 $created = mkdir($path, self::getDefaultPerm(), true);
  98.             else
  99.                 $created = true;
  100.         else {
  101.             $created = false;
  102.             if(! file_exists($path) || $overwrite) {
  103.                 if(! file_exists(self::getPathFromString($path)))
  104.                     new self(self::getPathFromString($path), true, false, true); // Creates missing directories if there are some
  105.                 // Create a new empty file
  106.                 fclose(fopen($path, 'wb'));
  107.             }
  108.             else
  109.                 $created = true;
  110.  
  111.             if(file_exists($path))
  112.                 $created = true;
  113.         }
  114.  
  115.         // Update file info
  116.         if($created)
  117.             $this->updateFileInfo($path);
  118.         else
  119.             unset($this);
  120.     }
  121.  
  122.     /**
  123.      * Rename a file or directory
  124.      *
  125.      * @param string $newName - the new name
  126.      * @return bool - true on success else false
  127.      * @throws Exception - File/Directory not found
  128.      */
  129.     public function rename($newName) {
  130.         // "Move" File - Better say rename
  131.         if(rename($this->getFullPath(), $this->getPath() . $newName)) {
  132.  
  133.             // Update file info
  134.             $this->updateFileInfo($this->getPath() . $newName);
  135.  
  136.             return true;
  137.         }
  138.  
  139.         return false;
  140.     }
  141.  
  142.     /**
  143.      * Move and may rename a file or directory
  144.      *
  145.      * @param string $newPath - The new destination of the file/directory
  146.      * @param string|bool $newName - The new name | false doesn't change the name
  147.      * @param bool $overwrite - Overwrites a file/directory if it exists at the destination | false do not overwrite | true overwrite
  148.      * @return bool - true on success else false
  149.      * @throws Exception - File/Directory not found
  150.      */
  151.     public function move($newPath, $newName = false, $overwrite = false) {
  152.         $newPath = self::checkDirPath($newPath);
  153.         $path = $newPath . (($newName) ? $newName : $this->getFilename());
  154.  
  155.         if(! file_exists($path) || $overwrite) {
  156.             // Delete existing dir if overwrite is allowed
  157.             if($overwrite && file_exists($path) && is_dir($path) && $this->isDir()) {
  158.                 $deleteDir = new self($path);
  159.                 $deleteDir->delete();
  160.             }
  161.  
  162.             // Move the file/directory
  163.             $move = rename($this->getFullPath(), $path);
  164.  
  165.             if($move) {
  166.                 // Update File info
  167.                 $this->updateFileInfo($path);
  168.  
  169.                 return true;
  170.             }
  171.         }
  172.         return false;
  173.     }
  174.  
  175.     /**
  176.      * Copy a file and may rename the new one and may create a new instance
  177.      *
  178.      * @param string $newPath - The destination of the copy of the file/directory
  179.      * @param string|bool $newName - The new name | false doesn't change the name
  180.      * @param bool $overwrite - Overwrites a file/directory if it exists at the destination | false do not overwrite | true overwrite
  181.      * @param bool $newResource - Create a new instance of this class for the copy of the file/directory? true does | false not
  182.      * @return bool|file - true on success else false and "file" on success if $newResource is true
  183.      */
  184.     public function copy($newPath, $newName = false, $overwrite = false, $newResource = false) {
  185.         $newPath = self::checkDirPath($newPath);
  186.         $path = $newPath . (($newName) ? $newName : $this->getFilename());
  187.  
  188.         if(! file_exists($path) || $overwrite) {
  189.             // Delete existing dir if overwrite is allowed
  190.             if($overwrite && file_exists($path) && is_dir($path) && $this->isDir()) {
  191.                 $deleteDir = new self($path);
  192.                 $deleteDir->delete();
  193.             }
  194.  
  195.             // Copy the file/directory
  196.             if(copy($this->getFullPath(), $path)) {
  197.                 if($newResource)
  198.                     return new self($path);
  199.  
  200.                 return true;
  201.             }
  202.         }
  203.         return false;
  204.     }
  205.  
  206.     /**
  207.      * Deletes the file/directory and remove this instance
  208.      */
  209.     public function delete() {
  210.         if($this->isDir()) {
  211.             // Delete files and sub folder within the selected folder
  212.             $this->clear();
  213.  
  214.             // Delete Folder
  215.             rmdir($this->getFullPath());
  216.             clearstatcache();
  217.         } else {
  218.             unlink($this->getFullPath());
  219.             clearstatcache();
  220.         }
  221.         unset($this);
  222.     }
  223.  
  224.     /**
  225.      * Get the content of a directory or file (on dir you say 1 file but on files you say 1 byte)
  226.      *
  227.      * @param int $limit - how many - on dirs set amount of files | on files set how many bytes
  228.      * @param int $start - start file (on dirs) or byte (on files)
  229.      * @param bool $subDirs - only on dirs get content from sub dirs?
  230.      * @return array|bool - (on dirs) file class array | (on files) false todo implement
  231.      */
  232.     public function getContent($limit = 1000, $start = 0, $subDirs = false) {
  233.         if($this->isDir()) {
  234.             if($handle = opendir($this->getFullPath())) {
  235.                 $array = array();
  236.                 $i = 0;
  237.                 $ignore = 0;
  238.                 while(($file = readdir($handle)) !== false) {
  239.                     if($file != '.' && $file != '..') {
  240.                         $tmpClass = new self($this->getFullPath() . $file);
  241.                         if($ignore >= $start) {
  242.                             // Add file/dir to return array
  243.                             if(! $tmpClass->isDir() || $subDirs) {
  244.                                 $array[$i] = $tmpClass;
  245.                                 $i++;
  246.                             }
  247.  
  248.                             // Stop if limit is reached
  249.                             if($i >= $limit && $limit > 0) {
  250.                                 if(is_resource($handle))
  251.                                     closedir($handle);
  252.                                 clearstatcache();
  253.  
  254.                                 return $array;
  255.                             }
  256.                         }
  257.                         // Increase ignoreCounter and increase it on dirs if enabled
  258.                         if(! $tmpClass->isDir() || $subDirs)
  259.                             $ignore++;
  260.  
  261.                         // Clear Memory
  262.                         unset($tmpClass);
  263.                     }
  264.                     unset($file);
  265.                 }
  266.  
  267.                 // Close handle and clear cache/memory
  268.                 unset($ignore);
  269.                 if(is_resource($handle))
  270.                     closedir($handle);
  271.                 clearstatcache();
  272.  
  273.                 return $array;
  274.             }
  275.         } else {
  276.             // todo implement (show file content)
  277.         }
  278.  
  279.         return false;
  280.     }
  281.  
  282.     /**
  283.      * Get the size of a file or directory
  284.      * ------------------------------------------------------------------------
  285.      * IMPORTANT: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions
  286.      * may return unexpected results for files which are larger than 2GB.
  287.      * See: http://php.net/manual/en/function.filesize.php
  288.      * ------------------------------------------------------------------------
  289.      *
  290.      * @return bool|int - The size of the file/directory (Bytes)
  291.      */
  292.     public function getSize() {
  293.         if($this->isDir()) {
  294.             $bytes = 0;
  295.  
  296.             if($handle = opendir($this->getFullPath())) {
  297.                 // Count files
  298.                 while(($file = readdir($handle)) !== false) {
  299.                     if($file != '.' && $file != '..') {
  300.                         $tmpClass = new self($this->getFullPath() . $file);
  301.  
  302.                         $bytes += $tmpClass->getSize();
  303.  
  304.                         // Clear Memory
  305.                         unset($tmpClass);
  306.                     }
  307.                     unset($file);
  308.                 }
  309.             }
  310.  
  311.             // Close handle and clear cache
  312.             if(is_resource($handle))
  313.                 closedir($handle);
  314.             clearstatcache();
  315.  
  316.             return $bytes;
  317.         } else
  318.             return filesize($this->getFullPath());
  319.     }
  320.  
  321.     /**
  322.      * Get the number of files in this directory
  323.      *
  324.      * @param bool $excludeSubDirs - Do not Count files in subdirectories? true doesn't count files in sub dirs | false count files in sub dirs
  325.      * @param bool $countDirs - Count dirs in the directory too? true counts dirs as the same as files | false ignore dirs on counting
  326.      * @return int number of files - if the instance is a file this return always 1
  327.      */
  328.     public function countFiles($excludeSubDirs = true, $countDirs = false) {
  329.         if($this->isDir()) {
  330.             $files = 0;
  331.             if($handle = opendir($this->getFullPath())) {
  332.                 // Count files
  333.                 while(($file = readdir($handle)) !== false) {
  334.                     if($file != '.' && $file != '..') {
  335.                         $tmpClass = new self($this->getFullPath() . $file);
  336.  
  337.                         // Is this a dir?
  338.                         if($tmpClass->isDir()) {
  339.                             // Count sub dirs?
  340.                             if($countDirs)
  341.                                 $files++;
  342.  
  343.                             // Check the content of the sub dirs too?
  344.                             if($excludeSubDirs === false)
  345.                                 $files += $tmpClass->countFiles(false, $countDirs);
  346.                         } else
  347.                             $files++;
  348.  
  349.                         // Clear Memory
  350.                         unset($tmpClass);
  351.                     }
  352.                     unset($file);
  353.                 }
  354.             }
  355.             // Close handle and clear cache
  356.             if(is_resource($handle))
  357.                 closedir($handle);
  358.             clearstatcache();
  359.  
  360.             return $files;
  361.         } else
  362.             return 1; // A File return always 1
  363.     }
  364.  
  365.     /**
  366.      * Delete everything in a file or a directory
  367.      */
  368.     public function clear() {
  369.         if($this->isDir()) {
  370.             if($handle = opendir($this->getFullPath())) {
  371.                 // Delete files and sub folder within the selected folder
  372.                 while(($file = readdir($handle)) !== false) {
  373.                     if($file != '.' && $file != '..') {
  374.                         $fileClass = new self($this->getFullPath() . $file);
  375.                         $fileClass->delete();
  376.                     }
  377.                 }
  378.  
  379.                 // Close handle and clear cache
  380.                 if(is_resource($handle))
  381.                     closedir($handle);
  382.                 clearstatcache();
  383.             }
  384.         } else {
  385.             $handle = fopen($this->getFullPath(), 'wb');
  386.  
  387.             // Close handle and clear cache
  388.             if(is_resource($handle))
  389.                 closedir($handle);
  390.             clearstatcache();
  391.         }
  392.     }
  393.  
  394.     /**
  395.      * Shows the creation time of a file
  396.      *
  397.      * @return int - creation time
  398.      */
  399.     public function getCTime() {
  400.         return filectime($this->getFullPath());
  401.     }
  402.  
  403.     /**
  404.      * Shows the last modification time of a file
  405.      *
  406.      * @return int modification time
  407.      */
  408.     public function getMTime() {
  409.         return filemtime($this->getFullPath());
  410.     }
  411.  
  412.     /**
  413.      * Changes the permission of a file or directory
  414.      *
  415.      * @param string|bool $perm - Permissions as a string or false if restoring the files default permissions
  416.      * @return bool - true on success else false
  417.      */
  418.     public function chmod($perm = false) {
  419.         return chmod($this->getFullPath(), ((is_string($perm)) ? octdec($perm) : self::getDefaultPerm()));
  420.     }
  421.  
  422.     /**
  423.      * Update the information about this file/directory in this instance
  424.      *
  425.      * @param string $filePath - path of the file/directory MUST exist!
  426.      * @throws Exception - File/Directory not found
  427.      */
  428.     private function updateFileInfo($filePath) {
  429.         if(! file_exists($filePath))
  430.             throw new Exception(__CLASS__ . '->' . __FUNCTION__ . ': &quot;' . $filePath . '&quot; doesn\'t exists!');
  431.  
  432.         $lastSlash = strrpos($filePath, DS);
  433.         $this->setFullPath($filePath);
  434.         if(is_dir($this->getFullPath())) {
  435.             $this->setDir(true);
  436.             $this->setFileType('DIRECTORY');
  437.  
  438.             // Check if last char is an slash if yes recheck to the previous slash
  439.             $lastChar = substr($this->getFullPath(), -1);
  440.             if($lastChar == DS) {
  441.                 $filePath = substr($filePath, 0, -1);
  442.                 $lastSlash = strrpos($filePath, DS);
  443.             } else
  444.                 $this->setFullPath($this->getFullPath() . DS);
  445.             unset($lastChar);
  446.  
  447.             // Get path and directory name
  448.             if($lastSlash !== false) {
  449.                 $this->setPath(substr($this->getFullPath(), 0, $lastSlash + 1));
  450.                 $this->setFilename(substr($this->getFullPath(), $lastSlash + 1));
  451.             } else {
  452.                 $this->setPath($this->getFullPath());
  453.                 $this->setFilename($this->getFullPath());
  454.             }
  455.  
  456.             // Check if filename not end with slash
  457.             $lastChar = substr($this->getFilename(), -1);
  458.             if($lastChar == DS)
  459.                 $this->setFilename(substr($this->getFilename(), 0, -1));
  460.             $this->setName($this->getFilename());
  461.         } else {
  462.             $this->setDir(false);
  463.  
  464.             // Get Filename
  465.             if($lastSlash !== false) {
  466.                 $this->setPath(substr($filePath, 0, $lastSlash + 1));
  467.                 $file = substr($this->getFullPath(), $lastSlash + 1);
  468.             } else {
  469.                 $this->setPath($this->getFullPath());
  470.                 $file = $this->getFullPath();
  471.             }
  472.             $this->setFilename($file);
  473.  
  474.             $lastDot = stripos($file, '.');
  475.             if($lastDot !== false) {
  476.                 $this->setName(substr($file, 0, $lastDot));
  477.                 $this->setFileType(strtolower(substr($file, $lastDot + 1)));
  478.             } else {
  479.                 $this->setName($this->getFilename());
  480.                 $this->setFileType('NONE');
  481.             }
  482.         }
  483.     }
  484.  
  485.     /**
  486.      * Get the Full-Path of the file or directory
  487.      *
  488.      * @return string - the path to the file/directory including the name of the dir/file
  489.      */
  490.     public function getFullPath() {
  491.         return $this->fullPath;
  492.     }
  493.  
  494.     /**
  495.      * Set the Full-Path of the file or directory
  496.      *
  497.      * @param string $fullPath - the path to the file/directory including the name of the dir/file
  498.      */
  499.     private function setFullPath($fullPath) {
  500.         $this->fullPath = $fullPath;
  501.     }
  502.  
  503.     /**
  504.      * Get the name of the file plus extension eg "index.php" or a directory
  505.      *
  506.      * @return string - The File name
  507.      */
  508.     public function getFilename() {
  509.         return $this->filename;
  510.     }
  511.  
  512.     /**
  513.      * Set the name of the file plus extension eg "index.php" or a directory
  514.      *
  515.      * @param string $filename - The File name
  516.      */
  517.     private function setFilename($filename) {
  518.         $this->filename = $filename;
  519.     }
  520.  
  521.     /**
  522.      * Get the name of the file without extension eg "index" instead of "index.php" or a directory
  523.      *
  524.      * @return string - The name
  525.      */
  526.     public function getName() {
  527.         return $this->name;
  528.     }
  529.  
  530.     /**
  531.      * Set the name of the file without extension eg "index" instead of "index.php" or a directory
  532.      *
  533.      * @param string $name - The name
  534.      */
  535.     private function setName($name) {
  536.         $this->name = $name;
  537.     }
  538.  
  539.     /**
  540.      * Get the Path to the file but without the filename itself or the path to the directory without the dir itself
  541.      *
  542.      * @return string - The Path to the dir/file
  543.      */
  544.     public function getPath() {
  545.         return $this->path;
  546.     }
  547.  
  548.     /**
  549.      * Set the Path to the file but without the filename itself or the path to the directory without the dir itself
  550.      *
  551.      * @param string $path - The Path to the dir/file
  552.      */
  553.     private function setPath($path) {
  554.         $this->path = $path;
  555.     }
  556.  
  557.     /**
  558.      * Get the File type of this instance
  559.      *
  560.      * @return string - file type of the file or "NONE" or "DIRECTORY"
  561.      */
  562.     public function getFileType() {
  563.         return $this->fileType;
  564.     }
  565.  
  566.     /**
  567.      * Set the File type of this instance
  568.      *
  569.      * @param string $fileType - file type
  570.      */
  571.     private function setFileType($fileType) {
  572.         $this->fileType = $fileType;
  573.     }
  574.  
  575.     /**
  576.      * @return bool - true if this instance is a directory else false
  577.      */
  578.     public function isDir() {
  579.         return $this->dir;
  580.     }
  581.  
  582.     /**
  583.      * @param bool $dir - is this a directory? true is a directory | false is not a directory
  584.      */
  585.     private function setDir($dir) {
  586.         $this->dir = $dir;
  587.     }
  588.  
  589.     /**
  590.      * Get the default permissions
  591.      *
  592.      * @return number - Default Permissions for chmod and functions that need permissions
  593.      */
  594.     public static function getDefaultPerm() {
  595.         return octdec(self::$defaultPerm);
  596.     }
  597.  
  598.     /**
  599.      * Set the default permissions
  600.      *
  601.      * @param string $defaultPerm - Default Permissions for chmod and functions that need permissions
  602.      */
  603.     public static function setDefaultPerm($defaultPerm) {
  604.         self::$defaultPerm = $defaultPerm;
  605.     }
  606. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement