Merge pull request #6798 from eileenmcnaughton/master
[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 = array();
26
27 private $variableFactory = array();
28
29 public function __construct() {
30 $this
31 ->register('civicrm.root', function () {
32 return \CRM_Core_Config::singleton()->userSystem->getCiviSourceStorage();
33 })
34 ->register('civicrm.files', function () {
35 return \CRM_Core_Config::singleton()->userSystem->getDefaultFileStorage();
36 })
37 ->register('cms', function () {
38 return array(
39 'path' => \CRM_Core_Config::singleton()->userSystem->cmsRootPath(),
40 'url' => \CRM_Utils_System::baseCMSURL(),
41 );
42 })
43 ->register('cms.root', function () {
44 return array(
45 'path' => \CRM_Core_Config::singleton()->userSystem->cmsRootPath(),
46 // Misleading: this *removes* the language part of the URL, producing a pristine base URL.
47 'url' => \CRM_Utils_System::languageNegotiationURL(\CRM_Utils_System::baseCMSURL(), FALSE, TRUE),
48 );
49 });
50 }
51
52 /**
53 * Register a new URL/file path mapping.
54 *
55 * @param string $name
56 * The name of the variable.
57 * @param callable $factory
58 * Function which returns an array with keys:
59 * - path: string.
60 * - url: string.
61 * @return $this
62 */
63 public function register($name, $factory) {
64 $this->variableFactory[$name] = $factory;
65 return $this;
66 }
67
68 /**
69 * @param string $name
70 * Ex: 'civicrm.root'.
71 * @param string $attr
72 * Ex: 'url', 'path'.
73 * @return mixed
74 */
75 public function getVariable($name, $attr) {
76 if (!isset($this->variables[$name])) {
77 $this->variables[$name] = call_user_func($this->variableFactory[$name]);
78 }
79 if (!isset($this->variables[$name][$attr])) {
80 throw new \RuntimeException("Cannot resolve path using \"$name.$attr\"");
81 }
82 return $this->variables[$name][$attr];
83 }
84
85 public function hasVariable($name) {
86 return isset($this->variableFactory[$name]);
87 }
88
89 /**
90 * Determine the absolute path to a file, given that the file is most likely
91 * in a given particular variable.
92 *
93 * @param string $value
94 * The file path.
95 * Use "." to reference to default file root.
96 * Values may begin with a variable, e.g. "[civicrm.files]/upload".
97 * @return mixed|string
98 */
99 public function getPath($value) {
100 $defaultContainer = self::DEFAULT_PATH;
101 if ($value && $value{0} == '[' && preg_match(';^\[([a-zA-Z0-9\._]+)\]/(.*);', $value, $matches)) {
102 $defaultContainer = $matches[1];
103 $value = $matches[2];
104 }
105 if (empty($value)) {
106 return FALSE;
107 }
108 if ($value === '.') {
109 $value = '';
110 }
111 return \CRM_Utils_File::absoluteDirectory($value, $this->getVariable($defaultContainer, 'path'));
112 }
113
114 /**
115 * Determine the URL to a file.
116 *
117 * @param string $value
118 * The file path. The path may begin with a variable, e.g. "[civicrm.files]/upload".
119 * @param string $preferFormat
120 * The preferred format ('absolute', 'relative').
121 * The result data may not meet the preference -- if the setting
122 * refers to an external domain, then the result will be
123 * absolute (regardless of preference).
124 * @param bool|NULL $ssl
125 * NULL to autodetect. TRUE to force to SSL.
126 * @return mixed|string
127 */
128 public function getUrl($value, $preferFormat = 'relative', $ssl = NULL) {
129 $defaultContainer = self::DEFAULT_URL;
130 if ($value && $value{0} == '[' && preg_match(';^\[([a-zA-Z0-9\._]+)\](/(.*))$;', $value, $matches)) {
131 $defaultContainer = $matches[1];
132 $value = empty($matches[3]) ? '.' : $matches[3];
133 }
134
135 if (empty($value)) {
136 return FALSE;
137 }
138 if ($value === '.') {
139 $value = '';
140 }
141 if (substr($value, 0, 4) == 'http') {
142 return $value;
143 }
144
145 $value = $this->getVariable($defaultContainer, 'url') . $value;
146
147 if ($preferFormat === 'relative') {
148 $parsed = parse_url($value);
149 if (isset($_SERVER['HTTP_HOST']) && isset($parsed['host']) && $_SERVER['HTTP_HOST'] == $parsed['host']) {
150 $value = $parsed['path'];
151 }
152 }
153
154 if ($ssl || ($ssl === NULL && \CRM_Utils_System::isSSL())) {
155 $value = str_replace('http://', 'https://', $value);
156 }
157
158 return $value;
159 }
160
161 }