Completed
Pull Request — master (#339)
by Jesus
04:50 queued 02:10
created

locallib.php ➔ bigbluebuttonbn_check_opencast()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 5
nop 1
dl 0
loc 19
rs 8.8333
c 0
b 0
f 0
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
 * Internal library of functions for module BigBlueButtonBN.
19
 *
20
 * @package   mod_bigbluebuttonbn
21
 * @copyright 2010 onwards, Blindside Networks Inc
22
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 * @author    Jesus Federico  (jesus [at] blindsidenetworks [dt] com)
24
 * @author    Fred Dixon  (ffdixon [at] blindsidenetworks [dt] com)
25
 */
26
27
use mod_bigbluebuttonbn\locallib;
28
use mod_bigbluebuttonbn\plugin;
29
use mod_bigbluebuttonbn\task;
30
31
defined('MOODLE_INTERNAL') || die;
32
33
global $CFG;
34
35
require_once(__DIR__ . '/lib.php');
36
37
/** @var BIGBLUEBUTTONBN_UPDATE_CACHE boolean set to true indicates that cache has to be updated */
38
const BIGBLUEBUTTONBN_UPDATE_CACHE = true;
39
/** @var BIGBLUEBUTTONBN_TYPE_ALL integer set to 0 defines an instance type that inclueds room and recordings */
40
const BIGBLUEBUTTONBN_TYPE_ALL = 0;
41
/** @var BIGBLUEBUTTONBN_TYPE_ROOM_ONLY integer set to 1 defines an instance type that inclueds only room */
42
const BIGBLUEBUTTONBN_TYPE_ROOM_ONLY = 1;
43
/** @var BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY integer set to 2 defines an instance type that inclueds only recordings */
44
const BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY = 2;
45
/** @var BIGBLUEBUTTONBN_ROLE_VIEWER string defines the bigbluebutton viewer role */
46
const BIGBLUEBUTTONBN_ROLE_VIEWER = 'viewer';
47
/** @var BIGBLUEBUTTONBN_ROLE_MODERATOR string defines the bigbluebutton moderator role */
48
const BIGBLUEBUTTONBN_ROLE_MODERATOR = 'moderator';
49
/** @var BIGBLUEBUTTON_EVENT_ACTIVITY_VIEWED string defines the bigbluebuttonbn activity_viewed event */
50
const BIGBLUEBUTTON_EVENT_ACTIVITY_VIEWED = 'activity_viewed';
51
/** @var BIGBLUEBUTTON_EVENT_ACTIVITY_MANAGEMENT_VIEWED string defines the bigbluebuttonbn activity_management_viewed event */
52
const BIGBLUEBUTTON_EVENT_ACTIVITY_MANAGEMENT_VIEWED = 'activity_management_viewed';
53
/** @var BIGBLUEBUTTON_EVENT_LIVE_SESSION string defines the bigbluebuttonbn live_session event */
54
const BIGBLUEBUTTON_EVENT_LIVE_SESSION = 'live_session';
55
/** @var BIGBLUEBUTTON_EVENT_MEETING_CREATED string defines the bigbluebuttonbn meeting_created event */
56
const BIGBLUEBUTTON_EVENT_MEETING_CREATED = 'meeting_created';
57
/** @var BIGBLUEBUTTON_EVENT_MEETING_ENDED string defines the bigbluebuttonbn meeting_ended event */
58
const BIGBLUEBUTTON_EVENT_MEETING_ENDED = 'meeting_ended';
59
/** @var BIGBLUEBUTTON_EVENT_MEETING_JOINED string defines the bigbluebuttonbn meeting_joined event */
60
const BIGBLUEBUTTON_EVENT_MEETING_JOINED = 'meeting_joined';
61
/** @var BIGBLUEBUTTON_EVENT_MEETING_LEFT string defines the bigbluebuttonbn meeting_left event */
62
const BIGBLUEBUTTON_EVENT_MEETING_LEFT = 'meeting_left';
63
/** @var BIGBLUEBUTTON_EVENT_RECORDING_DELETED string defines the bigbluebuttonbn recording_deleted event */
64
const BIGBLUEBUTTON_EVENT_RECORDING_DELETED = 'recording_deleted';
65
/** @var BIGBLUEBUTTON_EVENT_RECORDING_IMPORTED string defines the bigbluebuttonbn recording_imported event */
66
const BIGBLUEBUTTON_EVENT_RECORDING_IMPORTED = 'recording_imported';
67
/** @var BIGBLUEBUTTON_EVENT_RECORDING_PROTECTED string defines the bigbluebuttonbn recording_protected event */
68
const BIGBLUEBUTTON_EVENT_RECORDING_PROTECTED = 'recording_protected';
69
/** @var BIGBLUEBUTTON_EVENT_RECORDING_PUBLISHED string defines the bigbluebuttonbn recording_published event */
70
const BIGBLUEBUTTON_EVENT_RECORDING_PUBLISHED = 'recording_published';
71
/** @var BIGBLUEBUTTON_EVENT_RECORDING_UNPROTECTED string defines the bigbluebuttonbn recording_unprotected event */
72
const BIGBLUEBUTTON_EVENT_RECORDING_UNPROTECTED = 'recording_unprotected';
73
/** @var BIGBLUEBUTTON_EVENT_RECORDING_UNPUBLISHED string defines the bigbluebuttonbn recording_unpublished event */
74
const BIGBLUEBUTTON_EVENT_RECORDING_UNPUBLISHED = 'recording_unpublished';
75
/** @var BIGBLUEBUTTON_EVENT_RECORDING_EDITED string defines the bigbluebuttonbn recording_edited event */
76
const BIGBLUEBUTTON_EVENT_RECORDING_EDITED = 'recording_edited';
77
/** @var BIGBLUEBUTTON_EVENT_RECORDING_VIEWED string defines the bigbluebuttonbn recording_viewed event */
78
const BIGBLUEBUTTON_EVENT_RECORDING_VIEWED = 'recording_viewed';
79
/** @var BIGBLUEBUTTON_EVENT_MEETING_START string defines the bigbluebuttonbn meeting_start event */
80
const BIGBLUEBUTTON_EVENT_MEETING_START = 'meeting_start';
81
/** @var BIGBLUEBUTTON_CLIENTTYPE_FLASH integer that defines the bigbluebuttonbn default web client based on Adobe FLASH */
82
const BIGBLUEBUTTON_CLIENTTYPE_FLASH = 0;
83
/** @var BIGBLUEBUTTON_CLIENTTYPE_HTML5 integer that defines the bigbluebuttonbn default web client based on HTML5 */
84
const BIGBLUEBUTTON_CLIENTTYPE_HTML5 = 1;
85
/** @var BIGBLUEBUTTON_ORIGIN_BASE integer set to 0 defines that the user acceded the session from activity page */
86
const BIGBLUEBUTTON_ORIGIN_BASE = 0;
87
/** @var BIGBLUEBUTTON_ORIGIN_TIMELINE integer set to 1 defines that the user acceded the session from Timeline */
88
const BIGBLUEBUTTON_ORIGIN_TIMELINE = 1;
89
/** @var BIGBLUEBUTTON_ORIGIN_INDEX integer set to 2 defines that the user acceded the session from Index */
90
const BIGBLUEBUTTON_ORIGIN_INDEX = 2;
91
92
/**
93
 * Builds and retunrs a url for joining a bigbluebutton meeting.
94
 *
95
 * @param string $meetingid
96
 * @param string $username
97
 * @param string $pw
98
 * @param string $logouturl
99
 * @param string $configtoken
100
 * @param string $userid
101
 * @param string $clienttype
102
 * @param string $createtime
103
 *
104
 * @return string
105
 */
106
function bigbluebuttonbn_get_join_url(
107
    $meetingid,
108
    $username,
109
    $pw,
110
    $logouturl,
111
    $configtoken = null,
112
    $userid = null,
113
    $clienttype = BIGBLUEBUTTON_CLIENTTYPE_FLASH,
114
    $createtime = null
115
) {
116
    $data = ['meetingID' => $meetingid,
117
        'fullName' => $username,
118
        'password' => $pw,
119
        'logoutURL' => $logouturl,
120
    ];
121
    // Choose between Adobe Flash or HTML5 Client.
122
    if ($clienttype == BIGBLUEBUTTON_CLIENTTYPE_HTML5) {
123
        $data['joinViaHtml5'] = 'true';
124
    }
125
    if (!is_null($configtoken)) {
126
        $data['configToken'] = $configtoken;
127
    }
128
    if (!is_null($userid)) {
129
        $data['userID'] = $userid;
130
    }
131
    if (!is_null($createtime)) {
132
        $data['createTime'] = $createtime;
133
    }
134
    return \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('join', $data);
135
}
136
137
/**
138
 * Creates a bigbluebutton meeting and returns the response in an array.
139
 *
140
 * @param array  $data
141
 * @param array  $metadata
142
 * @param string $pname
143
 * @param string $purl
144
 *
145
 * @return array
146
 */
147
function bigbluebuttonbn_get_create_meeting_array($data, $metadata = array(), $pname = null, $purl = null) {
148
    $createmeetingurl = \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('create', $data, $metadata);
149
    $method = 'GET';
150
    $payload = null;
151
    if (!is_null($pname) && !is_null($purl)) {
152
        $method = 'POST';
153
        $payload = "<?xml version='1.0' encoding='UTF-8'?><modules><module name='presentation'><document url='".
154
            $purl."' /></module></modules>";
155
    }
156
    $xml = bigbluebuttonbn_wrap_xml_load_file($createmeetingurl, $method, $payload);
157
    if ($xml) {
158
        $response = array('returncode' => $xml->returncode, 'message' => $xml->message, 'messageKey' => $xml->messageKey);
159
        if ($xml->meetingID) {
160
            $response += array('meetingID' => $xml->meetingID, 'attendeePW' => $xml->attendeePW,
161
                'moderatorPW' => $xml->moderatorPW, 'hasBeenForciblyEnded' => $xml->hasBeenForciblyEnded);
162
        }
163
        return $response;
164
    }
165
    return array('returncode' => 'FAILED', 'message' => 'unreachable', 'messageKey' => 'Server is unreachable');
166
}
167
168
/**
169
 * Fetch meeting info and wrap response in array.
170
 *
171
 * @param string $meetingid
172
 *
173
 * @return array
174
 */
175
function bigbluebuttonbn_get_meeting_info_array($meetingid) {
176
    $xml = bigbluebuttonbn_wrap_xml_load_file(
177
        \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('getMeetingInfo', ['meetingID' => $meetingid])
178
    );
179
    if ($xml && $xml->returncode == 'SUCCESS' && empty($xml->messageKey)) {
180
        // Meeting info was returned.
181
        return array('returncode' => $xml->returncode,
182
            'meetingID' => $xml->meetingID,
183
            'moderatorPW' => $xml->moderatorPW,
184
            'attendeePW' => $xml->attendeePW,
185
            'hasBeenForciblyEnded' => $xml->hasBeenForciblyEnded,
186
            'running' => $xml->running,
187
            'recording' => $xml->recording,
188
            'startTime' => $xml->startTime,
189
            'endTime' => $xml->endTime,
190
            'participantCount' => $xml->participantCount,
191
            'moderatorCount' => $xml->moderatorCount,
192
            'attendees' => $xml->attendees,
193
            'metadata' => $xml->metadata,
194
        );
195
    }
196
    if ($xml) {
197
        // Either failure or success without meeting info.
198
        return (array) $xml;
199
    }
200
    // If the server is unreachable, then prompts the user of the necessary action.
201
    return array('returncode' => 'FAILED', 'message' => 'unreachable', 'messageKey' => 'Server is unreachable');
202
}
203
204
/**
205
 * Helper function to retrieve recordings from a BigBlueButton server.
206
 *
207
 * @param string|array $meetingids   list of meetingIDs "mid1,mid2,mid3" or array("mid1","mid2","mid3")
208
 * @param string|array $recordingids list of $recordingids "rid1,rid2,rid3" or array("rid1","rid2","rid3") for filtering
209
 *
210
 * @return associative array with recordings indexed by recordID, each recording is a non sequential associative array
211
 */
212
function bigbluebuttonbn_get_recordings_array($meetingids, $recordingids = []) {
213
    $meetingidsarray = $meetingids;
214
    if (!is_array($meetingids)) {
215
        $meetingidsarray = explode(',', $meetingids);
216
    }
217
    // If $meetingidsarray is empty there is no need to go further.
218
    if (empty($meetingidsarray)) {
219
        return array();
220
    }
221
    $recordings = bigbluebuttonbn_get_recordings_array_fetch($meetingidsarray);
0 ignored issues
show
Bug introduced by
It seems like $meetingidsarray defined by $meetingids on line 213 can also be of type string; however, bigbluebuttonbn_get_recordings_array_fetch() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
222
    // Sort recordings.
223
    uasort($recordings, 'bigbluebuttonbn_recording_build_sorter');
224
    // Filter recordings based on recordingIDs.
225
    $recordingidsarray = $recordingids;
226
    if (!is_array($recordingids)) {
227
        $recordingidsarray = explode(',', $recordingids);
228
    }
229
    if (empty($recordingidsarray)) {
230
        // No recording ids, no need to filter.
231
        return $recordings;
232
    }
233
    return bigbluebuttonbn_get_recordings_array_filter($recordingidsarray, $recordings);
0 ignored issues
show
Bug introduced by
It seems like $recordingidsarray defined by $recordingids on line 225 can also be of type string; however, bigbluebuttonbn_get_recordings_array_filter() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
234
}
235
236
/**
237
 * Helper function to fetch recordings from a BigBlueButton server.
238
 *
239
 * @param array $meetingidsarray array with meeting ids in the form array("mid1","mid2","mid3")
240
 *
241
 * @return array (associative) with recordings indexed by recordID, each recording is a non sequential associative array
242
 */
243
function bigbluebuttonbn_get_recordings_array_fetch($meetingidsarray) {
244
    if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)
245
            || defined('BEHAT_SITE_RUNNING')
246
            || defined('BEHAT_TEST')
247
            || defined('BEHAT_UTIL')) {
248
        // Just return the fake recording.
249
        global $CFG;
250
        require_once($CFG->libdir . '/testing/generator/lib.php');
251
        require_once(__DIR__ . '/tests/generator/lib.php');
252
        return mod_bigbluebuttonbn_generator::bigbluebuttonbn_get_recordings_array_fetch($meetingidsarray);
253
    }
254
    $recordings = array();
255
    // Execute a paginated getRecordings request.
256
    $pagecount = 25;
257
    $pages = floor(count($meetingidsarray) / $pagecount) + 1;
258
    if (count($meetingidsarray) > 0 && count($meetingidsarray) % $pagecount == 0) {
259
        $pages--;
260
    }
261
    for ($page = 1; $page <= $pages; ++$page) {
262
        $mids = array_slice($meetingidsarray, ($page - 1) * $pagecount, $pagecount);
263
        $recordings += bigbluebuttonbn_get_recordings_array_fetch_page($mids);
264
    }
265
    return $recordings;
266
}
267
268
/**
269
 * Helper function to fetch one page of upto 25 recordings from a BigBlueButton server.
270
 *
271
 * @param array  $mids
272
 *
273
 * @return array
274
 */
275
function bigbluebuttonbn_get_recordings_array_fetch_page($mids) {
276
    $recordings = array();
277
    // Do getRecordings is executed using a method GET (supported by all versions of BBB).
278
    $url = \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('getRecordings', ['meetingID' => implode(',', $mids)]);
279
    $xml = bigbluebuttonbn_wrap_xml_load_file($url);
280
    if ($xml && $xml->returncode == 'SUCCESS' && isset($xml->recordings)) {
281
        // If there were meetings already created.
282
        foreach ($xml->recordings->recording as $recordingxml) {
283
            $recording = bigbluebuttonbn_get_recording_array_value($recordingxml);
284
            $recordings[$recording['recordID']] = $recording;
285
286
            // Check if there is childs.
287
            if (isset($recordingxml->breakoutRooms->breakoutRoom)) {
288
                foreach ($recordingxml->breakoutRooms->breakoutRoom as $breakoutroom) {
289
                    $url = \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url(
290
                        'getRecordings',
291
                        ['recordID' => implode(',', (array) $breakoutroom)]
292
                    );
293
                    $xml = bigbluebuttonbn_wrap_xml_load_file($url);
294
                    if ($xml && $xml->returncode == 'SUCCESS' && isset($xml->recordings)) {
295
                        // If there were meetings already created.
296
                        foreach ($xml->recordings->recording as $recordingxml) {
297
                            $recording = bigbluebuttonbn_get_recording_array_value($recordingxml);
298
                            $recordings[$recording['recordID']] = $recording;
299
                        }
300
                    }
301
                }
302
            }
303
        }
304
    }
305
    return $recordings;
306
}
307
308
/**
309
 * Helper function to remove a set of recordings from an array.
310
 *
311
 * @param array  $rids
312
 * @param array  $recordings
313
 *
314
 * @return array
315
 */
316
function bigbluebuttonbn_get_recordings_array_filter($rids, &$recordings) {
317
    foreach ($recordings as $key => $recording) {
318
        if (!in_array($recording['recordID'], $rids)) {
319
            unset($recordings[$key]);
320
        }
321
    }
322
    return $recordings;
323
}
324
325
/**
326
 * Helper function to retrieve imported recordings from the Moodle database.
327
 * The references are stored as events in bigbluebuttonbn_logs.
328
 *
329
 * @param string $courseid
330
 * @param string $bigbluebuttonbnid
331
 * @param bool   $subset
332
 *
333
 * @return associative array with imported recordings indexed by recordID, each recording
334
 * is a non sequential associative array that corresponds to the actual recording in BBB
335
 */
336
function bigbluebuttonbn_get_recordings_imported_array($courseid = 0, $bigbluebuttonbnid = null, $subset = true) {
337
    global $DB;
338
    $select = bigbluebuttonbn_get_recordings_imported_sql_select($courseid, $bigbluebuttonbnid, $subset);
339
    $recordsimported = $DB->get_records_select('bigbluebuttonbn_logs', $select);
340
    $recordsimportedarray = array();
341
    foreach ($recordsimported as $recordimported) {
342
        $meta = json_decode($recordimported->meta, true);
343
        $recording = $meta['recording'];
344
        // Override imported flag with actual ID.
345
        $recording['imported'] = $recordimported->id;
346
        if (isset($recordimported->protected)) {
347
            $recording['protected'] = (string) $recordimported->protected;
348
        }
349
        $recordsimportedarray[$recording['recordID']] = $recording;
350
    }
351
    return $recordsimportedarray;
352
}
353
354
/**
355
 * Helper function to retrive the default config.xml file.
356
 *
357
 * @return string
358
 */
359
function bigbluebuttonbn_get_default_config_xml() {
360
    $xml = bigbluebuttonbn_wrap_xml_load_file(
361
        \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('getDefaultConfigXML')
362
    );
363
    return $xml;
364
}
365
366
/**
367
 * Helper function to convert an xml recording object to an array in the format used by the plugin.
368
 *
369
 * @param object $recording
370
 *
371
 * @return array
372
 */
373
function bigbluebuttonbn_get_recording_array_value($recording) {
374
    // Add formats.
375
    $playbackarray = array();
376
    foreach ($recording->playback->format as $format) {
377
        $playbackarray[(string) $format->type] = array('type' => (string) $format->type,
378
            'url' => trim((string) $format->url), 'length' => (string) $format->length);
379
        // Add preview per format when existing.
380
        if ($format->preview) {
381
            $playbackarray[(string) $format->type]['preview'] = bigbluebuttonbn_get_recording_preview_images($format->preview);
382
        }
383
    }
384
    // Add the metadata to the recordings array.
385
    $metadataarray = bigbluebuttonbn_get_recording_array_meta(get_object_vars($recording->metadata));
386
    $recordingarray = array('recordID' => (string) $recording->recordID,
387
        'meetingID' => (string) $recording->meetingID, 'meetingName' => (string) $recording->name,
388
        'published' => (string) $recording->published, 'startTime' => (string) $recording->startTime,
389
        'endTime' => (string) $recording->endTime, 'playbacks' => $playbackarray);
390
    if (isset($recording->protected)) {
391
        $recordingarray['protected'] = (string) $recording->protected;
392
    }
393
    return $recordingarray + $metadataarray;
394
}
395
396
/**
397
 * Helper function to convert an xml recording preview images to an array in the format used by the plugin.
398
 *
399
 * @param object $preview
400
 *
401
 * @return array
402
 */
403
function bigbluebuttonbn_get_recording_preview_images($preview) {
404
    $imagesarray = array();
405
    foreach ($preview->images->image as $image) {
406
        $imagearray = array('url' => trim((string) $image));
407
        foreach ($image->attributes() as $attkey => $attvalue) {
408
            $imagearray[$attkey] = (string) $attvalue;
409
        }
410
        array_push($imagesarray, $imagearray);
411
    }
412
    return $imagesarray;
413
}
414
415
/**
416
 * Helper function to convert an xml recording metadata object to an array in the format used by the plugin.
417
 *
418
 * @param array $metadata
419
 *
420
 * @return array
421
 */
422
function bigbluebuttonbn_get_recording_array_meta($metadata) {
423
    $metadataarray = array();
424
    foreach ($metadata as $key => $value) {
425
        if (is_object($value)) {
426
            $value = '';
427
        }
428
        $metadataarray['meta_' . $key] = $value;
429
    }
430
    return $metadataarray;
431
}
432
433
/**
434
 * Helper function to sort an array of recordings. It compares the startTime in two recording objecs.
435
 *
436
 * @param object $a
437
 * @param object $b
438
 *
439
 * @return array
440
 */
441
function bigbluebuttonbn_recording_build_sorter($a, $b) {
442
    global $CFG;
443
    $resultless = !empty($CFG->bigbluebuttonbn_recordings_sortorder) ? -1 : 1;
444
    $resultmore = !empty($CFG->bigbluebuttonbn_recordings_sortorder) ? 1 : -1;
445
    if ($a['startTime'] < $b['startTime']) {
446
        return $resultless;
447
    }
448
    if ($a['startTime'] == $b['startTime']) {
449
        return 0;
450
    }
451
    return $resultmore;
452
}
453
454
/**
455
 * Perform deleteRecordings on BBB.
456
 *
457
 * @param string $recordids
458
 *
459
 * @return boolean
460
 */
461 View Code Duplication
function bigbluebuttonbn_delete_recordings($recordids) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
462
    $ids = explode(',', $recordids);
463
    foreach ($ids as $id) {
464
        $xml = bigbluebuttonbn_wrap_xml_load_file(
465
            \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('deleteRecordings', ['recordID' => $id])
466
        );
467
        if ($xml && $xml->returncode != 'SUCCESS') {
468
            return false;
469
        }
470
    }
471
    return true;
472
}
473
474
/**
475
 * Perform publishRecordings on BBB.
476
 *
477
 * @param string $recordids
478
 * @param string $publish
479
 */
480 View Code Duplication
function bigbluebuttonbn_publish_recordings($recordids, $publish = 'true') {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
481
    $ids = explode(',', $recordids);
482
    foreach ($ids as $id) {
483
        $xml = bigbluebuttonbn_wrap_xml_load_file(
484
            \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('publishRecordings', ['recordID' => $id, 'publish' => $publish])
485
        );
486
        if ($xml && $xml->returncode != 'SUCCESS') {
487
            return false;
488
        }
489
    }
490
    return true;
491
}
492
493
/**
494
 * Perform updateRecordings on BBB.
495
 *
496
 * @param string $recordids
497
 * @param array $params ['key'=>param_key, 'value']
498
 */
499 View Code Duplication
function bigbluebuttonbn_update_recordings($recordids, $params) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
500
    $ids = explode(',', $recordids);
501
    foreach ($ids as $id) {
502
        $xml = bigbluebuttonbn_wrap_xml_load_file(
503
            \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('updateRecordings', ['recordID' => $id] + (array) $params)
504
        );
505
        if ($xml && $xml->returncode != 'SUCCESS') {
506
            return false;
507
        }
508
    }
509
    return true;
510
}
511
512
/**
513
 * Perform end on BBB.
514
 *
515
 * @param string $meetingid
516
 * @param string $modpw
517
 */
518
function bigbluebuttonbn_end_meeting($meetingid, $modpw) {
519
    $xml = bigbluebuttonbn_wrap_xml_load_file(
520
        \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('end', ['meetingID' => $meetingid, 'password' => $modpw])
521
    );
522
    if ($xml) {
523
        // If the xml packet returned failure it displays the message to the user.
524
        return array('returncode' => $xml->returncode, 'message' => $xml->message, 'messageKey' => $xml->messageKey);
525
    }
526
    // If the server is unreachable, then prompts the user of the necessary action.
527
    return null;
528
}
529
530
/**
531
 * Perform api request on BBB.
532
 *
533
 * @return string
534
 */
535
function bigbluebuttonbn_get_server_version() {
536
    $xml = bigbluebuttonbn_wrap_xml_load_file(
537
        \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url()
538
    );
539
    if ($xml && $xml->returncode == 'SUCCESS') {
540
        return $xml->version;
541
    }
542
    return null;
543
}
544
545
/**
546
 * Perform api request on BBB and wraps the response in an XML object
547
 *
548
 * @param string $url
549
 * @param string $method
550
 * @param string $data
551
 * @param string $contenttype
552
 *
553
 * @return object
554
 */
555
function bigbluebuttonbn_wrap_xml_load_file($url, $method = 'GET', $data = null, $contenttype = 'text/xml') {
556
    if (extension_loaded('curl')) {
557
        $response = bigbluebuttonbn_wrap_xml_load_file_curl_request($url, $method, $data, $contenttype);
558
        if (!$response) {
559
            debugging('No response on wrap_simplexml_load_file', DEBUG_DEVELOPER);
560
            return null;
561
        }
562
        $previous = libxml_use_internal_errors(true);
563
        try {
564
            $xml = simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
565
            return $xml;
566
        } catch (Exception $e) {
567
            libxml_use_internal_errors($previous);
568
            $error = 'Caught exception: ' . $e->getMessage();
569
            debugging($error, DEBUG_DEVELOPER);
570
            return null;
571
        }
572
    }
573
    // Alternative request non CURL based.
574
    $previous = libxml_use_internal_errors(true);
575
    try {
576
        $response = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
577
        return $response;
578
    } catch (Exception $e) {
579
        $error = 'Caught exception: ' . $e->getMessage();
580
        debugging($error, DEBUG_DEVELOPER);
581
        libxml_use_internal_errors($previous);
582
        return null;
583
    }
584
}
585
586
/**
587
 * Perform api request on BBB using CURL and wraps the response in an XML object
588
 *
589
 * @param string $url
590
 * @param string $method
591
 * @param string $data
592
 * @param string $contenttype
593
 *
594
 * @return object
595
 */
596
function bigbluebuttonbn_wrap_xml_load_file_curl_request($url, $method = 'GET', $data = null, $contenttype = 'text/xml') {
597
    global $CFG;
598
    require_once($CFG->libdir . '/filelib.php');
599
    $c = new curl();
600
    $c->setopt(array('SSL_VERIFYPEER' => true));
601
    if ($method == 'POST') {
602
        if (is_null($data) || is_array($data)) {
603
            return $c->post($url);
604
        }
605
        $options = array();
606
        $options['CURLOPT_HTTPHEADER'] = array(
607
            'Content-Type: ' . $contenttype,
608
            'Content-Length: ' . strlen($data),
609
            'Content-Language: en-US',
610
        );
611
612
        return $c->post($url, $data, $options);
613
    }
614
    if ($method == 'HEAD') {
615
        $c->head($url, array('followlocation' => true, 'timeout' => 1));
616
        return $c->get_info();
617
    }
618
    return $c->get($url);
619
}
620
621
/**
622
 * End the session associated with this instance (if it's running).
623
 *
624
 * @param object $bigbluebuttonbn
625
 *
626
 * @return void
627
 */
628
function bigbluebuttonbn_end_meeting_if_running($bigbluebuttonbn) {
629
    $meetingid = $bigbluebuttonbn->meetingid . '-' . $bigbluebuttonbn->course . '-' . $bigbluebuttonbn->id;
630
    if (bigbluebuttonbn_is_meeting_running($meetingid)) {
631
        bigbluebuttonbn_end_meeting($meetingid, $bigbluebuttonbn->moderatorpass);
632
    }
633
}
634
635
/**
636
 * Returns user roles in a context.
637
 *
638
 * @param object $context
639
 * @param integer $userid
640
 *
641
 * @return array $userroles
642
 */
643
function bigbluebuttonbn_get_user_roles($context, $userid) {
644
    global $DB;
645
    $userroles = get_user_roles($context, $userid);
646
    if ($userroles) {
647
        $where = '';
648
        foreach ($userroles as $userrole) {
649
            $where .= (empty($where) ? ' WHERE' : ' OR') . ' id=' . $userrole->roleid;
650
        }
651
        $userroles = $DB->get_records_sql('SELECT * FROM {role}' . $where);
652
    }
653
    return $userroles;
654
}
655
656
/**
657
 * Returns guest role wrapped in an array.
658
 *
659
 * @return array
660
 */
661
function bigbluebuttonbn_get_guest_role() {
662
    $guestrole = get_guest_role();
663
    return array($guestrole->id => $guestrole);
664
}
665
666
/**
667
 * Returns an array containing all the users in a context.
668
 *
669
 * @param context $context
670
 *
671
 * @return array $users
672
 */
673
function bigbluebuttonbn_get_users(context $context = null) {
674
    $users = (array) get_enrolled_users($context, '', 0, 'u.*', null, 0, 0, true);
675
    foreach ($users as $key => $value) {
676
        $users[$key] = fullname($value);
677
    }
678
    return $users;
679
}
680
681
/**
682
 * Returns an array containing all the users in a context wrapped for html select element.
683
 *
684
 * @param context_course $context
685
 * @param null $bbactivity
686
 * @return array $users
687
 * @throws coding_exception
688
 * @throws moodle_exception
689
 */
690
function bigbluebuttonbn_get_users_select(context_course $context, $bbactivity = null) {
691
    // CONTRIB-7972, check the group of current user and course group mode.
692
    $groups = null;
0 ignored issues
show
Unused Code introduced by
$groups is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
693
    $users = (array) get_enrolled_users($context, '', 0, 'u.*', null, 0, 0, true);
694
    $course = get_course($context->instanceid);
695
    $groupmode = groups_get_course_groupmode($course);
696
    if ($bbactivity) {
697
        list($bbcourse, $cm) = get_course_and_cm_from_instance($bbactivity->id, 'bigbluebuttonbn');
0 ignored issues
show
Unused Code introduced by
The assignment to $bbcourse is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
698
        $groupmode = groups_get_activity_groupmode($cm);
699
700
    }
701
    if ($groupmode == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $context)) {
702
        global $USER;
703
        $groups = groups_get_all_groups($course->id, $USER->id);
704
        $users = [];
705
        foreach ($groups as $g) {
706
            $users += (array) get_enrolled_users($context, '', $g->id, 'u.*', null, 0, 0, true);
707
        }
708
    }
709
    return array_map(
710
            function($u) {
711
                return array('id' => $u->id, 'name' => fullname($u));
712
            },
713
            $users);
714
}
715
716
/**
717
 * Returns an array containing all the roles in a context.
718
 *
719
 * @param context $context
720
 * @param bool $onlyviewableroles
721
 *
722
 * @return array $roles
723
 */
724
function bigbluebuttonbn_get_roles(context $context = null, bool $onlyviewableroles = true) {
725
    global $CFG;
726
727
    if ($onlyviewableroles == true && $CFG->branch >= 35) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
728
        $roles = (array) get_viewable_roles($context);
729
        foreach ($roles as $key => $value) {
730
            $roles[$key] = $value;
731
        }
732
    } else {
733
        $roles = (array) role_get_names($context);
734
        foreach ($roles as $key => $value) {
735
            $roles[$key] = $value->localname;
736
        }
737
    }
738
739
    return $roles;
740
}
741
742
/**
743
 * Returns an array containing all the roles in a context wrapped for html select element.
744
 *
745
 * @param context $context
746
 * @param bool $onlyviewableroles
747
 *
748
 * @return array $users
749
 */
750
function bigbluebuttonbn_get_roles_select(context $context = null, bool $onlyviewableroles = true) {
751
    global $CFG;
752
753
    if ($onlyviewableroles == true && $CFG->branch >= 35) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
754
        $roles = (array) get_viewable_roles($context);
755
        foreach ($roles as $key => $value) {
756
            $roles[$key] = array('id' => $key, 'name' => $value);
757
        }
758
    } else {
759
        $roles = (array) role_get_names($context);
760
        foreach ($roles as $key => $value) {
761
            $roles[$key] = array('id' => $value->id, 'name' => $value->localname);
762
        }
763
    }
764
765
    return $roles;
766
}
767
768
/**
769
 * Returns role that corresponds to an id.
770
 *
771
 * @param string|integer $id
772
 *
773
 * @return object $role
774
 */
775
function bigbluebuttonbn_get_role($id) {
776
    $roles = (array) role_get_names();
777
    if (is_numeric($id) && isset($roles[$id])) {
778
        return (object) $roles[$id];
779
    }
780
    foreach ($roles as $role) {
781
        if ($role->shortname == $id) {
782
            return $role;
783
        }
784
    }
785
}
786
787
/**
788
 * Returns an array to populate a list of participants used in mod_form.js.
789
 *
790
 * @param context $context
791
 * @param null|object $bbactivity
792
 * @return array $data
793
 */
794
function bigbluebuttonbn_get_participant_data($context, $bbactivity = null) {
795
    $data = array(
796
        'all' => array(
797
            'name' => get_string('mod_form_field_participant_list_type_all', 'bigbluebuttonbn'),
798
            'children' => []
799
        ),
800
    );
801
    $data['role'] = array(
802
        'name' => get_string('mod_form_field_participant_list_type_role', 'bigbluebuttonbn'),
803
        'children' => bigbluebuttonbn_get_roles_select($context, true)
804
      );
805
    $data['user'] = array(
806
        'name' => get_string('mod_form_field_participant_list_type_user', 'bigbluebuttonbn'),
807
        'children' => bigbluebuttonbn_get_users_select($context, $bbactivity),
0 ignored issues
show
Bug introduced by
It seems like $bbactivity defined by parameter $bbactivity on line 794 can also be of type object; however, bigbluebuttonbn_get_users_select() does only seem to accept null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
808
    );
809
    return $data;
810
}
811
812
/**
813
 * Returns an array to populate a list of participants used in mod_form.php.
814
 *
815
 * @param object $bigbluebuttonbn
816
 * @param context $context
817
 *
818
 * @return array
819
 */
820
function bigbluebuttonbn_get_participant_list($bigbluebuttonbn, $context) {
821
    global $USER;
822
    if ($bigbluebuttonbn == null) {
823
        return bigbluebuttonbn_get_participant_rules_encoded(
824
            bigbluebuttonbn_get_participant_list_default($context, $USER->id)
825
        );
826
    }
827
    if (empty($bigbluebuttonbn->participants)) {
828
        $bigbluebuttonbn->participants = "[]";
829
    }
830
    $rules = json_decode($bigbluebuttonbn->participants, true);
831
    if (empty($rules)) {
832
        $rules = bigbluebuttonbn_get_participant_list_default($context, bigbluebuttonbn_instance_ownerid($bigbluebuttonbn));
833
    }
834
    return bigbluebuttonbn_get_participant_rules_encoded($rules);
835
}
836
837
/**
838
 * Returns an array to populate a list of participants used in mod_form.php with default values.
839
 *
840
 * @param context $context
841
 * @param integer $ownerid
842
 *
843
 * @return array
844
 */
845
function bigbluebuttonbn_get_participant_list_default($context, $ownerid = null) {
846
    $participantlist = array();
847
    $participantlist[] = array(
848
        'selectiontype' => 'all',
849
        'selectionid' => 'all',
850
        'role' => BIGBLUEBUTTONBN_ROLE_VIEWER,
851
    );
852
    $defaultrules = explode(',', \mod_bigbluebuttonbn\locallib\config::get('participant_moderator_default'));
853
    foreach ($defaultrules as $defaultrule) {
854
        if ($defaultrule == '0') {
855
            if (!empty($ownerid) && is_enrolled($context, $ownerid)) {
856
                $participantlist[] = array(
857
                    'selectiontype' => 'user',
858
                    'selectionid' => (string) $ownerid,
859
                    'role' => BIGBLUEBUTTONBN_ROLE_MODERATOR);
860
            }
861
            continue;
862
        }
863
        $participantlist[] = array(
864
            'selectiontype' => 'role',
865
            'selectionid' => $defaultrule,
866
            'role' => BIGBLUEBUTTONBN_ROLE_MODERATOR);
867
    }
868
    return $participantlist;
869
}
870
871
/**
872
 * Returns an array to populate a list of participants used in mod_form.php with bigbluebuttonbn values.
873
 *
874
 * @param array $rules
875
 *
876
 * @return array
877
 */
878
function bigbluebuttonbn_get_participant_rules_encoded($rules) {
879
    foreach ($rules as $key => $rule) {
880
        if ($rule['selectiontype'] !== 'role' || is_numeric($rule['selectionid'])) {
881
            continue;
882
        }
883
        $role = bigbluebuttonbn_get_role($rule['selectionid']);
884
        if ($role == null) {
885
            unset($rules[$key]);
886
            continue;
887
        }
888
        $rule['selectionid'] = $role->id;
889
        $rules[$key] = $rule;
890
    }
891
    return $rules;
892
}
893
894
/**
895
 * Returns an array to populate a list of participant_selection used in mod_form.php.
896
 *
897
 * @return array
898
 */
899
function bigbluebuttonbn_get_participant_selection_data() {
900
    return [
901
        'type_options' => [
902
            'all' => get_string('mod_form_field_participant_list_type_all', 'bigbluebuttonbn'),
903
            'role' => get_string('mod_form_field_participant_list_type_role', 'bigbluebuttonbn'),
904
            'user' => get_string('mod_form_field_participant_list_type_user', 'bigbluebuttonbn'),
905
        ],
906
        'type_selected' => 'all',
907
        'options' => ['all' => '---------------'],
908
        'selected' => 'all',
909
    ];
910
}
911
912
/**
913
 * Evaluate if a user in a context is moderator based on roles and participation rules.
914
 *
915
 * @param context $context
916
 * @param array $participantlist
917
 * @param integer $userid
918
 *
919
 * @return boolean
920
 */
921
function bigbluebuttonbn_is_moderator($context, $participantlist, $userid = null) {
922
    global $USER;
923
    if (!is_array($participantlist)) {
924
        return false;
925
    }
926
    if (empty($userid)) {
927
        $userid = $USER->id;
928
    }
929
    $userroles = bigbluebuttonbn_get_guest_role();
930
    if (!isguestuser()) {
931
        $userroles = bigbluebuttonbn_get_user_roles($context, $userid);
932
    }
933
    return bigbluebuttonbn_is_moderator_validator($participantlist, $userid, $userroles);
934
}
935
936
/**
937
 * Iterates participant list rules to evaluate if a user is moderator.
938
 *
939
 * @param array $participantlist
940
 * @param integer $userid
941
 * @param array $userroles
942
 *
943
 * @return boolean
944
 */
945
function bigbluebuttonbn_is_moderator_validator($participantlist, $userid, $userroles) {
946
    // Iterate participant rules.
947
    foreach ($participantlist as $participant) {
948
        if (bigbluebuttonbn_is_moderator_validate_rule($participant, $userid, $userroles)) {
949
            return true;
950
        }
951
    }
952
    return false;
953
}
954
955
/**
956
 * Evaluate if a user is moderator based on roles and a particular participation rule.
957
 *
958
 * @param object $participant
959
 * @param integer $userid
960
 * @param array $userroles
961
 *
962
 * @return boolean
963
 */
964
function bigbluebuttonbn_is_moderator_validate_rule($participant, $userid, $userroles) {
965
    if ($participant['role'] == BIGBLUEBUTTONBN_ROLE_VIEWER) {
966
        return false;
967
    }
968
    // Validation for the 'all' rule.
969
    if ($participant['selectiontype'] == 'all') {
970
        return true;
971
    }
972
    // Validation for a 'user' rule.
973
    if ($participant['selectiontype'] == 'user') {
974
        if ($participant['selectionid'] == $userid) {
975
            return true;
976
        }
977
        return false;
978
    }
979
    // Validation for a 'role' rule.
980
    $role = bigbluebuttonbn_get_role($participant['selectionid']);
981
    if ($role != null && array_key_exists($role->id, $userroles)) {
982
        return true;
983
    }
984
    return false;
985
}
986
987
/**
988
 * Helper returns error message key for the language file that corresponds to a bigbluebutton error key.
989
 *
990
 * @param string $messagekey
991
 * @param string $defaultkey
992
 *
993
 * @return string
994
 */
995
function bigbluebuttonbn_get_error_key($messagekey, $defaultkey = null) {
996
    if ($messagekey == 'checksumError') {
997
        return 'index_error_checksum';
998
    }
999
    if ($messagekey == 'maxConcurrent') {
1000
        return 'view_error_max_concurrent';
1001
    }
1002
    return $defaultkey;
1003
}
1004
1005
/**
1006
 * Helper evaluates if a voicebridge number is unique.
1007
 *
1008
 * @param integer $instance
1009
 * @param integer $voicebridge
1010
 *
1011
 * @return string
1012
 */
1013
function bigbluebuttonbn_voicebridge_unique($instance, $voicebridge) {
1014
    global $DB;
1015
    if ($voicebridge == 0) {
1016
        return true;
1017
    }
1018
    $select = 'voicebridge = ' . $voicebridge;
1019
    if ($instance != 0) {
1020
        $select .= ' AND id <>' . $instance;
1021
    }
1022
    if (!$DB->get_records_select('bigbluebuttonbn', $select)) {
1023
        return true;
1024
    }
1025
    return false;
1026
}
1027
1028
/**
1029
 * Helper estimate a duration for the meeting based on the closingtime.
1030
 *
1031
 * @param integer $closingtime
1032
 *
1033
 * @return integer
1034
 */
1035
function bigbluebuttonbn_get_duration($closingtime) {
1036
    $duration = 0;
1037
    $now = time();
1038
    if ($closingtime > 0 && $now < $closingtime) {
1039
        $duration = ceil(($closingtime - $now) / 60);
1040
        $compensationtime = intval((int) \mod_bigbluebuttonbn\locallib\config::get('scheduled_duration_compensation'));
1041
        $duration = intval($duration) + $compensationtime;
1042
    }
1043
    return $duration;
1044
}
1045
1046
/**
1047
 * Helper return array containing the file descriptor for a preuploaded presentation.
1048
 *
1049
 * @param context $context
1050
 * @param string $presentation
1051
 * @param integer $id
1052
 *
1053
 * @return array
1054
 */
1055
function bigbluebuttonbn_get_presentation_array($context, $presentation, $id = null) {
1056
    global $CFG;
1057
    if (empty($presentation)) {
1058
        if ($CFG->bigbluebuttonbn_preuploadpresentation_enabled) {
1059
            // Item has not presentation but presentation is enabled..
1060
            // Check if exist some file by default in general mod setting ("presentationdefault").
1061
            $fs = get_file_storage();
1062
            $files = $fs->get_area_files(
1063
                context_system::instance()->id,
1064
                'mod_bigbluebuttonbn',
1065
                'presentationdefault',
1066
                0,
1067
                "filename",
1068
                false
1069
            );
1070
1071 View Code Duplication
            if (count($files) == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1072
                // Not exist file by default in "presentationbydefault" setting.
1073
                return array('url' => null, 'name' => null, 'icon' => null, 'mimetype_description' => null);
1074
            }
1075
1076
            // Exists file in general setting to use as default for presentation. Cache image for temp public access.
1077
            $file = reset($files);
1078
            unset($files);
1079
            $pnoncevalue = null;
1080 View Code Duplication
            if (!is_null($id)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1081
                // Create the nonce component for granting a temporary public access.
1082
                $cache = cache::make_from_params(
1083
                    cache_store::MODE_APPLICATION,
1084
                    'mod_bigbluebuttonbn',
1085
                    'presentationdefault_cache'
1086
                );
1087
                $pnoncekey = sha1(context_system::instance()->id);
1088
                /* The item id was adapted for granting public access to the presentation once in order
1089
                 * to allow BigBlueButton to gather the file. */
1090
                $pnoncevalue = bigbluebuttonbn_generate_nonce();
1091
                $cache->set($pnoncekey, array('value' => $pnoncevalue, 'counter' => 0));
1092
            }
1093
1094
            $url = moodle_url::make_pluginfile_url(
1095
                $file->get_contextid(),
1096
                $file->get_component(),
1097
                $file->get_filearea(),
1098
                $pnoncevalue,
1099
                $file->get_filepath(),
1100
                $file->get_filename()
1101
            );
1102
            return (array('name' => $file->get_filename(), 'icon' => file_file_icon($file, 24),
1103
                'url' => $url->out(false), 'mimetype_description' => get_mimetype_description($file)));
1104
        }
1105
1106
        return array('url' => null, 'name' => null, 'icon' => null, 'mimetype_description' => null);
1107
    }
1108
    $fs = get_file_storage();
1109
    $files = $fs->get_area_files(
1110
        $context->id,
1111
        'mod_bigbluebuttonbn',
1112
        'presentation',
1113
        0,
1114
        'itemid, filepath, filename',
1115
        false
1116
    );
1117 View Code Duplication
    if (count($files) == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1118
        return array('url' => null, 'name' => null, 'icon' => null, 'mimetype_description' => null);
1119
    }
1120
    $file = reset($files);
1121
    unset($files);
1122
    $pnoncevalue = null;
1123 View Code Duplication
    if (!is_null($id)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1124
        // Create the nonce component for granting a temporary public access.
1125
        $cache = cache::make_from_params(
1126
            cache_store::MODE_APPLICATION,
1127
            'mod_bigbluebuttonbn',
1128
            'presentation_cache'
1129
        );
1130
        $pnoncekey = sha1($id);
1131
        /* The item id was adapted for granting public access to the presentation once in order
1132
         * to allow BigBlueButton to gather the file. */
1133
        $pnoncevalue = bigbluebuttonbn_generate_nonce();
1134
        $cache->set($pnoncekey, array('value' => $pnoncevalue, 'counter' => 0));
1135
    }
1136
    $url = moodle_url::make_pluginfile_url(
1137
        $file->get_contextid(),
1138
        $file->get_component(),
1139
        $file->get_filearea(),
1140
        $pnoncevalue,
1141
        $file->get_filepath(),
1142
        $file->get_filename()
1143
    );
1144
    return array('name' => $file->get_filename(), 'icon' => file_file_icon($file, 24),
1145
        'url' => $url->out(false), 'mimetype_description' => get_mimetype_description($file));
1146
}
1147
1148
/**
1149
 * Helper generates a nonce used for the preuploaded presentation callback url.
1150
 *
1151
 * @return string
1152
 */
1153
function bigbluebuttonbn_generate_nonce() {
1154
    $mt = microtime();
1155
    $rand = mt_rand();
1156
    return md5($mt . $rand);
1157
}
1158
1159
/**
1160
 * Helper generates a random password.
1161
 *
1162
 * @param integer $length
1163
 * @param string $unique
1164
 *
1165
 * @return string
1166
 */
1167
function bigbluebuttonbn_random_password($length = 8, $unique = "") {
1168
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
1169
    do {
1170
        $password = substr(str_shuffle($chars), 0, $length);
1171
    } while ($unique == $password);
1172
    return $password;
1173
}
1174
1175
/**
1176
 * Helper register a bigbluebuttonbn event.
1177
 *
1178
 * @param string $type
1179
 * @param object $bigbluebuttonbn
1180
 * @param array $options [timecreated, userid, other]
1181
 *
1182
 * @return void
1183
 */
1184
function bigbluebuttonbn_event_log($type, $bigbluebuttonbn, $options = []) {
1185
    global $DB;
1186
    if (!in_array($type, \mod_bigbluebuttonbn\event\events::$events)) {
1187
        // No log will be created.
1188
        return;
1189
    }
1190
    $course = $DB->get_record('course', array('id' => $bigbluebuttonbn->course), '*', MUST_EXIST);
1191
    $cm = get_coursemodule_from_instance('bigbluebuttonbn', $bigbluebuttonbn->id, $course->id, false, MUST_EXIST);
1192
    $context = context_module::instance($cm->id);
1193
    $params = array('context' => $context, 'objectid' => $bigbluebuttonbn->id);
1194
    if (array_key_exists('timecreated', $options)) {
1195
        $params['timecreated'] = $options['timecreated'];
1196
    }
1197
    if (array_key_exists('userid', $options)) {
1198
        $params['userid'] = $options['userid'];
1199
    }
1200
    if (array_key_exists('other', $options)) {
1201
        $params['other'] = $options['other'];
1202
    }
1203
    $event = call_user_func_array(
1204
        '\mod_bigbluebuttonbn\event\\' . $type . '::create',
1205
        array($params)
1206
    );
1207
    $event->add_record_snapshot('course_modules', $cm);
1208
    $event->add_record_snapshot('course', $course);
1209
    $event->add_record_snapshot('bigbluebuttonbn', $bigbluebuttonbn);
1210
    $event->trigger();
1211
}
1212
1213
/**
1214
 * Updates the meeting info cached object when a participant has joined.
1215
 *
1216
 * @param string $meetingid
1217
 * @param bool $ismoderator
1218
 *
1219
 * @return void
1220
 */
1221
function bigbluebuttonbn_participant_joined($meetingid, $ismoderator) {
1222
    $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', 'meetings_cache');
1223
    $result = $cache->get($meetingid);
1224
    $meetinginfo = json_decode($result['meeting_info']);
1225
    $meetinginfo->participantCount += 1;
1226
    if ($ismoderator) {
1227
        $meetinginfo->moderatorCount += 1;
1228
    }
1229
    $cache->set($meetingid, array('creation_time' => $result['creation_time'],
1230
        'meeting_info' => json_encode($meetinginfo)));
1231
}
1232
1233
/**
1234
 * Gets a meeting info object cached or fetched from the live session.
1235
 *
1236
 * @param string $meetingid
1237
 * @param boolean $updatecache
1238
 *
1239
 * @return array
1240
 */
1241
function bigbluebuttonbn_get_meeting_info($meetingid, $updatecache = false) {
1242
    $cachettl = (int) \mod_bigbluebuttonbn\locallib\config::get('waitformoderator_cache_ttl');
1243
    $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', 'meetings_cache');
1244
    $result = $cache->get($meetingid);
1245
    $now = time();
1246
    if (!$updatecache && !empty($result) && $now < ($result['creation_time'] + $cachettl)) {
1247
        // Use the value in the cache.
1248
        return (array) json_decode($result['meeting_info']);
1249
    }
1250
    // Ping again and refresh the cache.
1251
    $meetinginfo = (array) bigbluebuttonbn_wrap_xml_load_file(
1252
        \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('getMeetingInfo', ['meetingID' => $meetingid])
1253
    );
1254
    $cache->set($meetingid, array('creation_time' => time(), 'meeting_info' => json_encode($meetinginfo)));
1255
    return $meetinginfo;
1256
}
1257
1258
/**
1259
 * Perform isMeetingRunning on BBB.
1260
 *
1261
 * @param string $meetingid
1262
 * @param boolean $updatecache
1263
 *
1264
 * @return boolean
1265
 */
1266
function bigbluebuttonbn_is_meeting_running($meetingid, $updatecache = false) {
1267
    /* As a workaround to isMeetingRunning that always return SUCCESS but only returns true
1268
     * when at least one user is in the session, we use getMeetingInfo instead.
1269
     */
1270
    $meetinginfo = bigbluebuttonbn_get_meeting_info($meetingid, $updatecache);
1271
    return ($meetinginfo['returncode'] === 'SUCCESS');
1272
}
1273
1274
/**
1275
 * Publish an imported recording.
1276
 *
1277
 * @param string $id
1278
 * @param boolean $publish
1279
 *
1280
 * @return boolean
1281
 */
1282 View Code Duplication
function bigbluebuttonbn_publish_recording_imported($id, $publish = true) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1283
    global $DB;
1284
    // Locate the record to be updated.
1285
    $record = $DB->get_record('bigbluebuttonbn_logs', array('id' => $id));
1286
    $meta = json_decode($record->meta, true);
1287
    // Prepare data for the update.
1288
    $meta['recording']['published'] = ($publish) ? 'true' : 'false';
1289
    $record->meta = json_encode($meta);
1290
    // Proceed with the update.
1291
    $DB->update_record('bigbluebuttonbn_logs', $record);
1292
    return true;
1293
}
1294
1295
/**
1296
 * Delete an imported recording.
1297
 *
1298
 * @param string $id
1299
 *
1300
 * @return boolean
1301
 */
1302
function bigbluebuttonbn_delete_recording_imported($id) {
1303
    global $DB;
1304
    // Execute delete.
1305
    $DB->delete_records('bigbluebuttonbn_logs', array('id' => $id));
1306
    return true;
1307
}
1308
1309
/**
1310
 * Update an imported recording.
1311
 *
1312
 * @param string $id
1313
 * @param array $params ['key'=>param_key, 'value']
1314
 *
1315
 * @return boolean
1316
 */
1317
function bigbluebuttonbn_update_recording_imported($id, $params) {
1318
    global $DB;
1319
    // Locate the record to be updated.
1320
    $record = $DB->get_record('bigbluebuttonbn_logs', array('id' => $id));
1321
    $meta = json_decode($record->meta, true);
1322
    // Prepare data for the update.
1323
    $meta['recording'] = $params + $meta['recording'];
1324
    $record->meta = json_encode($meta);
1325
    // Proceed with the update.
1326
    if (!$DB->update_record('bigbluebuttonbn_logs', $record)) {
1327
        return false;
1328
    }
1329
    return true;
1330
}
1331
1332
/**
1333
 * Protect/Unprotect an imported recording.
1334
 *
1335
 * @param string $id
1336
 * @param boolean $protect
1337
 *
1338
 * @return boolean
1339
 */
1340 View Code Duplication
function bigbluebuttonbn_protect_recording_imported($id, $protect = true) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1341
    global $DB;
1342
    // Locate the record to be updated.
1343
    $record = $DB->get_record('bigbluebuttonbn_logs', array('id' => $id));
1344
    $meta = json_decode($record->meta, true);
1345
    // Prepare data for the update.
1346
    $meta['recording']['protected'] = ($protect) ? 'true' : 'false';
1347
    $record->meta = json_encode($meta);
1348
    // Proceed with the update.
1349
    $DB->update_record('bigbluebuttonbn_logs', $record);
1350
    return true;
1351
}
1352
1353
/**
1354
 * Sets a custom config.xml file for being used on create.
1355
 *
1356
 * @param string $meetingid
1357
 * @param string $configxml
1358
 *
1359
 * @return object
1360
 */
1361
function bigbluebuttonbn_set_config_xml($meetingid, $configxml) {
1362
    $urldefaultconfig = \mod_bigbluebuttonbn\locallib\config::get('server_url') . 'api/setConfigXML?';
1363
    $configxmlparams = bigbluebuttonbn_set_config_xml_params($meetingid, $configxml);
1364
    $xml = bigbluebuttonbn_wrap_xml_load_file(
1365
        $urldefaultconfig,
1366
        'POST',
1367
        $configxmlparams,
1368
        'application/x-www-form-urlencoded'
1369
    );
1370
    return $xml;
1371
}
1372
1373
/**
1374
 * Sets qs used with a custom config.xml file request.
1375
 *
1376
 * @param string $meetingid
1377
 * @param string $configxml
1378
 *
1379
 * @return string
1380
 */
1381
function bigbluebuttonbn_set_config_xml_params($meetingid, $configxml) {
1382
    $params = 'configXML=' . urlencode($configxml) . '&meetingID=' . urlencode($meetingid);
1383
    $sharedsecret = \mod_bigbluebuttonbn\locallib\config::get('shared_secret');
1384
    $configxmlparams = $params . '&checksum=' . sha1('setConfigXML' . $params . $sharedsecret);
1385
    return $configxmlparams;
1386
}
1387
1388
/**
1389
 * Sets a custom config.xml file for being used on create.
1390
 *
1391
 * @param string $meetingid
1392
 * @param string $configxml
1393
 *
1394
 * @return array
1395
 */
1396
function bigbluebuttonbn_set_config_xml_array($meetingid, $configxml) {
1397
    $configxml = bigbluebuttonbn_set_config_xml($meetingid, $configxml);
1398
    $configxmlarray = (array) $configxml;
1399
    if ($configxmlarray['returncode'] != 'SUCCESS') {
1400
        debugging('BigBlueButton was not able to set the custom config.xml file', DEBUG_DEVELOPER);
1401
        return '';
1402
    }
1403
    return $configxmlarray['configToken'];
1404
}
1405
1406
/**
1407
 * Helper function builds a row for the data used by the recording table.
1408
 *
1409
 * @param array $bbbsession
1410
 * @param array $recording
1411
 * @param array $tools
1412
 *
1413
 * @return array
1414
 */
1415
function bigbluebuttonbn_get_recording_data_row($bbbsession, $recording, $tools = ['protect', 'publish', 'delete']) {
1416
    if (!bigbluebuttonbn_include_recording_table_row($bbbsession, $recording)) {
1417
        return;
1418
    }
1419
    $rowdata = new stdClass();
1420
    // Set recording_types.
1421
    $rowdata->playback = bigbluebuttonbn_get_recording_data_row_types($recording, $bbbsession);
1422
    // Set activity name.
1423
    $rowdata->recording = bigbluebuttonbn_get_recording_data_row_meta_activity($recording, $bbbsession);
1424
    // Set activity description.
1425
    $rowdata->description = bigbluebuttonbn_get_recording_data_row_meta_description($recording, $bbbsession);
1426
    if (bigbluebuttonbn_get_recording_data_preview_enabled($bbbsession)) {
1427
        // Set recording_preview.
1428
        $rowdata->preview = bigbluebuttonbn_get_recording_data_row_preview($recording);
1429
    }
1430
    // Set date.
1431
    $rowdata->date = bigbluebuttonbn_get_recording_data_row_date($recording);
1432
    // Set formatted date.
1433
    $rowdata->date_formatted = bigbluebuttonbn_get_recording_data_row_date_formatted($rowdata->date);
1434
    // Set formatted duration.
1435
    $rowdata->duration_formatted = $rowdata->duration = bigbluebuttonbn_get_recording_data_row_duration($recording);
1436
    // Set actionbar, if user is allowed to manage recordings.
1437
    if ($bbbsession['managerecordings']) {
1438
        $rowdata->actionbar = bigbluebuttonbn_get_recording_data_row_actionbar($recording, $tools);
1439
    }
1440
    return $rowdata;
1441
}
1442
1443
/**
1444
 * Helper function evaluates if a row for the data used by the recording table is editable.
1445
 *
1446
 * @param array $bbbsession
1447
 *
1448
 * @return boolean
1449
 */
1450
function bigbluebuttonbn_get_recording_data_row_editable($bbbsession) {
1451
    return ($bbbsession['managerecordings'] && ((double) $bbbsession['serverversion'] >= 1.0 || $bbbsession['bnserver']));
1452
}
1453
1454
/**
1455
 * Helper function evaluates if recording preview should be included.
1456
 *
1457
 * @param array $bbbsession
1458
 *
1459
 * @return boolean
1460
 */
1461
function bigbluebuttonbn_get_recording_data_preview_enabled($bbbsession) {
1462
    return ((double) $bbbsession['serverversion'] >= 1.0 && $bbbsession['bigbluebuttonbn']->recordings_preview == '1');
1463
}
1464
1465
/**
1466
 * Helper function converts recording date used in row for the data used by the recording table.
1467
 *
1468
 * @param array $recording
1469
 *
1470
 * @return integer
1471
 */
1472
function bigbluebuttonbn_get_recording_data_row_date($recording) {
1473
    if (!isset($recording['startTime'])) {
1474
        return 0;
1475
    }
1476
    return floatval($recording['startTime']);
1477
}
1478
1479
/**
1480
 * Helper function format recording date used in row for the data used by the recording table.
1481
 *
1482
 * @param integer $starttime
1483
 *
1484
 * @return string
1485
 */
1486
function bigbluebuttonbn_get_recording_data_row_date_formatted($starttime) {
1487
    global $USER;
1488
    $starttime = $starttime - ($starttime % 1000);
1489
    // Set formatted date.
1490
    $dateformat = get_string('strftimerecentfull', 'langconfig') . ' %Z';
1491
    return userdate($starttime / 1000, $dateformat, usertimezone($USER->timezone));
1492
}
1493
1494
/**
1495
 * Helper function converts recording duration used in row for the data used by the recording table.
1496
 *
1497
 * @param array $recording
1498
 *
1499
 * @return integer
1500
 */
1501
function bigbluebuttonbn_get_recording_data_row_duration($recording) {
1502
    foreach (array_values($recording['playbacks']) as $playback) {
1503
        // Ignore restricted playbacks.
1504
        if (array_key_exists('restricted', $playback) && strtolower($playback['restricted']) == 'true') {
1505
            continue;
1506
        }
1507
        // Take the lenght form the fist playback with an actual value.
1508
        if (!empty($playback['length'])) {
1509
            return intval($playback['length']);
1510
        }
1511
    }
1512
    return 0;
1513
}
1514
1515
/**
1516
 * Helper function builds recording actionbar used in row for the data used by the recording table.
1517
 *
1518
 * @param array $recording
1519
 * @param array $tools
1520
 *
1521
 * @return string
1522
 */
1523
function bigbluebuttonbn_get_recording_data_row_actionbar($recording, $tools) {
1524
    $actionbar = '';
1525
    foreach ($tools as $tool) {
1526
        $buttonpayload = bigbluebuttonbn_get_recording_data_row_actionbar_payload($recording, $tool);
1527
        if ($tool == 'protect') {
1528
            if (isset($recording['imported'])) {
1529
                $buttonpayload['disabled'] = 'disabled';
1530
            }
1531
            if (!isset($recording['protected'])) {
1532
                $buttonpayload['disabled'] = 'invisible';
1533
            }
1534
        }
1535
        $actionbar .= bigbluebuttonbn_actionbar_render_button($recording, $buttonpayload);
1536
    }
1537
    $head = html_writer::start_tag('div', array(
1538
        'id' => 'recording-actionbar-' . $recording['recordID'],
1539
        'data-recordingid' => $recording['recordID'],
1540
        'data-meetingid' => $recording['meetingID']));
1541
    $tail = html_writer::end_tag('div');
1542
    return $head . $actionbar . $tail;
1543
}
1544
1545
/**
1546
 * Helper function returns the corresponding payload for an actionbar button used in row
1547
 * for the data used by the recording table.
1548
 *
1549
 * @param array $recording
1550
 * @param array $tool
1551
 *
1552
 * @return array
1553
 */
1554
function bigbluebuttonbn_get_recording_data_row_actionbar_payload($recording, $tool) {
1555
    if ($tool == 'protect') {
1556
        $protected = 'false';
1557
        if (isset($recording['protected'])) {
1558
            $protected = $recording['protected'];
1559
        }
1560
        return bigbluebuttonbn_get_recording_data_row_action_protect($protected);
1561
    }
1562
    if ($tool == 'publish') {
1563
        return bigbluebuttonbn_get_recording_data_row_action_publish($recording['published']);
1564
    }
1565
    return array('action' => $tool, 'tag' => $tool);
1566
}
1567
1568
/**
1569
 * Helper function returns the payload for protect action button used in row
1570
 * for the data used by the recording table.
1571
 *
1572
 * @param string $protected
1573
 *
1574
 * @return array
1575
 */
1576
function bigbluebuttonbn_get_recording_data_row_action_protect($protected) {
1577
    if ($protected == 'true') {
1578
        return array('action' => 'unprotect', 'tag' => 'lock');
1579
    }
1580
    return array('action' => 'protect', 'tag' => 'unlock');
1581
}
1582
1583
/**
1584
 * Helper function returns the payload for publish action button used in row
1585
 * for the data used by the recording table.
1586
 *
1587
 * @param string $published
1588
 *
1589
 * @return array
1590
 */
1591
function bigbluebuttonbn_get_recording_data_row_action_publish($published) {
1592
    if ($published == 'true') {
1593
        return array('action' => 'unpublish', 'tag' => 'hide');
1594
    }
1595
    return array('action' => 'publish', 'tag' => 'show');
1596
}
1597
1598
/**
1599
 * Helper function builds recording preview used in row for the data used by the recording table.
1600
 *
1601
 * @param array $recording
1602
 *
1603
 * @return string
1604
 */
1605
function bigbluebuttonbn_get_recording_data_row_preview($recording) {
1606
    $options = array('id' => 'preview-' . $recording['recordID']);
1607
    if ($recording['published'] === 'false') {
1608
        $options['hidden'] = 'hidden';
1609
    }
1610
    $recordingpreview = html_writer::start_tag('div', $options);
1611
    foreach ($recording['playbacks'] as $playback) {
1612
        if (isset($playback['preview'])) {
1613
            $recordingpreview .= bigbluebuttonbn_get_recording_data_row_preview_images($playback);
1614
            break;
1615
        }
1616
    }
1617
    $recordingpreview .= html_writer::end_tag('div');
1618
    return $recordingpreview;
1619
}
1620
1621
/**
1622
 * Helper function builds element with actual images used in recording preview row based on a selected playback.
1623
 *
1624
 * @param array $playback
1625
 *
1626
 * @return string
1627
 */
1628
function bigbluebuttonbn_get_recording_data_row_preview_images($playback) {
1629
    global $CFG;
1630
    $recordingpreview  = html_writer::start_tag('div', array('class' => 'container-fluid'));
1631
    $recordingpreview .= html_writer::start_tag('div', array('class' => 'row'));
1632
    foreach ($playback['preview'] as $image) {
1633
        if ($CFG->bigbluebuttonbn_recordings_validate_url && !bigbluebuttonbn_is_valid_resource(trim($image['url']))) {
1634
            return '';
1635
        }
1636
        $recordingpreview .= html_writer::start_tag('div', array('class' => ''));
1637
        $recordingpreview .= html_writer::empty_tag(
1638
            'img',
1639
            array('src' => trim($image['url']) . '?' . time(), 'class' => 'recording-thumbnail pull-left')
1640
        );
1641
        $recordingpreview .= html_writer::end_tag('div');
1642
    }
1643
    $recordingpreview .= html_writer::end_tag('div');
1644
    $recordingpreview .= html_writer::start_tag('div', array('class' => 'row'));
1645
    $recordingpreview .= html_writer::tag(
1646
        'div',
1647
        get_string('view_recording_preview_help', 'bigbluebuttonbn'),
1648
        array('class' => 'text-center text-muted small')
1649
    );
1650
    $recordingpreview .= html_writer::end_tag('div');
1651
    $recordingpreview .= html_writer::end_tag('div');
1652
    return $recordingpreview;
1653
}
1654
1655
/**
1656
 * Helper function renders recording types to be used in row for the data used by the recording table.
1657
 *
1658
 * @param array $recording
1659
 * @param array $bbbsession
1660
 *
1661
 * @return string
1662
 */
1663
function bigbluebuttonbn_get_recording_data_row_types($recording, $bbbsession) {
1664
    $dataimported = 'false';
1665
    $title = '';
1666
    if (isset($recording['imported'])) {
1667
        $dataimported = 'true';
1668
        $title = get_string('view_recording_link_warning', 'bigbluebuttonbn');
1669
    }
1670
    $visibility = '';
1671
    if ($recording['published'] === 'false') {
1672
        $visibility = 'hidden ';
1673
    }
1674
    $id = 'playbacks-' . $recording['recordID'];
1675
    $recordingtypes = html_writer::start_tag('div', array('id' => $id, 'data-imported' => $dataimported,
1676
        'data-meetingid' => $recording['meetingID'], 'data-recordingid' => $recording['recordID'],
1677
        'title' => $title, $visibility => $visibility));
1678
    foreach ($recording['playbacks'] as $playback) {
1679
        $recordingtypes .= bigbluebuttonbn_get_recording_data_row_type($recording, $bbbsession, $playback);
1680
    }
1681
    $recordingtypes .= html_writer::end_tag('div');
1682
    return $recordingtypes;
1683
}
1684
1685
/**
1686
 * Helper function renders the link used for recording type in row for the data used by the recording table.
1687
 *
1688
 * @param array $recording
1689
 * @param array $bbbsession
1690
 * @param array $playback
1691
 *
1692
 * @return string
1693
 */
1694
function bigbluebuttonbn_get_recording_data_row_type($recording, $bbbsession, $playback) {
1695
    global $CFG, $OUTPUT;
1696
    if (!bigbluebuttonbn_include_recording_data_row_type($recording, $bbbsession, $playback)) {
1697
        return '';
1698
    }
1699
    $text = bigbluebuttonbn_get_recording_type_text($playback['type']);
1700
    $href = $CFG->wwwroot . '/mod/bigbluebuttonbn/bbb_view.php?action=play&bn=' . $bbbsession['bigbluebuttonbn']->id .
1701
        '&mid=' . $recording['meetingID'] . '&rid=' . $recording['recordID'] . '&rtype=' . $playback['type'];
1702
    if (!isset($recording['imported']) || !isset($recording['protected']) || $recording['protected'] === 'false') {
1703
        $href .= '&href=' . urlencode(trim($playback['url']));
1704
    }
1705
    $linkattributes = array(
1706
        'id' => 'recording-play-' . $playback['type'] . '-' . $recording['recordID'],
1707
        'class' => 'btn btn-sm btn-default',
1708
        'onclick' => 'M.mod_bigbluebuttonbn.recordings.recordingPlay(this);',
1709
        'data-action' => 'play',
1710
        'data-target' => $playback['type'],
1711
        'data-href' => $href,
1712
      );
1713
    if ($CFG->bigbluebuttonbn_recordings_validate_url && !bigbluebuttonbn_is_bn_server()
1714
            && !bigbluebuttonbn_is_valid_resource(trim($playback['url']))) {
1715
        $linkattributes['class'] = 'btn btn-sm btn-warning';
1716
        $linkattributes['title'] = get_string('view_recording_format_errror_unreachable', 'bigbluebuttonbn');
1717
        unset($linkattributes['data-href']);
1718
    }
1719
    return $OUTPUT->action_link('#', $text, null, $linkattributes) . '&#32;';
1720
}
1721
1722
/**
1723
 * Helper function to handle yet unknown recording types
1724
 *
1725
 * @param string $playbacktype : for now presentation, video, statistics, capture, notes, podcast
1726
 *
1727
 * @return string the matching language string or a capitalised version of the provided string
1728
 */
1729
function bigbluebuttonbn_get_recording_type_text($playbacktype) {
1730
    // Check first if string exists, and if it does'nt just default to the capitalised version of the string.
1731
    $text = ucwords($playbacktype);
1732
    $typestringid = 'view_recording_format_' . $playbacktype;
1733
    if (get_string_manager()->string_exists($typestringid, 'bigbluebuttonbn')) {
1734
        $text = get_string($typestringid, 'bigbluebuttonbn');
1735
    }
1736
    return $text;
1737
}
1738
1739
/**
1740
 * Helper function validates a remote resource.
1741
 *
1742
 * @param string $url
1743
 *
1744
 * @return boolean
1745
 */
1746
function bigbluebuttonbn_is_valid_resource($url) {
1747
    $urlhost = parse_url($url, PHP_URL_HOST);
1748
    $serverurlhost = parse_url(\mod_bigbluebuttonbn\locallib\config::get('server_url'), PHP_URL_HOST);
1749
    // Skip validation when the recording URL host is the same as the configured BBB server.
1750
    if ($urlhost == $serverurlhost) {
1751
        return true;
1752
    }
1753
    // Skip validation when the recording URL was already validated.
1754
    $validatedurls = bigbluebuttonbn_cache_get('recordings_cache', 'validated_urls', array());
0 ignored issues
show
Documentation introduced by
array() is of type array, but the function expects a integer|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1755
    if (array_key_exists($urlhost, $validatedurls)) {
1756
        return $validatedurls[$urlhost];
1757
    }
1758
    // Validate the recording URL.
1759
    $validatedurls[$urlhost] = true;
1760
    $curlinfo = bigbluebuttonbn_wrap_xml_load_file_curl_request($url, 'HEAD');
1761
    if (!isset($curlinfo['http_code']) || $curlinfo['http_code'] != 200) {
1762
        $error = "Resources hosted by " . $urlhost . " are unreachable. Server responded with code " . $curlinfo['http_code'];
1763
        debugging($error, DEBUG_DEVELOPER);
1764
        $validatedurls[$urlhost] = false;
1765
    }
1766
    bigbluebuttonbn_cache_set('recordings_cache', 'validated_urls', $validatedurls);
1767
    return $validatedurls[$urlhost];
1768
}
1769
1770
/**
1771
 * Helper function renders the name for meeting used in row for the data used by the recording table.
1772
 *
1773
 * @param array $recording
1774
 * @param array $bbbsession
1775
 *
1776
 * @return string
1777
 */
1778
function bigbluebuttonbn_get_recording_data_row_meeting($recording, $bbbsession) {
0 ignored issues
show
Unused Code introduced by
The parameter $bbbsession is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1779
    $payload = array();
1780
    $source = 'meetingName';
1781
    $metaname = trim($recording['meetingName']);
1782
    return bigbluebuttonbn_get_recording_data_row_text($recording, $metaname, $source, $payload);
1783
}
1784
1785
/**
1786
 * Helper function renders the name for recording used in row for the data used by the recording table.
1787
 *
1788
 * @param array $recording
1789
 * @param array $bbbsession
1790
 *
1791
 * @return string
1792
 */
1793
function bigbluebuttonbn_get_recording_data_row_meta_activity($recording, $bbbsession) {
1794
    $payload = array();
1795 View Code Duplication
    if (bigbluebuttonbn_get_recording_data_row_editable($bbbsession)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1796
        $payload = array('recordingid' => $recording['recordID'], 'meetingid' => $recording['meetingID'],
1797
            'action' => 'edit', 'tag' => 'edit',
1798
            'target' => 'name');
1799
    }
1800
    $oldsource = 'meta_contextactivity';
1801
    if (isset($recording[$oldsource])) {
1802
        $metaname = trim($recording[$oldsource]);
1803
        return bigbluebuttonbn_get_recording_data_row_text($recording, $metaname, $oldsource, $payload);
1804
    }
1805
    $newsource = 'meta_bbb-recording-name';
1806 View Code Duplication
    if (isset($recording[$newsource])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1807
        $metaname = trim($recording[$newsource]);
1808
        return bigbluebuttonbn_get_recording_data_row_text($recording, $metaname, $newsource, $payload);
1809
    }
1810
    $metaname = trim($recording['meetingName']);
1811
    return bigbluebuttonbn_get_recording_data_row_text($recording, $metaname, $newsource, $payload);
1812
}
1813
1814
/**
1815
 * Helper function renders the description for recording used in row for the data used by the recording table.
1816
 *
1817
 * @param array $recording
1818
 * @param array $bbbsession
1819
 *
1820
 * @return string
1821
 */
1822
function bigbluebuttonbn_get_recording_data_row_meta_description($recording, $bbbsession) {
1823
    $payload = array();
1824 View Code Duplication
    if (bigbluebuttonbn_get_recording_data_row_editable($bbbsession)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1825
        $payload = array('recordingid' => $recording['recordID'], 'meetingid' => $recording['meetingID'],
1826
            'action' => 'edit', 'tag' => 'edit',
1827
            'target' => 'description');
1828
    }
1829
    $oldsource = 'meta_contextactivitydescription';
1830 View Code Duplication
    if (isset($recording[$oldsource])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1831
        $metadescription = trim($recording[$oldsource]);
1832
        return bigbluebuttonbn_get_recording_data_row_text($recording, $metadescription, $oldsource, $payload);
1833
    }
1834
    $newsource = 'meta_bbb-recording-description';
1835 View Code Duplication
    if (isset($recording[$newsource])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1836
        $metadescription = trim($recording[$newsource]);
1837
        return bigbluebuttonbn_get_recording_data_row_text($recording, $metadescription, $newsource, $payload);
1838
    }
1839
    return bigbluebuttonbn_get_recording_data_row_text($recording, '', $newsource, $payload);
1840
}
1841
1842
/**
1843
 * Helper function renders text element for recording used in row for the data used by the recording table.
1844
 *
1845
 * @param array $recording
1846
 * @param string $text
1847
 * @param string $source
1848
 * @param array $data
1849
 *
1850
 * @return string
1851
 */
1852
function bigbluebuttonbn_get_recording_data_row_text($recording, $text, $source, $data) {
1853
    $htmltext = '<span>' . htmlentities($text) . '</span>';
1854
    if (empty($data)) {
1855
        return $htmltext;
1856
    }
1857
    $target = $data['action'] . '-' . $data['target'];
1858
    $id = 'recording-' . $target . '-' . $data['recordingid'];
1859
    $attributes = array('id' => $id, 'class' => 'quickeditlink col-md-20',
1860
        'data-recordingid' => $data['recordingid'], 'data-meetingid' => $data['meetingid'],
1861
        'data-target' => $data['target'], 'data-source' => $source);
1862
    $head = html_writer::start_tag('div', $attributes);
1863
    $tail = html_writer::end_tag('div');
1864
    $payload = array('action' => $data['action'], 'tag' => $data['tag'], 'target' => $data['target']);
1865
    $htmllink = bigbluebuttonbn_actionbar_render_button($recording, $payload);
1866
    return $head . $htmltext . $htmllink . $tail;
1867
}
1868
1869
/**
1870
 * Helper function render a button for the recording action bar
1871
 *
1872
 * @param array $recording
1873
 * @param array $data
1874
 *
1875
 * @return string
1876
 */
1877
function bigbluebuttonbn_actionbar_render_button($recording, $data) {
1878
    global $OUTPUT;
1879
    if (empty($data)) {
1880
        return '';
1881
    }
1882
    $target = $data['action'];
1883
    if (isset($data['target'])) {
1884
        $target .= '-' . $data['target'];
1885
    }
1886
    $id = 'recording-' . $target . '-' . $recording['recordID'];
1887
    $onclick = 'M.mod_bigbluebuttonbn.recordings.recording' . ucfirst($data['action']) . '(this); return false;';
1888
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('recording_icons_enabled')) {
1889
        // With icon for $manageaction.
1890
        $iconattributes = array('id' => $id, 'class' => 'iconsmall');
1891
        $linkattributes = array(
1892
            'id' => $id,
1893
            'onclick' => $onclick,
1894
            'data-action' => $data['action'],
1895
        );
1896
        if (!isset($recording['imported'])) {
1897
            $linkattributes['data-links'] = bigbluebuttonbn_count_recording_imported_instances(
1898
                $recording['recordID']
1899
            );
1900
        }
1901
        if (isset($data['disabled'])) {
1902
            $iconattributes['class'] .= ' fa-' . $data['disabled'];
1903
            $linkattributes['class'] = 'disabled';
1904
            unset($linkattributes['onclick']);
1905
        }
1906
        $icon = new pix_icon(
1907
            'i/' . $data['tag'],
1908
            get_string('view_recording_list_actionbar_' . $data['action'], 'bigbluebuttonbn'),
1909
            'moodle',
1910
            $iconattributes
1911
        );
1912
        return $OUTPUT->action_icon('#', $icon, null, $linkattributes, false);
1913
    }
1914
    // With text for $manageaction.
1915
    $linkattributes = array('title' => get_string($data['tag']), 'class' => 'btn btn-xs btn-danger',
1916
        'onclick' => $onclick);
1917
    return $OUTPUT->action_link('#', get_string($data['action']), null, $linkattributes);
1918
}
1919
1920
/**
1921
 * Helper function builds the recording table.
1922
 *
1923
 * @param array $bbbsession
1924
 * @param array $recordings
1925
 * @param array $tools
1926
 *
1927
 * @return object
1928
 */
1929
function bigbluebuttonbn_get_recording_table($bbbsession, $recordings, $tools = ['protect', 'publish', 'delete']) {
1930
    global $DB;
1931
    // Declare the table.
1932
    $table = new html_table();
1933
    $table->data = array();
1934
    // Initialize table headers.
1935
    $table->head[] = get_string('view_recording_playback', 'bigbluebuttonbn');
1936
    $table->head[] = get_string('view_recording_name', 'bigbluebuttonbn');
1937
    $table->head[] = get_string('view_recording_description', 'bigbluebuttonbn');
1938
    if (bigbluebuttonbn_get_recording_data_preview_enabled($bbbsession)) {
1939
        $table->head[] = get_string('view_recording_preview', 'bigbluebuttonbn');
1940
    }
1941
    $table->head[] = get_string('view_recording_date', 'bigbluebuttonbn');
1942
    $table->head[] = get_string('view_recording_duration', 'bigbluebuttonbn');
1943
    $table->align = array('left', 'left', 'left', 'left', 'left', 'center');
1944
    $table->size = array('', '', '', '', '', '');
1945
    if ($bbbsession['managerecordings']) {
1946
        $table->head[] = get_string('view_recording_actionbar', 'bigbluebuttonbn');
1947
        $table->align[] = 'left';
1948
        $table->size[] = (count($tools) * 40) . 'px';
1949
    }
1950
    // Get the groups of the user.
1951
    $usergroups = groups_get_all_groups($bbbsession['course']->id, $bbbsession['userID']);
1952
1953
    // Build table content.
1954
    foreach ($recordings as $recording) {
1955
        $meetingid = $recording['meetingID'];
0 ignored issues
show
Unused Code introduced by
$meetingid is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1956
        $shortmeetingid = explode('-', $recording['meetingID']);
1957
        if (isset($shortmeetingid[0])) {
1958
            $meetingid = $shortmeetingid[0];
0 ignored issues
show
Unused Code introduced by
$meetingid is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1959
        }
1960
        // Check if the record belongs to a Visible Group type.
1961
        list($course, $cm) = get_course_and_cm_from_cmid($bbbsession['cm']->id);
0 ignored issues
show
Unused Code introduced by
The assignment to $course is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
1962
        $groupmode = groups_get_activity_groupmode($cm);
1963
        $displayrow = true;
1964
        if (($groupmode != VISIBLEGROUPS)
1965
                && !$bbbsession['administrator'] && !$bbbsession['moderator']) {
1966
            $groupid = explode('[', $recording['meetingID']);
1967
            if (isset($groupid[1])) {
1968
                // It is a group recording and the user is not moderator/administrator. Recording should not be included by default.
1969
                $displayrow = false;
1970
                $groupid = explode(']', $groupid[1]);
1971
                if (isset($groupid[0])) {
1972
                    foreach ($usergroups as $usergroup) {
1973
                        if ($usergroup->id == $groupid[0]) {
1974
                            // Include recording if the user is in the same group.
1975
                            $displayrow = true;
1976
                        }
1977
                    }
1978
                }
1979
            }
1980
        }
1981
        if ($displayrow) {
1982
            $rowdata = bigbluebuttonbn_get_recording_data_row($bbbsession, $recording, $tools);
1983
            if (!empty($rowdata)) {
1984
                $row = bigbluebuttonbn_get_recording_table_row($bbbsession, $recording, $rowdata);
1985
                array_push($table->data, $row);
1986
            }
1987
        }
1988
    }
1989
    return $table;
1990
}
1991
1992
/**
1993
 * Helper function builds the recording table row and insert into table.
1994
 *
1995
 * @param array $bbbsession
1996
 * @param array $recording
1997
 * @param object $rowdata
1998
 *
1999
 * @return object
2000
 */
2001
function bigbluebuttonbn_get_recording_table_row($bbbsession, $recording, $rowdata) {
2002
    $row = new html_table_row();
2003
    $row->id = 'recording-tr-' . $recording['recordID'];
2004
    $row->attributes['data-imported'] = 'false';
2005
    $texthead = '';
2006
    $texttail = '';
2007
    if (isset($recording['imported'])) {
2008
        $row->attributes['title'] = get_string('view_recording_link_warning', 'bigbluebuttonbn');
2009
        $row->attributes['data-imported'] = 'true';
2010
        $texthead = '<em>';
2011
        $texttail = '</em>';
2012
    }
2013
    $rowdata->date_formatted = str_replace(' ', '&nbsp;', $rowdata->date_formatted);
2014
    $row->cells = array();
2015
    $row->cells[] = $texthead . $rowdata->playback . $texttail;
2016
    $row->cells[] = $texthead . $rowdata->recording . $texttail;
2017
    $row->cells[] = $texthead . $rowdata->description . $texttail;
2018
    if (bigbluebuttonbn_get_recording_data_preview_enabled($bbbsession)) {
2019
        $row->cells[] = $rowdata->preview;
2020
    }
2021
    $row->cells[] = $texthead . $rowdata->date_formatted . $texttail;
2022
    $row->cells[] = $rowdata->duration_formatted;
2023
    if ($bbbsession['managerecordings']) {
2024
        $row->cells[] = $rowdata->actionbar;
2025
    }
2026
    return $row;
2027
}
2028
2029
/**
2030
 * Get the basic data to display in the table view
2031
 *
2032
 * @param array $bbbsession the current session
2033
 * @param array $enabledfeatures feature enabled for this activity
2034
 * @return associative array containing the recordings indexed by recordID, each recording is also a
2035
 * non sequential associative array itself that corresponds to the actual recording in BBB
2036
 */
2037
function bigbluebutton_get_recordings_for_table_view($bbbsession, $enabledfeatures) {
2038
    $bigbluebuttonbnid = null;
2039
    if ($enabledfeatures['showroom']) {
2040
        $bigbluebuttonbnid = $bbbsession['bigbluebuttonbn']->id;
2041
    }
2042
    // Get recordings.
2043
    $recordings = bigbluebuttonbn_get_recordings(
2044
        $bbbsession['course']->id, $bigbluebuttonbnid, $enabledfeatures['showroom'],
2045
        $bbbsession['bigbluebuttonbn']->recordings_deleted
2046
    );
2047
    if ($enabledfeatures['importrecordings']) {
2048
        // Get recording links.
2049
        $bigbluebuttonbnid = $bbbsession['bigbluebuttonbn']->id;
2050
        $recordingsimported = bigbluebuttonbn_get_recordings_imported_array(
2051
            $bbbsession['course']->id, $bigbluebuttonbnid, true
2052
        );
2053
        /* Perform aritmetic addition instead of merge so the imported recordings corresponding to existent
2054
         * recordings are not included. */
2055
        if ($bbbsession['bigbluebuttonbn']->recordings_imported) {
2056
            $recordings = $recordingsimported;
2057
        } else {
2058
            $recordings += $recordingsimported;
2059
        }
2060
    }
2061
    return $recordings;
2062
}
2063
2064
/**
2065
 * Helper function evaluates if recording row should be included in the table.
2066
 *
2067
 * @param array $bbbsession
2068
 * @param array $recording
2069
 *
2070
 * @return boolean
2071
 */
2072
function bigbluebuttonbn_include_recording_table_row($bbbsession, $recording) {
2073
    // Exclude unpublished recordings, only if user has no rights to manage them.
2074
    if ($recording['published'] != 'true' && !$bbbsession['managerecordings']) {
2075
        return false;
2076
    }
2077
    // Imported recordings are always shown as long as they are published.
2078
    if (isset($recording['imported'])) {
2079
        return true;
2080
    }
2081
    // Administrators and moderators are always allowed.
2082
    if ($bbbsession['administrator'] || $bbbsession['moderator']) {
2083
        return true;
2084
    }
2085
    // When groups are enabled, exclude those to which the user doesn't have access to.
2086
    if (isset($bbbsession['group']) && $recording['meetingID'] != $bbbsession['meetingid']) {
2087
        return false;
2088
    }
2089
    return true;
2090
}
2091
2092
/**
2093
 * Helper function triggers a send notification when the recording is ready.
2094
 *
2095
 * @param object $bigbluebuttonbn
2096
 *
2097
 * @return void
2098
 */
2099
function bigbluebuttonbn_send_notification_recording_ready($bigbluebuttonbn) {
2100
    \mod_bigbluebuttonbn\locallib\notifier::notify_recording_ready($bigbluebuttonbn);
2101
}
2102
2103
/**
2104
 * Helper function enqueues list of meeting events to be stored and processed as for completion.
2105
 *
2106
 * @param object $bigbluebuttonbn
2107
 * @param object $jsonobj
2108
 *
2109
 * @return void
2110
 */
2111
function bigbluebuttonbn_process_meeting_events($bigbluebuttonbn, $jsonobj) {
2112
    $meetingid = $jsonobj->{'meeting_id'};
2113
    $recordid = $jsonobj->{'internal_meeting_id'};
2114
    $attendees = $jsonobj->{'data'}->{'attendees'};
2115
    foreach ($attendees as $attendee) {
2116
        $userid = $attendee->{'ext_user_id'};
2117
        $overrides['meetingid'] = $meetingid;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$overrides was never initialized. Although not strictly required by PHP, it is generally a good practice to add $overrides = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
2118
        $overrides['userid'] = $userid;
0 ignored issues
show
Bug introduced by
The variable $overrides does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
2119
        $meta['recordid'] = $recordid;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$meta was never initialized. Although not strictly required by PHP, it is generally a good practice to add $meta = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
2120
        $meta['data'] = $attendee;
2121
        // Stores the log.
2122
        bigbluebuttonbn_log($bigbluebuttonbn, BIGBLUEBUTTON_LOG_EVENT_SUMMARY, $overrides, json_encode($meta));
2123
        // Enqueue a task for processing the completion.
2124
        bigbluebuttonbn_enqueue_completion_update($bigbluebuttonbn, $userid);
2125
    }
2126
}
2127
2128
/**
2129
 * Helper function enqueues one user for being validated as for completion.
2130
 *
2131
 * @param object $bigbluebuttonbn
2132
 * @param string $userid
2133
 *
2134
 * @return void
2135
 */
2136
function bigbluebuttonbn_enqueue_completion_update($bigbluebuttonbn, $userid) {
2137
    try {
2138
        // Create the instance of completion_update_state task.
2139
        $task = new \mod_bigbluebuttonbn\task\completion_update_state();
2140
        // Add custom data.
2141
        $data = array(
2142
            'bigbluebuttonbn' => $bigbluebuttonbn,
2143
            'userid' => $userid,
2144
        );
2145
        $task->set_custom_data($data);
2146
        // CONTRIB-7457: Task should be executed by a user, maybe Teacher as Student won't have rights for overriding.
2147
        // $ task -> set_userid ( $ user -> id );.
2148
        // Enqueue it.
2149
        \core\task\manager::queue_adhoc_task($task);
2150
    } catch (Exception $e) {
2151
        mtrace("Error while enqueuing completion_update_state task. " . (string) $e);
2152
    }
2153
}
2154
2155
/**
2156
 * Helper function enqueues completion trigger.
2157
 *
2158
 * @param object $bigbluebuttonbn
2159
 * @param string $userid
2160
 *
2161
 * @return void
2162
 */
2163
function bigbluebuttonbn_completion_update_state($bigbluebuttonbn, $userid) {
2164
    global $CFG;
2165
    require_once($CFG->libdir.'/completionlib.php');
2166
    list($course, $cm) = get_course_and_cm_from_instance($bigbluebuttonbn, 'bigbluebuttonbn');
2167
    $completion = new completion_info($course);
2168
    if (!$completion->is_enabled($cm)) {
2169
        mtrace("Completion not enabled");
2170
        return;
2171
    }
2172
    if (bigbluebuttonbn_get_completion_state($course, $cm, $userid, COMPLETION_AND)) {
2173
        mtrace("Completion succeeded for user $userid");
2174
        $completion->update_state($cm, COMPLETION_COMPLETE, $userid, true);
2175
    } else {
2176
        mtrace("Completion did not succeed for user $userid");
2177
    }
2178
}
2179
2180
/**
2181
 * Helper evaluates if the bigbluebutton server used belongs to blindsidenetworks domain.
2182
 *
2183
 * @return boolean
2184
 */
2185
function bigbluebuttonbn_is_bn_server() {
2186
    if (\mod_bigbluebuttonbn\locallib\config::get('bn_server')) {
2187
        return true;
2188
    }
2189
    $parsedurl = parse_url(\mod_bigbluebuttonbn\locallib\config::get('server_url'));
2190
    if (!isset($parsedurl['host'])) {
2191
        return false;
2192
    }
2193
    $h = $parsedurl['host'];
2194
    $hends = explode('.', $h);
2195
    $hendslength = count($hends);
2196
    return ($hends[$hendslength - 1] == 'com' && $hends[$hendslength - 2] == 'blindsidenetworks');
2197
}
2198
2199
/**
2200
 * Helper function returns a list of courses a user has access to, wrapped in an array that can be used
2201
 * by a html select.
2202
 *
2203
 * @param array $bbbsession
2204
 *
2205
 * @return array
2206
 */
2207
function bigbluebuttonbn_import_get_courses_for_select(array $bbbsession) {
2208
    if ($bbbsession['administrator']) {
2209
        $courses = get_courses('all', 'c.fullname ASC');
2210
        // It includes the name of the site as a course (category 0), so remove the first one.
2211
        unset($courses['1']);
2212
    } else {
2213
        $courses = enrol_get_users_courses($bbbsession['userID'], false, 'id,shortname,fullname');
2214
    }
2215
    $coursesforselect = [];
2216
    foreach ($courses as $course) {
2217
        $coursesforselect[$course->id] = $course->fullname . " (" . $course->shortname . ")";
2218
    }
2219
    return $coursesforselect;
2220
}
2221
2222
/**
2223
 * Helper function renders recording table.
2224
 *
2225
 * @param array $bbbsession
2226
 * @param array $recordings
2227
 * @param array $tools
2228
 *
2229
 * @return array
2230
 */
2231
function bigbluebuttonbn_output_recording_table($bbbsession, $recordings, $tools = ['protect', 'publish', 'delete']) {
2232
    if (isset($recordings) && !empty($recordings)) {
2233
        // There are recordings for this meeting.
2234
        $table = bigbluebuttonbn_get_recording_table($bbbsession, $recordings, $tools);
2235
    }
2236
    if (!isset($table) || !isset($table->data)) {
2237
        // Render a table with "No recordings".
2238
        return html_writer::div(
2239
            get_string('view_message_norecordings', 'bigbluebuttonbn'),
2240
            '',
2241
            array('id' => 'bigbluebuttonbn_recordings_table')
2242
        );
2243
    }
2244
    // Render the table.
2245
    return html_writer::div(html_writer::table($table), '', array('id' => 'bigbluebuttonbn_recordings_table'));
2246
}
2247
/**
2248
 * Helper function renders recording link for opencast.
2249
 *
2250
 * @param string $courseid
2251
 * 
2252
 * @return array
2253
 */
2254
function bigbluebuttonbn_output_recording_opencast($courseid) {
2255
    $opencast_url = new \moodle_url('/blocks/opencast/index.php', array('courseid'=>$courseid));
2256
    return html_writer::div(html_writer::tag('button', get_string('view_message_oc_recordings', 'bigbluebuttonbn'), 
2257
                                array('class' => 'btn btn-primary', 'onclick' => "window.location='{$opencast_url}';")),
2258
                                 '', array('id' => 'bigbluebuttonbn_recordings_opencast', 'class' => 'py-3'));
2259
}
2260
/**
2261
 * Helper function to convert an html string to plain text.
2262
 *
2263
 * @param string $html
2264
 * @param integer $len
2265
 *
2266
 * @return string
2267
 */
2268
function bigbluebuttonbn_html2text($html, $len = 0) {
2269
    $text = strip_tags($html);
2270
    $text = str_replace('&nbsp;', ' ', $text);
2271
    $textlen = strlen($text);
2272
    $text = mb_substr($text, 0, $len);
2273
    if ($textlen > $len) {
2274
        $text .= '...';
2275
    }
2276
    return $text;
2277
}
2278
2279
/**
2280
 * Helper function to obtain the tags linked to a bigbluebuttonbn activity
2281
 *
2282
 * @param string $id
2283
 *
2284
 * @return string containing the tags separated by commas
2285
 */
2286
function bigbluebuttonbn_get_tags($id) {
2287
    if (class_exists('core_tag_tag')) {
2288
        return implode(',', core_tag_tag::get_item_tags_array('core', 'course_modules', $id));
2289
    }
2290
    return implode(',', tag_get_tags('bigbluebuttonbn', $id));
2291
}
2292
2293
/**
2294
 * Helper function to define the sql used for gattering the bigbluebuttonbnids whose meetingids should be included
2295
 * in the getRecordings request
2296
 *
2297
 * @param string $courseid
2298
 * @param string $bigbluebuttonbnid
2299
 * @param bool   $subset
2300
 *
2301
 * @return string containing the sql used for getting the target bigbluebuttonbn instances
2302
 */
2303
function bigbluebuttonbn_get_recordings_sql_select($courseid, $bigbluebuttonbnid = null, $subset = true) {
2304
    if (empty($courseid)) {
2305
        $courseid = 0;
2306
    }
2307
    if (empty($bigbluebuttonbnid)) {
2308
        return "course = '{$courseid}'";
2309
    }
2310
    if ($subset) {
2311
        return "id = '{$bigbluebuttonbnid}'";
2312
    }
2313
    return "id <> '{$bigbluebuttonbnid}' AND course = '{$courseid}'";
2314
}
2315
2316
/**
2317
 * Helper function to define the sql used for gattering the bigbluebuttonbnids whose meetingids should be included
2318
 * in the getRecordings request considering only those that belong to deleted activities.
2319
 *
2320
 * @param string $courseid
2321
 * @param string $bigbluebuttonbnid
2322
 * @param bool   $subset
2323
 *
2324
 * @return string containing the sql used for getting the target bigbluebuttonbn instances
2325
 */
2326 View Code Duplication
function bigbluebuttonbn_get_recordings_deleted_sql_select($courseid = 0, $bigbluebuttonbnid = null, $subset = true) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2327
    $sql = "log = '" . BIGBLUEBUTTONBN_LOG_EVENT_DELETE . "' AND meta like '%has_recordings%' AND meta like '%true%'";
2328
    if (empty($courseid)) {
2329
        $courseid = 0;
2330
    }
2331
    if (empty($bigbluebuttonbnid)) {
2332
        return $sql . " AND courseid = {$courseid}";
2333
    }
2334
    if ($subset) {
2335
        return $sql . " AND bigbluebuttonbnid = '{$bigbluebuttonbnid}'";
2336
    }
2337
    return $sql . " AND courseid = {$courseid} AND bigbluebuttonbnid <> '{$bigbluebuttonbnid}'";
2338
}
2339
2340
/**
2341
 * Helper function to define the sql used for gattering the bigbluebuttonbnids whose meetingids should be included
2342
 * in the getRecordings request considering only those that belong to imported recordings.
2343
 *
2344
 * @param string $courseid
2345
 * @param string $bigbluebuttonbnid
2346
 * @param bool   $subset
2347
 *
2348
 * @return string containing the sql used for getting the target bigbluebuttonbn instances
2349
 */
2350 View Code Duplication
function bigbluebuttonbn_get_recordings_imported_sql_select($courseid = 0, $bigbluebuttonbnid = null, $subset = true) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2351
    $sql = "log = '" . BIGBLUEBUTTONBN_LOG_EVENT_IMPORT . "'";
2352
    if (empty($courseid)) {
2353
        $courseid = 0;
2354
    }
2355
    if (empty($bigbluebuttonbnid)) {
2356
        return $sql . " AND courseid = '{$courseid}'";
2357
    }
2358
    if ($subset) {
2359
        return $sql . " AND bigbluebuttonbnid = '{$bigbluebuttonbnid}'";
2360
    }
2361
    return $sql . " AND courseid = '{$courseid}' AND bigbluebuttonbnid <> '{$bigbluebuttonbnid}'";
2362
}
2363
2364
/**
2365
 * Helper function to get recordings and imported recordings together.
2366
 *
2367
 * @param string $courseid
2368
 * @param string $bigbluebuttonbnid
2369
 * @param bool   $subset
2370
 * @param bool   $includedeleted
2371
 *
2372
 * @return associative array containing the recordings indexed by recordID, each recording is also a
2373
 * non sequential associative array itself that corresponds to the actual recording in BBB
2374
 */
2375
function bigbluebuttonbn_get_allrecordings($courseid = 0, $bigbluebuttonbnid = null, $subset = true, $includedeleted = false) {
2376
    $recordings = bigbluebuttonbn_get_recordings($courseid, $bigbluebuttonbnid, $subset, $includedeleted);
2377
    $recordingsimported = bigbluebuttonbn_get_recordings_imported_array($courseid, $bigbluebuttonbnid, $subset);
2378
    return ($recordings + $recordingsimported);
2379
}
2380
2381
/**
2382
 * Helper function to retrieve recordings from the BigBlueButton. The references are stored as events
2383
 * in bigbluebuttonbn_logs.
2384
 *
2385
 * @param string $courseid
2386
 * @param string $bigbluebuttonbnid
2387
 * @param bool   $subset
2388
 * @param bool   $includedeleted
2389
 *
2390
 * @return associative array containing the recordings indexed by recordID, each recording is also a
2391
 * non sequential associative array itself that corresponds to the actual recording in BBB
2392
 */
2393
function bigbluebuttonbn_get_recordings($courseid = 0, $bigbluebuttonbnid = null, $subset = true, $includedeleted = false) {
2394
    global $DB;
2395
    $select = bigbluebuttonbn_get_recordings_sql_select($courseid, $bigbluebuttonbnid, $subset);
2396
    $bigbluebuttonbns = $DB->get_records_select_menu('bigbluebuttonbn', $select, null, 'id', 'id, meetingid');
2397
    /* Consider logs from deleted bigbluebuttonbn instances whose meetingids should be included in
2398
     * the getRecordings request. */
2399
    if ($includedeleted) {
2400
        $selectdeleted = bigbluebuttonbn_get_recordings_deleted_sql_select($courseid, $bigbluebuttonbnid, $subset);
2401
        $bigbluebuttonbnsdel = $DB->get_records_select_menu(
2402
            'bigbluebuttonbn_logs',
2403
            $selectdeleted,
2404
            null,
2405
            'bigbluebuttonbnid',
2406
            'bigbluebuttonbnid, meetingid'
2407
        );
2408
        if (!empty($bigbluebuttonbnsdel)) {
2409
            // Merge bigbluebuttonbnis from deleted instances, only keys are relevant.
2410
            // Artimetic merge is used in order to keep the keys.
2411
            $bigbluebuttonbns += $bigbluebuttonbnsdel;
2412
        }
2413
    }
2414
    // Gather the meetingids from bigbluebuttonbn logs that include a create with record=true.
2415
    if (empty($bigbluebuttonbns)) {
2416
        return array();
2417
    }
2418
    // Prepare select for loading records based on existent bigbluebuttonbns.
2419
    $sql = 'SELECT DISTINCT meetingid, bigbluebuttonbnid FROM {bigbluebuttonbn_logs} WHERE ';
2420
    $sql .= '(bigbluebuttonbnid=' . implode(' OR bigbluebuttonbnid=', array_keys($bigbluebuttonbns)) . ')';
2421
    // Include only Create events and exclude those with record not true.
2422
    $sql .= ' AND log = ? AND meta LIKE ? AND meta LIKE ?';
2423
    // Execute select for loading records based on existent bigbluebuttonbns.
2424
    $records = $DB->get_records_sql_menu($sql, array(BIGBLUEBUTTONBN_LOG_EVENT_CREATE, '%record%', '%true%'));
2425
    // Get actual recordings.
2426
    return bigbluebuttonbn_get_recordings_array(array_keys($records));
2427
}
2428
2429
/**
2430
 * Helper function iterates an array with recordings and unset those already imported.
2431
 *
2432
 * @param array $recordings
2433
 * @param integer $courseid
2434
 * @param integer $bigbluebuttonbnid
2435
 *
2436
 * @return array
2437
 */
2438
function bigbluebuttonbn_unset_existent_recordings_already_imported($recordings, $courseid, $bigbluebuttonbnid) {
2439
    $recordingsimported = bigbluebuttonbn_get_recordings_imported_array($courseid, $bigbluebuttonbnid, true);
2440
    foreach ($recordings as $key => $recording) {
2441
        if (isset($recordingsimported[$recording['recordID']])) {
2442
            unset($recordings[$key]);
2443
        }
2444
    }
2445
    return $recordings;
2446
}
2447
2448
/**
2449
 * Helper function to count the imported recordings for a recordingid.
2450
 *
2451
 * @param string $recordid
2452
 *
2453
 * @return integer
2454
 */
2455
function bigbluebuttonbn_count_recording_imported_instances($recordid) {
2456
    global $DB;
2457
    $sql = 'SELECT COUNT(DISTINCT id) FROM {bigbluebuttonbn_logs} WHERE log = ? AND meta LIKE ? AND meta LIKE ?';
2458
    return $DB->count_records_sql($sql, array(BIGBLUEBUTTONBN_LOG_EVENT_IMPORT, '%recordID%', "%{$recordid}%"));
2459
}
2460
2461
/**
2462
 * Helper function returns an array with all the instances of imported recordings for a recordingid.
2463
 *
2464
 * @param string $recordid
2465
 *
2466
 * @return array
2467
 */
2468
function bigbluebuttonbn_get_recording_imported_instances($recordid) {
2469
    global $DB;
2470
    $sql = 'SELECT * FROM {bigbluebuttonbn_logs} WHERE log = ? AND meta LIKE ? AND meta LIKE ?';
2471
    $recordingsimported = $DB->get_records_sql($sql, array(BIGBLUEBUTTONBN_LOG_EVENT_IMPORT, '%recordID%',
2472
        "%{$recordid}%"));
2473
    return $recordingsimported;
2474
}
2475
2476
/**
2477
 * Helper function to get how much callback events are logged.
2478
 *
2479
 * @param string $recordid
2480
 * @param string $callbacktype
2481
 *
2482
 * @return integer
2483
 */
2484
function bigbluebuttonbn_get_count_callback_event_log($recordid, $callbacktype = 'recording_ready') {
2485
    global $DB;
2486
    $sql = 'SELECT count(DISTINCT id) FROM {bigbluebuttonbn_logs} WHERE log = ? AND meta LIKE ? AND meta LIKE ?';
2487
    // Callback type added on version 2.4, validate recording_ready first or assume it on records with no callback.
2488
    if ($callbacktype == 'recording_ready') {
2489
        $sql .= ' AND (meta LIKE ? OR meta NOT LIKE ? )';
2490
        $count = $DB->count_records_sql($sql, array(BIGBLUEBUTTON_LOG_EVENT_CALLBACK, '%recordid%', "%$recordid%",
2491
            $callbacktype, 'callback'));
2492
        return $count;
2493
    }
2494
    $sql .= ' AND meta LIKE ?;';
2495
    $count = $DB->count_records_sql($sql, array(BIGBLUEBUTTON_LOG_EVENT_CALLBACK, '%recordid%', "%$recordid%", "%$callbacktype%"));
2496
    return $count;
2497
}
2498
2499
/**
2500
 * Helper function returns an array with the profiles (with features per profile) for the different types
2501
 * of bigbluebuttonbn instances.
2502
 *
2503
 * @return array
2504
 */
2505
function bigbluebuttonbn_get_instance_type_profiles() {
2506
    $instanceprofiles = array(
2507
        BIGBLUEBUTTONBN_TYPE_ALL => array('id' => BIGBLUEBUTTONBN_TYPE_ALL,
2508
            'name' => get_string('instance_type_default', 'bigbluebuttonbn'),
2509
            'features' => array('all')),
2510
        BIGBLUEBUTTONBN_TYPE_ROOM_ONLY => array('id' => BIGBLUEBUTTONBN_TYPE_ROOM_ONLY,
2511
            'name' => get_string('instance_type_room_only', 'bigbluebuttonbn'),
2512
            'features' => array('showroom', 'welcomemessage', 'voicebridge', 'waitformoderator', 'userlimit',
2513
                'recording', 'sendnotifications', 'preuploadpresentation', 'permissions', 'schedule', 'groups',
2514
                'modstandardelshdr', 'availabilityconditionsheader', 'tagshdr', 'competenciessection',
2515
                'clienttype', 'completionattendance', 'completionengagement', 'availabilityconditionsheader')),
2516
        BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY => array('id' => BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY,
2517
            'name' => get_string('instance_type_recording_only', 'bigbluebuttonbn'),
2518
            'features' => array('showrecordings', 'importrecordings', 'availabilityconditionsheader')),
2519
    );
2520
    return $instanceprofiles;
2521
}
2522
2523
/**
2524
 * Helper function returns an array with enabled features for an specific profile type.
2525
 *
2526
 * @param array $typeprofiles
2527
 * @param string $type
2528
 *
2529
 * @return array
2530
 */
2531
function bigbluebuttonbn_get_enabled_features($typeprofiles, $type = null) {
2532
    $enabledfeatures = array();
2533
    $features = $typeprofiles[BIGBLUEBUTTONBN_TYPE_ALL]['features'];
2534
    if (!is_null($type) && key_exists($type, $typeprofiles)) {
2535
        $features = $typeprofiles[$type]['features'];
2536
    }
2537
    $enabledfeatures['showroom'] = (in_array('all', $features) || in_array('showroom', $features));
2538
    // Evaluates if recordings are enabled for the Moodle site.
2539
    $enabledfeatures['showrecordings'] = false;
2540
    if (\mod_bigbluebuttonbn\locallib\config::recordings_enabled()) {
2541
        $enabledfeatures['showrecordings'] = (in_array('all', $features) || in_array('showrecordings', $features));
2542
    }
2543
    $enabledfeatures['importrecordings'] = false;
2544
    if (\mod_bigbluebuttonbn\locallib\config::importrecordings_enabled()) {
2545
        $enabledfeatures['importrecordings'] = (in_array('all', $features) || in_array('importrecordings', $features));
2546
    }
2547
    // Evaluates if clienttype is enabled for the Moodle site.
2548
    $enabledfeatures['clienttype'] = false;
2549
    if (\mod_bigbluebuttonbn\locallib\config::clienttype_enabled()) {
2550
        $enabledfeatures['clienttype'] = (in_array('all', $features) || in_array('clienttype', $features));
2551
    }
2552
    return $enabledfeatures;
2553
}
2554
2555
/**
2556
 * Helper function returns an array with the profiles (with features per profile) for the different types
2557
 * of bigbluebuttonbn instances that the user is allowed to create.
2558
 *
2559
 * @param boolean $room
2560
 * @param boolean $recording
2561
 *
2562
 * @return array
2563
 */
2564
function bigbluebuttonbn_get_instance_type_profiles_create_allowed($room, $recording) {
2565
    $profiles = bigbluebuttonbn_get_instance_type_profiles();
2566
    if (!$room) {
2567
        unset($profiles[BIGBLUEBUTTONBN_TYPE_ROOM_ONLY]);
2568
        unset($profiles[BIGBLUEBUTTONBN_TYPE_ALL]);
2569
    }
2570
    if (!$recording) {
2571
        unset($profiles[BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY]);
2572
        unset($profiles[BIGBLUEBUTTONBN_TYPE_ALL]);
2573
    }
2574
    return $profiles;
2575
}
2576
2577
/**
2578
 * Helper function returns an array with the profiles (with features per profile) for the different types
2579
 * of bigbluebuttonbn instances.
2580
 *
2581
 * @param array $profiles
2582
 *
2583
 * @return array
2584
 */
2585
function bigbluebuttonbn_get_instance_profiles_array($profiles = []) {
2586
    $profilesarray = array();
2587
    foreach ($profiles as $key => $profile) {
2588
        $profilesarray[$profile['id']] = $profile['name'];
2589
    }
2590
    return $profilesarray;
2591
}
2592
2593
/**
2594
 * Helper function returns time in a formatted string.
2595
 *
2596
 * @param integer $time
2597
 *
2598
 * @return string
2599
 */
2600
function bigbluebuttonbn_format_activity_time($time) {
2601
    global $CFG;
2602
    require_once($CFG->dirroot.'/calendar/lib.php');
2603
    $activitytime = '';
2604
    if ($time) {
2605
        $activitytime = calendar_day_representation($time) . ' ' .
2606
        get_string('mod_form_field_notification_msg_at', 'bigbluebuttonbn') . ' ' .
2607
        calendar_time_representation($time);
2608
    }
2609
    return $activitytime;
2610
}
2611
2612
/**
2613
 * Helper function returns array with all the strings to be used in javascript.
2614
 *
2615
 * @return array
2616
 */
2617
function bigbluebuttonbn_get_strings_for_js() {
2618
    $locale = bigbluebuttonbn_get_locale();
2619
    $stringman = get_string_manager();
2620
    $strings = $stringman->load_component_strings('bigbluebuttonbn', $locale);
2621
    return $strings;
2622
}
2623
2624
/**
2625
 * Helper function returns the locale set by moodle.
2626
 *
2627
 * @return string
2628
 */
2629
function bigbluebuttonbn_get_locale() {
2630
    $lang = get_string('locale', 'core_langconfig');
2631
    return substr($lang, 0, strpos($lang, '.'));
2632
}
2633
2634
/**
2635
 * Helper function returns the locale code based on the locale set by moodle.
2636
 *
2637
 * @return string
2638
 */
2639
function bigbluebuttonbn_get_localcode() {
2640
    $locale = bigbluebuttonbn_get_locale();
2641
    return substr($locale, 0, strpos($locale, '_'));
2642
}
2643
2644
/**
2645
 * Helper function returns array with the instance settings used in views.
2646
 *
2647
 * @param string $id
2648
 * @param object $bigbluebuttonbnid
2649
 *
2650
 * @return array
2651
 */
2652
function bigbluebuttonbn_view_validator($id, $bigbluebuttonbnid) {
2653
    if ($id) {
2654
        return bigbluebuttonbn_view_instance_id($id);
2655
    }
2656
    if ($bigbluebuttonbnid) {
2657
        return bigbluebuttonbn_view_instance_bigbluebuttonbn($bigbluebuttonbnid);
2658
    }
2659
}
2660
2661
/**
2662
 * Helper function returns array with the instance settings used in views based on id.
2663
 *
2664
 * @param string $id
2665
 *
2666
 * @return array
2667
 */
2668 View Code Duplication
function bigbluebuttonbn_view_instance_id($id) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2669
    global $DB;
2670
    $cm = get_coursemodule_from_id('bigbluebuttonbn', $id, 0, false, MUST_EXIST);
2671
    $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
2672
    $bigbluebuttonbn = $DB->get_record('bigbluebuttonbn', array('id' => $cm->instance), '*', MUST_EXIST);
2673
    return array('cm' => $cm, 'course' => $course, 'bigbluebuttonbn' => $bigbluebuttonbn);
2674
}
2675
2676
/**
2677
 * Helper function returns array with the instance settings used in views based on bigbluebuttonbnid.
2678
 *
2679
 * @param object $bigbluebuttonbnid
2680
 *
2681
 * @return array
2682
 */
2683 View Code Duplication
function bigbluebuttonbn_view_instance_bigbluebuttonbn($bigbluebuttonbnid) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2684
    global $DB;
2685
    $bigbluebuttonbn = $DB->get_record('bigbluebuttonbn', array('id' => $bigbluebuttonbnid), '*', MUST_EXIST);
2686
    $course = $DB->get_record('course', array('id' => $bigbluebuttonbn->course), '*', MUST_EXIST);
2687
    $cm = get_coursemodule_from_instance('bigbluebuttonbn', $bigbluebuttonbn->id, $course->id, false, MUST_EXIST);
2688
    return array('cm' => $cm, 'course' => $course, 'bigbluebuttonbn' => $bigbluebuttonbn);
2689
}
2690
2691
/**
2692
 * Helper function renders general settings if the feature is enabled.
2693
 *
2694
 * @param object $renderer
2695
 *
2696
 * @return void
2697
 */
2698
function bigbluebuttonbn_settings_general(&$renderer) {
2699
    // Configuration for BigBlueButton.
2700
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_general_shown()) {
2701
        $renderer->render_group_header('general');
2702
        $renderer->render_group_element(
2703
            'server_url',
2704
            $renderer->render_group_element_text('server_url', BIGBLUEBUTTONBN_DEFAULT_SERVER_URL)
2705
        );
2706
        $renderer->render_group_element(
2707
            'shared_secret',
2708
            $renderer->render_group_element_text('shared_secret', BIGBLUEBUTTONBN_DEFAULT_SHARED_SECRET)
2709
        );
2710
    }
2711
}
2712
2713
/**
2714
 * Helper function renders record settings if the feature is enabled.
2715
 *
2716
 * @param object $renderer
2717
 *
2718
 * @return void
2719
 */
2720
function bigbluebuttonbn_settings_record(&$renderer) {
2721
    // Configuration for 'recording' feature.
2722
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_record_meeting_shown()) {
2723
        $renderer->render_group_header('recording');
2724
        $renderer->render_group_element(
2725
            'recording_default',
2726
            $renderer->render_group_element_checkbox('recording_default', 1)
2727
        );
2728
        $renderer->render_group_element(
2729
            'recording_editable',
2730
            $renderer->render_group_element_checkbox('recording_editable', 1)
2731
        );
2732
        if (bigbluebuttonbn_check_opencast()) {
2733
            $renderer->render_group_element(
2734
                'oc_recording',
2735
                $renderer->render_group_element_checkbox('oc_recording', 0)
2736
            );
2737
        }
2738
        $renderer->render_group_element(
2739
            'recording_icons_enabled',
2740
            $renderer->render_group_element_checkbox('recording_icons_enabled', 1)
2741
        );
2742
2743
        // Add recording start to load and allow/hide stop/pause.
2744
        $renderer->render_group_element(
2745
            'recording_all_from_start_default',
2746
            $renderer->render_group_element_checkbox('recording_all_from_start_default', 0)
2747
        );
2748
        $renderer->render_group_element(
2749
            'recording_all_from_start_editable',
2750
            $renderer->render_group_element_checkbox('recording_all_from_start_editable', 0)
2751
        );
2752
        $renderer->render_group_element(
2753
            'recording_hide_button_default',
2754
            $renderer->render_group_element_checkbox('recording_hide_button_default', 0)
2755
        );
2756
        $renderer->render_group_element(
2757
            'recording_hide_button_editable',
2758
            $renderer->render_group_element_checkbox('recording_hide_button_editable', 0)
2759
        );
2760
    }
2761
}
2762
2763
/**
2764
 * Helper function renders import recording settings if the feature is enabled.
2765
 *
2766
 * @param object $renderer
2767
 *
2768
 * @return void
2769
 */
2770 View Code Duplication
function bigbluebuttonbn_settings_importrecordings(&$renderer) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2771
    // Configuration for 'import recordings' feature.
2772
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_import_recordings_shown()) {
2773
        $renderer->render_group_header('importrecordings');
2774
        $renderer->render_group_element(
2775
            'importrecordings_enabled',
2776
            $renderer->render_group_element_checkbox('importrecordings_enabled', 0)
2777
        );
2778
        $renderer->render_group_element(
2779
            'importrecordings_from_deleted_enabled',
2780
            $renderer->render_group_element_checkbox('importrecordings_from_deleted_enabled', 0)
2781
        );
2782
    }
2783
}
2784
2785
/**
2786
 * Helper function renders show recording settings if the feature is enabled.
2787
 *
2788
 * @param object $renderer
2789
 *
2790
 * @return void
2791
 */
2792
function bigbluebuttonbn_settings_showrecordings(&$renderer) {
2793
    // Configuration for 'show recordings' feature.
2794
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_show_recordings_shown()) {
2795
        $renderer->render_group_header('recordings');
2796
        $renderer->render_group_element(
2797
            'recordings_html_default',
2798
            $renderer->render_group_element_checkbox('recordings_html_default', 1)
2799
        );
2800
        $renderer->render_group_element(
2801
            'recordings_html_editable',
2802
            $renderer->render_group_element_checkbox('recordings_html_editable', 0)
2803
        );
2804
        $renderer->render_group_element(
2805
            'recordings_deleted_default',
2806
            $renderer->render_group_element_checkbox('recordings_deleted_default', 1)
2807
        );
2808
        $renderer->render_group_element(
2809
            'recordings_deleted_editable',
2810
            $renderer->render_group_element_checkbox('recordings_deleted_editable', 0)
2811
        );
2812
        $renderer->render_group_element(
2813
            'recordings_imported_default',
2814
            $renderer->render_group_element_checkbox('recordings_imported_default', 0)
2815
        );
2816
        $renderer->render_group_element(
2817
            'recordings_imported_editable',
2818
            $renderer->render_group_element_checkbox('recordings_imported_editable', 1)
2819
        );
2820
        $renderer->render_group_element(
2821
            'recordings_preview_default',
2822
            $renderer->render_group_element_checkbox('recordings_preview_default', 1)
2823
        );
2824
        $renderer->render_group_element(
2825
            'recordings_preview_editable',
2826
            $renderer->render_group_element_checkbox('recordings_preview_editable', 0)
2827
        );
2828
        $renderer->render_group_element(
2829
            'recordings_sortorder',
2830
            $renderer->render_group_element_checkbox('recordings_sortorder', 0)
2831
        );
2832
        $renderer->render_group_element(
2833
            'recordings_validate_url',
2834
            $renderer->render_group_element_checkbox('recordings_validate_url', 1)
2835
        );
2836
    }
2837
}
2838
2839
/**
2840
 * Helper function renders wait for moderator settings if the feature is enabled.
2841
 *
2842
 * @param object $renderer
2843
 *
2844
 * @return void
2845
 */
2846
function bigbluebuttonbn_settings_waitmoderator(&$renderer) {
2847
    // Configuration for wait for moderator feature.
2848
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_wait_moderator_shown()) {
2849
        $renderer->render_group_header('waitformoderator');
2850
        $renderer->render_group_element(
2851
            'waitformoderator_default',
2852
            $renderer->render_group_element_checkbox('waitformoderator_default', 0)
2853
        );
2854
        $renderer->render_group_element(
2855
            'waitformoderator_editable',
2856
            $renderer->render_group_element_checkbox('waitformoderator_editable', 1)
2857
        );
2858
        $renderer->render_group_element(
2859
            'waitformoderator_ping_interval',
2860
            $renderer->render_group_element_text('waitformoderator_ping_interval', 10, PARAM_INT)
2861
        );
2862
        $renderer->render_group_element(
2863
            'waitformoderator_cache_ttl',
2864
            $renderer->render_group_element_text('waitformoderator_cache_ttl', 60, PARAM_INT)
2865
        );
2866
    }
2867
}
2868
2869
/**
2870
 * Helper function renders static voice bridge settings if the feature is enabled.
2871
 *
2872
 * @param object $renderer
2873
 *
2874
 * @return void
2875
 */
2876
function bigbluebuttonbn_settings_voicebridge(&$renderer) {
2877
    // Configuration for "static voice bridge" feature.
2878
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_static_voice_bridge_shown()) {
2879
        $renderer->render_group_header('voicebridge');
2880
        $renderer->render_group_element(
2881
            'voicebridge_editable',
2882
            $renderer->render_group_element_checkbox('voicebridge_editable', 0)
2883
        );
2884
    }
2885
}
2886
2887
/**
2888
 * Helper function renders preuploaded presentation settings if the feature is enabled.
2889
 *
2890
 * @param object $renderer
2891
 *
2892
 * @return void
2893
 */
2894
function bigbluebuttonbn_settings_preupload(&$renderer) {
2895
    // Configuration for "preupload presentation" feature.
2896
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_preupload_presentation_shown()) {
2897
        // This feature only works if curl is installed.
2898
        $preuploaddescripion = get_string('config_preuploadpresentation_description', 'bigbluebuttonbn');
2899
        if (!extension_loaded('curl')) {
2900
            $preuploaddescripion .= '<div class="form-defaultinfo">';
2901
            $preuploaddescripion .= get_string('config_warning_curl_not_installed', 'bigbluebuttonbn');
2902
            $preuploaddescripion .= '</div><br>';
2903
        }
2904
        $renderer->render_group_header('preuploadpresentation', null, $preuploaddescripion);
2905
        if (extension_loaded('curl')) {
2906
            $renderer->render_group_element(
2907
                'preuploadpresentation_enabled',
2908
                $renderer->render_group_element_checkbox('preuploadpresentation_enabled', 0)
2909
            );
2910
        }
2911
    }
2912
}
2913
2914
/**
2915
 * Helper function renders preuploaded presentation manage file if the feature is enabled.
2916
 * This allow to select a file for use as default in all BBB instances if preuploaded presetantion is enable.
2917
 *
2918
 * @param object $renderer
2919
 *
2920
 * @return void
2921
 */
2922
function bigbluebuttonbn_settings_preupload_manage_default_file(&$renderer) {
2923
    // Configuration for "preupload presentation" feature.
2924
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_preupload_presentation_shown()) {
2925
        if (extension_loaded('curl')) {
2926
            // This feature only works if curl is installed.
2927
            $renderer->render_filemanager_default_file_presentation("presentation_default");
2928
        }
2929
    }
2930
}
2931
2932
/**
2933
 * Helper function renders userlimit settings if the feature is enabled.
2934
 *
2935
 * @param object $renderer
2936
 *
2937
 * @return void
2938
 */
2939
function bigbluebuttonbn_settings_userlimit(&$renderer) {
2940
    // Configuration for "user limit" feature.
2941
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_user_limit_shown()) {
2942
        $renderer->render_group_header('userlimit');
2943
        $renderer->render_group_element(
2944
            'userlimit_default',
2945
            $renderer->render_group_element_text('userlimit_default', 0, PARAM_INT)
2946
        );
2947
        $renderer->render_group_element(
2948
            'userlimit_editable',
2949
            $renderer->render_group_element_checkbox('userlimit_editable', 0)
2950
        );
2951
    }
2952
}
2953
2954
/**
2955
 * Helper function renders duration settings if the feature is enabled.
2956
 *
2957
 * @param object $renderer
2958
 *
2959
 * @return void
2960
 */
2961
function bigbluebuttonbn_settings_duration(&$renderer) {
2962
    // Configuration for "scheduled duration" feature.
2963
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_scheduled_duration_shown()) {
2964
        $renderer->render_group_header('scheduled');
2965
        $renderer->render_group_element(
2966
            'scheduled_duration_enabled',
2967
            $renderer->render_group_element_checkbox('scheduled_duration_enabled', 1)
2968
        );
2969
        $renderer->render_group_element(
2970
            'scheduled_duration_compensation',
2971
            $renderer->render_group_element_text('scheduled_duration_compensation', 10, PARAM_INT)
2972
        );
2973
        $renderer->render_group_element(
2974
            'scheduled_pre_opening',
2975
            $renderer->render_group_element_text('scheduled_pre_opening', 10, PARAM_INT)
2976
        );
2977
    }
2978
}
2979
2980
/**
2981
 * Helper function renders participant settings if the feature is enabled.
2982
 *
2983
 * @param object $renderer
2984
 *
2985
 * @return void
2986
 */
2987
function bigbluebuttonbn_settings_participants(&$renderer) {
2988
    // Configuration for defining the default role/user that will be moderator on new activities.
2989
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_moderator_default_shown()) {
2990
        $renderer->render_group_header('participant');
2991
        // UI for 'participants' feature.
2992
        $roles = bigbluebuttonbn_get_roles(null, false);
2993
        $owner = array('0' => get_string('mod_form_field_participant_list_type_owner', 'bigbluebuttonbn'));
2994
        $renderer->render_group_element(
2995
            'participant_moderator_default',
2996
            $renderer->render_group_element_configmultiselect(
2997
                'participant_moderator_default',
2998
                array_keys($owner),
2999
                $owner + $roles // CONTRIB-7966: don't use array_merge here so it does not reindex the array.
3000
            )
3001
        );
3002
    }
3003
}
3004
3005
/**
3006
 * Helper function renders notification settings if the feature is enabled.
3007
 *
3008
 * @param object $renderer
3009
 *
3010
 * @return void
3011
 */
3012
function bigbluebuttonbn_settings_notifications(&$renderer) {
3013
    // Configuration for "send notifications" feature.
3014
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_send_notifications_shown()) {
3015
        $renderer->render_group_header('sendnotifications');
3016
        $renderer->render_group_element(
3017
            'sendnotifications_enabled',
3018
            $renderer->render_group_element_checkbox('sendnotifications_enabled', 1)
3019
        );
3020
    }
3021
}
3022
3023
/**
3024
 * Helper function renders client type settings if the feature is enabled.
3025
 *
3026
 * @param object $renderer
3027
 *
3028
 * @return void
3029
 */
3030
function bigbluebuttonbn_settings_clienttype(&$renderer) {
3031
    // Configuration for "clienttype" feature.
3032
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_clienttype_shown()) {
3033
        $renderer->render_group_header('clienttype');
3034
        $renderer->render_group_element(
3035
            'clienttype_editable',
3036
            $renderer->render_group_element_checkbox('clienttype_editable', 0)
3037
        );
3038
        // Web Client default.
3039
        $default = intval((int) \mod_bigbluebuttonbn\locallib\config::get('clienttype_default'));
3040
        $choices = array(BIGBLUEBUTTON_CLIENTTYPE_FLASH => get_string('mod_form_block_clienttype_flash', 'bigbluebuttonbn'),
3041
            BIGBLUEBUTTON_CLIENTTYPE_HTML5 => get_string('mod_form_block_clienttype_html5', 'bigbluebuttonbn'));
3042
        $renderer->render_group_element(
3043
            'clienttype_default',
3044
            $renderer->render_group_element_configselect(
3045
                'clienttype_default',
3046
                $default,
3047
                $choices
3048
            )
3049
        );
3050
    }
3051
}
3052
3053
/**
3054
 * Helper function renders general settings if the feature is enabled.
3055
 *
3056
 * @param object $renderer
3057
 *
3058
 * @return void
3059
 */
3060 View Code Duplication
function bigbluebuttonbn_settings_muteonstart(&$renderer) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3061
    // Configuration for BigBlueButton.
3062
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_muteonstart_shown()) {
3063
        $renderer->render_group_header('muteonstart');
3064
        $renderer->render_group_element(
3065
            'muteonstart_default',
3066
            $renderer->render_group_element_checkbox('muteonstart_default', 0)
3067
        );
3068
        $renderer->render_group_element(
3069
            'muteonstart_editable',
3070
            $renderer->render_group_element_checkbox('muteonstart_editable', 0)
3071
        );
3072
    }
3073
}
3074
3075
/**
3076
 * Helper function renders general settings if the feature is enabled.
3077
 *
3078
 * @param object $renderer
3079
 *
3080
 * @return void
3081
 */
3082
function bigbluebuttonbn_settings_locksettings(&$renderer) {
3083
    $renderer->render_group_header('locksettings');
3084
    // Configuration for various lock settings for meetings.
3085
    bigbluebuttonbn_settings_disablecam($renderer);
3086
    bigbluebuttonbn_settings_disablemic($renderer);
3087
    bigbluebuttonbn_settings_disableprivatechat($renderer);
3088
    bigbluebuttonbn_settings_disablepublicchat($renderer);
3089
    bigbluebuttonbn_settings_disablenote($renderer);
3090
    bigbluebuttonbn_settings_hideuserlist($renderer);
3091
    bigbluebuttonbn_settings_lockedlayout($renderer);
3092
    bigbluebuttonbn_settings_lockonjoin($renderer);
3093
    bigbluebuttonbn_settings_lockonjoinconfigurable($renderer);
3094
}
3095
3096
/**
3097
 * Helper function renders general settings if the feature is enabled.
3098
 *
3099
 * @param object $renderer
3100
 *
3101
 * @return void
3102
 */
3103
function bigbluebuttonbn_settings_disablecam(&$renderer) {
3104
    // Configuration for BigBlueButton.
3105
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disablecam_shown()) {
3106
        $renderer->render_group_element(
3107
            'disablecam_default',
3108
            $renderer->render_group_element_checkbox('disablecam_default', 0)
3109
        );
3110
        $renderer->render_group_element(
3111
            'disablecam_editable',
3112
            $renderer->render_group_element_checkbox('disablecam_editable', 1)
3113
        );
3114
    }
3115
}
3116
3117
/**
3118
 * Helper function renders general settings if the feature is enabled.
3119
 *
3120
 * @param object $renderer
3121
 *
3122
 * @return void
3123
 */
3124
function bigbluebuttonbn_settings_disablemic(&$renderer) {
3125
    // Configuration for BigBlueButton.
3126
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disablemic_shown()) {
3127
        $renderer->render_group_element(
3128
            'disablemic_default',
3129
            $renderer->render_group_element_checkbox('disablemic_default', 0)
3130
        );
3131
        $renderer->render_group_element(
3132
            'disablecam_editable',
3133
            $renderer->render_group_element_checkbox('disablemic_editable', 1)
3134
        );
3135
    }
3136
}
3137
3138
/**
3139
 * Helper function renders general settings if the feature is enabled.
3140
 *
3141
 * @param object $renderer
3142
 *
3143
 * @return void
3144
 */
3145
function bigbluebuttonbn_settings_disableprivatechat(&$renderer) {
3146
    // Configuration for BigBlueButton.
3147
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disableprivatechat_shown()) {
3148
        $renderer->render_group_element(
3149
            'disableprivatechat_default',
3150
            $renderer->render_group_element_checkbox('disableprivatechat_default', 0)
3151
        );
3152
        $renderer->render_group_element(
3153
            'disableprivatechat_editable',
3154
            $renderer->render_group_element_checkbox('disableprivatechat_editable', 1)
3155
        );
3156
    }
3157
}
3158
3159
/**
3160
 * Helper function renders general settings if the feature is enabled.
3161
 *
3162
 * @param object $renderer
3163
 *
3164
 * @return void
3165
 */
3166
function bigbluebuttonbn_settings_disablepublicchat(&$renderer) {
3167
    // Configuration for BigBlueButton.
3168
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disablepublicchat_shown()) {
3169
        $renderer->render_group_element(
3170
            'disablepublicchat_default',
3171
            $renderer->render_group_element_checkbox('disablepublicchat_default', 0)
3172
        );
3173
        $renderer->render_group_element(
3174
            'disablepublicchat_editable',
3175
            $renderer->render_group_element_checkbox('disablepublicchat_editable', 1)
3176
        );
3177
    }
3178
}
3179
3180
/**
3181
 * Helper function renders general settings if the feature is enabled.
3182
 *
3183
 * @param object $renderer
3184
 *
3185
 * @return void
3186
 */
3187
function bigbluebuttonbn_settings_disablenote(&$renderer) {
3188
    // Configuration for BigBlueButton.
3189
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disablenote_shown()) {
3190
        $renderer->render_group_element(
3191
            'disablenote_default',
3192
            $renderer->render_group_element_checkbox('disablenote_default', 0)
3193
        );
3194
        $renderer->render_group_element(
3195
            'disablenote_editable',
3196
            $renderer->render_group_element_checkbox('disablenote_editable', 1)
3197
        );
3198
    }
3199
}
3200
3201
/**
3202
 * Helper function renders general settings if the feature is enabled.
3203
 *
3204
 * @param object $renderer
3205
 *
3206
 * @return void
3207
 */
3208
function bigbluebuttonbn_settings_hideuserlist(&$renderer) {
3209
    // Configuration for BigBlueButton.
3210
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_hideuserlist_shown()) {
3211
        $renderer->render_group_element(
3212
            'hideuserlist_default',
3213
            $renderer->render_group_element_checkbox('hideuserlist_default', 0)
3214
        );
3215
        $renderer->render_group_element(
3216
            'hideuserlist_editable',
3217
            $renderer->render_group_element_checkbox('hideuserlist_editable', 1)
3218
        );
3219
    }
3220
}
3221
3222
/**
3223
 * Helper function renders general settings if the feature is enabled.
3224
 *
3225
 * @param object $renderer
3226
 *
3227
 * @return void
3228
 */
3229
function bigbluebuttonbn_settings_lockedlayout(&$renderer) {
3230
    // Configuration for BigBlueButton.
3231
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_lockedlayout_shown()) {
3232
        $renderer->render_group_element(
3233
            'lockedlayout_default',
3234
            $renderer->render_group_element_checkbox('lockedlayout_default', 0)
3235
        );
3236
        $renderer->render_group_element(
3237
            'lockedlayout_editable',
3238
            $renderer->render_group_element_checkbox('lockedlayout_editable', 1)
3239
        );
3240
    }
3241
}
3242
3243
/**
3244
 * Helper function renders general settings if the feature is enabled.
3245
 *
3246
 * @param object $renderer
3247
 *
3248
 * @return void
3249
 */
3250
function bigbluebuttonbn_settings_lockonjoin(&$renderer) {
3251
    // Configuration for BigBlueButton.
3252
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_lockonjoin_shown()) {
3253
        $renderer->render_group_element(
3254
            'lockonjoin_default',
3255
            $renderer->render_group_element_checkbox('lockonjoin_default', 0)
3256
        );
3257
        $renderer->render_group_element(
3258
            'lockonjoin_editable',
3259
            $renderer->render_group_element_checkbox('lockonjoin_editable', 1)
3260
        );
3261
    }
3262
}
3263
3264
/**
3265
 * Helper function renders general settings if the feature is enabled.
3266
 *
3267
 * @param object $renderer
3268
 *
3269
 * @return void
3270
 */
3271
function bigbluebuttonbn_settings_lockonjoinconfigurable(&$renderer) {
3272
    // Configuration for BigBlueButton.
3273
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_lockonjoinconfigurable_shown()) {
3274
        $renderer->render_group_element(
3275
            'lockonjoinconfigurable_default',
3276
            $renderer->render_group_element_checkbox('lockonjoinconfigurable_default', 0)
3277
        );
3278
        $renderer->render_group_element(
3279
            'lockonjoinconfigurable_editable',
3280
            $renderer->render_group_element_checkbox('lockonjoinconfigurable_editable', 1)
3281
        );
3282
    }
3283
}
3284
3285
/**
3286
 * Helper function renders default messages settings.
3287
 *
3288
 * @param object $renderer
3289
 *
3290
 * @return void
3291
 */
3292
function bigbluebuttonbn_settings_default_messages(&$renderer) {
3293
    $renderer->render_group_header('default_messages');
3294
    $renderer->render_group_element(
3295
        'welcome_default',
3296
        $renderer->render_group_element_textarea('welcome_default', '', PARAM_TEXT)
3297
    );
3298
}
3299
3300
/**
3301
 * Helper function renders extended settings if any of the features there is enabled.
3302
 *
3303
 * @param object $renderer
3304
 *
3305
 * @return void
3306
 */
3307
function bigbluebuttonbn_settings_extended(&$renderer) {
3308
    // Configuration for extended capabilities.
3309
    if (!(boolean) \mod_bigbluebuttonbn\settings\validator::section_settings_extended_shown()) {
3310
        return;
3311
    }
3312
    $renderer->render_group_header('extended_capabilities');
3313
    // UI for 'notify users when recording ready' feature.
3314
    $renderer->render_group_element(
3315
        'recordingready_enabled',
3316
        $renderer->render_group_element_checkbox('recordingready_enabled', 0)
3317
    );
3318
    // Configuration for extended BN capabilities should go here.
3319
}
3320
3321
/**
3322
 * Helper function renders experimental settings if any of the features there is enabled.
3323
 *
3324
 * @param object $renderer
3325
 *
3326
 * @return void
3327
 */
3328
function bigbluebuttonbn_settings_experimental(&$renderer) {
3329
    // Configuration for experimental features should go here.
3330
    $renderer->render_group_header('experimental_features');
3331
    // UI for 'register meeting events' feature.
3332
    $renderer->render_group_element(
3333
        'meetingevents_enabled',
3334
        $renderer->render_group_element_checkbox('meetingevents_enabled', 0)
3335
    );
3336
}
3337
3338
/**
3339
 * Helper function returns a sha1 encoded string that is unique and will be used as a seed for meetingid.
3340
 *
3341
 * @return string
3342
 */
3343
function bigbluebuttonbn_unique_meetingid_seed() {
3344
    global $DB;
3345
    do {
3346
        $encodedseed = sha1(bigbluebuttonbn_random_password(12));
3347
        $meetingid = (string) $DB->get_field('bigbluebuttonbn', 'meetingid', array('meetingid' => $encodedseed));
3348
    } while ($meetingid == $encodedseed);
3349
    return $encodedseed;
3350
}
3351
3352
/**
3353
 * Helper function renders the link used for recording type in row for the data used by the recording table.
3354
 *
3355
 * @param array $recording
3356
 * @param array $bbbsession
3357
 * @param array $playback
3358
 *
3359
 * @return boolean
3360
 */
3361
function bigbluebuttonbn_include_recording_data_row_type($recording, $bbbsession, $playback) {
3362
    // All types that are not restricted are included.
3363
    if (array_key_exists('restricted', $playback) && strtolower($playback['restricted']) == 'false') {
3364
        return true;
3365
    }
3366
    // All types that are not statistics are included.
3367
    if ($playback['type'] != 'statistics') {
3368
        return true;
3369
    }
3370
    // Exclude imported recordings.
3371
    if (isset($recording['imported'])) {
3372
        return false;
3373
    }
3374
    // Exclude non moderators.
3375
    if (!$bbbsession['administrator'] && !$bbbsession['moderator']) {
3376
        return false;
3377
    }
3378
    return true;
3379
}
3380
3381
/**
3382
 * Renders the general warning message.
3383
 *
3384
 * @param string $message
3385
 * @param string $type
3386
 * @param string $href
3387
 * @param string $text
3388
 * @param string $class
3389
 *
3390
 * @return string
3391
 */
3392
function bigbluebuttonbn_render_warning($message, $type = 'info', $href = '', $text = '', $class = '') {
3393
    global $OUTPUT;
3394
    $output = "\n";
3395
    // Evaluates if config_warning is enabled.
3396
    if (empty($message)) {
3397
        return $output;
3398
    }
3399
    $output .= $OUTPUT->box_start(
3400
        'box boxalignleft adminerror alert alert-' . $type . ' alert-block fade in',
3401
        'bigbluebuttonbn_view_general_warning'
3402
    ) . "\n";
3403
    $output .= '    ' . $message . "\n";
3404
    $output .= '  <div class="singlebutton pull-right">' . "\n";
3405
    if (!empty($href)) {
3406
        $output .= bigbluebuttonbn_render_warning_button($href, $text, $class);
3407
    }
3408
    $output .= '  </div>' . "\n";
3409
    $output .= $OUTPUT->box_end() . "\n";
3410
    return $output;
3411
}
3412
3413
/**
3414
 * Renders the general warning button.
3415
 *
3416
 * @param string $href
3417
 * @param string $text
3418
 * @param string $class
3419
 * @param string $title
3420
 *
3421
 * @return string
3422
 */
3423
function bigbluebuttonbn_render_warning_button($href, $text = '', $class = '', $title = '') {
3424
    if ($text == '') {
3425
        $text = get_string('ok', 'moodle');
3426
    }
3427
    if ($title == '') {
3428
        $title = $text;
3429
    }
3430
    if ($class == '') {
3431
        $class = 'btn btn-secondary';
3432
    }
3433
    $output = '  <form method="post" action="' . $href . '" class="form-inline">' . "\n";
3434
    $output .= '      <button type="submit" class="' . $class . '"' . "\n";
3435
    $output .= '          title="' . $title . '"' . "\n";
3436
    $output .= '          >' . $text . '</button>' . "\n";
3437
    $output .= '  </form>' . "\n";
3438
    return $output;
3439
}
3440
3441
/**
3442
 * Check if a BigBlueButtonBN is available to be used by the current user.
3443
 *
3444
 * @param  stdClass  $bigbluebuttonbn  BigBlueButtonBN instance
3445
 *
3446
 * @return boolean                     status if room available and current user allowed to join
3447
 */
3448
function bigbluebuttonbn_get_availability_status($bigbluebuttonbn) {
3449
    list($roomavailable) = bigbluebuttonbn_room_is_available($bigbluebuttonbn);
3450
    list($usercanjoin) = bigbluebuttonbn_user_can_join_meeting($bigbluebuttonbn);
3451
    return ($roomavailable && $usercanjoin);
3452
}
3453
3454
/**
3455
 * Helper for evaluating if scheduled activity is avaiable.
3456
 *
3457
 * @param  stdClass  $bigbluebuttonbn  BigBlueButtonBN instance
3458
 *
3459
 * @return array                       status (room available or not and possible warnings)
3460
 */
3461
function bigbluebuttonbn_room_is_available($bigbluebuttonbn) {
3462
    $open = true;
3463
    $closed = false;
3464
    $warnings = array();
3465
3466
    $timenow = time();
3467
    $timeopen = $bigbluebuttonbn->openingtime;
3468
    $timeclose = $bigbluebuttonbn->closingtime;
3469
    if (!empty($timeopen) && $timeopen > $timenow) {
3470
        $open = false;
3471
    }
3472
    if (!empty($timeclose) && $timenow > $timeclose) {
3473
        $closed = true;
3474
    }
3475
3476
    if (!$open || $closed) {
3477
        if (!$open) {
3478
            $warnings['notopenyet'] = userdate($timeopen);
3479
        }
3480
        if ($closed) {
3481
            $warnings['expired'] = userdate($timeclose);
3482
        }
3483
        return array(false, $warnings);
3484
    }
3485
3486
    return array(true, $warnings);
3487
}
3488
3489
/**
3490
 * Helper for evaluating if meeting can be joined.
3491
 *
3492
 * @param  stdClass $bigbluebuttonbn  BigBlueButtonBN instance
3493
 * @param  string   $mid
3494
 * @param  integer  $userid
3495
 *
3496
 * @return array    status (user allowed to join or not and possible message)
3497
 */
3498
function bigbluebuttonbn_user_can_join_meeting($bigbluebuttonbn, $mid = null, $userid = null) {
3499
    // By default, use a meetingid without groups.
3500
    if (empty($mid)) {
3501
        $mid = $bigbluebuttonbn->meetingid . '-' . $bigbluebuttonbn->course . '-' . $bigbluebuttonbn->id;
3502
    }
3503
    // When meeting is running, all authorized users can join right in.
3504
    if (bigbluebuttonbn_is_meeting_running($mid)) {
3505
        return array(true, get_string('view_message_conference_in_progress', 'bigbluebuttonbn'));
3506
    }
3507
    // When meeting is not running, see if the user can join.
3508
    $context = context_course::instance($bigbluebuttonbn->course);
3509
    $participantlist = bigbluebuttonbn_get_participant_list($bigbluebuttonbn, $context);
3510
    $isadmin = is_siteadmin($userid);
3511
    $ismoderator = bigbluebuttonbn_is_moderator($context, $participantlist, $userid);
3512
    // If user is administrator, moderator or if is viewer and no waiting is required, join allowed.
3513
    if ($isadmin || $ismoderator || !$bigbluebuttonbn->wait) {
3514
        return array(true, get_string('view_message_conference_room_ready', 'bigbluebuttonbn'));
3515
    }
3516
    // Otherwise, no join allowed.
3517
    return array(false, get_string('view_message_conference_wait_for_moderator', 'bigbluebuttonbn'));
3518
}
3519
3520
/**
3521
 * Helper for getting a value from a bigbluebuttonbn cache.
3522
 *
3523
 * @param  string   $name       BigBlueButtonBN cache
3524
 * @param  string   $key        Key to be retrieved
3525
 * @param  integer  $default    Default value in case key is not found or it is empty
3526
 *
3527
 * @return variable key value
3528
 */
3529
function bigbluebuttonbn_cache_get($name, $key, $default = null) {
3530
    $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', $name);
3531
    $result = $cache->get($key);
3532
    if (!empty($result)) {
3533
        return $result;
3534
    }
3535
    return $default;
3536
}
3537
3538
/**
3539
 * Helper for setting a value in a bigbluebuttonbn cache.
3540
 *
3541
 * @param  string   $name       BigBlueButtonBN cache
3542
 * @param  string   $key        Key to be created/updated
3543
 * @param  variable $value      Default value to be set
3544
 */
3545
function bigbluebuttonbn_cache_set($name, $key, $value) {
3546
    $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', $name);
3547
    $cache->set($key, $value);
3548
}
3549
3550
/**
3551
 * Helper for getting the owner userid of a bigbluebuttonbn instance.
3552
 *
3553
 * @param  stdClass $bigbluebuttonbn  BigBlueButtonBN instance
3554
 *
3555
 * @return integer ownerid (a valid user id or null if not registered/found)
3556
 */
3557
function bigbluebuttonbn_instance_ownerid($bigbluebuttonbn) {
3558
    global $DB;
3559
    $filters = array('bigbluebuttonbnid' => $bigbluebuttonbn->id, 'log' => 'Add');
3560
    $ownerid = (integer) $DB->get_field('bigbluebuttonbn_logs', 'userid', $filters);
3561
    return $ownerid;
3562
}
3563
3564
/**
3565
 * Helper evaluates if the bigbluebutton server used belongs to blindsidenetworks domain.
3566
 *
3567
 * @return boolean
3568
 */
3569
function bigbluebuttonbn_has_html5_client() {
3570
    $checkurl = \mod_bigbluebuttonbn\locallib\bigbluebutton::root() . "html5client/check";
3571
    $curlinfo = bigbluebuttonbn_wrap_xml_load_file_curl_request($checkurl, 'HEAD');
3572
    return (isset($curlinfo['http_code']) && $curlinfo['http_code'] == 200);
3573
}
3574
3575
/**
3576
 * Return the status of an activity [open|not_started|ended].
3577
 *
3578
 * @param array $bbbsession
3579
 * @return string
3580
 */
3581 View Code Duplication
function bigbluebuttonbn_view_get_activity_status(&$bbbsession) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3582
    $now = time();
3583
    if (!empty($bbbsession['bigbluebuttonbn']->openingtime) && $now < $bbbsession['bigbluebuttonbn']->openingtime) {
3584
        // The activity has not been opened.
3585
        return 'not_started';
3586
    }
3587
    if (!empty($bbbsession['bigbluebuttonbn']->closingtime) && $now > $bbbsession['bigbluebuttonbn']->closingtime) {
3588
        // The activity has been closed.
3589
        return 'ended';
3590
    }
3591
    // The activity is open.
3592
    return 'open';
3593
}
3594
3595
/**
3596
 * Set session URLs.
3597
 *
3598
 * @param array $bbbsession
3599
 * @param int $id
3600
 * @return string
3601
 */
3602
function bigbluebuttonbn_view_session_config(&$bbbsession, $id) {
3603
    // Operation URLs.
3604
    $bbbsession['bigbluebuttonbnURL'] = plugin::necurl(
3605
        '/mod/bigbluebuttonbn/view.php',
3606
        ['id' => $bbbsession['cm']->id]
3607
    );
3608
    $bbbsession['logoutURL'] = plugin::necurl(
3609
        '/mod/bigbluebuttonbn/bbb_view.php',
3610
        ['action' => 'logout', 'id' => $id, 'bn' => $bbbsession['bigbluebuttonbn']->id]
3611
    );
3612
    $bbbsession['recordingReadyURL'] = plugin::necurl(
3613
        '/mod/bigbluebuttonbn/bbb_broker.php',
3614
        ['action' => 'recording_ready', 'bigbluebuttonbn' => $bbbsession['bigbluebuttonbn']->id]
3615
    );
3616
    $bbbsession['meetingEventsURL'] = plugin::necurl(
3617
        '/mod/bigbluebuttonbn/bbb_broker.php',
3618
        ['action' => 'meeting_events', 'bigbluebuttonbn' => $bbbsession['bigbluebuttonbn']->id]
3619
    );
3620
    $bbbsession['joinURL'] = plugin::necurl(
3621
        '/mod/bigbluebuttonbn/bbb_view.php',
3622
        ['action' => 'join', 'id' => $id, 'bn' => $bbbsession['bigbluebuttonbn']->id]
3623
    );
3624
3625
    // Check status and set extra values.
3626
    $activitystatus = bigbluebuttonbn_view_get_activity_status($bbbsession); // In locallib.
3627 View Code Duplication
    if ($activitystatus == 'ended') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3628
        $bbbsession['presentation'] = bigbluebuttonbn_get_presentation_array(
3629
            $bbbsession['context'],
3630
            $bbbsession['bigbluebuttonbn']->presentation
3631
        );
3632
    } else if ($activitystatus == 'open') {
3633
        $bbbsession['presentation'] = bigbluebuttonbn_get_presentation_array(
3634
            $bbbsession['context'],
3635
            $bbbsession['bigbluebuttonbn']->presentation,
3636
            $bbbsession['bigbluebuttonbn']->id
3637
        );
3638
    }
3639
3640
    return $activitystatus;
3641
}
3642
3643
/**
3644
 * Helper for preparing metadata used while creating the meeting.
3645
 *
3646
 * @param  array    $bbbsession
3647
 * @return array
3648
 */
3649
function bigbluebuttonbn_create_meeting_metadata(&$bbbsession) {
3650
    global $USER;
3651
    // Create standard metadata.
3652
    $metadata = [
3653
        'bbb-origin' => $bbbsession['origin'],
3654
        'bbb-origin-version' => $bbbsession['originVersion'],
3655
        'bbb-origin-server-name' => $bbbsession['originServerName'],
3656
        'bbb-origin-server-common-name' => $bbbsession['originServerCommonName'],
3657
        'bbb-origin-tag' => $bbbsession['originTag'],
3658
        'bbb-context' => $bbbsession['course']->fullname,
3659
        'bbb-context-id' => $bbbsession['course']->id,
3660
        'bbb-context-name' => trim(html_to_text($bbbsession['course']->fullname, 0)),
3661
        'bbb-context-label' => trim(html_to_text($bbbsession['course']->shortname, 0)),
3662
        'bbb-recording-name' => bigbluebuttonbn_html2text($bbbsession['meetingname'], 64),
3663
        'bbb-recording-description' => bigbluebuttonbn_html2text($bbbsession['meetingdescription'], 64),
3664
        'bbb-recording-tags' => bigbluebuttonbn_get_tags($bbbsession['cm']->id), // Same as $id.
3665
    ];
3666
    // Special metadata for recording processing.
3667
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('recordingstatus_enabled')) {
3668
        $metadata["bn-recording-status"] = json_encode(
3669
            array(
3670
                'email' => array('"' . fullname($USER) . '" <' . $USER->email . '>'),
3671
                'context' => $bbbsession['bigbluebuttonbnURL'],
3672
            )
3673
        );
3674
    }
3675
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('recordingready_enabled')) {
3676
        $metadata['bn-recording-ready-url'] = $bbbsession['recordingReadyURL'];
3677
    }
3678
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('meetingevents_enabled')) {
3679
        $metadata['analytics-callback-url'] = $bbbsession['meetingEventsURL'];
3680
    }
3681
    // Special metadata for Opencast recordings
3682 View Code Duplication
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('oc_recording') 
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3683
        && bigbluebuttonbn_check_opencast($bbbsession['course']->id)) {
3684
        $metadata['opencast-dc-isPartOf'] = bigbluebuttonbn_check_opencast($bbbsession['course']->id);
3685
    }
3686
    return $metadata;
3687
}
3688
3689
/**
3690
 * Helper for checking/retreiving seriesid Opencast plugin.
3691
 *
3692
 * @param  string    $courseid
3693
 * @return boolean|string
3694
 */
3695
function bigbluebuttonbn_check_opencast($courseid = null) {
3696
    $block_plugins = core_plugin_manager::instance()->get_plugins_of_type('block');
3697
    if (in_array('opencast', array_keys($block_plugins))) {
3698
        $opencast = \block_opencast\local\apibridge::get_instance();
3699
        if (!$opencast) {
3700
            return false;
3701
        }
3702
        if ($courseid) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $courseid of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
3703
            $seriesid = $opencast->get_stored_seriesid($courseid);
3704
            $ocseriesid = $opencast->get_course_series($courseid);
3705
            if (!$seriesid || ($seriesid && !$ocseriesid)) {
3706
                return flase;
3707
            }
3708
            return $seriesid;
3709
        }
3710
        return true;
3711
    }
3712
    return false;
3713
}