-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmod_form.php
More file actions
520 lines (444 loc) · 25.9 KB
/
mod_form.php
File metadata and controls
520 lines (444 loc) · 25.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
<?php //$Id: mod_form.php,v 1.3 2008/08/10 08:05:15 mudrd8mz Exp $
/**
* This file defines de main exagames configuration form
* It uses the standard core Moodle (>1.8) formslib. For
* more info about them, please visit:
*
* http://docs.moodle.org/en/Development:lib/formslib.php
*
* The form must provide support for, at least these fields:
* - name: text element of 64cc max
*
* Also, it's usual to use these fields:
* - intro: one htmlarea element to describe the activity
* (will be showed in the list of activities of
* exagames type (index.php) and in the header
* of the exagames main page (view.php).
* - introformat: The format used to write the contents
* of the intro field. It automatically defaults
* to HTML when the htmleditor is used and can be
* manually selected if the htmleditor is not used
* (standard formats are: MOODLE, HTML, PLAIN, MARKDOWN)
* See lib/weblib.php Constants and the format_text()
* function for more info
*/
require_once('moodleform_mod.php');
class mod_exagames_mod_form extends moodleform_mod
{
function definition()
{
global $COURSE, $CFG, $DB, $OUTPUT, $PAGE, $USER;
$mform =& $this->_form;
//-------------------------------------------------------------------------------
$stringman = get_string_manager();
$strings = $stringman->load_component_strings('mod_exagames', $CFG->lang);
$PAGE->requires->strings_for_js(array_keys($strings), 'mod_exagames');
/// Adding the "general" fieldset, where all the common settings are showed
$mform->addElement('header', 'general', get_string('general', 'form'));
/// Adding the standard "name" field
$mform->addElement('text', 'name', get_string('exagamesname', 'exagames'), array('size' => '64'));
$mform->setType('name', PARAM_TEXT);
$mform->addRule('name', null, 'required', null, 'client');
$this->standard_intro_elements(null);
/// Adding the optional "intro" and "introformat" pair of fields
/*
$mform->addElement('htmleditor', 'intro', get_string('exagamesintro', 'exagames'));
$mform->setType('intro', PARAM_RAW);
$mform->addRule('intro', get_string('required'), 'required', null, 'client');
$mform->setHelpButton('intro', array('writing', 'richtext'), false, 'editorhelpbutton');
$mform->addElement('format', 'introformat', get_string('format'));
*/
/// Quiz Dropdown
$questions = array();
$questionBankNames = array();
$qtest = array();
//$exagame = $DB->get_record('exagames', ['id'=>$PAGE->cm->instance]);
//$exagame->quizid = optional_param('quizid', $exagame->quizid, PARAM_TEXT);
if ($recs = $DB->get_records_sql("
SELECT ca.*
FROM {$CFG->prefix}question_bank_entries as en
INNER JOIN {$CFG->prefix}question_categories as ca on en.questioncategoryid = ca.id
GROUP BY en.questioncategoryid")) {
foreach ($recs as $key=>$rec) {
$qtest[$key] = $DB->get_records_sql("
SELECT qu.* FROM {$CFG->prefix}question_bank_entries as ba
INNER JOIN {$CFG->prefix}question_versions as qv on ba.id = qv.questionbankentryid
INNER JOIN {$CFG->prefix}question as qu on qu.id = qv.questionid
WHERE ba.questioncategoryid = ?", [intval($rec->id)]);
$questions[$rec->id] = $rec->name;
$qDetails = new stdClass();
$qNameArr = array();
foreach ($qtest[$key] as $q) {
$curDetails = $DB->get_record(
'exagames_question',
array('id' => $q->id),
'difficulty, display_order, content_url',
IGNORE_MISSING);
if ($curDetails) {
$qDetails->difficulty = $curDetails->difficulty;
$qDetails->display_order = $curDetails->display_order;
$qDetails->content_url = $curDetails->content_url;
$qDetails->name = $q->name;
$qDetails->id = $q->id;
} else {
$qDetails = new stdClass();
$qDetails->difficulty = "";
$qDetails->display_order = "";
$qDetails->content_url = "";
$qDetails->name = $q->name;
$qDetails->id = $q->id;
}
$qNameArr[] = clone $qDetails;
}
$qObject = new stdClass();
$qObject->questionDetails = $qNameArr;
$qObject->quizName = $rec->name;
$questionBankNames[$rec->id] = $qObject;
}
}
/*$quizzes = array();
$quizzes_questionNames = array();
$firstQuizId = null;
$urlQuizId = optional_param('quizId', 0, PARAM_INT); // Course Module ID, or
if ($urlQuizId != null) $firstQuizId = $urlQuizId;
if ($recs = $DB->get_records_select('quiz', "course='$COURSE->id'", null, 'name', 'id,name')) {
foreach ($recs as $rec) {
if ($firstQuizId == null) {
$firstQuizId = $rec->id;
}
$quizzes[$rec->id] = $rec->name;
$quizObj->preload_questions();
$quizObj->load_questions();
$qDetails = new stdClass();
$qNameArr = array();
foreach ($quizObj->get_questions() as $q) {
$curDetails = $DB->get_record('exagames_question', array('id' => $q->id), $fields = 'difficulty, display_order, content_url', $strictness = IGNORE_MISSING);
if($curDetails) {
$qDetails->difficulty = $curDetails->difficulty;
$qDetails->display_order = $curDetails->display_order;
$qDetails->content_url = $curDetails->content_url;
$qDetails->name = $q->name;
$qDetails->id = $q->id;
} else {
$qDetails = new stdClass();
$qDetails->difficulty = "";
$qDetails->display_order = "";
$qDetails->content_url = "";
$qDetails->name = $q->name;
$qDetails->id = $q->id;
}
$qNameArr[] = clone $qDetails;
}
$qObject = new stdClass();
$qObject->questionDetails = $qNameArr;
// $temp = $DB->get_record('exagames_question', array ('id'=>), $fields='*', $strictness=IGNORE_MISSING);
$qObject->quizName = $rec->name;
$quizzes_questionNames[$rec->id] = $qObject;
}
}*/
/*if (!$quizzes) {
// dirty as moodle: link to add quiz if no quiz was found in this course!
$return = optional_param('return', 0, PARAM_BOOL);
$type = optional_param('type', '', PARAM_ALPHANUM);
$section = required_param('section', PARAM_INT);
$a = new StdClass;
$a->linkTag = '<a href="'.$CFG->wwwroot.'/course/modedit.php?add=quiz&type='.$type.'&course='.$COURSE->id.'§ion='.$section.'&return='.$return.'">';
$redirect = $CFG->wwwroot.'/course/modedit.php?add=quiz&type='.$type.'&course='.$COURSE->id.'§ion='.$section.'&return='.$return;
print_error('noquizzesincourse', 'exagames', $redirect, $a);
}*/
$mform->addElement('select', 'quizid', get_string('modulename', 'quiz'), $questions);
$mform->addHelpButton('quizid', 'quizid', 'exagames');
$mform->addRule('quizid', null, 'required', null, 'client');
$games = array(
'braingame' => get_string('game_braingame', 'exagames'),
'tiles' => get_string('game_tiles', 'exagames')
);
//element type, key, language, options
$mform->addElement('select', 'gametype', get_string('gametype', 'exagames'), $games);
$mform->addHelpButton('gametype', 'gametype', 'exagames');
//$quizLen = count($questionBankNames[$exagame->quizid]->questionDetails);
foreach ($questionBankNames as $quizKey => $questions) {
foreach ($questions->questionDetails as $questKey => $qDetails) {
$content_url = $qDetails->content_url;
$display_order = $qDetails->display_order;
$difficulty = $qDetails->difficulty;
$question_id = $qDetails->id;
$tilesEditor = [];
$urlParams = '?';
$urlParams .= isset($content_url) && $content_url != null ? "content_url=$content_url&" : "";
$urlParams .= isset($display_order) && $display_order != null ? "display_order=$display_order&" : "";
$urlParams .= isset($difficulty) && $difficulty != null ? "difficulty=$difficulty&" : "";
$urlParams .= isset($question_id) && $question_id != null ? "question_id=$question_id&" : "";
$urlParams .= isset($responses) && $responses != null ? "$responses" : "";
// save the language strings as well, since M.util does not work
$urlParams .= "no_config_safed_text=" . get_string('tiles_noConfig', 'exagames') . "&";
$urlParams .= "config_safed_text=" . get_string('tiles_saveText', 'exagames') . "&";
$urlParams .= "edit_config_safed_text=" . get_string('tiles_editConfig', 'exagames') . "&";
$urlParams .= "no_square_selected_text=" . get_string('tiles_noSquareSelected', 'exagames') . "&";
$urlParams .= "no_difficulty_selected_text=" . get_string('tiles_noDifficultySelected', 'exagames') . "&";
$urlParams .= "configuration_saved=" . get_string('configurationSaved', 'exagames') . "&";
$urlParams .= "no_configuration_saved=" . get_string('noConfigurationSaved', 'exagames') . "&";
$urlParams .= "randomize_button=" . get_string('randomizeButton', 'exagames') . "&";
$urlParams .= "simulate_button=" . get_string('simulateButton', 'exagames') . "&";
$urlParams .= "reset_button=" . get_string('resetButton', 'exagames') . "&";
$urlParams .= "save_button=" . get_string('saveButton', 'exagames') . "&";
$urlParams .= "diff_easy=" . get_string('easyDifficulty', 'exagames') . "&";
$urlParams .= "diff_int=" . get_string('interDifficulty', 'exagames') . "&";
$urlParams .= "diff_hard=" . get_string('hardDifficulty', 'exagames') . "&";
$tilesEditor[] = $mform->createElement("html", '
<div id="tileEditor-' . $quizKey . '-quest-' . $questKey . '" style="width: 940px; height:600px">
<iframe class="editor_frames" id="editorframe-' . $quizKey . '-quest-' . $questKey . '" frameborder="0" style="height:600px;width:100%" src="' . $CFG->wwwroot . '/mod/exagames/html5/form_editor/tiles.html' . $urlParams . '"></iframe></br>
</div>');
$tilesEditor[] = $mform->createElement('filemanager', 'attachments', get_string('attachment', 'exagames'), null,
array('subdirs' => 0, 'areamaxbytes' => 10485760, 'maxfiles' => 1,
'accepted_types' => array('.jpg', '.png', '.gif'), 'return_types' => FILE_INTERNAL | FILE_EXTERNAL));
$mform->addGroup($tilesEditor, 'Editor', get_string('question', 'exagames') . '"' . $qDetails->name . '"');
}
}
$url = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// $_SERVER['REQUEST_SCHEME'] . '//' . $_SERVER['SERVER_NAME']
?>
<!--<script src="/mod/exagames/html5/js/jquery.min.js"></script>-->
<script src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script>
let quizzes = <?php echo json_encode($questionBankNames); ?>;
let url_string = window.location.href;
let url = new URL(url_string);
var cur_quizid = url.searchParams.get("quizid");
var loc = <?php echo json_encode($url); ?>;
$(document).ready(function () {
handleGameTypeParam();
handleQuizSelectParam();
$('#id_quizid').prop('disabled', false);
$('#id_gametype').prop('disabled', false);
$('#id_gametype').on('change', function () {
handleGameTypeParam();
});
$('#id_quizid').on('change', function () {
handleQuizSelectParam();
});
$('.mainContainer').on('load', function(){
alert("test");
alert("<?php echo get_string('tiles_difficultyLabel_hard', 'exagames'); ?>");
$("iframe").contents().find('#difficultyLabel').html("<?php echo get_string('tiles_difficultyLabel', 'exagames'); ?>");
$("iframe").contents().find('#saveButton').html("<?php echo get_string('tiles_saveButton', 'exagames'); ?>");
$("iframe").contents().find('#randomizeButton').html("<?php echo get_string('tiles_randomizeButton', 'exagames'); ?>");
$("iframe").contents().find('#simulateButton').html("<?php echo get_string('tiles_simulateButton', 'exagames'); ?>");
$("iframe").contents().find('#saveText').html("<?php echo get_string('tiles_saveText', 'exagames'); ?>");
$("iframe").contents().find('#resetButton').html("<?php echo get_string('tiles_resetButton', 'exagames'); ?>");
$("iframe").contents().find("#difficultyForm input[value='easy']")
.next()
.html("<?php echo get_string('tiles_difficultyLabel_easy', 'exagames'); ?>");
$("iframe").contents().find("#difficultyForm input[value='intermediate']")
.next()
.html("<?php echo get_string('tiles_difficultyLabel_medium', 'exagames'); ?>");
$("iframe").contents().find("#difficultyForm input[value='hard']")
.next()
.html("<?php echo get_string('tiles_difficultyLabel_hard', 'exagames'); ?>");
$("iframe").contents().find('#difficultyLabel').html("<?php echo get_string('tiles_difficultyLabel', 'exagames'); ?>");
});
});
function handleGameTypeParam() {
switch($('#id_gametype').val()) {
case 'tiles':
$('.initial-hide').show();
handleQuizSelectParam();
break;
case 'braingame':
$("div[id*=tileEditor]").parent().parent().parent().parent().css('display', 'none');
break;
}
}
function handleQuizSelectParam() {
$("div[id*=tileEditor]").parent().parent().parent().parent().css('display', 'none');
if($('#id_gametype').val() == 'tiles') {
$("div[id*=tileEditor-" + $('#id_quizid').val() + "]").parent().parent().parent().parent().css('display', 'block');
$("div[id*=tileEditor-" + $('#id_quizid').val() + "]").css('display', 'block');
$(".filemanager").show();
$(".form-filetypes-descriptions").show();
setTimeout(function() {
$('#id_quizid').trigger('change');
}, 500);
}
}
function getLoadSwitchRef() {
return $('#id_quizid');
}
function a(frameId) {
return $('#' + frameId).parent().parent().find(".fm-content-wrapper > .fp-content");
}
function getFMImage(frameId) {
return new Promise((resolve, reject) => {
let fileElement = $('#' + frameId).parent().parent().find('.fp-file .fp-thumbnail > img');
if (fileElement.length) {
let imagePath = $(fileElement).attr('src');
resolve(imagePath);
} else {
let elapsedTime = 0;
let intervalId;
intervalId = setInterval(function() {
fileElement = $('#' + frameId).closest('.felement').find('.filemanager img.realpreview').first();
if (fileElement.length > 0) {
clearInterval(intervalId);
let imagePath = $(fileElement).attr('src');
resolve(imagePath);
}
elapsedTime += 50;
if (elapsedTime >= 1000) {
clearInterval(intervalId);
resolve(''); // return an empty string if not found
}
}, 50); // check every 50 ms
}
});
}
function getFMImageOld(frameId) {
let fileElement = $('#' + frameId).parent().parent().find('.fp-file .fp-thumbnail > img');
if (fileElement.length) {
let imagePath = $($(fileElement)[0]).attr('src');
return imagePath;
} else {
// check element no more than 1 second
var elapsedTime = 0;
var intervalId;
var imagePath = '';
intervalId = setInterval(function() {
fileElement = $('#' + frameId).closest('.felement').find('.filemanager img.realpreview').first();
if (fileElement.length > 0) {
// exists!
imagePath = $(fileElement).attr('src');
if (imagePath) {
imagePath = trimURLParamsFromMedia(imagePath);
}
return imagePath;
}
elapsedTime += 50;
if (elapsedTime >= 1000) { // 1 second - limit
clearInterval(intervalId);
return '';
}
}, 50); // every 50 ms
}
}
function trimURLParamsFromMedia(str) {
if (str.includes(".png")) {
return str.substring(0, str.indexOf('.png') + 4);
} else if (str.includes(".jpg")) {
return str.substring(0, str.indexOf('.jpg') + 4);
} else if (str.includes(".gif")) {
return str.substring(0, str.indexOf('.gif') + 4);
} else {
return str;
}
}
function getWindowLoc() {
return window.location.href;
}
function swapElement(a, b) {
// create a temporary marker div
var aNext = $('<div>').insertAfter(a);
a.insertAfter(b);
b.insertBefore(aNext);
// remove marker div
aNext.remove();
}
function removeURLParameter(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts = url.split('?');
if (urlparts.length >= 2) {
var prefix = encodeURIComponent(parameter) + '=';
var pars = urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i = pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url = urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
return url;
} else {
return url;
}
}
</script>
<?php
if ((optional_param('func', '', PARAM_TEXT) == 'configure_question') && ($questionId = optional_param('questionid', '', PARAM_INT)) && ($content_url = optional_param('content_url', '', PARAM_TEXT))) {
// $content_url contains an url into DRAFT file, so we need to save it directly:
if ($content_url && strpos($content_url, '/user/draft/') !== false ) { // only for DRAFT urls
$parsed_url = parse_url($content_url);
$path = $parsed_url['path'];
$dynamic_part = substr($path, strpos($path, "exagames/lib/file_load.php/") + strlen("exagames/lib/file_load.php/"));
$parts = explode('/', $dynamic_part);
$contextid = $parts[0];
$context = context::instance_by_id($contextid);
$component = $parts[1];
$filearea = $parts[2];
$draftid = $parts[3];
$filename = urldecode($parts[4]);
$fullpath = "/$context->id/$component/$filearea/$draftid/$filename";
$filehash = sha1($fullpath);
$fs = get_file_storage();
$draftFile = $fs->get_file_by_hash($filehash);
if ($draftFile) { // only if all ok with draft file
$draftContent = $draftFile->get_content();
// save to real fixed filearea
$newComponent = 'mod_exagames';
$newFilearea = 'question_content';
$file_record = array(
'contextid' => $contextid,
'component' => $newComponent,
'filearea' => $newFilearea,
'itemid' => $questionId,
'filepath' => '/',
'filename' => $filename,
'timecreated' => time(),
'timemodified' => time(),
);
// Remove files: we need only single file for every question
$fs->delete_area_files($contextid, $newComponent, $newFilearea, $questionId);
// And new file create
$new_file = $fs->create_file_from_string($file_record, $draftContent);
$content_partUrl = implode('/', [$contextid, $newComponent, $newFilearea, $questionId, $filename]);
$mainLength = strpos($content_url, "exagames/lib/file_load.php/") + strlen("exagames/lib/file_load.php/");
$mainUrl = substr($content_url, 0, $mainLength);
$mainUrl .= $content_partUrl;
$content_url = $mainUrl;
}
}
$questionConfig = new stdClass();
$questionConfig->id = $questionId;
$questionConfig->content_url = $content_url;
$questionConfig->tile_size = optional_param('tile_size', '', PARAM_TEXT);
$questionConfig->difficulty = optional_param('difficulty', '', PARAM_TEXT);
$questionConfig->display_order = optional_param('display_order', '', PARAM_TEXT);
if (!$DB->record_exists('exagames_question', array('id' => $questionId))) {
$DB->execute("
INSERT INTO {$CFG->prefix}exagames_question (id, tile_size, content_url, difficulty, display_order)
VALUES ({$questionConfig->id}, '', '', '', '')
");
}
$DB->update_record('exagames_question', $questionConfig);
echo "ok=1";
exit;
}
/*
$mform->addElement('text', 'url', get_string('url', 'exagames'), array('size'=>'64'));
$mform->addHelpButton('url', 'url', 'exagames');*/
//-------------------------------------------------------------------------------
/// Adding the rest of exagames settings, spreeading all them into this fieldset
/// or adding more fieldsets ('header' elements) if needed for better logic
/*
$mform->addElement('static', 'label1', 'exagamessetting1', 'Your exagames fields go here. Replace me!');
$mform->addElement('header', 'exagamesfieldset', get_string('exagamesfieldset', 'exagames'));
$mform->addElement('static', 'label2', 'exagamessetting2', 'Your exagames fields go here. Replace me!');
*/
//-------------------------------------------------------------------------------
// add standard elements, common to all modules
$this->standard_coursemodule_elements();
//-------------------------------------------------------------------------------
// add standard buttons, common to all modules
$this->add_action_buttons();
}
}