summaryrefslogtreecommitdiffstats
path: root/potx.inc
blob: 9f3351a411b9019f6b33511c79c3b833cd1522ff (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
<?php

/**
 * @file
 *   Localization string extraction API.
 *
 *   The main goal of the API is to let callers parse Drupal source code files
 *   and get strings found using the localization API.
 *
 *   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.
 *
 *   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
 */

/**
 * The current Drupal major API verion.
 *
 * This should be the only difference between different branches of potx.inc
 */
define('POTX_API_CURRENT', 7);

/**
 * 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);

/**
 * 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);

// === File lookup, parsing and output building ================================

/**
 * Collect a list of source file names relevant for extraction.
 *
 * @param $path
 *   Where to start searching for files recursively.
 *   Provide non-empty path values with a trailing slash.
 * @param $basename
 *   Allows the restriction of search to a specific basename
 *   (ie. to collect files for a specific module).
 * @param $api_version
 *   Drupal API version to work with.
 */
function potx_parser_source_files($path = '', $basename = '*', $api_version = POTX_API_CURRENT) {
  // It would be so nice to just use GLOB_BRACE, but it is not available on all
  // operarting systems, so we are working around the missing functionality by
  // going thrugh per extension.
  $extensions = array('php', 'inc', 'module', 'engine', 'theme', 'install', 'info', 'profile');
  if ($api_version > POTX_API_5) {
    $extensions[] = 'js';
  }
  $files = array();
  foreach ($extensions as $extension) {
    $files_here = glob($path . $basename . '.' . $extension);
    if (is_array($files_here)) {
      $files = array_merge($files, $files_here);
    }
    if ($basename != '*') {
      // Basename was specific, so look for things like basename.admin.inc as well.
      // If the basnename was *, the above glob() already covered this case.
      $files_here = glob($path . $basename . '.*.' . $extension);
      if (is_array($files_here)) {
        $files = array_merge($files, $files_here);
      }
    }
  }

  // Grab subdirectories.
  $dirs = glob($path . '*', GLOB_ONLYDIR);
  if (is_array($dirs)) {
    foreach ($dirs as $dir) {
      // Skip CVS, svn and git data as well as tests.
      if (!preg_match("!(^|.+/)(CVS|\.svn|\.git|tests)$!", $dir)) {
        $files = array_merge($files, potx_parser_source_files("$dir/", $basename));
      }
    }
  }

  foreach ($files as $id => $file_name) {
    // Skip API and test files.
    if (preg_match('!(\.api\.php|\.test)$!', $file_name)) {
      unset($files[$id]);
    }
  }
  return $files;
}

/**
 * Process a file and save extracted information with the callbacks given.
 *
 * @param $file_path
 *   Comlete path to file to process.
 * @param $display_name
 *   Display oriented file name for saved string data and error messages.
 * @param $string_save_callback
 *   Callback function to use to save the collected strings.
 * @param $file_version_callback
 *   Callback function to use to save collected version numbers.
 * @param $api_version
 *   Drupal API version to work with.
 */
function potx_parser_parse_file($file_path, $display_name = '', $string_save_callback = 'potx_parser_callback_save_string', $file_version_callback = 'potx_parser_callback_version', $api_version = POTX_API_CURRENT) {
  global $_potx_tokens, $_potx_lookup;

  $basename = basename($file_path);
  $name_parts = pathinfo($basename);
  $display_name = empty($display_name) ? $file_path : $display_name;

  // Grab the CVS version number from the code if available.
  // @todo: Drupal is moving to git, so this will not have much meaning then.
  $code = file_get_contents($file_path);
  potx_parser_get_version_number($code, $display_name, $file_version_callback);

  if ($name_parts['extension'] == 'info') {
    // .info files are not PHP code, no need to tokenize.
    potx_parser_get_info_strings($file_path, $display_name, $string_save_callback, $api_version);
    return;
  }
  elseif ($name_parts['extension'] == 'js') {
    // JS files are not PHP code, no need to tokenize.
    if ($api_version > POTX_API_5) {
      potx_parser_get_js_strings($code, $display_name, $string_save_callback);
    }
    return;
  }

  // Extract raw PHP language tokens.
  $raw_tokens = token_get_all($code);
  unset($code);

  // List of tokens to get an index of, so we can do quick lookups of use of
  // these functions and don't need to look through the whole token array.
  $tokens_to_index = array(
    't',
    'st',
    '_locale_import_message',
    'watchdog',
    'format_plural',
    $name_parts['filename'] . '_perm',
    'node_perm',
    $name_parts['filename'] . '_menu',
    $name_parts['filename'] . '_menu_alter',
    '_locale_get_predefined_list',
    '_locale_get_iso639_list',
  );

  // 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;
         // Fill an array for finding token offsets quickly. We need the $t
         // entries, as well as other functions invoked in the code that we
         // look for.
         if (($token[0] == T_STRING && in_array($token[1], $tokens_to_index)) || ($token[0] == T_VARIABLE && $token[1] == '$t')) {
           if (!isset($_potx_lookup[$token[1]])) {
             $_potx_lookup[$token[1]] = array();
           }
           $_potx_lookup[$token[1]][] = $token_number;
         }
      }
      $_potx_tokens[] = $token;
      $token_number++;
    }

    // Keep track of line numbers based on newlines in the token we just
    // processed.
    if (is_array($token)) {
      $line_number += count(explode("\n", $token[1])) - 1;
    }
    else {
      $line_number += count(explode("\n", $token)) - 1;
    }
  }
  unset($raw_tokens);

  // Drupal 7 onwards supports context on t(), st() and $t().
  $use_context = ($api_version > POTX_API_6);
  potx_parser_find_t_strings($display_name, $string_save_callback, 't',  POTX_STRING_RUNTIME, $use_context);
  potx_parser_find_t_strings($display_name, $string_save_callback, '$t', POTX_STRING_BOTH, $use_context);
  potx_parser_find_t_strings($display_name, $string_save_callback, 'st', POTX_STRING_INSTALLER, $use_context);

  // This does not support context even in Drupal 7.
  potx_parser_find_t_strings($display_name, $string_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.
    potx_parser_find_watchdog_strings($display_name, $string_save_callback);
  }
  else {
    // Watchdog calls only have their first argument translated in Drupal 5.x
    // and before.
    potx_parser_find_t_strings($display_name, $string_save_callback, 'watchdog');
  }

  // Plurals need unique parsing.
  potx_parser_find_format_plural_strings($display_name, $string_save_callback, $api_version);

  if ($name_parts['extension'] == 'module') {
    if ($api_version < POTX_API_7) {
      potx_parser_find_perm_strings($display_name, $name_parts['filename'], $string_save_callback);
    }
    if ($api_version > POTX_API_5) {
      potx_parser_find_menu_strings($display_name, $name_parts['filename'], $string_save_callback);
    }
  }

  // Special handling of some Drupal core files.
  if (($basename == 'locale.inc' && $api_version < POTX_API_7) || $basename == 'iso.inc') {
    potx_parser_find_language_strings($display_name, $string_save_callback, $api_version);
  }
  elseif ($basename == 'locale.module') {
    potx_parser_add_date_strings($display_name, $string_save_callback, $api_version);
  }
  elseif ($basename == 'common.inc') {
    potx_parser_add_format_interval_strings($display_name, $string_save_callback, $api_version);
  }
  elseif ($basename == 'system.module') {
    potx_parser_add_default_region_strings($display_name, $string_save_callback, $api_version);
  }
  elseif ($basename == 'user.module') {
    // Save default user role names.
    $string_save_callback('anonymous user', POTX_CONTEXT_NONE, $display_name);
    $string_save_callback('authenticated user', POTX_CONTEXT_NONE, $display_name);
    if ($api_version > POTX_API_6) {
      // Administator role is included by default from Drupal 7.
      $string_save_callback('administrator', POTX_CONTEXT_NONE, $display_name);
    }
  }

  // Drop this data set that we don't need anymore.
  $_potx_tokens = $_potx_lookup = array();
}

/**
 * Build a complete .po file based on string data collected earlier.
 *
 * @param $string_mode
 *   Strings to generate files for: POTX_STRING_RUNTIME or POTX_STRING_INSTALLER.
 * @param $string_save_callback
 *   Callback used to save strings previously.
 * @param $file_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_parser_build_output($string_mode = POTX_STRING_RUNTIME,  $string_save_callback = 'potx_parser_callback_save_string', $file_version_callback = 'potx_parser_callback_version', $header_callback = 'potx_parser_callback_header', $template_export_langcode = NULL, $translation_export_langcode = NULL, $api_version = POTX_API_CURRENT) {

  // Initialize storage for .po file output.
  $data = array(
    'header'  => $header_callback($template_export_langcode, $api_version),
    'sources' => array(),
    'strings' => '',
  );

  // Get strings and versions by reference.
  $strings  = $string_save_callback(NULL, NULL, NULL, 0, $string_mode);
  $versions = $file_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();
      foreach ($file_info as $file => $lines) {
        $occured[] = $file . ':' . join(';', $lines);
        if (isset($versions[$file])) {
          $file_list[] = $versions[$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 (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)) {
          $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)) {
          $output .= _potx_translation_export($translation_export_langcode, $string, NULL, $api_version);
        }
        else {
          $output .= "msgstr \"\"\n";
        }
      }
      $output .= "\n";

      // Maintain a list of unique file names.
      $data['sources']  = array_unique(array_merge($data['sources'], $file_list));
      $data['strings'] .= $output;
    }
  }

  // Build replacement for file listing.
  if (count($data['sources']) > 1) {
    $filelist = "Generated from files:\n#  " . join("\n#  ", $data['sources']);
  }
  elseif (count($data['sources']) == 1) {
    $filelist = "Generated from file: " . join('', $data['sources']);
  }
  else {
    $filelist = 'No version information was available in the source files.';
  }
  return str_replace('--VERSIONS--', $filelist, $data['header']) . $data['strings'];
}

/**
 * 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.
 */
function _potx_translation_export($translation_export_langcode, $string, $plural = NULL, $api_version = POTX_API_CURRENT) {
  include_once 'includes/locale.inc';

  // 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 ($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()) {
      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_query('SELECT plurals FROM {' . $language_table . "} WHERE {$language_column} = :langcode", array(':langcode' => $translation_export_langcode))->fetchField();
    $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;
  }
}

// === Token based code tree parsers ===========================================

/**
 * 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 + ","
 *   and then an optional value for the replacements and an optional array
 *   for the options with an optional context key (for Drupal 7+).
 *
 * @param $display_name
 *   Name of file parsed.
 * @param $string_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.
 * @param $context_support
 *   Whether we should look for string context provided.
 */
function potx_parser_find_t_strings($display_name, $string_save_callback, $function_name = 't', $string_mode = POTX_STRING_RUNTIME, $context_support = FALSE) {
  global $_potx_tokens, $_potx_lookup;

  // Lookup tokens by function name.
  if (isset($_potx_lookup[$function_name])) {
    foreach ($_potx_lookup[$function_name] as $ti) {
      list($ctok, $par, $mid, $rig) = array($_potx_tokens[$ti], $_potx_tokens[$ti+1], $_potx_tokens[$ti+2], $_potx_tokens[$ti+3]);
      list($type, $string, $line) = $ctok;
      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 ($context_support && ($rig == ',')) {
            // If there was a comma after the string, we need to look forward
            // to try and find the context.
            $context = potx_parser_util_context($ti, $ti + 4, $display_name, $function_name);
          }
          if ($context !== POTX_CONTEXT_ERROR) {
            // Only save if there was no error in context parsing.
            $string_save_callback(potx_parser_util_format_string($mid[1]), $context, $display_name, $line, $string_mode);
          }
          else {
            // $function_name() found, but the context is not good.
            potx_parser_util_token_error($display_name, $line, $function_name, $ti, t('The context specified for @function() is not valid.', array('@function' => $function_name)));
          }
        }
        else {
          // $function_name() found, but inside is something which is not a string literal.
          potx_parser_util_token_error($display_name, $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 watchdog() calls. Only from Drupal 6.
 *
 * These sequences are searched for:
 *   watchdog + "(" + T_CONSTANT_ENCAPSED_STRING + "," +
 *   T_CONSTANT_ENCAPSED_STRING + something
 *
 * @param $display_name
 *   Name of file parsed.
 * @param $string_save_callback
 *   Callback function used to save strings.
 */
function potx_parser_find_watchdog_strings($display_name, $string_save_callback) {
  global $_potx_tokens, $_potx_lookup;

  // Lookup tokens by function name.
  if (isset($_potx_lookup['watchdog'])) {
    foreach ($_potx_lookup['watchdog'] as $ti) {
      list($ctok, $par, $mtype, $comma, $message, $rig) = array($_potx_tokens[$ti], $_potx_tokens[$ti+1], $_potx_tokens[$ti+2], $_potx_tokens[$ti+3], $_potx_tokens[$ti+4], $_potx_tokens[$ti+5]);
      list($type, $string, $line) = $ctok;
      if ($par == '(') {
        // Both type and message should be a string literal.
        if (in_array($rig, array(')', ',')) && $comma == ','
          && (is_array($mtype) && ($mtype[0] == T_CONSTANT_ENCAPSED_STRING))
          && (is_array($message) && ($message[0] == T_CONSTANT_ENCAPSED_STRING))) {
            // Context is not supported on watchdog().
            $string_save_callback(potx_parser_util_format_string($mtype[1]), POTX_CONTEXT_NONE, $display_name, $line);
            $string_save_callback(potx_parser_util_format_string($message[1]), POTX_CONTEXT_NONE, $display_name, $line);
        }
        else {
          // watchdog() found, but inside is something which is not a string literal.
          potx_parser_util_token_error($display_name, $line, 'watchdog', $ti, t('The first two watchdog() parameters should be literal strings. There should be no variables, concatenation, constants or even a t() call there.'), 'http://drupal.org/node/323101');
        }
      }
    }
  }
}

/**
 * Detect all occurances of format_plural calls.
 *
 * These sequences are searched for:
 *   T_STRING("format_plural") + "(" + ..anything (might be more tokens).. +
 *   "," + T_CONSTANT_ENCAPSED_STRING +
 *   "," + T_CONSTANT_ENCAPSED_STRING + parenthesis (or comma allowed from
 *   Drupal 6)
 *
 * @param $display_name
 *   Name of file parsed.
 * @param $string_save_callback
 *   Callback function used to save strings.
 * @param $api_version
 *   Drupal API version to work with.
 */
function potx_parser_find_format_plural_strings($display_name, $string_save_callback, $api_version = POTX_API_CURRENT) {
  global $_potx_tokens, $_potx_lookup;

  if (isset($_potx_lookup['format_plural'])) {
    foreach ($_potx_lookup['format_plural'] as $ti) {
      list($ctok, $par1) = array($_potx_tokens[$ti], $_potx_tokens[$ti+1]);
      list($type, $string, $line) = $ctok;
      if ($par1 == "(") {
        // Eat up everything that is used as the first parameter
        $tn = $ti + 2;
        $depth = 0;
        while (!($_potx_tokens[$tn] == "," && $depth == 0)) {
          if ($_potx_tokens[$tn] == "(") {
            $depth++;
          }
          elseif ($_potx_tokens[$tn] == ")") {
            $depth--;
          }
          $tn++;
        }
        // Get further parameters
        list($comma1, $singular, $comma2, $plural, $par2) = array($_potx_tokens[$tn], $_potx_tokens[$tn+1], $_potx_tokens[$tn+2], $_potx_tokens[$tn+3], $_potx_tokens[$tn+4]);
        if (($comma2 == ',') && ($par2 == ')' || ($par2 == ',' && $api_version > POTX_API_5)) &&
          (is_array($singular) && ($singular[0] == T_CONSTANT_ENCAPSED_STRING)) &&
          (is_array($plural) && ($plural[0] == T_CONSTANT_ENCAPSED_STRING))) {
          // By default, there is no context.
          $context = POTX_CONTEXT_NONE;
          if ($par2 == ',' && ($api_version > POTX_API_6)) {
            // If there was a comma after the plural, we need to look forward
            // to try and find the context.
            $context = potx_parser_util_context($ti, $tn + 5, $display_name, 'format_plural');
          }
          if ($context !== POTX_CONTEXT_ERROR) {
            // Only save if there was no error in context parsing.
            $string_save_callback(
              potx_parser_util_format_string($singular[1]) . "\0" . potx_parser_util_format_string($plural[1]),
              $context,
              $display_name,
              $line
            );
          }
          else {
            // format_plural() found, but the context is not good.
            potx_parser_util_token_error($display_name, $line, 'format_plural', $ti, t('The context specified for format_plural() is not valid.'));
          }
        }
        else {
          // format_plural() found, but the parameters are not correct.
          potx_parser_util_token_error($display_name, $line, 'format_plural', $ti, t('In format_plural(), the singular and plural strings should be literal strings. There should be no variables, concatenation, constants or even a t() call there.'), 'http://drupal.org/node/323072');
        }
      }
    }
  }
}

/**
 * Detect permission names from the hook_perm() implementations.
 *
 * Note that this will get confused with a similar pattern in a comment,
 * and with dynamic permissions, which need to be accounted for.
 *
 * @param $display_name
 *   Full path name of file parsed.
 * @param $filebase
 *   Filenaname of file parsed.
 * @param $string_save_callback
 *   Callback function used to save strings.
 */
function potx_parser_find_perm_strings($display_name, $filebase, $string_save_callback) {
  global $_potx_tokens, $_potx_lookup;

  if (isset($_potx_lookup[$filebase . '_perm'])) {
    // Special case for node module, because it uses dynamic permissions.
    // Include the static permissions by hand. That's about all we can do here.
    if ($filebase == 'node') {
      $line = $_potx_tokens[$_potx_lookup['node_perm'][0]][2];
      // List from node.module 1.763 (checked in on 2006/12/29 at 21:25:36 by drumm)
      $nodeperms = array('administer content types', 'administer nodes', 'access content', 'view revisions', 'revert revisions');
      foreach ($nodeperms as $item) {
        // hook_perm() is only ever found on a Drupal system which does not
        // support context.
        $string_save_callback($item, POTX_CONTEXT_NONE, $display_name, $line);
      }
    }
    else {
      $count = 0;
      foreach ($_potx_lookup[$filebase . '_perm'] as $ti) {
        $tn = $ti;
        while (is_array($_potx_tokens[$tn]) || $_potx_tokens[$tn] != '}') {
          if (is_array($_potx_tokens[$tn]) && $_potx_tokens[$tn][0] == T_CONSTANT_ENCAPSED_STRING) {
            // hook_perm() is only ever found on a Drupal system which does not
            // support context.
            $string_save_callback(potx_parser_util_format_string($_potx_tokens[$tn][1]), POTX_CONTEXT_NONE, $display_name, $_potx_tokens[$tn][2]);
            $count++;
          }
          $tn++;
        }
      }
      if (!$count) {
        potx_parser_util_set_message(t('%hook should have an array of literal string permission names.', array('%hook' => $filebase . '_perm()')), $display_name, NULL, NULL, 'http://drupal.org/node/323101');
      }
    }
  }
}

/**
 * List of menu item titles. Only from Drupal 6.
 *
 * @param $display_name
 *   Full path name of file parsed.
 * @param $filebase
 *   Filenaname of file parsed.
 * @param $string_save_callback
 *   Callback function used to save strings.
 */
function potx_parser_find_menu_strings($display_name, $filebase, $string_save_callback) {
  global $_potx_tokens, $_potx_lookup;

  $hooks = array('_menu', '_menu_alter');
  $keys = array("'title'", '"title"', "'description'", '"description"');

  foreach ($hooks as $hook) {
    if (isset($_potx_lookup[$filebase . $hook]) && is_array($_potx_lookup[$filebase . $hook])) {
      // We have this menu hook in this file.
      foreach ($_potx_lookup[$filebase . $hook] as $ti) {
        $end = potx_parser_util_end_of_function($ti);
        $tn = $ti;
        while ($tn < $end) {

          // Support for array syntax more commonly used in menu hooks:
          // $items = array('node/add' => array('title' => 'Add content'));
          if ($_potx_tokens[$tn][0] == T_CONSTANT_ENCAPSED_STRING && in_array($_potx_tokens[$tn][1], $keys) && $_potx_tokens[$tn+1][0] == T_DOUBLE_ARROW) {
            if ($_potx_tokens[$tn+2][0] == T_CONSTANT_ENCAPSED_STRING) {
              // We cannot export menu item context.
              $string_save_callback(
                potx_parser_util_format_string($_potx_tokens[$tn+2][1]),
                POTX_CONTEXT_NONE,
                $display_name,
                $_potx_tokens[$tn+2][2]
              );
              $tn+=2; // Jump forward by 2.
            }
            else {
              potx_parser_util_set_message(t('Invalid menu %element definition found in %hook. Title and description keys of the menu array should be literal strings.', array('%element' => $_potx_tokens[$tn][1], '%hook' => $filebase . $hook . '()')), $display_name, $_potx_tokens[$tn][2], NULL, 'http://drupal.org/node/323101');
            }
          }

          // Support for array syntax more commonly used in menu alters:
          // $items['node/add']['title'] = 'Add content here';
          if (is_string($_potx_tokens[$tn]) && $_potx_tokens[$tn] == '[' && $_potx_tokens[$tn+1][0] == T_CONSTANT_ENCAPSED_STRING && in_array($_potx_tokens[$tn+1][1], $keys) && is_string($_potx_tokens[$tn+2]) && $_potx_tokens[$tn+2] == ']') {
            if (is_string($_potx_tokens[$tn+3]) && $_potx_tokens[$tn+3] == '=' && $_potx_tokens[$tn+4][0] == T_CONSTANT_ENCAPSED_STRING) {
              // We cannot export menu item context.
              $string_save_callback(
                potx_parser_util_format_string($_potx_tokens[$tn+4][1]),
                POTX_CONTEXT_NONE,
                $display_name,
                $_potx_tokens[$tn+4][2]
              );
              $tn+=4; // Jump forward by 4.
            }
            else {
              potx_parser_util_set_message(t('Invalid menu %element definition found in %hook. Title and description keys of the menu array should be literal strings.', array('%element' => $_potx_tokens[$tn+1][1], '%hook' => $filebase . $hook . '()')), $display_name, $_potx_tokens[$tn+1][2], NULL, 'http://drupal.org/node/323101');
            }
          }
          $tn++;
        }
      }
    }
  }
}

/**
 * Get languages names from Drupal's locale.inc.
 *
 * @param $display_name
 *   Full path name of file parsed
 * @param $string_save_callback
 *   Callback function used to save strings.
 * @param $api_version
 *   Drupal API version to work with.
 */
function potx_parser_find_language_strings($display_name, $string_save_callback, $api_version = POTX_API_CURRENT) {
  global $_potx_tokens, $_potx_lookup;

  foreach ($_potx_lookup[$api_version > POTX_API_5 ? '_locale_get_predefined_list' : '_locale_get_iso639_list'] as $ti) {
    // Search for the definition of _locale_get_predefined_list(), not where it is called.
    if ($_potx_tokens[$ti-1][0] == T_FUNCTION) {
      break;
    }
  }

  $end = potx_parser_util_end_of_function($ti);
  $ti += 7; // function name, (, ), {, return, array, (
  while ($ti < $end) {
    while ($_potx_tokens[$ti][0] != T_ARRAY) {
      if (!is_array($_potx_tokens[$ti]) && $_potx_tokens[$ti] == ';') {
        // We passed the end of the list, break out to function level
        // to prevent an infinite loop.
        break 2;
      }
      $ti++;
    }
    $ti += 2; // array, (
    // Language names are context-less.
    $string_save_callback(potx_parser_util_format_string($_potx_tokens[$ti][1]), POTX_CONTEXT_NONE, $display_name, $_potx_tokens[$ti][2]);
  }
}

// === Standard set of string additions ========================================

/**
 * Add date strings, which cannot be extracted otherwise.
 *
 * This is called for locale.module.
 *
 * @param $display_name
 *   Name of the file parsed.
 * @param $string_save_callback
 *   Callback function used to save strings.
 * @param $api_version
 *   Drupal API version to work with.
 */
function potx_parser_add_date_strings($display_name, $string_save_callback, $api_version = POTX_API_CURRENT) {
  for ($i = 1; $i <= 12; $i++) {
    $stamp = mktime(0, 0, 0, $i, 1, 1971);
    if ($api_version > POTX_API_6) {
      // From Drupal 7, long month names are saved with this context.
      $string_save_callback(date("F", $stamp), 'Long month name', $display_name);
    }
    elseif ($api_version > POTX_API_5) {
      // Drupal 6 uses a little hack. No context.
      $string_save_callback('!long-month-name ' . date("F", $stamp), POTX_CONTEXT_NONE, $display_name);
    }
    else {
      // Older versions just accept the confusion, no context.
      $string_save_callback(date("F", $stamp), POTX_CONTEXT_NONE, $display_name);
    }
    // Short month names lack a context anyway.
    $string_save_callback(date("M", $stamp), POTX_CONTEXT_NONE, $display_name);
  }
  for ($i = 0; $i <= 7; $i++) {
    $stamp = $i * 86400;
    $string_save_callback(date("D", $stamp), POTX_CONTEXT_NONE, $display_name);
    $string_save_callback(date("l", $stamp), POTX_CONTEXT_NONE, $display_name);
  }
  $string_save_callback('am', POTX_CONTEXT_NONE, $display_name);
  $string_save_callback('pm', POTX_CONTEXT_NONE, $display_name);
  $string_save_callback('AM', POTX_CONTEXT_NONE, $display_name);
  $string_save_callback('PM', POTX_CONTEXT_NONE, $display_name);
}

/**
 * Add format_interval special strings.
 *
 * These cannot be extracted otherwise. This is called for common.inc
 *
 * @param $display_name
 *   Name of the file parsed.
 * @param $string_save_callback
 *   Callback function used to save strings.
 * @param $api_version
 *   Drupal API version to work with.
 */
function potx_parser_add_format_interval_strings($display_name, $string_save_callback, $api_version = POTX_API_CURRENT) {
  $components = array(
    '1 year' => '@count years',
    '1 week' => '@count weeks',
    '1 day'  => '@count days',
    '1 hour' => '@count hours',
    '1 min'  => '@count min',
    '1 sec'  => '@count sec'
  );
  if ($api_version > POTX_API_6) {
    // Month support added in Drupal 7.
    $components['1 month'] = '@count months';
  }

  foreach ($components as $singular => $plural) {
    // Intervals support no context.
    $string_save_callback($singular . "\0" . $plural, POTX_CONTEXT_NONE, $display_name);
  }
}

/**
 * Add default theme region names, which cannot be extracted otherwise.
 *
 * These default names are defined in system.module
 *
 * @param $display_name
 *   Name of the file parsed.
 * @param $string_save_callback
 *   Callback function used to save strings.
 * @param $api_version
 *   Drupal API version to work with.
 */
function potx_parser_add_default_region_strings($display_name, $string_save_callback, $api_version = POTX_API_CURRENT) {
  $regions = array(
    'Left sidebar',
    'Right sidebar',
    'Content',
    'Header',
    'Footer',
  );
  if ($api_version > POTX_API_6) {
    $regions[] = 'Highlighted';
    $regions[] = 'Help';
    $regions[] = 'Page top';
    $regions[] = 'Page bottom';
  }
  foreach ($regions as $region) {
    // Regions come with the default context.
    $string_save_callback($region, POTX_CONTEXT_NONE, $display_name);
  }
}

// === Non-token based parsing functions =======================================

/**
 * Parse an .info file and add relevant strings to the list.
 *
 * @param $file_path
 *   Complete file path to load contents with.
 * @param $display_name
 *   Display oriented file name for saved string data and error messages.
 * @param $string_save_callback
 *   Callback function to use to save the collected strings.
 * @param $api_version
 *   Drupal API version to work with.
 */
function potx_parser_get_info_strings($file_path, $display_name, $string_save_callback, $api_version = POTX_API_CURRENT) {
  $info = array();

  if (file_exists($file_path)) {
    // Drupal 6+ has drupal_parse_info_file() and a special .info format.
    $info = $api_version > POTX_API_5 ? drupal_parse_info_file($file_path) : parse_ini_file($file_path);
  }

  // We need the name, description and package values. Others,
  // like core and PHP compatibility, timestamps or versions
  // are not to be translated.
  foreach (array('name', 'description', 'package') as $key) {
    if (isset($info[$key])) {
      // No context support for .info file strings.
      $string_save_callback(addcslashes($info[$key], "\0..\37\\\""), POTX_CONTEXT_NONE, $display_name);
    }
  }

  // Add regions names from themes.
  if (isset($info['regions']) && is_array($info['regions'])) {
    foreach ($info['regions'] as $region => $region_name) {
      // No context support for .info file strings.
      $string_save_callback(addcslashes($region_name, "\0..\37\\\""), POTX_CONTEXT_NONE, $display_name);
    }
  }
}

/**
 * Parse a JavaScript file for translatables. Only from Drupal 6.
 *
 * Extracts strings wrapped in Drupal.t() and Drupal.formatPlural()
 * calls and inserts them into potx storage.
 *
 * Regex code lifted from _locale_parse_js_file().
 */
function potx_parser_get_js_strings($code, $display_name, $string_save_callback) {
  $js_string_regex = '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+';

  // Match all calls to Drupal.t() in an array.
  // Note: \s also matches newlines with the 's' modifier.
  preg_match_all('~[^\w]Drupal\s*\.\s*t\s*\(\s*(' . $js_string_regex . ')\s*[,\)]~s', $code, $t_matches, PREG_SET_ORDER);
  if (isset($t_matches) && count($t_matches)) {
    foreach ($t_matches as $match) {
      // Remove match from code to help us identify faulty Drupal.t() calls.
      $code = str_replace($match[0], '', $code);
      // @todo: figure out how to parse out context, once Drupal supports it.
      $string_save_callback(potx_parser_get_js_string($match[1]), POTX_CONTEXT_NONE, $display_name, 0);
    }
  }

  // Match all Drupal.formatPlural() calls in another array.
  preg_match_all('~[^\w]Drupal\s*\.\s*formatPlural\s*\(\s*.+?\s*,\s*(' . $js_string_regex . ')\s*,\s*((?:(?:\'(?:\\\\\'|[^\'])*@count(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*@count(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+)\s*[,\)]~s', $code, $plural_matches, PREG_SET_ORDER);
  if (isset($plural_matches) && count($plural_matches)) {
    foreach ($plural_matches as $index => $match) {
      // Remove match from code to help us identify faulty
      // Drupal.formatPlural() calls later.
      $code = str_replace($match[0], '', $code);
      // @todo: figure out how to parse out context, once Drupal supports it.
      $string_save_callback(
        potx_parser_get_js_string($match[1]) . "\0" . potx_parser_get_js_string($match[2]),
        POTX_CONTEXT_NONE,
        $display_name,
        0
      );
    }
  }

  // Any remaining Drupal.t() or Drupal.formatPlural() calls are evil. This
  // regex is not terribly accurate (ie. code wrapped inside will confuse
  // the match), but we only need some unique part to identify the faulty calls.
  preg_match_all('~[^\w]Drupal\s*\.\s*(t|formatPlural)\s*\([^)]+\)~s', $code, $faulty_matches, PREG_SET_ORDER);
  if (isset($faulty_matches) && count($faulty_matches)) {
    foreach ($faulty_matches as $index => $match) {
      $message = ($match[1] == 't') ? t('Drupal.t() calls should have a single literal string as their first parameter.') : t('The singular and plural string parameters on Drupal.formatPlural() calls should be literal strings, plural containing a @count placeholder.');
      potx_parser_util_set_message($message, $display_name, NULL, $match[0], 'http://drupal.org/node/323109');
    }
  }
}

/**
 * Clean up string found in JavaScript source code. Only from Drupal 6.
 */
function potx_parser_get_js_string($string) {
  return potx_parser_util_format_string(implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', $string)));
}

/**
 * Get the exact CVS version number from a file.
 *
 * @todo This will be obsoleted by the drupal.org GIT migration.
 *
 * @param $code
 *   Complete source code of the file parsed.
 * @param $display_name
 *   Name of the file parsed (to be passed to $file_version_callback).
 * @param $file_version_callback
 *   Callback used to save the version information.
 */
function potx_parser_get_version_number($code, $display_name, $file_version_callback) {
  // Prevent CVS from replacing this pattern with actual info.
  if (preg_match('!\\$I' . 'd: ([^\\$]+) Exp \\$!', $code, $version_info)) {
    $file_version_callback($version_info[1], $display_name);
  }
  else {
    // Unknown version information.
    $file_version_callback($display_name . ': n/a', $display_name);
  }
}

/**
 * Default $file_version_callback used by the potx system.
 *
 * Saves values to a global array to reduce memory consumption problems when
 * passing around big chunks of values.
 *
 * @param $value
 *   The version number value of $file. If NULL, the collected
 *   values are returned.
 * @param $display_name
 *   Name of file where the version information was found.
 */
function potx_parser_callback_version($value = NULL, $display_name = NULL) {
  global $_potx_versions;

  if (isset($value)) {
    $_potx_versions[$display_name] = $value;
  }
  else {
    return $_potx_versions;
  }
}

// === Default file parse callbacks ============================================

/**
 * Default $string_save_callback used by the potx system.
 *
 * Saves values to global arrays to reduce memory consumption problems when
 * passing around big chunks of values.
 *
 * @param $value
 *   The string value. If NULL, the array of collected values
 *   are returned for the given $string_mode.
 * @param $context
 *   From Drupal 7, separate contexts are supported. POTX_CONTEXT_NONE is
 *   the default, if the code does not specify a context otherwise.
 * @param $display_name
 *   Name of file where the string was found.
 * @param $line
 *   Line number where the string was found.
 * @param $string_mode
 *   String mode: POTX_STRING_INSTALLER, POTX_STRING_RUNTIME
 *   or POTX_STRING_BOTH.
 */
function potx_parser_callback_save_string($value = NULL, $context = NULL, $display_name = NULL, $line = 0, $string_mode = POTX_STRING_RUNTIME) {
  global $_potx_strings, $_potx_install;

  if (isset($value)) {

    // Value set but empty. Mark error on empty translatable string. Only trim
    // for empty string checking, since we should store leading/trailing
    // whitespace as it appears in the string otherwise.
    $check_empty = trim($value);
    if (empty($check_empty)) {
      potx_parser_util_set_message(t('Empty string attempted to be localized. Please do not leave test code for localization in your source.'), $display_name, $line);
      return;
    }

    switch ($string_mode) {
      case POTX_STRING_BOTH:
        // Mark installer strings as duplicates of runtime strings if
        // the string was both recorded in the runtime and in the installer.
        $_potx_install[$value][$context][$display_name][] = $line . ' (dup)';
        // Break intentionally missing.
      case POTX_STRING_RUNTIME:
        // Mark runtime strings as duplicates of installer strings if
        // the string was both recorded in the runtime and in the installer.
        $_potx_strings[$value][$context][$display_name][] = $line . ($string_mode == POTX_STRING_BOTH ? ' (dup)' : '');
        break;
      case POTX_STRING_INSTALLER:
        $_potx_install[$value][$context][$display_name][] = $line;
        break;
    }
  }
  else {
    return ($string_mode == POTX_STRING_RUNTIME ? $_potx_strings : $_potx_install);
  }
}
/**
 * Returns a header generated for a given file.
 *
 * @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_parser_callback_header($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 (isset($template_export_langcode)) {
    $language = db_query($api_version > POTX_API_5 ? "SELECT language, name, plurals, formula FROM {languages} WHERE language = :langcode" : "SELECT locale, name, plurals, formula FROM {locales_meta} WHERE locale = :langcode", array(':langcode' => $template_export_langcode))->fetchObject();
  }

  $output  = '# $' . 'Id' . '$' . "\n";
  $output .= "#\n";
  $output .= '# ' . (isset($language) ? $language->name : 'LANGUAGE') . " translation\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->name : '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($language->formula) && isset($language->plurals)) {
    $output .= "\"Plural-Forms: nplurals=" . $language->plurals . "; plural=" . strtr($language->formula, array('$' => '')) . ";\\n\"\n\n";
  }
  else {
    $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
  }
  return $output;
}

// === Utility functions =======================================================

/**
 * Helper function to look up the token closing the current function.
 *
 * @param $here
 *   The token at the function name
 */
function potx_parser_util_end_of_function($here) {
  global $_potx_tokens;

  // Seek to open brace.
  while (is_array($_potx_tokens[$here]) || $_potx_tokens[$here] != '{') {
    $here++;
  }
  $nesting = 1;
  while ($nesting > 0) {
    $here++;
    if (!is_array($_potx_tokens[$here])) {
      if ($_potx_tokens[$here] == '}') {
        $nesting--;
      }
      if ($_potx_tokens[$here] == '{') {
        $nesting++;
      }
    }
  }
  return $here;
}

/**
 * Helper to move past t() and format_plural() arguments in search of context.
 *
 * @param $here
 *   The token before the start of the arguments
 */
function potx_parser_util_skip_args($here) {
  global $_potx_tokens;

  $nesting = 0;
  // Go through to either the end of the function call or to a comma
  // after the current position on the same nesting level.
  while (!(($_potx_tokens[$here] == ',' && $nesting == 0) ||
           ($_potx_tokens[$here] == ')' && $nesting == -1))) {
    $here++;
    if (!is_array($_potx_tokens[$here])) {
      if ($_potx_tokens[$here] == ')') {
        $nesting--;
      }
      if ($_potx_tokens[$here] == '(') {
        $nesting++;
      }
    }
  }
  // If we run out of nesting, it means we reached the end of the function call,
  // so we skipped the arguments but did not find meat for looking at the
  // specified context.
  return ($nesting == 0 ? $here : FALSE);
}

/**
 * Helper to find the value for 'context' on t() and format_plural().
 *
 * @param $tf
 *   Start position of the original function.
 * @param $ti
 *   Start position where we should search from.
 * @param $file
 *   Full path name of file parsed.
 * @param function_name
 *   The name of the function to look for. Either 'format_plural' or 't'
 *   given that Drupal 7 only supports context on these.
 */
function potx_parser_util_context($tf, $ti, $file, $function_name) {
  global $_potx_tokens;

  // Start from after the comma and skip the possible arguments for the function
  // so we can look for the context.
  if (($ti = potx_parser_util_skip_args($ti)) && ($_potx_tokens[$ti] == ',')) {
    // Now we actually might have some definition for a context. The $options
    // argument is coming up, which might have a key for context.
    list($com, $arr, $par) = array($_potx_tokens[$ti], $_potx_tokens[$ti+1], $_potx_tokens[$ti+2]);
    if ($com == ',' && $arr[1] == 'array' && $par == '(') {
      $nesting = 0;
      $ti += 3;
      // Go through to either the end of the array or to the key definition of
      // context on the same nesting level.
      while (!((is_array($_potx_tokens[$ti]) && (in_array($_potx_tokens[$ti][1], array('"context"', "'context'"))) && ($_potx_tokens[$ti][0] == T_CONSTANT_ENCAPSED_STRING) && ($nesting == 0)) ||
               ($_potx_tokens[$ti] == ')' && $nesting == -1))) {
        $ti++;
        if (!is_array($_potx_tokens[$ti])) {
          if ($_potx_tokens[$ti] == ')') {
            $nesting--;
          }
          if ($_potx_tokens[$ti] == '(') {
            $nesting++;
          }
        }
      }
      if ($nesting == 0) {
        // Found the 'context' key on the top level of the $options array.
        list($arw, $str) = array($_potx_tokens[$ti+1], $_potx_tokens[$ti+2]);
        if (is_array($arw) && $arw[1] == '=>' && is_array($str) && $str[0] == T_CONSTANT_ENCAPSED_STRING) {
          return potx_parser_util_format_string($str[1]);
        }
        else {
          list($type, $string, $line) = $_potx_tokens[$ti];
          // @todo: fix error reference.
          potx_parser_util_token_error($file, $line, $function_name, $tf, t('The context element in the options array argument 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');
          // Return with error.
          return POTX_CONTEXT_ERROR;
        }
      }
      else {
        // Did not found 'context' key in $options array.
        return POTX_CONTEXT_NONE;
      }
    }
  }

  // After skipping args, we did not find a comma to look for $options.
  return POTX_CONTEXT_NONE;
}

/**
 * Escape quotes in a strings depending on the surrounding quote type used.
 *
 * @param $str
 *   The strings to escape
 */
function potx_parser_util_format_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\\\"");
}

/**
 * Save an error with an extract of where the error was found.
 *
 * @param $display_name
 *   Display 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
 *   Optional documentation reference.
 */
function potx_parser_util_token_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++;
      }
      elseif ($_potx_tokens[$ti] == ")") {
        $par--;
      }
    }
    $ti++;
  }
  potx_parser_util_set_message($error, $file, $line, $marker . '(' . $tokens, $docs_url);
}

/**
 * Parse error message collection function.
 *
 * @param $value
 *   Error message or NULL to get the errors collected (and reset the list).
 * @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_parser_util_set_message($value = NULL, $file = NULL, $line = NULL, $excerpt = NULL, $docs_url = NULL) {
  static $messages = array();

  if (empty($value)) {
    $errors = $messages;
    $messages = array();
    return $errors;
  }

  $location_info = '';
  if (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 (isset($docs_url)) {
    $read_more = t('Read more at <a href="@url">@url</a>', array('@url' => $docs_url));
  }

  $readable_error_message = join(' ', array($value, $location_info, $read_more));
  $messages[] = array($value, $file, $line, $excerpt, $docs_url, $readable_error_message);
}

/**
 * Get the list of messages saved when parsing one or more files.
 *
 * Also cleans off the list of messages.
 */
function potx_parser_util_get_messages() {
  return potx_parser_util_set_message();
}

/**
 * Reset global variables used for storing cross-function data.
 */
function potx_parser_util_reset() {
  global $_potx_strings, $_potx_install, $_potx_versions;
  $_potx_strings = $_potx_install = $_potx_versions = array();
}