]> git.mxchange.org Git - friendica.git/blob - src/Util/BasePath.php
06fa5246797028fb1bbee1dc75a5b7184db7726c
[friendica.git] / src / Util / BasePath.php
1 <?php
2
3 namespace Friendica\Util;
4
5 class BasePath
6 {
7         /**
8          * @var string
9          */
10         private $baseDir;
11         /**
12          * @var array
13          */
14         private $server;
15
16         /**
17          * @param string|null $baseDir The default base path
18          * @param array       $server  server arguments
19          */
20         public function __construct(string $baseDir, array $server = [])
21         {
22                 $this->baseDir = $baseDir;
23                 $this->server = $server;
24         }
25
26         /**
27          * @brief Returns the base filesystem path of the App
28          *
29          * It first checks for the internal variable, then for DOCUMENT_ROOT and
30          * finally for PWD
31          *
32          * @return string
33          *
34          * @throws \Exception if directory isn't usable
35          */
36         public function getPath()
37         {
38                 $baseDir = $this->baseDir;
39                 $server = $this->server;
40
41                 if ((!$baseDir || !is_dir($baseDir)) && !empty($server['DOCUMENT_ROOT'])) {
42                         $baseDir = $server['DOCUMENT_ROOT'];
43                 }
44
45                 if ((!$baseDir || !is_dir($baseDir)) && !empty($server['PWD'])) {
46                         $baseDir = $server['PWD'];
47                 }
48
49                 $baseDir = self::getRealPath($baseDir);
50
51                 if (!is_dir($baseDir)) {
52                         throw new \Exception(sprintf('\'%s\' is not a valid basepath', $baseDir));
53                 }
54
55                 return $baseDir;
56         }
57
58         /**
59          * @brief Returns a normalized file path
60          *
61          * This is a wrapper for the "realpath" function.
62          * That function cannot detect the real path when some folders aren't readable.
63          * Since this could happen with some hosters we need to handle this.
64          *
65          * @param string $path The path that is about to be normalized
66          * @return string normalized path - when possible
67          */
68         public static function getRealPath($path)
69         {
70                 $normalized = realpath($path);
71
72                 if (!is_bool($normalized)) {
73                         return $normalized;
74                 } else {
75                         return $path;
76                 }
77         }
78 }