3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 * Parse Javascript content and extract translatable strings.
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 * Parse a javascript file for translatable strings.
23 * @param string $jsCode
24 * Raw Javascript code.
26 * Array of translatable strings
28 public static function parseStrings($jsCode) {
30 // Match all calls to ts() in an array.
31 // Note: \s also matches newlines with the 's' modifier.
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) {
41 $text = str_replace("\\\n", '', $text);
42 // Unescape escaped quotes
43 $text = str_replace('\\' . $quote, $quote, $text);
45 $text = substr(ltrim($text, $quote), 0, -1);
46 $strings[$text] = $text;
48 return array_values($strings);
52 * Identify duplicate, adjacent, identical closures and consolidate them.
54 * Note that you can only dedupe closures if they are directly adjacent and
55 * have exactly the same parameters.
57 * Also dedupes the "use strict" directive as it is only meaningful at the beginning of a closure.
59 * @param array $scripts
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.
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, '/');
74 $opening .= '\)\s*\{';
75 $opening = '/^' . $opening . '\s*(?:"use strict";\s|\'use strict\';\s)?/';
77 // Example closing: })(angular, CRM.$, CRM._);
78 $closing = '\}\s*\)\s*\(\s*';
79 $closing .= implode(',\s*', array_map(function ($v) {
80 return preg_quote($v, '/');
83 $closing = "/$closing\$/";
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]);
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).
101 * At time of writing, running this against the Angular modules, this impl
102 * of stripComments currently adds 10-20ms and cuts ~7%.
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.
108 * @param string $script
111 public static function stripComments($script) {
112 return preg_replace("#^\\s*//[^\n]*$(?:\r\n|\n)?#m", "", $script);
116 * Decodes a js variable (not necessarily strict json but valid js) into a php variable.
118 * This is similar to using json_decode($js, TRUE) but more forgiving about syntax.
120 * ex. {a: 'Apple', 'b': "Banana", c: [1, 2, 3]}
128 * @param bool $throwException
130 * @throws CRM_Core_Exception
132 public static function decode($js, $throwException = FALSE) {
134 $first = substr($js, 0, 1);
135 $last = substr($js, -1);
136 if ($first === "'" && $last === "'") {
137 $js = self
::convertSingleQuoteString($js, $throwException);
139 elseif (($first === '{' && $last === '}') ||
($first === '[' && $last === ']')) {
140 $obj = self
::getRawProps($js);
141 foreach ($obj as $idx => $item) {
142 $obj[$idx] = self
::decode($item, $throwException);
146 $result = json_decode($js);
147 if ($throwException && $result === NULL && $js !== 'null') {
148 throw new CRM_Core_Exception(json_last_error_msg());
155 * @param bool $throwException
156 * @return string|null
157 * @throws CRM_Core_Exception
159 public static function convertSingleQuoteString(string $str, $throwException) {
160 // json_decode can only handle double quotes around strings, so convert single-quoted strings
161 $backslash = chr(0) . 'backslash' . chr(0);
162 $str = str_replace(['\\\\', '\\"', '"', '\\&', '\\/', $backslash], [$backslash, '"', '\\"', '&', '/', '\\'], substr($str, 1, -1));
163 // Ensure the string doesn't terminate early by checking that all single quotes are escaped
165 while (($pos = strpos($str, "'", $pos +
1)) !== FALSE) {
166 if (($pos - strlen(rtrim(substr($str, 0, $pos)))) %
2) {
167 if ($throwException) {
168 throw new CRM_Core_Exception('Invalid string passed to CRM_Utils_JS::decode');
173 return '"' . $str . '"';
177 * Encodes a variable to js notation (not strict json) suitable for e.g. an angular attribute.
179 * Like json_encode() but the output looks more like native javascript,
180 * with single quotes around strings and no unnecessary quotes around object keys.
187 * Ex output: {a: 'Apple', b: 'Banana', c: [1, 2, 3]}
189 * @param mixed $value
192 public static function encode($value) {
193 if (is_array($value)) {
194 return self
::writeObject($value, TRUE);
196 $result = json_encode($value, JSON_UNESCAPED_SLASHES
);
197 // Convert double-quotes around string to single quotes
198 if (is_string($value) && substr($result, 0, 1) === '"' && substr($result, -1) === '"') {
199 $backslash = chr(0) . 'backslash' . chr(0);
200 return "'" . str_replace(['\\\\', '\\"', "'", $backslash], [$backslash, '"', "\\'", '\\\\'], substr($result, 1, -1)) . "'";
206 * Gets the properties of a javascript object/array WITHOUT decoding them.
208 * Useful when the object might contain js functions, expressions, etc. which cannot be decoded.
209 * Returns an array with keys as property names and values as raw strings of js.
211 * Ex Input: {foo: getFoo(arg), 'bar': function() {return "bar";}}
213 * 'foo' => 'getFoo(arg)',
214 * 'bar' => 'function() {return "bar";}',
221 public static function getRawProps($js) {
223 if (!is_string($js) ||
$js === '' ||
!($js[0] === '{' ||
$js[0] === '[')) {
224 throw new Exception("Invalid js object string passed to CRM_Utils_JS::getRawProps");
226 $chars = str_split(substr($js, 1));
227 $isEscaped = $quote = NULL;
228 $type = $js[0] === '{' ?
'object' : 'array';
229 $key = $type == 'array' ?
0 : NULL;
231 $end = strlen($js) - 2;
232 $quotes = ['"', "'", '/'];
239 $enclosures = array_fill_keys($brackets, 0);
241 foreach ($chars as $index => $char) {
242 if (!$isEscaped && in_array($char, $quotes, TRUE)) {
243 // Open quotes, taking care not to mistake the division symbol for opening a regex
244 if (!$quote && !($char == '/' && preg_match('{[\w)]\s*$}', $item))) {
248 elseif ($char === $quote) {
253 // Delineates property key
254 if ($char == ':' && !array_filter($enclosures) && !$key) {
259 // Delineates property value
260 if (($char == ',' ||
$index == $end) && !array_filter($enclosures) && isset($key) && trim($item) !== '') {
261 // Trim, unquote, and unescape characters in key
262 if ($type == 'object') {
264 $key = in_array($key[0], $quotes) ? self
::decode($key) : $key;
266 $result[$key] = trim($item);
267 $key = $type == 'array' ?
$key +
1 : NULL;
271 // Open brackets - we'll ignore delineators inside
272 if (isset($enclosures[$char])) {
273 $enclosures[$char]++
;
276 if (isset($brackets[$char]) && $enclosures[$brackets[$char]]) {
277 $enclosures[$brackets[$char]]--;
281 // We are escaping the next char if this is a backslash not preceded by an odd number of backslashes
282 $isEscaped = $char === '\\' && ((strlen($item) - strlen(rtrim($item, '\\'))) %
2);
288 * Converts a php array to javascript object/array notation (not strict JSON).
290 * Does not encode keys unless they contain special characters.
291 * Does not encode values by default, so either specify $encodeValues = TRUE,
292 * or pass strings of valid js/json as values (per output from getRawProps).
293 * @see CRM_Utils_JS::getRawProps
296 * @param bool $encodeValues
299 public static function writeObject($obj, $encodeValues = FALSE) {
301 $brackets = isset($obj[0]) && array_keys($obj) === range(0, count($obj) - 1) ?
['[', ']'] : ['{', '}'];
302 foreach ($obj as $key => $val) {
304 $val = self
::encode($val);
306 if ($brackets[0] == '{') {
307 // Enclose the key in quotes unless it is purely alphanumeric
308 if (preg_match('/\W/', $key)) {
309 // Prefer single quotes
310 $key = preg_match('/^[\w "]+$/', $key) ?
"'" . $key . "'" : json_encode($key, JSON_UNESCAPED_SLASHES
);
312 $js[] = "$key: $val";
318 return $brackets[0] . implode(', ', $js) . $brackets[1];