Merge pull request #17733 from eileenmcnaughton/pvv
[civicrm-core.git] / CRM / Utils / JS.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Parse Javascript content and extract translatable strings.
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18 class CRM_Utils_JS {
19
20 /**
21 * Parse a javascript file for translatable strings.
22 *
23 * @param string $jsCode
24 * Raw Javascript code.
25 * @return array
26 * Array of translatable strings
27 */
28 public static function parseStrings($jsCode) {
29 $strings = [];
30 // Match all calls to ts() in an array.
31 // Note: \s also matches newlines with the 's' modifier.
32 preg_match_all('~
33 [^\w]ts\s* # match "ts" with whitespace
34 \(\s* # match "(" argument list start
35 ((?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+)\s*
36 [,\)] # match ")" or "," to finish
37 ~sx', $jsCode, $matches);
38 foreach ($matches[1] as $text) {
39 $quote = $text[0];
40 // Remove newlines
41 $text = str_replace("\\\n", '', $text);
42 // Unescape escaped quotes
43 $text = str_replace('\\' . $quote, $quote, $text);
44 // Remove end quotes
45 $text = substr(ltrim($text, $quote), 0, -1);
46 $strings[$text] = $text;
47 }
48 return array_values($strings);
49 }
50
51 /**
52 * Identify duplicate, adjacent, identical closures and consolidate them.
53 *
54 * Note that you can only dedupe closures if they are directly adjacent and
55 * have exactly the same parameters.
56 *
57 * Also dedupes the "use strict" directive as it is only meaningful at the beginning of a closure.
58 *
59 * @param array $scripts
60 * Javascript source.
61 * @param array $localVars
62 * Ordered list of JS vars to identify the start of a closure.
63 * @param array $inputVals
64 * Ordered list of input values passed into the closure.
65 * @return string[]
66 * Javascript source.
67 */
68 public static function dedupeClosures($scripts, $localVars, $inputVals) {
69 // Example opening: (function (angular, $, _) {
70 $opening = '\s*\(\s*function\s*\(\s*';
71 $opening .= implode(',\s*', array_map(function ($v) {
72 return preg_quote($v, '/');
73 }, $localVars));
74 $opening .= '\)\s*\{';
75 $opening = '/^' . $opening . '\s*(?:"use strict";\s|\'use strict\';\s)?/';
76
77 // Example closing: })(angular, CRM.$, CRM._);
78 $closing = '\}\s*\)\s*\(\s*';
79 $closing .= implode(',\s*', array_map(function ($v) {
80 return preg_quote($v, '/');
81 }, $inputVals));
82 $closing .= '\);\s*';
83 $closing = "/$closing\$/";
84
85 $scripts = array_values($scripts);
86 for ($i = count($scripts) - 1; $i > 0; $i--) {
87 if (preg_match($closing, $scripts[$i - 1]) && preg_match($opening, $scripts[$i])) {
88 $scripts[$i - 1] = preg_replace($closing, '', $scripts[$i - 1]);
89 $scripts[$i] = preg_replace($opening, '', $scripts[$i]);
90 }
91 }
92
93 return $scripts;
94 }
95
96 /**
97 * This is a primitive comment stripper. It doesn't catch all comments
98 * and falls short of minification, but it doesn't munge Angular injections
99 * and is fast enough to run synchronously (without caching).
100 *
101 * At time of writing, running this against the Angular modules, this impl
102 * of stripComments currently adds 10-20ms and cuts ~7%.
103 *
104 * Please be extremely cautious about extending this. If you want better
105 * minification, you should probably remove this implementation,
106 * import a proper JSMin implementation, and cache its output.
107 *
108 * @param string $script
109 * @return string
110 */
111 public static function stripComments($script) {
112 return preg_replace("#^\\s*//[^\n]*$(?:\r\n|\n)?#m", "", $script);
113 }
114
115 /**
116 * Decodes a js variable (not necessarily strict json but valid js) into a php variable.
117 *
118 * This is similar to using json_decode($js, TRUE) but more forgiving about syntax.
119 *
120 * ex. {a: 'Apple', 'b': "Banana", c: [1, 2, 3]}
121 * Returns: [
122 * 'a' => 'Apple',
123 * 'b' => 'Banana',
124 * 'c' => [1, 2, 3],
125 * ]
126 *
127 * @param string $js
128 * @return mixed
129 * @throws Exception
130 */
131 public static function decode($js) {
132 $js = trim($js);
133 $first = substr($js, 0, 1);
134 $last = substr($js, -1);
135 if ($last === $first && ($first === "'" || $first === '"')) {
136 // Use a temp placeholder for escaped backslashes
137 $backslash = chr(0) . 'backslash' . chr(0);
138 return str_replace(['\\\\', "\\'", '\\"', '\\&', '\\/', $backslash], [$backslash, "'", '"', '&', '/', '\\'], substr($js, 1, -1));
139 }
140 if (($first === '{' && $last === '}') || ($first === '[' && $last === ']')) {
141 $obj = self::getRawProps($js);
142 foreach ($obj as $idx => $item) {
143 $obj[$idx] = self::decode($item);
144 }
145 return $obj;
146 }
147 return json_decode($js);
148 }
149
150 /**
151 * Encodes a variable to js notation (not strict json) suitable for e.g. an angular attribute.
152 *
153 * Like json_encode() but the output looks more like native javascript,
154 * with single quotes around strings and no unnecessary quotes around object keys.
155 *
156 * Ex input: [
157 * 'a' => 'Apple',
158 * 'b' => 'Banana',
159 * 'c' => [1, 2, 3],
160 * ]
161 * Ex output: {a: 'Apple', b: 'Banana', c: [1, 2, 3]}
162 *
163 * @param mixed $value
164 * @return string
165 */
166 public static function encode($value) {
167 if (is_array($value)) {
168 return self::writeObject($value, TRUE);
169 }
170 $result = json_encode($value, JSON_UNESCAPED_SLASHES);
171 // Convert double-quotes around string to single quotes
172 if (is_string($value) && substr($result, 0, 1) === '"' && substr($result, -1) === '"') {
173 $backslash = chr(0) . 'backslash' . chr(0);
174 return "'" . str_replace(['\\\\', '\\"', "'", $backslash], [$backslash, '"', "\\'", '\\\\'], substr($result, 1, -1)) . "'";
175 }
176 return $result;
177 }
178
179 /**
180 * Gets the properties of a javascript object/array WITHOUT decoding them.
181 *
182 * Useful when the object might contain js functions, expressions, etc. which cannot be decoded.
183 * Returns an array with keys as property names and values as raw strings of js.
184 *
185 * Ex Input: {foo: getFoo(arg), 'bar': function() {return "bar";}}
186 * Returns: [
187 * 'foo' => 'getFoo(arg)',
188 * 'bar' => 'function() {return "bar";}',
189 * ]
190 *
191 * @param $js
192 * @return array
193 * @throws Exception
194 */
195 public static function getRawProps($js) {
196 $js = trim($js);
197 if (!is_string($js) || $js === '' || !($js[0] === '{' || $js[0] === '[')) {
198 throw new Exception("Invalid js object string passed to CRM_Utils_JS::getRawProps");
199 }
200 $chars = str_split(substr($js, 1));
201 $isEscaped = $quote = NULL;
202 $type = $js[0] === '{' ? 'object' : 'array';
203 $key = $type == 'array' ? 0 : NULL;
204 $item = '';
205 $end = strlen($js) - 2;
206 $quotes = ['"', "'", '/'];
207 $brackets = [
208 '}' => '{',
209 ')' => '(',
210 ']' => '[',
211 ':' => '?',
212 ];
213 $enclosures = array_fill_keys($brackets, 0);
214 $result = [];
215 foreach ($chars as $index => $char) {
216 if (!$isEscaped && in_array($char, $quotes, TRUE)) {
217 // Open quotes, taking care not to mistake the division symbol for opening a regex
218 if (!$quote && !($char == '/' && preg_match('{[\w)]\s*$}', $item))) {
219 $quote = $char;
220 }
221 // Close quotes
222 elseif ($char === $quote) {
223 $quote = NULL;
224 }
225 }
226 if (!$quote) {
227 // Delineates property key
228 if ($char == ':' && !array_filter($enclosures) && !$key) {
229 $key = $item;
230 $item = '';
231 continue;
232 }
233 // Delineates property value
234 if (($char == ',' || $index == $end) && !array_filter($enclosures) && isset($key) && trim($item) !== '') {
235 // Trim, unquote, and unescape characters in key
236 if ($type == 'object') {
237 $key = trim($key);
238 $key = in_array($key[0], $quotes) ? self::decode($key) : $key;
239 }
240 $result[$key] = trim($item);
241 $key = $type == 'array' ? $key + 1 : NULL;
242 $item = '';
243 continue;
244 }
245 // Open brackets - we'll ignore delineators inside
246 if (isset($enclosures[$char])) {
247 $enclosures[$char]++;
248 }
249 // Close brackets
250 if (isset($brackets[$char]) && $enclosures[$brackets[$char]]) {
251 $enclosures[$brackets[$char]]--;
252 }
253 }
254 $item .= $char;
255 // We are escaping the next char if this is a backslash not preceded by an odd number of backslashes
256 $isEscaped = $char === '\\' && ((strlen($item) - strlen(rtrim($item, '\\'))) % 2);
257 }
258 return $result;
259 }
260
261 /**
262 * Converts a php array to javascript object/array notation (not strict JSON).
263 *
264 * Does not encode keys unless they contain special characters.
265 * Does not encode values by default, so either specify $encodeValues = TRUE,
266 * or pass strings of valid js/json as values (per output from getRawProps).
267 * @see CRM_Utils_JS::getRawProps
268 *
269 * @param array $obj
270 * @param bool $encodeValues
271 * @return string
272 */
273 public static function writeObject($obj, $encodeValues = FALSE) {
274 $js = [];
275 $brackets = isset($obj[0]) && array_keys($obj) === range(0, count($obj) - 1) ? ['[', ']'] : ['{', '}'];
276 foreach ($obj as $key => $val) {
277 if ($encodeValues) {
278 $val = self::encode($val);
279 }
280 if ($brackets[0] == '{') {
281 // Enclose the key in quotes unless it is purely alphanumeric
282 if (preg_match('/\W/', $key)) {
283 // Prefer single quotes
284 $key = preg_match('/^[\w "]+$/', $key) ? "'" . $key . "'" : json_encode($key, JSON_UNESCAPED_SLASHES);
285 }
286 $js[] = "$key: $val";
287 }
288 else {
289 $js[] = $val;
290 }
291 }
292 return $brackets[0] . implode(', ', $js) . $brackets[1];
293 }
294
295 }