summaryrefslogtreecommitdiffstats
path: root/i18n_string/i18n_string.inc
blob: 5390c25144eb50eb572e0b29245c569a1dda33c2 (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
<?php
/**
 * @file
 *   API for internationalization strings
 */

/**
 * String object that contains source and translations.
 * 
 * Note all database operations must go through textgroup object so we can switch storage at some point.
 */
class i18n_string_object {
  // Updated source string
  public $string;
  // Properties from locale source
  public $lid;
  public $source;
  public $textgroup;
  public $location;  
  public $context;
  public $version;
  // Properties from i18n_tring
  public $type;
  public $objectid;
  public $property;
  public $objectkey;
  public $format;
  // Properties from metadata
  public $title;
  // Array of translations to multiple languages
  public $translations;
  // Textgroup object
  protected $_textgroup;
 
  /**
   * Class constructor
   */
  public function __construct($data = NULL) {
    if ($data) {
      $this->set_properties($data);
    }
  }
  /**
   * Get message parameters from context and string.
   */
  public function get_args() {
    return array(
      '%location' => $this->location,
      '%textgroup' => $this->textgroup,
      '%string' => ($string = $this->get_string()) ? $string : t('[empty string]'),
    );
  }
  /**
   * Set context properties
   */
  public function set_context($context) {
    $parts = is_array($context) ? $context : explode(':', $context);  
    $this->context = is_array($context) ? implode(':', $context) : $context;
    // Location will be the full string name
    $this->location = $this->textgroup . ':' . $this->context;
    $this->type = array_shift($parts);
    $this->objectid = $parts ? array_shift($parts) : '';
    $this->objectkey = (int)$this->objectid;      
    // Remaining elements glued again with ':'
    $this->property = $parts ? implode(':', $parts) : '';
    return $this;
  }
  /**
   * Get string name including textgroup and context
   */
  public function get_name() {
    return $this->textgroup . ':' . $this->type . ':' . $this->objectid . ':' . $this->property;
  }
  /**
   * Get source string
   */
  public function get_string() {
    if (isset($this->string)) {
      return $this->string;
    }
    elseif (isset($this->source)) {
      return $this->source;
    }
    elseif ($this->textgroup()->debug) {
      return empty($this->lid) ? t('[Source not found]') : t('[String not found]');
    }
    else {
      return '';
    }
  }
  /**
   * Set source string
   * 
   * @param $string
   *   Plain string or array with 'string', 'format', etc...
   */
  public function set_string($string) {
    if (is_array($string)) {
      $this->string = isset($string['string']) ? $string['string'] : NULL;
      if (isset($string['format'])) {
        $this->format = $string['format'];
      }
    }
    else {
      $this->string = $string;
    }
    if (isset($string['title'])) {
      $this->title = $string['title'];
    }
    return $this;
  }
  /**
   * Get string title.
   */
  public function get_title() {
    return isset($this->title) ? $this->title : t('String');
  }
  /**
   * Get translation to language from string object
   */
  public function get_translation($langcode) {
    if (!isset($this->translations[$langcode])) {
      $translation = $this->textgroup()->load_translation($this, $langcode);
      if ($translation && isset($translation->translation)) {
        $this->set_translation($translation, $langcode);
      }
      else {
        // No source, no translation
        $this->translations[$langcode] = FALSE;
      }      
    }
    // Which doesn't mean we've got a translation, only that we've got the result cached
    return $this->translations[$langcode];
  }
  /**
   * Set translation for language
   * 
   * @param $translation
   *   Translation object (from database) or string
   */
  public function set_translation($translation, $langcode = NULL) {
    if (is_object($translation)) {
      $langcode = $langcode ? $langcode : $translation->language;
      $string = isset($translation->translation) ? $translation->translation : FALSE;
      $this->set_properties($translation);
    }
    else {
      $string = $translation;
    }
    $this->translations[$langcode] = $string;
    return $this;
  }

  /**
   * Format the resulting translation or the default string applying callbacks
   *
   * There's a hidden variable, 'i18n_string_debug', that when set to TRUE will display additional info
   */
  public function format_translation($langcode, $options = array()) {
    $options += array('langcode' => $langcode, 'sanitize' => TRUE, 'sanitize default' => FALSE, 'cache' => FALSE, 'debug' => $this->textgroup()->debug);
    if ($translation = $this->get_translation($langcode)) {
      $string = $translation;
      if (isset($options['filter'])) {
        $string = call_user_func($options['filter'], $string);
      }
    }
    else {
      // Get default source string if no translation.
      $string = $this->get_string();
      $options['sanitize'] = $options['sanitize default'];
    }
    if (!empty($this->format)) {
      $options += array('format' => $this->format);
    }
    elseif (empty($translation) && $options['sanitize']) {
      // We are bout to display the source string without text format, force check_plain.
      $string = check_plain($string);
    }
    // Add debug information if enabled
    if ($options['debug']) {
      $info = array($langcode, $this->textgroup, $this->context);
      if (!empty($this->format)) {
        $info[] = $this->format;
      }
      $options += array('suffix' => '');
      $options['suffix'] .= ' [' . implode(':', $info) . ']';
    }
    // Finally, apply options, filters, callback, etc...
    return i18n_string_format($string, $options);
  }

  /**
   * Get source string provided a string object.
   *
   * @return
   *   String object if source exists.
   */
  public function get_source() {
    // If already searched and not found we don't have a source, 
    if (isset($this->lid) && !$this->lid) {
      return NULL;
    }
    elseif (!isset($this->lid) || !isset($this->source)) {
      // We may have lid from loading a translation but not loaded the source yet.
      if ($source = $this->textgroup()->load_source($this)) {
        $this->set_properties($source, FALSE);
        if (!isset($this->string)) {
          $this->string = $source->source;
        }
        return $this;
      }
      else {
        $this->lid = FALSE;
        return NULL;
      }
    }
    else {
      return $this;
    }
  }
  
  /**
   * Set properties from object or array
   * 
   * @param $properties
   *   Obejct or array of properties
   * @param $set_null
   *   Whether to set null properties too
   */
  public function set_properties($properties, $set_null = TRUE) {
    foreach ((array)$properties as $field => $value) {
      if (property_exists($this, $field) && ($set_null || isset($value))) {
        $this->$field = $value;
      }
    }
    return $this;
  }
  /**
   * Access textgroup object
   */
  protected function textgroup() {
    if (!isset($this->_textgroup)) {
      $this->_textgroup = i18n_string_textgroup($this->textgroup);
    }
    return $this->_textgroup;
  }
  /**
   * Update this string.
   */
  public function update($options = array()) {
    return $this->textgroup()->string_update($this, $options);
  }
  /**
   * Delete this string.
   */
  public function remove($options = array()) {
    return $this->textgroup()->string_remove($this, $options);
  }
}

/**
 * Textgroup handler for i18n_string API
 */
class i18n_string_textgroup_default {
  // Text group name
  public $textgroup;
  // Debug flag, set to true to print out more information.
  public $debug;
  // Cached or preloaded string objects
  public $strings;
  // Multiple translations search map
  protected $cache_multiple;

  /**
   * Class constructor.
   * 
   * There are to hidden variables to produce debugging information:
   * - 'i18n_string_debug', generic for all text groups.
   * - 'i18n_string_debug_TEXTGROUP', enable debug only for TEXTGROUP.
   */
  public function __construct($textgroup) {
    $this->textgroup = $textgroup;
    $this->debug = variable_get('i18n_string_debug', FALSE) || variable_get('i18n_string_debug_' . $textgroup, FALSE);
  }
  /**
   * Build string object
   * 
   * @param $context
   *   Context array or string
   * @param $string string
   *   Current value for string source
   */
  public function build_string($context, $string = NULL) {
    // First try to locate string on cache
    $context = is_array($context) ? implode(':', $context) : $context;
    if ($cached = $this->cache_get($context)) {
      $i18nstring = $cached;
    }
    else {    
      $i18nstring = new i18n_string_object();
      $i18nstring->textgroup = $this->textgroup;
      $i18nstring->set_context($context);
      $this->cache_set($context, $i18nstring);
    }
    if (isset($string)) {
      $i18nstring->set_string($string);
    }
    return $i18nstring;
  }
  /**
   * Add source string to the locale tables for translation.
   *
   * It will also add data into i18n_string table for faster retrieval and indexing of groups of strings.
   * Some string context doesn't have a numeric oid (I.e. content types), it will be set to zero.
   *
   * This function checks for already existing string without context for this textgroup and updates it accordingly.
   * It is intended for backwards compatibility, using already created strings.
   *
   * @param $i18nstring
   *   String object
   * @param $format
   *   Text format, for strings that will go through some filter
   * @return
   *   Update status.
   */
  protected function string_add($i18nstring, $options = array()) {
    $options += array('watchdog' => TRUE);
    // Default return status if nothing happens
    $status = -1;
    $source = NULL;
    $location = $i18nstring->location;
    // The string may not be allowed for translation depending on its format.
    if (!$this->string_check($i18nstring, $options)) {
      // The format may have changed and it's not allowed now, delete the source string
      return $this->string_remove($i18nstring, $options);
    }
    elseif ($source = $i18nstring->get_source()) {
      if ($source->source != $i18nstring->string || $source->location != $location) {
        $i18nstring->location = $location;
        // String has changed, mark translations for update
        $status = $this->save_source($i18nstring);
        db_update('locales_target')
          ->fields(array('i18n_status' => I18N_STRING_STATUS_UPDATE))
          ->condition('lid', $source->lid)
          ->execute();
      }
      elseif (empty($source->version)) {
        // When refreshing strings, we've done version = 0, update it
        $this->save_source($i18nstring);
      }
    }
    else {
      // We don't have the source object, create it
      $status = $this->save_source($i18nstring);
    }
    // Make sure we have i18n_string part, create or update
    // This will also create the source object if doesn't exist
    $this->save_string($i18nstring);

    if ($options['watchdog']) {
      switch ($status) {
        case SAVED_UPDATED:
          watchdog('i18n_string', 'Updated string %location for textgroup %textgroup: %string', $i18nstring->get_args());
          break;
        case SAVED_NEW:
          watchdog('i18n_string', 'Created string %location for text group %textgroup: %string', $i18nstring->get_args());
          break;
      }
    }
    return $status;
  }

  /**
   * Check if string is ok for translation
   */
  protected static function string_check($i18nstring, $options = array()) {
    $options += array('messages' => FALSE, 'watchdog' => TRUE);
    if (!empty($i18nstring->format) && !i18n_string_allowed_format($i18nstring->format)) {
      // This format is not allowed, so we remove the string, in this case we produce a warning
      drupal_set_message(t('The string %location for textgroup %textgroup is not allowed for translation because of its text format.', $i18nstring->get_args()), 'warning');
      return FALSE;
    }
    else {
      return TRUE;
    }
  }

  /**
   * Filter array of strings
   * 
   * @param $filter
   *   Array of name value conditions. 
   */
  protected static function string_filter($string_list, $filter) {
    // Remove 'language' and '*' conditions.
    if (isset($filter['language'])) {
      unset($filter['language']);
    }
    while ($field = array_search('*', $filter)) {
      unset($filter[$field]);
    }
    foreach ($string_list as $key => $string) {
      foreach ($filter as $field => $value) {
        if ($string->$field != $value) {
          unset($string_list[$key]);
          break;
        }
      }
    }
    return $string_list;
  }

  /**
   * Build query for i18n_string table
   */
  protected static function string_query($context, $multiple = FALSE) {
    // Search the database using lid if we've got it or textgroup, context otherwise
    $query = db_select('i18n_string', 's')->fields('s');
    if (!empty($context->lid)) {
      $query->condition('s.lid', $context->lid);
    }
    else {
      $query->condition('s.textgroup', $context->textgroup);
      if (!$multiple) {
        $query->condition('s.context', $context->context);
      }
      else {
        // Query multiple strings
        foreach (array('type', 'objectid', 'property') as $field) {
          if (!empty($context->$field)) {
            $query->condition('s.' . $field, $context->$field);
          }
        }
      }
    }
    return $query;
  }

  /**
   * Remove string object.
   */
  public function string_remove($i18nstring, $options = array()) {
    $options += array('watchdog' => TRUE, 'messages' => $this->debug);
    if ($source = $i18nstring->get_source()) {
      db_delete('locales_target')->condition('lid', $source->lid)->execute();
      db_delete('i18n_string')->condition('lid', $source->lid)->execute();
      db_delete('locales_source')->condition('lid', $source->lid)->execute();
      $this->cache_set($source->context, NULL);
      if ($options['watchdog']) {
        watchdog('i18n_string', 'Deleted string %location for text group %textgroup: %string', $i18nstring->get_args());
      }
      if ($options['messages']) {
        drupal_set_message(t('Deleted string %location for tex tgroup %textgroup: %string', $i18nstring->get_args()));
      }
      return SAVED_DELETED;
    }
    else {
      if($options['messages']) {
        drupal_set_message(t('Cannot delete string, not found %location for text group %textgroup: %string', $i18nstring->get_args()));
      }
      return FALSE;
    }
  }

  /**
   * Translate string object
   *
   * @param $i18nstring
   *   String object
   * @param $options
   *   Array with aditional options
   */
  protected function string_translate($i18nstring, $options = array()) {
    $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
    // Search for existing translation (result will be cached in this function call)
    $i18nstring->get_translation($langcode);
    return $i18nstring;
  }

  /**
   * Update / create / remove string.
   *
   * @param $name
   *   String context.
   * @pram $string
   *   New value of string for update/create. May be empty for removing.
   * @param $format
   *   Text format, that must have been checked against allowed formats for translation
   * @param $options
   *   Processing options, the ones used here are:
   *   - 'watchdog', whether to produce watchdog messages.
   *   - 'messages', whether to produce user messages.
   *   - 'check', whether to check string format and then update/delete if not allowed.
   * @return status
   *   SAVED_UPDATED | SAVED_NEW | SAVED_DELETED
   */
  public function string_update($i18nstring, $options = array()) {
    $options += array('watchdog' => TRUE, 'messages' => FALSE, 'check' => TRUE);
    if (!$options['check'] || !$this->string_check($i18nstring, $options)) {
      $status = $this->string_remove($i18nstring, $options);
    }
    elseif ($i18nstring->get_string()) {
      $status = $this->string_add($i18nstring, $options);
    }
    else {
      $status = $this->string_remove($i18nstring, $options);
    }
    if ($options['messages']) {
      switch ($status) {
        case SAVED_UPDATED:
          drupal_set_message(t('Updated string %location for text group %textgroup: %string', $i18nstring->get_args()));
          break;
        case SAVED_NEW:
          drupal_set_message(t('Created string %location for text group %textgroup: %string', $i18nstring->get_args()));
          break;
      }
    }
    if ($options['watchdog']) {
      switch ($status) {
        case SAVED_UPDATED:
          watchdog('i18n_string', 'Updated string %location for text group %textgroup: %string', $i18nstring->get_args());
          break;
        case SAVED_NEW:
          watchdog('i18n_string', 'Created string %location for text group %textgroup: %string', $i18nstring->get_args());
          break;
      }
    } 
    return $status;
  }

  /**
   * Set string object into cache
   */
  protected function cache_set($context, $string) {
    $this->strings[$context] = $string;
  }

  /**
   * Get translation from cache
   */
  protected function cache_get($context) {
    return isset($this->strings[$context]) ? $this->strings[$context] : NULL;
  }

  /**
   * Reset cache, needed for tests
   */
  public function cache_reset() {
    $this->strings = array();
    $this->string_format = array();
    $this->translations = array();
  }

  /**
   * Load string source from db
   */
  public static function load_source($i18nstring) {
    // Search the database using lid if we've got it or textgroup, context otherwise
    $query = db_select('locales_source', 's')->fields('s');
    $query->leftJoin('i18n_string', 'i', 's.lid = i.lid');
    $query->fields('i', array('format', 'objectid', 'type', 'property', 'objectindex'));
    if (!empty($i18nstring->lid)) {
      $query->condition('s.lid', $i18nstring->lid);
    }
    else {
      $query->condition('s.textgroup', $i18nstring->textgroup);
      $query->condition('s.context', $i18nstring->context);
    }
    // Speed up the query, we just need one row
    return $query->range(0, 1)->execute()->fetchObject();
  }

  /**
   * Load translation from db
   *
   * @todo Optimize when we've already got the source string
   */
  public static function load_translation($i18nstring, $langcode) {
    // Search the database using lid if we've got it or textgroup, context otherwise
    if (!empty($i18nstring->lid)) {
      // We've alreay got lid, we just need translation data
      $query = db_select('locales_target', 't');
      $query->condition('t.lid', $i18nstring->lid);
    }
    else {
      // Still don't have lid, load string properties too
      $query = db_select('i18n_string', 's')->fields('s');
      $query->leftJoin('locales_target', 't', 's.lid = t.lid');
      $query->condition('s.textgroup', $i18nstring->textgroup);
      $query->condition('s.context', $i18nstring->context);
    }
    // Add translation fields   
    $query->fields('t', array('translation', 'i18n_status'));
    $query->condition('t.language', $langcode);
    // Speed up the query, we just need one row
    $query->range(0, 1);
    return $query->execute()->fetchObject();
  }

  /**
   * Save / update string object
   *
   * There seems to be a race condition sometimes so skip errors, #277711
   *
   * @param $string
   *   Full string object to be saved
   * @param $source
   *   Source string object
   */
  protected function save_string($string, $update = FALSE) {
    if (!$string->get_source()) {
      // Create source string so we get an lid
      $this->save_source($string);
    }
    if (!isset($string->objectkey)) {
      $string->objectkey = (int)$string->objectid;
    }
    if (!isset($string->format)) {
      $string->format = '';
    }
    $status = db_merge('i18n_string')
      ->key(array('lid' => $string->lid))
      ->fields(array(
          'textgroup' => $string->textgroup,
          'context' => $string->context,
          'objectid' => $string->objectid,
          'type' => $string->type,
          'property' => $string->property,
          'objectindex' => $string->objectkey,
          'format' => $string->format,
      ))
      ->execute();
    return $status;
  }

  /**
   * Save translation to the db
   *
   * @param $string
   *   Full string object with translation data (language, translation)
   */
  protected function save_translation($string, $langcode) {
    db_merge('locales_target')
      ->key(array('lid' => $string->lid, 'language' => $langcode))
      ->fields(array('translation' => $string->get_translation($langcode)))
      ->execute();
  }

  /**
   * Save source string (create / update)
   */
  protected static function save_source($source) {
    if (isset($source->string)) {
      $source->source = $source->string;
    }
    if (empty($source->version)) {
      $source->version = 1;
    }
    return drupal_write_record('locales_source', $source, !empty($source->lid) ? 'lid' : array());
  }

  /**
   * Remove source and translations for user defined string.
   *
   * Though for most strings the 'name' or 'string id' uniquely identifies that string,
   * there are some exceptions (like profile categories) for which we need to use the
   * source string itself as a search key.
   *
   * @param $context
   *   Textgroup and location glued with ':'.
   * @param $string
   *   Optional source string (string in default language).
   */
  public function context_remove($context, $string = NULL, $options = array()) {
    $options += array('messages' => $this->debug);
    $i18nstring = $this->build_string($context, $string);
    $status = $this->string_remove($i18nstring, $options);

    return $this;
  }

  /**
   * Translate source string
   */
  public function context_translate($context, $string, $options = array()) {
    $i18nstring = $this->build_string($context, $string);
    return $this->string_translate($i18nstring, $options);
  }

  /**
   * Update / create translation source for user defined strings.
   *
   * @param $name
   *   Textgroup and location glued with ':'.
   * @param $string
   *   Source string in default language. Default language may or may not be English.
   * @param $options
   *   Array with additional options:
   *   - 'format', String format if the string has text format.
   *   - 'messages', Whether to print out status messages.
   *   - 'check', whether to check string format and then update/delete if not allowed.
   */
  public function context_update($context, $string, $options = array()) {
    $options += array('format' => FALSE, 'messages' => $this->debug, 'watchdog' => TRUE, 'check' => TRUE);
    $i18nstring = $this->build_string($context, $string);
    $i18nstring->format = $options['format'];
    $this->string_update($i18nstring, $options);
    return $this;
  }

  /**
   * Build combinations of an array of arrays respecting keys.
   * 
   * Example:
   *   array(array(a,b), array(1,2)) will translate into
   *   array(a,1), array(a,2), array(b,1), array(b,2)
   */
  protected static function multiple_combine($properties) {
    $combinations = array();
    // Get first key, value. We need to make sure the array pointer is reset.
    $value = reset($properties);
    $key = key($properties);
    array_shift($properties);
    $values = is_array($value) ? $value : array($value);
    foreach ($values as $value) {
      if ($properties) {
        foreach (self::multiple_combine($properties) as $merge) {
          $combinations[] = array_merge(array($key => $value), $merge);
        }
      }
      else {
        $combinations[] = array($key => $value);
      }
    }
    return $combinations;
  }

  /**
   * Get multiple translations with search conditions.
   * 
   * @param $translations
   *   Array of translation objects as loaded from the db.
	 * @param $langcode
	 *   Language code, array of language codes or * to search all translations.
	 * 
   * @return array
   *   Array of i18n string objects.
   */
  protected function multiple_translation_build($translations, $langcode) {
    $strings = array();
    foreach ($translations as $translation) {   
      // The string object may be already in list
      if (isset($strings[$translation->context])) {
        $string = $strings[$translation->context];        
      }
      else {
        $string = $this->build_string($translation->context);
        $string->set_properties($translation);
        $strings[$string->context] = $string;
      }
      // If this is a translation we set it there too
      if ($translation->language && $translation->translation) {
        $string->set_translation($translation);
      }
      elseif ($langcode) {
        // This may only happen when we have a source string but not translation.
        $string->set_translation(FALSE, $langcode);
      }
    }
    return $strings;
  }

  /**
   * Load multiple translations from db
   *
   * @todo Optimize when we've already got the source object
   * 
   * @param $conditions
   *   Array of field values to use as query conditions.
   * @param $langcode
   *   Language code to search.
   * @param $index
   *   Field to use as index for the result.
   * @return array
   *   Array of string objects with translation set.
   */
  protected function multiple_translation_load($conditions, $langcode) {
    $conditions += array(
      'language' => $langcode,
      'textgroup' => $this->textgroup
    );
    // We may be querying all translations at the same time or just one language.
    // The language field needs some special treatment though.
    $query = db_select('i18n_string', 's')->fields('s');
    $query->leftJoin('locales_target', 't', 's.lid = t.lid');
    $query->fields('t', array('translation', 'language', 'i18n_status'));
    foreach ($conditions as $field => $value) {
      // Single array value, reduce array
      if (is_array($value) && count($value) == 1) {
        $value = reset($value);
      }
      if ($value === '*') {
        continue;
      }
      elseif ($field == 'language') {
        $query->condition('t.language', $value);
      }
      else {
        $query->condition('s.' . $field, $value);
      }
    }
    return $this->multiple_translation_build($query->execute()->fetchAll(), $langcode);
  }

  /**
   * Search multiple translations with key combinations.
   * 
   * @param $context array()
   *   String context conditions.
   *   Each context field may be a single value, an array of values or '*'
   *   
   * @return
   *   Array of translation objects indexed by context.
   */
  public function multiple_translation_search($context, $langcode) {
    // First, build conditions and identify the variable field.
    $keys = array('type', 'objectid', 'property');
    $conditions = array_combine($keys, $context) + array('language' => $langcode);
    // Find existing searches in cache, compile remaining ones.
    $translations = $search = array();
    foreach ($this->multiple_combine($conditions) as $combination) {
      $cached = $this->multiple_cache_get($combination);
      if (isset($cached)) {
        // Cache hit. Merge and remove value from search.
        $translations += $cached;
      }
      else {
        // Not in cache, add to search conditions.
        $search = array_merge_recursive($search, $combination);
      }
    }
    // If we've got any search values left, find translations.
    if ($search) {
      // Prepare conditions for search, de-dupe conditions values.
      foreach ($search as $key => $value) {
        if (is_array($value)) {
          $search[$key] = array_unique($value);
        }
      }
      // Load translations for conditions and set them to the cache
      $loaded = $this->multiple_translation_load($search, $langcode);
      if ($loaded) {
        $translations += $loaded;
      }
      // Set cache for each of the multiple search keys.
      foreach ($this->multiple_combine($search) as $combination) {
        $list = $loaded ? $this->string_filter($loaded, $combination) : array();
        $this->multiple_cache_set($combination, $list);
      }
    }
    return $translations;
  }

  /**
   * Set multiple cache.
   * 
   * @param $context
   *   String context with language property at the end.
   * @param $strings
   *   Array of strings (may be empty) to cache.
   */
  protected function multiple_cache_set($context, $strings) {
    $cache_key = implode(':', $context);
    $this->cache_multiple[$cache_key] = $strings;
  }
  
  /**
   * Get strings from multiple cache.
   * 
   * @param $context
   *   String context with language property at the end.
   * 
   * @return mixed
   *   Array of strings (may be empty) if we've got a cache hit.
   *   Null otherwise.
   */
  protected function multiple_cache_get($context) {
    $cache_key = implode(':', $context);
    if (isset($this->cache_multiple[$cache_key])) {
      return $this->cache_multiple[$cache_key];
    }
    else {
      // Now we try more generic keys. For instance, if we are searching 'term:1:*'
      // we may try too 'term:*:*' and filter out the results.
      foreach ($context as $key => $value) {
        if ($value != '*') {
          $try = array_merge($context, array($key => '*'));
          $cache_key = implode(':', $try);
          if (isset($this->cache_multiple[$cache_key])) {         
            // As we've found some more generic key, we need to filter using original conditions.
            $strings = $this->string_filter($this->cache_multiple[$cache_key], $context);
            return $strings;
          }
        }
      }
      // If we've reached here, we didn't find any cache match.
      return NULL;
    }   
  }

  /**
   * Translate array of source strings
   * 
   * @param $context
   *   Context array with placeholders (*)
   * @param $strings
   *   Optional array of source strings indexed by the placeholder property
   *   
   * @return array
   *   Array of string objects (with translation) indexed by the placeholder field
   */
  public function multiple_translate($context, $strings = array(), $options = array()) {
    // First, build conditions and identify the variable field
    $search = $context = array_combine(array('type', 'objectid', 'property'), $context);
    $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
    // If we've got keyed source strings set the array of keys on the placeholder field
    // or if not, remove that condition so we search all strings with that keys.   
    foreach ($search as $field => $value) {
      if ($value === '*') {
        $property = $field;
        if ($strings) {
          $search[$field] = array_keys($strings);
        }
      }
    }
    // Now we'll add the language code to conditions and get the translations indexed by the property field
    $result = $this->multiple_translation_search($search, $langcode);
    // Remap translations using property field. If we've got strings it is important that they are in the same order.
    $translations = $strings;
    foreach ($result as $key => $i18nstring) {
      $translations[$i18nstring->$property] = $i18nstring;
    }
    // Set strings as source or create 
    foreach ($strings as $key => $source) {
      if (isset($translations[$key]) && is_object($translations[$key])) {
        $translations[$key]->set_string($source);
      }
      else {
        // Not found any string for this property, create it to map in the response
        // But make sure we set this language's translation to FALSE so we don't search again
        $newcontext = $context;
        $newcontext[$property] = $key;
        $translations[$key] = $this->build_string($newcontext)
          ->set_string($source)
          ->set_translation(FALSE, $langcode);
      }
    }
    return $translations;
  }

  /**
   * Update string translation, only if source exists.
   * 
   * @param $context
   *   String context as array
   * @param $langcode
   *   Language code to create the translation for
   * @param $translation
   *   String translation for this language
   */
  function update_translation($context, $langcode, $translation) {
    $i18nstring = $this->build_string($context);
    if ($source = $i18nstring->get_source()) {
      $source->set_translation($translation, $langcode);
      $this->save_translation($source, $langcode);
      return $source;
    }
  }

  /**
   * Recheck strings after update
   */
  public function update_check() {
    // Find strings in locales_source that have no data in i18n_string
    $query = db_select('locales_source', 'l')
    ->fields('l')
    ->condition('l.textgroup', $this->textgroup);
    $alias = $query->leftJoin('i18n_string', 's', 'l.lid = s.lid');
    $query->condition('s.lid', NULL);
    foreach ($query->execute()->fetchAll() as $string) {
      $i18nstring = $this->build_string($string->context, $string->source);
      $this->save_string($i18nstring);
    }
  }

}

/**
 * String object wrapper
 */
class i18n_string_object_wrapper extends i18n_object_wrapper {
  // Text group object
  protected $textgroup;
  // Properties for translation
  protected $properties;
  
  /**
   * Get object strings for translation
   * 
 	 * This will return a simple array of string objects, indexed by full string name.
 	 * 
 	 * @param $options
 	 *   Array with processing options.
 	 *   - 'empty', whether to return empty strings, defaults to FALSE.
   */
  public function get_strings($options = array()) {
    $options += array('empty' => FALSE);
    $strings = array();
    foreach ($this->get_properties() as $textgroup => $textgroup_list) {
      foreach ($textgroup_list as $type => $type_list) {
        foreach ($type_list as $object_id => $object_list) {
          foreach ($object_list as $key => $string) {
            if ($options['empty'] || !empty($string['string'])) {
              // Build string object, that will trigger static caches everywhere.
              $i18nstring = i18n_string_textgroup($textgroup)
                ->build_string(array($type, $object_id, $key))
                ->set_string($string);
              $strings[$i18nstring->get_name()] = $i18nstring;
            }
          }
        }
      }
    }
    return $strings;
  }
  /**
   * Get object translatable properties
   * 
   * This will return a big array indexed by textgroup, object type, object id and string key.
   * Each element is an array with string information, and may have these properties:
   * - 'string', the string itself, will be NULL if the object doesn't have that string
   * - 'format', string format when needed
   * - 'title', string readable name
   */
  public function get_properties() {
    if (!isset($this->properties)) {
      $this->properties = $this->build_properties();
    }
    return $this->properties;
  }

  /**
   * Build properties from object.
   */
  protected function build_properties() {
    list($string_type, $object_id) = $this->get_string_context(); 
    $object_keys = array(
      $this->get_textgroup(),
      $string_type,
      $object_id,
    );
    $strings = array();   
    foreach ($this->get_string_info('properties', array()) as $field => $info) {
      $info = is_array($info) ? $info : array('title' => $info);
      $field_name = isset($info['field']) ? $info['field'] : $field;
      $value = $this->get_field($field_name);
      $strings[$this->get_textgroup()][$string_type][$object_id][$field] = array(
        'string' => is_array($value) || isset($info['empty']) && $value === $info['empty'] ? NULL : $value,
        'title' => $info['title'],
        'format' => isset($info['format']) ? $this->get_field($info['format']) : NULL,
        'name' => array_merge($object_keys, array($field)),
      );
    }
    // Call hook_i18n_string_list_TEXTGROUP_alter(), last chance for modules
    drupal_alter('i18n_string_list_' . $this->get_textgroup(), $strings, $this->type, $this->object);
    return $strings;
  }

  /**
   * Get string context
   */
  public function get_string_context() {
    return array($this->get_string_info('type'), $this->get_key());
  }

  /**
   * Get translate path for object
   *
   * @param $langcode
   * 	 Language code if we want ti for a specific language
   */
  public function get_translate_path($langcode = NULL) {
    $replacements = array('%language' => $langcode ? $langcode : '');
    if ($path = $this->get_string_info('translate path')) {
      return $this->path_replace($path, $replacements);
    }
    elseif ($path = $this->get_info('translate tab')) {
      // If we've got a translate tab path, we just add language to it
      return $this->path_replace($path . '/%language', $replacements);
    }
  }

  /**
   * Translation mode for object
   */
  public function get_translate_mode() {
    return !$this->get_langcode() ? I18N_MODE_LOCALIZE : I18N_MODE_NONE;
  }

  /**
   * Get textgroup name
   */
  public function get_textgroup() {
    return $this->get_string_info('textgroup');
  }

  /**
   * Get textgroup object
   */
  protected function textgroup() {
    if (!isset($this->textgroup)) {
      $this->textgroup = i18n_string_textgroup($this->get_textgroup());
    }
    return $this->textgroup;
  }

  /**
   * Translate object.
   * 
   * Translations are cached so it runs only once per language.
   * 
   * @return object/array
   *   A clone of the object with its properties translated.
   */
  public function translate($langcode, $options = array()) {
    // We may have it already translated. As objects are statically cached, translations are too.
    if (!isset($this->translations[$langcode])) {
      $this->translations[$langcode] = $this->translate_object($langcode, $options);
    }
    return $this->translations[$langcode];
  }

  /**
   * Translate access (localize strings)
   */
  protected function localize_access() {
    return user_access('translate interface');
  }

  /**
   * Translate all properties for object.
   * 
   * On top of object strings we search for all textgroup:type:objectid:* properties
   * 
   * @param $langcode
   *   A clone of the object or array
   */
  protected function translate_object($langcode, $options) {
    // Clone object or array so we don't affect the original one.
    $object = is_object($this->object) ? clone $this->object : $this->object;
    // Get object strings for translatable properties.
    if ($strings = $this->get_strings()) {
      // We preload some of the property translations with a single query.
      if ($context = $this->get_translate_context($langcode, $options)) {
        $found = $this->textgroup()->multiple_translation_search($context, $langcode);
      }
      // Replace all strings in object.
      foreach ($strings as $i18nstring) {
        $this->translate_field($object, $i18nstring, $langcode, $options);
      }
    }
    return $object;
  }

  /**
   * Context to be pre-loaded before translation.
   */
  protected function get_translate_context($langcode, $options) {
    // One-query translation of all textgroup:type:objectid:* properties
    $context = $this->get_string_context();
    $context[] = '*';
    return $context;
  }
  
  /**
   * Translate object property.
   * 
   * Mot often, this is a direct field set, but sometimes fields may have different formats.
   */
  protected function translate_field(&$object, $i18nstring, $langcode, $options) {
    $field_name = $i18nstring->property;
    $translation = $i18nstring->format_translation($langcode, $options);
    if (is_object($object)) {
      $object->$field_name = $translation;
    }
    elseif (is_array($object)) {
      $object[$field_name] = $translation;
    }
  }
  
  /**
   * Remove all strings for this object.
   */
  public function strings_remove($options = array()) {
    return $this->strings_operation('remove', $options + array('empty' => TRUE)); 
  }

  /**
   * Update all strings for this object.
   */
  public function strings_update($options = array()) {
    return $this->strings_operation('update', $options + array('empty' => TRUE, 'update' => TRUE));
  }
  
  /**
   * Run some operation on all this object's strings.
   * 
   * @param $method
   *   Operation to run on all strings: 'update', 'remove'.
   * @param $options
   *   Array of options to pass to the string method.
   *   
   * @return array
   *   Count for each result
   */
  protected function strings_operation($method, $options = array()) {
    $result = array();
    foreach ($this->get_strings($options) as $string) {
      $status = $string->$method($options);
      $result[$status] = isset($result[$status]) ? $result[$status] +1 : 1;
    }
    return $result;    
  }
}