Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathutils.class.php
More file actions
1269 lines (1165 loc) · 42.9 KB
/
Copy pathutils.class.php
File metadata and controls
1269 lines (1165 loc) · 42.9 KB
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 Stack - http://stack.maths.ed.ac.uk/
//
// Stack 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.
//
// Stack 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 Stack. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
/**
* Various utility classes for Stack.
*
* @package qtype_stack
* @copyright 2012 University of Birmingham
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses
*/
/**
* Interface for a class that stores debug information (or not).
*
* @package qtype_stack
* @copyright 2012 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface stack_debug_log {
/**
* Add description here.
* @return string the contents of the log.
*/
public function get_log();
/**
* Add to the log
* @param string $heading a heading to precede the acutal message.
* @param string $message the debug message.
*/
public function log($heading = '', $message = '');
}
/**
* Interface for a class that stores debug information (or not).
*
* @package qtype_stack
* @copyright 2012 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class stack_debug_log_base implements stack_debug_log {
// phpcs:ignore moodle.Commenting.VariableComment.Missing
protected $debuginfo = '';
/**
* Add description here.
* @return string the contents of the log.
*/
public function get_log() {
return $this->debuginfo;
}
/**
* Add to the log
* @param string $heading a heading to precede the acutal message.
* @param string $message the debug message.
*/
public function log($heading = '', $message = '') {
if ($heading) {
$this->debuginfo .= html_writer::tag('h3', $heading);
}
if ($message) {
$this->debuginfo .= html_writer::tag('pre', s($message));
}
}
}
/**
* A null stack_debug_log. Does not acutally log anything. Used when debugging is off.
*
* @package qtype_stack
* @copyright 2012 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class stack_debug_log_null implements stack_debug_log {
/**
* Add description here.
* @return string the contents of the log.
*/
public function get_log() {
return '';
}
/**
* Add to the log
* @param string $heading a heading to precede the acutal message.
* @param string $message the debug message.
*/
public function log($heading = '', $message = '') {
// Do nothing.
}
}
/**
* Utility methods for processing strings.
*
* @package qtype_stack
* @copyright 2012 University of Birmingham
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class stack_utils {
/** @var object the STACK config data, so we only ever have to load it from the DB once. */
protected static $config = null;
/** @var A list of mathematics environments we search for, from AMSmath package 2.0. */
protected static $mathdelimiters = ['equation', 'align', 'gather', 'flalign', 'multline', 'alignat', 'split'];
/**
* @var string fragment of regular expression that matches valid PRT and
* input names.
*/
const VALID_NAME_REGEX = '[a-zA-Z][a-zA-Z0-9_]*';
/**
* Static class. You cannot create instances.
*/
private function __construct() {
throw new stack_exception('stack_utils: you cannot create instances of this class.');
}
/**
* Create a debug log that either does, or does not, log anything.
* @param bool $debugenabled Whether we actually want to keep a debug log.
* @return stack_debug_log the log
*/
public static function make_debug_log($debugenabled = true) {
if ($debugenabled) {
return new stack_debug_log_base();
} else {
return new stack_debug_log_null();
}
}
/**
* Check whether the number of left and right substrings match, for example
* whether every 'left' has a matching 'right'.
* Returns true if equal, 'left' left is missing, 'right' if right is missing.
*
* @param string $string the string to test.
* @param string $left the left delimiter.
* @param string $right the right delimiter.
* @return bool|string true if they match; 'left' if there are left delimiters
* missing; or 'right' if there are right delimiters missing.
*/
public static function check_bookends($string, $left, $right) {
$leftcount = substr_count($string, $left);
$rightcount = substr_count($string, $right);
if ($leftcount == $rightcount) {
return true;
} else if ($leftcount > $rightcount) {
return 'right';
} else {
return 'left';
}
}
/**
* Check that the opening and closing brackets match, including nesting.
* This method only works with pairs of characters that are different, like ().
* It cannot cope with matching "", for example.
* @param string $string the string to test.
* @param string $lefts opening bracket characters. By default '([{'.
* @param string $rights the corresponding closing bracket characters. By default ')]}'.
* @return boolean true if all brackets match and are nested properly.
*/
public static function check_nested_bookends($string, $lefts = '([{', $rights = ')]}') {
$openstack = [];
$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
$char = $string[$i];
if (strpos($lefts, $char) !== false) {
array_push($openstack, $char);
} else if (($closerpos = strpos($rights, $char)) !== false) {
$opener = array_pop($openstack); // NULL if array is empty, which works.
if ($opener !== $lefts[$closerpos]) {
return false;
}
}
}
return empty($openstack);
}
/**
* Gets the first sub-string between two specified delimiters from within
* a larger string.
*
* @param string $string the string to analyse.
* @param string $left the left delimiter character.
* @param string $right the right delimiter character.
* @param int $start the position of the string to start searching at. (Default 0)
* @return array with three elements: (the extracted string including the delimiters,
* the start position of the substring, and the end position of the stubstring.
* If there is no match, ('', -1, -1) is returned. Well, acutally it is more
* complex than that. If you really care read the code.
*/
public static function substring_between($string, $left, $right, $start = 0) {
$start = strpos($string, $left, $start);
if ($start === false) {
return ['', -1, 0];
}
if ($left == $right) {
// Left and right are the same.
$end = strpos($string, $right, $start + 1); // Just go for the next one.
if ($end === false) {
return ['', $start, -1];
}
$end += 1;
} else {
$length = strlen($string);
$nesting = 1;
$end = $start + 1;
while ($nesting > 0 && $end < $length) {
if ($string[$end] == $left) {
$nesting += 1;
} else if ($string[$end] == $right) {
$nesting -= 1;
}
$end++;
}
if ($nesting > 0) {
return ['', -1, -1];
}
}
return [substr($string, $start, $end - $start), $start, $end - 1];
}
/**
* Gets the characters between two *characters*
* Works throughout a string returning an array of matches
*
* @param string $string the string to analyse.
* @param string $left the opening delimiter.
* @param string $right the closing delimiter. If omitted, uses $left.
* @param bool $skipempty whether to leave out any empty substrings.
* @return array of matches without $left or $right pre/suffixes
*/
public static function all_substring_between($string, $left, $right = null, $skipempty = false) {
if ($right == null) {
$right = $left;
}
$char = str_split($string);
$length = count($char);
$var = [];
$j = 0;
$i = 0;
$start = false;
$found = '';
while ($i < $length) {
if ($start == false) {
// Find starting @.
if ($char[$i] == $left) {
$start = true;
$found .= $char[$i];
}
} else {
// We have the first @ find ending @.
if ($char[$i] == $right) {
// End of cas command found.
$found .= $char[$i];
$found = str_replace($left, '', $found);
$found = str_replace($right, '', $found);
$found = trim($found);
if (!$skipempty || $found) {
$var[$j] = $found;
}
$j++;
$found = '';
$start = false;
} else {
$found .= $char[$i];
}
}
$i++;
}
return $var;
}
/**
* Replaces the text between $left and $right with the next string from the array.
* If the number of replacements does not match the number of strings to
* replaces, an exception is thrown.
*
* @param string $string the string to analyse.
* @param string $left the opening delimiter.
* @param string $right the closing delimiter. If omitted, uses $left.
* @param array $replacements array of replacement strings, must equal the
* @param bool $skipempty whether to leave out any empty substrings.
* number of replacements.
* @return string
*/
public static function replace_between($string, $left, $right, $replacements, $skipempty = false) {
// Do error checking.
$leftcount = substr_count($string, $left);
$rightcount = substr_count($string, $right);
$replacecount = count($replacements);
if ($left != $right && $leftcount != $rightcount) {
throw new stack_exception('replace_between: delimiters don\'t match.');
}
$result = '';
$matches = 0;
$char = str_split($string);
$length = count($char);
$i = 0;
$searching = true;
while ($i < $length) {
if ($searching) {
// Trying to find startchar.
if ($char[$i] == $left) {
$searching = false;
$empty = true;
}
$result .= $char[$i];
} else {
// Found startchar, looking for end.
if ($char[$i] == $right) {
// phpcs:disable
if ($skipempty && $empty) {
// Do nothing.
} else if (!isset($replacements[$matches])) {
throw new stack_exception('replace_between: not enough replacements.');
} else {
$result .= $replacements[$matches];
$matches++;
}
// phpcs:enable
$searching = true;
$result .= $char[$i];
}
$empty = false;
}
$i++;
}
if ($matches != count($replacements)) {
throw new stack_exception('replace_between: too many replacements.');
}
return $result;
}
/**
* Removes spaces, hyphens, and optionally other character from a string,
* replacing them with an underscore characters.
*
* @param string the string to process.
* @param array (Optional) additional characters to convert to underscores.
* @return string with characters replaced.
*/
public static function underscore($string, $toreplace = []) {
$toreplace[] = '-';
$toreplace[] = ' ';
return str_replace($toreplace, '_', $string);
}
/**
* Converts windows style paths to unix style with forward slashes
*
* @return string|null
*/
public static function convert_slash_paths($string) {
$in = trim($string);
$length = strlen($in);
$lastchar = $in[($length - 1)];
$trailingslash = false;
if ($lastchar == '\\') {
$trailingslash = true;
}
$patharray = self::cvs_to_array($string, "\\");
if (!empty($patharray)) {
$newpath = $patharray[0];
for ($i = 1; $i < count($patharray); $i++) {
$newpath .= "/" . $patharray[$i];
}
if ($trailingslash == true) {
return $newpath . '/';
} else {
return $newpath;
}
} else {
return null;
}
}
/**
* Extracts double quoted strings with \-escapes, extracts only the content
* not the quotes.
*
* @return array
*/
public static function all_substring_strings($string) {
$strings = [];
$i = 0;
$lastslash = false;
$instring = false;
$stringentry = -1;
while ($i < strlen($string)) {
$c = $string[$i];
$i++;
if ($instring) {
if ($c == '"' && !$lastslash) {
$instring = false;
// Last -1 to drop the quote.
$s = substr($string, $stringentry, ($i - $stringentry) - 1);
$strings[] = $s;
} else if ($c == "\\") {
$lastslash = !$lastslash;
} else if ($lastslash) {
$lastslash = false;
}
} else if ($c == '"') {
$instring = true;
$lastslash = false;
$stringentry = $i;
}
}
return $strings;
}
/**
* Replaces all Maxima strings with zero length strings to eliminate string
* contents for validation tasks.
*
* @return string
*/
public static function eliminate_strings($string) {
$cleared = '';
$i = 0;
$lastslash = false;
$instring = false;
$laststringexit = 0;
while ($i < strlen($string)) {
$c = $string[$i];
$i++;
if ($instring) {
if ($c == '"' && !$lastslash) {
$instring = false;
$laststringexit = $i - 1;
} else if ($c == "\\") {
$lastslash = !$lastslash;
} else if ($lastslash) {
$lastslash = false;
}
} else if ($c == '"') {
$instring = true;
$lastslash = false;
$cleared .= substr($string, $laststringexit, $i - $laststringexit);
}
}
$cleared .= substr($string, $laststringexit);
return $cleared;
}
/**
* Convert strings to protect LaTeX backslashes for use in Maxima strings.
* @param string in
* @return string out
*/
public static function protect_backslash_latex($string) {
$string = addslashes($string);
// We don't want to add slashes to strings within strings.
$string = str_replace('\\\\\"', '\"', $string);
return($string);
}
/**
* Converts a CSV string into an array, removing empty entries.
*
* @param string in
* @return array out
*/
public static function cvs_to_array($string, $token = ',') {
$exploded = explode($token, $string);
// Remove any null entries.
for ($i = 0; $i < count($exploded); $i++) {
$trim = trim($exploded[$i]);
if (!empty($trim)) {
$toreturn[] = $exploded[$i];
}
}
return $toreturn;
}
/**
* Converts an array to a CSV.
*
* @param $array the data to output.
* @return string the output.
*/
public static function array_to_cvs($array) {
if (!empty($array)) {
$string = '';
$i = 0;
foreach ($array as $element) {
if ($i > 0) {
$string .= ', ';
}
if (is_bool($element)) {
if ($element) {
$string .= 'TRUE';
} else {
$string .= 'FALSE';
}
} else {
$string .= $element;
}
$i++;
}
return $string;
} else {
return '';
}
}
/**
* Handles complex (comma-containing) list elements,
* i.e. sets {}, functions() and nested lists[[]]
* Strict checking on nesting.
* Helper for list_to_array_workhorse()
*/
private static function next_element($list, $delim) {
if ($list == '') {
return null;
}
// Do we have a string, which might contain commas, protected quotes and random brackets?
if (substr(trim($list), 0, 1) === '"') {
$startchar = strpos($list, '"'); // Start of the string.
$foundend = false;
for ($i = $startchar + 1; $i < strlen($list); $i++) {
if ($list[$i] == '"' && $list[$i - 1] != '\\') {
$foundend = true;
}
if ($foundend && $list[$i] == $delim) {
return substr($list, 0, $i);
}
}
// We started a string, but never ended with a comma.
return $list;
}
// Delimited by next comma at same degree of nesting.
$startdelimiter = "[({";
$enddelimiter = "])}";
$nesting = [0 => 0, 1 => 0, 2 => 0]; // Stores nesting for delimiters above.
for ($i = 0; $i < strlen($list); $i++) {
$startchar = strpos($startdelimiter, $list[$i]); // Which start delimiter.
$endchar = strpos($enddelimiter, $list[$i]); // Which end delimiter (if any).
// Change nesting for delimiter if specified.
if ($startchar !== false) {
$nesting[$startchar]++;
} else if ($endchar !== false) {
$nesting[$endchar]--;
} else if ($list[$i] == $delim && $nesting[0] == 0 && $nesting[1] == 0 && $nesting[2] == 0) {
// Otherwise, return element if all nestings are zero.
return substr($list, 0, $i);
}
}
// End of list reached.
if ($nesting[0] == 0 && $nesting[1] == 0 && $nesting[2] == 0) {
return $list;
} else {
return null;
}
}
// phpcs:ignore moodle.Commenting.MissingDocblock.Function
private static function list_to_array_workhorse($list, $rec = true, $delim = ',') {
$array = [];
$list = trim($list);
$list = substr($list, 1, strlen($list) - 2); // Trims outermost [] only.
$e = self::next_element($list, $delim);
while ($e !== null) {
if ($e[0] == '[') {
if ($rec) {
$array[] = self::list_to_array_workhorse($e, $rec, $delim);
} else {
$array[] = $e;
}
} else {
$array[] = $e;
}
$list = substr($list, strlen($e) + 1);
$e = self::next_element($list, $delim);
}
return $array;
}
/**
* Converts a list structure into an array.
* Handles nested lists, sets and functions with help from next_element().
*/
public static function list_to_array($string, $rec = true, $delim = ',') {
return self::list_to_array_workhorse($string, $rec, $delim);
}
/**
* Extract the names of all the placeholders like [[{$type}:{$name}]] from
* a bit of text. Names must start with an ASCII letter, and be comprised of
* ASCII letters, numbers and underscores.
*
* @param string $text some text. E.g. '[[input:ans1]]'.
* @param string $type the type of placeholder to extract. e.g. 'input'.
* @return array of placeholdernames.
*/
public static function extract_placeholders($text, $type) {
if (!$text) {
return [];
}
preg_match_all(
'~\[\[' . $type . ':(' . self::VALID_NAME_REGEX . ')\]\]~',
$text,
$matches
);
return $matches[1];
}
/**
* Extract what look like "sloppy" placeholders like [[{$type}:{$name}]] from
* a bit of text. We forbit bits of whitespace between the various bits.
* Modelled on public static function extract_placeholders($text, $type)
*
* @param string $text some text. E.g. '[[input:ans1]]'.
* @param string $type the type of placeholder to extract. e.g. 'input'.
* @return array of placeholdernames.
*/
public static function extract_placeholders_sloppy($text, $type) {
preg_match_all(
'~\[\[' . $type . ':(' . self::VALID_NAME_REGEX . ')\]\]~',
$text,
$matches1
);
preg_match_all(
'~\[\[\s*' . $type . '\s*:(\s*' . self::VALID_NAME_REGEX . ')\s*\]\]~',
$text,
$matches2
);
$ret = [];
foreach ($matches2[1] as $key => $name) {
if (!in_array(trim($name), $matches1[1])) {
$ret[] = $matches2[0][$key];
}
}
return($ret);
}
/**
* Add description here
* @param string $name a potential name for part of a STACK question.
* @return bool whether that name is allowed.
*/
public static function is_valid_name($name) {
return preg_match('~^' . self::VALID_NAME_REGEX . '$~', $name);
}
/**
* Get the stack configuration settings.
*/
public static function get_config() {
if (is_null(self::$config)) {
self::$config = get_config('qtype_stack');
}
return self::$config;
}
// phpcs:ignore moodle.Commenting.MissingDocblock.Function
public static function clear_config_cache() {
self::$config = null;
}
/**
* This breaks down a complex rename of the names of a set of things, so that
* the renames may safely be performed one-at-a-time. This is easier to understand
* with an example:
*
* Suppose the input is array(1 => 2, 2 => 1). Then the output will be
* array (1 => temp1, 2 => 1, temp1 => 2).
*
* This function can solve this problem in the general case.
*
* @param array $renamemap a mapping from oldname => newname for a set of things.
* @return array $saferenames a sequence of single rename operations,
* oldname => newname that when performed in order, will not cause a
* name clash.
*/
public static function decompose_rename_operation(array $renamemap) {
$nontrivialmap = [];
$usednames = [];
foreach ($renamemap as $from => $to) {
$usednames[(string) $from] = 1;
$usednames[(string) $to] = 1;
if ((string) $from !== (string) $to) {
$nontrivialmap[(string) $from] = (string) $to;
}
}
if (empty($nontrivialmap)) {
return [];
}
// First we deal with all renames that are not part of cycles.
// This bit is O(n^2) and it ought to be possible to do better,
// but it does not seem worth the effort.
$saferenames = [];
$todocount = count($nontrivialmap) + 1;
while (count($nontrivialmap) < $todocount) {
$todocount = count($nontrivialmap);
foreach ($nontrivialmap as $from => $to) {
if (array_key_exists($to, $nontrivialmap)) {
continue; // Cannot currenly do this rename.
}
// Is safe to do this rename now.
$saferenames[$from] = $to;
unset($nontrivialmap[$from]);
}
}
// Are we done?
if (empty($nontrivialmap)) {
return $saferenames;
}
// Now, what is left in $nontrivialmap will permutation, which must be a
// combination of distinct cycles. We need to break them.
$tempname = self::get_next_unused_name($usednames);
while (!empty($nontrivialmap)) {
// Extract the first cycle.
reset($nontrivialmap);
$current = $cyclestart = (string) key($nontrivialmap);
$cycle = [];
do {
$cycle[] = $current;
$next = $nontrivialmap[$current];
unset($nontrivialmap[$current]);
$current = $next;
} while ($current !== $cyclestart);
// Now convert it to a sequence of safe renames by using a temp.
$saferenames[$cyclestart] = $tempname;
$cycle[0] = $tempname;
$to = $cyclestart;
while ($from = array_pop($cycle)) {
$saferenames[$from] = $to;
$to = $from;
}
$tempname = self::get_next_unused_name($usednames, ++$tempname);
}
return $saferenames;
}
/**
* Get an name that is not used as a key in $usednames.
* @param array $usednames where the keys are the used names.
* @param string $suggestedname the form the name should take. Default 'temp1'.
* @return string an unused name.
*/
protected static function get_next_unused_name($usednames, $suggestedname = 'temp1') {
while (array_key_exists($suggestedname, $usednames)) {
$suggestedname++;
}
return $suggestedname;
}
/**
* Locale-aware version of PHP's asort function.
* @param array $array The array to sort. Sorted in place.
*/
public static function sort_array(&$array) {
if (class_exists('core_collator')) {
core_collator::asort($array);
} else {
collatorlib::asort($array);
}
}
/**
* Locale-aware version of PHP's ksort function.
* @param array $array The array to sort. Sorted in place.
*/
public static function sort_array_by_key(&$array) {
if (class_exists('core_collator')) {
core_collator::ksort($array);
} else {
collatorlib::ksort($array);
}
}
/**
* Converts a PHP string object to a PHP string object containing the Maxima code that would generate a similar
* string in Maxima.
* @param a string
* @return a string that contains ""-quotes around the content.
*/
public static function php_string_to_maxima_string($string) {
$converted = str_replace("\\", "\\\\", $string);
$converted = str_replace("\"", "\\\"", $converted);
return '"' . $converted . '"';
}
/**
* Converts a PHP string object containing a Maxima string as presented by the grind command to a PHP string object.
* @param a string that contains ""-quotes around the content.
* @return a string without those quotes.
*/
public static function maxima_string_to_php_string($string) {
$converted = str_replace("\\\\", "\\", $string);
$converted = str_replace("\\\"", '"', $converted);
return substr($converted, 1, -1);
}
/**
* Remove redundant "mbox" environments from Latex equations strings containing just strings.
* @param a string that contains ""-quotes around the content.
* @return a string without those quotes.
*/
public static function maxima_string_strip_mbox($string) {
$converted = trim($string);
if (substr($converted, 0, 2) == '\(' || substr($converted, 0, 2) == '\[') {
$converted = substr($converted, 2, -2);
}
if (substr(trim($converted), 0, 6) == '\text{') {
return substr(trim($converted), 6, -1);
}
return $string;
}
/**
* Translate some strings from Maxima.
* @param string $string
*/
public static function maxima_translate_string(string $string) {
$fixed = $string;
if (strpos($string, '0 to a negative exponent') !== false) {
$fixed = stack_string('Maxima_DivisionZero');
} else if (strpos($string, 'args: argument must be a non-atomic expression;') !== false) {
$fixed = stack_string('Maxima_Args');
}
return $fixed;
}
/**
* Find a rational approximation to $n
* @param float $n
* @param int $accuracy Stop when we get within this many decimal places of $n
*/
public static function rational_approximation(float $n, int $accuracy) {
$accuracy = pow(10, -$accuracy);
// Handle sign.
$sign = ($n < 0) ? -1 : 1;
$n = abs($n);
// Handle integers directly.
if (floor($n) == $n) {
return [$sign * $n, 1];
}
// Continued fraction expansion with convergents.
$p0 = 1;
$q0 = 0;
$p1 = floor($n);
$q1 = 1;
$x1 = $n;
$steps = 0;
// The algorithm converges quickly, so no need for more than 100 here.
while ($steps < 100) {
$steps++;
// Current approximation.
$approx = $p1 / $q1;
if (abs($approx - $n) <= $accuracy) {
break;
}
// Prevent division by zero.
$frac = $x1 - floor($x1);
if ($frac == 0.0) {
break;
}
// Next term in continued fraction.
$x1 = 1.0 / $frac;
$a = floor($x1);
// Recurrence.
$p2 = $a * $p1 + $p0;
$q2 = $a * $q1 + $q0;
// Shift.
$p0 = $p1;
$q0 = $q1;
$p1 = $p2;
$q1 = $q2;
}
return [$sign * $p1, $q1];
}
// phpcs:ignore moodle.Commenting.MissingDocblock.Function
public static function fix_to_continued_fraction($n, $accuracy) {
$frac = self::rational_approximation($n, $accuracy);
return $frac[0] / $frac[1];
}
/**
* Change fraction marks close to 1/3 or 2/3 to the values exact to 7 decimal places.
*
* Moodle rounds fractional marks close to 1/3 (0.33 <= x <= 0.34) or 2/3
* (0.66 <= x <= 0.67) to exactly 0.3333333 and 0.6666667, for example when @author tjh238
* course is backed up and restored. Some of the fractional marks that STACK
* uses are affected by this, and others are not. Therefore, after a course
* is backed up and restored, some question tests start failing.
*
* Therefore, this function is used to match Moodle's logic.
*
* @param float $fraction a fractional mark between 0 and 1.
* @return float $fraction, except that values close to 1/3 or 2/3 are returned to 7 decimal places.
*/
public static function fix_approximate_thirds($fraction) {
if (!is_numeric($fraction)) {
return $fraction;
}
$fraction = (float) $fraction;
if ($fraction >= 0.33 && $fraction <= 0.34) {
return 0.3333333;
} else if ($fraction >= 0.66 && $fraction <= 0.67) {
return 0.6666667;
} else {
return $fraction;
}
}
/**
* Remove trailing zeros from numbers.
*
* @param string $str Some kind of score/penalty string..
* @return float $str, Fixed if we have lots of trailing zeros.
*/
public static function fix_trailing_zeros($str) {
if (!is_numeric($str)) {
return $str;
}
return 0 + $str;
}
/**
* This function takes user input of the form "option:arg" and splits them up.
* Used to sort out options to the inputs field.
*/
public static function parse_option($option) {
$arg = '';
if (!(strpos($option, ':') === false)) {
$ops = explode(':', $option);
$option = $ops[0];
$arg = trim($ops[1]);
}
return([$option, $arg]);
}
/**
* This function takes html and counts the number of img fields
* with missing or empty alt text.
*/
public static function count_missing_alttext($text) {
$missingalt = 0;
// Yes, regular expressions can't parse html, but this should be good-enough to help users for now.
$matchentireimagetags = '
/
<img\b # Start of an image tag.
You can’t perform that action at this time.
