5f79555650c9f0babfe3cd616be04ec12de79fb9
[civicrm-core.git] / Civi / Core / AssetBuilder.php
1 <?php
2
3 namespace Civi\Core;
4
5 use Civi\Core\Exception\UnknownAssetException;
6
7 /**
8 * Class AssetBuilder
9 * @package Civi\Core
10 *
11 * The AssetBuilder is used to manage semi-dynamic assets.
12 * In normal production use, these assets are built on first
13 * reference and then stored in a public-facing cache folder.
14 * (In debug mode, these assets are constructed during every request.)
15 *
16 * There are generally two aspects to usage -- creating a URL
17 * for the asset, and defining the content of the asset.
18 *
19 * For example, suppose we wanted to define a static file
20 * named "api-fields.json" which lists all the fields of
21 * all the API entities.
22 *
23 * @code
24 * // Build a URL to `api-fields.json`.
25 * $url = \Civi::service('asset_builder')->getUrl('api-fields.json');
26 *
27 * // Define the content of `api-fields.json`.
28 * function hook_civicrm_buildAsset($asset, $params, &$mimeType, &$content) {
29 * if ($asset !== 'api-fields.json') return;
30 *
31 * $entities = civicrm_api3('Entity', 'get', array());
32 * $fields = array();
33 * foreach ($entities['values'] as $entity) {
34 * $fields[$entity] = civicrm_api3($entity, 'getfields');
35 * }
36 *
37 * $mimeType = 'application/json';
38 * $content = json_encode($fields);
39 * }
40 * @endCode
41 *
42 * Assets can be parameterized. Each combination of ($asset,$params)
43 * will be cached separately. For example, we might want a copy of
44 * 'api-fields.json' which only includes a handful of chosen entities.
45 * Simply pass the chosen entities into `getUrl()`, then update
46 * the definition to use `$params['entities']`, as in:
47 *
48 * @code
49 * // Build a URL to `api-fields.json`.
50 * $url = \Civi::service('asset_builder')->getUrl('api-fields.json', array(
51 * 'entities' => array('Contact', 'Phone', 'Email', 'Address'),
52 * ));
53 *
54 * // Define the content of `api-fields.json`.
55 * function hook_civicrm_buildAsset($asset, $params, &$mimeType, &$content) {
56 * if ($asset !== 'api-fields.json') return;
57 *
58 * $fields = array();
59 * foreach ($params['entities'] as $entity) {
60 * $fields[$entity] = civicrm_api3($entity, 'getfields');
61 * }
62 *
63 * $mimeType = 'application/json';
64 * $content = json_encode($fields);
65 * }
66 * @endCode
67 *
68 * Note: These assets are designed to hold non-sensitive data, such as
69 * aggregated JS or common metadata. There probably are ways to
70 * secure it (e.g. alternative digest() calculations), but the
71 * current implementation is KISS.
72 */
73 class AssetBuilder {
74
75 /**
76 * @return array
77 * Array(string $value => string $label).
78 */
79 public static function getCacheModes() {
80 return array(
81 '0' => ts('Disable'),
82 '1' => ts('Enable'),
83 'auto' => ts('Auto'),
84 );
85 }
86
87 protected $cacheEnabled;
88
89 /**
90 * AssetBuilder constructor.
91 * @param $cacheEnabled
92 */
93 public function __construct($cacheEnabled = NULL) {
94 if ($cacheEnabled === NULL) {
95 $cacheEnabled = \Civi::settings()->get('assetCache');
96 if ($cacheEnabled === 'auto') {
97 $cacheEnabled = !\CRM_Core_Config::singleton()->debug;
98 }
99 $cacheEnabled = (bool) $cacheEnabled;
100 }
101 $this->cacheEnabled = $cacheEnabled;
102 }
103
104 /**
105 * Determine if $name is a well-formed asset name.
106 *
107 * @param string $name
108 * @return bool
109 */
110 public function isValidName($name) {
111 return preg_match(';^[a-zA-Z0-9\.\-_/]+$;', $name)
112 && strpos($name, '..') === FALSE
113 && strpos($name, '.') !== FALSE;
114 }
115
116 /**
117 * @param string $name
118 * Ex: 'angular.json'.
119 * @param array $params
120 * @return string
121 * URL.
122 * Ex: 'http://example.org/files/civicrm/dyn/angular.abcd1234abcd1234.json'.
123 */
124 public function getUrl($name, $params = array()) {
125 if (!$this->isValidName($name)) {
126 throw new \RuntimeException("Invalid dynamic asset name");
127 }
128
129 if ($this->isCacheEnabled()) {
130 $fileName = $this->build($name, $params);
131 return $this->getCacheUrl($fileName);
132 }
133 else {
134 return \CRM_Utils_System::url('civicrm/asset/builder', array(
135 'an' => $name,
136 'ap' => $this->encode($params),
137 'ad' => $this->digest($name, $params),
138 ), TRUE, NULL, FALSE);
139 }
140 }
141
142 /**
143 * @param string $name
144 * Ex: 'angular.json'.
145 * @param array $params
146 * @return string
147 * URL.
148 * Ex: '/var/www/files/civicrm/dyn/angular.abcd1234abcd1234.json'.
149 */
150 public function getPath($name, $params = array()) {
151 if (!$this->isValidName($name)) {
152 throw new \RuntimeException("Invalid dynamic asset name");
153 }
154
155 $fileName = $this->build($name, $params);
156 return $this->getCachePath($fileName);
157 }
158
159 /**
160 * Build the cached copy of an $asset.
161 *
162 * @param string $name
163 * Ex: 'angular.json'.
164 * @param array $params
165 * @param bool $force
166 * Build the asset anew, even if it already exists.
167 * @return string
168 * File name (relative to cache folder).
169 * Ex: 'angular.abcd1234abcd1234.json'.
170 * @throws UnknownAssetException
171 */
172 public function build($name, $params, $force = FALSE) {
173 if (!$this->isValidName($name)) {
174 throw new UnknownAssetException("Asset name is malformed");
175 }
176 $nameParts = explode('.', $name);
177 array_splice($nameParts, -1, 0, array($this->digest($name, $params)));
178 $fileName = implode('.', $nameParts);
179 if ($force || !file_exists($this->getCachePath($fileName))) {
180 // No file locking, but concurrent writers should produce
181 // the same data, so we'll just plow ahead.
182
183 if (!file_exists($this->getCachePath())) {
184 mkdir($this->getCachePath());
185 }
186
187 $rendered = $this->render($name, $params);
188 file_put_contents($this->getCachePath($fileName), $rendered['content']);
189 return $fileName;
190 }
191 return $fileName;
192 }
193
194 /**
195 * Generate the content for a dynamic asset.
196 *
197 * @param string $name
198 * @param array $params
199 * @return array
200 * Array with keys:
201 * - statusCode: int, ex: 200.
202 * - mimeType: string, ex: 'text/html'.
203 * - content: string, ex: '<body>Hello world</body>'.
204 * @throws \CRM_Core_Exception
205 */
206 public function render($name, $params = array()) {
207 if (!$this->isValidName($name)) {
208 throw new UnknownAssetException("Asset name is malformed");
209 }
210 \CRM_Utils_Hook::buildAsset($name, $params, $mimeType, $content);
211 if ($mimeType === NULL && $content === NULL) {
212 throw new UnknownAssetException("Unrecognized asset name: $name");
213 }
214 // Beg your pardon, sir. Please may I have an HTTP response class instead?
215 return array(
216 'statusCode' => 200,
217 'mimeType' => $mimeType,
218 'content' => $content,
219 );
220 }
221
222 /**
223 * Clear out any cache files.
224 */
225 public function clear() {
226 \CRM_Utils_File::cleanDir($this->getCachePath());
227 }
228
229 /**
230 * Determine the local path of a cache file.
231 *
232 * @param string|NULL $fileName
233 * Ex: 'angular.abcd1234abcd1234.json'.
234 * @return string
235 * URL.
236 * Ex: '/var/www/files/civicrm/dyn/angular.abcd1234abcd1234.json'.
237 */
238 protected function getCachePath($fileName = NULL) {
239 // imageUploadDir has the correct functional properties but a wonky name.
240 $suffix = ($fileName === NULL) ? '' : (DIRECTORY_SEPARATOR . $fileName);
241 return
242 \CRM_Utils_File::addTrailingSlash(\CRM_Core_Config::singleton()->imageUploadDir)
243 . 'dyn' . $suffix;
244 }
245
246 /**
247 * Determine the URL of a cache file.
248 *
249 * @param string|NULL $fileName
250 * Ex: 'angular.abcd1234abcd1234.json'.
251 * @return string
252 * URL.
253 * Ex: 'http://example.org/files/civicrm/dyn/angular.abcd1234abcd1234.json'.
254 */
255 protected function getCacheUrl($fileName = NULL) {
256 // imageUploadURL has the correct functional properties but a wonky name.
257 $suffix = ($fileName === NULL) ? '' : ('/' . $fileName);
258 return
259 \CRM_Utils_File::addTrailingSlash(\CRM_Core_Config::singleton()->imageUploadURL, '/')
260 . 'dyn' . $suffix;
261 }
262
263 /**
264 * Create a unique identifier for the $params.
265 *
266 * This identifier is designed to avoid accidental cache collisions.
267 *
268 * @param string $name
269 * @param array $params
270 * @return string
271 */
272 protected function digest($name, $params) {
273 // WISHLIST: For secure digest, generate+persist privatekey & call hash_hmac.
274 ksort($params);
275 $digest = md5(
276 $name .
277 \CRM_Core_Resources::singleton()->getCacheCode() .
278 \CRM_Core_Config_Runtime::getId() .
279 json_encode($params)
280 );
281 return $digest;
282 }
283
284 /**
285 * Encode $params in a format that's optimized for shorter URLs.
286 *
287 * @param array $params
288 * @return string
289 */
290 protected function encode($params) {
291 if (empty($params)) {
292 return '';
293 }
294
295 $str = json_encode($params);
296 if (function_exists('gzdeflate')) {
297 $str = gzdeflate($str);
298 }
299 return base64_encode($str);
300 }
301
302 /**
303 * @param string $str
304 * @return array
305 */
306 protected function decode($str) {
307 if ($str === NULL || $str === FALSE || $str === '') {
308 return array();
309 }
310
311 $str = base64_decode($str);
312 if (function_exists('gzdeflate')) {
313 $str = gzinflate($str);
314 }
315 return json_decode($str, TRUE);
316 }
317
318 /**
319 * @return bool
320 */
321 public function isCacheEnabled() {
322 return $this->cacheEnabled;
323 }
324
325 /**
326 * @param bool|null $cacheEnabled
327 * @return AssetBuilder
328 */
329 public function setCacheEnabled($cacheEnabled) {
330 $this->cacheEnabled = $cacheEnabled;
331 return $this;
332 }
333
334 /**
335 * (INTERNAL ONLY)
336 *
337 * Execute a page-request for `civicrm/asset/builder`.
338 */
339 public static function pageRun() {
340 // Beg your pardon, sir. Please may I have an HTTP response class instead?
341 $asset = self::pageRender($_GET);
342 if (function_exists('http_response_code')) {
343 // PHP 5.4+
344 http_response_code($asset['statusCode']);
345 }
346 else {
347 header('X-PHP-Response-Code: ' . $asset['statusCode'], TRUE, $asset['statusCode']);
348 }
349
350 header('Content-Type: ' . $asset['mimeType']);
351 echo $asset['content'];
352 \CRM_Utils_System::civiExit();
353 }
354
355 /**
356 * (INTERNAL ONLY)
357 *
358 * Execute a page-request for `civicrm/asset/builder`.
359 *
360 * @param array $get
361 * The _GET values.
362 * @return array
363 * Array with keys:
364 * - statusCode: int, ex 200.
365 * - mimeType: string, ex 'text/html'.
366 * - content: string, ex '<body>Hello world</body>'.
367 */
368 public static function pageRender($get) {
369 // Beg your pardon, sir. Please may I have an HTTP response class instead?
370 try {
371 $assets = \Civi::service('asset_builder');
372 return $assets->render($get['an'], $assets->decode($get['ap']));
373 }
374 catch (UnknownAssetException $e) {
375 return array(
376 'statusCode' => 404,
377 'mimeType' => 'text/plain',
378 'content' => $e->getMessage(),
379 );
380 }
381 }
382
383 }