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