Classes

File io/filesystem/File.class.php

File io/filesystem/File.class.php

  1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 
<?php
/**
 * This class represents a text file which can be read and written.
 * @package     IO
 * @subpackage  Filesystem
 * @copyright   &copy; 2005-2019 PHPBoost
 * @license     https://www.gnu.org/licenses/gpl-3.0.html GNU/GPL-3.0
 * @author      Nicolas Duhamel <akhenathon2@gmail.com>
 * @version     PHPBoost 5.2 - last update: 2019 03 27
 * @since       PHPBoost 2.0 - 2008 07 06
 * @contributor Loic ROUCHON <horn@phpboost.com>
 * @contributor Benoit SAUTEL <ben.popeye@phpboost.com>
 * @contributor Julien BRISWALTER <j1.seth@phpboost.com>
 * @contributor Arnaud GENET <elenwii@phpboost.com>
*/

class File extends FileSystemElement
{
    const READ = 0x1;
    const WRITE = 0x2;
    const APPEND = 0x3;
    private static $BUFFER_SIZE = 8192;

    /**
     * @var string Content of the file
     */
    private $contents;
    /**
     * @var int Open mode
     */
    private $mode = 0;
    /**
     * @var File descriptor of the open file.
     */
    private $file_descriptor;

    /**
     * Builds a File object.
     * @param string $path Path of the file you want to work with.
     * @param int $mode If you want to open it only to read it, use the flag File::READ, if it's to write it use the File::WRITE flag, you also can use the File::READ_WRITE flag.
     * @param bool $whenopen If you want to open the file now, use the File::DIRECT_OPENING constant, if you want to open it only when you will need it, use the File::LAZY_OPENING constant.
     */
    public function __construct($path)
    {
        parent::__construct($path);
    }

    public function __destruct()
    {
        $this->close();
    }

    /**
     * Returns the element name without extension.
     * @return string The element name without extension.
     */
    public function get_name_without_extension()
    {
        $name = $this->get_name();
        return mb_substr($name, 0, mb_strpos($name, '.'));
    }

    /**
     * Returns the extension of the element.
     * @return string Element extension.
     */
    public function get_extension()
    {
        $name = $this->get_name();
        return mb_substr(mb_strrchr($name,'.'), 1);
    }

    /**
     * Returns the content of the file.
     * @param int $start Byte from which you want to start. 0 if you want to read the file from its begening, 1 to start with the second etc.
     * @param int $len Number of bytes you want to read.
     * @return string The read content.
     */
    public function read($start = 0, $len = -1)
    {
        $opened_by_me = $this->open(self::READ);

        fseek($this->file_descriptor, $start);

        if ($len == -1)
        {
            $len = filesize($this->get_path());
        }

        $content = '';
        while (!feof($this->file_descriptor) && $len > 0)
        {
            $content .= fread($this->file_descriptor, min($len, self::$BUFFER_SIZE));
            $len -= self::$BUFFER_SIZE;
        }
        if ($opened_by_me)
        {
            $this->close();
        }
        return $content;
    }

    /**
     * Returns the content of the file grouped by lines.
     * @return string[] The list of the lines of the file.
     */
    public function read_lines()
    {
        return explode("\n", $this->read());
    }

    /**
     * Writes some text in the file. Erases the file previous content
     * @param string $data The text you want to write in the file.
     * @throws IOException If it's not possible to write the file
     */
    public function write($data)
    {
        $opened_by_me = $this->open(self::WRITE);
        $this->write_data($data);
        if ($opened_by_me)
        {
            $this->close();
        }
    }

    /**
     * Appends some text at the end of the file.
     * @param string $data The text you want to write in the file.
     * @throws IOException If it's not possible to write the file
     */
    public function append($data)
    {
        $opened_by_me = $this->open(self::APPEND);
        $this->write_data($data);
        if ($opened_by_me)
        {
            $this->close();
        }
    }

    /**
     * empty the file
     */
    public function erase()
    {
        $opened_by_me = $this->open(self::WRITE);
        ftruncate($this->file_descriptor, 0);
        if ($opened_by_me)
        {
            $this->close();
        }
    }

    /**
     * Closes a file and frees the allocated memory relative to the file.
     */
    public function close()
    {
        if ($this->is_open())
        {
            $this->mode = 0;
            fclose($this->file_descriptor);
            $this->file_descriptor = null;
        }
    }

    /**
     * Deletes the file.
     * @throws IOException if the file cannot been deleted
     */
    public function delete()
    {
        $this->close();
        if (file_exists($this->get_path()))
        {
            if (!unlink($this->get_path()))
            {
                // Empty the file if it couldn't delete it
                $this->erase();
                throw new IOException('The file ' . $this->get_path()  . ' couldn\'t been deleted');
            }
        }
    }

    /**
     * @param bool $blocking if true, block the script, if false, non blocking operation
     * Locks the file (it won't be readable by another thread which could try to access it).
     * @throws IOException if the file cannot been locked
     */
    public function lock($blocking = true)
    {
        if (!$this->is_open())
        {
            throw new IOException('The file ' . $this->get_path() . ' should be opened before trying to lock it');
        }
        $this->open(self::WRITE);
        $success = @flock($this->file_descriptor, LOCK_EX, $blocking);
        /*
        if (!$success)
        {
            throw new IOException('The file ' . $this->get_path() . ' couldn\'t been locked');
        }
        */
    }

    /**
     * Unlocks a file. The file must have been locked before you call this method.
     * @throws IOException if the file cannot been unlocked
     */
    public function unlock()
    {
        if (!$this->is_open())
        {
            throw new IOException('The file ' . $this->get_path() . ' should be opened before trying to unlock it');
        }
        $this->open(self::WRITE);
        $succeed = @flock($this->file_descriptor, LOCK_UN);
        /*if (!$succeed)
        {
            throw new IOException('The file ' . $this->get_path() . ' couldn\'t been unlocked');
        }
        */
    }

    /**
     * Forces the system to write all the buffered output.
     */
    public function flush()
    {
        if ($this->is_open())
        {
            fflush($this->file_descriptor);
        }
    }

    /**
     * Returns the date of the last modification of the file.
     * @return int The UNIX timestamp corresponding to the last modification date.
     */
    public function get_last_modification_date()
    {
        return @filemtime($this->get_path());
    }

    /**
     * Returns the last access date of the file.
     * @return int The UNIX timestamp corresponding to the last access date of the file.
     */
    public function get_last_access_date()
    {
        return @filectime($this->get_path());
    }

    /**
     * Returns the size of the file.
     * @return int The size of the file in bytes.
     */
    public function get_file_size()
    {
        return (int)@filesize($this->get_path());
    }

    /**
     * Opens the file. You cannot read or write a closed file, use this method to open it.
     * @throws IOException If the file can neither been read nor created.
     */
    public function open($mode)
    {
        if ($this->mode != $mode)
        {
            $this->close();
            $this->mode = $mode;
            switch ($this->mode)
            {
                case self::APPEND:
                    $this->file_descriptor = @fopen($this->get_path(), 'a+b');
                    $this->check_file_descriptor('Can\'t open the file for creating / writing');
                    break;
                case self::WRITE:
                    $this->file_descriptor = @fopen($this->get_path(), 'w+b');
                    $this->check_file_descriptor('Can\'t open the file for creating / writing');
                    break;
                case self::READ:
                default:
                    $this->file_descriptor = @fopen($this->get_path(), 'rb');
                    $this->check_file_descriptor('Can\'t open the file for reading');
                    break;
            }
            return true;
        }
        return false;
    }

    /**
     * Allows you to know if the file is already open.
     * @return bool true if the file is open, false if it's closed.
     */
    private function is_open()
    {
        return is_resource($this->file_descriptor);
    }

    private function write_data($data)
    {
        $bytes_to_write = TextHelper::strlen($data);
        $bytes_written = 0;
        while ($bytes_written < $bytes_to_write)
        {
            $bytes = fwrite($this->file_descriptor, TextHelper::substr($data, $bytes_written, self::$BUFFER_SIZE));
            if ($bytes === false || $bytes == 0)
            {
                break;
            }
            $bytes_written += $bytes;
        }
    }

    private function check_file_descriptor($message)
    {
        if ($this->file_descriptor === false || $this->file_descriptor === null)
        {
            throw new IOException($message . ' : ' . $this->get_path());
        }
    }

    /**
     * Get file checksum in sha256.
     * @param string $filename Path of the file you want to work with.
     * @return string The hash of the file in sha256.
     */
    public static function get_file_checksum($filename)
    {
        return hash_file('sha256', $filename);
    }
}
?>