Issues (10)

lib/Data/Filesystem.php (2 issues)

Labels
Severity
1
<?php
2
/**
3
 * PrivateBin
4
 *
5
 * a zero-knowledge paste bin
6
 *
7
 * @link      https://github.com/PrivateBin/PrivateBin
8
 * @copyright 2012 S├ębastien SAUVAGE (sebsauvage.net)
9
 * @license   https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
10
 * @version   1.3
11
 */
12
13
namespace PrivateBin\Data;
14
15
use PrivateBin\Persistence\DataStore;
16
17
/**
18
 * Filesystem
19
 *
20
 * Model for filesystem data access, implemented as a singleton.
21
 */
22
class Filesystem extends AbstractData
23
{
24
    /**
25
     * get instance of singleton
26
     *
27
     * @access public
28
     * @static
29
     * @param  array $options
30
     * @return Filesystem
31
     */
32 53
    public static function getInstance(array $options)
33
    {
34
        // if needed initialize the singleton
35 53
        if (!(self::$_instance instanceof self)) {
36 48
            self::$_instance = new self;
37
        }
38
        // if given update the data directory
39
        if (
40 53
            is_array($options) &&
41 53
            array_key_exists('dir', $options)
42
        ) {
43 53
            DataStore::setPath($options['dir']);
44
        }
45 53
        return self::$_instance;
46
    }
47
48
    /**
49
     * Create a paste.
50
     *
51
     * @access public
52
     * @param  string $pasteid
53
     * @param  array  $paste
54
     * @return bool
55
     */
56 39
    public function create($pasteid, array $paste)
57
    {
58 39
        $storagedir = self::_dataid2path($pasteid);
59 39
        $file       = $storagedir . $pasteid . '.php';
60 39
        if (is_file($file)) {
61 2
            return false;
62
        }
63 39
        if (!is_dir($storagedir)) {
64 39
            mkdir($storagedir, 0700, true);
65
        }
66 39
        return DataStore::store($file, $paste);
67
    }
68
69
    /**
70
     * Read a paste.
71
     *
72
     * @access public
73
     * @param  string $pasteid
74
     * @return array|false
75
     */
76 29
    public function read($pasteid)
77
    {
78 29
        if (!$this->exists($pasteid)) {
79 1
            return false;
80
        }
81 29
        return self::upgradePreV1Format(
82 29
            DataStore::get(self::_dataid2path($pasteid) . $pasteid . '.php')
83
        );
84
    }
85
86
    /**
87
     * Delete a paste and its discussion.
88
     *
89
     * @access public
90
     * @param  string $pasteid
91
     */
92 14
    public function delete($pasteid)
93
    {
94 14
        $pastedir = self::_dataid2path($pasteid);
95 14
        if (is_dir($pastedir)) {
96
            // Delete the paste itself.
97 11
            if (is_file($pastedir . $pasteid . '.php')) {
98 11
                unlink($pastedir . $pasteid . '.php');
99
            }
100
101
            // Delete discussion if it exists.
102 11
            $discdir = self::_dataid2discussionpath($pasteid);
103 11
            if (is_dir($discdir)) {
104
                // Delete all files in discussion directory
105 1
                $dir = dir($discdir);
106 1
                while (false !== ($filename = $dir->read())) {
107 1
                    if (is_file($discdir . $filename)) {
108 1
                        unlink($discdir . $filename);
109
                    }
110
                }
111 1
                $dir->close();
112 1
                rmdir($discdir);
113
            }
114
        }
115 14
    }
116
117
    /**
118
     * Test if a paste exists.
119
     *
120
     * @access public
121
     * @param  string $pasteid
122
     * @return bool
123
     */
124 53
    public function exists($pasteid)
125
    {
126 53
        $basePath  = self::_dataid2path($pasteid) . $pasteid;
127 53
        $pastePath = $basePath . '.php';
128
        // convert to PHP protected files if needed
129 53
        if (is_readable($basePath)) {
130 1
            DataStore::prependRename($basePath, $pastePath);
131
132
            // convert comments, too
133 1
            $discdir = self::_dataid2discussionpath($pasteid);
134 1
            if (is_dir($discdir)) {
135 1
                $dir = dir($discdir);
136 1
                while (false !== ($filename = $dir->read())) {
137 1
                    if (substr($filename, -4) !== '.php' && strlen($filename) >= 16) {
138 1
                        $commentFilename = $discdir . $filename . '.php';
139 1
                        DataStore::prependRename($discdir . $filename, $commentFilename);
140
                    }
141
                }
142 1
                $dir->close();
143
            }
144
        }
145 53
        return is_readable($pastePath);
146
    }
147
148
    /**
149
     * Create a comment in a paste.
150
     *
151
     * @access public
152
     * @param  string $pasteid
153
     * @param  string $parentid
154
     * @param  string $commentid
155
     * @param  array  $comment
156
     * @return bool
157
     */
158 4
    public function createComment($pasteid, $parentid, $commentid, array $comment)
159
    {
160 4
        $storagedir = self::_dataid2discussionpath($pasteid);
161 4
        $file       = $storagedir . $pasteid . '.' . $commentid . '.' . $parentid . '.php';
162 4
        if (is_file($file)) {
163 1
            return false;
164
        }
165 4
        if (!is_dir($storagedir)) {
166 4
            mkdir($storagedir, 0700, true);
167
        }
168 4
        return DataStore::store($file, $comment);
169
    }
170
171
    /**
172
     * Read all comments of paste.
173
     *
174
     * @access public
175
     * @param  string $pasteid
176
     * @return array
177
     */
178 16
    public function readComments($pasteid)
179
    {
180 16
        $comments = array();
181 16
        $discdir  = self::_dataid2discussionpath($pasteid);
182 16
        if (is_dir($discdir)) {
183 3
            $dir = dir($discdir);
184 3
            while (false !== ($filename = $dir->read())) {
185
                // Filename is in the form pasteid.commentid.parentid.php:
186
                // - pasteid is the paste this reply belongs to.
187
                // - commentid is the comment identifier itself.
188
                // - parentid is the comment this comment replies to (It can be pasteid)
189 3
                if (is_file($discdir . $filename)) {
190 3
                    $comment = DataStore::get($discdir . $filename);
191 3
                    $items   = explode('.', $filename);
192
                    // Add some meta information not contained in file.
193 3
                    $comment['id']       = $items[1];
194 3
                    $comment['parentid'] = $items[2];
195
196
                    // Store in array
197 3
                    $key            = $this->getOpenSlot($comments, (int) $comment['meta']['created']);
198 3
                    $comments[$key] = $comment;
199
                }
200
            }
201 3
            $dir->close();
202
203
            // Sort comments by date, oldest first.
204 3
            ksort($comments);
205
        }
206 16
        return $comments;
207
    }
208
209
    /**
210
     * Test if a comment exists.
211
     *
212
     * @access public
213
     * @param  string $pasteid
214
     * @param  string $parentid
215
     * @param  string $commentid
216
     * @return bool
217
     */
218 8
    public function existsComment($pasteid, $parentid, $commentid)
219
    {
220 8
        return is_file(
221 8
            self::_dataid2discussionpath($pasteid) .
222 8
            $pasteid . '.' . $commentid . '.' . $parentid . '.php'
223
        );
224
    }
225
226
    /**
227
     * Returns up to batch size number of paste ids that have expired
228
     *
229
     * @access private
230
     * @param  int $batchsize
231
     * @return array
232
     */
233 15
    protected function _getExpiredPastes($batchsize)
234
    {
235 15
        $pastes     = array();
236 15
        $mainpath   = DataStore::getPath();
237 15
        $firstLevel = array_filter(
238 15
            scandir($mainpath),
0 ignored issues
show
It seems like scandir($mainpath) can also be of type false; however, parameter $input of array_filter() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

238
            /** @scrutinizer ignore-type */ scandir($mainpath),
Loading history...
239 15
            'self::_isFirstLevelDir'
240
        );
241 15
        if (count($firstLevel) > 0) {
242
            // try at most 10 times the $batchsize pastes before giving up
243 3
            for ($i = 0, $max = $batchsize * 10; $i < $max; ++$i) {
244 3
                $firstKey    = array_rand($firstLevel);
245 3
                $secondLevel = array_filter(
246 3
                    scandir($mainpath . DIRECTORY_SEPARATOR . $firstLevel[$firstKey]),
247 3
                    'self::_isSecondLevelDir'
248
                );
249
250
                // skip this folder in the next checks if it is empty
251 3
                if (count($secondLevel) == 0) {
252 1
                    unset($firstLevel[$firstKey]);
253 1
                    continue;
254
                }
255
256 3
                $secondKey = array_rand($secondLevel);
257 3
                $path      = $mainpath . DIRECTORY_SEPARATOR .
258 3
                    $firstLevel[$firstKey] . DIRECTORY_SEPARATOR .
259 3
                    $secondLevel[$secondKey];
260 3
                if (!is_dir($path)) {
261
                    continue;
262
                }
263 3
                $thirdLevel = array_filter(
264 3
                    array_map(
265 3
                        function ($filename) {
266 3
                            return strlen($filename) >= 20 ?
267 3
                                substr($filename, 0, -4) :
268 3
                                $filename;
269 3
                        },
270 3
                        scandir($path)
0 ignored issues
show
It seems like scandir($path) can also be of type false; however, parameter $arr1 of array_map() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

270
                        /** @scrutinizer ignore-type */ scandir($path)
Loading history...
271
                    ),
272 3
                    'PrivateBin\\Model\\Paste::isValidId'
273
                );
274 3
                if (count($thirdLevel) == 0) {
275
                    continue;
276
                }
277 3
                $thirdKey = array_rand($thirdLevel);
278 3
                $pasteid  = $thirdLevel[$thirdKey];
279 3
                if (in_array($pasteid, $pastes)) {
280 1
                    continue;
281
                }
282
283 3
                if ($this->exists($pasteid)) {
284 3
                    $data = $this->read($pasteid);
285
                    if (
286 3
                        array_key_exists('expire_date', $data['meta']) &&
287 3
                        $data['meta']['expire_date'] < time()
288
                    ) {
289 1
                        $pastes[] = $pasteid;
290 1
                        if (count($pastes) >= $batchsize) {
291
                            break;
292
                        }
293
                    }
294
                }
295
            }
296
        }
297 15
        return $pastes;
298
    }
299
300
    /**
301
     * Convert paste id to storage path.
302
     *
303
     * The idea is to creates subdirectories in order to limit the number of files per directory.
304
     * (A high number of files in a single directory can slow things down.)
305
     * eg. "f468483c313401e8" will be stored in "data/f4/68/f468483c313401e8"
306
     * High-trafic websites may want to deepen the directory structure (like Squid does).
307
     *
308
     * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/'
309
     *
310
     * @access private
311
     * @static
312
     * @param  string $dataid
313
     * @return string
314
     */
315 53
    private static function _dataid2path($dataid)
316
    {
317 53
        return DataStore::getPath(
318 53
            substr($dataid, 0, 2) . DIRECTORY_SEPARATOR .
319 53
            substr($dataid, 2, 2) . DIRECTORY_SEPARATOR
320
        );
321
    }
322
323
    /**
324
     * Convert paste id to discussion storage path.
325
     *
326
     * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/e3570978f9e4aa90.discussion/'
327
     *
328
     * @access private
329
     * @static
330
     * @param  string $dataid
331
     * @return string
332
     */
333 23
    private static function _dataid2discussionpath($dataid)
334
    {
335 23
        return self::_dataid2path($dataid) . $dataid .
336 23
            '.discussion' . DIRECTORY_SEPARATOR;
337
    }
338
339
    /**
340
     * Check that the given element is a valid first level directory.
341
     *
342
     * @access private
343
     * @static
344
     * @param  string $element
345
     * @return bool
346
     */
347 15
    private static function _isFirstLevelDir($element)
348
    {
349 15
        return self::_isSecondLevelDir($element) &&
350 15
            is_dir(DataStore::getPath($element));
351
    }
352
353
    /**
354
     * Check that the given element is a valid second level directory.
355
     *
356
     * @access private
357
     * @static
358
     * @param  string $element
359
     * @return bool
360
     */
361 15
    private static function _isSecondLevelDir($element)
362
    {
363 15
        return (bool) preg_match('/^[a-f0-9]{2}$/', $element);
364
    }
365
}
366