forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathframework.php
1682 lines (1485 loc) · 67.7 KB
/
framework.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 - http://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 <http://www.gnu.org/licenses/>.
/**
* \core_h5p\framework class
*
* @package core_h5p
* @copyright 2019 Mihail Geshoski <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_h5p;
use Moodle\H5PFrameworkInterface;
use Moodle\H5PCore;
/**
* Moodle's implementation of the H5P framework interface.
*
* @package core_h5p
* @copyright 2019 Mihail Geshoski <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class framework implements H5PFrameworkInterface {
/** @var string The path to the last uploaded h5p */
private $lastuploadedfolder;
/** @var string The path to the last uploaded h5p file */
private $lastuploadedfile;
/** @var stored_file The .h5p file */
private $file;
/**
* Returns info for the current platform.
* Implements getPlatformInfo.
*
* @return array An associative array containing:
* - name: The name of the platform, for instance "Moodle"
* - version: The version of the platform, for instance "3.8"
* - h5pVersion: The version of the H5P component
*/
public function getPlatformInfo() {
global $CFG;
return array(
'name' => 'Moodle',
'version' => $CFG->version,
'h5pVersion' => $CFG->version,
);
}
/**
* Fetches a file from a remote server using HTTP GET.
* Implements fetchExternalData.
*
* @param string $url Where you want to get or send data
* @param array $data Data to post to the URL
* @param bool $blocking Set to 'FALSE' to instantly time out (fire and forget)
* @param string $stream Path to where the file should be saved
* @return string The content (response body). NULL if something went wrong
*/
public function fetchExternalData($url, $data = null, $blocking = true, $stream = null) {
if ($stream === null) {
// Download file.
set_time_limit(0);
// Get the extension of the remote file.
$parsedurl = parse_url($url);
$ext = pathinfo($parsedurl['path'], PATHINFO_EXTENSION);
// Generate local tmp file path.
$fs = new \core_h5p\file_storage();
$localfolder = $fs->getTmpPath();
$stream = $localfolder;
// Add the remote file's extension to the temp file.
if ($ext) {
$stream .= '.' . $ext;
}
$this->getUploadedH5pFolderPath($localfolder);
$this->getUploadedH5pPath($stream);
}
$response = download_file_content($url, null, $data, true, 300, 20,
false, $stream);
if (empty($response->error) && ($response->status != '404')) {
return $response->results;
} else {
$this->setErrorMessage($response->error, 'failed-fetching-external-data');
}
}
/**
* Set the tutorial URL for a library. All versions of the library is set.
* Implements setLibraryTutorialUrl.
*
* @param string $libraryname
* @param string $url
*/
public function setLibraryTutorialUrl($libraryname, $url) {
global $DB;
$sql = 'UPDATE {h5p_libraries}
SET tutorial = :tutorial
WHERE machinename = :machinename';
$params = [
'tutorial' => $url,
'machinename' => $libraryname,
];
$DB->execute($sql, $params);
}
/**
* Set an error message.
* Implements setErrorMessage.
*
* @param string $message The error message
* @param string $code An optional code
*/
public function setErrorMessage($message, $code = null) {
if ($message !== null) {
$this->set_message('error', $message, $code);
}
}
/**
* Set an info message.
* Implements setInfoMessage.
*
* @param string $message The info message
*/
public function setInfoMessage($message) {
if ($message !== null) {
$this->set_message('info', $message);
}
}
/**
* Return messages.
* Implements getMessages.
*
* @param string $type The message type, e.g. 'info' or 'error'
* @return string[] Array of messages
*/
public function getMessages($type) {
global $SESSION;
// Return and reset messages.
$messages = array();
if (isset($SESSION->core_h5p_messages[$type])) {
$messages = $SESSION->core_h5p_messages[$type];
unset($SESSION->core_h5p_messages[$type]);
if (empty($SESSION->core_h5p_messages)) {
unset($SESSION->core_h5p_messages);
}
}
return $messages;
}
/**
* Translation function.
* The purpose of this function is to map the strings used in the core h5p methods
* and replace them with the translated ones. If a translation for a particular string
* is not available, the default message (key) will be returned.
* Implements t.
*
* @param string $message The english string to be translated
* @param array $replacements An associative array of replacements to make after translation
* @return string Translated string or the english string if a translation is not available
*/
public function t($message, $replacements = array()) {
// Create mapping.
$translationsmap = [
'The file you uploaded is not a valid HTML5 Package (It does not have the .h5p file extension)' => 'noextension',
'The file you uploaded is not a valid HTML5 Package (We are unable to unzip it)' => 'nounzip',
'The main h5p.json file is not valid' => 'nojson',
'Library directory name must match machineName or machineName-majorVersion.minorVersion (from library.json).' .
' (Directory: %directoryName , machineName: %machineName, majorVersion: %majorVersion, minorVersion:' .
' %minorVersion)'
=> 'librarydirectoryerror',
'A valid content folder is missing' => 'missingcontentfolder',
'A valid main h5p.json file is missing' => 'invalidmainjson',
'Missing required library @library' => 'missinglibrary',
"Note that the libraries may exist in the file you uploaded, but you're not allowed to upload new libraries." .
' Contact the site administrator about this.' => 'missinguploadpermissions',
'Invalid library name: %name' => 'invalidlibraryname',
'Could not find library.json file with valid json format for library %name' => 'missinglibraryjson',
'Invalid semantics.json file has been included in the library %name' => 'invalidsemanticsjson',
'Invalid language file %file in library %library' => 'invalidlanguagefile',
'Invalid language file %languageFile has been included in the library %name' => 'invalidlanguagefile2',
'The file "%file" is missing from library: "%name"' => 'missinglibraryfile',
'The system was unable to install the <em>%component</em> component from the package, it requires a newer' .
' version of the H5P plugin. This site is currently running version %current, whereas the required version' .
' is %required or higher. You should consider upgrading and then try again.' => 'missingcoreversion',
"Invalid data provided for %property in %library. Boolean expected." => 'invalidlibrarydataboolean',
"Invalid data provided for %property in %library" => 'invalidlibrarydata',
"Can't read the property %property in %library" => 'invalidlibraryproperty',
'The required property %property is missing from %library' => 'missinglibraryproperty',
'Illegal option %option in %library' => 'invalidlibraryoption',
'Added %new new H5P library and updated %old old one.' => 'addedandupdatedss',
'Added %new new H5P library and updated %old old ones.' => 'addedandupdatedsp',
'Added %new new H5P libraries and updated %old old one.' => 'addedandupdatedps',
'Added %new new H5P libraries and updated %old old ones.' => 'addedandupdatedpp',
'Added %new new H5P library.' => 'addednewlibrary',
'Added %new new H5P libraries.' => 'addednewlibraries',
'Updated %old H5P library.' => 'updatedlibrary',
'Updated %old H5P libraries.' => 'updatedlibraries',
'Missing dependency @dep required by @lib.' => 'missingdependency',
'Provided string is not valid according to regexp in semantics. (value: "%value", regexp: "%regexp")'
=> 'invalidstring',
'File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.'
=> 'invalidfile',
'Invalid selected option in multi-select.' => 'invalidmultiselectoption',
'Invalid selected option in select.' => 'invalidselectoption',
'H5P internal error: unknown content type "@type" in semantics. Removing content!' => 'invalidsemanticstype',
'Copyright information' => 'copyrightinfo',
'Title' => 'title',
'Author' => 'author',
'Year(s)' => 'years',
'Year' => 'year',
'Source' => 'source',
'License' => 'license',
'Undisclosed' => 'undisclosed',
'General Public License v3' => 'gpl',
'Public Domain' => 'pd',
'Public Domain Dedication and Licence' => 'pddl',
'Public Domain Mark' => 'pdm',
'Public Domain Mark (PDM)' => 'pdm',
'Copyright' => 'copyrightstring',
'The mbstring PHP extension is not loaded. H5P need this to function properly' => 'missingmbstring',
'The version of the H5P library %machineName used in this content is not valid. Content contains %contentLibrary, ' .
'but it should be %semanticsLibrary.' => 'wrongversion',
'The H5P library %library used in the content is not valid' => 'invalidlibrarynamed',
'Fullscreen' => 'fullscreen',
'Disable fullscreen' => 'disablefullscreen',
'Download' => 'download',
'Rights of use' => 'copyright',
'Embed' => 'embed',
'Size' => 'size',
'Show advanced' => 'showadvanced',
'Hide advanced' => 'hideadvanced',
'Include this script on your website if you want dynamic sizing of the embedded content:' => 'resizescript',
'Close' => 'close',
'Thumbnail' => 'thumbnail',
'No copyright information available for this content.' => 'nocopyright',
'Download this content as a H5P file.' => 'downloadtitle',
'View copyright information for this content.' => 'copyrighttitle',
'View the embed code for this content.' => 'embedtitle',
'Visit H5P.org to check out more cool content.' => 'h5ptitle',
'This content has changed since you last used it.' => 'contentchanged',
"You'll be starting over." => 'startingover',
'by' => 'by',
'Show more' => 'showmore',
'Show less' => 'showless',
'Sublevel' => 'sublevel',
'Confirm action' => 'confirmdialogheader',
'Please confirm that you wish to proceed. This action is not reversible.' => 'confirmdialogbody',
'Cancel' => 'cancellabel',
'Confirm' => 'confirmlabel',
'4.0 International' => 'licenseCC40',
'3.0 Unported' => 'licenseCC30',
'2.5 Generic' => 'licenseCC25',
'2.0 Generic' => 'licenseCC20',
'1.0 Generic' => 'licenseCC10',
'General Public License' => 'licenseGPL',
'Version 3' => 'licenseV3',
'Version 2' => 'licenseV2',
'Version 1' => 'licenseV1',
'CC0 1.0 Universal (CC0 1.0) Public Domain Dedication' => 'licenseCC010',
'CC0 1.0 Universal' => 'licenseCC010U',
'License Version' => 'licenseversion',
'Creative Commons' => 'creativecommons',
'Attribution' => 'ccattribution',
'Attribution (CC BY)' => 'ccattribution',
'Attribution-ShareAlike' => 'ccattributionsa',
'Attribution-ShareAlike (CC BY-SA)' => 'ccattributionsa',
'Attribution-NoDerivs' => 'ccattributionnd',
'Attribution-NoDerivs (CC BY-ND)' => 'ccattributionnd',
'Attribution-NonCommercial' => 'ccattributionnc',
'Attribution-NonCommercial (CC BY-NC)' => 'ccattributionnc',
'Attribution-NonCommercial-ShareAlike' => 'ccattributionncsa',
'Attribution-NonCommercial-ShareAlike (CC BY-NC-SA)' => 'ccattributionncsa',
'Attribution-NonCommercial-NoDerivs' => 'ccattributionncnd',
'Attribution-NonCommercial-NoDerivs (CC BY-NC-ND)' => 'ccattributionncnd',
'Public Domain Dedication (CC0)' => 'ccpdd',
'Years (from)' => 'yearsfrom',
'Years (to)' => 'yearsto',
"Author's name" => 'authorname',
"Author's role" => 'authorrole',
'Editor' => 'editor',
'Licensee' => 'licensee',
'Originator' => 'originator',
'Any additional information about the license' => 'additionallicenseinfo',
'License Extras' => 'licenseextras',
'Changelog' => 'changelog',
'Content Type' => 'contenttype',
'Date' => 'date',
'Changed by' => 'changedby',
'Description of change' => 'changedescription',
'Photo cropped, text changed, etc.' => 'changeplaceholder',
'Author comments' => 'authorcomments',
'Comments for the editor of the content (This text will not be published as a part of copyright info)'
=> 'authorcommentsdescription',
'Reuse' => 'reuse',
'Reuse Content' => 'reuseContent',
'Reuse this content.' => 'reuseDescription',
'Content is copied to the clipboard' => 'contentCopied',
'Connection lost. Results will be stored and sent when you regain connection.' => 'connectionLost',
'Connection reestablished.' => 'connectionReestablished',
'Attempting to submit stored results.' => 'resubmitScores',
'Your connection to the server was lost' => 'offlineDialogHeader',
'We were unable to send information about your completion of this task. Please check your internet connection.'
=> 'offlineDialogBody',
'Retrying in :num....' => 'offlineDialogRetryMessage',
'Retry now' => 'offlineDialogRetryButtonLabel',
'Successfully submitted results.' => 'offlineSuccessfulSubmit',
'One of the files inside the package exceeds the maximum file size allowed. (%file %used > %max)'
=> 'fileExceedsMaxSize',
'The total size of the unpacked files exceeds the maximum size allowed. (%used > %max)'
=> 'unpackedFilesExceedsMaxSize',
'Unable to read file from the package: %fileName' => 'couldNotReadFileFromZip',
'Unable to parse JSON from the package: %fileName' => 'couldNotParseJSONFromZip',
'A problem with the server write access was detected. Please make sure that your server can write to your data folder.' => 'nowriteaccess',
'H5P hub communication has been disabled because one or more H5P requirements failed.' => 'hubcommunicationdisabled',
'Site could not be registered with the hub. Please contact your site administrator.' => 'sitecouldnotberegistered',
'The H5P Hub has been disabled until this problem can be resolved. You may still upload libraries through the "H5P Libraries" page.' => 'hubisdisableduploadlibraries',
'When you have revised your server setup you may re-enable H5P hub communication in H5P Settings.' => 'reviseserversetupandretry',
'You have been provided a unique key that identifies you with the Hub when receiving new updates. The key is available for viewing in the "H5P Settings" page.' => 'sitekeyregistered',
'Your PHP max post size is quite small. With your current setup, you may not upload files larger than {$a->%number} MB. This might be a problem when trying to upload H5Ps, images and videos. Please consider to increase it to more than 5MB' => 'maxpostsizetoosmall',
'Your PHP max upload size is bigger than your max post size. This is known to cause issues in some installations.' => 'uploadsizelargerthanpostsize',
'Your PHP max upload size is quite small. With your current setup, you may not upload files larger than {$a->%number} MB. This might be a problem when trying to upload H5Ps, images and videos. Please consider to increase it to more than 5MB.' => 'maxuploadsizetoosmall',
'Your PHP version does not support ZipArchive.' => 'noziparchive',
'Your PHP version is outdated. H5P requires version 5.2 to function properly. Version 5.6 or later is recommended.' => 'oldphpversion',
'Your server does not have SSL enabled. SSL should be enabled to ensure a secure connection with the H5P hub.' => 'sslnotenabled',
'Your site was successfully registered with the H5P Hub.' => 'successfullyregisteredwithhub'
];
if (isset($translationsmap[$message])) {
return get_string($translationsmap[$message], 'core_h5p', $replacements);
}
debugging("String translation cannot be found. Please add a string definition for '" .
$message . "' in the core_h5p component.", DEBUG_DEVELOPER);
return $message;
}
/**
* Get URL to file in the specifimake_pluginfile_urlc library.
* Implements getLibraryFileUrl.
*
* @param string $libraryfoldername The name or path of the library's folder
* @param string $filename The file name
* @return string URL to file
*/
public function getLibraryFileUrl($libraryfoldername, $filename) {
global $DB;
// Remove unnecessary slashes (first and last, if present) from the path to the folder
// of the library file.
$libraryfilepath = trim($libraryfoldername, '/');
// Get the folder name of the library from the path.
// The first element should represent the folder name of the library.
$libfoldername = explode('/', $libraryfilepath)[0];
$factory = new \core_h5p\factory();
$core = $factory->get_core();
// The provided folder name of the library must have a valid format (can be parsed).
// The folder name is parsed with a purpose of getting the library related information
// such as 'machineName', 'majorVersion' and 'minorVersion'.
// This information is later used to retrieve the library ID.
if (!$libdata = $core->libraryFromString($libfoldername, true)) {
debugging('The provided string value "' . $libfoldername .
'" is not a valid name for a library folder.', DEBUG_DEVELOPER);
return;
}
$params = array(
'machinename' => $libdata['machineName'],
'majorversion' => $libdata['majorVersion'],
'minorversion' => $libdata['minorVersion']
);
$libraries = $DB->get_records('h5p_libraries', $params, 'patchversion DESC', 'id',
0, 1);
if (!$library = reset($libraries)) {
debugging('The library "' . $libfoldername . '" does not exist.', DEBUG_DEVELOPER);
return;
}
$context = \context_system::instance();
return \moodle_url::make_pluginfile_url($context->id, 'core_h5p', 'libraries',
$library->id, '/' . $libraryfilepath . '/', $filename)->out();
}
/**
* Get the Path to the last uploaded h5p.
* Implements getUploadedH5PFolderPath.
*
* @param string $setpath The path to the folder of the last uploaded h5p
* @return string Path to the folder where the last uploaded h5p for this session is located
*/
public function getUploadedH5pFolderPath($setpath = null) {
if ($setpath !== null) {
$this->lastuploadedfolder = $setpath;
}
if (!isset($this->lastuploadedfolder)) {
throw new \coding_exception('Using getUploadedH5pFolderPath() before path is set');
}
return $this->lastuploadedfolder;
}
/**
* Get the path to the last uploaded h5p file.
* Implements getUploadedH5PPath.
*
* @param string $setpath The path to the last uploaded h5p
* @return string Path to the last uploaded h5p
*/
public function getUploadedH5pPath($setpath = null) {
if ($setpath !== null) {
$this->lastuploadedfile = $setpath;
}
if (!isset($this->lastuploadedfile)) {
throw new \coding_exception('Using getUploadedH5pPath() before path is set');
}
return $this->lastuploadedfile;
}
/**
* Load addon libraries.
* Implements loadAddons.
*
* @return array The array containing the addon libraries
*/
public function loadAddons() {
global $DB;
$addons = array();
$records = $DB->get_records_sql(
"SELECT l1.id AS library_id,
l1.machinename AS machine_name,
l1.majorversion AS major_version,
l1.minorversion AS minor_version,
l1.patchversion AS patch_version,
l1.addto AS add_to,
l1.preloadedjs AS preloaded_js,
l1.preloadedcss AS preloaded_css
FROM {h5p_libraries} l1
LEFT JOIN {h5p_libraries} l2
ON l1.machinename = l2.machinename
AND (l1.majorversion < l2.majorversion
OR (l1.majorversion = l2.majorversion
AND l1.minorversion < l2.minorversion))
WHERE l1.addto IS NOT NULL
AND l2.machinename IS NULL");
// NOTE: These are treated as library objects but are missing the following properties:
// title, droplibrarycss, fullscreen, runnable, semantics.
// Extract num from records.
foreach ($records as $addon) {
$addons[] = H5PCore::snakeToCamel($addon);
}
return $addons;
}
/**
* Load config for libraries.
* Implements getLibraryConfig.
*
* @param array|null $libraries List of libraries
* @return array|null The library config if it exists, null otherwise
*/
public function getLibraryConfig($libraries = null) {
global $CFG;
return isset($CFG->core_h5p_library_config) ? $CFG->core_h5p_library_config : null;
}
/**
* Get a list of the current installed libraries.
* Implements loadLibraries.
*
* @return array Associative array containing one entry per machine name.
* For each machineName there is a list of libraries(with different versions).
*/
public function loadLibraries() {
global $DB;
$results = $DB->get_records('h5p_libraries', [], 'title ASC, majorversion ASC, minorversion ASC',
'id, machinename AS machine_name, majorversion AS major_version, minorversion AS minor_version,
patchversion AS patch_version, runnable, title, enabled');
$libraries = array();
foreach ($results as $library) {
$libraries[$library->machine_name][] = $library;
}
return $libraries;
}
/**
* Returns the URL to the library admin page.
* Implements getAdminUrl.
*
* @return string URL to admin page
*/
public function getAdminUrl() {
// Not supported.
}
/**
* Return the library's ID.
* Implements getLibraryId.
*
* @param string $machinename The librarys machine name
* @param string $majorversion Major version number for library (optional)
* @param string $minorversion Minor version number for library (optional)
* @return int|bool Identifier, or false if non-existent
*/
public function getLibraryId($machinename, $majorversion = null, $minorversion = null) {
global $DB;
$params = array(
'machinename' => $machinename
);
if ($majorversion !== null) {
$params['majorversion'] = $majorversion;
}
if ($minorversion !== null) {
$params['minorversion'] = $minorversion;
}
$libraries = $DB->get_records('h5p_libraries', $params,
'majorversion DESC, minorversion DESC, patchversion DESC', 'id', 0, 1);
// Get the latest version which matches the input parameters.
if ($libraries) {
$library = reset($libraries);
return $library->id ?? false;
}
return false;
}
/**
* Get allowed file extension list.
* Implements getWhitelist.
*
* The default extension list is part of h5p, but admins should be allowed to modify it.
*
* @param boolean $islibrary TRUE if this is the whitelist for a library. FALSE if it is the whitelist
* for the content folder we are getting.
* @param string $defaultcontentwhitelist A string of file extensions separated by whitespace.
* @param string $defaultlibrarywhitelist A string of file extensions separated by whitespace.
* @return string A string containing the allowed file extensions separated by whitespace.
*/
public function getWhitelist($islibrary, $defaultcontentwhitelist, $defaultlibrarywhitelist) {
return $defaultcontentwhitelist . ($islibrary ? ' ' . $defaultlibrarywhitelist : '');
}
/**
* Is the library a patched version of an existing library?
* Implements isPatchedLibrary.
*
* @param array $library An associative array containing:
* - machineName: The library machine name
* - majorVersion: The librarys major version
* - minorVersion: The librarys minor version
* - patchVersion: The librarys patch version
* @return boolean TRUE if the library is a patched version of an existing library FALSE otherwise
*/
public function isPatchedLibrary($library) {
global $DB;
$sql = "SELECT id
FROM {h5p_libraries}
WHERE machinename = :machinename
AND majorversion = :majorversion
AND minorversion = :minorversion
AND patchversion < :patchversion";
$library = $DB->get_records_sql(
$sql,
array(
'machinename' => $library['machineName'],
'majorversion' => $library['majorVersion'],
'minorversion' => $library['minorVersion'],
'patchversion' => $library['patchVersion']
),
0,
1
);
return !empty($library);
}
/**
* Is H5P in development mode?
* Implements isInDevMode.
*
* @return boolean TRUE if H5P development mode is active FALSE otherwise
*/
public function isInDevMode() {
return false; // Not supported (Files in moodle not editable).
}
/**
* Is the current user allowed to update libraries?
* Implements mayUpdateLibraries.
*
* @return boolean TRUE if the user is allowed to update libraries,
* FALSE if the user is not allowed to update libraries.
*/
public function mayUpdateLibraries() {
return helper::can_update_library($this->get_file());
}
/**
* Get the .h5p file.
*
* @return stored_file The .h5p file.
*/
public function get_file(): \stored_file {
if (!isset($this->file)) {
throw new \coding_exception('Using get_file() before file is set');
}
return $this->file;
}
/**
* Set the .h5p file.
*
* @param stored_file $file The .h5p file.
*/
public function set_file(\stored_file $file): void {
$this->file = $file;
}
/**
* Store data about a library.
* Implements saveLibraryData.
*
* Also fills in the libraryId in the libraryData object if the object is new.
*
* @param array $librarydata Associative array containing:
* - libraryId: The id of the library if it is an existing library
* - title: The library's name
* - machineName: The library machineName
* - majorVersion: The library's majorVersion
* - minorVersion: The library's minorVersion
* - patchVersion: The library's patchVersion
* - runnable: 1 if the library is a content type, 0 otherwise
* - fullscreen(optional): 1 if the library supports fullscreen, 0 otherwise
* - embedtypes: list of supported embed types
* - preloadedJs(optional): list of associative arrays containing:
* - path: path to a js file relative to the library root folder
* - preloadedCss(optional): list of associative arrays containing:
* - path: path to css file relative to the library root folder
* - dropLibraryCss(optional): list of associative arrays containing:
* - machineName: machine name for the librarys that are to drop their css
* - semantics(optional): Json describing the content structure for the library
* - metadataSettings(optional): object containing:
* - disable: 1 if metadata is disabled completely
* - disableExtraTitleField: 1 if the title field is hidden in the form
* @param bool $new Whether it is a new or existing library.
*/
public function saveLibraryData(&$librarydata, $new = true) {
global $DB;
// Some special properties needs some checking and converting before they can be saved.
$preloadedjs = $this->library_parameter_values_to_csv($librarydata, 'preloadedJs', 'path');
$preloadedcss = $this->library_parameter_values_to_csv($librarydata, 'preloadedCss', 'path');
$droplibrarycss = $this->library_parameter_values_to_csv($librarydata, 'dropLibraryCss', 'machineName');
if (!isset($librarydata['semantics'])) {
$librarydata['semantics'] = '';
}
if (!isset($librarydata['fullscreen'])) {
$librarydata['fullscreen'] = 0;
}
$embedtypes = '';
if (isset($librarydata['embedTypes'])) {
$embedtypes = implode(', ', $librarydata['embedTypes']);
}
$library = (object) array(
'title' => $librarydata['title'],
'machinename' => $librarydata['machineName'],
'majorversion' => $librarydata['majorVersion'],
'minorversion' => $librarydata['minorVersion'],
'patchversion' => $librarydata['patchVersion'],
'runnable' => $librarydata['runnable'],
'fullscreen' => $librarydata['fullscreen'],
'embedtypes' => $embedtypes,
'preloadedjs' => $preloadedjs,
'preloadedcss' => $preloadedcss,
'droplibrarycss' => $droplibrarycss,
'semantics' => $librarydata['semantics'],
'addto' => isset($librarydata['addTo']) ? json_encode($librarydata['addTo']) : null,
'coremajor' => isset($librarydata['coreApi']['majorVersion']) ? $librarydata['coreApi']['majorVersion'] : null,
'coreminor' => isset($librarydata['coreApi']['majorVersion']) ? $librarydata['coreApi']['minorVersion'] : null,
'metadatasettings' => isset($librarydata['metadataSettings']) ? $librarydata['metadataSettings'] : null,
);
if ($new) {
// Create new library and keep track of id.
$library->id = $DB->insert_record('h5p_libraries', $library);
$librarydata['libraryId'] = $library->id;
} else {
// Update library data.
$library->id = $librarydata['libraryId'];
// Save library data.
$DB->update_record('h5p_libraries', $library);
// Remove old dependencies.
$this->deleteLibraryDependencies($librarydata['libraryId']);
}
}
/**
* Insert new content.
* Implements insertContent.
*
* @param array $content An associative array containing:
* - id: The content id
* - params: The content in json format
* - library: An associative array containing:
* - libraryId: The id of the main library for this content
* - disable: H5P Button display options
* - pathnamehash: The pathnamehash linking the record with the entry in the mdl_files table
* - contenthash: The contenthash linking the record with the entry in the mdl_files table
* @param int $contentmainid Main id for the content if this is a system that supports versions
* @return int The ID of the newly inserted content
*/
public function insertContent($content, $contentmainid = null) {
return $this->updateContent($content);
}
/**
* Update old content or insert new content.
* Implements updateContent.
*
* @param array $content An associative array containing:
* - id: The content id
* - params: The content in json format
* - library: An associative array containing:
* - libraryId: The id of the main library for this content
* - disable: H5P Button display options
* - pathnamehash: The pathnamehash linking the record with the entry in the mdl_files table
* - contenthash: The contenthash linking the record with the entry in the mdl_files table
* @param int $contentmainid Main id for the content if this is a system that supports versions
* @return int The ID of the newly inserted or updated content
*/
public function updateContent($content, $contentmainid = null) {
global $DB;
if (!isset($content['pathnamehash'])) {
$content['pathnamehash'] = '';
}
if (!isset($content['contenthash'])) {
$content['contenthash'] = '';
}
// If the libraryid declared in the package is empty, get the latest version.
if (empty($content['library']['libraryId'])) {
$mainlibrary = $this->get_latest_library_version($content['library']['machineName']);
if (empty($mainlibrary)) {
// Raise an error if the main library is not defined and the latest version doesn't exist.
$message = $this->t('Missing required library @library', ['@library' => $content['library']['machineName']]);
$this->setErrorMessage($message, 'missing-required-library');
return false;
}
$content['library']['libraryId'] = $mainlibrary->id;
}
$content['disable'] = $content['disable'] ?? null;
// Add title to 'params' to use in the editor.
if (!empty($content['title'])) {
$params = json_decode($content['params']);
$params->title = $content['title'];
$content['params'] = json_encode($params);
}
$data = [
'jsoncontent' => $content['params'],
'displayoptions' => $content['disable'],
'mainlibraryid' => $content['library']['libraryId'],
'timemodified' => time(),
'filtered' => null,
'pathnamehash' => $content['pathnamehash'],
'contenthash' => $content['contenthash']
];
if (!isset($content['id'])) {
$data['timecreated'] = $data['timemodified'];
$id = $DB->insert_record('h5p', $data);
} else {
$id = $data['id'] = $content['id'];
$DB->update_record('h5p', $data);
}
return $id;
}
/**
* Resets marked user data for the given content.
* Implements resetContentUserData.
*
* @param int $contentid The h5p content id
*/
public function resetContentUserData($contentid) {
// Currently, we do not store user data for a content.
}
/**
* Save what libraries a library is depending on.
* Implements saveLibraryDependencies.
*
* @param int $libraryid Library Id for the library we're saving dependencies for
* @param array $dependencies List of dependencies as associative arrays containing:
* - machineName: The library machineName
* - majorVersion: The library's majorVersion
* - minorVersion: The library's minorVersion
* @param string $dependencytype The type of dependency
*/
public function saveLibraryDependencies($libraryid, $dependencies, $dependencytype) {
global $DB;
foreach ($dependencies as $dependency) {
// Find dependency library.
$dependencylibrary = $DB->get_record('h5p_libraries',
array(
'machinename' => $dependency['machineName'],
'majorversion' => $dependency['majorVersion'],
'minorversion' => $dependency['minorVersion']
)
);
// Create relation.
$DB->insert_record('h5p_library_dependencies', array(
'libraryid' => $libraryid,
'requiredlibraryid' => $dependencylibrary->id,
'dependencytype' => $dependencytype
));
}
}
/**
* Give an H5P the same library dependencies as a given H5P.
* Implements copyLibraryUsage.
*
* @param int $contentid Id identifying the content
* @param int $copyfromid Id identifying the content to be copied
* @param int $contentmainid Main id for the content, typically used in frameworks
*/
public function copyLibraryUsage($contentid, $copyfromid, $contentmainid = null) {
// Currently not being called.
}
/**
* Deletes content data.
* Implements deleteContentData.
*
* @param int $contentid Id identifying the content
*/
public function deleteContentData($contentid) {
global $DB;
// Remove content.
$DB->delete_records('h5p', array('id' => $contentid));
// Remove content library dependencies.
$this->deleteLibraryUsage($contentid);
}
/**
* Delete what libraries a content item is using.
* Implements deleteLibraryUsage.
*
* @param int $contentid Content Id of the content we'll be deleting library usage for
*/
public function deleteLibraryUsage($contentid) {
global $DB;
$DB->delete_records('h5p_contents_libraries', array('h5pid' => $contentid));
}
/**
* Saves what libraries the content uses.
* Implements saveLibraryUsage.
*
* @param int $contentid Id identifying the content
* @param array $librariesinuse List of libraries the content uses
*/
public function saveLibraryUsage($contentid, $librariesinuse) {
global $DB;
$droplibrarycsslist = array();
foreach ($librariesinuse as $dependency) {
if (!empty($dependency['library']['dropLibraryCss'])) {
$droplibrarycsslist = array_merge($droplibrarycsslist,
explode(', ', $dependency['library']['dropLibraryCss']));
}
}
foreach ($librariesinuse as $dependency) {
$dropcss = in_array($dependency['library']['machineName'], $droplibrarycsslist) ? 1 : 0;
$DB->insert_record('h5p_contents_libraries', array(
'h5pid' => $contentid,
'libraryid' => $dependency['library']['libraryId'],
'dependencytype' => $dependency['type'],
'dropcss' => $dropcss,
'weight' => $dependency['weight']
));
}
}
/**
* Get number of content/nodes using a library, and the number of dependencies to other libraries.
* Implements getLibraryUsage.
*
* @param int $id Library identifier
* @param boolean $skipcontent Optional. Set as true to get number of content instances for library
* @return array The array contains two elements, keyed by 'content' and 'libraries'.
* Each element contains a number
*/
public function getLibraryUsage($id, $skipcontent = false) {
global $DB;
if ($skipcontent) {
$content = -1;
} else {
$sql = "SELECT COUNT(distinct c.id)
FROM {h5p_libraries} l
JOIN {h5p_contents_libraries} cl ON l.id = cl.libraryid
JOIN {h5p} c ON cl.h5pid = c.id
WHERE l.id = :libraryid";
$sqlargs = array(
'libraryid' => $id
);
$content = $DB->count_records_sql($sql, $sqlargs);
}
$libraries = $DB->count_records('h5p_library_dependencies', ['requiredlibraryid' => $id]);
return array(
'content' => $content,
'libraries' => $libraries,
);
}
/**
* Loads a library.
* Implements loadLibrary.
*
* @param string $machinename The library's machine name
* @param int $majorversion The library's major version
* @param int $minorversion The library's minor version
* @return array|bool Returns FALSE if the library does not exist
* Otherwise an associative array containing:
* - libraryId: The id of the library if it is an existing library,
* - title: The library's name,
* - machineName: The library machineName
* - majorVersion: The library's majorVersion