File: check_translation.php

package info (click to toggle)
kalkun 0.8.3.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,340 kB
  • sloc: php: 30,659; javascript: 30,443; sql: 961; sh: 766; xml: 105; makefile: 41
file content (620 lines) | stat: -rwxr-xr-x 14,655 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
#!/usr/bin/php
<?php
if (php_sapi_name() !== 'cli') exit;

/**
 * This is part of kalkun - a web based SMS manager
 * Copyright: 2021 Fab Stz <fabstz-it@yahoo.fr>
 * License: GPL-2.0-or-later
 *
 * This script will recursively check the PHP files in a directory for
 * translation inconsistencies
 *   - labels used by tr() but not in the translation file
 *   - labels that are not consistent in the english file
 *   - labels that are in the translation file, but never used.
 *
 * Usage:
 *   utils/check_translation.php [all|application|application/plugins/<plugin_name>]
 *   php -f utils/check_translation.php [all|application|application/plugins/<plugin_name>]
 *
 *  /!\ This must be run from the root dir of the project
 *
 *   directory:
 *       The directory containing the files to check.
 *       - all: check core application + plugins
 *       - application: the core application without the plugins
 *       - application/plugins/<plugin_name>: the given plugin only
 *
 */

// The script needs PhpParser to parse kalkun's PHP code
include_once realpath(__DIR__).'/vendor/autoload.php';

use PhpParser\Error;
use PhpParser\ParserFactory;
use PhpParser\Node;
use PhpParser\NodeFinder;

/**
 * Search recusively for files in a base directory matching a glob pattern.
 * The `GLOB_NOCHECK` flag has no effect.
 *
 * @param  string $base Directory to search
 * @param  string $pattern Glob pattern to match files
 * @param  int $flags Glob flags from https://www.php.net/manual/function.glob.php
 * @return string[] Array of files matching the pattern
 *
 * License: DWTFYW
 * https://gist.github.com/UziTech/3b65b2543cee57cd6d2ecfcccf846f20
 */
function glob_recursive($base, $pattern, $flags = 0)
{
	$flags = $flags & ~GLOB_NOCHECK;

	if (substr($base, -1) !== DIRECTORY_SEPARATOR)
	{
		$base .= DIRECTORY_SEPARATOR;
	}

	$files = glob($base.$pattern, $flags);
	if ( ! is_array($files))
	{
		$files = [];
	}

	$dirs = glob($base.'*', GLOB_ONLYDIR | GLOB_NOSORT | GLOB_MARK);
	if ( ! is_array($dirs))
	{
		return $files;
	}

	foreach ($dirs as $dir)
	{
		$dirFiles = glob_recursive($dir, $pattern, $flags);
		$files = array_merge($files, $dirFiles);
	}

	return $files;
}

/**
* array_merge_recursive does indeed merge arrays, but it converts values with duplicate
* keys to arrays rather than overwriting the value in the first array with the duplicate
* value in the second array, as array_merge does. I.e., with array_merge_recursive,
* this happens (documented behavior):
*
* array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
*     => array('key' => array('org value', 'new value'));
*
* array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
* Matching keys' values in the second array overwrite those in the first array, as is the
* case with array_merge, i.e.:
*
* array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
*     => array('key' => array('new value'));
*
* Parameters are passed by reference, though only for performance reasons. They're not
* altered by this function.
*
* @param array $array1
* @param array $array2
* @return array
* @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
* @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
*/
function array_merge_recursive_distinct (array &$array1, array &$array2)
{
	$merged = $array1;

	foreach ($array2 as $key => &$value)
	{
		if (is_array ($value) && isset ($merged[$key]) && is_array ($merged[$key]))
		{
			$merged[$key] = array_merge_recursive_distinct ($merged[$key], $value);
		}
		else
		{
			$merged[$key] = $value;
		}
	}

	return $merged;
}

/**
 * Returns if $str contains $search
 *
 * @param string $str
 * @param sting $search
 * @return boolean
 */
function contains($str, $search)
{
	if (strpos($str, $search) !== FALSE)
	{
		return TRUE;
	}
	return FALSE;
}


/**
 *
 * @param string $basedir
 * @param boolean $with_plugins
 * @return array
 */
function get_all_tr_labels($basedir, $with_plugins)
{
	$php_files = glob_recursive($basedir, '*.php');
	//var_dump($php_files);

	$all_labels = [];
	foreach ($php_files as $filename)
	{
		// If we are parsing the core of kalkun, don't load the php files of the plugins.
		// Parsing of the plugins should be made separately
		if ( ! contains($basedir, '/plugins')
		  && contains($filename, '/plugins')
		  && ! contains($filename, '/plugins/Plugin_')
		  ) {
			if ( ! $with_plugins)
			{
				continue;
			}
		}

		//var_dump($filename);
		$code = file_get_contents($filename);

		$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);

		try
		{
			$ast = $parser->parse($code);
		}
		catch (Error $error)
		{
			echo "Parse error: {$error->getMessage()}\n";
			return;
		}

		$additonal_labels = get_tr_labels($ast);
		$all_labels = array_merge_recursive_distinct($all_labels, $additonal_labels);
	}
	//var_dump($all_labels);
	//$j = json_encode($all_labels, JSON_PRETTY_PRINT);
	//echo $j;
	return $all_labels;
}

/**
 * Extract tr labels with the help of PHPParser
 *
 * @param type $ast
 * @return array
 */
function get_tr_labels($ast)
{
	$nodeFinder = new NodeFinder;
	$expr = $nodeFinder->findInstanceOf($ast, Node\Expr\FuncCall::class);

	$labels = [];
	$labels2 = [];
	foreach ($expr as $f)
	{
		if (! $f->name instanceof Node\Name)
		{
			continue;
		}
		$fn_name = $f->name->toCodeString();
		//var_dump($fn_name);

		if ($fn_name === 'tr' || $fn_name === 'tr_addcslashes' || $fn_name === 'tr_js' || $fn_name === 'tr_raw' || $fn_name === 'tr_no_op')
		{
			if ($fn_name === 'tr' || $fn_name === 'tr_js' || $fn_name === 'tr_raw' || $fn_name === 'tr_no_op')
			{
				$tr_args = $f->args;
			}
			else
			{
				$tr_args = array_slice($f->args, 1);
			}

			if ( ! property_exists($tr_args[0]->value, "value") || ! $tr_args[0]->value instanceof PhpParser\Node\Scalar\String_)
			{
				echo "\033[31mERROR:\033[0m ";
				echo "Function: $fn_name().";
				if (property_exists($tr_args[0]->value, "name"))
				{
					echo " Argument name: " . $tr_args[0]->value->name . ".";
				}
				echo " Argument is not a string or doesn't have a value. Type: ".get_class($tr_args[0]->value).".";
				echo "\n";
				continue;
			}
			$label = $tr_args[0]->value->value;
			$item['label'] = $label;
			//var_dump($label);
			if (sizeof($tr_args) > 1)
			{
				//var_dump($tr_args[1]->value);
				if ($tr_args[1]->value instanceof PhpParser\Node\Expr\ConstFetch)
				{
					$context = $tr_args[1]->value->name->toCodeString();
					if ($context === 'NULL')
					{
						$labels2[$label] = '';
					}
					else
					{
						$item['context'] = $context;
						$labels2[$label][$context] = '';
					}
				}
				else
				{
					$context = $tr_args[1]->value->value;
					$item['context'] = $context;
					$labels2[$label][$context] = '';
				}
			}
			else
			{
				$labels2[$label] = '';
			}
			array_push($labels, $item);
		}
	}
	//var_dump($labels2);
	return $labels2;
}


/**
 * Check if key & value of translations are the same.
 *
 * @param array $lang_array
 * @return array
 */
function check_discordant_label($lang_array)
{
	//var_dump($lang_array);

	$discordant = [];
	foreach ($lang_array as $file => $lang)
	{
		$count_discordant_label = 0;
		foreach ($lang as $key => $value)
		{
			if (is_array($value))
			{
				foreach ($value as $k => $v)
				{
					if ($key !== $v)
					{
						$discordant[$file][$key] = $v;
					}
					else
					{
						//echo "OK: $v [in context: $k]\n";
					}
				}
			}
			else
			{
				if ($key !== $value)
				{
					$discordant[$file][$key] = $value;
				}
				else
				{
					//echo "OK: $value\n";
				}
			}
		}
	}
	return $discordant;
}

/**
 * Check unused translations (only in english)
 *
 * @param type $available
 * @param type $requested
 * @return type
 *
 */
function check_unused_labels($available, $requested)
{
	$unused = [];

	foreach ($available as $file => $lang)
	{
		foreach ($lang as $key => $value)
		{
			if (is_array($value))
			{
				if (array_key_exists($key, $requested) && is_array($requested[$key]))
				{
					if ( ! array_key_exists(key($value), $requested[$key]))
					{
						$unused[$file][$key][key($value)] = $value[key($value)] ;
					}
				}
				else
				{
					$unused[$file][$key] = $value ;
				}
			}
			else
			{
				if ( ! array_key_exists($key, $requested) || is_array($requested[$key]))
				{
					$unused[$file][$key] = $value ;
				}
			}
		}
	}
	return $unused;
}

/**
 *
 * display_cmd_to_remove_labels
 *
 * @param array $unused
 * @param string $basedir
 * @return type
 */
function display_cmd_to_remove_labels($unused, $basedir)
{
	if (sizeof($unused) === 0)
	{
		return;
	}
	echo "\nRun these commands to remove them:";
	foreach ($unused as $file => $lang)
	{
		$basename = basename($file);
		foreach ($lang as $key => $value)
		{
			$escaped_key = $key;
			$escaped_key = str_replace("'", "\\\'\''", $escaped_key);
			$escaped_key = str_replace("/", "\\/", $escaped_key);
			echo "\n";
			if (is_array($value))
			{
				echo "for lang in $(find ${basedir}/language -mindepth 1 -type d | sort); do sed -i -e '/\$lang\['\''${escaped_key}'\''\]\['\''".key($value)."'\''\]/ d' \$lang/${basename}; done";
			}
			else
			{
				echo "for lang in $(find ${basedir}/language -mindepth 1 -type d | sort); do sed -i -e '/\$lang\['\''${escaped_key}'\''\]/ d' \$lang/${basename}; done";
			}
		}
	}
	echo "\n";
}

/**
 * Check untranslated string
 * Note: this is also displayed in the GUI by showing a globe icon next to the label
 *
 * @param array $lang_array
 * @param array $requested
 * @return type
 *
 */
function check_missing_labels($lang_array, $requested)
{
	$missings = [];

	$available = [];
	foreach ($lang_array as $item)
	{
		$available = array_merge($available, $item);
	}

	foreach ($requested as $key => $value)
	{
		if (is_array($value))
		{
			if (array_key_exists($key, $available) && is_array($available[$key]))
			{
				if ( ! array_key_exists(key($value), $available[$key]))
				{
					//Missing
					$missings[$key][key($value)] = $value[key($value)] ;
				}
			}
			else
			{
				//Missing
				$missings[$key] = $value ;
			}
		}
		else
		{
			if (array_key_exists($key, $available))
			{
				//echo "OK: $key\n";
			}
			else
			{
				$missings[$key] = $value ;
			}
		}
	}
	return $missings;
}

/**
 * display_cmd_to_add_labels
 *
 * @param array $missings
 * @param string $basedir
 * @return type
 */
function display_cmd_to_add_labels($missings, $basedir)
{
	if (sizeof($missings) === 0)
	{
		return;
	}
	echo "\nRun these commands to add them:\n\n";
	echo "export KALKUN_LANG_OUTPUT_FILE=\$(basename \$(find ${basedir}/language -name '*_lang.php' | rev | cut -d '/' -f 1 | rev | sort -u | grep -v date_lang | head -1))\n";
	foreach ($missings as $key => $value)
	{
		$escaped_key = $key;
		$escaped_key = str_replace("'", "\\'\''", $escaped_key);
		if (is_array($value))
		{
			echo "for lang in $(find ${basedir}/language -mindepth 1 -type d | sort); do echo '\$lang['\''${escaped_key}'\'']['\''".key($value)."'\''] = '\''${escaped_key}'\'';' >> \$lang/\$KALKUN_LANG_OUTPUT_FILE; done";
		}
		else
		{
			echo "for lang in $(find ${basedir}/language -mindepth 1 -type d | sort); do echo '\$lang['\''${escaped_key}'\''] = '\''${escaped_key}'\'';' >> \$lang/\$KALKUN_LANG_OUTPUT_FILE; done";
		}
		echo "\n";
	}
	echo "\n";
}

/**
 * Perform the translation check on "$basedir"
 * Return the total count of checks in error
 *
 * @param string $basedir
 * @return int
 *
 */
function perfom_check($basedir)
{
	$error_count = 0;

	// Load the $lang array that is in the _lang.php file
	$lang_array = [];

	defined('BASEPATH') || define('BASEPATH', '');
	foreach (glob("${basedir}/language/english/*_lang.php") as $filename)
	{
		include $filename;
		$lang_array[$filename] = $lang;
		unset($lang);
	}

	echo "Parsing PHP files in: ${basedir}\n";
	echo str_repeat('¯', 22 + strlen($basedir))."\n";

	echo "Checking unused labels...  \n";
	$unused_label = check_unused_labels($lang_array, get_all_tr_labels($basedir, TRUE));

	echo "Checking discordant labels in the english file...\n";
	$discordant_label = check_discordant_label($lang_array);

	echo "Checking missing labels...\n";
	// Load translations we already have ($lang array)
	$additional_lang_files = [
		'vendor/codeigniter/framework/system/language/english/date_lang.php',
		'application/language/english/kalkun_lang.php'
	];
	foreach ($additional_lang_files as $file)
	{
		include $file;
		$lang_array[$file] = $lang;
	}
	$missing_labels_in_english = check_missing_labels($lang_array, get_all_tr_labels($basedir, FALSE));
	//var_dump($lang);

	echo "\n";
	echo "Results:\n";

	$total_unused_labels = 0;
	foreach ($unused_label as $val)
	{
		$total_unused_labels += sizeof($val);
	}

	if ($total_unused_labels !== 0)
	{
		echo "- ${total_unused_labels} key(s) present in translation file but not used anywhere.\n";
		echo json_encode($unused_label, JSON_PRETTY_PRINT);
		echo "\n";
		display_cmd_to_remove_labels($unused_label, $basedir);
		echo "\n";
		$error_count++;
	}
	else
	{
		echo "- No unused labels found.\n";
	}

	if (sizeof($discordant_label) !== 0)
	{
		echo '- '.sizeof($discordant_label)." key(s) have a discordant label. Please fix by setting same value as key.\n";
		echo json_encode($discordant_label, JSON_PRETTY_PRINT);
		echo "\n\n";
		$error_count++;
	}
	else
	{
		echo "- No discordant labels found.\n";
	}

	if (sizeof($missing_labels_in_english) !== 0)
	{
		echo '- '.sizeof($missing_labels_in_english)." label(s) have no translation in an english *_lang.php file.\n";
		echo json_encode($missing_labels_in_english, JSON_PRETTY_PRINT);
		echo "\n";
		display_cmd_to_add_labels($missing_labels_in_english, $basedir);
		echo "\n";
		$error_count++;
	}
	else
	{
		echo "- No missing labels found.\n";
	}

	echo "\n";
	return $error_count;
}


/**
 * Main call
 *
 */

$total_error_count = 0;

if (sizeof($argv) > 1)
{
	if ($argv[1] === 'all')
	{
		$total_error_count += perfom_check('application');
		$plugin_dirs = glob('application/plugins/*', GLOB_ONLYDIR | GLOB_MARK);
		// Exclude some plugins from the check.
		$plugin_dirs = array_filter($plugin_dirs, function($v) {
			return false === strpos($v, 'application/plugins/rest_api/');
		});
		foreach ($plugin_dirs as $dir)
		{
			$total_error_count += perfom_check($dir);
		}
	}
	else
	{
		$total_error_count += perfom_check($argv[1]);
	}
}
else
{
	$total_error_count += perfom_check('application');
}

// We return status code 1 only is labels are discordant. Unused labels is only informational.
if ($total_error_count !== 0)
{
	echo "Total checks in error: ${total_error_count}\n";
}
exit ($total_error_count);