more package deps
[phorkie.git] / src / phorkie / Tools.php
1 <?php
2 namespace phorkie;
3
4
5 class Tools
6 {
7     public static function recursiveDelete($path)
8     {
9         if (!is_dir($path) || is_link($path)) {
10             return unlink($path);
11         }
12         foreach (scandir($path) as $file) {
13             if ($file == '.' || $file == '..') {
14                 continue;
15             }
16             $filepath = $path . DIRECTORY_SEPARATOR . $file;
17             if (!static::recursiveDelete($filepath)) {
18                 return false;
19             };
20         }
21         return rmdir($path);
22     }
23
24     /**
25      * Create a full URL with protocol and host name
26      *
27      * @param string $path Path to the file, with leading /
28      *
29      * @return string Full URL
30      */
31     public static function fullUrl($path)
32     {
33         if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) {
34             $prot = 'https';
35         } else {
36             $prot = 'http';
37         }
38         return $prot . '://' . $_SERVER['HTTP_HOST'] . $path;
39     }
40
41     /**
42      * Removes malicious parts from a file name
43      *
44      * @param string $file File name from the user
45      *
46      * @return string Fixed and probably secure filename
47      */
48     public static function sanitizeFilename($file)
49     {
50         $file = trim($file);
51         $file = str_replace(array('\\', '//'), '/', $file);
52         $file = str_replace('/../', '/', $file);
53         if (substr($file, 0, 3) == '../') {
54             $file = substr($file, 3);
55         }
56         if (substr($file, 0, 1) == '../') {
57             $file = substr($file, 1);
58         }
59
60         return $file;
61     }
62
63 }
64
65 ?>