-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfilter.php
1011 lines (858 loc) · 33.9 KB
/
filter.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 JSXGraph Moodle Filter.
//
// 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 <http://www.gnu.org/licenses/>.
/**
* This is a plugin to enable function plotting and dynamic geometry constructions with JSXGraph within a Moodle platform.
*
* JSXGraph is a cross-browser JavaScript library for interactive geometry,
* function plotting, charting, and data visualization in the web browser.
* JSXGraph is implemented in pure JavaScript and does not rely on any other
* library. Special care has been taken to optimize the performance.
*
* @package filter_jsxgraph
* @copyright 2023 JSXGraph team - Center for Mobile Learning with Digital Technology – Universität Bayreuth
* Matthias Ehmann,
* Michael Gerhaeuser,
* Carsten Miller,
* Andreas Walter <[email protected]>,
* Alfred Wassermann <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
global $PAGE, $CFG;
require_once($CFG->libdir . '/pagelib.php');
/**
* Class filter_jsxgraph
*
* @package filter_jsxgraph
* @copyright 2023 JSXGraph team - Center for Mobile Learning with Digital Technology – Universität Bayreuth
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class filter_jsxgraph extends moodle_text_filter {
/**
* Path to jsxgraphcores
*
* @var String
*/
public const PATH_FOR_CORES = '/filter/jsxgraph/amd/src/';
/**
* Path to library folders
*
* @var String
*/
public const PATH_FOR_LIBS = '/filter/jsxgraph/libs/';
/**
* Const for tag name (<jsxgraph></jsxgraph>).
*
* @var String
*/
private const TAG = "jsxgraph";
/**
* Name for JavaScript constant for board ids.
* This is supplemented by a counter (BOARDID0, BOARDID1, ...).
*
* @var String
*/
private const BOARDID_CONST = "BOARDID";
/**
* Name for JavaScript constant array of board ids.
*
* @var String
*/
private const BOARDIDS_CONST = "BOARDIDS";
/**
* HTML encoding.
*
* @var String
*/
private const ENCODING = "UTF-8";
/**
* Allowed dimension attributes.
*
* @var String
*/
private const ALLOWED_DIMS = ["aspect-ratio", "width", "height", "max-width", "max-height"];
/**
* Attribute for aspect ratio.
*
* @var String
*/
private const AR = "aspect-ratio";
/**
* Allowed dimension attributes without aspect ratio.
*
* @var String
*/
private const ALLOWED_DIMS_EXCEPT_AR = ["width", "height", "max-width", "max-height"];
/**
* Attributes for width.
*
* @var String
*/
private const WIDTHS = ["width", "max-width"];
/**
* Parsed DOM node.
*
* @var domDocument
*/
private $document = null;
/**
* List of <jsxgraph> tags.
*
* @var domNode[]
*/
private $taglist = null;
/**
* Global admin settings.
*
* @var object
*/
private $settings = null;
/**
* List of used unique board ids. Length >= length of $taglist.
*
* @var string[]
*/
private $ids = [];
/**
* Used version of JSXGraph.
*
* @var null|object
*/
private $versionjsx = null;
/**
* Used version of Moodle.
*
* @var null|object
*/
private $versionmoodle = null;
/**
* Main filter function.
*
* @param String $text Moodle standard.
* @param Array $options Moodle standard.
*
* @return String
*/
public function filter($text, $options = []) {
// To optimize speed, search for a <jsxgraph> tag (avoiding to parse everything on every text).
if (!is_int(strpos($text, '<' . static::TAG))) {
return $text;
}
// 0. STEP: Do some initial stuff.
$this->settings = $this->get_adminsettings();
$this->set_versions();
if (!isset($this->versionjsx) || !isset($this->versionmoodle)) {
return $text;
}
// 1. STEP: Convert HTML string to a dom object.
// Create a new dom object.
$this->document = new domDocument('1.0', static::ENCODING);
$this->document->formatOutput = true;
// Load the html into the object.
libxml_use_internal_errors(true);
if ($this->settings["convertencoding"]) {
$this->document->loadHTML(mb_convert_encoding($text, 'HTML-ENTITIES', static::ENCODING));
} else {
$this->document->loadHTML($text);
}
libxml_use_internal_errors(false);
// Discard white space.
$this->document->preserveWhiteSpace = false;
$this->document->strictErrorChecking = false;
$this->document->recover = true;
// 2. STEP: Get tag elements.
$this->taglist = $this->document->getElementsByTagname(static::TAG);
// 3.+4. STEP: Load library (if needed) and iterate backwards through the <jsxgraph> tags.
if (!empty($this->taglist)) {
$this->load_jsxgraph();
for ($i = $this->taglist->length - 1; $i > -1; $i--) {
$node = $this->taglist->item($i);
$this->ids = [];
$new = $this->get_replaced_node($node, $i);
// Replace <jsxgraph>-node.
$node->parentNode->replaceChild($this->document->appendChild($new), $node);
$this->apply_js($node);
}
}
// 5. STEP: Paste new div node in web page.
// Remove DOCTYPE.
$this->document->removeChild($this->document->firstChild);
// Remove <html><body></body></html>.
$str = $this->document->saveHTML();
$str = str_replace("<body>", "", $str);
$str = str_replace("</body>", "", $str);
$str = str_replace("<html>", "", $str);
$str = str_replace("</html>", "", $str);
// Cleanup.
$this->taglist = null;
$this->document = null;
$this->settings = null;
return $str;
}
/**
* Create a new div node for a given JSXGraph node.
*
* @param domNode $node JSXGraph node.
* @param Integer $index Index in taglist.
*
* @return domNode
*/
private function get_replaced_node($node, $index) {
$attributes = $this->get_tagattributes($node);
// Create div node.
$new = $this->document->createElement('div');
$a = $this->document->createAttribute('class');
$a->value = 'jsxgraph-boards';
$new->appendChild($a);
for ($i = 0; $i < $attributes['numberOfBoards']; $i++) {
// Create div id.
$divid = $this->string_or($attributes['boardid'][$i], $attributes['box'][$i]);
if ($this->settings['usedivid']) {
$divid = $this->string_or($divid, $this->settings['divid'] . $index);
} else {
$divid = $this->string_or($divid, 'JSXGraph_' . strtoupper(uniqid()));
}
$this->ids[$i] = $divid;
// Create new div element containing JSXGraph.
$dimensions = [
"width" => $this->string_or($attributes['width'][$i], $this->settings['fixwidth']),
"height" => $this->string_or($attributes['height'][$i], $this->settings['fixheight']),
"aspect-ratio" => $this->string_or($attributes['aspect-ratio'][$i], $this->settings['aspectratio']),
"max-width" => $this->string_or($attributes['max-width'][$i], $this->settings['maxwidth']),
"max-height" => $this->string_or($attributes['max-height'][$i], $this->settings['maxheight']),
];
$div = $this->get_board_html(
$divid,
$dimensions,
$attributes['class'][$i],
$attributes['wrapper-class'][$i],
$attributes['force-wrapper'][$i],
$this->settings['fallbackaspectratio'],
$this->settings['fallbackwidth']
);
$divdom = new DOMDocument;
libxml_use_internal_errors(true);
$divdom->loadHTML($div);
libxml_use_internal_errors(false);
$new->appendChild($this->document->importNode($divdom->documentElement, true));
// Load formulas extension.
if ($this->settings['formulasextension'] || $attributes['ext_formulas'][$i]) {
$this->load_library('formulas');
}
}
return $new;
}
/**
* Combine global code and code contained in $node. Define some JavaScript constants. Apply this code to the dom.
*
* @param domNode $node JSXGraph node.
*
* @return void
*/
private function apply_js($node) {
global $PAGE;
$attributes = $this->get_tagattributes($node);
$code = "";
// Load global JavaScript code from administrator settings.
if ($this->settings['globalJS'] !== '' && $attributes['useGlobalJS'][0]) {
$code .=
"// Global JavaScript code from administrator settings.\n" .
"//////////////////////////////////////////////////////\n\n" .
$this->settings['globalJS'] .
"\n\n";
}
// Define BOARDID constants and some attributes for accessibility.
$code .=
"// Define BOARDID constants.\n" .
"////////////////////////////\n\n";
for ($i = 0; $i < count($this->ids); $i++) {
$name = static::BOARDID_CONST . $i;
$code .=
"const $name = '" . $this->ids[$i] . "';\n" .
"console.log('$name = `'+$name+'` has been prepared.');\n";
}
$code .=
"const " . static::BOARDID_CONST . " = " . static::BOARDID_CONST . "0" . ";\n" .
"const " . static::BOARDIDS_CONST . " = ['" . implode("', '", $this->ids) . "'];\n" .
"\n";
$code .=
"// Accessibility.\n" .
"/////////////////\n\n";
$code .=
"if(JXG.exists(JXG.Options.board)) {\n" .
"JXG.Options.board.title = '" . $attributes['title'][0] . "';\n" .
"JXG.Options.board.description = '" . $attributes['description'][0] . "';\n" .
"}\n";
// Load the code from <jsxgraph>-node.
$usercode = $this->document->saveHTML($node);
// Remove <jsxgraph> tags.
$usercode = preg_replace("(</?" . static::TAG . "[^>]*\>)i", "", $usercode);
// In order not to terminate the JavaScript part prematurely, the backslash has to be escaped.
$usercode = str_replace("</script>", "<\/script>", $usercode);
$code .=
"// Code from user input.\n" .
"////////////////////////\n";
$code .= $usercode;
// Surround the code with version-specific strings, e.g. "require".
$surroundings = $this->get_code_surroundings();
$code = $surroundings["pre"] . "\n\n" . $code . $surroundings["post"];
// Convert the HTML-entities in the variable $code.
if ($this->settings['html_entities'] && $attributes['entities']) {
$code = html_entity_decode($code);
}
// Paste the code.
// POI: Version differences. Here no differences.
$PAGE->requires->js_init_call($code);
}
/**
* Helper Function for apply_js(...). Returns the pre and post part of JavaScript code.
*
* @return String[]
*/
private function get_code_surroundings() {
$result = [
'pre' => '',
'post' => '',
];
$condition = '';
for ($i = 0; $i < count($this->ids); $i++) {
$condition .= "document.getElementById('" . $this->ids[$i] . "') != null && ";
}
$condition = substr($condition, 0, -4);
// Build from the inside out.
// POI: Version differences.
if ($this->versionmoodle["is_newer_version"]) {
if ($this->versionjsx["version_number"] >= $this->jxg_to_version_number("1.5.0")) {
$result["pre"] =
"require(['" . $this->get_core_url() . "'], function (JXG) {\n" .
"if ($condition) {\n" .
$result["pre"];
$result["post"] =
$result["post"] .
"}\n " .
"});\n";
} else {
$result["pre"] =
"if ($condition) {\n" .
$result["pre"];
$result["post"] =
$result["post"] .
"}\n ";
}
} else {
if ($this->versionjsx["version_number"] >= $this->jxg_to_version_number("1.5.0")) {
$result["pre"] =
"require(['" . $this->get_core_url() . "'], function (JXG) {\n" .
"if ($condition) {\n" .
$result["pre"];
$result["post"] =
$result["post"] .
"}\n " .
"});\n";
} else if ($this->versionjsx["version_number"] > $this->jxg_to_version_number("0.99.6")) {
$result["pre"] =
"require(['jsxgraphcore'], function (JXG) {\n" .
"if ($condition) { \n" .
$result["pre"];
$result["post"] =
$result["post"] .
"}\n " .
"});\n";
} else {
$result["pre"] =
"if ($condition) {\n" .
$result["pre"];
$result["post"] =
$result["post"] .
"}\n ";
}
}
$result["pre"] =
"\n//< ![CDATA[\n" .
$result["pre"];
$result["post"] =
$result["post"] .
"\n//]]>\n";
$result["pre"] =
"\n\n// ###################################################" .
"\n// JavaScript code for JSXGraph board '" . $this->ids[0] . "' and other\n" .
$result["pre"];
$result["post"] =
$result["post"] .
"\n// End code for JSXGraph board '" . $this->ids[0] . "' and other " .
"\n// ###################################################\n\n";
return $result;
}
/**
* Returns the path to the core file.
*
* @return moodle_url
*/
private function get_core_url() {
return new moodle_url(static::PATH_FOR_CORES . $this->versionjsx["file"]);
}
/**
* Load JSXGraph code from local or from server
*/
private function load_jsxgraph() {
global $PAGE;
// POI: Version differences.
if ($this->versionmoodle["is_newer_version"]) {
if ($this->versionjsx["version_number"] >= $this->jxg_to_version_number("1.5.0")) {
// Nothing to do!
return;
} else {
$t = $this->document->createElement('script', '');
$a = $this->document->createAttribute('type');
$a->value = 'text/javascript';
$t->appendChild($a);
$a = $this->document->createAttribute('src');
$a->value = $this->get_core_url();
$t->appendChild($a);
$this->document->appendChild($t);
}
} else {
if ($this->versionjsx["version_number"] >= $this->jxg_to_version_number("1.5.0")) {
// Nothing to do!
return;
} else {
$PAGE->requires->js($this->get_core_url());
}
}
}
/**
* Sets $this->versionjsx and $this->versionmoodle objects.
* Needs $this->settings to be set!
*
* @return void
*
* @see $versionjsx
* @see $versionmoodle
*/
private function set_versions() {
$this->versionjsx = null;
$this->versionmoodle = null;
// Resolve JSXGraph version.
if (!empty($this->settings)) {
$jsxversion = $this->settings['versionJSXGraph'];
$versions = json_decode(get_config('filter_jsxgraph', 'versions'), true);
if (empty($jsxversion) || $jsxversion === 'auto') {
$jsxversion = $versions[1]["id"];
}
foreach ($versions as $v) {
if ($v["id"] === $jsxversion) {
$this->versionjsx = $v;
break;
}
}
$this->versionjsx["version"] = $this->versionjsx["id"];
$this->versionjsx["version_number"] = $this->jxg_to_version_number($this->versionjsx["version"]);
}
// Resolve Moodle version.
$this->versionmoodle = [
"version" => get_config('moodle', 'version'),
"is_supported" => get_config('moodle', 'version') >= get_config('filter_jsxgraph', 'requires'),
"is_newer_version" => get_config('moodle', 'version') >= 2023042400,
];
if (!$this->versionmoodle["is_supported"]) {
$this->versionmoodle = null;
}
}
/**
* Build a <div> for board.
*
* This function creates the HTML for a board according to the given dimensions. It is possible, to define an aspect-ratio.
* If there are given width and height, aspect-ratio is ignored.
*
* There are the following use-cases:
* ===========================================================================================================================
* | nr | given | behavior |
* ===========================================================================================================================
* | 1 | width and height in any com- | The dimensions are applied to the boards <div>. Layout is like in the css |
* | | bination (min-/max-/...) | specification defined. See notes (a) and (b). Aspect-ratio is ignored in |
* | | | this case. Please note also (c). |
* ---------------------------------------------------------------------------------------------------------------------------
* | 2 | aspect-ratio and | The boards width ist fix according its value. The height is automatically |
* | | (min-/max-)width | regulated following the given aspect-ratio. |
* ---------------------------------------------------------------------------------------------------------------------------
* | 3 | aspect-ratio and | The boards height ist fix according its value. The width is automatically |
* | | (min-/max-)height | regulated following the given aspect-ratio. This case doesn't work on |
* | | | browsers which doesn't support aspect-ratio. The css trick (see (a)) can |
* | | | not help here. |
* ---------------------------------------------------------------------------------------------------------------------------
* | 4 | only aspect-ratio | The $defaultwidth is used. Apart from that see case 2. |
* ---------------------------------------------------------------------------------------------------------------------------
* | 5 | nothing | Aspect-ratio is set to $defaultaspectratio and then see case 4. |
* ===========================================================================================================================
*
* Notes:
* (a) Pay attention: the <div> uses the css attribute "aspect-ratio" which is not supported by every browser. If the browser
* does not support this, a trick with a wrapping <div> and padding-bottom is applied. This trick only works, if
* aspect-ratio and (min-/max-)width are given, not in combination with (min-/max-)height! For an overview of browsers
* which support aspect-ratio see {@link https://caniuse.com/mdn-css_properties_aspect-ratio.}
* (b) If the css trick is not needed, the result is only the <div> with id $id for the board. The value of $wrapperclasses
* is ignored.
* In the trick the div is wrapped by a <div> with id $id + '-wrapper'. This wrapper contains the main dimensions and the
* board-<div> gets only relative dimensions according to the case, e.g. width: 100%.
* You can force adding an wrapper by setting $forcewrapper to true.
* (c) If only width is given, the height will be 0 like in css. You have to define an aspect-ratio or height to display the
* board!
*
* @param String $id
* @param Object $dimensions with possible attributes
* aspect-ratio (the ratio of width / height)
* width (px, rem, vw, ...; if only a number is given, its interpreted as px)
* height (px, rem, vh, ...; if only a number is given, its interpreted as px)
* max-width (px, rem, vw, ...; if only a number is given, its interpreted as px)
* min-width (px, rem, vw, ...; if only a number is given, its interpreted as px)
* max-height (px, rem, vh, ...; if only a number is given, its interpreted as px)
* min-height (px, rem, vh, ...; if only a number is given, its interpreted as px)
* @param String $classes Additional css classes for the board.
* @param String $wrapperclasses Additional css classes for the boards container.
* (If it is needed. In the other case this is merged with $classes.)
* @param Boolean $forcewrapper Default: false.
* @param String $defaultaspectratio Default: "1 / 1".
* @param String $defaultwidth Default: "100%".
* @param Boolean $perventjsdimreg Default: false.
*
* @return String The <div> for the board.
*/
private function get_board_html(
$id, $dimensions = [], $classes = "", $wrapperclasses = "", $forcewrapper = false,
$defaultaspectratio = "1 / 1", $defaultwidth = "100%",
$perventjsdimreg = false
) {
if (!function_exists("empty_or_0_or_default")) {
/**
* Returns true if variable is empty, 0 or equal to $default.
*
* @param mixed $var Some variable
* @param null $default Default value
*
* @return bool
*/
function empty_or_0_or_default($var, $default = null) {
return empty($var) || $var === 0 || $var === '0' || $var === '0px' || $var === $default;
}
}
if (!function_exists("css_norm")) {
/**
* Returns a css value or $default,
*
* @param mixed $var Some variable
* @param String $default Default value
*
* @return String
*/
function css_norm($var, $default = '') {
if (substr('' . $var, 0, 1) === '0') {
$var = 0;
} else if (empty($var)) {
$var = $default;
} else if (is_numeric($var)) {
$var .= 'px';
}
return "" . $var;
}
}
// Tmp vars.
$styles = "";
$wrapperstyles = "";
$tmp = true;
foreach (static::ALLOWED_DIMS_EXCEPT_AR as $attr) {
$tmp = $tmp && empty_or_0_or_default($dimensions[$attr]);
}
if ($tmp && empty_or_0_or_default($dimensions[static::AR])) {
$dimensions[static::AR] = $defaultaspectratio;
$dimensions["width"] = $defaultwidth;
}
// At this point there is at least an aspect-ratio.
foreach (static::ALLOWED_DIMS as $attr) {
if (!empty_or_0_or_default($dimensions[$attr])) {
$styles .= "$attr: " . css_norm($dimensions[$attr]) . "; ";
}
}
$styles = substr($styles, 0, -1);
$classes = !empty($classes) ? ' ' . $classes : '';
$board = '<div id="' . $id . '" class="jxgbox' . $classes . '" style="' . $styles . '"></div>';
if (!$perventjsdimreg) {
foreach (static::WIDTHS as $attr) {
if (!empty_or_0_or_default($dimensions[$attr])) {
$wrapperstyles .= "$attr: " . css_norm($dimensions[$attr]) . "; ";
}
}
$js = "\n" .
'<script type="text/javascript">
(function() {
let addWrapper = function (boardid, classes = [], styles = "") {
let board = document.getElementById(boardid),
wrapper, wrapperid = boardid + "-wrapper";
wrapper = document.createElement("div");
wrapper.id = wrapperid;
wrapper.classList.add("jxgbox-wrapper");
for (let c of classes)
wrapper.classList.add(c);
wrapper.style = styles;
board.parentNode.insertBefore(wrapper, board.nextSibling);
wrapper.appendChild(board);
}
const FORCE_WRAPPER = false || ' . ($forcewrapper ? 'true' : 'false') . ';
let boardid = "' . $id . '",
wrapper_classes = "' . $wrapperclasses . '".split(" "),
wrapper_styles = "' . $wrapperstyles . '",
board = document.getElementById(boardid),
ar, ar_h, ar_w, padding_bottom;
if (!CSS.supports("aspect-ratio", "1 / 1") && board.style["aspect-ratio"] !== "") {
ar = board.style["aspect-ratio"].split("/", 3);
ar_w = ar[0].trim();
ar_h = ar[1].trim();
padding_bottom = ar_h / ar_w * 100;
if (wrapper_styles !== "")
addWrapper(boardid, wrapper_classes, wrapper_styles);
board.style = "height: 0; padding-bottom: " + padding_bottom + "%; /*" + board.style + "*/";
} else if (FORCE_WRAPPER) {
wrapper_styles = "";
if (board.style.width.indexOf("%") > -1) {
wrapper_styles += "width: " + board.style.width + "; "
board.style.width = "100%";
}
if (board.style.height.indexOf("%") > -1) {
wrapper_styles += "height: " + board.style.height + "; "
board.style.height = "100%";
}
addWrapper(boardid, wrapper_classes, wrapper_styles);
}
})();
</script>';
} else {
$js = "";
}
return $board . $js;
}
/**
* Load additional library
*
* @param String $libname
*
*/
private function load_library($libname) {
global $PAGE;
$libs = [
'formulas' => 'formulas_extension/JSXQuestion.js',
];
if (!array_key_exists($libname, $libs)) {
return;
}
$url = static::PATH_FOR_LIBS . $libs[$libname];
// POI: Version differences.
if ($this->versionmoodle["is_newer_version"]) {
$t = $this->document->createElement('script', '');
$a = $this->document->createAttribute('type');
$a->value = 'text/javascript';
$t->appendChild($a);
$a = $this->document->createAttribute('src');
$a->value = new moodle_url($url);
$t->appendChild($a);
$this->document->appendChild($t);
} else {
$PAGE->requires->js(new moodle_url($url));
}
}
/**
* Determine the attributes
*
* @param domNode $node
*
* @return String[]
*/
private function get_tagattributes($node) {
$numberofboardsattr = 'numberOfBoards';
$numberofboardsval = 1;
$attributes = [
'title' => '',
'description' => '',
'width' => '',
'height' => '',
'aspect-ratio' => '',
'max-width' => '',
'max-height' => '',
'class' => '',
'wrapper-class' => '',
'force-wrapper' => '',
'entities' => '',
'useGlobalJS' => '',
'ext_formulas' => '',
'box' => '',
'boardid' => '',
];
$boolattributes = [
'force-wrapper' => false,
'entities' => true,
'useGlobalJS' => true,
'ext_formulas' => null,
];
$possiblearrayattributes = [
'title',
'description',
'width',
'height',
'aspect-ratio',
'max-width',
'max-height',
'class',
'wrapper-class',
'box',
'boardid',
];
$numberofboardsval =
$node->getAttribute($numberofboardsattr) ? :
$node->getAttribute(strtolower($numberofboardsattr)) ? : $numberofboardsval;
foreach ($attributes as $attr => $value) {
$a = $node->getAttribute($attr) ? : $node->getAttribute(strtolower($attr));
if (isset($a) && !empty($a)) {
$a = explode(',', $a);
} else {
$a = [''];
}
$attributes[$attr] = [];
$arrattr = in_array($attr, $possiblearrayattributes);
for ($i = 0; $i < $numberofboardsval; $i++) {
if (!isset($a[$i]) || empty($a[$i]) || !$arrattr) {
$attributes[$attr][$i] = $a[0];
} else {
$attributes[$attr][$i] = $a[$i];
}
if (array_key_exists($attr, $boolattributes)) {
$attributes[$attr][$i] = $this->get_bool_value($node, $attr, $attributes[$attr][$i], $boolattributes[$attr]);
}
}
}
$attributes[$numberofboardsattr] = $numberofboardsval;
return $attributes;
}
/**
* Get settings made by administrator
*
* @return Array settings from administration
*/
private function get_adminsettings() {
// Set defaults.
$defaults = [
'versionJSXGraph' => 'auto',
'formulasextension' => true,
'html_entities' => true,
'convertencoding' => true,
'globalJS' => '',
'usedivid' => false,
'divid' => 'box',
'fixwidth' => '',
'fixheight' => '',
'aspectratio' => '',
'maxwidth' => '',
'maxheight' => '',
'fallbackaspectratio' => '1 / 1',
'fallbackwidth' => '100%',
];
$bools = [
'formulasextension',
'html_entities',
'convertencoding',
'usedivid',
];
$trims = [
'globalJS',
];
// Read and save settings.
foreach ($defaults as $a => &$default) {
$tmp = get_config('filter_jsxgraph', $a);
if (in_array($a, $bools)) {
$tmp = $this->convert_bool($tmp);
}
if (in_array($a, $trims)) {
$tmp = trim($tmp);
}
$default = $tmp;
}
return $defaults;
}
/**
* Converts a version string like 1.2.3 to an integer.
*
* @param String $versionstring
*
* @return Integer
*/
private function jxg_to_version_number($versionstring) {
$arr = explode('.', $versionstring);
return
intval($arr[0]) * 10000 +
intval($arr[1]) * 100 +
intval($arr[2]) * 1;
}
/**
* Gives the value of $attribute in $node as bool. If the attribute does not exist, $stdval is returned.
*
* @param domNode $node
* @param String $attribute
* @param String $givenval
* @param bool|String $stdval
*
* @return bool
*/
private function get_bool_value($node, $attribute, $givenval, $stdval) {
if ($node->hasAttribute($attribute)) {
if ($givenval == '') {
return true;
} else {
return $this->convert_bool($givenval, $stdval);
}
} else {
return $stdval;
}
}
/**
* Convert string to bool
*
* @param String $string
* @param bool $default
*
* @return bool
*/
private function convert_bool($string, $default = false) {
if ($string === false || $string === "false" || $string === 0 || $string === "0") {
return false;
} else if ($string === true || $string === "true" || $string === 1 || $string === "1") {
return true;
} else {
return $default;
}
}
/**
* Decide between two strings
*
* @param String $choice1
* @param String $choice2