Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Library of interface functions and constants for module hvp.
19
 *
20
 * All the core Moodle functions, neeeded to allow the module to work
21
 * integrated in Moodle should be placed here.
22
 *
23
 * All the hvp specific functions, needed to implement all the module
24
 * logic, should go to locallib.php. This will help to save some memory when
25
 * Moodle is performing actions across all modules.
26
 *
27
 * @package    mod_hvp
28
 * @copyright  2016 Joubel AS <contact@joubel.com>
29
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30
 */
31
 
32
use core_calendar\action_factory;
33
use core_calendar\local\event\entities\action_interface;
34
 
35
defined('MOODLE_INTERNAL') || die();
36
 
37
require_once('autoloader.php');
38
 
39
 /* Moodle core API */
40
 
41
/**
42
 * Returns the information on whether the module supports a feature
43
 *
44
 * See {@link plugin_supports()} for more info.
45
 *
46
 * @param string $feature FEATURE_xx constant for requested feature
47
 * @return mixed true if the feature is supported, null if unknown
48
 */
49
function hvp_supports($feature) {
50
    switch($feature) {
51
        case FEATURE_GROUPS:
52
            return true;
53
        case FEATURE_GROUPINGS:
54
            return true;
55
        case FEATURE_GROUPMEMBERSONLY:
56
            return true;
57
        case FEATURE_MOD_INTRO:
58
            return true;
59
        case FEATURE_COMPLETION_TRACKS_VIEWS:
60
            return true;
61
        case FEATURE_COMPLETION_HAS_RULES:
62
            return true;
63
        case FEATURE_GRADE_HAS_GRADE:
64
            return true;
65
        case FEATURE_GRADE_OUTCOMES:
66
            return false;
67
        case FEATURE_BACKUP_MOODLE2:
68
            return true;
69
        case FEATURE_SHOW_DESCRIPTION:
70
            return true;
71
 
72
        default:
73
            return null;
74
    }
75
}
76
 
77
/**
78
 * Saves a new instance of the hvp into the database
79
 *
80
 * Given an object containing all the necessary data,
81
 * (defined by the form in mod_form.php) this function
82
 * will create a new instance and return the id number
83
 * of the new instance.
84
 *
85
 * @param stdClass $hvp Submitted data from the form in mod_form.php
86
 * @return int The id of the newly inserted newmodule record
87
 */
88
function hvp_add_instance($hvp) {
89
    // Save content.
90
    $hvp->id = hvp_save_content($hvp);
91
 
92
    // Set and create grade item.
93
    hvp_grade_item_update($hvp);
94
 
95
    if (class_exists('\core_completion\api')) {
96
        $completiontimeexpected = !empty($hvp->completionexpected) ? $hvp->completionexpected : null;
97
        \core_completion\api::update_completion_date_event($hvp->coursemodule, 'hvp', $hvp->id, $completiontimeexpected);
98
    }
99
 
100
    return $hvp->id;
101
}
102
 
103
/**
104
 * Updates an instance of the hvp in the database
105
 *
106
 * Given an object containing all the necessary data,
107
 * (defined by the form in mod_form.php) this function
108
 * will update an existing instance with new data.
109
 *
110
 * @param stdClass $hvp An object from the form in mod_form.php
111
 * @return boolean Success/Fail
112
 */
113
function hvp_update_instance($hvp) {
114
    // Make ID available for core to save.
115
    $hvp->id = $hvp->instance;
116
 
117
    // Save content.
118
    hvp_save_content($hvp);
119
    hvp_grade_item_update($hvp);
120
 
121
    if (class_exists('\core_completion\api')) {
122
        $completiontimeexpected = !empty($hvp->completionexpected) ? $hvp->completionexpected : null;
123
        \core_completion\api::update_completion_date_event($hvp->coursemodule, 'hvp', $hvp->id, $completiontimeexpected);
124
    }
125
 
126
    return true;
127
}
128
 
129
/**
130
 * Does the actual process of saving the H5P content that's submitted through
131
 * the activity form
132
 *
133
 * @param stdClass $hvp
134
 * @return int Content ID
135
 */
136
function hvp_save_content($hvp) {
137
    // Determine if we're uploading or creating.
138
    if ($hvp->h5paction === 'upload') {
139
        // Save uploaded package.
140
        $hvp->uploaded = true;
141
        $h5pstorage = \mod_hvp\framework::instance('storage');
142
        $h5pstorage->savePackage((array)$hvp);
143
        $hvp->id = $h5pstorage->contentId;
144
    } else {
145
        // Save newly created or edited content.
146
        $core = \mod_hvp\framework::instance();
147
        $editor = \mod_hvp\framework::instance('editor');
148
 
149
        if (!empty($hvp->id)) {
150
            // Load existing content to get old parameters for comparison.
151
            $content = $core->loadContent($hvp->id);
152
            $oldlib = $content['library'];
153
            $oldparams = json_decode($content['params']);
154
        }
155
 
156
        // Make params and library available for core to save.
157
        $hvp->library = H5PCore::libraryFromString($hvp->h5plibrary);
158
        $hvp->library['libraryId'] = $core->h5pF->getLibraryId($hvp->library['machineName'],
159
                                                               $hvp->library['majorVersion'],
160
                                                               $hvp->library['minorVersion']);
161
 
162
        $hvp->id = $core->saveContent((array)$hvp);
163
        // We need to process the parameters to move any images or files and
164
        // to determine which dependencies the content has.
165
 
166
        // Prepare current parameters.
167
        $params = json_decode($hvp->params);
168
 
169
        // Move any uploaded images or files. Determine content dependencies.
170
        $editor->processParameters($hvp, $hvp->library, $params,
171
                                   isset($oldlib) ? $oldlib : null,
172
                                   isset($oldparams) ? $oldparams : null);
173
    }
174
 
175
    return $hvp->id;
176
}
177
 
178
/**
179
 * Removes an instance of the hvp from the database
180
 *
181
 * Given an ID of an instance of this module,
182
 * this function will permanently delete the instance
183
 * and any data that depends on it.
184
 *
185
 * @param int $id Id of the module instance
186
 * @return boolean Success/Failure
187
 */
188
function hvp_delete_instance($id) {
189
    global $DB;
190
 
191
    // Load content record.
192
    if (! $hvp = $DB->get_record('hvp', array('id' => "$id"))) {
193
        return false;
194
    }
195
 
196
    // Load CM.
197
    $cm = \get_coursemodule_from_instance('hvp', $id);
198
 
199
    // Delete content.
200
    $h5pstorage = \mod_hvp\framework::instance('storage');
201
    $h5pstorage->deletePackage(array('id' => $hvp->id, 'slug' => $hvp->slug, 'coursemodule' => $cm->id));
202
 
203
    // Delete xAPI statements.
204
    $DB->delete_records('hvp_xapi_results', array (
205
      'content_id' => $hvp->id
206
    ));
207
 
208
    // Get library details.
209
    $library = $DB->get_record_sql(
210
            "SELECT machine_name AS name, major_version, minor_version
211
               FROM {hvp_libraries}
212
              WHERE id = ?",
213
            array($hvp->main_library_id)
214
    );
215
 
216
    // Only log event if we found library.
217
    if ($library) {
218
        // Log content delete.
219
        new \mod_hvp\event(
220
            'content', 'delete',
221
            $hvp->id, $hvp->name,
222
            $library->name, $library->major_version . '.' . $library->minor_version
223
        );
224
    }
225
 
226
    return true;
227
}
228
 
229
/**
230
 * Serves the files from the hvp file areas
231
 *
232
 * @package mod_hvp
233
 * @category files
234
 *
235
 * @param stdClass $course the course object
236
 * @param stdClass $cm the course module object
237
 * @param stdClass $context the newmodule's context
238
 * @param string $filearea the name of the file area
239
 * @param array $args extra arguments (itemid, path)
240
 * @param bool $forcedownload whether or not force download
241
 * @param array $options additional options affecting the file serving
242
 *
243
 * @return true|false Success
244
 */
245
function hvp_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, $options = array()) {
246
    switch ($filearea) {
247
        default:
248
            return false; // Invalid file area.
249
 
250
        case 'libraries':
251
            if ($context->contextlevel != CONTEXT_SYSTEM) {
252
                return false; // Invalid context.
253
            }
254
 
255
            // Check permissions.
256
            if (!has_capability('mod/hvp:getcachedassets', $context)) {
257
                return false;
258
            }
259
 
260
            $itemid = 0;
261
            break;
262
        case 'cachedassets':
263
            if ($context->contextlevel != CONTEXT_SYSTEM) {
264
                return false; // Invalid context.
265
            }
266
 
267
            // Check permissions.
268
            if (!has_capability('mod/hvp:getcachedassets', $context)) {
269
                return false;
270
            }
271
 
272
            $options['cacheability'] = 'public';
273
            $options['immutable'] = true;
274
 
275
            $itemid = 0;
276
            break;
277
 
278
        case 'content':
279
            if ($context->contextlevel != CONTEXT_MODULE) {
280
                return false; // Invalid context.
281
            }
282
 
283
            // Check permissions.
284
            if (!has_capability('mod/hvp:view', $context)) {
285
                return false;
286
            }
287
 
288
            $itemid = array_shift($args);
289
            break;
290
 
291
        case 'exports':
292
            if ($context->contextlevel != CONTEXT_MODULE) {
293
                return false; // Invalid context.
294
            }
295
 
296
            // Allow download if valid temporary hash.
297
            $ishub = false;
298
            $hub = optional_param('hub', null, PARAM_RAW);
299
            if ($hub) {
300
                list($time, $hash) = explode('.', $hub, 2);
301
                $time = hvp_base64_decode($time);
302
                $hash = hvp_base64_decode($hash);
303
 
304
                $data = $time . ':' . get_config('mod_hvp', 'site_uuid');
305
                $signature = hash_hmac('SHA512', $data, get_config('mod_hvp', 'hub_secret'), true);
306
 
307
                if ($time < (time() - 43200) || !hash_equals($signature, $hash)) {
308
                    // No valid hash.
309
                    return false;
310
                }
311
                $ishub = true;
312
            } else if (!has_capability('mod/hvp:view', $context)) {
313
                // No permission.
314
                return false;
315
            }
316
            // Note that the getexport permission is checked after loading the content.
317
 
318
            // Get core.
319
            $h5pinterface = \mod_hvp\framework::instance('interface');
320
            $h5pcore = \mod_hvp\framework::instance('core');
321
 
322
            $matches = array();
323
 
324
            // Get content id from filename.
325
            if (!preg_match('/(\d*).h5p$/', $args[0], $matches)) {
326
                // Did not find any content ID.
327
                return false;
328
            }
329
 
330
            $contentid = $matches[1];
331
            $content = $h5pinterface->loadContent($contentid);
332
            $displayoptions = $h5pcore->getDisplayOptionsForView($content['disable'], $context->instanceid);
333
 
334
            // Check permissions.
335
            if (!$displayoptions['export'] && !$ishub) {
336
                return false;
337
            }
338
 
339
            $itemid = 0;
340
 
341
            // Change context to course for retrieving file.
342
            $cm = get_coursemodule_from_id('hvp', $context->instanceid);
343
            $context = context_course::instance($cm->course);
344
            break;
345
 
346
        case 'editor':
347
            $cap = ($context->contextlevel === CONTEXT_COURSE ? 'addinstance' : 'manage');
348
 
349
            // Check permissions.
350
            if (!has_capability("mod/hvp:$cap", $context)) {
351
                return false;
352
            }
353
 
354
            $itemid = 0;
355
            break;
356
    }
357
 
358
    $filename = array_pop($args);
359
    $filepath = (!$args ? '/' : '/' .implode('/', $args) . '/');
360
 
361
    $fs = get_file_storage();
362
    $file = $fs->get_file($context->id, 'mod_hvp', $filearea, $itemid, $filepath, $filename);
363
    if (!$file) {
364
        return false; // No such file.
365
    }
366
 
367
    // Totara: use allowxss option to prevent application/x-javascript mimetype
368
    // from being converted to application/x-forcedownload.
369
    $options['allowxss'] = '1';
370
 
371
    send_stored_file($file, 86400, 0, $forcedownload, $options);
372
 
373
    return true;
374
}
375
 
376
/**
377
 * Create/update grade item for given hvp
378
 *
379
 * @category grade
380
 * @param stdClass $hvp object with extra cmidnumber
381
 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
382
 * @return int, 0 if ok, error code otherwise
383
 */
384
function hvp_grade_item_update($hvp, $grades=null) {
385
    global $CFG;
386
 
387
    if (!function_exists('grade_update')) { // Workaround for buggy PHP versions.
388
        require_once($CFG->libdir . '/gradelib.php');
389
    }
390
 
391
    $params = array('itemname' => $hvp->name, 'idnumber' => $hvp->cmidnumber);
392
 
393
    if (isset($hvp->maximumgrade)) {
394
        $params['gradetype'] = GRADE_TYPE_VALUE;
395
        $params['grademax'] = $hvp->maximumgrade;
396
    }
397
 
398
    // Recalculate rawgrade relative to grademax.
399
    if (isset($hvp->rawgrade) && isset($hvp->rawgrademax) && $hvp->rawgrademax != 0) {
400
        // Get max grade Obs: do not try to use grade_get_grades because it
401
        // requires context which we don't have inside an ajax.
402
        $gradeitem = grade_item::fetch(array(
403
            'itemtype' => 'mod',
404
            'itemmodule' => 'hvp',
405
            'iteminstance' => $hvp->id,
406
            'courseid' => $hvp->course
407
        ));
408
 
409
        if (isset($gradeitem) && isset($gradeitem->grademax)) {
410
            $grades->rawgrade = ($hvp->rawgrade / $hvp->rawgrademax) * $gradeitem->grademax;
411
        }
412
    }
413
 
414
    if ($grades === 'reset') {
415
        $params['reset'] = true;
416
        $grades = null;
417
    }
418
 
419
    return grade_update('mod/hvp', $hvp->course, 'mod', 'hvp', $hvp->id, 0, $grades, $params);
420
}
421
 
422
/**
423
 * Update activity grades
424
 *
425
 * @category grade
426
 * @param stdClass $hvp null means all hvps (with extra cmidnumber property)
427
 * @param int $userid specific user only, 0 means all
428
 * @param bool $nullifnone If true and the user has no grade then a grade item with rawgrade == null will be inserted
429
 */
430
function hvp_update_grades($hvp=null, $userid=0, $nullifnone=true) {
431
    if ($userid and $nullifnone) {
432
        $grade = new stdClass();
433
        $grade->userid   = $userid;
434
        $grade->rawgrade = null;
435
        hvp_grade_item_update($hvp, $grade);
436
 
437
    } else {
438
        hvp_grade_item_update($hvp);
439
    }
440
}
441
 
442
/**
443
 * Obtains the automatic completion state for this H5P activity on any conditions
444
 * in settings, such as if a certain grade is achieved.
445
 *
446
 * @param object $course Course
447
 * @param object $cm Course-module
448
 * @param int $userid User ID
449
 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
450
 * @return bool True if completed, false if not. (If no conditions, then return
451
 *   value depends on comparison type)
452
 */
453
function hvp_get_completion_state($course, $cm, $userid, $type) {
454
    global $DB, $CFG;
455
    $hvp = $DB->get_record('hvp', array('id' => $cm->instance), '*', MUST_EXIST);
456
    if (!$hvp->completionpass) {
457
        return $type;
458
    }
459
    // Check for passing grade.
460
    if ($hvp->completionpass) {
461
        require_once($CFG->libdir . '/gradelib.php');
462
        $item = grade_item::fetch(array('courseid' => $course->id, 'itemtype' => 'mod',
463
                'itemmodule' => 'hvp', 'iteminstance' => $cm->instance, 'outcomeid' => null));
464
        if ($item) {
465
            $grades = grade_grade::fetch_users_grades($item, array($userid), false);
466
            if (!empty($grades[$userid])) {
467
                return $grades[$userid]->is_passed($item);
468
            }
469
        }
470
    }
471
    return false;
472
}
473
 
474
/**
475
 * URL compatible base64 decoding.
476
 *
477
 * @param string $string
478
 * @return string
479
 */
480
function hvp_base64_decode($string) {
481
    $r = strlen($string) % 4;
482
    if ($r) {
483
        $l = 4 - $r;
484
        $string .= str_repeat('=', $l);
485
    }
486
    return base64_decode(strtr($string, '-_', '+/'));
487
}
488
 
489
 
490
/**
491
 * This function receives a calendar event and returns the action associated with it, or null if there is none.
492
 *
493
 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
494
 * is not displayed on the block.
495
 *
496
 * @param calendar_event $event
497
 * @param action_factory $factory
498
 * @return action_interface|null
499
 */
500
function mod_hvp_core_calendar_provide_event_action(calendar_event $event, action_factory $factory) {
501
    $cm = get_fast_modinfo($event->courseid)->instances['hvp'][$event->instance];
502
 
503
    $completion = new \completion_info($cm->get_course());
504
 
505
    $completiondata = $completion->get_data($cm, false);
506
 
507
    if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
508
        return null;
509
    }
510
 
511
    return $factory->create_instance(
512
            get_string('view'),
513
            new moodle_url('/mod/hvp/view.php', ['id' => $cm->id]),
514
            1,
515
            true
516
    );
517
}
518