-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmlanglib.php
2443 lines (2106 loc) · 85.7 KB
/
mlanglib.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
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Moodle language manipulation library
*
* Provides classes and functions to handle various low-level operations on Moodle
* strings in various formats.
*
* @package local_amos
* @copyright 2010 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Base exception thrown by low level language manipulation operations
*/
class mlang_exception extends moodle_exception {
/**
* Constructor.
*
* @param string $hint short description of problem
* @param string $debuginfo detailed information how to fix problem
*/
public function __construct($hint, $debuginfo=null) {
parent::__construct('err_exception', 'local_amos', '', $hint, $debuginfo);
}
}
/**
* Represents a collection of strings for a given component
*/
class mlang_component implements IteratorAggregate, Countable {
/** @var the name of the component, what {@see string_manager::get_string()} uses as the second param */
public $name;
/** @var string language code we are part of */
public $lang;
/** @var mlang_version we are part of */
public $version;
/** @var holds instances of mlang_string in an associative array */
protected $strings = array();
/**
* Constructor.
*
* @param string $name the name of the component, eg. 'role', 'glossary', 'datafield_text' etc.
* @param string $lang
* @param mlang_version $version
*/
public function __construct($name, $lang, mlang_version $version) {
$this->name = $name;
$this->lang = $lang;
$this->version = $version;
}
/**
* Given a path to a file, returns the name of the component
*
* @param mixed $filepath
* @return string
*/
public static function name_from_filename($filepath) {
$pathparts = pathinfo($filepath);
return $pathparts['filename'];
}
/**
* Factory method returning an instance with strings loaded from a file in Moodle PHP format
*
* @param string $filepath full path to the file to load
* @param string $lang lang pack we are part of
* @param mlang_version $version the branch to put this string on
* @param int $timemodified use this as a timestamp of string modification instead of the filemtime()
* @param string $name use this as a component name instead of guessing from the file name
* @param int $format in what string format the file is written - 1 for 1.x string, 2 for 2.x strings
* @throws Exception
* @return mlang_component
*/
public static function from_phpfile($filepath, $lang, mlang_version $version, $timemodified=null, $name=null, $format=null) {
if (empty($name)) {
$name = self::name_from_filename($filepath);
}
$component = new mlang_component($name, $lang, $version);
unset($string);
if (is_readable($filepath)) {
if (empty($timemodified)) {
$timemodified = filemtime($filepath);
}
// Empty placeholder to prevent PHP notices.
$a = '';
include($filepath);
} else {
throw new Exception('Strings definition file ' . $filepath . ' not readable');
}
if ($version->code <= 19) {
// We are going to import strings for 1.x branch.
$target = 1;
if (is_null($format)) {
$format = 1;
}
if ($format !== 1) {
throw new coding_exception('For Moodle 1.x, only strings in legacy format are supported.');
}
} else {
// We are going to import strings for 2.x branch.
$target = 2;
if (is_null($format)) {
$format = 2;
}
}
if (!empty($string) && is_array($string)) {
foreach ($string as $id => $value) {
$id = clean_param($id, PARAM_STRINGID);
if (empty($id)) {
continue;
}
$value = mlang_string::fix_syntax($value, $target, $format);
$component->add_string(new mlang_string($id, $value, $timemodified), true);
}
} else {
debugging('No strings defined in ' . $filepath, DEBUG_DEVELOPER);
}
return $component;
}
/**
* Get a snapshot of all strings in the given component
*
* @param string $name The component name.
* @param string $lang The language code.
* @param mlang_version $version Version of the component.
* @param int $timestamp Time of the snapshot, defaults to the most recent one.
* @param bool $deleted Shall deleted strings be included?
* @param bool $fullinfo Shall full information about the string (commit messages, source etc.) be returned?
* @param array $strnames Limit the list of loaded strings to ones in this list only.
* @return mlang_component Component with the strings from the snapshot.
*/
public static function from_snapshot(string $name, string $lang, mlang_version $version, ?int $timestamp = null,
bool $deleted=false, bool $fullinfo = false, ?array $strnames = null): mlang_component {
global $DB;
$sql = "SELECT r.id, r.strname, r.strtext, r.since, r.timemodified";
if ($fullinfo) {
$sql .= ", c.id AS commitid, c.source, c.timecommitted, c.commitmsg, c.commithash, c.userid, c.userinfo";
}
$params = [
'component' => $name,
'version' => $version->code,
];
if ($lang === 'en') {
$table = 'amos_strings';
$langsql = '';
} else {
$table = 'amos_translations';
$langsql = " AND lang = :lang ";
$params['lang'] = $lang;
}
$sql .= " FROM {" . $table . "} r";
if ($fullinfo) {
$sql .= " LEFT JOIN {amos_commits} c ON (r.commitid = c.id)";
}
$sql .= " WHERE component = :component
$langsql
AND since <= :version";
if (!empty($strnames)) {
list($strsql, $strparams) = $DB->get_in_or_equal($strnames, SQL_PARAMS_NAMED);
$sql .= " AND strname $strsql";
$params += $strparams;
}
if (!empty($timestamp)) {
$sql .= " AND timemodified <= :timemodified";
$params['timemodified'] = $timestamp;
}
$rs = $DB->get_recordset_sql($sql, $params);
$latest = [];
foreach ($rs as $r) {
if (!isset($latest[$r->strname])) {
$latest[$r->strname] = $r;
} else {
$s = $latest[$r->strname];
if ($r->since < $s->since) {
continue;
}
if (($r->since == $s->since) && ($r->timemodified < $s->timemodified)) {
continue;
}
if (($r->since == $s->since) && ($r->timemodified == $s->timemodified) && ($r->id < $s->id)) {
continue;
}
$latest[$r->strname] = $r;
}
}
$rs->close();
if (!$deleted) {
// Prune the deleted strings. Keep in mind to do it only this late here and not in SQL.
// The string could have been added, deleted and re-added again. We need to know what the latest one is.
foreach ($latest as $strname => $str) {
if ($str->strtext === null) {
unset($latest[$strname]);
}
}
}
ksort($latest);
$component = new mlang_component($name, $lang, $version);
foreach ($latest as $str) {
$extra = null;
if ($fullinfo) {
$extra = (object)[];
foreach ($str as $property => $value) {
if (!in_array($property, ['strname', 'strtext', 'timemodified'])) {
$extra->{$property} = $value;
}
}
}
$component->add_string(new mlang_string($str->strname, $str->strtext, $str->timemodified,
$str->strtext === null, $extra), true);
}
return $component;
}
/**
* Calculate a identifier of a given component name, language and version
*
* Such identifier can be used as a key in component collections (associative arrays).
*
* @param string $name the name of the component, eg. 'role', 'glossary', 'datafield_text' etc.
* @param string $lang
* @param mlang_version $version
* @return string
*/
public static function calculate_identifier($name, $lang, mlang_version $version) {
return md5($name . '#' . $lang . '@' . $version->code);
}
/**
* Returns the current identifier of the component
*
* Every component is identified by its branch, lang and name. This method returns md5 hash of
* a concatenation of these three values.
*
* @return string
*/
public function get_identifier() {
return self::calculate_identifier($this->name, $this->lang, $this->version);
}
// phpcs:disable moodle.NamingConventions.ValidFunctionName
/**
* Returns an external iterator over strings in the component.
*
* @return ArrayIterator
*/
public function getIterator(): Traversable {
return new ArrayIterator($this->strings);
}
// phpcs:enable
/**
* Return the number of strings in the component.
*
* @return int
*/
public function count(): int {
return count($this->strings);
}
/**
* Returns the string object or null if not known
*
* @param string $id string identifier
* @return mlang_string|null
*/
public function get_string($id) {
if (!isset($this->strings[$id])) {
return null;
}
return $this->strings[$id];
}
/**
* Checks if the component contains some strings or a given string
*
* @param string $id If null, checks if any string is defined. Otherwise checks for a given string
* @return bool
*/
public function has_string($id=null) {
if (is_null($id)) {
return (!empty($this->strings));
} else {
return (isset($this->strings[$id]));
}
}
/**
* Returns array of all string identifiers in the component
*
* @return array of string identifiers
*/
public function get_string_keys() {
return array_keys($this->strings);
}
/**
* Returns the number of strings in the component
*
* Beware - if deleted strings are loaded into this component, they are counted too - unless non-translatable
* strings are excluded.
*
* @param bool $forstats Counting strings for stats purposes, so non-translatable strings are excluded
* @return int
*/
public function get_number_of_strings($forstats = false) {
if (!$forstats) {
return count($this->strings);
} else {
$result = 0;
foreach ($this->strings as $string) {
if ($string->should_be_included_in_stats()) {
$result++;
}
}
return $result;
}
}
/**
* Adds new string into the collection
*
* @param mlang_string $string to add
* @param bool $force if true, existing string will be replaced
* @throws coding_exception when trying to add existing component without $force
* @return void
*/
public function add_string(mlang_string $string, $force=false) {
if (!$force && isset($this->strings[$string->id])) {
throw new coding_exception('You are trying to add a string \'' . $string->id .
'\' that already exists in this component. If this is intentional, use the \'force\' parameter');
}
$this->strings[$string->id] = $string;
$string->component = $this;
}
/**
* Removes a string from the component container
*
* @param string $id string identifier
*/
public function unlink_string($id) {
if (isset($this->strings[$id])) {
$this->strings[$id]->component = null;
unset($this->strings[$id]);
}
}
/**
* Unlinks all strings
*/
public function clear() {
foreach ($this->strings as $string) {
$this->unlink_string($string->id);
}
}
/**
* Exports the string into a file in Moodle PHP format ($string array)
*
* @param string $filepath full path of the file to write into
* @param string $phpdoc optional custom PHPdoc block for the file
* @return false if unable to open a file
*/
public function export_phpfile($filepath, $phpdoc = null) {
if (! $f = fopen($filepath, 'w')) {
return false;
}
fwrite($f, <<<EOF
<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
EOF
);
if (empty($phpdoc)) {
$version = $this->version->label;
$lang = $this->lang;
$name = $this->name;
fwrite($f, <<<EOF
/**
* Strings for component '$name', language '$lang', version '$version'.
*
* @package $this->name
* @category string
* @copyright 1999 Martin Dougiamas and contributors
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
EOF
);
} else {
fwrite($f, $phpdoc);
}
fwrite($f, "defined('MOODLE_INTERNAL') || die();\n\n");
ksort($this->strings);
foreach ($this as $string) {
if ($this->name === 'langconfig' && $string->id === 'parentlanguage') {
$knownlangs = mlang_tools::list_languages();
if ($string->text !== '' && !isset($knownlangs[$string->text])) {
fwrite($f, "// Warning: this parentlanguage value is not a valid language code!\n");
fwrite($f, '// $string[\'' . $string->id . '\'] = ');
fwrite($f, var_export($string->text, true));
fwrite($f, ";\n");
continue;
}
}
fwrite($f, '$string[\'' . $string->id . '\'] = ');
fwrite($f, var_export($string->text, true));
fwrite($f, ";\n");
}
fclose($f);
}
/**
* Returns the relative path to the file where the component should be exported to
*
* This respects the component language and version. For Moodle 1.6 - 1.9, string files
* are put into common lang/xx_utf8 directory. Since Moodle 2.0, every plugin type
* holds its own strings itself. This may either return the path in the source tree
* (if $treeish param is true) or a path using a directory common for all components.
*
* For example, for Workshop module this returns 'lang/xx_utf8/workshop.php' in 1.x,
* 'mod/workshop/lang/xx/workshop.php' in treeish 2.x and 'lang/xx/workshop.php' in
* non-treeish (flat) 2.x
*
* @param bool $treeish shall the path respect the component location in the source code tree
* @return string relative path to the file
*/
public function get_phpfile_location($treeish=true) {
global $CFG;
if ($this->version->code <= 19) {
// Moodle 1.x.
return 'lang/' . $this->lang . '_utf8/' . $this->name . '.php';
} else {
// Moodle 2.x.
if ($treeish) {
debugging('The method get_phpfile_location() may produce wrong results as '.
'it is unable to differentiate core plugins from activity modules. '.
'Using normalize_component() is not reliable much because it depends '.
'on the site version and may be wrong for older/newer versions');
list($type, $plugin) = \core_component::normalize_component($this->name);
if ($type === 'core') {
return 'lang/' . $this->lang . '/' . $this->name . '.php';
} else {
$abspath = get_plugin_directory($type, $plugin);
if (substr($abspath, 0, strlen($CFG->dirroot)) !== $CFG->dirroot) {
throw new coding_exception('Plugin directory outside dirroot', $abspath);
}
$relpath = substr($abspath, strlen($CFG->dirroot) + 1);
return $relpath . '/lang/' . $this->lang . '/' . $this->name . '.php';
}
} else {
return 'lang/' . $this->lang . '/' . $this->name . '.php';
}
}
}
/**
* Prunes the strings, keeping just those defined in given $mask as well
*
* This may be used to get rid of strings that are not defined in another component.
* Typically can be used to clean the translation from strings that are not defined in
* the English pack.
* Beware - if the string is defined in $mask as deleted, it will be kept in this regardless
* its state.
*
* @param mlang_component $mask component to compare strings with
* @return int number of removed strings
*/
public function intersect(mlang_component $mask) {
$removed = 0;
$masked = array_flip($mask->get_string_keys());
foreach (array_keys($this->strings) as $key) {
if (! isset($masked[$key])) {
$this->unlink_string($key);
$removed++;
}
}
return $removed;
}
/**
* Prunes all strings that have the same text as in the reference component
*
* This may be used to get rid of strings that are defined in another component
* and have the same text value. Typical usage is the post-merge cleanup of the en_fix
* language pack.
* Beware - if the string is defined in $reference as deleted, it will be kept in this
* regardless its state and value. Our strings that are already deleted are not
* affected.
*
* @param mlang_component $reference component to compare strings with
* @return array list of removed string ids
*/
public function complement(mlang_component $reference) {
$removed = [];
foreach ($this->strings as $id => $string) {
if ($string->deleted) {
// Do not affect our strings that are already deleted.
continue;
}
if (!$reference->has_string($id)) {
// Do not affect strings not present in $reference.
// See {@see self::intersect()} if you want to get rid of such strings.
continue;
}
if (mlang_string::differ($string, $reference->get_string($id))) {
// Do not affect strings that are considered as different from the ones
// in the $reference.
continue;
}
$this->unlink_string($id);
$removed[] = $id;
}
return $removed;
}
/**
* Returns timemodified stamp of the most recent string in the component
*
* @return int timestamp, 0 if the component is empty
*/
public function get_recent_timemodified() {
$recent = 0;
foreach ($this as $string) {
if ($string->timemodified > $recent) {
$recent = $string->timemodified;
}
}
return $recent;
}
/**
* Clean all strings from debris
*
* @see mlang_string::clean_text()
*/
public function clean_texts() {
if ($this->version->code <= 19) {
$format = 1;
} else {
$format = 2;
}
foreach ($this as $string) {
$string->clean_text($format);
}
}
/**
* Fix the mlang_version after waking up from the serialization.
*/
public function __wakeup() {
if ($this->version->code >= 1600) {
$this->version = mlang_version::by_code($this->version->code / 100);
} else {
$this->version = mlang_version::by_code($this->version->code);
}
}
}
/**
* Represents a single string
*/
class mlang_string {
/** @var string identifier */
public $id = null;
/** @var string */
public $text = '';
/** @var int the time stamp when this string was saved */
public $timemodified = null;
/** @var bool is deleted */
public $deleted = false;
/** @var extra information about the string */
public $extra = null;
/** @var mlang_component we are part of */
public $component;
/** @var boolean should we skip some cleaning */
public $nocleaning = false;
/**
* Constructor.
*
* @param string $id string identifier
* @param string $text string text
* @param int $timemodified
* @param bool $deleted
* @param stdclass $extra
*/
public function __construct($id, $text='', $timemodified=null, $deleted=0, stdclass $extra=null) {
if (is_null($timemodified)) {
$timemodified = time();
}
$this->id = $id;
$this->text = $text;
$this->timemodified = $timemodified;
$this->deleted = $deleted;
$this->extra = $extra;
}
/**
* Returns true if the two given strings should be considered as different, false otherwise.
*
* Deleted strings are considered equal, regardless the actual text
*
* @param mlang_string $a
* @param mlang_string $b
* @return bool
*/
public static function differ(mlang_string $a, mlang_string $b) {
if ($a->deleted and $b->deleted) {
return false;
}
if (is_null($a->text) or is_null($b->text)) {
if (is_null($a->text) and is_null($b->text)) {
return false;
} else {
return true;
}
}
if ($a->nocleaning || $b->nocleaning) {
if ($a->text === $b->text) {
return false;
}
} else {
if (trim($a->text) === trim($b->text)) {
return false;
}
}
return true;
}
/**
* Clean the string text from debris and make sure it has an expected format
*
* @see self::fix_syntax()
* @param int $format the string syntax revision (1 for Moodle 1.x, 2 for Moodle 2.x)
*/
public function clean_text($format=2) {
if ($this->nocleaning) {
$this->text = self::fix_syntax_minimal($this->text);
} else {
$this->text = self::fix_syntax($this->text, $format);
}
}
/**
* Given a string text, returns it being formatted properly for storing in AMOS repository
*
* We need to know for what branch the string should be prepared due to internal changes in
* format required by get_string()
* - for get_string() in Moodle 1.6 - 1.9 use $format == 1
* - for get_string() in Moodle 2.0 and higher use $format == 2
*
* Typical usages of this methods:
* $t = mlang_string::fix_syntax($t); // sanity new translations of 2.x strings
* $t = mlang_string::fix_syntax($t, 1); // sanity legacy 1.x strings
* $t = mlang_string::fix_syntax($t, 2, 1); // convert format of 1.x strings into 2.x
*
* Backward converting 2.x format into 1.x is not supported
*
* @param string $text string text to be fixed
* @param int $format target get_string() format version
* @param int $from which format version does the text come from, defaults to the same as $format
* @return string
*/
public static function fix_syntax($text, $format=2, $from=null) {
if (is_null($from)) {
$from = $format;
}
// Common filter.
$clean = trim($text);
$search = array(
// phpcs:disable moodle.Commenting.InlineComment
// Remove \r if it is part of \r\n.
'/\r(?=\n)/',
// Control characters to be replaced with \n.
// LINE TABULATION, FORM FEED, CARRIAGE RETURN, END OF TRANSMISSION BLOCK,
// END OF MEDIUM, SUBSTITUTE, BREAK PERMITTED HERE, NEXT LINE, START OF STRING,
// STRING TERMINATOR and Unicode character categorys Zl and Zp
'/[\x{0B}-\r\x{17}\x{19}\x{1A}\x{82}\x{85}\x{98}\x{9C}\p{Zl}\p{Zp}]/u',
// Control characters to be removed.
// NULL, ENQUIRY, ACKNOWLEDGE, BELL, SHIFT {OUT,IN}, DATA LINK ESCAPE,
// DEVICE CONTROL {ONE,TWO,THREE,FOUR}, NEGATIVE ACKNOWLEDGE, SYNCHRONOUS IDLE, ESCAPE,
// DELETE, PADDING CHARACTER, HIGH OCTET PRESET, NO BREAK HERE, INDEX,
// {START,END} OF SELECTED AREA, CHARACTER TABULATION {SET,WITH JUSTIFICATION},
// LINE TABULATION SET, PARTIAL LINE {FORWARD,BACKWARD}, REVERSE LINE FEED,
// SINGLE SHIFT {TWO,THREE}, DEVICE CONTROL STRING, PRIVATE USE {ONE,TWO},
// SET TRANSMIT STATE, MESSAGE WAITING, {START,END} OF GUARDED AREA,
// {SINGLE {GRAPHIC,} CHARACTER,CONTROL SEQUENCE} INTRODUCER, OPERATING SYSTEM COMMAND,
// PRIVACY MESSAGE, APPLICATION PROGRAM COMMAND, ZERO WIDTH {,NO-BREAK} SPACE,
// REPLACEMENT CHARACTER
'/[\0\x{05}-\x{07}\x{0E}-\x{16}\x{1B}\x{7F}\x{80}\x{81}\x{83}\x{84}\x{86}-\x{93}\x{95}-\x{97}\x{99}-\x{9B}' .
'\x{9D}-\x{9F}\x{200B}\x{FEFF}\x{FFFD}]++/u',
// Remove trailing whitespace at the end of lines in a multiline string.
'/[ \t]+(?=\n)/',
// phpcs:enable
);
$replace = array(
'',
"\n",
'',
'',
);
$clean = preg_replace($search, $replace, $clean);
if (($format === 2) && ($from === 2)) {
// Clean up translations of 2.x strings.
$clean = preg_replace("/\n{3,}/", "\n\n\n", $clean);
} else if (($format === 2) && ($from === 1)) {
// Convert 1.x string into 2.x format.
$clean = preg_replace("/\n{3,}/", "\n\n\n", $clean);
$clean = preg_replace('/%+/', '%', $clean);
$clean = str_replace('\$', '@@@___XXX_ESCAPED_DOLLAR__@@@', $clean);
$clean = str_replace("\\", '', $clean);
$clean = preg_replace('/(^|[^{])\$a\b(\->[a-zA-Z0-9_]+)?/', '\\1{$a\\2}', $clean);
$clean = str_replace('@@@___XXX_ESCAPED_DOLLAR__@@@', '$', $clean);
$clean = str_replace('$', '$', $clean);
} else if (($format === 1) && ($from === 1)) {
// Clean up legacy 1.x strings.
$clean = preg_replace("/\n{3,}/", "\n\n", $clean);
$clean = str_replace('\$', '@@@___XXX_ESCAPED_DOLLAR__@@@', $clean);
$clean = str_replace("\\", '', $clean);
$clean = str_replace('$', '\$', $clean);
$clean = preg_replace('/\\\\\$a\b(\->[a-zA-Z0-9_]+)?/', '$a\\1', $clean);
$clean = str_replace('@@@___XXX_ESCAPED_DOLLAR__@@@', '\$', $clean);
$clean = str_replace('"', "\\\"", $clean);
$clean = preg_replace('/%+/', '%', $clean);
$clean = str_replace('%', '%%', $clean);
} else {
throw new mlang_exception('Unknown get_string() format version');
}
return $clean;
}
/**
* Making minimal sanitize of string, no trims or double lines deletion
*
* @param string $text string text to be fixed
* @return string
*/
public static function fix_syntax_minimal($text) {
$search = array(
// phpcs:disable moodle.Commenting.InlineComment
// Remove \r if it is part of \r\n.
'/\r(?=\n)/',
// Control characters to be replaced with \n.
// LINE TABULATION, FORM FEED, CARRIAGE RETURN, END OF TRANSMISSION BLOCK,
// END OF MEDIUM, SUBSTITUTE, BREAK PERMITTED HERE, NEXT LINE, START OF STRING,
// STRING TERMINATOR and Unicode character categorys Zl and Zp
'/[\x{0B}-\r\x{17}\x{19}\x{1A}\x{82}\x{85}\x{98}\x{9C}\p{Zl}\p{Zp}]/u',
// Control characters to be removed.
// NULL, ENQUIRY, ACKNOWLEDGE, BELL, SHIFT {OUT,IN}, DATA LINK ESCAPE,
// DEVICE CONTROL {ONE,TWO,THREE,FOUR}, NEGATIVE ACKNOWLEDGE, SYNCHRONOUS IDLE, ESCAPE,
// DELETE, PADDING CHARACTER, HIGH OCTET PRESET, NO BREAK HERE, INDEX,
// {START,END} OF SELECTED AREA, CHARACTER TABULATION {SET,WITH JUSTIFICATION},
// LINE TABULATION SET, PARTIAL LINE {FORWARD,BACKWARD}, REVERSE LINE FEED,
// SINGLE SHIFT {TWO,THREE}, DEVICE CONTROL STRING, PRIVATE USE {ONE,TWO},
// SET TRANSMIT STATE, MESSAGE WAITING, {START,END} OF GUARDED AREA,
// {SINGLE {GRAPHIC,} CHARACTER,CONTROL SEQUENCE} INTRODUCER, OPERATING SYSTEM COMMAND,
// PRIVACY MESSAGE, APPLICATION PROGRAM COMMAND, ZERO WIDTH {,NO-BREAK} SPACE,
// REPLACEMENT CHARACTER
// phpcs:enable
'/[\0\x{05}-\x{07}\x{0E}-\x{16}\x{1B}\x{7F}\x{80}\x{81}\x{83}\x{84}\x{86}-\x{93}\x{95}-\x{97}\x{99}-\x{9B}' .
'\x{9D}-\x{9F}\x{200B}\x{FEFF}\x{FFFD}]++/u',
);
$replace = array(
'',
"\n",
'',
);
$clean = preg_replace($search, $replace, $text);
return $clean;
}
/**
* Should the string be counted when calculating the translation stats.
*
* @return bool
*/
public function should_be_included_in_stats() {
if ($this->deleted) {
return false;
}
return true;
}
}
/**
* Staging area is a collection of components to be committed into the strings repository
*
* After obtaining a new instance and adding some components into it, you should either call commit()
* or clear(). Otherwise, the copies of staged strings remain in PHP memory and they are not
* garbage collected because of the circular reference component-string.
*/
class mlang_stage implements IteratorAggregate, Countable {
/** @var array of mlang_component */
protected $components = array();
/**
* Adds a copy of the given component into the staging area
*
* @param mlang_component $component
* @param bool $force replace the previously staged string if there is such if there is already
* @return void
*/
public function add(mlang_component $component, $force=false) {
$cid = $component->get_identifier();
if (!isset($this->components[$cid])) {
$this->components[$cid] = new mlang_component($component->name, $component->lang, $component->version);
}
foreach ($component as $string) {
$this->components[$cid]->add_string(clone($string), $force);
}
}
/**
* Removes staged components
*/
public function clear() {
foreach ($this->components as $component) {
$component->clear();
}
$this->components = array();
}
/**
* Check the staged strings against the repository cap and keep modified strings only
*
* @param int|null $basetimestamp the timestamp to rebase against, null for the most recent
* @param bool $deletemissing if true, then all strings that are in repository but not in stage will be marked as to be deleted
* @param int $deletetimestamp if $deletemissing is true, what timestamp to use when removing strings (defaults to current)
*/
public function rebase($basetimestamp=null, $deletemissing=false, $deletetimestamp=null) {
if (!is_bool($deletemissing)) {
throw new coding_exception('Incorrect type of the parameter $deletemissing');
}
foreach ($this->components as $cx => $component) {
$cap = mlang_component::from_snapshot($component->name, $component->lang, $component->version, $basetimestamp, true);
if ($deletemissing) {
if (empty($deletetimestamp)) {
$deletetimestamp = time();
}
foreach ($cap as $existing) {
$stagedstring = $component->get_string($existing->id);
if (is_null($stagedstring)) {
$tobedeleted = clone($existing);
$tobedeleted->deleted = true;
$tobedeleted->timemodified = $deletetimestamp;
$component->add_string($tobedeleted);
}
}
}
foreach ($component as $stagedstring) {
$capstring = $cap->get_string($stagedstring->id);
if (is_null($capstring)) {
// The staged string does not exist in the repository yet - will be committed.
continue;
}
if ($stagedstring->deleted && empty($capstring->deleted)) {
// The staged string object is the removal record - will be committed.
continue;
}
if (empty($stagedstring->deleted) && $capstring->deleted) {
// Re-adding a deleted string - will be committed.
continue;
}
if (!mlang_string::differ($stagedstring, $capstring)) {
// The staged string is the same as the most recent one in the repository.
$component->unlink_string($stagedstring->id);
continue;
}
if ($stagedstring->timemodified < $capstring->timemodified) {
// The staged string is older than the cap, do not keep it.
$component->unlink_string($stagedstring->id);
continue;
}
}
// Unstage the whole component if it is empty.
if (!$component->has_string()) {
unset($this->components[$cx]);
}
$cap->clear();
}
}
/**
* Commit the strings in the staging area, by default rebasing first