Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | 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
 * This plugin is used to access equella repositories.
19
 *
20
 * @since Moodle 2.3
21
 * @package    repository_equella
22
 * @copyright  2012 Dongsheng Cai {@link http://dongsheng.org}
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
defined('MOODLE_INTERNAL') || die();
27
 
28
require_once($CFG->dirroot . '/repository/lib.php');
29
 
30
/**
31
 * repository_equella class implements equella_client
32
 *
33
 * @since Moodle 2.3
34
 * @package    repository_equella
35
 * @copyright  2012 Dongsheng Cai {@link http://dongsheng.org}
36
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37
 */
38
class repository_equella extends repository {
39
    /** @var array mimetype filter */
40
    private $mimetypes = array();
41
 
42
    /**
43
     * Constructor
44
     *
45
     * @param int $repositoryid repository instance id
46
     * @param int|stdClass $context a context id or context object
47
     * @param array $options repository options
48
     */
49
    public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array()) {
50
        parent::__construct($repositoryid, $context, $options);
51
 
52
        if (isset($this->options['mimetypes'])) {
53
            $mt = $this->options['mimetypes'];
54
            if (!empty($mt) && is_array($mt) && !in_array('*', $mt)) {
55
                $this->mimetypes = array_unique(array_map(array($this, 'to_mime_type'), $mt));
56
            }
57
        }
58
    }
59
 
60
    /**
61
     * Display embedded equella interface
62
     *
63
     * @param string $path
64
     * @param mixed $page
65
     * @return array
66
     */
67
    public function get_listing($path = null, $page = null) {
68
        global $COURSE;
69
        $callbackurl = new moodle_url('/repository/equella/callback.php', array('repo_id'=>$this->id));
70
 
71
        $mimetypesstr = '';
72
        $restrict = '';
73
        if (!empty($this->mimetypes)) {
74
            $mimetypesstr = '&mimeTypes=' . implode(',', $this->mimetypes);
75
            // We're restricting to a mime type, so we always restrict to selecting resources only.
76
            $restrict = '&attachmentonly=true';
77
        } else if ($this->get_option('equella_select_restriction') != 'none') {
78
            // The option value matches the EQUELLA paramter name.
79
            $restrict = '&' . $this->get_option('equella_select_restriction') . '=true';
80
        }
81
 
82
        $url = $this->get_option('equella_url')
83
                . '?method=lms'
84
                . '&returnurl='.urlencode($callbackurl)
85
                . '&returnprefix=tle'
86
                . '&template=standard'
87
                . '&token='.urlencode($this->getssotoken('write'))
88
                . '&courseId='.urlencode($COURSE->idnumber)
89
                . '&courseCode='.urlencode($COURSE->shortname)
90
                . '&action=searchThin'
91
                . '&forcePost=true'
92
                . '&cancelDisabled=true'
93
                . '&attachmentUuidUrls=true'
94
                . '&options='.urlencode($this->get_option('equella_options') . $mimetypesstr)
95
                . $restrict;
96
 
97
        $manageurl = $this->get_option('equella_url');
98
        $manageurl = str_ireplace('signon.do', 'logon.do', $manageurl);
99
        $manageurl = $this->appendtoken($manageurl);
100
 
101
        $list = array();
102
        $list['object'] = array();
103
        $list['object']['type'] = 'text/html';
104
        $list['object']['src'] = $url;
105
        $list['nologin']  = true;
106
        $list['nosearch'] = true;
107
        $list['norefresh'] = true;
108
        $list['manage'] = $manageurl;
109
        return $list;
110
    }
111
 
112
    /**
113
     * Supported equella file types
114
     *
115
     * @return int
116
     */
117
    public function supported_returntypes() {
118
        return (FILE_INTERNAL | FILE_REFERENCE);
119
    }
120
 
121
    /**
122
     * Prepare file reference information
123
     *
124
     * @param string $source
125
     * @return string file referece
126
     */
127
    public function get_file_reference($source) {
128
        // Internally we store serialized value but user input is json-encoded for security reasons.
129
        $ref = json_decode(base64_decode($source));
130
        $filename  = clean_param($ref->filename, PARAM_FILE);
131
        $url = clean_param($ref->url, PARAM_URL);
132
        return base64_encode(serialize((object)array('url' => $url, 'filename' => $filename)));
133
    }
134
 
135
    /**
136
     * Counts the number of failed connections.
137
     *
138
     * If we received the connection timeout more than 3 times in a row, we don't attemt to
139
     * connect to the server any more during this request.
140
     *
141
     * This function is used by {@link repository_equella::sync_reference()} that
142
     * synchronises the file size of referenced files.
143
     *
144
     * @param int $errno omit if we just want to know the return value, the last curl_errno otherwise
145
     * @return bool true if we had less than 3 failed connections, false if no more connections
146
     * attempts recommended
147
     */
148
    private function connection_result($errno = null) {
149
        static $countfailures = array();
150
        $sess = sesskey();
151
        if (!array_key_exists($sess, $countfailures)) {
152
            $countfailures[$sess] = 0;
153
        }
154
        if ($errno !== null) {
155
            if ($errno == 0) {
156
                // reset count of failed connections
157
                $countfailures[$sess] = 0;
158
            } else if ($errno == 7 /*CURLE_COULDNT_CONNECT*/ || $errno == 9 /*CURLE_REMOTE_ACCESS_DENIED*/) {
159
                // problems with server
160
                $countfailures[$sess]++;
161
            }
162
        }
163
        return ($countfailures[$sess] < 3);
164
    }
165
 
166
    /**
1441 ariadna 167
     * Returned unserialized object from base64 encoded file reference data
168
     *
169
     * @param string $reference
170
     * @return stdClass
171
     */
172
    private function unserialize_reference(string $reference): stdClass {
173
        $decoded = base64_decode($reference);
174
        return unserialize_object($decoded);
175
    }
176
 
177
    /**
1 efrain 178
     * Download a file, this function can be overridden by subclass. {@link curl}
179
     *
180
     * @param string $reference the source of the file
181
     * @param string $filename filename (without path) to save the downloaded file in the
182
     * temporary directory
183
     * @return null|array null if download failed or array with elements:
184
     *   path: internal location of the file
185
     *   url: URL to the source (from parameters)
186
     */
187
    public function get_file($reference, $filename = '') {
188
        global $USER, $CFG;
1441 ariadna 189
        $ref = $this->unserialize_reference($reference);
1 efrain 190
        if (!isset($ref->url) || !($url = $this->appendtoken($ref->url))) {
191
            // Occurs when the user isn't known..
192
            return null;
193
        }
194
        $path = $this->prepare_file($filename);
195
        $cookiepathname = $this->prepare_file($USER->id. '_'. uniqid('', true). '.cookie');
196
        $c = new curl(array('cookie'=>$cookiepathname));
197
        $result = $c->download_one($url, null, array('filepath' => $path, 'followlocation' => true, 'timeout' => $CFG->repositorygetfiletimeout));
198
        // Delete cookie jar.
199
        if (file_exists($cookiepathname)) {
200
            unlink($cookiepathname);
201
        }
202
        if ($result !== true) {
203
            throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
204
        }
205
        return array('path'=>$path, 'url'=>$url);
206
    }
207
 
208
    public function sync_reference(stored_file $file) {
209
        global $USER, $CFG;
210
        if ($file->get_referencelastsync() + DAYSECS > time() || !$this->connection_result()) {
211
            // Synchronise not more often than once a day.
212
            // if we had several unsuccessfull attempts to connect to server - do not try any more.
213
            return false;
214
        }
1441 ariadna 215
        $ref = $this->unserialize_reference($file->get_reference());
1 efrain 216
        if (!isset($ref->url) || !($url = $this->appendtoken($ref->url))) {
217
            // Occurs when the user isn't known..
218
            $file->set_missingsource();
219
            return true;
220
        }
221
 
222
        $cookiepathname = $this->prepare_file($USER->id. '_'. uniqid('', true). '.cookie');
223
        $c = new curl(array('cookie' => $cookiepathname));
224
        if (file_extension_in_typegroup($ref->filename, 'web_image')) {
225
            $path = $this->prepare_file('');
226
            $result = $c->download_one($url, null, array('filepath' => $path, 'followlocation' => true, 'timeout' => $CFG->repositorysyncimagetimeout));
227
            if ($result === true) {
228
                $file->set_synchronised_content_from_file($path);
229
                return true;
230
            }
231
        } else {
232
            $result = $c->head($url, array('followlocation' => true, 'timeout' => $CFG->repositorysyncfiletimeout));
233
        }
234
        // Delete cookie jar.
235
        if (file_exists($cookiepathname)) {
236
            unlink($cookiepathname);
237
        }
238
 
239
        $this->connection_result($c->get_errno());
240
        $curlinfo = $c->get_info();
241
        if (isset($curlinfo['http_code']) && $curlinfo['http_code'] == 200
242
                && array_key_exists('download_content_length', $curlinfo)
243
                && $curlinfo['download_content_length'] >= 0) {
244
            // we received a correct header and at least can tell the file size
245
            $file->set_synchronized(null, $curlinfo['download_content_length']);
246
            return true;
247
        }
248
        $file->set_missingsource();
249
        return true;
250
    }
251
 
252
    /**
253
     * Repository method to serve the referenced file
254
     *
255
     * @param stored_file $storedfile the file that contains the reference
256
     * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
257
     * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
258
     * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
259
     * @param array $options additional options affecting the file serving
260
     */
1441 ariadna 261
    public function send_file($stored_file, $lifetime=null , $filter=0, $forcedownload=false, ?array $options = null) {
262
        $ref = $this->unserialize_reference($stored_file->get_reference());
263
        if (isset($ref->url) && $url = $this->appendtoken($ref->url)) {
1 efrain 264
            header('Location: ' . $url);
265
        } else {
266
            send_file_not_found();
267
        }
268
    }
269
 
270
    /**
271
     * Add Instance settings input to Moodle form
272
     *
273
     * @param MoodleQuickForm $mform
274
     */
275
    public static function instance_config_form($mform) {
276
        global $CFG;
277
        require_once("{$CFG->dirroot}/user/profile/lib.php");
278
 
279
        $mform->addElement('text', 'equella_url', get_string('equellaurl', 'repository_equella'));
280
        $mform->setType('equella_url', PARAM_URL);
281
 
282
        $strrequired = get_string('required');
283
        $mform->addRule('equella_url', $strrequired, 'required', null, 'client');
284
 
285
        $userfieldoptions = ['default' => get_string('equellausername', 'repository_equella')];
286
        foreach (profile_get_custom_fields() as $field) {
287
            if ($field->datatype != 'text') {
288
                continue;
289
            }
290
            $userfieldoptions[$field->shortname] = format_string($field->name, true, ['context' => context_system::instance()]);
291
        }
292
        $mform->addElement('select', 'equella_userfield', get_string('equellauserfield', 'repository_equella'), $userfieldoptions);
293
        $mform->setDefault('equella_userfield', $userfieldoptions['default']);
294
        $mform->addHelpButton('equella_userfield', 'equellauserfield', 'repository_equella');
295
 
296
        $mform->addElement('text', 'equella_options', get_string('equellaoptions', 'repository_equella'));
297
        $mform->setType('equella_options', PARAM_NOTAGS);
298
 
299
        $choices = array(
300
            'none' => get_string('restrictionnone', 'repository_equella'),
301
            'itemonly' => get_string('restrictionitemsonly', 'repository_equella'),
302
            'attachmentonly' => get_string('restrictionattachmentsonly', 'repository_equella'),
303
        );
304
        $mform->addElement('select', 'equella_select_restriction', get_string('selectrestriction', 'repository_equella'), $choices);
305
 
306
        $mform->addElement('header', 'groupheader',
307
            get_string('group', 'repository_equella', get_string('groupdefault', 'repository_equella')));
308
        $mform->addElement('text', 'equella_shareid', get_string('sharedid', 'repository_equella'));
309
        $mform->setType('equella_shareid', PARAM_RAW);
310
        $mform->addRule('equella_shareid', $strrequired, 'required', null, 'client');
311
 
312
        $mform->addElement('text', 'equella_sharedsecret', get_string('sharedsecrets', 'repository_equella'));
313
        $mform->setType('equella_sharedsecret', PARAM_RAW);
314
        $mform->addRule('equella_sharedsecret', $strrequired, 'required', null, 'client');
315
 
316
        foreach (self::get_all_editing_roles() as $role) {
317
            $mform->addElement('header', 'groupheader_'.$role->shortname, get_string('group', 'repository_equella',
318
                role_get_name($role)));
319
            $mform->addElement('text', "equella_{$role->shortname}_shareid", get_string('sharedid', 'repository_equella'));
320
            $mform->setType("equella_{$role->shortname}_shareid", PARAM_RAW);
321
            $mform->addElement('text', "equella_{$role->shortname}_sharedsecret",
322
                get_string('sharedsecrets', 'repository_equella'));
323
            $mform->setType("equella_{$role->shortname}_sharedsecret", PARAM_RAW);
324
        }
325
    }
326
 
327
    /**
328
     * Names of the instance settings
329
     *
330
     * @return array
331
     */
332
    public static function get_instance_option_names() {
333
        $rv = array('equella_url', 'equella_select_restriction', 'equella_options',
334
            'equella_shareid', 'equella_sharedsecret', 'equella_userfield',
335
        );
336
 
337
        foreach (self::get_all_editing_roles() as $role) {
338
            array_push($rv, "equella_{$role->shortname}_shareid");
339
            array_push($rv, "equella_{$role->shortname}_sharedsecret");
340
        }
341
 
342
        return $rv;
343
    }
344
 
345
    /**
346
     * Generate equella token
347
     *
348
     * @param string $username
349
     * @param string $shareid
350
     * @param string $sharedsecret
351
     * @return string
352
     */
353
    private static function getssotoken_raw($username, $shareid, $sharedsecret) {
354
        $time = time() . '000';
355
        return urlencode($username)
356
            . ':'
357
            . $shareid
358
            . ':'
359
            . $time
360
            . ':'
361
            . base64_encode(pack('H*', md5($username . $shareid . $time . $sharedsecret)));
362
    }
363
 
364
    /**
365
     * Append token
366
     *
367
     * @param string $url
368
     * @param $readwrite
369
     * @return string
370
     */
371
    private function appendtoken($url, $readwrite = null) {
372
        $ssotoken = $this->getssotoken($readwrite);
373
        if (!$ssotoken) {
374
            return false;
375
        }
376
        return $url . (strpos($url, '?') != false ? '&' : '?') . 'token=' . urlencode($ssotoken);
377
    }
378
 
379
    /**
380
     * Generate equella sso token
381
     *
382
     * @param string $readwrite
383
     * @return string
384
     */
385
    private function getssotoken($readwrite = 'read') {
386
        global $USER;
387
 
388
        if (empty($USER->username)) {
389
            return false;
390
        }
391
        $equellauserfield = $this->get_userfield_value();
392
        if ($readwrite == 'write') {
393
 
394
            foreach (self::get_all_editing_roles() as $role) {
395
                if (user_has_role_assignment($USER->id, $role->id, $this->context->id)) {
396
                    // See if the user has a role that is linked to an equella role.
397
                    $shareid = $this->get_option("equella_{$role->shortname}_shareid");
398
                    if (!empty($shareid)) {
399
                        return $this->getssotoken_raw($equellauserfield, $shareid,
400
                            $this->get_option("equella_{$role->shortname}_sharedsecret"));
401
                    }
402
                }
403
            }
404
        }
405
        // If we are only reading, use the unadorned shareid and secret.
406
        $shareid = $this->get_option('equella_shareid');
407
        if (!empty($shareid)) {
408
            return $this->getssotoken_raw($equellauserfield, $shareid, $this->get_option('equella_sharedsecret'));
409
        }
410
    }
411
 
412
    private static function get_all_editing_roles() {
413
        return get_roles_with_capability('moodle/course:manageactivities', CAP_ALLOW);
414
    }
415
 
416
    /**
417
     * Convert moodle mimetypes list to equella format
418
     *
419
     * @param string $value
420
     * @return string
421
     */
422
    private static function to_mime_type($value) {
423
        return mimeinfo('type', $value);
424
    }
425
 
426
    /**
427
     * Return the source information
428
     *
429
     * @param string $source
430
     * @return string|null
431
     */
432
    public function get_file_source_info($source) {
433
        $ref = json_decode(base64_decode($source));
434
        $filename  = clean_param($ref->filename, PARAM_FILE);
435
        return 'EQUELLA: ' . $filename;
436
    }
437
 
438
    /**
439
     * Return human readable reference information
440
     * {@link stored_file::get_reference()}
441
     *
442
     * @param string $reference
443
     * @param int $filestatus status of the file, 0 - ok, 666 - source missing
444
     * @return string
445
     */
446
    public function get_reference_details($reference, $filestatus = 0) {
447
        if (!$filestatus) {
1441 ariadna 448
            $ref = $this->unserialize_reference($reference);
449
            return $this->get_name(). ': '. ($ref->filename ?? '');
1 efrain 450
        } else {
451
            return get_string('lostsource', 'repository', '');
452
        }
453
    }
454
 
455
    /**
456
     * Is this repository accessing private data?
457
     *
458
     * @return bool
459
     */
460
    public function contains_private_data() {
461
        return false;
462
    }
463
 
464
    /**
465
     * Retrieve the userfield/username.
466
     *
467
     * @return string
468
     */
469
    public function get_userfield_value(): string {
470
        global $USER;
471
        $userfield = $this->get_option('equella_userfield');
472
        if ($userfield != 'default' && isset($USER->profile[$userfield])) {
473
            return $USER->profile[$userfield];
474
        } else {
475
            return $USER->username;
476
        }
477
    }
478
}