]>
Commit | Line | Data |
---|---|---|
2e28269b | 1 | <?php |
b2306b0c A |
2 | |
3 | require_once 'exceptions/IOException.php'; | |
4 | ||
2e28269b | 5 | /** |
b2306b0c A |
6 | * Class FileUtils |
7 | * | |
8 | * Utility class for file manipulation. | |
2e28269b | 9 | */ |
b2306b0c | 10 | class FileUtils |
2e28269b | 11 | { |
b2306b0c A |
12 | /** |
13 | * @var string | |
14 | */ | |
15 | protected static $phpPrefix = '<?php /* '; | |
16 | ||
17 | /** | |
18 | * @var string | |
19 | */ | |
20 | protected static $phpSuffix = ' */ ?>'; | |
2e28269b V |
21 | |
22 | /** | |
b2306b0c A |
23 | * Write data into a file (Shaarli database format). |
24 | * The data is stored in a PHP file, as a comment, in compressed base64 format. | |
25 | * | |
26 | * The file will be created if it doesn't exist. | |
27 | * | |
28 | * @param string $file File path. | |
813849e5 | 29 | * @param mixed $content Content to write. |
b2306b0c A |
30 | * |
31 | * @return int|bool Number of bytes written or false if it fails. | |
2e28269b | 32 | * |
b2306b0c | 33 | * @throws IOException The destination file can't be written. |
2e28269b | 34 | */ |
b2306b0c | 35 | public static function writeFlatDB($file, $content) |
2e28269b | 36 | { |
b2306b0c A |
37 | if (is_file($file) && !is_writeable($file)) { |
38 | // The datastore exists but is not writeable | |
39 | throw new IOException($file); | |
d2d4f993 | 40 | } elseif (!is_file($file) && !is_writeable(dirname($file))) { |
b2306b0c A |
41 | // The datastore does not exist and its parent directory is not writeable |
42 | throw new IOException(dirname($file)); | |
43 | } | |
44 | ||
45 | return file_put_contents( | |
46 | $file, | |
47 | self::$phpPrefix.base64_encode(gzdeflate(serialize($content))).self::$phpSuffix | |
48 | ); | |
49 | } | |
50 | ||
51 | /** | |
52 | * Read data from a file containing Shaarli database format content. | |
8c322aab V |
53 | * |
54 | * If the file isn't readable or doesn't exist, default data will be returned. | |
b2306b0c A |
55 | * |
56 | * @param string $file File path. | |
57 | * @param mixed $default The default value to return if the file isn't readable. | |
58 | * | |
59 | * @return mixed The content unserialized, or default if the file isn't readable, or false if it fails. | |
60 | */ | |
61 | public static function readFlatDB($file, $default = null) | |
62 | { | |
63 | // Note that gzinflate is faster than gzuncompress. | |
64 | // See: http://www.php.net/manual/en/function.gzdeflate.php#96439 | |
8c322aab V |
65 | if (! is_readable($file)) { |
66 | return $default; | |
67 | } | |
68 | ||
69 | $data = file_get_contents($file); | |
70 | if ($data == '') { | |
71 | return $default; | |
b2306b0c A |
72 | } |
73 | ||
8c322aab V |
74 | return unserialize( |
75 | gzinflate( | |
76 | base64_decode( | |
77 | substr($data, strlen(self::$phpPrefix), -strlen(self::$phpSuffix)) | |
78 | ) | |
79 | ) | |
80 | ); | |
2e28269b V |
81 | } |
82 | } |