-
Notifications
You must be signed in to change notification settings - Fork 80
/
Translatable.php
executable file
·1805 lines (1620 loc) · 60.5 KB
/
Translatable.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* The Translatable decorator allows your DataObjects to have versions in different languages,
* defining which fields are can be translated. Translatable can be applied
* to any {@link DataObject} subclass, but is mostly used with {@link SiteTree}.
* Translatable is compatible with the {@link Versioned} extension.
* To avoid cluttering up the database-schema of the 99% of sites without multiple languages,
* the translation-feature is disabled by default.
*
* Locales (e.g. 'en_US') are used in Translatable for identifying a record by language,
* see section "Locales and Language Tags".
*
* <h2>Configuration</h2>
*
* <h3>Through Object::add_extension()</h3>
* Enabling Translatable through {@link Object::add_extension()} in your _config.php:
* <code>
* Object::add_extension('MyClass', 'Translatable');
* </code>
* This is the recommended approach for enabling Translatable.
*
* <h3>Through $extensions</h3>
* <code>
* class MyClass extends DataObject {
* static $extensions = array(
* "Translatable"
* );
* }
* </code>
*
* Make sure to rebuild the database through /dev/build after enabling translatable.
* Use the correct {@link set_default_locale()} before building the database
* for the first time, as this locale will be written on all new records.
*
* <h3>"Default" locales</h3>
*
* Important: If the "default language" of your site is not US-English (en_US),
* please ensure to set the appropriate default language for
* your content before building the database with Translatable enabled:
* <code>
* Translatable::set_default_locale(<locale>); // e.g. 'de_DE' or 'fr_FR'
* </code>
*
* For the Translatable class, a "locale" consists of a language code plus a region
* code separated by an underscore,
* for example "de_AT" for German language ("de") in the region Austria ("AT").
* See http://www.w3.org/International/articles/language-tags/ for a detailed description.
*
* <h2>Usage</h2>
*
* Getting a translation for an existing instance:
* <code>
* $translatedObj = Translatable::get_one_by_locale('MyObject', 'de_DE');
* </code>
*
* Getting a translation for an existing instance:
* <code>
* $obj = DataObject::get_by_id('MyObject', 99); // original language
* $translatedObj = $obj->getTranslation('de_DE');
* </code>
*
* Getting translations through {@link Translatable::set_current_locale()}.
* This is *not* a recommended approach, but sometimes inavoidable (e.g. for {@link Versioned} methods).
* <code>
* $origLocale = Translatable::get_current_locale();
* Translatable::set_current_locale('de_DE');
* $obj = Versioned::get_one_by_stage('MyObject', "ID = 99");
* Translatable::set_current_locale($origLocale);
* </code>
*
* Creating a translation:
* <code>
* $obj = new MyObject();
* $translatedObj = $obj->createTranslation('de_DE');
* </code>
*
* <h2>Usage for SiteTree</h2>
*
* Translatable can be used for subclasses of {@link SiteTree} as well.
*
* <code>
* Object::add_extension('SiteTree', 'Translatable');
* Object::add_extension('SiteConig', 'Translatable');
* </code>
*
* If a child page translation is requested without the parent
* page already having a translation in this language, the extension
* will recursively create translations up the tree.
* Caution: The "URLSegment" property is enforced to be unique across
* languages by auto-appending the language code at the end.
* You'll need to ensure that the appropriate "reading language" is set
* before showing links to other pages on a website through $_GET['locale'].
* Pages in different languages can have different publication states
* through the {@link Versioned} extension.
*
* Note: You can't get Children() for a parent page in a different language
* through set_current_locale(). Get the translated parent first.
*
* <code>
* // wrong
* Translatable::set_current_locale('de_DE');
* $englishParent->Children();
* // right
* $germanParent = $englishParent->getTranslation('de_DE');
* $germanParent->Children();
* </code>
*
* <h2>Translation groups</h2>
*
* Each translation can have one or more related pages in other languages.
* This relation is optional, meaning you can
* create translations which have no representation in the "default language".
* This means you can have a french translation with a german original,
* without either of them having a representation
* in the default english language tree.
* Caution: There is no versioning for translation groups,
* meaning associating an object with a group will affect both stage and live records.
*
* SiteTree database table (abbreviated)
* ^ ID ^ URLSegment ^ Title ^ Locale ^
* | 1 | about-us | About us | en_US |
* | 2 | ueber-uns | Über uns | de_DE |
* | 3 | contact | Contact | en_US |
*
* SiteTree_translationgroups database table
* ^ TranslationGroupID ^ OriginalID ^
* | 99 | 1 |
* | 99 | 2 |
* | 199 | 3 |
*
* <h2>Character Sets</h2>
*
* Caution: Does not apply any character-set conversion, it is assumed that all content
* is stored and represented in UTF-8 (Unicode). Please make sure your database and
* HTML-templates adjust to this.
*
* <h2>Permissions</h2>
*
* Authors without administrative access need special permissions to edit locales other than
* the default locale.
*
* - TRANSLATE_ALL: Translate into all locales
* - Translate_<locale>: Translate a specific locale. Only available for all locales set in
* `Translatable::set_allowed_locales()`.
*
* Note: If user-specific view permissions are required, please overload `SiteTree->canView()`.
*
* <h2>Uninstalling/Disabling</h2>
*
* Disabling Translatable after creating translations will lead to all
* pages being shown in the default sitetree regardless of their language.
* It is advised to start with a new database after uninstalling Translatable,
* or manually filter out translated objects through their "Locale" property
* in the database.
*
* @see http://doc.silverstripe.org/doku.php?id=multilingualcontent
*
* @author Ingo Schommer <ingo (at) silverstripe (dot) com>
* @author Michael Gall <michael (at) wakeless (dot) net>
* @author Bernat Foj Capell <bernat@silverstripe.com>
*
* @package translatable
*/
class Translatable extends DataExtension implements PermissionProvider {
/**
* The 'default' language.
* @var string
*/
protected static $default_locale = 'en_US';
/**
* The language in which we are reading dataobjects.
*
* @var string
*/
protected static $current_locale = null;
/**
* A cached list of existing tables
*
* @var mixed
*/
protected static $tableList = null;
/**
* An array of fields that can be translated.
* @var array
*/
protected $translatableFields = null;
/**
* A map of the field values of the original (untranslated) DataObject record
* @var array
*/
protected $original_values = null;
/**
* If this is set to TRUE then {@link augmentSQL()} will automatically add a filter
* clause to limit queries to the current {@link get_current_locale()}. This camn be
* disabled using {@link disable_locale_filter()}
*
* @var bool
*/
protected static $locale_filter_enabled = true;
/**
* @var array All locales in which a translation can be created.
* This limits the choice in the CMS language dropdown in the
* "Translation" tab, as well as the language dropdown above
* the CMS tree. If not set, it will default to showing all
* common locales.
*/
protected static $allowed_locales = null;
/**
* Reset static configuration variables to their default values
*/
static function reset() {
self::enable_locale_filter();
self::$default_locale = 'en_US';
self::$current_locale = null;
self::$allowed_locales = null;
}
/**
* Choose the language the site is currently on.
*
* If $_GET['locale'] is currently set, then that locale will be used.
* Otherwise the member preference (if logged
* in) or default locale will be used.
*
* @todo Re-implement cookie and member option
*
* @param $langsAvailable array A numerical array of languages which are valid choices (optional)
* @return string Selected language (also saved in $current_locale).
*/
static function choose_site_locale($langsAvailable = array()) {
if(self::$current_locale) {
return self::$current_locale;
}
if(
(isset($_REQUEST['locale']) && !$langsAvailable)
|| (isset($_REQUEST['locale'])
&& in_array($_REQUEST['locale'], $langsAvailable))
) {
// get from request parameter
self::set_current_locale($_REQUEST['locale']);
} else {
self::set_current_locale(self::default_locale());
}
return self::$current_locale;
}
/**
* Get the current reading language.
* This value has to be set before the schema is built with translatable enabled,
* any changes after this can cause unintended side-effects.
*
* @return string
*/
static function default_locale() {
return self::$default_locale;
}
/**
* Set default language. Please set this value *before* creating
* any database records (like pages), as this locale will be attached
* to all new records.
*
* @param $locale String
*/
static function set_default_locale($locale) {
if($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
$localeList = i18n::get_locale_list();
if(isset($localeList[$locale])) {
self::$default_locale = $locale;
} else {
user_error(
"Translatable::set_default_locale(): '$locale' is not a valid locale.",
E_USER_WARNING
);
}
}
/**
* Get the current reading language.
* If its not chosen, call {@link choose_site_locale()}.
*
* @return string
*/
static function get_current_locale() {
return (self::$current_locale) ? self::$current_locale : self::choose_site_locale();
}
/**
* Set the reading language, either namespaced to 'site' (website content)
* or 'cms' (management backend). This value is used in {@link augmentSQL()}
* to "auto-filter" all SELECT queries by this language.
* See {@link disable_locale_filter()} on how to override this behaviour temporarily.
*
* @param string $lang New reading language.
*/
static function set_current_locale($locale) {
if($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
self::$current_locale = $locale;
}
/**
* Get a singleton instance of a class in the given language.
* @param string $class The name of the class.
* @param string $locale The name of the language.
* @param string $filter A filter to be inserted into the WHERE clause.
* @param boolean $cache Use caching (default: false)
* @param string $orderby A sort expression to be inserted into the ORDER BY clause.
* @return DataObject
*/
static function get_one_by_locale($class, $locale, $filter = '', $cache = false, $orderby = "") {
if($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
$orig = Translatable::get_current_locale();
Translatable::set_current_locale($locale);
$do = $class::get()->where($filter)->sort($orderby)->First();
Translatable::set_current_locale($orig);
return $do;
}
/**
* Get all the instances of the given class translated to the given language
*
* @param string $class The name of the class
* @param string $locale The name of the language
* @param string $filter A filter to be inserted into the WHERE clause.
* @param string $sort A sort expression to be inserted into the ORDER BY clause.
* @param string $join A single join clause. This can be used for filtering, only 1
* instance of each DataObject will be returned.
* @param string $limit A limit expression to be inserted into the LIMIT clause.
* @param string $containerClass The container class to return the results in.
* @param string $having A filter to be inserted into the HAVING clause.
* @return mixed The objects matching the conditions.
*/
static function get_by_locale($class, $locale, $filter = '', $sort = '', $join = "", $limit = "") {
if($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
$oldLang = self::get_current_locale();
self::set_current_locale($locale);
$result = $class::get();
if($filter) $result = $result->where($filter);
if($sort) $result = $result->sort($sort);
if($join) $result = $result->leftJoin($join);
if($limit) $result = $result->limit($limit);
self::set_current_locale($oldLang);
return $result;
}
/**
* @return bool
*/
public static function locale_filter_enabled() {
return self::$locale_filter_enabled;
}
/**
* Enables automatic filtering by locale. This is normally called after is has been
* disabled using {@link disable_locale_filter()}.
*/
public static function enable_locale_filter() {
self::$locale_filter_enabled = true;
}
/**
* Disables automatic locale filtering in {@link augmentSQL()}. This can be re-enabled
* using {@link enable_locale_filter()}.
*/
public static function disable_locale_filter() {
self::$locale_filter_enabled = false;
}
/**
* Gets all translations for this specific page.
* Doesn't include the language of the current record.
*
* @return array Numeric array of all locales, sorted alphabetically.
*/
function getTranslatedLocales() {
$langs = array();
$baseDataClass = ClassInfo::baseDataClass($this->owner->class); //Base Class
$translationGroupClass = $baseDataClass . "_translationgroups";
if($this->owner->hasExtension("Versioned") && Versioned::current_stage() == "Live") {
$baseDataClass = $baseDataClass . "_Live";
}
$translationGroupID = $this->getTranslationGroup();
if(is_numeric($translationGroupID)) {
$query = new SQLQuery(
'DISTINCT "Locale"',
sprintf(
'"%s" LEFT JOIN "%s" ON "%s"."OriginalID" = "%s"."ID"',
$baseDataClass,
$translationGroupClass,
$translationGroupClass,
$baseDataClass
), // from
sprintf(
'"%s"."TranslationGroupID" = %d AND "%s"."Locale" != \'%s\'',
$translationGroupClass,
$translationGroupID,
$baseDataClass,
$this->owner->Locale
) // where
);
$langs = $query->execute()->column();
}
if($langs) {
$langCodes = array_values($langs);
sort($langCodes);
return $langCodes;
} else {
return array();
};
}
/**
* Gets all locales that a member can access
* as defined by {@link $allowed_locales}
* and {@link canTranslate()}.
* If {@link $allowed_locales} is not set and
* the user has the `TRANSLATE_ALL` permission,
* the method will return all available locales in the system.
*
* @param Member $member
* @return array Map of locales
*/
function getAllowedLocalesForMember($member) {
$locales = self::get_allowed_locales();
if(!$locales) $locales = i18n::get_common_locales();
if($locales) foreach($locales as $k => $locale) {
if(!$this->canTranslate($member, $locale)) unset($locales[$k]);
}
return $locales;
}
/**
* Get a list of languages in which a given element has been translated.
*
* @deprecated 2.4 Use {@link getTranslations()}
*
* @param string $class Name of the class of the element
* @param int $id ID of the element
* @return array List of languages
*/
static function get_langs_by_id($class, $id) {
$do = DataObject::get_by_id($class, $id);
return ($do ? $do->getTranslatedLocales() : array());
}
/**
* Enables the multilingual feature
*
* @deprecated 2.4 Use Object::add_extension('SiteTree', 'Translatable')
*/
static function enable() {
if(class_exists('SiteTree')) Object::add_extension('SiteTree', 'Translatable');
}
/**
* Disable the multilingual feature
*
* @deprecated 2.4 Use Object::remove_extension('SiteTree', 'Translatable')
*/
static function disable() {
if(class_exists('SiteTree')) Object::remove_extension('SiteTree', 'Translatable');
}
/**
* Check whether multilingual support has been enabled
*
* @deprecated 2.4 Use Object::has_extension('SiteTree', 'Translatable')
* @return boolean True if enabled
*/
static function is_enabled() {
if(class_exists('SiteTree')){
return Object::has_extension('SiteTree', 'Translatable');
}else{
return false;
}
}
/**
* Construct a new Translatable object.
* @var array $translatableFields The different fields of the object that can be translated.
* This is currently not implemented, all fields are marked translatable (see {@link setOwner()}).
*/
function __construct($translatableFields = null) {
parent::__construct();
// @todo Disabled selection of translatable fields - we're setting all fields as
// translatable in setOwner()
/*
if(!is_array($translatableFields)) {
$translatableFields = func_get_args();
}
$this->translatableFields = $translatableFields;
*/
// workaround for extending a method on another decorator (Hierarchy):
// split the method into two calls, and overwrite the wrapper AllChildrenIncludingDeleted()
// Has to be executed even with Translatable disabled, as it overwrites the method with same name
// on Hierarchy class, and routes through to Hierarchy->doAllChildrenIncludingDeleted() instead.
// Caution: There's an additional method for augmentAllChildrenIncludingDeleted()
}
function setOwner($owner, $ownerBaseClass = null) {
parent::setOwner($owner, $ownerBaseClass);
// setting translatable fields by inspecting owner - this should really be done in the constructor
if($this->owner && $this->translatableFields === null) {
$this->translatableFields = array_merge(
array_keys($this->owner->inheritedDatabaseFields()),
array_keys($this->owner->has_many()),
array_keys($this->owner->many_many()),
array_keys($this->owner->has_one())
);
}
}
static function add_to_class($class, $extensionClass, $args = null) {
Config::inst()->update($class, 'defaults', array(
"Locale" => Translatable::default_locale() // as an overloaded getter as well: getLang()
));
Config::inst()->update($class, 'db', array(
"Locale" => "DBLocale",
//"TranslationMasterID" => "Int" // optional relation to a "translation master"
));
parent::add_to_class($class, $extensionClass, $args);
}
/**
* Changes any SELECT query thats not filtering on an ID
* to limit by the current language defined in {@link get_current_locale()}.
* It falls back to "Locale='' OR Lang IS NULL" and assumes that
* this implies querying for the default language.
*
* Use {@link disable_locale_filter()} to temporarily disable this "auto-filtering".
*/
function augmentSQL(SQLQuery &$query) {
// If the record is saved (and not a singleton), and has a locale,
// limit the current call to its locale. This fixes a lot of problems
// with other extensions like Versioned
if($this->owner->ID && !empty($this->owner->Locale)) {
$locale = $this->owner->Locale;
} else {
$locale = Translatable::get_current_locale();
}
$baseTable = ClassInfo::baseDataClass($this->owner->class);
if(
$locale
// unless the filter has been temporarily disabled
&& self::locale_filter_enabled()
// DataObject::get_by_id() should work independently of language
&& !$query->filtersOnID()
// the query contains this table
// @todo Isn't this always the case?!
&& array_search($baseTable, array_keys($query->getFrom())) !== false
// or we're already filtering by Lang (either from an earlier augmentSQL()
// call or through custom SQL filters)
&& !preg_match('/("|\'|`)Locale("|\'|`)/', implode(' ', $query->getWhere()))
//&& !$query->filtersOnFK()
) {
$qry = sprintf('"%s"."Locale" = \'%s\'', $baseTable, Convert::raw2sql($locale));
$query->addWhere($qry);
}
}
/**
* Create <table>_translation database table to enable
* tracking of "translation groups" in which each related
* translation of an object acts as a sibling, rather than
* a parent->child relation.
*/
function augmentDatabase() {
$baseDataClass = ClassInfo::baseDataClass($this->owner->class);
if($this->owner->class != $baseDataClass) return;
$fields = array(
'OriginalID' => 'Int',
'TranslationGroupID' => 'Int',
);
$indexes = array(
'OriginalID' => true,
'TranslationGroupID' => true
);
// Add new tables if required
DB::requireTable("{$baseDataClass}_translationgroups", $fields, $indexes);
// Remove 2.2 style tables
DB::dontRequireTable("{$baseDataClass}_lang");
if($this->owner->hasExtension('Versioned')) {
DB::dontRequireTable("{$baseDataClass}_lang_Live");
DB::dontRequireTable("{$baseDataClass}_lang_versions");
}
}
/**
* @todo Find more appropriate place to hook into database building
*/
function requireDefaultRecords() {
// @todo This relies on the Locale attribute being on the base data class, and not any subclasses
if($this->owner->class != ClassInfo::baseDataClass($this->owner->class)) return false;
// Permissions: If a group doesn't have any specific TRANSLATE_<locale> edit rights,
// but has CMS_ACCESS_CMSMain (general CMS access), then assign TRANSLATE_ALL permissions as a default.
// Auto-setting permissions based on these intransparent criteria is a bit hacky,
// but unavoidable until we can determine when a certain permission code was made available first
// (see http://open.silverstripe.org/ticket/4940)
$groups = Permission::get_groups_by_permission(array(
'CMS_ACCESS_CMSMain',
'CMS_ACCESS_LeftAndMain',
'ADMIN'
));
if($groups) foreach($groups as $group) {
$codes = $group->Permissions()->column('Code');
$hasTranslationCode = false;
foreach($codes as $code) {
if(preg_match('/^TRANSLATE_/', $code)) $hasTranslationCode = true;
}
// Only add the code if no more restrictive code exists
if(!$hasTranslationCode) Permission::grant($group->ID, 'TRANSLATE_ALL');
}
// If the Translatable extension was added after the first records were already
// created in the database, make sure to update the Locale property if
// if wasn't set before
$idsWithoutLocale = DB::query(sprintf(
'SELECT "ID" FROM "%s" WHERE "Locale" IS NULL OR "Locale" = \'\'',
ClassInfo::baseDataClass($this->owner->class)
))->column();
if(!$idsWithoutLocale) return;
if(class_exists('SiteTree') && $this->owner->class == 'SiteTree') {
foreach(array('Stage', 'Live') as $stage) {
foreach($idsWithoutLocale as $id) {
$obj = Versioned::get_one_by_stage(
$this->owner->class,
$stage,
sprintf('"SiteTree"."ID" = %d', $id)
);
if(!$obj) continue;
$obj->Locale = Translatable::default_locale();
$obj->writeToStage($stage);
$obj->addTranslationGroup($obj->ID);
$obj->destroy();
unset($obj);
}
}
} else {
foreach($idsWithoutLocale as $id) {
$obj = DataObject::get_by_id($this->owner->class, $id);
if(!$obj) continue;
$obj->Locale = Translatable::default_locale();
$obj->write();
$obj->addTranslationGroup($obj->ID);
$obj->destroy();
unset($obj);
}
}
DB::alteration_message(sprintf(
"Added default locale '%s' to table %s","changed",
Translatable::default_locale(),
$this->owner->class
));
}
/**
* Add a record to a "translation group",
* so its relationship to other translations
* based off the same object can be determined later on.
* See class header for further comments.
*
* @param int $originalID Either the primary key of the record this new translation is based on,
* or the primary key of this record, to create a new translation group
* @param boolean $overwrite
*/
public function addTranslationGroup($originalID, $overwrite = false) {
if(!$this->owner->exists()) return false;
$baseDataClass = ClassInfo::baseDataClass($this->owner->class);
$existingGroupID = $this->getTranslationGroup($originalID);
// Remove any existing groups if overwrite flag is set
if($existingGroupID && $overwrite) {
$sql = sprintf(
'DELETE FROM "%s_translationgroups" WHERE "TranslationGroupID" = %d AND "OriginalID" = %d',
$baseDataClass,
$existingGroupID,
$this->owner->ID
);
DB::query($sql);
$existingGroupID = null;
}
// Add to group (only if not in existing group or $overwrite flag is set)
if(!$existingGroupID) {
$sql = sprintf(
'INSERT INTO "%s_translationgroups" ("TranslationGroupID","OriginalID") VALUES (%d,%d)',
$baseDataClass,
$originalID,
$this->owner->ID
);
DB::query($sql);
}
}
/**
* Gets the translation group for the current record.
* This ID might equal the record ID, but doesn't have to -
* it just points to one "original" record in the list.
*
* @return int Numeric ID of the translationgroup in the <classname>_translationgroup table
*/
public function getTranslationGroup() {
if(!$this->owner->exists()) return false;
$baseDataClass = ClassInfo::baseDataClass($this->owner->class);
return DB::query(
sprintf(
'SELECT "TranslationGroupID" FROM "%s_translationgroups" WHERE "OriginalID" = %d',
$baseDataClass,
$this->owner->ID
)
)->value();
}
/**
* Removes a record from the translation group lookup table.
* Makes no assumptions on other records in the group - meaning
* if this happens to be the last record assigned to the group,
* this group ceases to exist.
*/
public function removeTranslationGroup() {
$baseDataClass = ClassInfo::baseDataClass($this->owner->class);
DB::query(
sprintf('DELETE FROM "%s_translationgroups" WHERE "OriginalID" = %d', $baseDataClass, $this->owner->ID)
);
}
/**
* Determine if a table needs Versioned support
* This is called at db/build time
*
* @param string $table Table name
* @return boolean
*/
function isVersionedTable($table) {
return false;
}
/**
* Note: The bulk of logic is in ModelAsController->getNestedController()
* and ContentController->handleRequest()
*/
function contentcontrollerInit($controller) {
$controller->Locale = Translatable::choose_site_locale();
}
function modelascontrollerInit($controller) {
//$this->contentcontrollerInit($controller);
}
function initgetEditForm($controller) {
$this->contentcontrollerInit($controller);
}
/**
* Recursively creates translations for parent pages in this language
* if they aren't existing already. This is a necessity to make
* nested pages accessible in a translated CMS page tree.
* It would be more userfriendly to grey out untranslated pages,
* but this involves complicated special cases in AllChildrenIncludingDeleted().
*
* {@link SiteTree->onBeforeWrite()} will ensure that each translation will get
* a unique URL across languages, by means of {@link SiteTree::get_by_link()}
* and {@link Translatable->alternateGetByURL()}.
*/
function onBeforeWrite() {
// If language is not set explicitly, set it to current_locale.
// This might be a bit overzealous in assuming the language
// of the content, as a "single language" website might be expanded
// later on. See {@link requireDefaultRecords()} for batch setting
// of empty Locale columns on each dev/build call.
if(!$this->owner->Locale) {
$this->owner->Locale = Translatable::get_current_locale();
}
// Specific logic for SiteTree subclasses.
// If page has untranslated parents, create (unpublished) translations
// of those as well to avoid having inaccessible children in the sitetree.
// Caution: This logic is very sensitve to infinite loops when translation status isn't determined properly
// If a parent for the newly written translation was existing before this
// onBeforeWrite() call, it will already have been linked correctly through createTranslation()
if(
class_exists('SiteTree')
&& $this->owner->hasField('ParentID')
&& $this->owner instanceof SiteTree
) {
if(
!$this->owner->ID
&& $this->owner->ParentID
&& !$this->owner->Parent()->hasTranslation($this->owner->Locale)
) {
$parentTranslation = $this->owner->Parent()->createTranslation($this->owner->Locale);
$this->owner->ParentID = $parentTranslation->ID;
}
}
// Has to be limited to the default locale, the assumption is that the "page type"
// dropdown is readonly on all translations.
if($this->owner->ID && $this->owner->Locale == Translatable::default_locale()) {
$changedFields = $this->owner->getChangedFields();
if(isset($changedFields['ClassName'])) {
$this->owner->ClassName = $changedFields['ClassName']['before'];
$translations = $this->owner->getTranslations();
$this->owner->ClassName = $changedFields['ClassName']['after'];
if($translations) foreach($translations as $translation) {
$translation->setClassName($this->owner->ClassName);
$translation = $translation->newClassInstance($translation->ClassName);
$translation->populateDefaults();
$translation->forceChange();
$translation->write();
}
}
}
// see onAfterWrite()
if(!$this->owner->ID) {
$this->owner->_TranslatableIsNewRecord = true;
}
}
function onAfterWrite() {
// hacky way to determine if the record was created in the database,
// or just updated
if($this->owner->_TranslatableIsNewRecord) {
// this would kick in for all new records which are NOT
// created through createTranslation(), meaning they don't
// have the translation group automatically set.
$translationGroupID = $this->getTranslationGroup();
if(!$translationGroupID) {
$this->addTranslationGroup(
$this->owner->_TranslationGroupID ? $this->owner->_TranslationGroupID : $this->owner->ID
);
}
unset($this->owner->_TranslatableIsNewRecord);
unset($this->owner->_TranslationGroupID);
}
}
/**
* Remove the record from the translation group mapping.
*/
function onBeforeDelete() {
// @todo Coupling to Versioned, we need to avoid removing
// translation groups if records are just deleted from a stage
// (="unpublished"). Ideally the translation group tables would
// be specific to different Versioned changes, making this restriction unnecessary.
// This will produce orphaned translation group records for SiteTree subclasses.
if(!$this->owner->hasExtension('Versioned')) {
$this->removeTranslationGroup();
}
parent::onBeforeDelete();
}
/**
* Attempt to get the page for a link in the default language that has been translated.
*
* @param string $URLSegment
* @param int|null $parentID
* @return SiteTree
*/
public function alternateGetByLink($URLSegment, $parentID) {
// If the parentID value has come from a translated page,
// then we need to find the corresponding parentID value
// in the default Locale.
if (
is_int($parentID)
&& $parentID > 0
&& ($parent = DataObject::get_by_id('SiteTree', $parentID))
&& ($parent->isTranslation())
) {
$parentID = $parent->getTranslationGroup();
}
// Find the locale language-independent of the page
self::disable_locale_filter();
$default = SiteTree::get()->where(sprintf (
'"URLSegment" = \'%s\'%s',
Convert::raw2sql($URLSegment),
(is_int($parentID) ? " AND \"ParentID\" = $parentID" : null)
))->First();
self::enable_locale_filter();
return $default;
}
//-----------------------------------------------------------------------------------------------//
function applyTranslatableFieldsUpdate($fields, $type) {
if (method_exists($this, $type)) {
$this->$type($fields);
} else {
throw new InvalidArgumentException("Method $type does not exist on object of type ". get_class($this));
}
}
/**
* If the record is not shown in the default language, this method
* will try to autoselect a master language which is shown alongside
* the normal formfields as a readonly representation.
* This gives translators a powerful tool for their translation workflow
* without leaving the translated page interface.
* Translatable also adds a new tab "Translation" which shows existing
* translations, as well as a formaction to create new translations based
* on a dropdown with available languages.
*
* This method can be called multiple times on the same FieldList
* because it checks which fields have already been added or modified.
*
* @todo This is specific to SiteTree and CMSMain
* @todo Implement a special "translation mode" which triggers display of the
* readonly fields, so you can translation INTO the "default language" while
* seeing readonly fields as well.
*/
function updateCMSFields(FieldList $fields) {
$this->addTranslatableFields($fields);
// Show a dropdown to create a new translation.
// This action is possible both when showing the "default language"
// and a translation. Include the current locale (record might not be saved yet).
$alreadyTranslatedLocales = $this->getTranslatedLocales();
$alreadyTranslatedLocales[$this->owner->Locale] = $this->owner->Locale;
$alreadyTranslatedLocales = array_combine($alreadyTranslatedLocales, $alreadyTranslatedLocales);
// Check if fields exist already to avoid adding them twice on repeat invocations
$tab = $fields->findOrMakeTab('Root.Translations', _t('Translatable.TRANSLATIONS', 'Translations'));
if(!$tab->fieldByName('CreateTransHeader')) {
$tab->push(new HeaderField(
'CreateTransHeader',
_t('Translatable.CREATE', 'Create new translation'),
2
));
}
if(!$tab->fieldByName('NewTransLang') && !$tab->fieldByName('AllTransCreated')) {
$langDropdown = LanguageDropdownField::create(
"NewTransLang",
_t('Translatable.NEWLANGUAGE', 'New language'),
$alreadyTranslatedLocales,
'SiteTree',
'Locale-English',
$this->owner
)->addExtraClass('languageDropdown no-change-track');
$tab->push($langDropdown);
$canAddLocale = (count($langDropdown->getSource()) > 0);
if($canAddLocale) {
// Only add create button if new languages are available
$tab->push(
$createButton = InlineFormAction::create(
'createtranslation',
_t('Translatable.CREATEBUTTON', 'Create')
)->addExtraClass('createTranslationButton')
);
$createButton->includeDefaultJS(false); // not fluent API...
} else {
$tab->removeByName('NewTransLang');
$tab->push(new LiteralField(
'AllTransCreated',
_t('Translatable.ALLCREATED', 'All allowed translations have been created.')