forked from kgaut/drupal-potx
-
Notifications
You must be signed in to change notification settings - Fork 1
/
potx.inc
3201 lines (2914 loc) · 112 KB
/
potx.inc
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Extraction API used by the web and command line interface.
*
* This include file implements the default string and file version
* storage as well as formatting of POT files for web download or
* file system level creation. The strings, versions and file contents
* are handled with global variables to reduce the possible memory overhead
* and API clutter of passing them around. Custom string and version saving
* functions can be implemented to use the functionality provided here as an
* API for Drupal code to translatable string conversion.
*
* The potx-cli.php script can be used with this include file as
* a command line interface to string extraction. The potx.module
* can be used as a web interface for manual extraction.
*
* For a module using potx as an extraction API, but providing more
* sophisticated functionality on top of it, look into the
* 'Localization server' module: http://drupal.org/project/l10n_server
*/
/**
* Use Twig and the Symfony YAML parser, found in the vendor directory.
*/
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ . '/vendor');
spl_autoload_register(function($c){
@include preg_replace('#\\\|_(?!.*\\\)#','/',$c).'.php';
});
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;
/**
* The current Drupal major API verion.
*
* This should be the only difference between different branches of potx.inc
*/
define('POTX_API_CURRENT', 7);
/**
* Silence status reports.
*/
define('POTX_STATUS_SILENT', 0);
/**
* Drupal message based status reports.
*/
define('POTX_STATUS_MESSAGE', 1);
/**
* Command line status reporting.
*
* Status goes to standard output, errors to standard error.
*/
define('POTX_STATUS_CLI', 2);
/**
* Structured array status logging.
*
* Useful for coder review status reporting.
*/
define('POTX_STATUS_STRUCTURED', 3);
/**
* Core parsing mode:
* - .info files folded into general.pot
* - separate files generated for modules
*/
define('POTX_BUILD_CORE', 0);
/**
* Multiple files mode:
* - .info files folded into their module pot files
* - separate files generated for modules
*/
define('POTX_BUILD_MULTIPLE', 1);
/**
* Single file mode:
* - all files folded into one pot file
*/
define('POTX_BUILD_SINGLE', 2);
/**
* Save string to both installer and runtime collection.
*/
define('POTX_STRING_BOTH', 0);
/**
* Save string to installer collection only.
*/
define('POTX_STRING_INSTALLER', 1);
/**
* Save string to runtime collection only.
*/
define('POTX_STRING_RUNTIME', 2);
/**
* Parse source files in Drupal 5.x format.
*/
define('POTX_API_5', 5);
/**
* Parse source files in Drupal 6.x format.
*
* Changes since 5.x documented at http://drupal.org/node/114774
*/
define('POTX_API_6', 6);
/**
* Parse source files in Drupal 7.x format.
*
* Changes since 6.x documented at http://drupal.org/node/224333
*/
define('POTX_API_7', 7);
/**
* Parse source files in Drupal 8.x format.
*
* Changes since 7.x documented at
* http://drupal.org/list-changes/drupal?to_branch=8.x
*/
define('POTX_API_8', 8);
/**
* When no context is used. Makes it easy to look these up.
*/
define('POTX_CONTEXT_NONE', NULL);
/**
* When there was a context identification error.
*/
define('POTX_CONTEXT_ERROR', FALSE);
/**
* Regular expression pattern used to localize JavaScript strings.
*/
define('POTX_JS_STRING', '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+');
/**
* Regular expression pattern used to match simple JS object literal.
*
* This pattern matches a basic JS object, but will fail on an object with
* nested objects. Used in JS file parsing for string arg processing.
*/
define('POTX_JS_OBJECT', '\{.*?\}');
/**
* Regular expression to match an object containing a key 'context'.
*
* Pattern to match a JS object containing a 'context key' with a string value,
* which is captured. Will fail if there are nested objects.
*/
define('POTX_JS_OBJECT_CONTEXT', '
\{ # match object literal start
.*? # match anything, non-greedy
(?: # match a form of "context"
\'context\'
|
"context"
|
context
)
\s*:\s* # match key-value separator ":"
(' . POTX_JS_STRING . ') # match context string
.*? # match anything, non-greedy
\} # match end of object literal
');
/**
* Process a file and put extracted information to the given parameters.
*
* @param $file_path
* Comlete path to file to process.
* @param $strip_prefix
* An integer denoting the number of chars to strip from filepath for output.
* @param $save_callback
* Callback function to use to save the collected strings.
* @param $version_callback
* Callback function to use to save collected version numbers.
* @param $api_version
* Drupal API version to work with.
*/
function _potx_process_file($file_path, $strip_prefix = 0, $save_callback = '_potx_save_string', $version_callback = '_potx_save_version', $api_version = POTX_API_CURRENT) {
global $_potx_tokens, $_potx_lookup;
// Figure out the basename and extension to select extraction method.
$basename = basename($file_path);
$name_parts = pathinfo($basename);
// Always grab the CVS version number from the code
$code = file_get_contents($file_path);
$file_name = $strip_prefix > 0 ? substr($file_path, $strip_prefix) : $file_path;
_potx_find_version_number($code, $file_name, $version_callback);
// The .info files are not PHP code, no need to tokenize.
if ($name_parts['extension'] == 'info' && $api_version < POTX_API_8) {
_potx_find_info_file_strings($file_path, $file_name, $save_callback, $api_version);
return;
}
elseif ($name_parts['extension'] == 'yml' && $api_version > POTX_API_7) {
_potx_parse_yaml_file($code, $file_name, $file_path, $save_callback);
}
elseif ($name_parts['extension'] == 'js' && $api_version > POTX_API_5) {
// @todo: D7 context support.
_potx_parse_js_file($code, $file_name, $save_callback);
}
elseif ($name_parts['extension'] == 'twig' && $api_version > POTX_API_7) {
_potx_parse_twig_file($code, $file_name, $save_callback);
}
$constraint_extract = FALSE;
if (substr($name_parts['filename'], -10) == 'Constraint' && $api_version > POTX_API_7) {
$constraint_extract = TRUE;
}
// Extract raw PHP language tokens.
$raw_tokens = token_get_all($code);
unset($code);
// Remove whitespace and possible HTML (the later in templates for example),
// count line numbers so we can include them in the output.
$_potx_tokens = array();
$_potx_lookup = array();
$token_number = 0;
$line_number = 1;
foreach ($raw_tokens as $token) {
if ((!is_array($token)) || (($token[0] != T_WHITESPACE) && ($token[0] != T_INLINE_HTML))) {
if (is_array($token)) {
$token[] = $line_number;
$constraint_match = $constraint_extract && $token[0] == T_VARIABLE && strlen($token[1]) >= 7 && substr_compare($token[1], 'message', -7, 7, true) === 0;
// Fill array for finding token offsets quickly.
if (in_array($token[0], array(T_STRING, T_DOC_COMMENT)) || ($token[0] == T_VARIABLE && $token[1] == '$t') || $constraint_match
|| ($token[0] == T_CONSTANT_ENCAPSED_STRING && ($token[1] == "'#template'" || $token[1] == '"#template"'))) {
// Give doc comments a specific key because their content varies.
$key = ($token[0] == T_DOC_COMMENT) ? 'T_DOC_COMMENT' : ($constraint_match ? 'T_POTX_CONSTRAINT' : $token[1]);
// Normalise "#template" token to support both single-quoted and double-quoted #template keys.
if ($key == '"#template"') {
$key = "'#template'";
}
if (!isset($_potx_lookup[$key])) {
$_potx_lookup[$key] = array();
}
$_potx_lookup[$key][] = $token_number;
}
}
$_potx_tokens[] = $token;
$token_number++;
}
// Collect line numbers.
if (is_array($token)) {
$line_number += count(explode("\n", $token[1])) - 1;
}
else {
$line_number += count(explode("\n", $token)) - 1;
}
}
unset($raw_tokens);
// Regular t() calls with different usages.
if ($api_version > POTX_API_6) {
// Drupal 7 onwards supports context on t().
_potx_find_t_calls_with_context($file_name, $save_callback);
if ($api_version < POTX_API_8) {
// st() and $t() are supported up to Drupal 7.
_potx_find_t_calls_with_context($file_name, $save_callback, '$t', POTX_STRING_BOTH);
_potx_find_t_calls_with_context($file_name, $save_callback, 'st', POTX_STRING_INSTALLER);
}
else {
// TranslatableMarkup (and deprecated TranslationWrapper) added in Drupal 8.
_potx_find_t_calls_with_context($file_name, $save_callback, 'TranslatableMarkup');
_potx_find_t_calls_with_context($file_name, $save_callback, 'TranslationWrapper');
}
}
else {
// Context-less API up to Drupal 6.
_potx_find_t_calls($file_name, $save_callback);
_potx_find_t_calls($file_name, $save_callback, '$t', POTX_STRING_BOTH);
_potx_find_t_calls($file_name, $save_callback, 'st', POTX_STRING_INSTALLER);
}
if ($api_version < POTX_API_8) {
// This does not support context even in Drupal 7.
_potx_find_t_calls($file_name, $save_callback, '_locale_import_message', POTX_STRING_BOTH);
}
if ($api_version > POTX_API_5) {
// Watchdog calls have both of their arguments translated from Drupal 6.x.
if ($api_version < POTX_API_8) {
_potx_find_watchdog_calls($file_name, $save_callback);
}
if ($api_version > POTX_API_7) {
// Logging calls may use a colorful set of methods now.
_potx_find_t_calls($file_name, $save_callback, 'debug');
_potx_find_t_calls($file_name, $save_callback, 'info');
_potx_find_t_calls($file_name, $save_callback, 'notice');
_potx_find_t_calls($file_name, $save_callback, 'warning');
_potx_find_t_calls($file_name, $save_callback, 'error');
_potx_find_t_calls($file_name, $save_callback, 'critical');
_potx_find_t_calls($file_name, $save_callback, 'alert');
_potx_find_t_calls($file_name, $save_callback, 'emergency');
_potx_find_log_calls($file_name, $save_callback);
}
}
else {
// Watchdog calls only have their first argument translated in Drupal 5.x
// and before.
_potx_find_t_calls($file_name, $save_callback, 'watchdog');
}
// Plurals need unique parsing.
if ($api_version < POTX_API_8) {
// format_plural() is removed in Drupal 8.
_potx_find_format_plural_calls($file_name, $save_callback, 'format_plural', $api_version);
}
// Support for formatPlural() calls in Drupal 8+.
if ($api_version > POTX_API_7) {
_potx_find_format_plural_calls($file_name, $save_callback, 'formatPlural', $api_version);
_potx_find_format_plural_calls($file_name, $save_callback, 'PluralTranslatableMarkup', $api_version);
}
if ($name_parts['extension'] == 'module') {
if ($api_version < POTX_API_7) {
_potx_find_perm_hook($file_name, $name_parts['filename'], $save_callback);
}
if ($api_version > POTX_API_5) {
// @todo: if tabs are not defined on the menu hook anymore, exclude this for 8.
_potx_find_menu_hooks($file_name, $name_parts['filename'], $save_callback);
}
}
// Support @Translation annotation (in doc comments) on Drupal 8+.
if ($api_version > POTX_API_7) {
_potx_find_translation_annotations($file_name, $save_callback);
}
if ($constraint_extract) {
_potx_find_constraint_messages($file_name, $save_callback);
}
if ($api_version > POTX_API_7) {
_potx_process_inline_templates($file_name, $save_callback);
}
// Special handling of some Drupal core files.
if ($api_version < POTX_API_8 && (($basename == 'locale.inc' && $api_version < POTX_API_7) || $basename == 'iso.inc')) {
_potx_find_language_names($file_name, $save_callback, $api_version);
}
elseif ($api_version > POTX_API_7 && $basename == 'LanguageManager.php') {
_potx_find_language_names($file_name, $save_callback, $api_version);
}
elseif ($basename == 'locale.module') {
// Applies to all Drupal versions, yay!
_potx_add_date_strings($file_name, $save_callback, $api_version);
}
elseif ($basename == 'common.inc') {
// Applies to all Drupal versions, yay!
_potx_add_format_interval_strings($file_name, $save_callback, $api_version);
}
elseif ($basename == 'system.module') {
// Applies to all Drupal versions, yay!
_potx_add_default_region_names($file_name, $save_callback, $api_version);
}
elseif ($basename == 'user.module' && $api_version < POTX_API_8) {
// Save default user role names (up to Drupal 7).
$save_callback('anonymous user', POTX_CONTEXT_NONE, $file_name);
$save_callback('authenticated user', POTX_CONTEXT_NONE, $file_name);
if ($api_version > POTX_API_6) {
// Administator role is included by default from Drupal 7.
$save_callback('administrator', POTX_CONTEXT_NONE, $file_name);
}
}
}
/**
* Executes tasks that need to happen after all the files have been processed.
*
* @param string $save_callback
* @param int $api_version
*/
function potx_finish_processing($save_callback = '_potx_save_string', $api_version = POTX_API_CURRENT) {
global $yaml_translation_patterns;
global $_potx_module_metadata;
global $potx_callbacks;
if ($api_version > POTX_API_7) {
foreach ($_potx_module_metadata as $module_name => $module_metadata) {
$potx_callbacks['store_module_metadata']($module_name, $module_metadata);
}
// Parsing shipped configuration has to happen after processing all schemas.
_potx_parse_shipped_configuration($save_callback, $api_version);
// Clear yaml translation patterns, so translation patterns for a module
// won't be used for extracting translatable strings for another module.
$yaml_translation_patterns = NULL;
}
}
/**
* Creates complete file strings with _potx_store()
*
* @param $string_mode
* Strings to generate files for: POTX_STRING_RUNTIME or POTX_STRING_INSTALLER.
* @param $build_mode
* Storage mode used: single, multiple or core
* @param $force_name
* Forces a given file name to get used, if single mode is on, without extension
* @param $save_callback
* Callback used to save strings previously.
* @param $version_callback
* Callback used to save versions previously.
* @param $header_callback
* Callback to invoke to get the POT header.
* @param $template_export_langcode
* Language code if the template should have language dependent content
* (like plural formulas and language name) included.
* @param $translation_export_langcode
* Language code if translations should also be exported.
* @param $api_version
* Drupal API version to work with.
*/
function _potx_build_files($string_mode = POTX_STRING_RUNTIME, $build_mode = POTX_BUILD_SINGLE, $force_name = 'general', $save_callback = '_potx_save_string', $version_callback = '_potx_save_version', $header_callback = '_potx_get_header', $template_export_langcode = NULL, $translation_export_langcode = NULL, $api_version = POTX_API_CURRENT) {
global $_potx_store;
// Get Drupal core major version, to establish translation context support.
$core_version_major = 0;
if (defined('VERSION')) {
// 4.7, 5, 6, 7.
$core_version_major = VERSION;
}
elseif (class_exists('\\Drupal') && defined('\\Drupal::VERSION')) {
// 8.
$core_version_major = \Drupal::VERSION;
}
if ($core_version_major) {
if (($pos = strpos($core_version_major, '-'))) {
$core_version_major = substr($core_version_major, 0, $pos);
}
$core_version_major = (int) floor($core_version_major);
}
// Get strings and versions by reference.
$strings = $save_callback(NULL, NULL, NULL, 0, $string_mode);
$versions = $version_callback();
// We might not have any string recorded in this string mode.
if (!is_array($strings)) {
return;
}
foreach ($strings as $string => $string_info) {
foreach ($string_info as $context => $file_info) {
// Build a compact list of files this string occured in.
$occured = $file_list = array();
// Look for strings appearing in multiple directories (ie.
// different subprojects). So we can include them in general.pot.
$names = array_keys($file_info);
$last_location = dirname(array_shift($names));
$multiple_locations = FALSE;
foreach ($file_info as $file => $lines) {
$occured[] = "$file:". join(';', $lines);
if (isset($versions[$file])) {
$file_list[] = $versions[$file];
}
if (dirname($file) != $last_location) {
$multiple_locations = TRUE;
}
$last_location = dirname($file);
}
// Mark duplicate strings (both translated in the app and in the installer).
$comment = join(" ", $occured);
if (strpos($comment, '(dup)') !== FALSE) {
$comment = '(duplicate) '. str_replace('(dup)', '', $comment);
}
$output = "#: $comment\n";
if ($build_mode == POTX_BUILD_SINGLE) {
// File name forcing in single mode.
$file_name = $force_name;
}
elseif (strpos($comment, '.info')) {
// Store .info file strings either in general.pot or the module pot file,
// depending on the mode used.
$file_name = ($build_mode == POTX_BUILD_CORE ? 'general' : str_replace('.info', '.module', $file_name));
}
elseif ($multiple_locations) {
// Else if occured more than once, store in general.pot.
$file_name = 'general';
}
else {
// Fold multiple files in the same folder into one.
if (empty($last_location) || $last_location == '.') {
$file_name = 'root';
}
else {
$file_name = str_replace('/', '-', $last_location);
}
}
if (strpos($string, "\0") !== FALSE) {
// Plural strings have a null byte delimited format.
list($singular, $plural) = explode("\0", $string);
if (!empty($context)) {
$output .= "msgctxt \"$context\"\n";
}
$output .= "msgid \"$singular\"\n";
$output .= "msgid_plural \"$plural\"\n";
if (isset($translation_export_langcode)) {
if (!empty($context) && $core_version_major >= 7) {
$output .= _potx_translation_export($translation_export_langcode, $singular, $plural, $api_version, $context);
}
else {
$output .= _potx_translation_export($translation_export_langcode, $singular, $plural, $api_version);
}
}
else {
$output .= "msgstr[0] \"\"\n";
$output .= "msgstr[1] \"\"\n";
}
}
else {
// Simple strings.
if (!empty($context)) {
$output .= "msgctxt \"$context\"\n";
}
$output .= "msgid \"$string\"\n";
if (isset($translation_export_langcode)) {
if (!empty($context) && $core_version_major >= 7) {
$output .= _potx_translation_export($translation_export_langcode, $string, NULL, $api_version, $context);
}
else {
$output .= _potx_translation_export($translation_export_langcode, $string, NULL, $api_version);
}
}
else {
$output .= "msgstr \"\"\n";
}
}
$output .= "\n";
// Store the generated output in the given file storage.
if (!isset($_potx_store[$file_name])) {
$_potx_store[$file_name] = array(
'header' => $header_callback($file_name, $template_export_langcode, $api_version),
'sources' => $file_list,
'strings' => $output,
'count' => 1,
);
}
else {
// Maintain a list of unique file names.
$_potx_store[$file_name]['sources'] = array_unique(array_merge($_potx_store[$file_name]['sources'], $file_list));
$_potx_store[$file_name]['strings'] .= $output;
$_potx_store[$file_name]['count'] += 1;
}
}
}
}
/**
* Export translations with a specific language.
*
* @param $translation_export_langcode
* Language code if translations should also be exported.
* @param $string
* String or singular version if $plural was provided.
* @param $plural
* Plural version of singular string.
* @param $api_version
* Drupal API version to work with.
* @param $context
* Translation context (Drupal >=7).
*
* @return string
*/
function _potx_translation_export($translation_export_langcode, $string, $plural = NULL, $api_version = POTX_API_CURRENT, $context = '') {
// Stip out slash escapes.
$string = stripcslashes($string);
// Column and table name changed between versions.
$language_column = $api_version > POTX_API_5 ? 'language' : 'locale';
$language_table = $api_version > POTX_API_5 ? 'languages' : 'locales_meta';
if (!isset($plural)) {
// Single string to look translation up for.
if (!empty($context)) {
$translation = db_query("SELECT t.translation FROM {locales_source} s LEFT JOIN {locales_target} t ON t.lid = s.lid WHERE s.source = :source AND t.{$language_column} = :langcode AND context = :context", array(':source' => $string, ':langcode' => $translation_export_langcode, ':context' => $context))->fetchField();
}
else {
$translation = db_query("SELECT t.translation FROM {locales_source} s LEFT JOIN {locales_target} t ON t.lid = s.lid WHERE s.source = :source AND t.{$language_column} = :langcode", array(':source' => $string, ':langcode' => $translation_export_langcode))->fetchField();
}
if ($translation) {
return 'msgstr '. _locale_export_string($translation);
}
return "msgstr \"\"\n";
}
else {
// String with plural variants. Fill up source string array first.
$plural = stripcslashes($plural);
$strings = array();
$number_of_plurals = db_table_exists('{'. $language_table . '}') ?
db_query('SELECT plurals FROM {'. $language_table ."} WHERE {$language_column} = :langcode", array(':langcode' => $translation_export_langcode))->fetchField() :
0;
$plural_index = 0;
while ($plural_index < $number_of_plurals) {
if ($plural_index == 0) {
// Add the singular version.
$strings[] = $string;
}
elseif ($plural_index == 1) {
// Only add plural version if required.
$strings[] = $plural;
}
else {
// More plural versions only if required, with the lookup source
// string modified as imported into the database.
$strings[] = str_replace('@count', '@count['. $plural_index .']', $plural);
}
$plural_index++;
}
$output = '';
if (count($strings)) {
// Source string array was done, so export translations.
foreach ($strings as $index => $string) {
if ($translation = db_query("SELECT t.translation FROM {locales_source} s LEFT JOIN {locales_target} t ON t.lid = s.lid WHERE s.source = :source AND t.{$language_column} = :langcode", array(':source' => $string, ':langcode' => $translation_export_langcode))->fetchField()) {
$output .= 'msgstr['. $index .'] '. _locale_export_string(_locale_export_remove_plural($translation));
}
else {
$output .= "msgstr[". $index ."] \"\"\n";
}
}
}
else {
// No plural information was recorded, so export empty placeholders.
$output .= "msgstr[0] \"\"\n";
$output .= "msgstr[1] \"\"\n";
}
return $output;
}
}
/**
* Returns a header generated for a given file
*
* @param $file
* Name of POT file to generate header for
* @param $template_export_langcode
* Language code if the template should have language dependent content
* (like plural formulas and language name) included.
* @param $api_version
* Drupal API version to work with.
*/
function _potx_get_header($file, $template_export_langcode = NULL, $api_version = POTX_API_CURRENT) {
// We only have language to use if we should export with that langcode.
$language = NULL;
if ($template_export_langcode) {
$language = \Drupal::service('language_manager')->getLanguage($template_export_langcode);
$plurals = \Drupal::service('locale.plural.formula')->getNumberOfPlurals($template_export_langcode);
$formula = '(n!=1)';
}
$output = '# $'.'Id'.'$'."\n";
$output .= "#\n";
$output .= '# '. (isset($language) ? $language->getName() : 'LANGUAGE') .' translation of Drupal ('. $file .")\n";
$output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
$output .= "# --VERSIONS--\n";
$output .= "#\n";
$output .= "#, fuzzy\n";
$output .= "msgid \"\"\n";
$output .= "msgstr \"\"\n";
$output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
$output .= '"POT-Creation-Date: '. date("Y-m-d H:iO") ."\\n\"\n";
$output .= '"PO-Revision-Date: '. (isset($language) ? date("Y-m-d H:iO") : 'YYYY-mm-DD HH:MM+ZZZZ') ."\\n\"\n";
$output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
$output .= "\"Language-Team: ". (isset($language) ? $language->getName() : 'LANGUAGE') ." <EMAIL@ADDRESS>\\n\"\n";
$output .= "\"MIME-Version: 1.0\\n\"\n";
$output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
$output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
if (isset($formula) && isset($plurals)) {
$output .= "\"Plural-Forms: nplurals=". $plurals ."; plural=". $formula) .";\\n\"\n\n";
}
else {
$output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
}
return $output;
}
/**
* Write out generated files to the current folder.
*
* @param $http_filename
* File name for content-disposition header in case of usage
* over HTTP. If not given, files are written to the local filesystem.
* @param $content_disposition
* See RFC2183. 'inline' or 'attachment', with a default of
* 'inline'. Only used if $http_filename is set.
* @todo
* Look into whether multiple files can be output via HTTP.
*/
function _potx_write_files($http_filename = NULL, $content_disposition = 'inline') {
global $_potx_store;
// Generate file lists and output files.
if (is_array($_potx_store)) {
foreach ($_potx_store as $file => $contents) {
// Build replacement for file listing.
if (count($contents['sources']) > 1) {
$filelist = "Generated from files:\n# " . join("\n# ", $contents['sources']);
}
elseif (count($contents['sources']) == 1) {
$filelist = "Generated from file: " . join('', $contents['sources']);
}
else {
$filelist = 'No version information was available in the source files.';
}
$output = str_replace('--VERSIONS--', $filelist, $contents['header'] . $contents['strings']);
if ($http_filename) {
// HTTP output.
header('Content-Type: text/plain; charset=utf-8');
header('Content-Transfer-Encoding: 8bit');
header("Content-Disposition: $content_disposition; filename=$http_filename");
print $output;
return;
}
else {
// Local file output, flatten directory structure.
$file = str_replace('.', '-', preg_replace('![/]?([a-zA-Z_0-9]*/)*!', '', $file)) .'.pot';
$fp = fopen($file, 'w');
fwrite($fp, $output);
fclose($fp);
}
}
}
}
/**
* Escape quotes in a strings depending on the surrounding
* quote type used.
*
* @param $str
* The strings to escape
*/
function _potx_format_quoted_string($str) {
$quo = substr($str, 0, 1);
$str = substr($str, 1, -1);
if ($quo == '"') {
$str = stripcslashes($str);
}
else {
$str = strtr($str, array("\\'" => "'", "\\\\" => "\\"));
}
return addcslashes($str, "\0..\37\\\"");
}
/**
* Output a marker error with an extract of where the error was found.
*
* @param $file
* Name of file
* @param $line
* Line number of error
* @param $marker
* Function name with which the error was identified
* @param $ti
* Index on the token array
* @param $error
* Helpful error message for users.
* @param $docs_url
* Documentation reference.
*/
function _potx_marker_error($file, $line, $marker, $ti, $error, $docs_url = NULL) {
global $_potx_tokens;
$tokens = '';
$ti += 2;
$tc = count($_potx_tokens);
$par = 1;
while ((($tc - $ti) > 0) && $par) {
if (is_array($_potx_tokens[$ti])) {
$tokens .= $_potx_tokens[$ti][1];
}
else {
$tokens .= $_potx_tokens[$ti];
if ($_potx_tokens[$ti] == "(") {
$par++;
}
else if ($_potx_tokens[$ti] == ")") {
$par--;
}
}
$ti++;
}
potx_status('error', $error, $file, $line, $marker .'('. $tokens, $docs_url);
}
/**
* Status notification function.
*
* @param $op
* Operation to perform or type of message text.
* - set: sets the reporting mode to $value
* use one of the POTX_STATUS_* constants as $value
* - get: returns the list of error messages recorded
* if $value is true, it also clears the internal message cache
* - error: sends an error message in $value with optional $file and $line
* - status: sends a status message in $value
* @param $value
* Value depending on $op.
* @param $file
* Name of file the error message is related to.
* @param $line
* Number of line the error message is related to.
* @param $excerpt
* Excerpt of the code in question, if available.
* @param $docs_url
* URL to the guidelines to follow to fix the problem.
*/
function potx_status($op, $value = NULL, $file = NULL, $line = NULL, $excerpt = NULL, $docs_url = NULL) {
static $mode = POTX_STATUS_CLI;
static $messages = array();
switch ($op) {
case 'set':
// Setting the reporting mode.
$mode = $value;
return;
case 'get':
// Getting the errors. Optionally deleting the messages.
$errors = $messages;
if (!empty($value)) {
$messages = array();
}
return $errors;
case 'error':
case 'status':
// Location information is required in 3 of the four possible reporting
// modes as part of the error message. The structured mode needs the
// file, line and excerpt info separately, not in the text.
$location_info = '';
if (($mode != POTX_STATUS_STRUCTURED) && isset($file)) {
if (isset($line)) {
if (isset($excerpt)) {
$location_info = t('At %excerpt in %file on line %line.', array('%excerpt' => $excerpt, '%file' => $file, '%line' => $line));
}
else {
$location_info = t('In %file on line %line.', array('%file' => $file, '%line' => $line));
}
}
else {
if (isset($excerpt)) {
$location_info = t('At %excerpt in %file.', array('%excerpt' => $excerpt, '%file' => $file));
}
else {
$location_info = t('In %file.', array('%file' => $file));
}
}
}
// Documentation helpers are provided as readable text in most modes.
$read_more = '';
if (($mode != POTX_STATUS_STRUCTURED) && isset($docs_url)) {
$read_more = ($mode == POTX_STATUS_CLI) ? t('Read more at @url', array('@url' => $docs_url)) : t('Read more at <a href="@url">@url</a>', array('@url' => $docs_url));
}
// Error message or progress text to display.
switch ($mode) {
case POTX_STATUS_MESSAGE:
drupal_set_message(join(' ', array($value, $location_info, $read_more)), $op);
break;
case POTX_STATUS_CLI:
fwrite($op == 'error' ? STDERR : STDOUT, join("\n", array($value, $location_info, $read_more)) ."\n\n");
break;
case POTX_STATUS_SILENT:
if ($op == 'error') {
$messages[] = join(' ', array($value, $location_info, $read_more));
}
break;
case POTX_STATUS_STRUCTURED:
if ($op == 'error') {
$messages[] = array($value, $file, $line, $excerpt, $docs_url);
}
break;
}
return;
}
}
/**
* Detect all occurances of t()-like calls.
*
* These sequences are searched for:
* T_STRING("$function_name") + "(" + T_CONSTANT_ENCAPSED_STRING + ")"
* T_STRING("$function_name") + "(" + T_CONSTANT_ENCAPSED_STRING + ","
*
* @param $file
* Name of file parsed.
* @param $save_callback
* Callback function used to save strings.
* @param function_name
* The name of the function to look for (could be 't', '$t', 'st'
* or any other t-like function).
* @param $string_mode
* String mode to use: POTX_STRING_INSTALLER, POTX_STRING_RUNTIME or
* POTX_STRING_BOTH.
*/
function _potx_find_t_calls($file, $save_callback, $function_name = 't', $string_mode = POTX_STRING_RUNTIME) {
global $_potx_tokens, $_potx_lookup;
// Lookup tokens by function name.
if (isset($_potx_lookup[$function_name])) {
foreach ($_potx_lookup[$function_name] as $ti) {
list($prev, $ctok, $par, $mid, $rig) = array($_potx_tokens[$ti - 1], $_potx_tokens[$ti], $_potx_tokens[$ti+1], $_potx_tokens[$ti+2], $_potx_tokens[$ti+3]);
list($type, $string, $line) = $ctok;
if (is_array($prev) && $prev[0] == T_FUNCTION) {
continue;
}
if ($function_name == 'debug' && is_array($prev) && $prev[0] != T_OBJECT_OPERATOR) {
continue;
}
if ($par == "(") {
if (in_array($rig, array(")", ","))
&& (is_array($mid) && ($mid[0] == T_CONSTANT_ENCAPSED_STRING))) {
// This function is only used for context-less call types.
$save_callback(_potx_format_quoted_string($mid[1]), POTX_CONTEXT_NONE, $file, $line, $string_mode);
}
else {
// $function_name() found, but inside is something which is not a string literal.
_potx_marker_error($file, $line, $function_name, $ti, t('The first parameter to @function() should be a literal string. There should be no variables, concatenation, constants or other non-literal strings there.', array('@function' => $function_name)), 'http://drupal.org/node/322732');
}
}
}
}
}
/**
* Detect all occurances of t()-like calls from Drupal 7 (with context).
*
* These sequences are searched for:
* T_STRING("$function_name") + "(" + T_CONSTANT_ENCAPSED_STRING + ")"
* T_STRING("$function_name") + "(" + T_CONSTANT_ENCAPSED_STRING + ","
* and then an optional value for the replacements and an optional array
* for the options with an optional context key.
*
* @param $file
* Name of file parsed.
* @param $save_callback
* Callback function used to save strings.
* @param function_name
* The name of the function to look for (could be 't', '$t', 'st'
* or any other t-like function). Drupal 7 only supports context on t(), st()
* and $t().
* @param $string_mode
* String mode to use: POTX_STRING_INSTALLER, POTX_STRING_RUNTIME or
* POTX_STRING_BOTH.
*/
function _potx_find_t_calls_with_context($file, $save_callback, $function_name = 't', $string_mode = POTX_STRING_RUNTIME) {
global $_potx_tokens, $_potx_lookup;
// Lookup tokens by function name.
if (isset($_potx_lookup[$function_name])) {
foreach ($_potx_lookup[$function_name] as $ti) {
if (count($_potx_tokens) <= $ti + 3 || $_potx_tokens[$ti+1] != '(') {
// This is not a t() call or similar, e.g. "TranslatableMarkup" in "class TranslationWrapper extends TranslatableMarkup {}"
continue;
}
list($prev, $ctok, $par, $mid, $rig) = array($_potx_tokens[$ti - 1], $_potx_tokens[$ti], $_potx_tokens[$ti+1], $_potx_tokens[$ti+2], $_potx_tokens[$ti+3]);
list($type, $string, $line) = $ctok;
if (is_array($prev) && $prev[0] == T_FUNCTION) {
continue;
}
if ($par == "(") {
if (in_array($rig, array(")", ","))
&& (is_array($mid) && ($mid[0] == T_CONSTANT_ENCAPSED_STRING))) {
// By default, there is no context.
$context = POTX_CONTEXT_NONE;
if ($rig == ',') {
// If there was a comma after the string, we need to look forward