Merge pull request #17513 from JMAConsulting/core-1795
[civicrm-core.git] / Civi / Core / Paths.php
1 <?php
2 namespace Civi\Core;
3
4 /**
5 * Class Paths
6 * @package Civi\Core
7 *
8 * This paths class translates path-expressions into local file paths and
9 * URLs. Path-expressions may take a few forms:
10 *
11 * - Paths and URLs may use a variable prefix. For example, '[civicrm.files]/upload'
12 * - Paths and URLS may be absolute.
13 * - Paths may be relative (base dir: [civicrm.files]).
14 * - URLs may be relative (base dir: [cms.root]).
15 */
16 class Paths {
17
18 const DEFAULT_URL = 'cms.root';
19 const DEFAULT_PATH = 'civicrm.files';
20
21 /**
22 * @var array
23 * Array(string $name => array(url => $, path => $)).
24 */
25 private $variables = [];
26
27 private $variableFactory = [];
28
29 /**
30 * Class constructor.
31 */
32 public function __construct() {
33 // Below is a *default* set of functions to calculate paths/URLs.
34 // Some variables may be overridden as follow:
35 // - The global `$civicrm_paths` may be preset before Civi boots. (Ex: via `civicrm.settings.php`, `settings.php`, or `vendor/autoload.php`)
36 // - Variables may be re-registered. (Ex: via `CRM_Utils_System_WordPress`)
37 $this
38 ->register('civicrm.root', function () {
39 return \CRM_Core_Config::singleton()->userSystem->getCiviSourceStorage();
40 })
41 ->register('civicrm.packages', function () {
42 return [
43 'path' => \Civi::paths()->getPath('[civicrm.root]/packages/'),
44 'url' => \Civi::paths()->getUrl('[civicrm.root]/packages/', 'absolute'),
45 ];
46 })
47 ->register('civicrm.vendor', function () {
48 return [
49 'path' => \Civi::paths()->getPath('[civicrm.root]/vendor/'),
50 'url' => \Civi::paths()->getUrl('[civicrm.root]/vendor/', 'absolute'),
51 ];
52 })
53 ->register('civicrm.bower', function () {
54 return [
55 'path' => \Civi::paths()->getPath('[civicrm.root]/bower_components/'),
56 'url' => \Civi::paths()->getUrl('[civicrm.root]/bower_components/', 'absolute'),
57 ];
58 })
59 ->register('civicrm.files', function () {
60 return \CRM_Core_Config::singleton()->userSystem->getDefaultFileStorage();
61 })
62 ->register('civicrm.private', function () {
63 return [
64 // For backward compatibility with existing deployments, this
65 // effectively returns `dirname(CIVICRM_TEMPLATE_COMPILEDIR)`.
66 // That's confusing. Future installers should probably set `civicrm.private`
67 // explicitly instead of setting `CIVICRM_TEMPLATE_COMPILEDIR`.
68 'path' => \CRM_Utils_File::baseFilePath(),
69 ];
70 })
71 ->register('civicrm.log', function () {
72 return [
73 'path' => \Civi::paths()->getPath('[civicrm.private]/ConfigAndLog'),
74 ];
75 })
76 ->register('civicrm.compile', function () {
77 return [
78 // These two formulations are equivalent in typical deployments; however,
79 // for existing systems which previously customized CIVICRM_TEMPLATE_COMPILEDIR,
80 // using the constant should be more backward-compatibility.
81 'path' => defined('CIVICRM_TEMPLATE_COMPILEDIR') ? CIVICRM_TEMPLATE_COMPILEDIR : \Civi::paths()->getPath('[civicrm.private]/templates_c'),
82 ];
83 })
84 ->register('civicrm.l10n', function () {
85 $dir = defined('CIVICRM_L10N_BASEDIR') ? CIVICRM_L10N_BASEDIR : \Civi::paths()->getPath('[civicrm.private]/l10n');
86 return [
87 'path' => is_dir($dir) ? $dir : \Civi::paths()->getPath('[civicrm.root]/l10n'),
88 ];
89 })
90 ->register('cms', function () {
91 return [
92 'path' => \CRM_Core_Config::singleton()->userSystem->cmsRootPath(),
93 'url' => \CRM_Utils_System::baseCMSURL(),
94 ];
95 })
96 ->register('cms.root', function () {
97 return [
98 'path' => \CRM_Core_Config::singleton()->userSystem->cmsRootPath(),
99 // Misleading: this *removes* the language part of the URL, producing a pristine base URL.
100 'url' => \CRM_Utils_System::languageNegotiationURL(\CRM_Utils_System::baseCMSURL(), FALSE, TRUE),
101 ];
102 });
103 }
104
105 /**
106 * Register a new URL/file path mapping.
107 *
108 * @param string $name
109 * The name of the variable.
110 * @param callable $factory
111 * Function which returns an array with keys:
112 * - path: string.
113 * - url: string.
114 * @return Paths
115 */
116 public function register($name, $factory) {
117 $this->variableFactory[$name] = $factory;
118 return $this;
119 }
120
121 /**
122 * @param string $name
123 * Ex: 'civicrm.root'.
124 * @param string $attr
125 * Ex: 'url', 'path'.
126 * @return mixed
127 */
128 public function getVariable($name, $attr) {
129 if (!isset($this->variables[$name])) {
130 $this->variables[$name] = call_user_func($this->variableFactory[$name]);
131 if (isset($GLOBALS['civicrm_paths'][$name])) {
132 $this->variables[$name] = array_merge($this->variables[$name], $GLOBALS['civicrm_paths'][$name]);
133 }
134 if (isset($this->variables[$name]['url'])) {
135 // Typical behavior is to return an absolute URL. If an admin has put an override that's site-relative, then convert.
136 $this->variables[$name]['url'] = $this->toAbsoluteUrl($this->variables[$name]['url'], $name);
137 }
138 }
139 if (!isset($this->variables[$name][$attr])) {
140 throw new \RuntimeException("Cannot resolve path using \"$name.$attr\"");
141 }
142 return $this->variables[$name][$attr];
143 }
144
145 /**
146 * @param string $url
147 * Ex: 'https://example.com:8000/foobar' or '/foobar'
148 * @param string $for
149 * Ex: 'civicrm.root' or 'civicrm.packages'
150 * @return string
151 */
152 private function toAbsoluteUrl($url, $for) {
153 if (!$url) {
154 return $url;
155 }
156 elseif ($url[0] === '/') {
157 // Relative URL interpretation
158 if ($for === 'cms.root') {
159 throw new \RuntimeException('Invalid configuration: the [cms.root] path must be an absolute URL');
160 }
161 $cmsUrl = rtrim($this->getVariable('cms.root', 'url'), '/');
162 // The norms for relative URLs dictate:
163 // Single-slash: "/sub/dir" or "/" (domain-relative)
164 // Double-slash: "//example.com/sub/dir" (same-scheme)
165 $prefix = ($url === '/' || $url[1] !== '/')
166 ? $cmsUrl
167 : (parse_url($cmsUrl, PHP_URL_SCHEME) . ':');
168 return $prefix . $url;
169 }
170 else {
171 // Assume this is an absolute URL, as in the past ('_h_ttp://').
172 return $url;
173 }
174 }
175
176 /**
177 * Does the variable exist.
178 *
179 * @param string $name
180 *
181 * @return bool
182 */
183 public function hasVariable($name) {
184 return isset($this->variableFactory[$name]);
185 }
186
187 /**
188 * Determine the absolute path to a file, given that the file is most likely
189 * in a given particular variable.
190 *
191 * @param string $value
192 * The file path.
193 * Use "." to reference to default file root.
194 * Values may begin with a variable, e.g. "[civicrm.files]/upload".
195 * @return mixed|string
196 */
197 public function getPath($value) {
198 if ($value === NULL || $value === FALSE || $value === '') {
199 return FALSE;
200 }
201
202 $defaultContainer = self::DEFAULT_PATH;
203 if ($value && $value{0} == '[' && preg_match(';^\[([a-zA-Z0-9\._]+)\]/(.*);', $value, $matches)) {
204 $defaultContainer = $matches[1];
205 $value = $matches[2];
206 }
207
208 $isDot = $value === '.';
209 if ($isDot) {
210 $value = '';
211 }
212
213 $result = \CRM_Utils_File::absoluteDirectory($value, $this->getVariable($defaultContainer, 'path'));
214 return $isDot ? rtrim($result, '/' . DIRECTORY_SEPARATOR) : $result;
215 }
216
217 /**
218 * Determine the URL to a file.
219 *
220 * @param string $value
221 * The file path. The path may begin with a variable, e.g. "[civicrm.files]/upload".
222 *
223 * This function was designed for locating files under a given tree, and the
224 * the result for a straight variable expressions ("[foo.bar]") was not
225 * originally defined. You may wish to use one of these:
226 *
227 * - getVariable('foo.bar', 'url') => Lookup variable by itself
228 * - getUrl('[foo.bar]/') => Get the variable (normalized with a trailing "/").
229 * - getUrl('[foo.bar]/.') => Get the variable (normalized without a trailing "/").
230 * @param string $preferFormat
231 * The preferred format ('absolute', 'relative').
232 * The result data may not meet the preference -- if the setting
233 * refers to an external domain, then the result will be
234 * absolute (regardless of preference).
235 * @param bool|NULL $ssl
236 * NULL to autodetect. TRUE to force to SSL.
237 * @return FALSE|string
238 * The URL for $value (string), or FALSE if the $value is not specified.
239 */
240 public function getUrl($value, $preferFormat = 'relative', $ssl = NULL) {
241 if ($value === NULL || $value === FALSE || $value === '') {
242 return FALSE;
243 }
244
245 $defaultContainer = self::DEFAULT_URL;
246 if ($value && $value{0} == '[' && preg_match(';^\[([a-zA-Z0-9\._]+)\](/(.*))$;', $value, $matches)) {
247 $defaultContainer = $matches[1];
248 $value = $matches[3];
249 }
250
251 $isDot = $value === '.';
252 if (substr($value, 0, 5) === 'http:' || substr($value, 0, 6) === 'https:') {
253 return $value;
254 }
255
256 $value = rtrim($this->getVariable($defaultContainer, 'url'), '/') . ($isDot ? '' : "/$value");
257
258 if ($preferFormat === 'relative') {
259 $parsed = parse_url($value);
260 if (isset($_SERVER['HTTP_HOST']) && isset($parsed['host']) && $_SERVER['HTTP_HOST'] == $parsed['host']) {
261 $value = $parsed['path'];
262 }
263 }
264
265 if ($ssl || ($ssl === NULL && \CRM_Utils_System::isSSL())) {
266 $value = str_replace('http://', 'https://', $value);
267 }
268
269 return $value;
270 }
271
272 }