Completed
Pull Request — master (#367)
by
unknown
03:44
created

locallib.php ➔ bigbluebuttonbn_settings_accessmodal()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 15
rs 9.7666
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, $rids = []) {
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), 'recordID' => implode(',', $rids)]);
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
1637
        if ((bool)\mod_bigbluebuttonbn\locallib\config::get('recordings_proxy_playback')) {
1638
            $parseurl = parse_url($image['url']);
1639
            $url = "./proxy_presentation.php{$parseurl['path']}";
1640
        } else {
1641
            $url = $image['url'];
1642
        }
1643
1644
        $recordingpreview .= html_writer::start_tag('div', array('class' => ''));
1645
        $recordingpreview .= html_writer::empty_tag(
1646
            'img',
1647
            array('src' => trim($url) . '?' . time(), 'class' => 'recording-thumbnail pull-left')
1648
        );
1649
        $recordingpreview .= html_writer::end_tag('div');
1650
    }
1651
    $recordingpreview .= html_writer::end_tag('div');
1652
    $recordingpreview .= html_writer::start_tag('div', array('class' => 'row'));
1653
    $recordingpreview .= html_writer::tag(
1654
        'div',
1655
        get_string('view_recording_preview_help', 'bigbluebuttonbn'),
1656
        array('class' => 'text-center text-muted small')
1657
    );
1658
    $recordingpreview .= html_writer::end_tag('div');
1659
    $recordingpreview .= html_writer::end_tag('div');
1660
    return $recordingpreview;
1661
}
1662
1663
/**
1664
 * Helper function renders recording types to be used in row for the data used by the recording table.
1665
 *
1666
 * @param array $recording
1667
 * @param array $bbbsession
1668
 *
1669
 * @return string
1670
 */
1671
function bigbluebuttonbn_get_recording_data_row_types($recording, $bbbsession) {
1672
    $dataimported = 'false';
1673
    $title = '';
1674
    if (isset($recording['imported'])) {
1675
        $dataimported = 'true';
1676
        $title = get_string('view_recording_link_warning', 'bigbluebuttonbn');
1677
    }
1678
    $visibility = '';
1679
    if ($recording['published'] === 'false') {
1680
        $visibility = 'hidden ';
1681
    }
1682
    $id = 'playbacks-' . $recording['recordID'];
1683
    $recordingtypes = html_writer::start_tag('div', array('id' => $id, 'data-imported' => $dataimported,
1684
        'data-meetingid' => $recording['meetingID'], 'data-recordingid' => $recording['recordID'],
1685
        'title' => $title, $visibility => $visibility));
1686
    foreach ($recording['playbacks'] as $playback) {
1687
        $recordingtypes .= bigbluebuttonbn_get_recording_data_row_type($recording, $bbbsession, $playback);
1688
    }
1689
    $recordingtypes .= html_writer::end_tag('div');
1690
    return $recordingtypes;
1691
}
1692
1693
/**
1694
 * Helper function renders the link used for recording type in row for the data used by the recording table.
1695
 *
1696
 * @param array $recording
1697
 * @param array $bbbsession
1698
 * @param array $playback
1699
 *
1700
 * @return string
1701
 */
1702
function bigbluebuttonbn_get_recording_data_row_type($recording, $bbbsession, $playback) {
1703
    global $CFG, $OUTPUT;
1704
    if (!bigbluebuttonbn_include_recording_data_row_type($recording, $bbbsession, $playback)) {
1705
        return '';
1706
    }
1707
    $text = bigbluebuttonbn_get_recording_type_text($playback['type']);
1708
    $href = $CFG->wwwroot . '/mod/bigbluebuttonbn/bbb_view.php?action=play&bn=' . $bbbsession['bigbluebuttonbn']->id .
1709
        '&mid=' . $recording['meetingID'] . '&rid=' . $recording['recordID'] . '&rtype=' . $playback['type'];
1710
    if (!isset($recording['imported']) || !isset($recording['protected']) || $recording['protected'] === 'false') {
1711
        $href .= '&href=' . urlencode(trim($playback['url']));
1712
    }
1713
    $linkattributes = array(
1714
        'id' => 'recording-play-' . $playback['type'] . '-' . $recording['recordID'],
1715
        'class' => 'btn btn-sm btn-default',
1716
        'onclick' => 'M.mod_bigbluebuttonbn.recordings.recordingPlay(this);',
1717
        'data-action' => 'play',
1718
        'data-target' => $playback['type'],
1719
        'data-href' => $href,
1720
      );
1721
    if ($CFG->bigbluebuttonbn_recordings_validate_url && !bigbluebuttonbn_is_bn_server()
1722
            && !bigbluebuttonbn_is_valid_resource(trim($playback['url']))) {
1723
        $linkattributes['class'] = 'btn btn-sm btn-warning';
1724
        $linkattributes['title'] = get_string('view_recording_format_errror_unreachable', 'bigbluebuttonbn');
1725
        unset($linkattributes['data-href']);
1726
    }
1727
    return $OUTPUT->action_link('#', $text, null, $linkattributes) . '&#32;';
1728
}
1729
1730
/**
1731
 * Helper function to handle yet unknown recording types
1732
 *
1733
 * @param string $playbacktype : for now presentation, video, statistics, capture, notes, podcast
1734
 *
1735
 * @return string the matching language string or a capitalised version of the provided string
1736
 */
1737
function bigbluebuttonbn_get_recording_type_text($playbacktype) {
1738
    // Check first if string exists, and if it does'nt just default to the capitalised version of the string.
1739
    $text = ucwords($playbacktype);
1740
    $typestringid = 'view_recording_format_' . $playbacktype;
1741
    if (get_string_manager()->string_exists($typestringid, 'bigbluebuttonbn')) {
1742
        $text = get_string($typestringid, 'bigbluebuttonbn');
1743
    }
1744
    return $text;
1745
}
1746
1747
/**
1748
 * Helper function validates a remote resource.
1749
 *
1750
 * @param string $url
1751
 *
1752
 * @return boolean
1753
 */
1754
function bigbluebuttonbn_is_valid_resource($url) {
1755
    $urlhost = parse_url($url, PHP_URL_HOST);
1756
    $serverurlhost = parse_url(\mod_bigbluebuttonbn\locallib\config::get('server_url'), PHP_URL_HOST);
1757
    // Skip validation when the recording URL host is the same as the configured BBB server.
1758
    if ($urlhost == $serverurlhost) {
1759
        return true;
1760
    }
1761
    // Skip validation when the recording URL was already validated.
1762
    $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...
1763
    if (array_key_exists($urlhost, $validatedurls)) {
1764
        return $validatedurls[$urlhost];
1765
    }
1766
    // Validate the recording URL.
1767
    $validatedurls[$urlhost] = true;
1768
    $curlinfo = bigbluebuttonbn_wrap_xml_load_file_curl_request($url, 'HEAD');
1769
    if (!isset($curlinfo['http_code']) || $curlinfo['http_code'] != 200) {
1770
        $error = "Resources hosted by " . $urlhost . " are unreachable. Server responded with code " . $curlinfo['http_code'];
1771
        debugging($error, DEBUG_DEVELOPER);
1772
        $validatedurls[$urlhost] = false;
1773
    }
1774
    bigbluebuttonbn_cache_set('recordings_cache', 'validated_urls', $validatedurls);
1775
    return $validatedurls[$urlhost];
1776
}
1777
1778
/**
1779
 * Helper function renders the name for meeting used in row for the data used by the recording table.
1780
 *
1781
 * @param array $recording
1782
 * @param array $bbbsession
1783
 *
1784
 * @return string
1785
 */
1786
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...
1787
    $payload = array();
1788
    $source = 'meetingName';
1789
    $metaname = trim($recording['meetingName']);
1790
    return bigbluebuttonbn_get_recording_data_row_text($recording, $metaname, $source, $payload);
1791
}
1792
1793
/**
1794
 * Helper function renders the name for recording used in row for the data used by the recording table.
1795
 *
1796
 * @param array $recording
1797
 * @param array $bbbsession
1798
 *
1799
 * @return string
1800
 */
1801
function bigbluebuttonbn_get_recording_data_row_meta_activity($recording, $bbbsession) {
1802
    $payload = array();
1803 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...
1804
        $payload = array('recordingid' => $recording['recordID'], 'meetingid' => $recording['meetingID'],
1805
            'action' => 'edit', 'tag' => 'edit',
1806
            'target' => 'name');
1807
    }
1808
    $oldsource = 'meta_contextactivity';
1809
    if (isset($recording[$oldsource])) {
1810
        $metaname = trim($recording[$oldsource]);
1811
        return bigbluebuttonbn_get_recording_data_row_text($recording, $metaname, $oldsource, $payload);
1812
    }
1813
    $newsource = 'meta_bbb-recording-name';
1814 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...
1815
        $metaname = trim($recording[$newsource]);
1816
        return bigbluebuttonbn_get_recording_data_row_text($recording, $metaname, $newsource, $payload);
1817
    }
1818
    $metaname = trim($recording['meetingName']);
1819
    return bigbluebuttonbn_get_recording_data_row_text($recording, $metaname, $newsource, $payload);
1820
}
1821
1822
/**
1823
 * Helper function renders the description for recording used in row for the data used by the recording table.
1824
 *
1825
 * @param array $recording
1826
 * @param array $bbbsession
1827
 *
1828
 * @return string
1829
 */
1830
function bigbluebuttonbn_get_recording_data_row_meta_description($recording, $bbbsession) {
1831
    $payload = array();
1832 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...
1833
        $payload = array('recordingid' => $recording['recordID'], 'meetingid' => $recording['meetingID'],
1834
            'action' => 'edit', 'tag' => 'edit',
1835
            'target' => 'description');
1836
    }
1837
    $oldsource = 'meta_contextactivitydescription';
1838 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...
1839
        $metadescription = trim($recording[$oldsource]);
1840
        return bigbluebuttonbn_get_recording_data_row_text($recording, $metadescription, $oldsource, $payload);
1841
    }
1842
    $newsource = 'meta_bbb-recording-description';
1843 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...
1844
        $metadescription = trim($recording[$newsource]);
1845
        return bigbluebuttonbn_get_recording_data_row_text($recording, $metadescription, $newsource, $payload);
1846
    }
1847
    return bigbluebuttonbn_get_recording_data_row_text($recording, '', $newsource, $payload);
1848
}
1849
1850
/**
1851
 * Helper function renders text element for recording used in row for the data used by the recording table.
1852
 *
1853
 * @param array $recording
1854
 * @param string $text
1855
 * @param string $source
1856
 * @param array $data
1857
 *
1858
 * @return string
1859
 */
1860
function bigbluebuttonbn_get_recording_data_row_text($recording, $text, $source, $data) {
1861
    $htmltext = '<span>' . htmlentities($text) . '</span>';
1862
    if (empty($data)) {
1863
        return $htmltext;
1864
    }
1865
    $target = $data['action'] . '-' . $data['target'];
1866
    $id = 'recording-' . $target . '-' . $data['recordingid'];
1867
    $attributes = array('id' => $id, 'class' => 'quickeditlink col-md-20',
1868
        'data-recordingid' => $data['recordingid'], 'data-meetingid' => $data['meetingid'],
1869
        'data-target' => $data['target'], 'data-source' => $source);
1870
    $head = html_writer::start_tag('div', $attributes);
1871
    $tail = html_writer::end_tag('div');
1872
    $payload = array('action' => $data['action'], 'tag' => $data['tag'], 'target' => $data['target']);
1873
    $htmllink = bigbluebuttonbn_actionbar_render_button($recording, $payload);
1874
    return $head . $htmltext . $htmllink . $tail;
1875
}
1876
1877
/**
1878
 * Helper function render a button for the recording action bar
1879
 *
1880
 * @param array $recording
1881
 * @param array $data
1882
 *
1883
 * @return string
1884
 */
1885
function bigbluebuttonbn_actionbar_render_button($recording, $data) {
1886
    global $OUTPUT;
1887
    if (empty($data)) {
1888
        return '';
1889
    }
1890
    $target = $data['action'];
1891
    if (isset($data['target'])) {
1892
        $target .= '-' . $data['target'];
1893
    }
1894
    $id = 'recording-' . $target . '-' . $recording['recordID'];
1895
    $onclick = 'M.mod_bigbluebuttonbn.recordings.recording' . ucfirst($data['action']) . '(this); return false;';
1896
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('recording_icons_enabled')) {
1897
        // With icon for $manageaction.
1898
        $iconattributes = array('id' => $id, 'class' => 'iconsmall');
1899
        $linkattributes = array(
1900
            'id' => $id,
1901
            'onclick' => $onclick,
1902
            'data-action' => $data['action'],
1903
        );
1904
        if (!isset($recording['imported'])) {
1905
            $linkattributes['data-links'] = bigbluebuttonbn_count_recording_imported_instances(
1906
                $recording['recordID']
1907
            );
1908
        }
1909
        if (isset($data['disabled'])) {
1910
            $iconattributes['class'] .= ' fa-' . $data['disabled'];
1911
            $linkattributes['class'] = 'disabled';
1912
            unset($linkattributes['onclick']);
1913
        }
1914
        $icon = new pix_icon(
1915
            'i/' . $data['tag'],
1916
            get_string('view_recording_list_actionbar_' . $data['action'], 'bigbluebuttonbn'),
1917
            'moodle',
1918
            $iconattributes
1919
        );
1920
        return $OUTPUT->action_icon('#', $icon, null, $linkattributes, false);
1921
    }
1922
    // With text for $manageaction.
1923
    $linkattributes = array('title' => get_string($data['tag']), 'class' => 'btn btn-xs btn-danger',
1924
        'onclick' => $onclick);
1925
    return $OUTPUT->action_link('#', get_string($data['action']), null, $linkattributes);
1926
}
1927
1928
/**
1929
 * Helper function builds the recording table.
1930
 *
1931
 * @param array $bbbsession
1932
 * @param array $recordings
1933
 * @param array $tools
1934
 *
1935
 * @return object
1936
 */
1937
function bigbluebuttonbn_get_recording_table($bbbsession, $recordings, $tools = ['protect', 'publish', 'delete']) {
1938
    global $DB;
1939
    // Declare the table.
1940
    $table = new html_table();
1941
    $table->data = array();
1942
    // Initialize table headers.
1943
    $table->head[] = get_string('view_recording_playback', 'bigbluebuttonbn');
1944
    $table->head[] = get_string('view_recording_name', 'bigbluebuttonbn');
1945
    $table->head[] = get_string('view_recording_description', 'bigbluebuttonbn');
1946
    if (bigbluebuttonbn_get_recording_data_preview_enabled($bbbsession)) {
1947
        $table->head[] = get_string('view_recording_preview', 'bigbluebuttonbn');
1948
    }
1949
    $table->head[] = get_string('view_recording_date', 'bigbluebuttonbn');
1950
    $table->head[] = get_string('view_recording_duration', 'bigbluebuttonbn');
1951
    $table->align = array('left', 'left', 'left', 'left', 'left', 'center');
1952
    $table->size = array('', '', '', '', '', '');
1953
    if ($bbbsession['managerecordings']) {
1954
        $table->head[] = get_string('view_recording_actionbar', 'bigbluebuttonbn');
1955
        $table->align[] = 'left';
1956
        $table->size[] = (count($tools) * 40) . 'px';
1957
    }
1958
    // Get the groups of the user.
1959
    $usergroups = groups_get_all_groups($bbbsession['course']->id, $bbbsession['userID']);
1960
1961
    // Build table content.
1962
    foreach ($recordings as $recording) {
1963
        $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...
1964
        $shortmeetingid = explode('-', $recording['meetingID']);
1965
        if (isset($shortmeetingid[0])) {
1966
            $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...
1967
        }
1968
        // Check if the record belongs to a Visible Group type.
1969
        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...
1970
        $groupmode = groups_get_activity_groupmode($cm);
1971
        $displayrow = true;
1972
        if (($groupmode != VISIBLEGROUPS)
1973
                && !$bbbsession['administrator'] && !$bbbsession['moderator']) {
1974
            $groupid = explode('[', $recording['meetingID']);
1975
            if (isset($groupid[1])) {
1976
                // It is a group recording and the user is not moderator/administrator. Recording should not be included by default.
1977
                $displayrow = false;
1978
                $groupid = explode(']', $groupid[1]);
1979
                if (isset($groupid[0])) {
1980
                    foreach ($usergroups as $usergroup) {
1981
                        if ($usergroup->id == $groupid[0]) {
1982
                            // Include recording if the user is in the same group.
1983
                            $displayrow = true;
1984
                        }
1985
                    }
1986
                }
1987
            }
1988
        }
1989
        if ($displayrow) {
1990
            $rowdata = bigbluebuttonbn_get_recording_data_row($bbbsession, $recording, $tools);
1991
            if (!empty($rowdata)) {
1992
                $row = bigbluebuttonbn_get_recording_table_row($bbbsession, $recording, $rowdata);
1993
                array_push($table->data, $row);
1994
            }
1995
        }
1996
    }
1997
    return $table;
1998
}
1999
2000
/**
2001
 * Helper function builds the recording table row and insert into table.
2002
 *
2003
 * @param array $bbbsession
2004
 * @param array $recording
2005
 * @param object $rowdata
2006
 *
2007
 * @return object
2008
 */
2009
function bigbluebuttonbn_get_recording_table_row($bbbsession, $recording, $rowdata) {
2010
    $row = new html_table_row();
2011
    $row->id = 'recording-tr-' . $recording['recordID'];
2012
    $row->attributes['data-imported'] = 'false';
2013
    $texthead = '';
2014
    $texttail = '';
2015
    if (isset($recording['imported'])) {
2016
        $row->attributes['title'] = get_string('view_recording_link_warning', 'bigbluebuttonbn');
2017
        $row->attributes['data-imported'] = 'true';
2018
        $texthead = '<em>';
2019
        $texttail = '</em>';
2020
    }
2021
    $rowdata->date_formatted = str_replace(' ', '&nbsp;', $rowdata->date_formatted);
2022
    $row->cells = array();
2023
    $row->cells[] = $texthead . $rowdata->playback . $texttail;
2024
    $row->cells[] = $texthead . $rowdata->recording . $texttail;
2025
    $row->cells[] = $texthead . $rowdata->description . $texttail;
2026
    if (bigbluebuttonbn_get_recording_data_preview_enabled($bbbsession)) {
2027
        $row->cells[] = $rowdata->preview;
2028
    }
2029
    $row->cells[] = $texthead . $rowdata->date_formatted . $texttail;
2030
    $row->cells[] = $rowdata->duration_formatted;
2031
    if ($bbbsession['managerecordings']) {
2032
        $row->cells[] = $rowdata->actionbar;
2033
    }
2034
    return $row;
2035
}
2036
2037
/**
2038
 * Get the basic data to display in the table view
2039
 *
2040
 * @param array $bbbsession the current session
2041
 * @param array $enabledfeatures feature enabled for this activity
2042
 * @return associative array containing the recordings indexed by recordID, each recording is also a
2043
 * non sequential associative array itself that corresponds to the actual recording in BBB
2044
 */
2045
function bigbluebutton_get_recordings_for_table_view($bbbsession, $enabledfeatures) {
2046
    $bigbluebuttonbnid = null;
2047
    if ($enabledfeatures['showroom']) {
2048
        $bigbluebuttonbnid = $bbbsession['bigbluebuttonbn']->id;
2049
    }
2050
    // Get recordings.
2051
    $recordings = bigbluebuttonbn_get_recordings(
2052
        $bbbsession['course']->id, $bigbluebuttonbnid, $enabledfeatures['showroom'],
2053
        $bbbsession['bigbluebuttonbn']->recordings_deleted
2054
    );
2055
    if ($enabledfeatures['importrecordings']) {
2056
        // Get recording links.
2057
        $bigbluebuttonbnid = $bbbsession['bigbluebuttonbn']->id;
2058
        $recordingsimported = bigbluebuttonbn_get_recordings_imported_array(
2059
            $bbbsession['course']->id, $bigbluebuttonbnid, true
2060
        );
2061
        /* Perform aritmetic addition instead of merge so the imported recordings corresponding to existent
2062
         * recordings are not included. */
2063
        if ($bbbsession['bigbluebuttonbn']->recordings_imported) {
2064
            $recordings = $recordingsimported;
2065
        } else {
2066
            $recordings += $recordingsimported;
2067
        }
2068
    }
2069
    return $recordings;
2070
}
2071
2072
/**
2073
 * Helper function evaluates if recording row should be included in the table.
2074
 *
2075
 * @param array $bbbsession
2076
 * @param array $recording
2077
 *
2078
 * @return boolean
2079
 */
2080
function bigbluebuttonbn_include_recording_table_row($bbbsession, $recording) {
2081
    // Exclude unpublished recordings, only if user has no rights to manage them.
2082
    if ($recording['published'] != 'true' && !$bbbsession['managerecordings']) {
2083
        return false;
2084
    }
2085
    // Imported recordings are always shown as long as they are published.
2086
    if (isset($recording['imported'])) {
2087
        return true;
2088
    }
2089
    // Administrators and moderators are always allowed.
2090
    if ($bbbsession['administrator'] || $bbbsession['moderator']) {
2091
        return true;
2092
    }
2093
    // When groups are enabled, exclude those to which the user doesn't have access to.
2094
    if (isset($bbbsession['group']) && $recording['meetingID'] != $bbbsession['meetingid']) {
2095
        return false;
2096
    }
2097
    return true;
2098
}
2099
2100
/**
2101
 * Helper function triggers a send notification when the recording is ready.
2102
 *
2103
 * @param object $bigbluebuttonbn
2104
 *
2105
 * @return void
2106
 */
2107
function bigbluebuttonbn_send_notification_recording_ready($bigbluebuttonbn) {
2108
    \mod_bigbluebuttonbn\locallib\notifier::notify_recording_ready($bigbluebuttonbn);
2109
}
2110
2111
/**
2112
 * Helper function enqueues list of meeting events to be stored and processed as for completion.
2113
 *
2114
 * @param object $bigbluebuttonbn
2115
 * @param object $jsonobj
2116
 *
2117
 * @return void
2118
 */
2119
function bigbluebuttonbn_process_meeting_events($bigbluebuttonbn, $jsonobj) {
2120
    $meetingid = $jsonobj->{'meeting_id'};
2121
    $recordid = $jsonobj->{'internal_meeting_id'};
2122
    $attendees = $jsonobj->{'data'}->{'attendees'};
2123
    foreach ($attendees as $attendee) {
2124
        $userid = $attendee->{'ext_user_id'};
2125
        $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...
2126
        $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...
2127
        $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...
2128
        $meta['data'] = $attendee;
2129
        // Stores the log.
2130
        bigbluebuttonbn_log($bigbluebuttonbn, BIGBLUEBUTTON_LOG_EVENT_SUMMARY, $overrides, json_encode($meta));
2131
        // Enqueue a task for processing the completion.
2132
        bigbluebuttonbn_enqueue_completion_update($bigbluebuttonbn, $userid);
2133
    }
2134
}
2135
2136
/**
2137
 * Helper function enqueues one user for being validated as for completion.
2138
 *
2139
 * @param object $bigbluebuttonbn
2140
 * @param string $userid
2141
 *
2142
 * @return void
2143
 */
2144
function bigbluebuttonbn_enqueue_completion_update($bigbluebuttonbn, $userid) {
2145
    try {
2146
        // Create the instance of completion_update_state task.
2147
        $task = new \mod_bigbluebuttonbn\task\completion_update_state();
2148
        // Add custom data.
2149
        $data = array(
2150
            'bigbluebuttonbn' => $bigbluebuttonbn,
2151
            'userid' => $userid,
2152
        );
2153
        $task->set_custom_data($data);
2154
        // CONTRIB-7457: Task should be executed by a user, maybe Teacher as Student won't have rights for overriding.
2155
        // $ task -> set_userid ( $ user -> id );.
2156
        // Enqueue it.
2157
        \core\task\manager::queue_adhoc_task($task);
2158
    } catch (Exception $e) {
2159
        mtrace("Error while enqueuing completion_update_state task. " . (string) $e);
2160
    }
2161
}
2162
2163
/**
2164
 * Helper function enqueues completion trigger.
2165
 *
2166
 * @param object $bigbluebuttonbn
2167
 * @param string $userid
2168
 *
2169
 * @return void
2170
 */
2171
function bigbluebuttonbn_completion_update_state($bigbluebuttonbn, $userid) {
2172
    global $CFG;
2173
    require_once($CFG->libdir.'/completionlib.php');
2174
    list($course, $cm) = get_course_and_cm_from_instance($bigbluebuttonbn, 'bigbluebuttonbn');
2175
    $completion = new completion_info($course);
2176
    if (!$completion->is_enabled($cm)) {
2177
        mtrace("Completion not enabled");
2178
        return;
2179
    }
2180
    if (bigbluebuttonbn_get_completion_state($course, $cm, $userid, COMPLETION_AND)) {
2181
        mtrace("Completion succeeded for user $userid");
2182
        $completion->update_state($cm, COMPLETION_COMPLETE, $userid, true);
2183
    } else {
2184
        mtrace("Completion did not succeed for user $userid");
2185
    }
2186
}
2187
2188
/**
2189
 * Helper evaluates if the bigbluebutton server used belongs to blindsidenetworks domain.
2190
 *
2191
 * @return boolean
2192
 */
2193
function bigbluebuttonbn_is_bn_server() {
2194
    if (\mod_bigbluebuttonbn\locallib\config::get('bn_server')) {
2195
        return true;
2196
    }
2197
    $parsedurl = parse_url(\mod_bigbluebuttonbn\locallib\config::get('server_url'));
2198
    if (!isset($parsedurl['host'])) {
2199
        return false;
2200
    }
2201
    $h = $parsedurl['host'];
2202
    $hends = explode('.', $h);
2203
    $hendslength = count($hends);
2204
    return ($hends[$hendslength - 1] == 'com' && $hends[$hendslength - 2] == 'blindsidenetworks');
2205
}
2206
2207
/**
2208
 * Helper function returns a list of courses a user has access to, wrapped in an array that can be used
2209
 * by a html select.
2210
 *
2211
 * @param array $bbbsession
2212
 *
2213
 * @return array
2214
 */
2215
function bigbluebuttonbn_import_get_courses_for_select(array $bbbsession) {
2216
    if ($bbbsession['administrator']) {
2217
        $courses = get_courses('all', 'c.fullname ASC');
2218
        // It includes the name of the site as a course (category 0), so remove the first one.
2219
        unset($courses['1']);
2220
    } else {
2221
        $courses = enrol_get_users_courses($bbbsession['userID'], false, 'id,shortname,fullname');
2222
    }
2223
    $coursesforselect = [];
2224
    foreach ($courses as $course) {
2225
        $coursesforselect[$course->id] = $course->fullname . " (" . $course->shortname . ")";
2226
    }
2227
    return $coursesforselect;
2228
}
2229
2230
/**
2231
 * Helper function renders recording table.
2232
 *
2233
 * @param array $bbbsession
2234
 * @param array $recordings
2235
 * @param array $tools
2236
 *
2237
 * @return array
2238
 */
2239
function bigbluebuttonbn_output_recording_table($bbbsession, $recordings, $tools = ['protect', 'publish', 'delete']) {
2240
    if (isset($recordings) && !empty($recordings)) {
2241
        // There are recordings for this meeting.
2242
        $table = bigbluebuttonbn_get_recording_table($bbbsession, $recordings, $tools);
2243
    }
2244
    if (!isset($table) || !isset($table->data)) {
2245
        // Render a table with "No recordings".
2246
        return html_writer::div(
2247
            get_string('view_message_norecordings', 'bigbluebuttonbn'),
2248
            '',
2249
            array('id' => 'bigbluebuttonbn_recordings_table')
2250
        );
2251
    }
2252
    // Render the table.
2253
    return html_writer::div(html_writer::table($table), '', array('id' => 'bigbluebuttonbn_recordings_table'));
2254
}
2255
2256
/**
2257
 * Helper function to convert an html string to plain text.
2258
 *
2259
 * @param string $html
2260
 * @param integer $len
2261
 *
2262
 * @return string
2263
 */
2264
function bigbluebuttonbn_html2text($html, $len = 0) {
2265
    $text = strip_tags($html);
2266
    $text = str_replace('&nbsp;', ' ', $text);
2267
    $textlen = strlen($text);
2268
    $text = mb_substr($text, 0, $len);
2269
    if ($textlen > $len) {
2270
        $text .= '...';
2271
    }
2272
    return $text;
2273
}
2274
2275
/**
2276
 * Helper function to obtain the tags linked to a bigbluebuttonbn activity
2277
 *
2278
 * @param string $id
2279
 *
2280
 * @return string containing the tags separated by commas
2281
 */
2282
function bigbluebuttonbn_get_tags($id) {
2283
    if (class_exists('core_tag_tag')) {
2284
        return implode(',', core_tag_tag::get_item_tags_array('core', 'course_modules', $id));
2285
    }
2286
    return implode(',', tag_get_tags('bigbluebuttonbn', $id));
2287
}
2288
2289
/**
2290
 * Helper function to define the sql used for gattering the bigbluebuttonbnids whose meetingids should be included
2291
 * in the getRecordings request
2292
 *
2293
 * @param string $courseid
2294
 * @param string $bigbluebuttonbnid
2295
 * @param bool   $subset
2296
 *
2297
 * @return string containing the sql used for getting the target bigbluebuttonbn instances
2298
 */
2299
function bigbluebuttonbn_get_recordings_sql_select($courseid, $bigbluebuttonbnid = null, $subset = true) {
2300
    if (empty($courseid)) {
2301
        $courseid = 0;
2302
    }
2303
    if (empty($bigbluebuttonbnid)) {
2304
        return "course = '{$courseid}'";
2305
    }
2306
    if ($subset) {
2307
        return "id = '{$bigbluebuttonbnid}'";
2308
    }
2309
    return "id <> '{$bigbluebuttonbnid}' AND course = '{$courseid}'";
2310
}
2311
2312
/**
2313
 * Helper function to define the sql used for gattering the bigbluebuttonbnids whose meetingids should be included
2314
 * in the getRecordings request considering only those that belong to deleted activities.
2315
 *
2316
 * @param string $courseid
2317
 * @param string $bigbluebuttonbnid
2318
 * @param bool   $subset
2319
 *
2320
 * @return string containing the sql used for getting the target bigbluebuttonbn instances
2321
 */
2322 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...
2323
    $sql = "log = '" . BIGBLUEBUTTONBN_LOG_EVENT_DELETE . "' AND meta like '%has_recordings%' AND meta like '%true%'";
2324
    if (empty($courseid)) {
2325
        $courseid = 0;
2326
    }
2327
    if (empty($bigbluebuttonbnid)) {
2328
        return $sql . " AND courseid = {$courseid}";
2329
    }
2330
    if ($subset) {
2331
        return $sql . " AND bigbluebuttonbnid = '{$bigbluebuttonbnid}'";
2332
    }
2333
    return $sql . " AND courseid = {$courseid} AND bigbluebuttonbnid <> '{$bigbluebuttonbnid}'";
2334
}
2335
2336
/**
2337
 * Helper function to define the sql used for gattering the bigbluebuttonbnids whose meetingids should be included
2338
 * in the getRecordings request considering only those that belong to imported recordings.
2339
 *
2340
 * @param string $courseid
2341
 * @param string $bigbluebuttonbnid
2342
 * @param bool   $subset
2343
 *
2344
 * @return string containing the sql used for getting the target bigbluebuttonbn instances
2345
 */
2346 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...
2347
    $sql = "log = '" . BIGBLUEBUTTONBN_LOG_EVENT_IMPORT . "'";
2348
    if (empty($courseid)) {
2349
        $courseid = 0;
2350
    }
2351
    if (empty($bigbluebuttonbnid)) {
2352
        return $sql . " AND courseid = '{$courseid}'";
2353
    }
2354
    if ($subset) {
2355
        return $sql . " AND bigbluebuttonbnid = '{$bigbluebuttonbnid}'";
2356
    }
2357
    return $sql . " AND courseid = '{$courseid}' AND bigbluebuttonbnid <> '{$bigbluebuttonbnid}'";
2358
}
2359
2360
/**
2361
 * Helper function to get recordings and imported recordings together.
2362
 *
2363
 * @param string $courseid
2364
 * @param string $bigbluebuttonbnid
2365
 * @param bool   $subset
2366
 * @param bool   $includedeleted
2367
 *
2368
 * @return associative array containing the recordings indexed by recordID, each recording is also a
2369
 * non sequential associative array itself that corresponds to the actual recording in BBB
2370
 */
2371
function bigbluebuttonbn_get_allrecordings($courseid = 0, $bigbluebuttonbnid = null, $subset = true, $includedeleted = false) {
2372
    $recordings = bigbluebuttonbn_get_recordings($courseid, $bigbluebuttonbnid, $subset, $includedeleted);
2373
    $recordingsimported = bigbluebuttonbn_get_recordings_imported_array($courseid, $bigbluebuttonbnid, $subset);
2374
    return ($recordings + $recordingsimported);
2375
}
2376
2377
/**
2378
 * Helper function to retrieve recordings from the BigBlueButton. The references are stored as events
2379
 * in bigbluebuttonbn_logs.
2380
 *
2381
 * @param string $courseid
2382
 * @param string $bigbluebuttonbnid
2383
 * @param bool   $subset
2384
 * @param bool   $includedeleted
2385
 *
2386
 * @return associative array containing the recordings indexed by recordID, each recording is also a
2387
 * non sequential associative array itself that corresponds to the actual recording in BBB
2388
 */
2389
function bigbluebuttonbn_get_recordings($courseid = 0, $bigbluebuttonbnid = null, $subset = true, $includedeleted = false) {
2390
    global $DB;
2391
    $select = bigbluebuttonbn_get_recordings_sql_select($courseid, $bigbluebuttonbnid, $subset);
2392
    $bigbluebuttonbns = $DB->get_records_select_menu('bigbluebuttonbn', $select, null, 'id', 'id, meetingid');
2393
    /* Consider logs from deleted bigbluebuttonbn instances whose meetingids should be included in
2394
     * the getRecordings request. */
2395
    if ($includedeleted) {
2396
        $selectdeleted = bigbluebuttonbn_get_recordings_deleted_sql_select($courseid, $bigbluebuttonbnid, $subset);
2397
        $bigbluebuttonbnsdel = $DB->get_records_select_menu(
2398
            'bigbluebuttonbn_logs',
2399
            $selectdeleted,
2400
            null,
2401
            'bigbluebuttonbnid',
2402
            'bigbluebuttonbnid, meetingid'
2403
        );
2404
        if (!empty($bigbluebuttonbnsdel)) {
2405
            // Merge bigbluebuttonbnis from deleted instances, only keys are relevant.
2406
            // Artimetic merge is used in order to keep the keys.
2407
            $bigbluebuttonbns += $bigbluebuttonbnsdel;
2408
        }
2409
    }
2410
    // Gather the meetingids from bigbluebuttonbn logs that include a create with record=true.
2411
    if (empty($bigbluebuttonbns)) {
2412
        return array();
2413
    }
2414
    // Prepare select for loading records based on existent bigbluebuttonbns.
2415
    $sql = 'SELECT DISTINCT meetingid, bigbluebuttonbnid FROM {bigbluebuttonbn_logs} WHERE ';
2416
    $sql .= '(bigbluebuttonbnid=' . implode(' OR bigbluebuttonbnid=', array_keys($bigbluebuttonbns)) . ')';
2417
    // Include only Create events and exclude those with record not true.
2418
    $sql .= ' AND log = ? AND meta LIKE ? AND meta LIKE ?';
2419
    // Execute select for loading records based on existent bigbluebuttonbns.
2420
    $records = $DB->get_records_sql_menu($sql, array(BIGBLUEBUTTONBN_LOG_EVENT_CREATE, '%record%', '%true%'));
2421
    // Get actual recordings.
2422
    return bigbluebuttonbn_get_recordings_array(array_keys($records));
2423
}
2424
2425
/**
2426
 * Helper function iterates an array with recordings and unset those already imported.
2427
 *
2428
 * @param array $recordings
2429
 * @param integer $courseid
2430
 * @param integer $bigbluebuttonbnid
2431
 *
2432
 * @return array
2433
 */
2434
function bigbluebuttonbn_unset_existent_recordings_already_imported($recordings, $courseid, $bigbluebuttonbnid) {
2435
    $recordingsimported = bigbluebuttonbn_get_recordings_imported_array($courseid, $bigbluebuttonbnid, true);
2436
    foreach ($recordings as $key => $recording) {
2437
        if (isset($recordingsimported[$recording['recordID']])) {
2438
            unset($recordings[$key]);
2439
        }
2440
    }
2441
    return $recordings;
2442
}
2443
2444
/**
2445
 * Helper function to count the imported recordings for a recordingid.
2446
 *
2447
 * @param string $recordid
2448
 *
2449
 * @return integer
2450
 */
2451
function bigbluebuttonbn_count_recording_imported_instances($recordid) {
2452
    global $DB;
2453
    $sql = 'SELECT COUNT(DISTINCT id) FROM {bigbluebuttonbn_logs} WHERE log = ? AND meta LIKE ? AND meta LIKE ?';
2454
    return $DB->count_records_sql($sql, array(BIGBLUEBUTTONBN_LOG_EVENT_IMPORT, '%recordID%', "%{$recordid}%"));
2455
}
2456
2457
/**
2458
 * Helper function returns an array with all the instances of imported recordings for a recordingid.
2459
 *
2460
 * @param string $recordid
2461
 *
2462
 * @return array
2463
 */
2464
function bigbluebuttonbn_get_recording_imported_instances($recordid) {
2465
    global $DB;
2466
    $sql = 'SELECT * FROM {bigbluebuttonbn_logs} WHERE log = ? AND meta LIKE ? AND meta LIKE ?';
2467
    $recordingsimported = $DB->get_records_sql($sql, array(BIGBLUEBUTTONBN_LOG_EVENT_IMPORT, '%recordID%',
2468
        "%{$recordid}%"));
2469
    return $recordingsimported;
2470
}
2471
2472
/**
2473
 * Helper function to get how much callback events are logged.
2474
 *
2475
 * @param string $recordid
2476
 * @param string $callbacktype
2477
 *
2478
 * @return integer
2479
 */
2480
function bigbluebuttonbn_get_count_callback_event_log($recordid, $callbacktype = 'recording_ready') {
2481
    global $DB;
2482
    $sql = 'SELECT count(DISTINCT id) FROM {bigbluebuttonbn_logs} WHERE log = ? AND meta LIKE ? AND meta LIKE ?';
2483
    // Callback type added on version 2.4, validate recording_ready first or assume it on records with no callback.
2484
    if ($callbacktype == 'recording_ready') {
2485
        $sql .= ' AND (meta LIKE ? OR meta NOT LIKE ? )';
2486
        $count = $DB->count_records_sql($sql, array(BIGBLUEBUTTON_LOG_EVENT_CALLBACK, '%recordid%', "%$recordid%",
2487
            $callbacktype, 'callback'));
2488
        return $count;
2489
    }
2490
    $sql .= ' AND meta LIKE ?;';
2491
    $count = $DB->count_records_sql($sql, array(BIGBLUEBUTTON_LOG_EVENT_CALLBACK, '%recordid%', "%$recordid%", "%$callbacktype%"));
2492
    return $count;
2493
}
2494
2495
/**
2496
 * Helper function returns an array with the profiles (with features per profile) for the different types
2497
 * of bigbluebuttonbn instances.
2498
 *
2499
 * @return array
2500
 */
2501
function bigbluebuttonbn_get_instance_type_profiles() {
2502
    $instanceprofiles = array(
2503
        BIGBLUEBUTTONBN_TYPE_ALL => array('id' => BIGBLUEBUTTONBN_TYPE_ALL,
2504
            'name' => get_string('instance_type_default', 'bigbluebuttonbn'),
2505
            'features' => array('all')),
2506
        BIGBLUEBUTTONBN_TYPE_ROOM_ONLY => array('id' => BIGBLUEBUTTONBN_TYPE_ROOM_ONLY,
2507
            'name' => get_string('instance_type_room_only', 'bigbluebuttonbn'),
2508
            'features' => array('showroom', 'welcomemessage', 'voicebridge', 'waitformoderator', 'userlimit',
2509
                'recording', 'sendnotifications', 'preuploadpresentation', 'permissions', 'schedule', 'groups',
2510
                'modstandardelshdr', 'availabilityconditionsheader', 'tagshdr', 'competenciessection',
2511
                'clienttype', 'completionattendance', 'completionengagement', 'availabilityconditionsheader')),
2512
        BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY => array('id' => BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY,
2513
            'name' => get_string('instance_type_recording_only', 'bigbluebuttonbn'),
2514
            'features' => array('showrecordings', 'importrecordings', 'availabilityconditionsheader')),
2515
    );
2516
    return $instanceprofiles;
2517
}
2518
2519
/**
2520
 * Helper function returns an array with enabled features for an specific profile type.
2521
 *
2522
 * @param array $typeprofiles
2523
 * @param string $type
2524
 *
2525
 * @return array
2526
 */
2527
function bigbluebuttonbn_get_enabled_features($typeprofiles, $type = null) {
2528
    $enabledfeatures = array();
2529
    $features = $typeprofiles[BIGBLUEBUTTONBN_TYPE_ALL]['features'];
2530
    if (!is_null($type) && key_exists($type, $typeprofiles)) {
2531
        $features = $typeprofiles[$type]['features'];
2532
    }
2533
    $enabledfeatures['showroom'] = (in_array('all', $features) || in_array('showroom', $features));
2534
    // Evaluates if recordings are enabled for the Moodle site.
2535
    $enabledfeatures['showrecordings'] = false;
2536
    if (\mod_bigbluebuttonbn\locallib\config::recordings_enabled()) {
2537
        $enabledfeatures['showrecordings'] = (in_array('all', $features) || in_array('showrecordings', $features));
2538
    }
2539
    $enabledfeatures['importrecordings'] = false;
2540
    if (\mod_bigbluebuttonbn\locallib\config::importrecordings_enabled()) {
2541
        $enabledfeatures['importrecordings'] = (in_array('all', $features) || in_array('importrecordings', $features));
2542
    }
2543
    // Evaluates if clienttype is enabled for the Moodle site.
2544
    $enabledfeatures['clienttype'] = false;
2545
    if (\mod_bigbluebuttonbn\locallib\config::clienttype_enabled()) {
2546
        $enabledfeatures['clienttype'] = (in_array('all', $features) || in_array('clienttype', $features));
2547
    }
2548
    return $enabledfeatures;
2549
}
2550
2551
/**
2552
 * Helper function returns an array with the profiles (with features per profile) for the different types
2553
 * of bigbluebuttonbn instances that the user is allowed to create.
2554
 *
2555
 * @param boolean $room
2556
 * @param boolean $recording
2557
 *
2558
 * @return array
2559
 */
2560
function bigbluebuttonbn_get_instance_type_profiles_create_allowed($room, $recording) {
2561
    $profiles = bigbluebuttonbn_get_instance_type_profiles();
2562
    if (!$room) {
2563
        unset($profiles[BIGBLUEBUTTONBN_TYPE_ROOM_ONLY]);
2564
        unset($profiles[BIGBLUEBUTTONBN_TYPE_ALL]);
2565
    }
2566
    if (!$recording) {
2567
        unset($profiles[BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY]);
2568
        unset($profiles[BIGBLUEBUTTONBN_TYPE_ALL]);
2569
    }
2570
    return $profiles;
2571
}
2572
2573
/**
2574
 * Helper function returns an array with the profiles (with features per profile) for the different types
2575
 * of bigbluebuttonbn instances.
2576
 *
2577
 * @param array $profiles
2578
 *
2579
 * @return array
2580
 */
2581
function bigbluebuttonbn_get_instance_profiles_array($profiles = []) {
2582
    $profilesarray = array();
2583
    foreach ($profiles as $key => $profile) {
2584
        $profilesarray[$profile['id']] = $profile['name'];
2585
    }
2586
    return $profilesarray;
2587
}
2588
2589
/**
2590
 * Helper function returns time in a formatted string.
2591
 *
2592
 * @param integer $time
2593
 *
2594
 * @return string
2595
 */
2596
function bigbluebuttonbn_format_activity_time($time) {
2597
    global $CFG;
2598
    require_once($CFG->dirroot.'/calendar/lib.php');
2599
    $activitytime = '';
2600
    if ($time) {
2601
        $activitytime = calendar_day_representation($time) . ' ' .
2602
        get_string('mod_form_field_notification_msg_at', 'bigbluebuttonbn') . ' ' .
2603
        calendar_time_representation($time);
2604
    }
2605
    return $activitytime;
2606
}
2607
2608
/**
2609
 * Helper function returns array with all the strings to be used in javascript.
2610
 *
2611
 * @return array
2612
 */
2613
function bigbluebuttonbn_get_strings_for_js() {
2614
    $locale = bigbluebuttonbn_get_locale();
2615
    $stringman = get_string_manager();
2616
    $strings = $stringman->load_component_strings('bigbluebuttonbn', $locale);
2617
    return $strings;
2618
}
2619
2620
/**
2621
 * Helper function returns the locale set by moodle.
2622
 *
2623
 * @return string
2624
 */
2625
function bigbluebuttonbn_get_locale() {
2626
    $lang = get_string('locale', 'core_langconfig');
2627
    return substr($lang, 0, strpos($lang, '.'));
2628
}
2629
2630
/**
2631
 * Helper function returns the locale code based on the locale set by moodle.
2632
 *
2633
 * @return string
2634
 */
2635
function bigbluebuttonbn_get_localcode() {
2636
    $locale = bigbluebuttonbn_get_locale();
2637
    return substr($locale, 0, strpos($locale, '_'));
2638
}
2639
2640
/**
2641
 * Helper function returns array with the instance settings used in views.
2642
 *
2643
 * @param string $id
2644
 * @param object $bigbluebuttonbnid
2645
 *
2646
 * @return array
2647
 */
2648
function bigbluebuttonbn_view_validator($id, $bigbluebuttonbnid) {
2649
    if ($id) {
2650
        return bigbluebuttonbn_view_instance_id($id);
2651
    }
2652
    if ($bigbluebuttonbnid) {
2653
        return bigbluebuttonbn_view_instance_bigbluebuttonbn($bigbluebuttonbnid);
2654
    }
2655
}
2656
2657
/**
2658
 * Helper function returns array with the instance settings used in views based on id.
2659
 *
2660
 * @param string $id
2661
 *
2662
 * @return array
2663
 */
2664 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...
2665
    global $DB;
2666
    $cm = get_coursemodule_from_id('bigbluebuttonbn', $id, 0, false, MUST_EXIST);
2667
    $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
2668
    $bigbluebuttonbn = $DB->get_record('bigbluebuttonbn', array('id' => $cm->instance), '*', MUST_EXIST);
2669
    return array('cm' => $cm, 'course' => $course, 'bigbluebuttonbn' => $bigbluebuttonbn);
2670
}
2671
2672
/**
2673
 * Helper function returns array with the instance settings used in views based on bigbluebuttonbnid.
2674
 *
2675
 * @param object $bigbluebuttonbnid
2676
 *
2677
 * @return array
2678
 */
2679 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...
2680
    global $DB;
2681
    $bigbluebuttonbn = $DB->get_record('bigbluebuttonbn', array('id' => $bigbluebuttonbnid), '*', MUST_EXIST);
2682
    $course = $DB->get_record('course', array('id' => $bigbluebuttonbn->course), '*', MUST_EXIST);
2683
    $cm = get_coursemodule_from_instance('bigbluebuttonbn', $bigbluebuttonbn->id, $course->id, false, MUST_EXIST);
2684
    return array('cm' => $cm, 'course' => $course, 'bigbluebuttonbn' => $bigbluebuttonbn);
2685
}
2686
2687
/**
2688
 * Helper function renders general settings if the feature is enabled.
2689
 *
2690
 * @param object $renderer
2691
 *
2692
 * @return void
2693
 */
2694
function bigbluebuttonbn_settings_general(&$renderer) {
2695
    // Configuration for BigBlueButton.
2696
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_general_shown()) {
2697
        $renderer->render_group_header('general');
2698
        $renderer->render_group_element(
2699
            'server_url',
2700
            $renderer->render_group_element_text('server_url', BIGBLUEBUTTONBN_DEFAULT_SERVER_URL)
2701
        );
2702
        $renderer->render_group_element(
2703
            'shared_secret',
2704
            $renderer->render_group_element_text('shared_secret', BIGBLUEBUTTONBN_DEFAULT_SHARED_SECRET)
2705
        );
2706
    }
2707
}
2708
2709
/**
2710
 * Helper function renders record settings if the feature is enabled.
2711
 *
2712
 * @param object $renderer
2713
 *
2714
 * @return void
2715
 */
2716
function bigbluebuttonbn_settings_record(&$renderer) {
2717
    // Configuration for 'recording' feature.
2718
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_record_meeting_shown()) {
2719
        $renderer->render_group_header('recording');
2720
        $renderer->render_group_element(
2721
            'recording_default',
2722
            $renderer->render_group_element_checkbox('recording_default', 1)
2723
        );
2724
        $renderer->render_group_element(
2725
            'recording_editable',
2726
            $renderer->render_group_element_checkbox('recording_editable', 1)
2727
        );
2728
        $renderer->render_group_element(
2729
            'recording_icons_enabled',
2730
            $renderer->render_group_element_checkbox('recording_icons_enabled', 1)
2731
        );
2732
2733
        // Add recording start to load and allow/hide stop/pause.
2734
        $renderer->render_group_element(
2735
            'recording_all_from_start_default',
2736
            $renderer->render_group_element_checkbox('recording_all_from_start_default', 0)
2737
        );
2738
        $renderer->render_group_element(
2739
            'recording_all_from_start_editable',
2740
            $renderer->render_group_element_checkbox('recording_all_from_start_editable', 0)
2741
        );
2742
        $renderer->render_group_element(
2743
            'recording_hide_button_default',
2744
            $renderer->render_group_element_checkbox('recording_hide_button_default', 0)
2745
        );
2746
        $renderer->render_group_element(
2747
            'recording_hide_button_editable',
2748
            $renderer->render_group_element_checkbox('recording_hide_button_editable', 0)
2749
        );
2750
        $renderer->render_group_element(
2751
            'recording_hide_button_activityonly',
2752
            $renderer->render_group_element_checkbox('recording_hide_button_activityonly', 0)
2753
        );
2754
    }
2755
}
2756
2757
/**
2758
 * Helper function renders import recording settings if the feature is enabled.
2759
 *
2760
 * @param object $renderer
2761
 *
2762
 * @return void
2763
 */
2764 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...
2765
    // Configuration for 'import recordings' feature.
2766
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_import_recordings_shown()) {
2767
        $renderer->render_group_header('importrecordings');
2768
        $renderer->render_group_element(
2769
            'importrecordings_enabled',
2770
            $renderer->render_group_element_checkbox('importrecordings_enabled', 0)
2771
        );
2772
        $renderer->render_group_element(
2773
            'importrecordings_from_deleted_enabled',
2774
            $renderer->render_group_element_checkbox('importrecordings_from_deleted_enabled', 0)
2775
        );
2776
    }
2777
}
2778
2779
/**
2780
 * Helper function renders show recording settings if the feature is enabled.
2781
 *
2782
 * @param object $renderer
2783
 *
2784
 * @return void
2785
 */
2786
function bigbluebuttonbn_settings_showrecordings(&$renderer) {
2787
    // Configuration for 'show recordings' feature.
2788
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_show_recordings_shown()) {
2789
        $renderer->render_group_header('recordings');
2790
        $renderer->render_group_element(
2791
            'recordings_html_default',
2792
            $renderer->render_group_element_checkbox('recordings_html_default', 1)
2793
        );
2794
        $renderer->render_group_element(
2795
            'recordings_html_editable',
2796
            $renderer->render_group_element_checkbox('recordings_html_editable', 0)
2797
        );
2798
        $renderer->render_group_element(
2799
            'recordings_deleted_default',
2800
            $renderer->render_group_element_checkbox('recordings_deleted_default', 1)
2801
        );
2802
        $renderer->render_group_element(
2803
            'recordings_deleted_editable',
2804
            $renderer->render_group_element_checkbox('recordings_deleted_editable', 0)
2805
        );
2806
        $renderer->render_group_element(
2807
            'recordings_imported_default',
2808
            $renderer->render_group_element_checkbox('recordings_imported_default', 0)
2809
        );
2810
        $renderer->render_group_element(
2811
            'recordings_imported_editable',
2812
            $renderer->render_group_element_checkbox('recordings_imported_editable', 1)
2813
        );
2814
        $renderer->render_group_element(
2815
            'recordings_preview_default',
2816
            $renderer->render_group_element_checkbox('recordings_preview_default', 1)
2817
        );
2818
        $renderer->render_group_element(
2819
            'recordings_preview_editable',
2820
            $renderer->render_group_element_checkbox('recordings_preview_editable', 0)
2821
        );
2822
        $renderer->render_group_element(
2823
            'recordings_sortorder',
2824
            $renderer->render_group_element_checkbox('recordings_sortorder', 0)
2825
        );
2826
        $renderer->render_group_element(
2827
            'recordings_validate_url',
2828
            $renderer->render_group_element_checkbox('recordings_validate_url', 1)
2829
        );
2830
        $renderer->render_group_element(
2831
            'recordings_proxy_playback',
2832
            $renderer->render_group_element_checkbox('recordings_proxy_playback', 0)
2833
        );
2834
    }
2835
}
2836
2837
/**
2838
 * Helper function renders wait for moderator settings if the feature is enabled.
2839
 *
2840
 * @param object $renderer
2841
 *
2842
 * @return void
2843
 */
2844
function bigbluebuttonbn_settings_waitmoderator(&$renderer) {
2845
    // Configuration for wait for moderator feature.
2846
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_wait_moderator_shown()) {
2847
        $renderer->render_group_header('waitformoderator');
2848
        $renderer->render_group_element(
2849
            'waitformoderator_default',
2850
            $renderer->render_group_element_checkbox('waitformoderator_default', 0)
2851
        );
2852
        $renderer->render_group_element(
2853
            'waitformoderator_editable',
2854
            $renderer->render_group_element_checkbox('waitformoderator_editable', 1)
2855
        );
2856
        $renderer->render_group_element(
2857
            'waitformoderator_ping_interval',
2858
            $renderer->render_group_element_text('waitformoderator_ping_interval', 10, PARAM_INT)
2859
        );
2860
        $renderer->render_group_element(
2861
            'waitformoderator_cache_ttl',
2862
            $renderer->render_group_element_text('waitformoderator_cache_ttl', 60, PARAM_INT)
2863
        );
2864
    }
2865
}
2866
2867
/**
2868
 * Helper function renders static voice bridge settings if the feature is enabled.
2869
 *
2870
 * @param object $renderer
2871
 *
2872
 * @return void
2873
 */
2874
function bigbluebuttonbn_settings_voicebridge(&$renderer) {
2875
    // Configuration for "static voice bridge" feature.
2876
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_static_voice_bridge_shown()) {
2877
        $renderer->render_group_header('voicebridge');
2878
        $renderer->render_group_element(
2879
            'voicebridge_editable',
2880
            $renderer->render_group_element_checkbox('voicebridge_editable', 0)
2881
        );
2882
    }
2883
}
2884
2885
/**
2886
 * Helper function renders preuploaded presentation settings if the feature is enabled.
2887
 *
2888
 * @param object $renderer
2889
 *
2890
 * @return void
2891
 */
2892
function bigbluebuttonbn_settings_preupload(&$renderer) {
2893
    // Configuration for "preupload presentation" feature.
2894
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_preupload_presentation_shown()) {
2895
        // This feature only works if curl is installed.
2896
        $preuploaddescripion = get_string('config_preuploadpresentation_description', 'bigbluebuttonbn');
2897
        if (!extension_loaded('curl')) {
2898
            $preuploaddescripion .= '<div class="form-defaultinfo">';
2899
            $preuploaddescripion .= get_string('config_warning_curl_not_installed', 'bigbluebuttonbn');
2900
            $preuploaddescripion .= '</div><br>';
2901
        }
2902
        $renderer->render_group_header('preuploadpresentation', null, $preuploaddescripion);
2903
        if (extension_loaded('curl')) {
2904
            $renderer->render_group_element(
2905
                'preuploadpresentation_enabled',
2906
                $renderer->render_group_element_checkbox('preuploadpresentation_enabled', 0)
2907
            );
2908
        }
2909
    }
2910
}
2911
2912
/**
2913
 * Helper function renders preuploaded presentation manage file if the feature is enabled.
2914
 * This allow to select a file for use as default in all BBB instances if preuploaded presetantion is enable.
2915
 *
2916
 * @param object $renderer
2917
 *
2918
 * @return void
2919
 */
2920
function bigbluebuttonbn_settings_preupload_manage_default_file(&$renderer) {
2921
    // Configuration for "preupload presentation" feature.
2922
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_preupload_presentation_shown()) {
2923
        if (extension_loaded('curl')) {
2924
            // This feature only works if curl is installed.
2925
            $renderer->render_filemanager_default_file_presentation("presentation_default");
2926
        }
2927
    }
2928
}
2929
2930
/**
2931
 * Helper function renders userlimit settings if the feature is enabled.
2932
 *
2933
 * @param object $renderer
2934
 *
2935
 * @return void
2936
 */
2937
function bigbluebuttonbn_settings_userlimit(&$renderer) {
2938
    // Configuration for "user limit" feature.
2939
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_user_limit_shown()) {
2940
        $renderer->render_group_header('userlimit');
2941
        $renderer->render_group_element(
2942
            'userlimit_default',
2943
            $renderer->render_group_element_text('userlimit_default', 0, PARAM_INT)
2944
        );
2945
        $renderer->render_group_element(
2946
            'userlimit_editable',
2947
            $renderer->render_group_element_checkbox('userlimit_editable', 0)
2948
        );
2949
    }
2950
}
2951
2952
/**
2953
 * Helper function renders access modal settings if the feature is enabled.
2954
 *
2955
 * @param object $renderer
2956
 *
2957
 * @return void
2958
 */
2959
function bigbluebuttonbn_settings_accessmodal(&$renderer) {
2960
    // Configuration for "accessmodal" feature.
2961
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_accessmodal_shown()) {
2962
        $renderer->render_group_header('accessmodal');
2963
2964
        $renderer->render_group_element(
2965
            'accessmodal_default',
2966
            $renderer->render_group_element_editor('accessmodal_default', '', PARAM_RAW)
2967
        );
2968
        $renderer->render_group_element(
2969
            'accessmodal_editable',
2970
            $renderer->render_group_element_checkbox('accessmodal_editable', 0)
2971
        );
2972
    }
2973
}
2974
2975
/**
2976
 * Helper function renders duration settings if the feature is enabled.
2977
 *
2978
 * @param object $renderer
2979
 *
2980
 * @return void
2981
 */
2982
function bigbluebuttonbn_settings_duration(&$renderer) {
2983
    // Configuration for "scheduled duration" feature.
2984
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_scheduled_duration_shown()) {
2985
        $renderer->render_group_header('scheduled');
2986
        $renderer->render_group_element(
2987
            'scheduled_duration_enabled',
2988
            $renderer->render_group_element_checkbox('scheduled_duration_enabled', 1)
2989
        );
2990
        $renderer->render_group_element(
2991
            'scheduled_duration_compensation',
2992
            $renderer->render_group_element_text('scheduled_duration_compensation', 10, PARAM_INT)
2993
        );
2994
        $renderer->render_group_element(
2995
            'scheduled_pre_opening',
2996
            $renderer->render_group_element_text('scheduled_pre_opening', 10, PARAM_INT)
2997
        );
2998
    }
2999
}
3000
3001
/**
3002
 * Helper function renders participant settings if the feature is enabled.
3003
 *
3004
 * @param object $renderer
3005
 *
3006
 * @return void
3007
 */
3008
function bigbluebuttonbn_settings_participants(&$renderer) {
3009
    // Configuration for defining the default role/user that will be moderator on new activities.
3010
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_moderator_default_shown()) {
3011
        $renderer->render_group_header('participant');
3012
        // UI for 'participants' feature.
3013
        $roles = bigbluebuttonbn_get_roles(null, false);
3014
        $owner = array('0' => get_string('mod_form_field_participant_list_type_owner', 'bigbluebuttonbn'));
3015
        $renderer->render_group_element(
3016
            'participant_moderator_default',
3017
            $renderer->render_group_element_configmultiselect(
3018
                'participant_moderator_default',
3019
                array_keys($owner),
3020
                $owner + $roles // CONTRIB-7966: don't use array_merge here so it does not reindex the array.
3021
            )
3022
        );
3023
    }
3024
}
3025
3026
/**
3027
 * Helper function renders notification settings if the feature is enabled.
3028
 *
3029
 * @param object $renderer
3030
 *
3031
 * @return void
3032
 */
3033
function bigbluebuttonbn_settings_notifications(&$renderer) {
3034
    // Configuration for "send notifications" feature.
3035
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_send_notifications_shown()) {
3036
        $renderer->render_group_header('sendnotifications');
3037
        $renderer->render_group_element(
3038
            'sendnotifications_enabled',
3039
            $renderer->render_group_element_checkbox('sendnotifications_enabled', 1)
3040
        );
3041
    }
3042
}
3043
3044
/**
3045
 * Helper function renders client type settings if the feature is enabled.
3046
 *
3047
 * @param object $renderer
3048
 *
3049
 * @return void
3050
 */
3051
function bigbluebuttonbn_settings_clienttype(&$renderer) {
3052
    // Configuration for "clienttype" feature.
3053
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_clienttype_shown()) {
3054
        $renderer->render_group_header('clienttype');
3055
        $renderer->render_group_element(
3056
            'clienttype_editable',
3057
            $renderer->render_group_element_checkbox('clienttype_editable', 0)
3058
        );
3059
        // Web Client default.
3060
        $default = intval((int) \mod_bigbluebuttonbn\locallib\config::get('clienttype_default'));
3061
        $choices = array(BIGBLUEBUTTON_CLIENTTYPE_FLASH => get_string('mod_form_block_clienttype_flash', 'bigbluebuttonbn'),
3062
            BIGBLUEBUTTON_CLIENTTYPE_HTML5 => get_string('mod_form_block_clienttype_html5', 'bigbluebuttonbn'));
3063
        $renderer->render_group_element(
3064
            'clienttype_default',
3065
            $renderer->render_group_element_configselect(
3066
                'clienttype_default',
3067
                $default,
3068
                $choices
3069
            )
3070
        );
3071
    }
3072
}
3073
3074
/**
3075
 * Helper function renders general settings if the feature is enabled.
3076
 *
3077
 * @param object $renderer
3078
 *
3079
 * @return void
3080
 */
3081 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...
3082
    // Configuration for BigBlueButton.
3083
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_muteonstart_shown()) {
3084
        $renderer->render_group_header('muteonstart');
3085
        $renderer->render_group_element(
3086
            'muteonstart_default',
3087
            $renderer->render_group_element_checkbox('muteonstart_default', 0)
3088
        );
3089
        $renderer->render_group_element(
3090
            'muteonstart_editable',
3091
            $renderer->render_group_element_checkbox('muteonstart_editable', 0)
3092
        );
3093
    }
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_locksettings(&$renderer) {
3104
    $renderer->render_group_header('locksettings');
3105
    // Configuration for various lock settings for meetings.
3106
    bigbluebuttonbn_settings_disablecam($renderer);
3107
    bigbluebuttonbn_settings_disablemic($renderer);
3108
    bigbluebuttonbn_settings_disableprivatechat($renderer);
3109
    bigbluebuttonbn_settings_disablepublicchat($renderer);
3110
    bigbluebuttonbn_settings_disablenote($renderer);
3111
    bigbluebuttonbn_settings_hideuserlist($renderer);
3112
    bigbluebuttonbn_settings_lockedlayout($renderer);
3113
    bigbluebuttonbn_settings_lockonjoin($renderer);
3114
    bigbluebuttonbn_settings_lockonjoinconfigurable($renderer);
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_disablecam(&$renderer) {
3125
    // Configuration for BigBlueButton.
3126
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disablecam_shown()) {
3127
        $renderer->render_group_element(
3128
            'disablecam_default',
3129
            $renderer->render_group_element_checkbox('disablecam_default', 0)
3130
        );
3131
        $renderer->render_group_element(
3132
            'disablecam_editable',
3133
            $renderer->render_group_element_checkbox('disablecam_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_disablemic(&$renderer) {
3146
    // Configuration for BigBlueButton.
3147
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disablemic_shown()) {
3148
        $renderer->render_group_element(
3149
            'disablemic_default',
3150
            $renderer->render_group_element_checkbox('disablemic_default', 0)
3151
        );
3152
        $renderer->render_group_element(
3153
            'disablecam_editable',
3154
            $renderer->render_group_element_checkbox('disablemic_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_disableprivatechat(&$renderer) {
3167
    // Configuration for BigBlueButton.
3168
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disableprivatechat_shown()) {
3169
        $renderer->render_group_element(
3170
            'disableprivatechat_default',
3171
            $renderer->render_group_element_checkbox('disableprivatechat_default', 0)
3172
        );
3173
        $renderer->render_group_element(
3174
            'disableprivatechat_editable',
3175
            $renderer->render_group_element_checkbox('disableprivatechat_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_disablepublicchat(&$renderer) {
3188
    // Configuration for BigBlueButton.
3189
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disablepublicchat_shown()) {
3190
        $renderer->render_group_element(
3191
            'disablepublicchat_default',
3192
            $renderer->render_group_element_checkbox('disablepublicchat_default', 0)
3193
        );
3194
        $renderer->render_group_element(
3195
            'disablepublicchat_editable',
3196
            $renderer->render_group_element_checkbox('disablepublicchat_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_disablenote(&$renderer) {
3209
    // Configuration for BigBlueButton.
3210
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_disablenote_shown()) {
3211
        $renderer->render_group_element(
3212
            'disablenote_default',
3213
            $renderer->render_group_element_checkbox('disablenote_default', 0)
3214
        );
3215
        $renderer->render_group_element(
3216
            'disablenote_editable',
3217
            $renderer->render_group_element_checkbox('disablenote_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_hideuserlist(&$renderer) {
3230
    // Configuration for BigBlueButton.
3231
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_hideuserlist_shown()) {
3232
        $renderer->render_group_element(
3233
            'hideuserlist_default',
3234
            $renderer->render_group_element_checkbox('hideuserlist_default', 0)
3235
        );
3236
        $renderer->render_group_element(
3237
            'hideuserlist_editable',
3238
            $renderer->render_group_element_checkbox('hideuserlist_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_lockedlayout(&$renderer) {
3251
    // Configuration for BigBlueButton.
3252
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_lockedlayout_shown()) {
3253
        $renderer->render_group_element(
3254
            'lockedlayout_default',
3255
            $renderer->render_group_element_checkbox('lockedlayout_default', 0)
3256
        );
3257
        $renderer->render_group_element(
3258
            'lockedlayout_editable',
3259
            $renderer->render_group_element_checkbox('lockedlayout_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_lockonjoin(&$renderer) {
3272
    // Configuration for BigBlueButton.
3273
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_lockonjoin_shown()) {
3274
        $renderer->render_group_element(
3275
            'lockonjoin_default',
3276
            $renderer->render_group_element_checkbox('lockonjoin_default', 0)
3277
        );
3278
        $renderer->render_group_element(
3279
            'lockonjoin_editable',
3280
            $renderer->render_group_element_checkbox('lockonjoin_editable', 1)
3281
        );
3282
    }
3283
}
3284
3285
/**
3286
 * Helper function renders general settings if the feature is enabled.
3287
 *
3288
 * @param object $renderer
3289
 *
3290
 * @return void
3291
 */
3292
function bigbluebuttonbn_settings_lockonjoinconfigurable(&$renderer) {
3293
    // Configuration for BigBlueButton.
3294
    if ((boolean) \mod_bigbluebuttonbn\settings\validator::section_lockonjoinconfigurable_shown()) {
3295
        $renderer->render_group_element(
3296
            'lockonjoinconfigurable_default',
3297
            $renderer->render_group_element_checkbox('lockonjoinconfigurable_default', 0)
3298
        );
3299
        $renderer->render_group_element(
3300
            'lockonjoinconfigurable_editable',
3301
            $renderer->render_group_element_checkbox('lockonjoinconfigurable_editable', 1)
3302
        );
3303
    }
3304
}
3305
3306
/**
3307
 * Helper function renders default messages settings.
3308
 *
3309
 * @param object $renderer
3310
 *
3311
 * @return void
3312
 */
3313
function bigbluebuttonbn_settings_default_messages(&$renderer) {
3314
    $renderer->render_group_header('default_messages');
3315
    $renderer->render_group_element(
3316
        'welcome_default',
3317
        $renderer->render_group_element_textarea('welcome_default', '', PARAM_TEXT)
3318
    );
3319
}
3320
3321
/**
3322
 * Helper function renders extended settings if any of the features there is enabled.
3323
 *
3324
 * @param object $renderer
3325
 *
3326
 * @return void
3327
 */
3328
function bigbluebuttonbn_settings_extended(&$renderer) {
3329
    // Configuration for extended capabilities.
3330
    if (!(boolean) \mod_bigbluebuttonbn\settings\validator::section_settings_extended_shown()) {
3331
        return;
3332
    }
3333
    $renderer->render_group_header('extended_capabilities');
3334
    // UI for 'notify users when recording ready' feature.
3335
    $renderer->render_group_element(
3336
        'recordingready_enabled',
3337
        $renderer->render_group_element_checkbox('recordingready_enabled', 0)
3338
    );
3339
    // Configuration for extended BN capabilities should go here.
3340
}
3341
3342
/**
3343
 * Helper function renders experimental settings if any of the features there is enabled.
3344
 *
3345
 * @param object $renderer
3346
 *
3347
 * @return void
3348
 */
3349
function bigbluebuttonbn_settings_experimental(&$renderer) {
3350
    // Configuration for experimental features should go here.
3351
    $renderer->render_group_header('experimental_features');
3352
    // UI for 'register meeting events' feature.
3353
    $renderer->render_group_element(
3354
        'meetingevents_enabled',
3355
        $renderer->render_group_element_checkbox('meetingevents_enabled', 0)
3356
    );
3357
}
3358
3359
/**
3360
 * Helper function returns a sha1 encoded string that is unique and will be used as a seed for meetingid.
3361
 *
3362
 * @return string
3363
 */
3364
function bigbluebuttonbn_unique_meetingid_seed() {
3365
    global $DB;
3366
    do {
3367
        $encodedseed = sha1(bigbluebuttonbn_random_password(12));
3368
        $meetingid = (string) $DB->get_field('bigbluebuttonbn', 'meetingid', array('meetingid' => $encodedseed));
3369
    } while ($meetingid == $encodedseed);
3370
    return $encodedseed;
3371
}
3372
3373
/**
3374
 * Helper function renders the link used for recording type in row for the data used by the recording table.
3375
 *
3376
 * @param array $recording
3377
 * @param array $bbbsession
3378
 * @param array $playback
3379
 *
3380
 * @return boolean
3381
 */
3382
function bigbluebuttonbn_include_recording_data_row_type($recording, $bbbsession, $playback) {
3383
    // All types that are not restricted are included.
3384
    if (array_key_exists('restricted', $playback) && strtolower($playback['restricted']) == 'false') {
3385
        return true;
3386
    }
3387
    // All types that are not statistics are included.
3388
    if ($playback['type'] != 'statistics') {
3389
        return true;
3390
    }
3391
    // Exclude imported recordings.
3392
    if (isset($recording['imported'])) {
3393
        return false;
3394
    }
3395
    // Exclude non moderators.
3396
    if (!$bbbsession['administrator'] && !$bbbsession['moderator']) {
3397
        return false;
3398
    }
3399
    return true;
3400
}
3401
3402
/**
3403
 * Renders the general warning message.
3404
 *
3405
 * @param string $message
3406
 * @param string $type
3407
 * @param string $href
3408
 * @param string $text
3409
 * @param string $class
3410
 *
3411
 * @return string
3412
 */
3413
function bigbluebuttonbn_render_warning($message, $type = 'info', $href = '', $text = '', $class = '') {
3414
    global $OUTPUT;
3415
    $output = "\n";
3416
    // Evaluates if config_warning is enabled.
3417
    if (empty($message)) {
3418
        return $output;
3419
    }
3420
    $output .= $OUTPUT->box_start(
3421
        'box boxalignleft adminerror alert alert-' . $type . ' alert-block fade in',
3422
        'bigbluebuttonbn_view_general_warning'
3423
    ) . "\n";
3424
    $output .= '    ' . $message . "\n";
3425
    $output .= '  <div class="singlebutton pull-right">' . "\n";
3426
    if (!empty($href)) {
3427
        $output .= bigbluebuttonbn_render_warning_button($href, $text, $class);
3428
    }
3429
    $output .= '  </div>' . "\n";
3430
    $output .= $OUTPUT->box_end() . "\n";
3431
    return $output;
3432
}
3433
3434
/**
3435
 * Renders the general warning button.
3436
 *
3437
 * @param string $href
3438
 * @param string $text
3439
 * @param string $class
3440
 * @param string $title
3441
 *
3442
 * @return string
3443
 */
3444
function bigbluebuttonbn_render_warning_button($href, $text = '', $class = '', $title = '') {
3445
    if ($text == '') {
3446
        $text = get_string('ok', 'moodle');
3447
    }
3448
    if ($title == '') {
3449
        $title = $text;
3450
    }
3451
    if ($class == '') {
3452
        $class = 'btn btn-secondary';
3453
    }
3454
    $output = '  <form method="post" action="' . $href . '" class="form-inline">' . "\n";
3455
    $output .= '      <button type="submit" class="' . $class . '"' . "\n";
3456
    $output .= '          title="' . $title . '"' . "\n";
3457
    $output .= '          >' . $text . '</button>' . "\n";
3458
    $output .= '  </form>' . "\n";
3459
    return $output;
3460
}
3461
3462
/**
3463
 * Check if a BigBlueButtonBN is available to be used by the current user.
3464
 *
3465
 * @param  stdClass  $bigbluebuttonbn  BigBlueButtonBN instance
3466
 *
3467
 * @return boolean                     status if room available and current user allowed to join
3468
 */
3469
function bigbluebuttonbn_get_availability_status($bigbluebuttonbn) {
3470
    list($roomavailable) = bigbluebuttonbn_room_is_available($bigbluebuttonbn);
3471
    list($usercanjoin) = bigbluebuttonbn_user_can_join_meeting($bigbluebuttonbn);
3472
    return ($roomavailable && $usercanjoin);
3473
}
3474
3475
/**
3476
 * Helper for evaluating if scheduled activity is avaiable.
3477
 *
3478
 * @param  stdClass  $bigbluebuttonbn  BigBlueButtonBN instance
3479
 *
3480
 * @return array                       status (room available or not and possible warnings)
3481
 */
3482
function bigbluebuttonbn_room_is_available($bigbluebuttonbn) {
3483
    $open = true;
3484
    $closed = false;
3485
    $warnings = array();
3486
3487
    $timenow = time();
3488
    $timeopen = $bigbluebuttonbn->openingtime;
3489
    $timeclose = $bigbluebuttonbn->closingtime;
3490
    if (!empty($timeopen) && $timeopen > $timenow) {
3491
        $open = false;
3492
    }
3493
    if (!empty($timeclose) && $timenow > $timeclose) {
3494
        $closed = true;
3495
    }
3496
3497
    if (!$open || $closed) {
3498
        if (!$open) {
3499
            $warnings['notopenyet'] = userdate($timeopen);
3500
        }
3501
        if ($closed) {
3502
            $warnings['expired'] = userdate($timeclose);
3503
        }
3504
        return array(false, $warnings);
3505
    }
3506
3507
    return array(true, $warnings);
3508
}
3509
3510
/**
3511
 * Helper for evaluating if meeting can be joined.
3512
 *
3513
 * @param  stdClass $bigbluebuttonbn  BigBlueButtonBN instance
3514
 * @param  string   $mid
3515
 * @param  integer  $userid
3516
 *
3517
 * @return array    status (user allowed to join or not and possible message)
3518
 */
3519
function bigbluebuttonbn_user_can_join_meeting($bigbluebuttonbn, $mid = null, $userid = null) {
3520
    // By default, use a meetingid without groups.
3521
    if (empty($mid)) {
3522
        $mid = $bigbluebuttonbn->meetingid . '-' . $bigbluebuttonbn->course . '-' . $bigbluebuttonbn->id;
3523
    }
3524
    // When meeting is running, all authorized users can join right in.
3525
    if (bigbluebuttonbn_is_meeting_running($mid)) {
3526
        return array(true, get_string('view_message_conference_in_progress', 'bigbluebuttonbn'));
3527
    }
3528
    // When meeting is not running, see if the user can join.
3529
    $context = context_course::instance($bigbluebuttonbn->course);
3530
    $participantlist = bigbluebuttonbn_get_participant_list($bigbluebuttonbn, $context);
3531
    $isadmin = is_siteadmin($userid);
3532
    $ismoderator = bigbluebuttonbn_is_moderator($context, $participantlist, $userid);
3533
    // If user is administrator, moderator or if is viewer and no waiting is required, join allowed.
3534
    if ($isadmin || $ismoderator || !$bigbluebuttonbn->wait) {
3535
        return array(true, get_string('view_message_conference_room_ready', 'bigbluebuttonbn'));
3536
    }
3537
    // Otherwise, no join allowed.
3538
    return array(false, get_string('view_message_conference_wait_for_moderator', 'bigbluebuttonbn'));
3539
}
3540
3541
/**
3542
 * Helper for getting a value from a bigbluebuttonbn cache.
3543
 *
3544
 * @param  string   $name       BigBlueButtonBN cache
3545
 * @param  string   $key        Key to be retrieved
3546
 * @param  integer  $default    Default value in case key is not found or it is empty
3547
 *
3548
 * @return variable key value
3549
 */
3550
function bigbluebuttonbn_cache_get($name, $key, $default = null) {
3551
    $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', $name);
3552
    $result = $cache->get($key);
3553
    if (!empty($result)) {
3554
        return $result;
3555
    }
3556
    return $default;
3557
}
3558
3559
/**
3560
 * Helper for setting a value in a bigbluebuttonbn cache.
3561
 *
3562
 * @param  string   $name       BigBlueButtonBN cache
3563
 * @param  string   $key        Key to be created/updated
3564
 * @param  variable $value      Default value to be set
3565
 */
3566
function bigbluebuttonbn_cache_set($name, $key, $value) {
3567
    $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', $name);
3568
    $cache->set($key, $value);
3569
}
3570
3571
/**
3572
 * Helper for getting the owner userid of a bigbluebuttonbn instance.
3573
 *
3574
 * @param  stdClass $bigbluebuttonbn  BigBlueButtonBN instance
3575
 *
3576
 * @return integer ownerid (a valid user id or null if not registered/found)
3577
 */
3578
function bigbluebuttonbn_instance_ownerid($bigbluebuttonbn) {
3579
    global $DB;
3580
    $filters = array('bigbluebuttonbnid' => $bigbluebuttonbn->id, 'log' => 'Add');
3581
    $ownerid = (integer) $DB->get_field('bigbluebuttonbn_logs', 'userid', $filters);
3582
    return $ownerid;
3583
}
3584
3585
/**
3586
 * Helper evaluates if the bigbluebutton server used belongs to blindsidenetworks domain.
3587
 *
3588
 * @return boolean
3589
 */
3590
function bigbluebuttonbn_has_html5_client() {
3591
    $checkurl = \mod_bigbluebuttonbn\locallib\bigbluebutton::root() . "html5client/check";
3592
    $curlinfo = bigbluebuttonbn_wrap_xml_load_file_curl_request($checkurl, 'HEAD');
3593
    return (isset($curlinfo['http_code']) && $curlinfo['http_code'] == 200);
3594
}
3595
3596
/**
3597
 * Setup the bbbsession variable that is used all accross the plugin.
3598
 *
3599
 * @param object $context
3600
 * @param array $bbbsession
3601
 * @return void
3602
 */
3603
function bigbluebuttonbn_view_bbbsession_set($context, &$bbbsession) {
3604
    global $CFG, $USER;
3605
    // User data.
3606
    $bbbsession['username'] = fullname($USER);
3607
    $bbbsession['userID'] = $USER->id;
3608
    // User roles.
3609
    $bbbsession['administrator'] = is_siteadmin($bbbsession['userID']);
3610
    $participantlist = bigbluebuttonbn_get_participant_list($bbbsession['bigbluebuttonbn'], $context);
3611
    $bbbsession['moderator'] = bigbluebuttonbn_is_moderator($context, $participantlist);
3612
    $bbbsession['managerecordings'] = ($bbbsession['administrator']
3613
        || has_capability('mod/bigbluebuttonbn:managerecordings', $context));
3614
    $bbbsession['importrecordings'] = ($bbbsession['managerecordings']);
3615
    // Server data.
3616
    $bbbsession['modPW'] = $bbbsession['bigbluebuttonbn']->moderatorpass;
3617
    $bbbsession['viewerPW'] = $bbbsession['bigbluebuttonbn']->viewerpass;
3618
    // Database info related to the activity.
3619
    $bbbsession['meetingid'] = $bbbsession['bigbluebuttonbn']->meetingid . '-' . $bbbsession['course']->id . '-' .
3620
    $bbbsession['bigbluebuttonbn']->id;
3621
    $bbbsession['meetingname'] = $bbbsession['bigbluebuttonbn']->name;
3622
    $bbbsession['meetingdescription'] = $bbbsession['bigbluebuttonbn']->intro;
3623
    // Extra data for setting up the Meeting.
3624
    $bbbsession['userlimit'] = intval((int) \mod_bigbluebuttonbn\locallib\config::get('userlimit_default'));
3625
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('userlimit_editable')) {
3626
        $bbbsession['userlimit'] = intval($bbbsession['bigbluebuttonbn']->userlimit);
3627
    }
3628
    $bbbsession['voicebridge'] = $bbbsession['bigbluebuttonbn']->voicebridge;
3629 View Code Duplication
    if ($bbbsession['bigbluebuttonbn']->voicebridge > 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...
3630
        $bbbsession['voicebridge'] = 70000 + $bbbsession['bigbluebuttonbn']->voicebridge;
3631
    }
3632
    $bbbsession['wait'] = $bbbsession['bigbluebuttonbn']->wait;
3633
    $bbbsession['record'] = $bbbsession['bigbluebuttonbn']->record;
3634
    $bbbsession['recordallfromstart'] = $CFG->bigbluebuttonbn_recording_all_from_start_default;
3635
    if ($CFG->bigbluebuttonbn_recording_all_from_start_editable) {
3636
        $bbbsession['recordallfromstart'] = $bbbsession['bigbluebuttonbn']->recordallfromstart;
3637
    }
3638
    $bbbsession['recordhidebutton'] = $CFG->bigbluebuttonbn_recording_hide_button_default;
3639
    if ($CFG->bigbluebuttonbn_recording_hide_button_editable) {
3640
        $bbbsession['recordhidebutton'] = $bbbsession['bigbluebuttonbn']->recordhidebutton;
3641
    }
3642
3643
    // If the recording button should be hidden in activity only rooms, force recording off.
3644
    if ($CFG->bigbluebuttonbn_recording_hide_button_activityonly &&
3645
        $bbbsession['bigbluebuttonbn']->type == BIGBLUEBUTTONBN_TYPE_ROOM_ONLY) {
3646
        $bbbsession['record'] = "0";
3647
        $bbbsession['recordhidebutton'] = "1";
3648
    }
3649
3650
    $bbbsession['welcome'] = $bbbsession['bigbluebuttonbn']->welcome;
3651 View Code Duplication
    if (!isset($bbbsession['welcome']) || $bbbsession['welcome'] == '') {
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...
3652
        $bbbsession['welcome'] = get_string('mod_form_field_welcome_default', 'bigbluebuttonbn');
3653
    }
3654 View Code Duplication
    if ($bbbsession['bigbluebuttonbn']->record) {
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...
3655
        // Check if is enable record all from start.
3656
        if ($bbbsession['recordallfromstart']) {
3657
            $bbbsession['welcome'] .= '<br><br>' . get_string(
3658
                'bbbrecordallfromstartwarning',
3659
                'bigbluebuttonbn'
3660
            );
3661
        } else {
3662
            $bbbsession['welcome'] .= '<br><br>' . get_string('bbbrecordwarning', 'bigbluebuttonbn');
3663
        }
3664
    }
3665
    $bbbsession['openingtime'] = $bbbsession['bigbluebuttonbn']->openingtime;
3666
    $bbbsession['closingtime'] = $bbbsession['bigbluebuttonbn']->closingtime;
3667
    $bbbsession['muteonstart'] = $bbbsession['bigbluebuttonbn']->muteonstart;
3668
    // Lock settings.
3669
    $bbbsession['disablecam'] = $bbbsession['bigbluebuttonbn']->disablecam;
3670
    $bbbsession['disablemic'] = $bbbsession['bigbluebuttonbn']->disablemic;
3671
    $bbbsession['disableprivatechat'] = $bbbsession['bigbluebuttonbn']->disableprivatechat;
3672
    $bbbsession['disablepublicchat'] = $bbbsession['bigbluebuttonbn']->disablepublicchat;
3673
    $bbbsession['disablenote'] = $bbbsession['bigbluebuttonbn']->disablenote;
3674
    $bbbsession['hideuserlist'] = $bbbsession['bigbluebuttonbn']->hideuserlist;
3675
    $bbbsession['lockedlayout'] = $bbbsession['bigbluebuttonbn']->lockedlayout;
3676
    $bbbsession['lockonjoin'] = $bbbsession['bigbluebuttonbn']->lockonjoin;
3677
    $bbbsession['lockonjoinconfigurable'] = $bbbsession['bigbluebuttonbn']->lockonjoinconfigurable;
3678
    // Additional info related to the course.
3679
    $bbbsession['context'] = $context;
3680
    // Metadata (origin).
3681
    $bbbsession['origin'] = 'Moodle';
3682
    $bbbsession['originVersion'] = $CFG->release;
3683
    $parsedurl = parse_url($CFG->wwwroot);
3684
    $bbbsession['originServerName'] = $parsedurl['host'];
3685
    $bbbsession['originServerUrl'] = $CFG->wwwroot;
3686
    $bbbsession['originServerCommonName'] = '';
3687
    $bbbsession['originTag'] = 'moodle-mod_bigbluebuttonbn (' . get_config('mod_bigbluebuttonbn', 'version') . ')';
3688
    $bbbsession['bnserver'] = bigbluebuttonbn_is_bn_server();
3689
    // Setting for clienttype, assign flash if not enabled, or default if not editable.
3690
    $bbbsession['clienttype'] = BIGBLUEBUTTON_CLIENTTYPE_FLASH;
3691
    if (\mod_bigbluebuttonbn\locallib\config::clienttype_enabled()) {
3692
        $bbbsession['clienttype'] = \mod_bigbluebuttonbn\locallib\config::get('clienttype_default');
3693
    }
3694
    if (\mod_bigbluebuttonbn\locallib\config::get('clienttype_editable') && isset($bbbsession['bigbluebuttonbn']->clienttype)) {
3695
        $bbbsession['clienttype'] = $bbbsession['bigbluebuttonbn']->clienttype;
3696
    }
3697
}
3698
3699
/**
3700
 * Return the status of an activity [open|not_started|ended].
3701
 *
3702
 * @param array $bbbsession
3703
 * @return string
3704
 */
3705 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...
3706
    $now = time();
3707
    if (!empty($bbbsession['bigbluebuttonbn']->openingtime) && $now < $bbbsession['bigbluebuttonbn']->openingtime) {
3708
        // The activity has not been opened.
3709
        return 'not_started';
3710
    }
3711
    if (!empty($bbbsession['bigbluebuttonbn']->closingtime) && $now > $bbbsession['bigbluebuttonbn']->closingtime) {
3712
        // The activity has been closed.
3713
        return 'ended';
3714
    }
3715
    // The activity is open.
3716
    return 'open';
3717
}
3718
3719
/**
3720
 * Set session URLs.
3721
 *
3722
 * @param array $bbbsession
3723
 * @param int $id
3724
 * @return string
3725
 */
3726
function bigbluebuttonbn_view_session_config(&$bbbsession, $id) {
3727
    // Operation URLs.
3728
    $bbbsession['bigbluebuttonbnURL'] = plugin::necurl(
3729
        '/mod/bigbluebuttonbn/view.php',
3730
        ['id' => $bbbsession['cm']->id]
3731
    );
3732
    $bbbsession['logoutURL'] = plugin::necurl(
3733
        '/mod/bigbluebuttonbn/bbb_view.php',
3734
        ['action' => 'logout', 'id' => $id, 'bn' => $bbbsession['bigbluebuttonbn']->id]
3735
    );
3736
    $bbbsession['recordingReadyURL'] = plugin::necurl(
3737
        '/mod/bigbluebuttonbn/bbb_broker.php',
3738
        ['action' => 'recording_ready', 'bigbluebuttonbn' => $bbbsession['bigbluebuttonbn']->id]
3739
    );
3740
    $bbbsession['meetingEventsURL'] = plugin::necurl(
3741
        '/mod/bigbluebuttonbn/bbb_broker.php',
3742
        ['action' => 'meeting_events', 'bigbluebuttonbn' => $bbbsession['bigbluebuttonbn']->id]
3743
    );
3744
    $bbbsession['joinURL'] = plugin::necurl(
3745
        '/mod/bigbluebuttonbn/bbb_view.php',
3746
        ['action' => 'join', 'id' => $id, 'bn' => $bbbsession['bigbluebuttonbn']->id]
3747
    );
3748
3749
    // Check status and set extra values.
3750
    $activitystatus = bigbluebuttonbn_view_get_activity_status($bbbsession); // In locallib.
3751 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...
3752
        $bbbsession['presentation'] = bigbluebuttonbn_get_presentation_array(
3753
            $bbbsession['context'],
3754
            $bbbsession['bigbluebuttonbn']->presentation
3755
        );
3756
    } else if ($activitystatus == 'open') {
3757
        $bbbsession['presentation'] = bigbluebuttonbn_get_presentation_array(
3758
            $bbbsession['context'],
3759
            $bbbsession['bigbluebuttonbn']->presentation,
3760
            $bbbsession['bigbluebuttonbn']->id
3761
        );
3762
    }
3763
3764
    return $activitystatus;
3765
}
3766
3767
/**
3768
 * Helper for preparing metadata used while creating the meeting.
3769
 *
3770
 * @param  array    $bbbsession
3771
 * @return array
3772
 */
3773
function bigbluebuttonbn_create_meeting_metadata(&$bbbsession) {
3774
    global $USER;
3775
    // Create standard metadata.
3776
    $metadata = [
3777
        'bbb-origin' => $bbbsession['origin'],
3778
        'bbb-origin-version' => $bbbsession['originVersion'],
3779
        'bbb-origin-server-name' => $bbbsession['originServerName'],
3780
        'bbb-origin-server-common-name' => $bbbsession['originServerCommonName'],
3781
        'bbb-origin-tag' => $bbbsession['originTag'],
3782
        'bbb-context' => $bbbsession['course']->fullname,
3783
        'bbb-context-id' => $bbbsession['course']->id,
3784
        'bbb-context-name' => trim(html_to_text($bbbsession['course']->fullname, 0)),
3785
        'bbb-context-label' => trim(html_to_text($bbbsession['course']->shortname, 0)),
3786
        'bbb-recording-name' => bigbluebuttonbn_html2text($bbbsession['meetingname'], 64),
3787
        'bbb-recording-description' => bigbluebuttonbn_html2text($bbbsession['meetingdescription'], 64),
3788
        'bbb-recording-tags' => bigbluebuttonbn_get_tags($bbbsession['cm']->id), // Same as $id.
3789
    ];
3790
    // Special metadata for recording processing.
3791
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('recordingstatus_enabled')) {
3792
        $metadata["bn-recording-status"] = json_encode(
3793
            array(
3794
                'email' => array('"' . fullname($USER) . '" <' . $USER->email . '>'),
3795
                'context' => $bbbsession['bigbluebuttonbnURL'],
3796
            )
3797
        );
3798
    }
3799
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('recordingready_enabled')) {
3800
        $metadata['bn-recording-ready-url'] = $bbbsession['recordingReadyURL'];
3801
    }
3802
    if ((boolean) \mod_bigbluebuttonbn\locallib\config::get('meetingevents_enabled')) {
3803
        $metadata['analytics-callback-url'] = $bbbsession['meetingEventsURL'];
3804
    }
3805
    return $metadata;
3806
}
3807