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