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
 * \mod_hvp\framework class
19
 *
20
 * @package    mod_hvp
21
 * @copyright  2016 Joubel AS
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
namespace mod_hvp;
26
 
27
use H5peditorFile;
28
 
29
defined('MOODLE_INTERNAL') || die();
30
 
31
require_once(__DIR__ . '/../autoloader.php');
32
 
33
/**
34
 * Moodle's implementation of the H5P Editor framework interface.
35
 * Makes it possible for the editor's core library to communicate with the
36
 * database used by Moodle.
37
 *
38
 * @package    mod_hvp
39
 * @copyright  2016 Joubel AS
40
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41
 */
42
class editor_framework implements \H5peditorStorage {
43
 
44
    /**
45
     * Load language file(JSON) from database.
46
     * This is used to translate the editor fields(title, description etc.)
47
     *
48
     * @param string $name The machine readable name of the library(content type)
49
     * @param int $major Major part of version number
50
     * @param int $minor Minor part of version number
51
     * @param string $lang Language code
52
     * @return string Translation in JSON format
53
     */
54
    // @codingStandardsIgnoreLine
55
    public function getLanguage($name, $major, $minor, $lang) {
56
        global $DB;
57
 
58
        // Load translation field from DB.
59
        return $DB->get_field_sql(
60
            "SELECT hlt.language_json
61
               FROM {hvp_libraries_languages} hlt
62
               JOIN {hvp_libraries} hl ON hl.id = hlt.library_id
63
              WHERE hl.machine_name = ?
64
                AND hl.major_version = ?
65
                AND hl.minor_version = ?
66
                AND hlt.language_code = ?
67
            ", array(
68
                $name,
69
                $major,
70
                $minor,
71
                $lang
72
            )
73
        );
74
    }
75
 
76
    /**
77
     * "Callback" for mark the given file as a permanent file.
78
     * Used when saving content that has new uploaded files.
79
     *
80
     * @param int $fileid
81
     */
82
    // @codingStandardsIgnoreLine
83
    public function keepFile($fileid) {
84
        global $DB;
85
 
86
        // Remove from tmpfiles.
87
        $DB->delete_records('hvp_tmpfiles', array(
88
            'id' => $fileid
89
        ));
90
    }
91
 
92
    /**
93
     * Decides which content types the editor should have.
94
     *
95
     * Two usecases:
96
     * 1. No input, will list all the available content types.
97
     * 2. Libraries supported are specified, load additional data and verify
98
     * that the content types are available. Used by e.g. the Presentation Tool
99
     * Editor that already knows which content types are supported in its
100
     * slides.
101
     *
102
     * @param array $libraries List of library names + version to load info for
103
     * @return array List of all libraries loaded
104
     */
105
    // @codingStandardsIgnoreLine
106
    public function getLibraries($libraries = null) {
107
        global $DB;
108
 
109
        $contextid = required_param('contextId', PARAM_RAW);
110
        $superuser = has_capability('mod/hvp:userestrictedlibraries',
111
            \context::instance_by_id($contextid));
112
 
113
        if ($libraries !== null) {
114
            // Get details for the specified libraries only.
115
            $librarieswithdetails = array();
116
            foreach ($libraries as $library) {
117
                // Look for library.
118
                $details = $DB->get_record_sql(
119
                        "SELECT title,
120
                                runnable,
121
                                restricted,
122
                                tutorial_url,
123
                                metadata_settings
124
                           FROM {hvp_libraries}
125
                          WHERE machine_name = ?
126
                            AND major_version = ?
127
                            AND minor_version = ?
128
                            AND semantics IS NOT NULL
129
                        ", array(
130
                            $library->name,
131
                            $library->majorVersion,
132
                            $library->minorVersion
133
                        )
134
                );
135
                if ($details) {
136
                    // Library found, add details to list.
137
                    $library->tutorialUrl = $details->tutorial_url;
138
                    $library->title = $details->title;
139
                    $library->runnable = $details->runnable;
140
                    $library->restricted = $superuser ? false : ($details->restricted === '1' ? true : false);
141
                    $library->metadataSettings = json_decode($details->metadata_settings);
142
                    $librarieswithdetails[] = $library;
143
                }
144
            }
145
 
146
            // Done, return list with library details.
147
            return $librarieswithdetails;
148
        }
149
 
150
        // Load all libraries.
151
        $libraries = array();
152
        $librariesresult = $DB->get_records_sql(
153
                "SELECT id,
154
                        machine_name AS name,
155
                        title,
156
                        major_version,
157
                        minor_version,
158
                        tutorial_url,
159
                        restricted,
160
                        metadata_settings
161
                   FROM {hvp_libraries}
162
                  WHERE runnable = 1
163
                    AND semantics IS NOT NULL
164
               ORDER BY title"
165
        );
166
        foreach ($librariesresult as $library) {
167
            // Remove unique index.
168
            unset($library->id);
169
 
170
            // Convert snakes to camels.
171
            $library->majorVersion = (int) $library->major_version;
172
            unset($library->major_version);
173
            $library->minorVersion = (int) $library->minor_version;
174
            unset($library->minor_version);
175
            if (!empty($library->tutorial_url)) {
176
               $library->tutorialUrl = $library->tutorial_url;
177
            }
178
            unset($library->tutorial_url);
179
 
180
            $library->metadataSettings = json_decode($library->metadata_settings);
181
            unset($library->metadata_settings);
182
 
183
            // Make sure we only display the newest version of a library.
184
            foreach ($libraries as $key => $existinglibrary) {
185
                if ($library->name === $existinglibrary->name) {
186
                    // Found library with same name, check versions.
187
                    if ( ( $library->majorVersion === $existinglibrary->majorVersion &&
188
                           $library->minorVersion > $existinglibrary->minorVersion ) ||
189
                         ( $library->majorVersion > $existinglibrary->majorVersion ) ) {
190
                        // This is a newer version.
191
                        $existinglibrary->isOld = true;
192
                    } else {
193
                        // This is an older version.
194
                        $library->isOld = true;
195
                    }
196
                }
197
            }
198
 
199
            // Check to see if content type should be restricted.
200
            $library->restricted = $superuser ? false : ($library->restricted === '1' ? true : false);
201
 
202
            // Add new library.
203
            $libraries[] = $library;
204
        }
205
        return $libraries;
206
    }
207
 
208
    /**
209
     * Allow for other plugins to decide which styles and scripts are attached.
210
     * This is useful for adding and/or modifing the functionality and look of
211
     * the content types.
212
     *
213
     * @param array $files
214
     *  List of files as objects with path and version as properties
215
     * @param array $libraries
216
     *  List of libraries indexed by machineName with objects as values. The objects
217
     *  have majorVersion and minorVersion as properties.
218
     */
219
    // @codingStandardsIgnoreLine
220
    public function alterLibraryFiles(&$files, $libraries) {
221
        global $PAGE;
222
 
223
        // Refactor dependency list.
224
        $librarylist = array();
225
        foreach ($libraries as $dependency) {
226
            $librarylist[$dependency['machineName']] = array(
227
                'majorVersion' => $dependency['majorVersion'],
228
                'minorVersion' => $dependency['minorVersion']
229
            );
230
        }
231
 
232
        $contextid = required_param('contextId', PARAM_INT);
233
        $context   = \context::instance_by_id($contextid);
234
 
235
        $PAGE->set_context($context);
236
        $renderer = $PAGE->get_renderer('mod_hvp');
237
 
238
        $embedtype = 'editor';
239
        $renderer->hvp_alter_scripts($files['scripts'], $librarylist, $embedtype);
240
        $renderer->hvp_alter_styles($files['styles'], $librarylist, $embedtype);
241
    }
242
 
243
    /**
244
     * Saves a file or moves it temporarily. This is often necessary in order to
245
     * validate and store uploaded or fetched H5Ps.
246
     *
247
     * @param string $data Uri of data that should be saved as a temporary file
248
     * @param boolean $movefile Can be set to TRUE to move the data instead of saving it
249
     *
250
     * @return bool|object Returns false if saving failed or an object with path
251
     * of the directory and file that is temporarily saved
252
     */
253
    // @codingStandardsIgnoreLine
254
    public static function saveFileTemporarily($data, $movefile = false) {
255
        global $CFG;
256
 
257
        // Generate local tmp file path.
258
        $uniqueh5pid = uniqid('hvp-');
259
        $filename = $uniqueh5pid . '.h5p';
260
        $directory = $CFG->tempdir . DIRECTORY_SEPARATOR . $uniqueh5pid;
261
        $filepath = $directory . DIRECTORY_SEPARATOR . $filename;
262
 
263
        if (!is_dir($directory)) {
264
            mkdir($directory, 0777, true);
265
        }
266
 
267
        // Move file or save data to new file so core can validate H5P.
268
        if ($movefile) {
269
            move_uploaded_file($data, $filepath);
270
        } else {
271
            file_put_contents($filepath, $data);
272
        }
273
 
274
        // Add folder and file paths to H5P Core.
275
        $interface = framework::instance('interface');
276
        $interface->getUploadedH5pFolderPath($directory);
277
        $interface->getUploadedH5pPath($directory . DIRECTORY_SEPARATOR . $filename);
278
 
279
        return (object) array(
280
            'dir' => $directory,
281
            'fileName' => $filename
282
        );
283
    }
284
 
285
    /**
286
     * Marks a file for later cleanup, useful when files are not instantly cleaned
287
     * up. E.g. for files that are uploaded through the editor.
288
     *
289
     * @param int $file Id of file that should be cleaned up
290
     * @param int|null $contentid Content id of file
291
     */
292
    // @codingStandardsIgnoreLine
293
    public static function markFileForCleanup($file, $contentid = null) {
294
        global $DB;
295
 
296
        // Let H5P Core clean up.
297
        if ($contentid) {
298
            return;
299
        }
300
 
301
        // Track temporary files for later cleanup.
302
        $DB->insert_record_raw('hvp_tmpfiles', array(
303
            'id' => $file
304
        ), false, false, true);
305
    }
306
 
307
    /**
308
     * Clean up temporary files
309
     *
310
     * @param string $filepath Path to file or directory
311
     */
312
    // @codingStandardsIgnoreLine
313
    public static function removeTemporarilySavedFiles($filepath) {
314
        if (is_dir($filepath)) {
315
            \H5PCore::deleteFileTree($filepath);
316
        } else {
317
            @unlink($filepath);
318
        }
319
    }
320
 
321
    /**
322
     * Load a list of available language codes from the database.
323
     *
324
     * @param string $machineName The machine readable name of the library(content type)
325
     * @param int $majorVersion Major part of version number
326
     * @param int $minorVersion Minor part of version number
327
     *
328
     * @return array List of possible language codes
329
     * @throws \dml_exception
330
     */
331
    public function getAvailableLanguages($machineName, $majorVersion, $minorVersion) {
332
        global $DB;
333
 
334
        $sql = "SELECT language_code
335
                  FROM {hvp_libraries_languages} hlt
336
                  JOIN {hvp_libraries} hl
337
                    ON hl.id = hlt.library_id
338
                 WHERE hl.machine_name = :machinename
339
                   AND hl.major_version = :major
340
                   AND hl.minor_version = :minor";
341
 
342
        $results = $DB->get_records_sql($sql, array(
343
            'machinename' => $machineName,
344
            'major'       => $majorVersion,
345
            'minor'       => $minorVersion,
346
        ));
347
 
348
        $codes = array('en'); // Semantics is 'en' by default.
349
        foreach ($results as $result) {
350
            $codes[] = $result->language_code;
351
        }
352
 
353
        return $codes;
354
    }
355
}