8 * This paths class translates path-expressions into local file paths and
9 * URLs. Path-expressions may take a few forms:
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]).
18 const DEFAULT_URL
= 'cms.root';
19 const DEFAULT_PATH
= 'civicrm.files';
23 * Array(string $name => array(url => $, path => $)).
25 private $variables = [];
27 private $variableFactory = [];
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`)
38 ->register('civicrm.root', function () {
39 return \CRM_Core_Config
::singleton()->userSystem
->getCiviSourceStorage();
41 ->register('civicrm.packages', function () {
43 'path' => \Civi
::paths()->getPath('[civicrm.root]/packages/'),
44 'url' => \Civi
::paths()->getUrl('[civicrm.root]/packages/', 'absolute'),
47 ->register('civicrm.vendor', function () {
49 'path' => \Civi
::paths()->getPath('[civicrm.root]/vendor/'),
50 'url' => \Civi
::paths()->getUrl('[civicrm.root]/vendor/', 'absolute'),
53 ->register('civicrm.bower', function () {
55 'path' => \Civi
::paths()->getPath('[civicrm.root]/bower_components/'),
56 'url' => \Civi
::paths()->getUrl('[civicrm.root]/bower_components/', 'absolute'),
59 ->register('civicrm.files', function () {
60 return \CRM_Core_Config
::singleton()->userSystem
->getDefaultFileStorage();
62 ->register('civicrm.private', function () {
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(),
71 ->register('civicrm.log', function () {
73 'path' => \Civi
::paths()->getPath('[civicrm.private]/ConfigAndLog'),
76 ->register('civicrm.compile', function () {
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'),
84 ->register('civicrm.l10n', function () {
85 $dir = defined('CIVICRM_L10N_BASEDIR') ? CIVICRM_L10N_BASEDIR
: \Civi
::paths()->getPath('[civicrm.private]/l10n');
87 'path' => is_dir($dir) ?
$dir : \Civi
::paths()->getPath('[civicrm.root]/l10n'),
90 ->register('cms', function () {
92 'path' => \CRM_Core_Config
::singleton()->userSystem
->cmsRootPath(),
93 'url' => \CRM_Utils_System
::baseCMSURL(),
96 ->register('cms.root', function () {
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),
106 * Register a new URL/file path mapping.
108 * @param string $name
109 * The name of the variable.
110 * @param callable $factory
111 * Function which returns an array with keys:
116 public function register($name, $factory) {
117 $this->variableFactory
[$name] = $factory;
122 * @param string $name
123 * Ex: 'civicrm.root'.
124 * @param string $attr
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]);
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);
139 if (!isset($this->variables
[$name][$attr])) {
140 throw new \
RuntimeException("Cannot resolve path using \"$name.$attr\"");
142 return $this->variables
[$name][$attr];
147 * Ex: 'https://example.com:8000/foobar' or '/foobar'
149 * Ex: 'civicrm.root' or 'civicrm.packages'
152 private function toAbsoluteUrl($url, $for) {
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');
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] !== '/')
167 : (parse_url($cmsUrl, PHP_URL_SCHEME
) . ':');
168 return $prefix . $url;
171 // Assume this is an absolute URL, as in the past ('_h_ttp://').
177 * Does the variable exist.
179 * @param string $name
183 public function hasVariable($name) {
184 return isset($this->variableFactory
[$name]);
188 * Determine the absolute path to a file, given that the file is most likely
189 * in a given particular variable.
191 * @param string $value
193 * Use "." to reference to default file root.
194 * Values may begin with a variable, e.g. "[civicrm.files]/upload".
195 * @return mixed|string
197 public function getPath($value) {
198 if ($value === NULL ||
$value === FALSE ||
$value === '') {
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];
208 $isDot = $value === '.';
213 $result = \CRM_Utils_File
::absoluteDirectory($value, $this->getVariable($defaultContainer, 'path'));
214 return $isDot ?
rtrim($result, '/' . DIRECTORY_SEPARATOR
) : $result;
218 * Determine the URL to a file.
220 * @param string $value
221 * The file path. The path may begin with a variable, e.g. "[civicrm.files]/upload".
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:
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.
240 public function getUrl($value, $preferFormat = 'relative', $ssl = NULL) {
241 if ($value === NULL ||
$value === FALSE ||
$value === '') {
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];
251 $isDot = $value === '.';
252 if (substr($value, 0, 5) === 'http:' ||
substr($value, 0, 6) === 'https:') {
256 $value = rtrim($this->getVariable($defaultContainer, 'url'), '/') . ($isDot ?
'' : "/$value");
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'];
265 if ($ssl ||
($ssl === NULL && \CRM_Utils_System
::isSSL())) {
266 $value = str_replace('http://', 'https://', $value);