Merge remote-tracking branch 'origin/master'
[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 (!file_exists($path)) {
17             return true;
18         }
19         if (!is_dir($path) || is_link($path)) {
20             return unlink($path);
21         }
22         foreach (scandir($path) as $file) {
23             if ($file == '.' || $file == '..') {
24                 continue;
25             }
26             $filepath = $path . DIRECTORY_SEPARATOR . $file;
27             if (!static::recursiveDelete($filepath)) {
28                 return false;
29             };
30         }
31         return rmdir($path);
32     }
33
34     /**
35      * Create a full URL with protocol and host name
36      *
37      * @param string $path Path to the file, with leading /
38      *
39      * @return string Full URL
40      */
41     public static function fullUrl($path = '')
42     {
43         if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) {
44             $prot = 'https';
45         } else {
46             $prot = 'http';
47         }
48         return $prot . '://' . $_SERVER['HTTP_HOST'] . $GLOBALS['phorkie']['cfg']['baseurl'] . $path;
49     }
50
51     /**
52      * Removes malicious parts from a file name
53      *
54      * @param string $file File name from the user
55      *
56      * @return string Fixed and probably secure filename
57      */
58     public static function sanitizeFilename($file)
59     {
60         $file = trim($file);
61         $file = str_replace(array('\\', '//'), '/', $file);
62         $file = str_replace('/../', '/', $file);
63         if (substr($file, 0, 3) == '../') {
64             $file = substr($file, 3);
65         }
66         if (substr($file, 0, 1) == '../') {
67             $file = substr($file, 1);
68         }
69
70         return $file;
71     }
72
73
74     public static function detectBaseUrl()
75     {
76         if (!isset($_SERVER['REQUEST_URI'])
77             || !isset($_SERVER['SCRIPT_NAME'])
78         ) {
79             return '/';
80         }
81
82         $scriptName = $_SERVER['SCRIPT_NAME'];
83         $requestUri = $_SERVER['REQUEST_URI'];
84         if (substr($scriptName, -4) != '.php') {
85             //a phar
86             return $scriptName . '/';
87         }
88
89         if (substr($requestUri, -4) != '.php') {
90             $requestUri .= '.php';
91         }
92         $snl = strlen($scriptName);
93         if (substr($requestUri, -$snl) == $scriptName) {
94             return substr($requestUri, 0, -$snl) . '/';
95         }
96
97         return '/';
98     }
99 }
100 ?>