Completed
Push — master ( 9ea0a4...4aa6a0 )
by Julito
45:51 queued 25:47
created

SessionManager::user_is_general_coach()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 2
nop 2
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\Course;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Course. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
use Chamilo\CoreBundle\Entity\ExtraField;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ExtraField. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use Chamilo\CoreBundle\Entity\Repository\SequenceRepository;
7
use Chamilo\CoreBundle\Entity\SequenceResource;
8
use Chamilo\CoreBundle\Entity\Session;
9
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
10
use Chamilo\CoreBundle\Entity\SessionRelUser;
11
use Chamilo\UserBundle\Entity\User;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, User. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
12
use ExtraField as ExtraFieldModel;
13
14
/**
15
 * Class SessionManager.
16
 *
17
 * This is the session library for Chamilo
18
 * (as in courses>session, not as in PHP session)
19
 * All main sessions functions should be placed here.
20
 * This class provides methods for sessions management.
21
 * Include/require it in your code to use its features.
22
 *
23
 * @package chamilo.library
24
 */
25
class SessionManager
26
{
27
    public static $_debug = false;
28
29
    /**
30
     * Constructor.
31
     */
32
    public function __construct()
33
    {
34
    }
35
36
    /**
37
     * Fetches a session from the database.
38
     *
39
     * @param int $id Session Id
40
     *
41
     * @return array Session details
42
     */
43
    public static function fetch($id)
44
    {
45
        $em = Database::getManager();
46
47
        if (empty($id)) {
48
            return [];
49
        }
50
51
        /** @var Session $session */
52
        $session = $em->find('ChamiloCoreBundle:Session', $id);
53
54
        if (!$session) {
0 ignored issues
show
introduced by
$session is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
55
            return [];
56
        }
57
58
        $result = [
59
            'id' => $session->getId(),
60
            'id_coach' => $session->getGeneralCoach() ? $session->getGeneralCoach()->getId() : null,
61
            'session_category_id' => $session->getCategory() ? $session->getCategory()->getId() : null,
62
            'name' => $session->getName(),
63
            'description' => $session->getDescription(),
64
            'show_description' => $session->getShowDescription(),
65
            'duration' => $session->getDuration(),
66
            'nbr_courses' => $session->getNbrCourses(),
67
            'nbr_users' => $session->getNbrUsers(),
68
            'nbr_classes' => $session->getNbrClasses(),
69
            'session_admin_id' => $session->getSessionAdminId(),
70
            'visibility' => $session->getVisibility(),
71
            'promotion_id' => $session->getPromotionId(),
72
            'display_start_date' => $session->getDisplayStartDate()
73
                ? $session->getDisplayStartDate()->format('Y-m-d H:i:s')
74
                : null,
75
            'display_end_date' => $session->getDisplayEndDate()
76
                ? $session->getDisplayEndDate()->format('Y-m-d H:i:s')
77
                : null,
78
            'access_start_date' => $session->getAccessStartDate()
79
                ? $session->getAccessStartDate()->format('Y-m-d H:i:s')
80
                : null,
81
            'access_end_date' => $session->getAccessEndDate()
82
                ? $session->getAccessEndDate()->format('Y-m-d H:i:s')
83
                : null,
84
            'coach_access_start_date' => $session->getCoachAccessStartDate()
85
                ? $session->getCoachAccessStartDate()->format('Y-m-d H:i:s')
86
                : null,
87
            'coach_access_end_date' => $session->getCoachAccessEndDate()
88
                ? $session->getCoachAccessEndDate()->format('Y-m-d H:i:s')
89
                : null,
90
            'send_subscription_notification' => $session->getSendSubscriptionNotification(),
91
        ];
92
93
        // Converted to local values
94
        $variables = [
95
            'display_start_date',
96
            'display_end_date',
97
            'access_start_date',
98
            'access_end_date',
99
            'coach_access_start_date',
100
            'coach_access_end_date',
101
        ];
102
103
        foreach ($variables as $value) {
104
            $result[$value."_to_local_time"] = null;
105
            if (!empty($result[$value])) {
106
                $result[$value."_to_local_time"] = api_get_local_time($result[$value]);
107
            }
108
        }
109
110
        return $result;
111
    }
112
113
    /**
114
     * Create a session.
115
     *
116
     * @author Carlos Vargas <[email protected]>, from existing code
117
     *
118
     * @param string $name
119
     * @param string $startDate                    (YYYY-MM-DD hh:mm:ss)
120
     * @param string $endDate                      (YYYY-MM-DD hh:mm:ss)
121
     * @param string $displayStartDate             (YYYY-MM-DD hh:mm:ss)
122
     * @param string $displayEndDate               (YYYY-MM-DD hh:mm:ss)
123
     * @param string $coachStartDate               (YYYY-MM-DD hh:mm:ss)
124
     * @param string $coachEndDate                 (YYYY-MM-DD hh:mm:ss)
125
     * @param int    $sessionCategoryId            ID of the session category in which this session is registered
126
     * @param mixed  $coachId                      If int, this is the session coach id,
127
     *                                             if string, the coach ID will be looked for from the user table
128
     * @param int    $visibility                   Visibility after end date (0 = read-only, 1 = invisible, 2 = accessible)
129
     * @param bool   $fixSessionNameIfExists
130
     * @param string $duration
131
     * @param string $description                  Optional. The session description
132
     * @param int    $showDescription              Optional. Whether show the session description
133
     * @param array  $extraFields
134
     * @param int    $sessionAdminId               Optional. If this sessions was created by a session admin, assign it to him
135
     * @param bool   $sendSubscriptionNotification Optional.
136
     *                                             Whether send a mail notification to users being subscribed
137
     *
138
     * @todo use an array to replace all this parameters or use the model.lib.php ...
139
     *
140
     * @return mixed Session ID on success, error message otherwise
141
     * */
142
    public static function create_session(
143
        $name,
144
        $startDate,
145
        $endDate,
146
        $displayStartDate,
147
        $displayEndDate,
148
        $coachStartDate,
149
        $coachEndDate,
150
        $coachId,
151
        $sessionCategoryId,
152
        $visibility = 1,
153
        $fixSessionNameIfExists = false,
154
        $duration = null,
155
        $description = null,
156
        $showDescription = 0,
157
        $extraFields = [],
158
        $sessionAdminId = 0,
159
        $sendSubscriptionNotification = false
160
    ) {
161
        global $_configuration;
162
163
        // Check portal limits
164
        $access_url_id = 1;
165
166
        if (api_get_multiple_access_url()) {
167
            $access_url_id = api_get_current_access_url_id();
168
        }
169
170
        if (is_array($_configuration[$access_url_id]) &&
171
            isset($_configuration[$access_url_id]['hosting_limit_sessions']) &&
172
            $_configuration[$access_url_id]['hosting_limit_sessions'] > 0
173
        ) {
174
            $num = self::count_sessions();
175
            if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
176
                api_warn_hosting_contact('hosting_limit_sessions');
177
178
                return get_lang('PortalSessionsLimitReached');
179
            }
180
        }
181
182
        $name = Database::escape_string(trim($name));
183
        $sessionCategoryId = intval($sessionCategoryId);
184
        $visibility = intval($visibility);
185
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
186
187
        $startDate = Database::escape_string($startDate);
188
        $endDate = Database::escape_string($endDate);
189
190
        if (empty($name)) {
191
            $msg = get_lang('SessionNameIsRequired');
192
193
            return $msg;
194
        } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') &&
195
            !api_is_valid_date($startDate, 'Y-m-d H:i:s')
196
        ) {
197
            $msg = get_lang('InvalidStartDate');
198
199
            return $msg;
200
        } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') &&
201
            !api_is_valid_date($endDate, 'Y-m-d H:i:s')
202
        ) {
203
            $msg = get_lang('InvalidEndDate');
204
205
            return $msg;
206
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
207
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
208
209
            return $msg;
210
        } else {
211
            $ready_to_create = false;
212
            if ($fixSessionNameIfExists) {
213
                $name = self::generateNextSessionName($name);
214
                if ($name) {
215
                    $ready_to_create = true;
216
                } else {
217
                    $msg = get_lang('SessionNameAlreadyExists');
218
219
                    return $msg;
220
                }
221
            } else {
222
                $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='".$name."'");
223
                if (Database::num_rows($rs)) {
224
                    $msg = get_lang('SessionNameAlreadyExists');
225
226
                    return $msg;
227
                }
228
                $ready_to_create = true;
229
            }
230
231
            if ($ready_to_create) {
232
                $sessionAdminId = !empty($sessionAdminId) ? $sessionAdminId : api_get_user_id();
233
                $values = [
234
                    'name' => $name,
235
                    'id_coach' => $coachId,
236
                    'session_admin_id' => $sessionAdminId,
237
                    'visibility' => $visibility,
238
                    'description' => $description,
239
                    'show_description' => intval($showDescription),
240
                    'send_subscription_notification' => (int) $sendSubscriptionNotification,
241
                ];
242
243
                if (!empty($startDate)) {
244
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
245
                }
246
247
                if (!empty($endDate)) {
248
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
249
                }
250
251
                if (!empty($displayStartDate)) {
252
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
253
                }
254
255
                if (!empty($displayEndDate)) {
256
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
257
                }
258
259
                if (!empty($coachStartDate)) {
260
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
261
                }
262
                if (!empty($coachEndDate)) {
263
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
264
                }
265
266
                if (!empty($sessionCategoryId)) {
267
                    $values['session_category_id'] = $sessionCategoryId;
268
                }
269
270
                $session_id = Database::insert($tbl_session, $values);
271
272
                $duration = intval($duration);
273
274
                if (!empty($duration)) {
275
                    $sql = "UPDATE $tbl_session SET
276
                        access_start_date = NULL,
277
                        access_end_date = NULL,
278
                        display_start_date = NULL,
279
                        display_end_date = NULL,
280
                        coach_access_start_date = NULL,
281
                        coach_access_end_date = NULL,
282
                        duration = $duration
283
                    WHERE id = $session_id";
284
                    Database::query($sql);
285
                } else {
286
                    $sql = "UPDATE $tbl_session
287
                        SET duration = 0
288
                        WHERE id = $session_id";
289
                    Database::query($sql);
290
                }
291
292
                if (!empty($session_id)) {
293
                    $extraFields['item_id'] = $session_id;
294
                    $sessionFieldValue = new ExtraFieldValue('session');
295
                    $sessionFieldValue->saveFieldValues($extraFields);
296
297
                    /*
298
                      Sends a message to the user_id = 1
299
300
                      $user_info = api_get_user_info(1);
301
                      $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
302
                      $subject = api_get_setting('siteName').' - '.get_lang('ANewSessionWasCreated');
303
                      $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
304
                      api_mail_html($complete_name, $user_info['email'], $subject, $message);
305
                     *
306
                     */
307
                    //Adding to the correct URL
308
                    $access_url_id = api_get_current_access_url_id();
309
                    UrlManager::add_session_to_url($session_id, $access_url_id);
310
311
                    // add event to system log
312
                    $user_id = api_get_user_id();
313
                    Event::addEvent(
314
                        LOG_SESSION_CREATE,
315
                        LOG_SESSION_ID,
316
                        $session_id,
317
                        api_get_utc_datetime(),
318
                        $user_id
319
                    );
320
                }
321
322
                return $session_id;
323
            }
324
        }
325
    }
326
327
    /**
328
     * @param string $name
329
     *
330
     * @return bool
331
     */
332
    public static function sessionNameExists($name)
333
    {
334
        $name = Database::escape_string($name);
335
        $sql = "SELECT COUNT(*) as count FROM ".Database::get_main_table(TABLE_MAIN_SESSION)."
336
                WHERE name = '$name'";
337
        $result = Database::fetch_array(Database::query($sql));
338
339
        return $result['count'] > 0;
340
    }
341
342
    /**
343
     * @param string $where_condition
344
     *
345
     * @return mixed
346
     */
347
    public static function get_count_admin($where_condition = '')
348
    {
349
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
350
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
351
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
352
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
353
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
354
355
        $where = 'WHERE 1=1 ';
356
        $user_id = api_get_user_id();
357
        $extraJoin = '';
358
359
        if (api_is_session_admin() &&
360
            api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
361
        ) {
362
            $where .= " AND (
363
                            s.session_admin_id = $user_id  OR
364
                            sru.user_id = '$user_id' AND
365
                            sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
366
                            )
367
                      ";
368
369
            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
370
                           ON sru.session_id = s.id ";
371
        }
372
373
        $today = api_get_utc_datetime();
374
        $today = api_strtotime($today, 'UTC');
375
        $today = date('Y-m-d', $today);
376
377
        if (!empty($where_condition)) {
378
            $where_condition = str_replace("(  session_active = ':'  )", '1=1', $where_condition);
379
380
            $where_condition = str_replace('category_name', 'sc.name', $where_condition);
381
            $where_condition = str_replace(
382
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
383
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
384
                $where_condition
385
            );
386
            $where_condition = str_replace(
387
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
388
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
389
                $where_condition
390
            );
391
        } else {
392
            $where_condition = " AND 1 = 1";
393
        }
394
395
        $courseCondition = null;
396
        if (strpos($where_condition, 'c.id')) {
397
            $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
398
            $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
399
            $courseCondition = " INNER JOIN $table course_rel_session
400
                                 ON (s.id = course_rel_session.session_id)
401
                                 INNER JOIN $tableCourse c
402
                                 ON (course_rel_session.c_id = c.id)
403
                                ";
404
        }
405
406
        $sql = "SELECT COUNT(id) as total_rows FROM (
407
                SELECT DISTINCT
408
                 IF (
409
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
410
                    (s.access_start_date IS NULL AND s.access_end_date  = IS NULL ) OR
411
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
412
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
413
				, 1, 0) as session_active,
414
                s.id
415
                FROM $tbl_session s
416
                LEFT JOIN $tbl_session_category sc
417
                ON s.session_category_id = sc.id
418
                INNER JOIN $tbl_user u
419
                ON s.id_coach = u.user_id
420
                $courseCondition
421
                $extraJoin
422
                $where $where_condition ) as session_table";
423
424
        if (api_is_multiple_url_enabled()) {
425
            $access_url_id = api_get_current_access_url_id();
426
            if ($access_url_id != -1) {
427
                $where .= " AND ar.access_url_id = $access_url_id ";
428
429
                $sql = "SELECT count(id) as total_rows FROM (
430
                SELECT DISTINCT
431
                  IF (
432
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
433
                    (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
434
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
435
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
436
				, 1, 0)
437
				as session_active,
438
				s.id
439
                FROM $tbl_session s
440
                    LEFT JOIN  $tbl_session_category sc
441
                    ON s.session_category_id = sc.id
442
                    INNER JOIN $tbl_user u ON s.id_coach = u.user_id
443
                    INNER JOIN $table_access_url_rel_session ar
444
                    ON ar.session_id = s.id
445
                    $courseCondition
446
                    $extraJoin
447
                $where $where_condition) as session_table";
448
            }
449
        }
450
451
        $result_rows = Database::query($sql);
452
        $row = Database::fetch_array($result_rows);
453
        $num = $row['total_rows'];
454
455
        return $num;
456
    }
457
458
    /**
459
     * Gets the admin session list callback of the session/session_list.php page.
460
     *
461
     * @param array $options           order and limit keys
462
     * @param bool  $get_count         Whether to get all the results or only the count
463
     * @param array $columns
464
     * @param array $extraFieldsToLoad
465
     *
466
     * @return mixed Integer for number of rows, or array of results
467
     * @assert ([],true) !== false
468
     */
469
    public static function get_sessions_admin(
470
        $options = [],
471
        $get_count = false,
472
        $columns = [],
473
        $extraFieldsToLoad = []
474
    ) {
475
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
476
        $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
477
478
        $where = 'WHERE 1 = 1 ';
479
        $user_id = api_get_user_id();
480
481
        if (!api_is_platform_admin()) {
482
            if (api_is_session_admin() &&
483
                api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
484
            ) {
485
                $where .= " AND s.session_admin_id = $user_id ";
486
            }
487
        }
488
489
        if (!api_is_platform_admin() &&
490
            api_is_teacher() &&
491
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
492
        ) {
493
            $where .= " AND s.id_coach = $user_id ";
494
        }
495
        $extra_field = new ExtraFieldModel('session');
496
        $conditions = $extra_field->parseConditions($options);
497
        $inject_joins = $conditions['inject_joins'];
498
        $where .= $conditions['where'];
499
        $inject_where = $conditions['inject_where'];
500
        $inject_extra_fields = $conditions['inject_extra_fields'];
501
        $order = $conditions['order'];
502
        $limit = $conditions['limit'];
503
504
        $isMakingOrder = false;
505
        $showCountUsers = false;
506
507
        if ($get_count == true) {
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...
508
            $select = " SELECT count(DISTINCT s.id) as total_rows";
509
        } else {
510
            if (!empty($columns['column_model'])) {
511
                foreach ($columns['column_model'] as $column) {
512
                    if ($column['name'] == 'users') {
513
                        $showCountUsers = true;
514
                    }
515
                }
516
            }
517
518
            $select =
519
                "SELECT DISTINCT 
520
                     s.name,
521
                     s.display_start_date, 
522
                     s.display_end_date, 
523
                     access_start_date, 
524
                     access_end_date, 
525
                     s.visibility, 
526
                     s.session_category_id, 
527
                     $inject_extra_fields 
528
                     s.id 
529
             ";
530
531
            if ($showCountUsers) {
532
                $select .= ', count(su.user_id) users';
533
            }
534
            if (isset($options['order'])) {
535
                $isMakingOrder = strpos($options['order'], 'category_name') === 0;
536
            }
537
        }
538
539
        $isFilteringSessionCategory = strpos($where, 'category_name') !== false;
540
        $isFilteringSessionCategoryWithName = strpos($where, 'sc.name') !== false;
541
542
        if ($isMakingOrder || $isFilteringSessionCategory || $isFilteringSessionCategoryWithName) {
543
            $inject_joins .= " LEFT JOIN $sessionCategoryTable sc ON s.session_category_id = sc.id ";
544
545
            if ($isFilteringSessionCategory) {
546
                $where = str_replace('category_name', 'sc.name', $where);
547
            }
548
549
            if ($isMakingOrder) {
550
                $order = str_replace('category_name', 'sc.name', $order);
551
            }
552
        }
553
554
        if ($showCountUsers) {
555
            $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
556
            $inject_joins .= " LEFT JOIN $table su ON (su.session_id = s.id)";
557
        }
558
559
        $query = "$select FROM $tbl_session s $inject_joins $where $inject_where";
560
561
        if (api_is_multiple_url_enabled()) {
562
            $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
563
            $access_url_id = api_get_current_access_url_id();
564
            if ($access_url_id != -1) {
565
                $where .= " AND ar.access_url_id = $access_url_id ";
566
                $query = "$select
567
                        FROM $tbl_session s $inject_joins
568
                        INNER JOIN $table_access_url_rel_session ar
569
                        ON (ar.session_id = s.id) $where";
570
            }
571
        }
572
573
        if ($showCountUsers) {
574
            $query .= ' GROUP by s.id';
575
        }
576
        $allowOrder = api_get_configuration_value('session_list_order');
577
        if ($allowOrder) {
578
            $order = ' ORDER BY position ASC';
579
        }
580
581
        $query .= $order;
582
        $query .= $limit;
583
        $result = Database::query($query);
584
585
        $categories = self::get_all_session_category();
586
        $orderedCategories = [];
587
        if (!empty($categories)) {
588
            foreach ($categories as $category) {
589
                $orderedCategories[$category['id']] = $category['name'];
590
            }
591
        }
592
        $formatted_sessions = [];
593
        if (Database::num_rows($result)) {
594
            $sessions = Database::store_result($result, 'ASSOC');
595
            if ($get_count) {
596
                return $sessions[0]['total_rows'];
597
            }
598
599
            $activeIcon = Display::return_icon(
600
                'accept.png',
601
                get_lang('Active'),
602
                [],
603
                ICON_SIZE_SMALL
604
            );
605
            $inactiveIcon = Display::return_icon(
606
                'error.png',
607
                get_lang('Inactive'),
608
                [],
609
                ICON_SIZE_SMALL
610
            );
611
612
            foreach ($sessions as $session) {
613
                $session_id = $session['id'];
614
                if ($showCountUsers) {
615
                    $session['users'] = SessionManager::get_users_by_session(
616
                        $session['id'],
617
                        null,
618
                        true
619
                    );
620
                }
621
                $url = api_get_path(WEB_CODE_PATH)."session/resume_session.php?id_session=".$session['id'];
622
                if (api_is_drh()) {
623
                    $url = api_get_path(WEB_CODE_PATH)."session/about.php?session_id=".$session['id'];
624
                }
625
                if (api_is_platform_admin()) {
626
                    $url = api_get_path(WEB_CODE_PATH)."session/resume_session.php?id_session=".$session['id'];
627
                }
628
629
                if ($extraFieldsToLoad) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extraFieldsToLoad of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
630
                    $url = api_get_path(WEB_CODE_PATH)."session/about.php?session_id=".$session['id'];
631
                }
632
                $session['name'] = Display::url(
633
                    $session['name'],
634
                    $url
635
                );
636
637
                if (!empty($extraFieldsToLoad)) {
638
                    foreach ($extraFieldsToLoad as $field) {
639
                        $extraFieldValue = new ExtraFieldValue('session');
640
                        $fieldData = $extraFieldValue->getAllValuesByItemAndField(
641
                            $session['id'],
642
                            $field['id']
643
                        );
644
                        $fieldDataArray = [];
645
                        $fieldDataToString = '';
646
                        if (!empty($fieldData)) {
647
                            foreach ($fieldData as $data) {
648
                                $fieldDataArray[] = $data['value'];
649
                            }
650
                            $fieldDataToString = implode(', ', $fieldDataArray);
651
                        }
652
                        $session[$field['variable']] = $fieldDataToString;
653
                    }
654
                }
655
656
                if (isset($session['session_active']) && $session['session_active'] == 1) {
657
                    $session['session_active'] = $activeIcon;
658
                } else {
659
                    $session['session_active'] = $inactiveIcon;
660
                }
661
662
                $session = self::convert_dates_to_local($session, true);
663
664
                switch ($session['visibility']) {
665
                    case SESSION_VISIBLE_READ_ONLY: //1
666
                        $session['visibility'] = get_lang('ReadOnly');
667
                        break;
668
                    case SESSION_VISIBLE:           //2
669
                    case SESSION_AVAILABLE:         //4
670
                        $session['visibility'] = get_lang('Visible');
671
                        break;
672
                    case SESSION_INVISIBLE:         //3
673
                        $session['visibility'] = api_ucfirst(get_lang('Invisible'));
674
                        break;
675
                }
676
677
                // Cleaning double selects.
678
                foreach ($session as $key => &$value) {
679
                    if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $options_by_double does not exist. Did you maybe mean $options?
Loading history...
680
                        $options = explode('::', $value);
681
                    }
682
                    $original_key = $key;
683
684
                    if (strpos($key, '_second') === false) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
685
                    } else {
686
                        $key = str_replace('_second', '', $key);
687
                    }
688
689
                    if (isset($options_by_double[$key])) {
690
                        if (isset($options[0])) {
691
                            if (isset($options_by_double[$key][$options[0]])) {
692
                                if (strpos($original_key, '_second') === false) {
693
                                    $value = $options_by_double[$key][$options[0]]['option_display_text'];
694
                                } else {
695
                                    $value = $options_by_double[$key][$options[1]]['option_display_text'];
696
                                }
697
                            }
698
                        }
699
                    }
700
                }
701
                $formatted_sessions[$session_id] = $session;
702
                $categoryName = isset($orderedCategories[$session['session_category_id']]) ? $orderedCategories[$session['session_category_id']] : '';
703
                $formatted_sessions[$session_id]['category_name'] = $categoryName;
704
            }
705
        }
706
707
        return $formatted_sessions;
708
    }
709
710
    /**
711
     *  Get total of records for progress of learning paths in the given session.
712
     *
713
     *  @param int session id
714
     *
715
     *  @return int
716
     */
717
    public static function get_count_session_lp_progress($sessionId = 0)
718
    {
719
        $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
720
        $tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
721
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
722
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
723
724
        $sessionId = intval($sessionId);
725
726
        $sql = "SELECT  count(*) as total_rows
727
                FROM $tbl_lp_view v
728
                INNER JOIN $tbl_lp l ON l.id = v.lp_id
729
                INNER JOIN $tbl_user u ON u.user_id = v.user_id
730
                INNER JOIN $tbl_course c
731
                WHERE v.session_id = ".$sessionId;
732
        $result_rows = Database::query($sql);
733
        $row = Database::fetch_array($result_rows);
734
        $num = $row['total_rows'];
735
736
        return $num;
737
    }
738
739
    /**
740
     * Gets the progress of learning paths in the given session.
741
     *
742
     * @param int    $sessionId
743
     * @param int    $courseId
744
     * @param string $date_from
745
     * @param string $date_to
746
     * @param array options order and limit keys
747
     *
748
     * @return array table with user name, lp name, progress
749
     */
750
    public static function get_session_lp_progress(
751
        $sessionId = 0,
752
        $courseId = 0,
753
        $date_from,
754
        $date_to,
755
        $options
756
    ) {
757
        //escaping vars
758
        $sessionId = $sessionId == 'T' ? 'T' : intval($sessionId);
759
        $courseId = intval($courseId);
760
        $date_from = Database::escape_string($date_from);
761
        $date_to = Database::escape_string($date_to);
762
763
        //tables
764
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
765
        $user = Database::get_main_table(TABLE_MAIN_USER);
766
        $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
767
768
        $course = api_get_course_info_by_id($courseId);
769
770
        //getting all the students of the course
771
        //we are not using this because it only returns user ids
772
        /* if (empty($sessionId)
773
          {
774
          // Registered students in a course outside session.
775
          $users = CourseManager::get_student_list_from_course_code($course_code);
776
          } else {
777
          // Registered students in session.
778
          $users = CourseManager::get_student_list_from_course_code($course_code, true, $sessionId);
779
          } */
780
781
        $sessionCond = 'and session_id = %s';
782
        if ($sessionId == 'T') {
783
            $sessionCond = '';
784
        }
785
786
        $where = " WHERE c_id = '%s' AND s.status <> 2 $sessionCond";
787
788
        $limit = null;
789
        if (!empty($options['limit'])) {
790
            $limit = " LIMIT ".$options['limit'];
791
        }
792
793
        if (!empty($options['where'])) {
794
            $where .= ' '.$options['where'];
795
        }
796
797
        $order = null;
798
        if (!empty($options['order'])) {
799
            $order = " ORDER BY ".$options['order'];
800
        }
801
802
        $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
803
                FROM $session_course_user s
804
                INNER JOIN $user u ON u.user_id = s.user_id
805
                $where
806
                $order
807
                $limit";
808
809
        $sql_query = sprintf($sql, Database::escape_string($course['real_id']), $sessionId);
810
811
        $rs = Database::query($sql_query);
812
        while ($user = Database::fetch_array($rs)) {
813
            $users[$user['user_id']] = $user;
814
        }
815
816
        // Get lessons
817
        $lessons = LearnpathList::get_course_lessons($course['code'], $sessionId);
0 ignored issues
show
Bug introduced by
It seems like $sessionId can also be of type string; however, parameter $session_id of LearnpathList::get_course_lessons() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

817
        $lessons = LearnpathList::get_course_lessons($course['code'], /** @scrutinizer ignore-type */ $sessionId);
Loading history...
818
819
        $table = [];
820
        foreach ($users as $user) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $users does not seem to be defined for all execution paths leading up to this point.
Loading history...
821
            $data = [
822
                'lastname' => $user[1],
823
                'firstname' => $user[2],
824
                'username' => $user[3],
825
            ];
826
827
            $sessionCond = 'AND v.session_id = %d';
828
            if ($sessionId == 'T') {
829
                $sessionCond = "";
830
            }
831
832
            //Get lessons progress by user
833
            $sql = "SELECT v.lp_id as id, v.progress
834
                    FROM  $tbl_course_lp_view v
835
                    WHERE v.c_id = %d
836
                    AND v.user_id = %d
837
            $sessionCond";
838
839
            $sql_query = sprintf(
840
                $sql,
841
                intval($courseId),
842
                intval($user['user_id']),
843
                $sessionId
844
            );
845
846
            $result = Database::query($sql_query);
847
848
            $user_lessons = [];
849
            while ($row = Database::fetch_array($result)) {
850
                $user_lessons[$row['id']] = $row;
851
            }
852
853
            //Match course lessons with user progress
854
            $progress = 0;
855
            $count = 0;
856
            foreach ($lessons as $lesson) {
857
                $data[$lesson['id']] = (!empty($user_lessons[$lesson['id']]['progress'])) ? $user_lessons[$lesson['id']]['progress'] : 0;
858
                $progress += $data[$lesson['id']];
859
                $data[$lesson['id']] = $data[$lesson['id']].'%';
860
                $count++;
861
            }
862
            if ($count == 0) {
863
                $data['total'] = 0;
864
            } else {
865
                $data['total'] = round($progress / $count, 2).'%';
866
            }
867
            $table[] = $data;
868
        }
869
870
        return $table;
871
    }
872
873
    /**
874
     * Gets the survey answers.
875
     *
876
     * @param int $sessionId
877
     * @param int $courseId
878
     * @param int $surveyId
879
     * @param array options order and limit keys
880
     *
881
     * @todo fix the query
882
     *
883
     * @return array table with user name, lp name, progress
884
     */
885
    public static function get_survey_overview(
886
        $sessionId = 0,
887
        $courseId = 0,
888
        $surveyId = 0,
889
        $date_from,
890
        $date_to,
891
        $options
892
    ) {
893
        //escaping vars
894
        $sessionId = intval($sessionId);
895
        $courseId = intval($courseId);
896
        $surveyId = intval($surveyId);
897
898
        //tables
899
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
900
        $user = Database::get_main_table(TABLE_MAIN_USER);
901
        $c_survey = Database::get_course_table(TABLE_SURVEY);
902
        $c_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
903
        $c_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
904
        $c_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
905
906
        $course = api_get_course_info_by_id($courseId);
907
908
        $where = " WHERE c_id = '%s' AND s.status <> 2 AND session_id = %s";
909
910
        $limit = null;
911
        if (!empty($options['limit'])) {
912
            $limit = " LIMIT ".$options['limit'];
913
        }
914
915
        if (!empty($options['where'])) {
916
            $where .= ' '.$options['where'];
917
        }
918
919
        $order = null;
920
        if (!empty($options['order'])) {
921
            $order = " ORDER BY ".$options['order'];
922
        }
923
924
        $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
925
                FROM $session_course_user s
926
                INNER JOIN $user u ON u.user_id = s.user_id
927
                $where $order $limit";
928
929
        $sql_query = sprintf($sql, intval($course['real_id']), $sessionId);
930
        $rs = Database::query($sql_query);
931
        while ($user = Database::fetch_array($rs)) {
932
            $users[$user['user_id']] = $user;
933
        }
934
935
        //Get survey questions
936
        $questions = SurveyManager::get_questions($surveyId, $courseId);
937
938
        //Survey is anonymous?
939
        $result = Database::query(sprintf("SELECT anonymous FROM $c_survey WHERE survey_id = %d", $surveyId));
940
        $row = Database::fetch_array($result);
941
        $anonymous = ($row['anonymous'] == 1) ? true : false;
942
943
        $table = [];
944
        foreach ($users as $user) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $users does not seem to be defined for all execution paths leading up to this point.
Loading history...
945
            $data = [
946
                'lastname' => ($anonymous ? '***' : $user[1]),
947
                'firstname' => ($anonymous ? '***' : $user[2]),
948
                'username' => ($anonymous ? '***' : $user[3]),
949
            ];
950
951
            //Get questions by user
952
            $sql = "SELECT sa.question_id, sa.option_id, sqo.option_text, sq.type
953
                    FROM $c_survey_answer sa
954
                    INNER JOIN $c_survey_question sq
955
                    ON sq.question_id = sa.question_id
956
                    LEFT JOIN $c_survey_question_option sqo
957
                    ON
958
                      sqo.c_id = sa.c_id AND
959
                      sqo.question_id = sq.question_id AND
960
                      sqo.question_option_id = sa.option_id AND
961
                      sqo.survey_id = sq.survey_id
962
                    WHERE
963
                      sa.survey_id = %d AND
964
                      sa.c_id = %d AND
965
                      sa.user = %d
966
            "; //. $where_survey;
967
            $sql_query = sprintf($sql, $surveyId, $courseId, $user['user_id']);
968
969
            $result = Database::query($sql_query);
970
971
            $user_questions = [];
972
            while ($row = Database::fetch_array($result)) {
973
                $user_questions[$row['question_id']] = $row;
974
            }
975
976
            //Match course lessons with user progress
977
            foreach ($questions as $question_id => $question) {
978
                $option_text = 'option_text';
979
                if ($user_questions[$question_id]['type'] == 'open') {
980
                    $option_text = 'option_id';
981
                }
982
                $data[$question_id] = $user_questions[$question_id][$option_text];
983
            }
984
985
            $table[] = $data;
986
        }
987
988
        return $table;
989
    }
990
991
    /**
992
     * Gets the progress of the given session.
993
     *
994
     * @param int $sessionId
995
     * @param int $courseId
996
     * @param array options order and limit keys
997
     *
998
     * @return array table with user name, lp name, progress
999
     */
1000
    public static function get_session_progress(
1001
        $sessionId,
1002
        $courseId,
1003
        $date_from,
1004
        $date_to,
1005
        $options
1006
    ) {
1007
        $sessionId = intval($sessionId);
1008
1009
        $getAllSessions = false;
1010
        if (empty($sessionId)) {
1011
            $sessionId = 0;
1012
            $getAllSessions = true;
1013
        }
1014
1015
        //tables
1016
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1017
        $user = Database::get_main_table(TABLE_MAIN_USER);
1018
        $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1019
        $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1020
        $tbl_course_lp = Database::get_course_table(TABLE_LP_MAIN);
1021
        $wiki = Database::get_course_table(TABLE_WIKI);
1022
        $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
1023
        $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
1024
1025
        $course = api_get_course_info_by_id($courseId);
1026
        $where = " WHERE c_id = '%s' AND s.status <> 2 ";
1027
1028
        $limit = null;
1029
        if (!empty($options['limit'])) {
1030
            $limit = " LIMIT ".$options['limit'];
1031
        }
1032
1033
        if (!empty($options['where'])) {
1034
            $where .= ' '.$options['where'];
1035
        }
1036
1037
        $order = null;
1038
        if (!empty($options['order'])) {
1039
            $order = " ORDER BY ".$options['order'];
1040
        }
1041
1042
        //TODO, fix create report without session
1043
        $queryVariables = [$course['real_id']];
1044
        if (!empty($sessionId)) {
1045
            $where .= ' AND session_id = %s';
1046
            $queryVariables[] = $sessionId;
1047
            $sql = "SELECT
1048
                        u.user_id, u.lastname, u.firstname, u.username,
1049
                        u.email, s.c_id, s.session_id
1050
                    FROM $session_course_user s
1051
                    INNER JOIN $user u
1052
                    ON u.user_id = s.user_id
1053
                    $where $order $limit";
1054
        } else {
1055
            $sql = "SELECT
1056
                        u.user_id, u.lastname, u.firstname, u.username,
1057
                        u.email, s.c_id, s.session_id
1058
                    FROM $session_course_user s
1059
                    INNER JOIN $user u ON u.user_id = s.user_id
1060
                    $where $order $limit";
1061
        }
1062
1063
        $sql_query = vsprintf($sql, $queryVariables);
1064
        $rs = Database::query($sql_query);
1065
        while ($user = Database::fetch_array($rs)) {
1066
            $users[$user['user_id']] = $user;
1067
        }
1068
1069
        /**
1070
         *  Lessons.
1071
         */
1072
        $sql = "SELECT * FROM $tbl_course_lp WHERE c_id = %s "; //AND session_id = %s
1073
        $sql_query = sprintf($sql, $course['real_id']);
1074
        $result = Database::query($sql_query);
1075
        $arrLesson = [[]];
1076
        while ($row = Database::fetch_array($result)) {
1077
            if (empty($arrLesson[$row['session_id']]['lessons_total'])) {
1078
                $arrLesson[$row['session_id']]['lessons_total'] = 1;
1079
            } else {
1080
                $arrLesson[$row['session_id']]['lessons_total']++;
1081
            }
1082
        }
1083
1084
        /**
1085
         *  Exercises.
1086
         */
1087
        $exercises = ExerciseLib::get_all_exercises(
1088
            $course,
1089
            $sessionId,
1090
            false,
1091
            '',
1092
            $getAllSessions
1093
        );
1094
        $exercises_total = count($exercises);
1095
1096
        /**
1097
         *  Assignments.
1098
         */
1099
        //total
1100
        $params = [$course['real_id']];
1101
        if ($getAllSessions) {
1102
            $sql = "SELECT count(w.id) as count
1103
                    FROM $workTable w
1104
                    LEFT JOIN $workTableAssignment a
1105
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
1106
                    WHERE 
1107
                        w.c_id = %s AND 
1108
                        parent_id = 0 AND 
1109
                        active IN (1, 0)";
1110
        } else {
1111
            $sql = "SELECT count(w.id) as count
1112
                    FROM $workTable w
1113
                    LEFT JOIN $workTableAssignment a
1114
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
1115
                    WHERE 
1116
                        w.c_id = %s AND 
1117
                        parent_id = 0 AND 
1118
                        active IN (1, 0)";
1119
1120
            if (empty($sessionId)) {
1121
                $sql .= ' AND w.session_id = NULL ';
1122
            } else {
1123
                $sql .= ' AND w.session_id = %s ';
1124
                $params[] = $sessionId;
1125
            }
1126
        }
1127
1128
        $sql_query = vsprintf($sql, $params);
1129
        $result = Database::query($sql_query);
1130
        $row = Database::fetch_array($result);
1131
        $assignments_total = $row['count'];
1132
1133
        /**
1134
         * Wiki.
1135
         */
1136
        if ($getAllSessions) {
1137
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
1138
                    WHERE c_id = %s";
1139
        } else {
1140
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
1141
                    WHERE c_id = %s and session_id = %s";
1142
        }
1143
        $sql_query = sprintf($sql, $course['real_id'], $sessionId);
1144
        $result = Database::query($sql_query);
1145
        $row = Database::fetch_array($result);
1146
        $wiki_total = $row['count'];
1147
1148
        /**
1149
         * Surveys.
1150
         */
1151
        $survey_user_list = [];
1152
        $survey_list = SurveyManager::get_surveys($course['code'], $sessionId);
1153
1154
        $surveys_total = count($survey_list);
1155
        foreach ($survey_list as $survey) {
1156
            $user_list = SurveyManager::get_people_who_filled_survey(
1157
                $survey['survey_id'],
1158
                false,
1159
                $course['real_id']
1160
            );
1161
            foreach ($user_list as $user_id) {
1162
                isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id]++ : $survey_user_list[$user_id] = 1;
1163
            }
1164
        }
1165
1166
        /**
1167
         * Forums.
1168
         */
1169
        $forums_total = CourseManager::getCountForum(
1170
            $course['real_id'],
1171
            $sessionId,
1172
            $getAllSessions
1173
        );
1174
1175
        //process table info
1176
        foreach ($users as $user) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $users does not seem to be defined for all execution paths leading up to this point.
Loading history...
1177
            //Course description
1178
            $sql = "SELECT count(*) as count
1179
                    FROM $table_stats_access
1180
                    WHERE access_tool = 'course_description'
1181
                    AND c_id = '%s'
1182
                    AND access_session_id = %s
1183
                    AND access_user_id = %s ";
1184
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
1185
1186
            $result = Database::query($sql_query);
1187
            $row = Database::fetch_array($result);
1188
            $course_description_progress = ($row['count'] > 0) ? 100 : 0;
1189
1190
            if (!empty($arrLesson[$user['id_session']]['lessons_total'])) {
1191
                $lessons_total = $arrLesson[$user['id_session']]['lessons_total'];
1192
            } else {
1193
                $lessons_total = !empty($arrLesson[0]['lessons_total']) ? $arrLesson[0]['lessons_total'] : 0;
1194
            }
1195
1196
            //Lessons
1197
            //TODO: Lessons done and left is calculated by progress per item in lesson, maybe we should calculate it only per completed lesson?
1198
            $lessons_progress = Tracking::get_avg_student_progress(
1199
                $user['user_id'],
1200
                $course['code'],
1201
                [],
1202
                $user['id_session']
1203
            );
1204
            $lessons_done = ($lessons_progress * $lessons_total) / 100;
1205
            $lessons_left = $lessons_total - $lessons_done;
1206
1207
            // Exercises
1208
            $exercises_progress = str_replace(
1209
                '%',
1210
                '',
1211
                Tracking::get_exercise_student_progress(
1212
                    $exercises,
1213
                    $user['user_id'],
1214
                    $course['real_id'],
1215
                    $user['id_session']
1216
                )
1217
            );
1218
            $exercises_done = round(($exercises_progress * $exercises_total) / 100);
1219
            $exercises_left = $exercises_total - $exercises_done;
1220
1221
            //Assignments
1222
            $assignments_done = Tracking::count_student_assignments($user['user_id'], $course['code'], $user['id_session']);
1223
            $assignments_left = $assignments_total - $assignments_done;
1224
            if (!empty($assignments_total)) {
1225
                $assignments_progress = round((($assignments_done * 100) / $assignments_total), 2);
1226
            } else {
1227
                $assignments_progress = 0;
1228
            }
1229
1230
            // Wiki
1231
            // total revisions per user
1232
            $sql = "SELECT count(*) as count
1233
                    FROM $wiki
1234
                    WHERE c_id = %s and session_id = %s and user_id = %s";
1235
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
1236
            $result = Database::query($sql_query);
1237
            $row = Database::fetch_array($result);
1238
            $wiki_revisions = $row['count'];
1239
            //count visited wiki pages
1240
            $sql = "SELECT count(distinct default_value) as count
1241
                    FROM $table_stats_default
1242
                    WHERE
1243
                        default_user_id = %s AND
1244
                        default_event_type = 'wiki_page_view' AND
1245
                        default_value_type = 'wiki_page_id' AND
1246
                        c_id = %s
1247
                    ";
1248
            $sql_query = sprintf($sql, $user['user_id'], $course['real_id']);
1249
            $result = Database::query($sql_query);
1250
            $row = Database::fetch_array($result);
1251
1252
            $wiki_read = $row['count'];
1253
            $wiki_unread = $wiki_total - $wiki_read;
1254
            if (!empty($wiki_total)) {
1255
                $wiki_progress = round((($wiki_read * 100) / $wiki_total), 2);
1256
            } else {
1257
                $wiki_progress = 0;
1258
            }
1259
1260
            //Surveys
1261
            $surveys_done = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0);
1262
            $surveys_left = $surveys_total - $surveys_done;
1263
            if (!empty($surveys_total)) {
1264
                $surveys_progress = round((($surveys_done * 100) / $surveys_total), 2);
1265
            } else {
1266
                $surveys_progress = 0;
1267
            }
1268
1269
            //Forums
1270
            $forums_done = CourseManager::getCountForumPerUser(
1271
                $user['user_id'],
1272
                $course['real_id'],
1273
                $user['id_session']
1274
            );
1275
            $forums_left = $forums_total - $forums_done;
1276
            if (!empty($forums_total)) {
1277
                $forums_progress = round((($forums_done * 100) / $forums_total), 2);
1278
            } else {
1279
                $forums_progress = 0;
1280
            }
1281
1282
            // Overall Total
1283
            $overall_total = ($course_description_progress + $exercises_progress + $forums_progress + $assignments_progress + $wiki_progress + $surveys_progress) / 6;
1284
1285
            $link = '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$user[0].'&details=true&course='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1286
            $linkForum = '<a href="'.api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1287
            $linkWork = '<a href="'.api_get_path(WEB_CODE_PATH).'work/work.php?cidReq='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1288
            $linkWiki = '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?cidReq='.$course['code'].'&session_id='.$user['id_session'].'&action=statistics"> %s </a>';
1289
            $linkSurvey = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cidReq='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1290
1291
            $table[] = [
1292
                'lastname' => $user[1],
1293
                'firstname' => $user[2],
1294
                'username' => $user[3],
1295
                //'profile'   => '',
1296
                'total' => round($overall_total, 2).'%',
1297
                'courses' => sprintf($link, $course_description_progress.'%'),
1298
                'lessons' => sprintf($link, $lessons_progress.'%'),
1299
                'exercises' => sprintf($link, $exercises_progress.'%'),
1300
                'forums' => sprintf($link, $forums_progress.'%'),
1301
                'homeworks' => sprintf($link, $assignments_progress.'%'),
1302
                'wikis' => sprintf($link, $wiki_progress.'%'),
1303
                'surveys' => sprintf($link, $surveys_progress.'%'),
1304
                //course description
1305
                'course_description_progress' => $course_description_progress.'%',
1306
                //lessons
1307
                'lessons_total' => sprintf($link, $lessons_total),
1308
                'lessons_done' => sprintf($link, $lessons_done),
1309
                'lessons_left' => sprintf($link, $lessons_left),
1310
                'lessons_progress' => sprintf($link, $lessons_progress.'%'),
1311
                //exercises
1312
                'exercises_total' => sprintf($link, $exercises_total),
1313
                'exercises_done' => sprintf($link, $exercises_done),
1314
                'exercises_left' => sprintf($link, $exercises_left),
1315
                'exercises_progress' => sprintf($link, $exercises_progress.'%'),
1316
                //forums
1317
                'forums_total' => sprintf($linkForum, $forums_total),
1318
                'forums_done' => sprintf($linkForum, $forums_done),
1319
                'forums_left' => sprintf($linkForum, $forums_left),
1320
                'forums_progress' => sprintf($linkForum, $forums_progress.'%'),
1321
                //assignments
1322
                'assignments_total' => sprintf($linkWork, $assignments_total),
1323
                'assignments_done' => sprintf($linkWork, $assignments_done),
1324
                'assignments_left' => sprintf($linkWork, $assignments_left),
1325
                'assignments_progress' => sprintf($linkWork, $assignments_progress.'%'),
1326
                //wiki
1327
                'wiki_total' => sprintf($linkWiki, $wiki_total),
1328
                'wiki_revisions' => sprintf($linkWiki, $wiki_revisions),
1329
                'wiki_read' => sprintf($linkWiki, $wiki_read),
1330
                'wiki_unread' => sprintf($linkWiki, $wiki_unread),
1331
                'wiki_progress' => sprintf($linkWiki, $wiki_progress.'%'),
1332
                //survey
1333
                'surveys_total' => sprintf($linkSurvey, $surveys_total),
1334
                'surveys_done' => sprintf($linkSurvey, $surveys_done),
1335
                'surveys_left' => sprintf($linkSurvey, $surveys_left),
1336
                'surveys_progress' => sprintf($linkSurvey, $surveys_progress.'%'),
1337
            ];
1338
        }
1339
1340
        return $table;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $table seems to be defined by a foreach iteration on line 1176. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
1341
    }
1342
1343
    /**
1344
     * Get the ip, total of clicks, login date and time logged in for all user, in one session.
1345
     *
1346
     * @todo track_e_course_access table should have ip so we dont have to look for it in track_e_login
1347
     *
1348
     * @author César Perales <[email protected]>, Beeznest Team
1349
     *
1350
     * @version 1.9.6
1351
     */
1352
    public static function get_user_data_access_tracking_overview(
1353
        $sessionId,
1354
        $courseId,
1355
        $studentId = 0,
1356
        $profile = '',
1357
        $date_from = '',
1358
        $date_to = '',
1359
        $options
1360
    ) {
1361
        //escaping variables
1362
        $sessionId = intval($sessionId);
1363
        $courseId = intval($courseId);
1364
        $studentId = intval($studentId);
1365
        $profile = intval($profile);
1366
        $date_from = Database::escape_string($date_from);
1367
        $date_to = Database::escape_string($date_to);
1368
1369
        // database table definition
1370
        $user = Database::get_main_table(TABLE_MAIN_USER);
1371
        $course = Database::get_main_table(TABLE_MAIN_COURSE);
1372
        $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
1373
        $track_e_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1374
        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
1375
1376
        global $export_csv;
1377
        if ($export_csv) {
1378
            $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
1379
        } else {
1380
            $is_western_name_order = api_is_western_name_order();
1381
        }
1382
1383
        $where = null;
1384
        if (isset($sessionId) && !empty($sessionId)) {
1385
            $where = sprintf(" WHERE a.session_id = %d", $sessionId);
1386
        }
1387
        if (isset($courseId) && !empty($courseId)) {
1388
            $where .= sprintf(" AND c.id = %d", $courseId);
1389
        }
1390
        if (isset($studentId) && !empty($studentId)) {
1391
            $where .= sprintf(" AND u.user_id = %d", $studentId);
1392
        }
1393
        if (isset($profile) && !empty($profile)) {
1394
            $where .= sprintf(" AND u.status = %d", $profile);
1395
        }
1396
        if (!empty($date_to) && !empty($date_from)) {
1397
            $where .= sprintf(
1398
                " AND a.login_course_date >= '%s 00:00:00'
1399
                 AND a.login_course_date <= '%s 23:59:59'",
1400
                $date_from,
1401
                $date_to
1402
            );
1403
        }
1404
1405
        $limit = null;
1406
        if (!empty($options['limit'])) {
1407
            $limit = " LIMIT ".$options['limit'];
1408
        }
1409
1410
        if (!empty($options['where'])) {
1411
            $where .= ' '.$options['where'];
1412
        }
1413
1414
        $order = null;
1415
        if (!empty($options['order'])) {
1416
            $order = " ORDER BY ".$options['order'];
1417
        }
1418
1419
        //TODO add course name
1420
        $sql = "SELECT
1421
                a.login_course_date ,
1422
                u.username ,
1423
                ".($is_western_name_order ? "
1424
                    u.firstname,
1425
                    u.lastname,
1426
                    " : "
1427
                    u.lastname,
1428
                    u.firstname,
1429
                ")."
1430
                a.logout_course_date,
1431
                a.counter,
1432
                c.title,
1433
                c.code,
1434
                u.user_id,
1435
                a.session_id
1436
            FROM $track_e_course_access a
1437
            INNER JOIN $user u ON a.user_id = u.user_id
1438
            INNER JOIN $course c ON a.c_id = c.id
1439
            $where $order $limit";
1440
        $result = Database::query(sprintf($sql, $sessionId, $courseId));
1441
1442
        $data = [];
1443
        while ($user = Database::fetch_assoc($result)) {
1444
            $data[] = $user;
1445
        }
1446
1447
        foreach ($data as $key => $info) {
1448
            $sql = "SELECT
1449
                    name
1450
                    FROM $sessionTable
1451
                    WHERE
1452
                    id = {$info['session_id']}";
1453
            $result = Database::query($sql);
1454
            $session = Database::fetch_assoc($result);
1455
1456
            // building array to display
1457
            $return[] = [
1458
                'user_id' => $info['user_id'],
1459
                'logindate' => $info['login_course_date'],
1460
                'username' => $info['username'],
1461
                'firstname' => $info['firstname'],
1462
                'lastname' => $info['lastname'],
1463
                'clicks' => $info['counter'], //+ $clicks[$info['user_id']],
1464
                'ip' => '',
1465
                'timeLoggedIn' => gmdate("H:i:s", strtotime($info['logout_course_date']) - strtotime($info['login_course_date'])),
1466
                'session' => $session['name'],
1467
            ];
1468
        }
1469
1470
        foreach ($return as $key => $info) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $return seems to be defined by a foreach iteration on line 1447. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
1471
            //Search for ip, we do less querys if we iterate the final array
1472
            $sql = sprintf(
1473
                "SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date < '%s' ORDER BY login_date DESC LIMIT 1",
1474
                $info['user_id'],
1475
                $info['logindate']
1476
            ); //TODO add select by user too
1477
            $result = Database::query($sql);
1478
            $ip = Database::fetch_assoc($result);
1479
            //if no ip founded, we search the closest higher ip
1480
            if (empty($ip['user_ip'])) {
1481
                $sql = sprintf(
1482
                    "SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date > '%s'  ORDER BY login_date ASC LIMIT 1",
1483
                    $info['user_id'],
1484
                    $info['logindate']
1485
                ); //TODO add select by user too
1486
                $result = Database::query($sql);
1487
                $ip = Database::fetch_assoc($result);
1488
            }
1489
            //add ip to final array
1490
            $return[$key]['ip'] = $ip['user_ip'];
1491
        }
1492
1493
        return $return;
1494
    }
1495
1496
    /**
1497
     * Creates a new course code based in given code.
1498
     *
1499
     * @param string $session_name
1500
     *                             <code>
1501
     *                             $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3
1502
     *                             if the course code doest not exist in the DB the same course code will be returned
1503
     *                             </code>
1504
     *
1505
     * @return string wanted unused code
1506
     */
1507
    public static function generateNextSessionName($session_name)
1508
    {
1509
        $session_name_ok = !self::sessionNameExists($session_name);
1510
        if (!$session_name_ok) {
1511
            $table = Database::get_main_table(TABLE_MAIN_SESSION);
1512
            $session_name = Database::escape_string($session_name);
1513
            $sql = "SELECT count(*) as count FROM $table
1514
                    WHERE name LIKE '$session_name%'";
1515
            $result = Database::query($sql);
1516
            if (Database::num_rows($result) > 0) {
1517
                $row = Database::fetch_array($result);
1518
                $count = $row['count'] + 1;
1519
                $session_name = $session_name.'_'.$count;
1520
                $result = self::sessionNameExists($session_name);
1521
                if (!$result) {
1522
                    return $session_name;
1523
                }
1524
            }
1525
1526
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
1527
        }
1528
1529
        return $session_name;
1530
    }
1531
1532
    /**
1533
     * Edit a session.
1534
     *
1535
     * @author Carlos Vargas from existing code
1536
     *
1537
     * @param int    $id                           Session primary key
1538
     * @param string $name
1539
     * @param string $startDate
1540
     * @param string $endDate
1541
     * @param string $displayStartDate
1542
     * @param string $displayEndDate
1543
     * @param string $coachStartDate
1544
     * @param string $coachEndDate
1545
     * @param int    $coachId
1546
     * @param int    $sessionCategoryId
1547
     * @param int    $visibility
1548
     * @param string $description
1549
     * @param int    $showDescription
1550
     * @param int    $duration
1551
     * @param array  $extraFields
1552
     * @param int    $sessionAdminId
1553
     * @param bool   $sendSubscriptionNotification Optional.
1554
     *                                             Whether send a mail notification to users being subscribed
1555
     *
1556
     * @return mixed
1557
     */
1558
    public static function edit_session(
1559
        $id,
1560
        $name,
1561
        $startDate,
1562
        $endDate,
1563
        $displayStartDate,
1564
        $displayEndDate,
1565
        $coachStartDate,
1566
        $coachEndDate,
1567
        $coachId,
1568
        $sessionCategoryId,
1569
        $visibility,
1570
        $description = null,
1571
        $showDescription = 0,
1572
        $duration = null,
1573
        $extraFields = [],
1574
        $sessionAdminId = 0,
1575
        $sendSubscriptionNotification = false
1576
    ) {
1577
        $coachId = intval($coachId);
1578
        $sessionCategoryId = intval($sessionCategoryId);
1579
        $visibility = intval($visibility);
1580
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1581
1582
        if (empty($name)) {
1583
            Display::addFlash(
1584
                Display::return_message(get_lang('SessionNameIsRequired'), 'warning')
1585
            );
1586
1587
            return false;
1588
        } elseif (empty($coachId)) {
1589
            Display::addFlash(
1590
                Display::return_message(get_lang('CoachIsRequired'), 'warning')
1591
            );
1592
1593
            return false;
1594
        } elseif (!empty($startDate) &&
1595
            !api_is_valid_date($startDate, 'Y-m-d H:i') &&
1596
            !api_is_valid_date($startDate, 'Y-m-d H:i:s')
1597
        ) {
1598
            Display::addFlash(
1599
                Display::return_message(get_lang('InvalidStartDate'), 'warning')
1600
            );
1601
1602
            return false;
1603
        } elseif (!empty($endDate) &&
1604
            !api_is_valid_date($endDate, 'Y-m-d H:i') &&
1605
            !api_is_valid_date($endDate, 'Y-m-d H:i:s')
1606
        ) {
1607
            Display::addFlash(
1608
                Display::return_message(get_lang('InvalidEndDate'), 'warning')
1609
            );
1610
1611
            return false;
1612
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
1613
            Display::addFlash(
1614
                Display::return_message(get_lang('StartDateShouldBeBeforeEndDate'), 'warning')
1615
            );
1616
1617
            return false;
1618
        } else {
1619
            $sessionInfo = self::get_session_by_name($name);
1620
            $exists = false;
1621
1622
            if (!empty($sessionInfo)) {
1623
                if ($sessionInfo['id'] != $id) {
1624
                    $exists = true;
1625
                }
1626
            }
1627
1628
            if ($exists) {
1629
                Display::addFlash(
1630
                    Display::return_message(get_lang('SessionNameAlreadyExists'), 'warning')
1631
                );
1632
1633
                return false;
1634
            } else {
1635
                $values = [
1636
                    'name' => $name,
1637
                    'duration' => $duration,
1638
                    'id_coach' => $coachId,
1639
                    'description' => $description,
1640
                    'show_description' => intval($showDescription),
1641
                    'visibility' => $visibility,
1642
                    'send_subscription_notification' => $sendSubscriptionNotification,
1643
                    'access_start_date' => null,
1644
                    'access_end_date' => null,
1645
                    'display_start_date' => null,
1646
                    'display_end_date' => null,
1647
                    'coach_access_start_date' => null,
1648
                    'coach_access_end_date' => null,
1649
                ];
1650
1651
                if (!empty($sessionAdminId)) {
1652
                    $values['session_admin_id'] = $sessionAdminId;
1653
                }
1654
1655
                if (!empty($startDate)) {
1656
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
1657
                }
1658
1659
                if (!empty($endDate)) {
1660
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
1661
                }
1662
1663
                if (!empty($displayStartDate)) {
1664
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
1665
                }
1666
1667
                if (!empty($displayEndDate)) {
1668
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
1669
                }
1670
1671
                if (!empty($coachStartDate)) {
1672
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
1673
                }
1674
                if (!empty($coachEndDate)) {
1675
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
1676
                }
1677
1678
                if (!empty($sessionCategoryId)) {
1679
                    $values['session_category_id'] = $sessionCategoryId;
1680
                } else {
1681
                    $values['session_category_id'] = null;
1682
                }
1683
1684
                Database::update(
1685
                    $tbl_session,
1686
                    $values,
1687
                    ['id = ?' => $id]
1688
                );
1689
1690
                if (!empty($extraFields)) {
1691
                    $extraFields['item_id'] = $id;
1692
                    $sessionFieldValue = new ExtraFieldValue('session');
1693
                    $sessionFieldValue->saveFieldValues($extraFields);
1694
                }
1695
1696
                return $id;
1697
            }
1698
        }
1699
    }
1700
1701
    /**
1702
     * Delete session.
1703
     *
1704
     * @author Carlos Vargas  from existing code
1705
     *
1706
     * @param array $id_checked an array to delete sessions
1707
     * @param bool  $from_ws    optional, true if the function is called
1708
     *                          by a webservice, false otherwise
1709
     *
1710
     * @return bool
1711
     * */
1712
    public static function delete($id_checked, $from_ws = false)
1713
    {
1714
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1715
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1716
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1717
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1718
        $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1719
        $tbl_item_properties = Database::get_course_table(TABLE_ITEM_PROPERTY);
1720
        $tbl_student_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1721
        $tbl_student_publication_assignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1722
        $userGroupSessionTable = Database::get_main_table(TABLE_USERGROUP_REL_SESSION);
1723
        $trackCourseAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1724
        $trackAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
1725
1726
        $ticket = Database::get_main_table(TABLE_TICKET_TICKET);
1727
        $em = Database::getManager();
1728
        $userId = api_get_user_id();
1729
1730
        /** @var SequenceRepository $repo */
1731
        $repo = Database::getManager()->getRepository('ChamiloCoreBundle:SequenceResource');
1732
        $sequenceResource = $repo->findRequirementForResource(
1733
            $id_checked,
1734
            SequenceResource::SESSION_TYPE
1735
        );
1736
1737
        if ($sequenceResource) {
0 ignored issues
show
introduced by
$sequenceResource is of type Chamilo\CoreBundle\Entity\SequenceResource, thus it always evaluated to true.
Loading history...
1738
            Display::addFlash(
1739
                Display::return_message(
1740
                    get_lang('ThereIsASequenceResourceLinkedToThisSessionYouNeedToDeleteItFirst'),
1741
                    'error'
1742
                )
1743
            );
1744
1745
            return false;
1746
        }
1747
1748
        if (is_array($id_checked)) {
1749
            foreach ($id_checked as $sessionId) {
1750
                self::delete($sessionId);
1751
            }
1752
        } else {
1753
            $id_checked = intval($id_checked);
1754
        }
1755
1756
        if (self::allowed($id_checked) && !$from_ws) {
1757
            $qb = $em
1758
                ->createQuery('
1759
                    SELECT s.sessionAdminId FROM ChamiloCoreBundle:Session s
1760
                    WHERE s.id = ?1
1761
                ')
1762
                ->setParameter(1, $id_checked);
1763
1764
            $res = $qb->getSingleScalarResult();
1765
1766
            if ($res != $userId && !api_is_platform_admin()) {
1767
                api_not_allowed(true);
1768
            }
1769
        }
1770
1771
        // Delete documents inside a session
1772
        $courses = self::getCoursesInSession($id_checked);
1773
        foreach ($courses as $courseId) {
1774
            $courseInfo = api_get_course_info_by_id($courseId);
1775
            DocumentManager::deleteDocumentsFromSession($courseInfo, $id_checked);
1776
            $works = Database::select(
1777
                '*',
1778
                $tbl_student_publication,
1779
                [
1780
                    'where' => ['session_id = ? AND c_id = ?' => [$id_checked, $courseId]],
1781
                ]
1782
            );
1783
1784
            $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
1785
            foreach ($works as $index => $work) {
1786
                if ($work['filetype'] = 'folder') {
1787
                    Database::query("DELETE FROM $tbl_student_publication_assignment WHERE publication_id = $index");
1788
                }
1789
                my_delete($currentCourseRepositorySys.'/'.$work['url']);
1790
            }
1791
        }
1792
1793
        // Class
1794
        $sql = "DELETE FROM $userGroupSessionTable
1795
                WHERE session_id IN($id_checked)";
1796
        Database::query($sql);
1797
1798
        Database::query("DELETE FROM $tbl_student_publication WHERE session_id IN($id_checked)");
1799
        Database::query("DELETE FROM $tbl_session_rel_course WHERE session_id IN($id_checked)");
1800
        Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id IN($id_checked)");
1801
        Database::query("DELETE FROM $tbl_session_rel_user WHERE session_id IN($id_checked)");
1802
        Database::query("DELETE FROM $tbl_item_properties WHERE session_id IN ($id_checked)");
1803
        Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
1804
1805
        Database::query("DELETE FROM $trackCourseAccess WHERE session_id IN($id_checked)");
1806
        Database::query("DELETE FROM $trackAccess WHERE access_session_id IN($id_checked)");
1807
1808
        $sql = "UPDATE $ticket SET session_id = NULL WHERE session_id IN ($id_checked)";
1809
        Database::query($sql);
1810
1811
        $sql = "DELETE FROM $tbl_session WHERE id IN ($id_checked)";
1812
        Database::query($sql);
1813
1814
        $extraFieldValue = new ExtraFieldValue('session');
1815
        $extraFieldValue->deleteValuesByItem($id_checked);
1816
1817
        $repo->deleteResource(
1818
            $id_checked,
1819
            SequenceResource::SESSION_TYPE
1820
        );
1821
1822
        // Add event to system log
1823
        Event::addEvent(
1824
            LOG_SESSION_DELETE,
1825
            LOG_SESSION_ID,
1826
            $id_checked,
1827
            api_get_utc_datetime(),
1828
            $userId
1829
        );
1830
1831
        return true;
1832
    }
1833
1834
    /**
1835
     * @param int $id promotion id
1836
     *
1837
     * @return bool
1838
     */
1839
    public static function clear_session_ref_promotion($id)
1840
    {
1841
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1842
        $id = intval($id);
1843
        $sql = "UPDATE $tbl_session 
1844
                SET promotion_id = 0
1845
                WHERE promotion_id = $id";
1846
        if (Database::query($sql)) {
1847
            return true;
1848
        } else {
1849
            return false;
1850
        }
1851
    }
1852
1853
    /**
1854
     * Subscribes students to the given session and optionally (default)
1855
     * unsubscribes previous users.
1856
     *
1857
     * @author Carlos Vargas from existing code
1858
     * @author Julio Montoya. Cleaning code.
1859
     *
1860
     * @param int   $id_session
1861
     * @param array $user_list
1862
     * @param int   $session_visibility
1863
     * @param bool  $empty_users
1864
     *
1865
     * @return bool
1866
     */
1867
    public static function subscribe_users_to_session(
1868
        $id_session,
1869
        $user_list,
1870
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
1871
        $empty_users = true
1872
    ) {
1873
        if ($id_session != strval(intval($id_session))) {
1874
            return false;
1875
        }
1876
1877
        foreach ($user_list as $intUser) {
1878
            if ($intUser != strval(intval($intUser))) {
1879
                return false;
1880
            }
1881
        }
1882
1883
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1884
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1885
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1886
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1887
1888
        $entityManager = Database::getManager();
1889
        $session = $entityManager->find('ChamiloCoreBundle:Session', $id_session);
1890
1891
        // from function parameter
1892
        if (empty($session_visibility)) {
1893
            $session_visibility = $session->getVisibility();
1894
            //default status loaded if empty
1895
            // by default readonly 1
1896
            if (empty($session_visibility)) {
1897
                $session_visibility = SESSION_VISIBLE_READ_ONLY;
1898
            }
1899
        } else {
1900
            if (!in_array($session_visibility, [SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE])) {
1901
                $session_visibility = SESSION_VISIBLE_READ_ONLY;
1902
            }
1903
        }
1904
1905
        $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user
1906
                WHERE session_id = $id_session AND status = 0";
1907
        $result = Database::query($sql);
1908
        $existingUsers = [];
1909
        while ($row = Database::fetch_array($result)) {
1910
            $existingUsers[] = $row['user_id'];
1911
        }
1912
1913
        $sql = "SELECT c_id FROM $tbl_session_rel_course
1914
                WHERE session_id = $id_session";
1915
        $result = Database::query($sql);
1916
        $course_list = [];
1917
        while ($row = Database::fetch_array($result)) {
1918
            $course_list[] = $row['c_id'];
1919
        }
1920
1921
        if ($session->getSendSubscriptionNotification() &&
1922
            is_array($user_list)
1923
        ) {
1924
            // Sending emails only
1925
            foreach ($user_list as $user_id) {
1926
                if (in_array($user_id, $existingUsers)) {
1927
                    continue;
1928
                }
1929
1930
                $tplSubject = new Template(
1931
                    null,
1932
                    false,
1933
                    false,
1934
                    false,
1935
                    false,
1936
                    false
1937
                );
1938
                $layoutSubject = $tplSubject->get_template(
1939
                    'mail/subject_subscription_to_session_confirmation.tpl'
1940
                );
1941
                $subject = $tplSubject->fetch($layoutSubject);
1942
                $user_info = api_get_user_info($user_id);
1943
1944
                $tplContent = new Template(
1945
                    null,
1946
                    false,
1947
                    false,
1948
                    false,
1949
                    false,
1950
                    false
1951
                );
1952
                // Variables for default template
1953
                $tplContent->assign(
1954
                    'complete_name',
1955
                    stripslashes($user_info['complete_name'])
1956
                );
1957
                $tplContent->assign('session_name', $session->getName());
1958
                $tplContent->assign(
1959
                    'session_coach',
1960
                    $session->getGeneralCoach()->getCompleteName()
1961
                );
1962
                $layoutContent = $tplContent->get_template(
1963
                    'mail/content_subscription_to_session_confirmation.tpl'
1964
                );
1965
                $content = $tplContent->fetch($layoutContent);
1966
1967
                api_mail_html(
1968
                    $user_info['complete_name'],
1969
                    $user_info['mail'],
1970
                    $subject,
1971
                    $content,
1972
                    api_get_person_name(
1973
                        api_get_setting('administratorName'),
1974
                        api_get_setting('administratorSurname')
1975
                    ),
1976
                    api_get_setting('emailAdministrator')
1977
                );
1978
            }
1979
        }
1980
1981
        foreach ($course_list as $courseId) {
1982
            // for each course in the session
1983
            $nbr_users = 0;
1984
            $courseId = intval($courseId);
1985
1986
            $sql = "SELECT DISTINCT user_id
1987
                    FROM $tbl_session_rel_course_rel_user
1988
                    WHERE
1989
                        session_id = $id_session AND
1990
                        c_id = $courseId AND
1991
                        status = 0
1992
                    ";
1993
            $result = Database::query($sql);
1994
            $existingUsers = [];
1995
            while ($row = Database::fetch_array($result)) {
1996
                $existingUsers[] = $row['user_id'];
1997
            }
1998
1999
            // Delete existing users
2000
            if ($empty_users) {
2001
                foreach ($existingUsers as $existing_user) {
2002
                    if (!in_array($existing_user, $user_list)) {
2003
                        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2004
                                WHERE
2005
                                    session_id = $id_session AND
2006
                                    c_id = $courseId AND
2007
                                    user_id = $existing_user AND
2008
                                    status = 0 ";
2009
                        $result = Database::query($sql);
2010
2011
                        Event::addEvent(
2012
                            LOG_SESSION_DELETE_USER_COURSE,
2013
                            LOG_USER_ID,
2014
                            $existing_user,
2015
                            api_get_utc_datetime(),
2016
                            api_get_user_id(),
2017
                            $courseId,
2018
                            $id_session
2019
                        );
2020
2021
                        if (Database::affected_rows($result)) {
2022
                            $nbr_users--;
2023
                        }
2024
                    }
2025
                }
2026
            }
2027
2028
            // Replace with this new function
2029
            // insert new users into session_rel_course_rel_user and ignore if they already exist
2030
            foreach ($user_list as $enreg_user) {
2031
                if (!in_array($enreg_user, $existingUsers)) {
2032
                    $status = self::get_user_status_in_course_session(
2033
                        $enreg_user,
2034
                        $courseId,
2035
                        $id_session
2036
                    );
2037
                    // Avoid duplicate entries.
2038
                    if ($status === false || ($status !== false && $status != 0)) {
2039
                        $enreg_user = (int) $enreg_user;
2040
                        $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility, status)
2041
                                VALUES($id_session, $courseId, $enreg_user, $session_visibility, 0)";
2042
                        $result = Database::query($sql);
2043
                        if (Database::affected_rows($result)) {
2044
                            $nbr_users++;
2045
                        }
2046
2047
                        Event::addEvent(
2048
                            LOG_SESSION_ADD_USER_COURSE,
2049
                            LOG_USER_ID,
2050
                            $enreg_user,
2051
                            api_get_utc_datetime(),
2052
                            api_get_user_id(),
2053
                            $courseId,
2054
                            $id_session
2055
                        );
2056
                    }
2057
                }
2058
            }
2059
2060
            // Count users in this session-course relation
2061
            $sql = "SELECT COUNT(user_id) as nbUsers
2062
                    FROM $tbl_session_rel_course_rel_user
2063
                    WHERE session_id = $id_session AND c_id = $courseId AND status<>2";
2064
            $rs = Database::query($sql);
2065
            list($nbr_users) = Database::fetch_array($rs);
2066
            // update the session-course relation to add the users total
2067
            $sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users
2068
                    WHERE session_id = $id_session AND c_id = $courseId";
2069
            Database::query($sql);
2070
        }
2071
2072
        // Delete users from the session
2073
        if ($empty_users === true) {
2074
            $sql = "DELETE FROM $tbl_session_rel_user
2075
                    WHERE session_id = $id_session AND relation_type<>".SESSION_RELATION_TYPE_RRHH."";
2076
            Database::query($sql);
2077
        }
2078
2079
        // Insert missing users into session
2080
        $nbr_users = 0;
2081
        foreach ($user_list as $enreg_user) {
2082
            $isUserSubscribed = self::isUserSubscribedAsStudent($id_session, $enreg_user);
2083
            if ($isUserSubscribed === false) {
2084
                $enreg_user = (int) $enreg_user;
2085
                $nbr_users++;
2086
                $sql = "INSERT IGNORE INTO $tbl_session_rel_user (relation_type, session_id, user_id, registered_at)
2087
                        VALUES (0, $id_session, $enreg_user, '".api_get_utc_datetime()."')";
2088
                Database::query($sql);
2089
            }
2090
        }
2091
2092
        // update number of users in the session
2093
        $nbr_users = count($user_list);
2094
        if ($empty_users) {
2095
            // update number of users in the session
2096
            $sql = "UPDATE $tbl_session SET nbr_users= $nbr_users
2097
                    WHERE id = $id_session ";
2098
            Database::query($sql);
2099
        } else {
2100
            $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + $nbr_users
2101
                    WHERE id = $id_session";
2102
            Database::query($sql);
2103
        }
2104
    }
2105
2106
    /**
2107
     * Returns user list of the current users subscribed in the course-session.
2108
     *
2109
     * @param int   $sessionId
2110
     * @param array $courseInfo
2111
     * @param int   $status
2112
     *
2113
     * @return array
2114
     */
2115
    public static function getUsersByCourseSession(
2116
        $sessionId,
2117
        $courseInfo,
2118
        $status = null
2119
    ) {
2120
        $sessionId = intval($sessionId);
2121
        $courseId = $courseInfo['real_id'];
2122
2123
        if (empty($sessionId) || empty($courseId)) {
2124
            return [];
2125
        }
2126
2127
        $statusCondition = null;
2128
        if (isset($status) && !is_null($status)) {
2129
            $status = intval($status);
2130
            $statusCondition = " AND status = $status";
2131
        }
2132
2133
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2134
2135
        $sql = "SELECT DISTINCT user_id
2136
                FROM $table
2137
                WHERE
2138
                    session_id = $sessionId AND
2139
                    c_id = $courseId
2140
                    $statusCondition
2141
                ";
2142
2143
        $result = Database::query($sql);
2144
        $existingUsers = [];
2145
        while ($row = Database::fetch_array($result)) {
2146
            $existingUsers[] = $row['user_id'];
2147
        }
2148
2149
        return $existingUsers;
2150
    }
2151
2152
    /**
2153
     * Returns user list of the current users subscribed in the course-session.
2154
     *
2155
     * @param array $sessionList
2156
     * @param array $courseList
2157
     * @param int   $status
2158
     * @param int   $start
2159
     * @param int   $limit
2160
     *
2161
     * @return array
2162
     */
2163
    public static function getUsersByCourseAndSessionList(
2164
        $sessionList,
2165
        $courseList,
2166
        $status = null,
2167
        $start = null,
2168
        $limit = null
2169
    ) {
2170
        if (empty($sessionList) || empty($courseList)) {
2171
            return [];
2172
        }
2173
        $sessionListToString = implode("','", $sessionList);
2174
        $courseListToString = implode("','", $courseList);
2175
2176
        $statusCondition = null;
2177
        if (isset($status) && !is_null($status)) {
2178
            $status = intval($status);
2179
            $statusCondition = " AND status = $status";
2180
        }
2181
2182
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2183
2184
        $sql = "SELECT DISTINCT user_id
2185
                FROM $table
2186
                WHERE
2187
                    session_id IN ('$sessionListToString') AND
2188
                    c_id IN ('$courseListToString')
2189
                    $statusCondition
2190
                ";
2191
        if (!is_null($start) && !is_null($limit)) {
2192
            $start = (int) $start;
2193
            $limit = (int) $limit;
2194
            $sql .= "LIMIT $start, $limit";
2195
        }
2196
        $result = Database::query($sql);
2197
        $existingUsers = [];
2198
        while ($row = Database::fetch_array($result)) {
2199
            $existingUsers[] = $row['user_id'];
2200
        }
2201
2202
        return $existingUsers;
2203
    }
2204
2205
    /**
2206
     * Remove a list of users from a course-session.
2207
     *
2208
     * @param array $userList
2209
     * @param int   $sessionId
2210
     * @param array $courseInfo
2211
     * @param int   $status
2212
     * @param bool  $updateTotal
2213
     *
2214
     * @return bool
2215
     */
2216
    public static function removeUsersFromCourseSession(
2217
        $userList,
2218
        $sessionId,
2219
        $courseInfo,
2220
        $status = null,
2221
        $updateTotal = true
2222
    ) {
2223
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2224
        $tableSessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2225
        $sessionId = intval($sessionId);
2226
2227
        if (empty($sessionId) || empty($userList) || empty($courseInfo)) {
2228
            return false;
2229
        }
2230
2231
        is_array($courseInfo) ? $courseId = $courseInfo['real_id'] : $courseId = $courseInfo;
2232
2233
        $statusCondition = null;
2234
        if (isset($status) && !is_null($status)) {
2235
            $status = intval($status);
2236
            $statusCondition = " AND status = $status";
2237
        }
2238
2239
        foreach ($userList as $userId) {
2240
            $userId = intval($userId);
2241
            $sql = "DELETE FROM $table
2242
                    WHERE
2243
                        session_id = $sessionId AND
2244
                        c_id = $courseId AND
2245
                        user_id = $userId
2246
                        $statusCondition
2247
                    ";
2248
            Database::query($sql);
2249
        }
2250
2251
        if ($updateTotal) {
2252
            // Count users in this session-course relation
2253
            $sql = "SELECT COUNT(user_id) as nbUsers
2254
                    FROM $table
2255
                    WHERE
2256
                        session_id = $sessionId AND
2257
                        c_id = $courseId AND
2258
                        status <> 2";
2259
            $result = Database::query($sql);
2260
            list($userCount) = Database::fetch_array($result);
2261
2262
            // update the session-course relation to add the users total
2263
            $sql = "UPDATE $tableSessionCourse
2264
                    SET nbr_users = $userCount
2265
                    WHERE
2266
                        session_id = $sessionId AND
2267
                        c_id = $courseId";
2268
            Database::query($sql);
2269
        }
2270
    }
2271
2272
    /**
2273
     * Subscribe a user to an specific course inside a session.
2274
     *
2275
     * @param array  $user_list
2276
     * @param int    $session_id
2277
     * @param string $course_code
2278
     * @param int    $session_visibility
2279
     * @param bool   $removeUsersNotInList
2280
     *
2281
     * @return bool
2282
     */
2283
    public static function subscribe_users_to_session_course(
2284
        $user_list,
2285
        $session_id,
2286
        $course_code,
2287
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
2288
        $removeUsersNotInList = false
2289
    ) {
2290
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2291
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2292
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2293
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2294
2295
        if (empty($session_id) || empty($course_code)) {
2296
            return false;
2297
        }
2298
2299
        $session_id = intval($session_id);
2300
        $course_code = Database::escape_string($course_code);
2301
        $courseInfo = api_get_course_info($course_code);
2302
        $courseId = $courseInfo['real_id'];
2303
        $session_visibility = intval($session_visibility);
2304
2305
        if ($removeUsersNotInList) {
2306
            $currentUsers = self::getUsersByCourseSession($session_id, $courseInfo, 0);
2307
2308
            if (!empty($user_list)) {
2309
                $userToDelete = array_diff($currentUsers, $user_list);
2310
            } else {
2311
                $userToDelete = $currentUsers;
2312
            }
2313
2314
            if (!empty($userToDelete)) {
2315
                self::removeUsersFromCourseSession(
2316
                    $userToDelete,
2317
                    $session_id,
2318
                    $courseInfo,
2319
                    0,
2320
                    true
2321
                );
2322
            }
2323
        }
2324
2325
        $nbr_users = 0;
2326
        foreach ($user_list as $enreg_user) {
2327
            $enreg_user = intval($enreg_user);
2328
            // Checking if user exists in session - course - user table.
2329
            $sql = "SELECT count(user_id) as count
2330
                    FROM $tbl_session_rel_course_rel_user
2331
                    WHERE
2332
                        session_id = $session_id AND
2333
                        c_id = $courseId and
2334
                        user_id = $enreg_user ";
2335
            $result = Database::query($sql);
2336
            $count = 0;
2337
2338
            if (Database::num_rows($result) > 0) {
2339
                $row = Database::fetch_array($result, 'ASSOC');
2340
                $count = $row['count'];
2341
            }
2342
2343
            if ($count == 0) {
2344
                $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility)
2345
                        VALUES ($session_id, $courseId, $enreg_user, $session_visibility)";
2346
                $result = Database::query($sql);
2347
                if (Database::affected_rows($result)) {
2348
                    $nbr_users++;
2349
                }
2350
            }
2351
2352
            // Checking if user exists in session - user table.
2353
            $sql = "SELECT count(user_id) as count
2354
                    FROM $tbl_session_rel_user
2355
                    WHERE session_id = $session_id AND user_id = $enreg_user ";
2356
            $result = Database::query($sql);
2357
            $count = 0;
2358
2359
            if (Database::num_rows($result) > 0) {
2360
                $row = Database::fetch_array($result, 'ASSOC');
2361
                $count = $row['count'];
2362
            }
2363
2364
            if (empty($count)) {
2365
                // If user is not registered to a session then add it.
2366
                $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, registered_at)
2367
                        VALUES ($session_id, $enreg_user, '".api_get_utc_datetime()."')";
2368
                Database::query($sql);
2369
2370
                $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + 1
2371
                        WHERE id = $session_id ";
2372
                Database::query($sql);
2373
            }
2374
        }
2375
2376
        // count users in this session-course relation
2377
        $sql = "SELECT COUNT(user_id) as nbUsers
2378
                FROM $tbl_session_rel_course_rel_user
2379
                WHERE session_id = $session_id AND c_id = $courseId AND status <> 2";
2380
        $rs = Database::query($sql);
2381
        list($nbr_users) = Database::fetch_array($rs);
2382
        // update the session-course relation to add the users total
2383
        $sql = "UPDATE $tbl_session_rel_course
2384
                SET nbr_users = $nbr_users
2385
                WHERE session_id = $session_id AND c_id = $courseId";
2386
        Database::query($sql);
2387
    }
2388
2389
    /**
2390
     * Unsubscribe user from session.
2391
     *
2392
     * @param int Session id
2393
     * @param int User id
2394
     *
2395
     * @return bool True in case of success, false in case of error
2396
     */
2397
    public static function unsubscribe_user_from_session($session_id, $user_id)
2398
    {
2399
        $session_id = (int) $session_id;
2400
        $user_id = (int) $user_id;
2401
2402
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2403
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2404
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2405
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2406
2407
        $sql = "DELETE FROM $tbl_session_rel_user
2408
                WHERE
2409
                    session_id = $session_id AND
2410
                    user_id = $user_id AND
2411
                    relation_type <> ".SESSION_RELATION_TYPE_RRHH."";
2412
        $result = Database::query($sql);
2413
        $return = Database::affected_rows($result);
2414
2415
        // Update number of users
2416
        $sql = "UPDATE $tbl_session
2417
                SET nbr_users = nbr_users - $return
2418
                WHERE id = $session_id ";
2419
        Database::query($sql);
2420
2421
        // Get the list of courses related to this session
2422
        $course_list = self::get_course_list_by_session_id($session_id);
2423
        if (!empty($course_list)) {
2424
            foreach ($course_list as $course) {
2425
                $courseId = $course['id'];
2426
                // Delete user from course
2427
                $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2428
                        WHERE session_id = $session_id AND c_id = $courseId AND user_id = $user_id";
2429
                $result = Database::query($sql);
2430
2431
                Event::addEvent(
2432
                    LOG_SESSION_DELETE_USER_COURSE,
2433
                    LOG_USER_ID,
2434
                    $user_id,
2435
                    api_get_utc_datetime(),
2436
                    api_get_user_id(),
2437
                    $courseId,
2438
                    $session_id
2439
                );
2440
2441
                if (Database::affected_rows($result)) {
2442
                    // Update number of users in this relation
2443
                    $sql = "UPDATE $tbl_session_rel_course SET 
2444
                            nbr_users = nbr_users - 1
2445
                            WHERE session_id = $session_id AND c_id = $courseId";
2446
                    Database::query($sql);
2447
                }
2448
            }
2449
        }
2450
2451
        return true;
2452
    }
2453
2454
    /**
2455
     * Subscribes courses to the given session and optionally (default)
2456
     * unsubscribe previous users.
2457
     *
2458
     * @author Carlos Vargas from existing code
2459
     *
2460
     * @param int   $sessionId
2461
     * @param array $courseList                     List of courses int ids
2462
     * @param bool  $removeExistingCoursesWithUsers Whether to unsubscribe
2463
     *                                              existing courses and users (true, default) or not (false)
2464
     * @param bool  $copyEvaluation                 from base course to session course
2465
     * */
2466
    public static function add_courses_to_session(
2467
        $sessionId,
2468
        $courseList,
2469
        $removeExistingCoursesWithUsers = true,
2470
        $copyEvaluation = false
2471
    ) {
2472
        $sessionId = intval($sessionId);
2473
2474
        if (empty($sessionId) || empty($courseList)) {
2475
            return false;
2476
        }
2477
2478
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2479
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2480
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2481
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2482
2483
        // Get list of courses subscribed to this session
2484
        $sql = "SELECT c_id
2485
                FROM $tbl_session_rel_course
2486
                WHERE session_id = $sessionId";
2487
        $rs = Database::query($sql);
2488
        $existingCourses = Database::store_result($rs);
2489
        $nbr_courses = count($existingCourses);
2490
2491
        // Get list of users subscribed to this session
2492
        $sql = "SELECT user_id
2493
                FROM $tbl_session_rel_user
2494
                WHERE
2495
                    session_id = $sessionId AND
2496
                    relation_type<>".SESSION_RELATION_TYPE_RRHH;
2497
        $result = Database::query($sql);
2498
        $user_list = Database::store_result($result);
2499
2500
        // Remove existing courses from the session.
2501
        if ($removeExistingCoursesWithUsers === true && !empty($existingCourses)) {
2502
            foreach ($existingCourses as $existingCourse) {
2503
                if (!in_array($existingCourse['c_id'], $courseList)) {
2504
                    $sql = "DELETE FROM $tbl_session_rel_course
2505
                            WHERE
2506
                                c_id = ".$existingCourse['c_id']." AND
2507
                                session_id = $sessionId";
2508
                    Database::query($sql);
2509
2510
                    $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2511
                            WHERE
2512
                                c_id = ".$existingCourse['c_id']." AND
2513
                                session_id = $sessionId";
2514
                    Database::query($sql);
2515
2516
                    Event::addEvent(
2517
                        LOG_SESSION_DELETE_COURSE,
2518
                        LOG_COURSE_ID,
2519
                        $existingCourse['c_id'],
2520
                        api_get_utc_datetime(),
2521
                        api_get_user_id(),
2522
                        $existingCourse['c_id'],
2523
                        $sessionId
2524
                    );
2525
2526
                    CourseManager::remove_course_ranking(
2527
                        $existingCourse['c_id'],
2528
                        $sessionId
2529
                    );
2530
                    $nbr_courses--;
2531
                }
2532
            }
2533
        }
2534
2535
        // Pass through the courses list we want to add to the session
2536
        foreach ($courseList as $courseId) {
2537
            $courseInfo = api_get_course_info_by_id($courseId);
2538
2539
            // If course doesn't exists continue!
2540
            if (empty($courseInfo)) {
2541
                continue;
2542
            }
2543
2544
            $exists = false;
2545
            // check if the course we want to add is already subscribed
2546
            foreach ($existingCourses as $existingCourse) {
2547
                if ($courseId == $existingCourse['c_id']) {
2548
                    $exists = true;
2549
                }
2550
            }
2551
2552
            if (!$exists) {
2553
                // Copy gradebook categories and links (from base course)
2554
                // to the new course session
2555
                if ($copyEvaluation) {
2556
                    $cats = Category::load(null, null, $courseInfo['code']);
2557
                    if (!empty($cats)) {
2558
                        $sessionCategory = Category:: load(
2559
                            null,
2560
                            null,
2561
                            $courseInfo['code'],
2562
                            null,
2563
                            null,
2564
                            $sessionId,
2565
                            false
2566
                        );
2567
2568
                        // @todo remove commented code
2569
                        if (empty($sessionCategory)) {
2570
                            // There is no category for this course+session, so create one
2571
                            $cat = new Category();
2572
                            $sessionName = api_get_session_name($sessionId);
2573
                            $cat->set_name($courseInfo['code'].' - '.get_lang('Session').' '.$sessionName);
2574
                            $cat->set_session_id($sessionId);
2575
                            $cat->set_course_code($courseInfo['code']);
2576
                            $cat->set_description(null);
2577
                            //$cat->set_user_id($stud_id);
2578
                            $cat->set_parent_id(0);
2579
                            $cat->set_weight(100);
2580
                            $cat->set_visible(0);
2581
                            $cat->set_certificate_min_score(75);
2582
                            $cat->add();
2583
                            $sessionGradeBookCategoryId = $cat->get_id();
2584
                        } else {
2585
                            if (!empty($sessionCategory[0])) {
2586
                                $sessionGradeBookCategoryId = $sessionCategory[0]->get_id();
2587
                            }
2588
                        }
2589
2590
                        $categoryIdList = [];
2591
                        /** @var Category $cat */
2592
                        foreach ($cats as $cat) {
2593
                            $categoryIdList[$cat->get_id()] = $cat->get_id();
2594
                        }
2595
2596
                        $newCategoryIdList = [];
2597
                        foreach ($cats as $cat) {
2598
                            $links = $cat->get_links(
2599
                                null,
2600
                                false,
2601
                                $courseInfo['code'],
2602
                                0
2603
                            );
2604
2605
                            //$cat->set_session_id($sessionId);
2606
                            //$oldCategoryId = $cat->get_id();
2607
                            //$newId = $cat->add();
2608
                            //$newCategoryIdList[$oldCategoryId] = $newId;
2609
                            //$parentId = $cat->get_parent_id();
2610
2611
                            /*if (!empty($parentId)) {
2612
                                $newParentId = $newCategoryIdList[$parentId];
2613
                                $cat->set_parent_id($newParentId);
2614
                                $cat->save();
2615
                            }*/
2616
2617
                            if (!empty($links)) {
2618
                                /** @var AbstractLink $link */
2619
                                foreach ($links as $link) {
2620
                                    //$newCategoryId = $newCategoryIdList[$link->get_category_id()];
2621
                                    $link->set_category_id(
2622
                                        $sessionGradeBookCategoryId
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sessionGradeBookCategoryId does not seem to be defined for all execution paths leading up to this point.
Loading history...
2623
                                    );
2624
                                    $link->add();
2625
                                }
2626
                            }
2627
2628
                            $evaluationList = $cat->get_evaluations(
2629
                                null,
2630
                                false,
2631
                                $courseInfo['code'],
2632
                                0
2633
                            );
2634
2635
                            if (!empty($evaluationList)) {
2636
                                /** @var Evaluation $evaluation */
2637
                                foreach ($evaluationList as $evaluation) {
2638
                                    //$evaluationId = $newCategoryIdList[$evaluation->get_category_id()];
2639
                                    $evaluation->set_category_id(
2640
                                        $sessionGradeBookCategoryId
2641
                                    );
2642
                                    $evaluation->add();
2643
                                }
2644
                            }
2645
                        }
2646
2647
                        // Create
2648
                        DocumentManager::generateDefaultCertificate(
2649
                            $courseInfo,
2650
                            true,
2651
                            $sessionId
2652
                        );
2653
                    }
2654
                }
2655
2656
                // If the course isn't subscribed yet
2657
                $sql = "INSERT INTO $tbl_session_rel_course (session_id, c_id, nbr_users, position)
2658
                        VALUES ($sessionId, $courseId, 0, 0)";
2659
                Database::query($sql);
2660
2661
                Event::addEvent(
2662
                    LOG_SESSION_ADD_COURSE,
2663
                    LOG_COURSE_ID,
2664
                    $courseId,
2665
                    api_get_utc_datetime(),
2666
                    api_get_user_id(),
2667
                    $courseId,
2668
                    $sessionId
2669
                );
2670
2671
                // We add the current course in the existing courses array,
2672
                // to avoid adding another time the current course
2673
                $existingCourses[] = ['c_id' => $courseId];
2674
                $nbr_courses++;
2675
2676
                // subscribe all the users from the session to this course inside the session
2677
                $nbr_users = 0;
2678
                foreach ($user_list as $enreg_user) {
2679
                    $enreg_user_id = intval($enreg_user['user_id']);
2680
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id)
2681
                            VALUES ($sessionId, $courseId, $enreg_user_id)";
2682
                    $result = Database::query($sql);
2683
2684
                    Event::addEvent(
2685
                        LOG_SESSION_ADD_USER_COURSE,
2686
                        LOG_USER_ID,
2687
                        $enreg_user_id,
2688
                        api_get_utc_datetime(),
2689
                        api_get_user_id(),
2690
                        $courseId,
2691
                        $sessionId
2692
                    );
2693
2694
                    if (Database::affected_rows($result)) {
2695
                        $nbr_users++;
2696
                    }
2697
                }
2698
                $sql = "UPDATE $tbl_session_rel_course
2699
                        SET nbr_users = $nbr_users
2700
                        WHERE session_id = $sessionId AND c_id = $courseId";
2701
                Database::query($sql);
2702
            }
2703
        }
2704
2705
        $sql = "UPDATE $tbl_session
2706
                SET nbr_courses = $nbr_courses
2707
                WHERE id = $sessionId";
2708
        Database::query($sql);
2709
    }
2710
2711
    /**
2712
     * Unsubscribe course from a session.
2713
     *
2714
     * @param int $session_id
2715
     * @param int $course_id
2716
     *
2717
     * @return bool True in case of success, false otherwise
2718
     */
2719
    public static function unsubscribe_course_from_session($session_id, $course_id)
2720
    {
2721
        $session_id = (int) $session_id;
2722
        $course_id = (int) $course_id;
2723
2724
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2725
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2726
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2727
2728
        // Get course code
2729
        $course_code = CourseManager::get_course_code_from_course_id($course_id);
2730
        $course_id = intval($course_id);
2731
2732
        if (empty($course_code)) {
2733
            return false;
2734
        }
2735
2736
        // Unsubscribe course
2737
        $sql = "DELETE FROM $tbl_session_rel_course
2738
                WHERE c_id = $course_id AND session_id = $session_id";
2739
        $result = Database::query($sql);
2740
        $nb_affected = Database::affected_rows($result);
2741
2742
        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2743
                WHERE c_id = $course_id AND session_id = $session_id";
2744
        Database::query($sql);
2745
2746
        Event::addEvent(
2747
            LOG_SESSION_DELETE_COURSE,
2748
            LOG_COURSE_ID,
2749
            $course_id,
2750
            api_get_utc_datetime(),
2751
            api_get_user_id(),
2752
            $course_id,
2753
            $session_id
2754
        );
2755
2756
        if ($nb_affected > 0) {
2757
            // Update number of courses in the session
2758
            $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses - $nb_affected
2759
                    WHERE id = $session_id";
2760
            Database::query($sql);
2761
2762
            return true;
2763
        } else {
2764
            return false;
2765
        }
2766
    }
2767
2768
    /**
2769
     * Creates a new extra field for a given session.
2770
     *
2771
     * @param string $variable    Field's internal variable name
2772
     * @param int    $fieldType   Field's type
2773
     * @param string $displayText Field's language var name
2774
     * @param string $default     Field's default value
2775
     *
2776
     * @return int new extra field id
2777
     */
2778
    public static function create_session_extra_field(
2779
        $variable,
2780
        $fieldType,
2781
        $displayText,
2782
        $default = ''
2783
    ) {
2784
        $extraField = new ExtraFieldModel('session');
2785
        $params = [
2786
            'variable' => $variable,
2787
            'field_type' => $fieldType,
2788
            'display_text' => $displayText,
2789
            'default_value' => $default,
2790
        ];
2791
2792
        return $extraField->save($params);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $extraField->save($params) also could return the type boolean which is incompatible with the documented return type integer.
Loading history...
2793
    }
2794
2795
    /**
2796
     * Update an extra field value for a given session.
2797
     *
2798
     * @param int    $sessionId Session ID
2799
     * @param string $variable  Field variable name
2800
     * @param string $value     Optional. Default field value
2801
     *
2802
     * @return bool|int An integer when register a new extra field. And boolean when update the extrafield
2803
     */
2804
    public static function update_session_extra_field_value($sessionId, $variable, $value = '')
2805
    {
2806
        $extraFieldValue = new ExtraFieldValue('session');
2807
        $params = [
2808
            'item_id' => $sessionId,
2809
            'variable' => $variable,
2810
            'value' => $value,
2811
        ];
2812
2813
        return $extraFieldValue->save($params);
2814
    }
2815
2816
    /**
2817
     * Checks the relationship between a session and a course.
2818
     *
2819
     * @param int $session_id
2820
     * @param int $courseId
2821
     *
2822
     * @return bool returns TRUE if the session and the course are related, FALSE otherwise
2823
     * */
2824
    public static function relation_session_course_exist($session_id, $courseId)
2825
    {
2826
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2827
        $return_value = false;
2828
        $sql = "SELECT c_id FROM $tbl_session_course
2829
                WHERE
2830
                  session_id = ".intval($session_id)." AND
2831
                  c_id = ".intval($courseId);
2832
        $result = Database::query($sql);
2833
        $num = Database::num_rows($result);
2834
        if ($num > 0) {
2835
            $return_value = true;
2836
        }
2837
2838
        return $return_value;
2839
    }
2840
2841
    /**
2842
     * Get the session information by name.
2843
     *
2844
     * @param string $name
2845
     *
2846
     * @return mixed false if the session does not exist, array if the session exist
2847
     * */
2848
    public static function get_session_by_name($name)
2849
    {
2850
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2851
        $name = Database::escape_string(trim($name));
2852
        if (empty($name)) {
2853
            return false;
2854
        }
2855
2856
        $sql = 'SELECT *
2857
		        FROM '.$tbl_session.'
2858
		        WHERE name = "'.$name.'"';
2859
        $result = Database::query($sql);
2860
        $num = Database::num_rows($result);
2861
        if ($num > 0) {
2862
            return Database::fetch_array($result);
2863
        } else {
2864
            return false;
2865
        }
2866
    }
2867
2868
    /**
2869
     * Create a session category.
2870
     *
2871
     * @author Jhon Hinojosa <[email protected]>, from existing code
2872
     *
2873
     * @param string        name
2874
     * @param int        year_start
2875
     * @param int        month_start
2876
     * @param int        day_start
2877
     * @param int        year_end
2878
     * @param int        month_end
2879
     * @param int        day_end
2880
     *
2881
     * @return int session ID
2882
     * */
2883
    public static function create_category_session(
2884
        $sname,
2885
        $syear_start,
2886
        $smonth_start,
2887
        $sday_start,
2888
        $syear_end,
2889
        $smonth_end,
2890
        $sday_end
2891
    ) {
2892
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2893
        $name = trim($sname);
2894
        $year_start = intval($syear_start);
2895
        $month_start = intval($smonth_start);
2896
        $day_start = intval($sday_start);
2897
        $year_end = intval($syear_end);
2898
        $month_end = intval($smonth_end);
2899
        $day_end = intval($sday_end);
2900
2901
        $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start);
2902
        $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end);
2903
2904
        if (empty($name)) {
2905
            $msg = get_lang('SessionCategoryNameIsRequired');
2906
2907
            return $msg;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $msg returns the type string which is incompatible with the documented return type integer.
Loading history...
2908
        } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
2909
            $msg = get_lang('InvalidStartDate');
2910
2911
            return $msg;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $msg returns the type string which is incompatible with the documented return type integer.
Loading history...
2912
        } elseif (!$month_end && !$day_end && !$year_end) {
2913
            $date_end = '';
2914
        } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
2915
            $msg = get_lang('InvalidEndDate');
2916
2917
            return $msg;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $msg returns the type string which is incompatible with the documented return type integer.
Loading history...
2918
        } elseif ($date_start >= $date_end) {
2919
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
2920
2921
            return $msg;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $msg returns the type string which is incompatible with the documented return type integer.
Loading history...
2922
        }
2923
2924
        $access_url_id = api_get_current_access_url_id();
2925
        $params = [
2926
            'name' => $name,
2927
            'date_start' => $date_start,
2928
            'access_url_id' => $access_url_id,
2929
        ];
2930
2931
        if (!empty($date_end)) {
2932
            $params['date_end'] = $date_end;
2933
        }
2934
2935
        $id = Database::insert($tbl_session_category, $params);
2936
2937
        // Add event to system log
2938
        $user_id = api_get_user_id();
2939
        Event::addEvent(
2940
            LOG_SESSION_CATEGORY_CREATE,
2941
            LOG_SESSION_CATEGORY_ID,
2942
            $id,
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type false; however, parameter $event_value of Event::addEvent() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2942
            /** @scrutinizer ignore-type */ $id,
Loading history...
2943
            api_get_utc_datetime(),
2944
            $user_id
2945
        );
2946
2947
        return $id;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $id could also return false which is incompatible with the documented return type integer. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
2948
    }
2949
2950
    /**
2951
     * Edit a sessions category.
2952
     *
2953
     * @author Jhon Hinojosa <[email protected]>,from existing code
2954
     *
2955
     * @param int        id
2956
     * @param string        name
2957
     * @param int        year_start
2958
     * @param int        month_start
2959
     * @param int        day_start
2960
     * @param int        year_end
2961
     * @param int        month_end
2962
     * @param int        day_end
2963
     *
2964
     * @return bool
2965
     *              The parameter id is a primary key
2966
     * */
2967
    public static function edit_category_session(
2968
        $id,
2969
        $sname,
2970
        $syear_start,
2971
        $smonth_start,
2972
        $sday_start,
2973
        $syear_end,
2974
        $smonth_end,
2975
        $sday_end
2976
    ) {
2977
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2978
        $name = trim($sname);
2979
        $year_start = intval($syear_start);
2980
        $month_start = intval($smonth_start);
2981
        $day_start = intval($sday_start);
2982
        $year_end = intval($syear_end);
2983
        $month_end = intval($smonth_end);
2984
        $day_end = intval($sday_end);
2985
        $id = intval($id);
2986
        $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start);
2987
        $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end);
2988
2989
        if (empty($name)) {
2990
            $msg = get_lang('SessionCategoryNameIsRequired');
2991
2992
            return $msg;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $msg returns the type string which is incompatible with the documented return type boolean.
Loading history...
2993
        } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
2994
            $msg = get_lang('InvalidStartDate');
2995
2996
            return $msg;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $msg returns the type string which is incompatible with the documented return type boolean.
Loading history...
2997
        } elseif (!$month_end && !$day_end && !$year_end) {
2998
            $date_end = null;
2999
        } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
3000
            $msg = get_lang('InvalidEndDate');
3001
3002
            return $msg;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $msg returns the type string which is incompatible with the documented return type boolean.
Loading history...
3003
        } elseif ($date_start >= $date_end) {
3004
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
3005
3006
            return $msg;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $msg returns the type string which is incompatible with the documented return type boolean.
Loading history...
3007
        }
3008
        if ($date_end != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $date_end of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
3009
            $sql = "UPDATE $tbl_session_category
3010
                    SET
3011
                        name = '".Database::escape_string($name)."',
3012
                        date_start = '$date_start' ,
3013
                        date_end = '$date_end'
3014
                    WHERE id= $id";
3015
        } else {
3016
            $sql = "UPDATE $tbl_session_category SET
3017
                        name = '".Database::escape_string($name)."',
3018
                        date_start = '$date_start',
3019
                        date_end = NULL
3020
                    WHERE id= $id";
3021
        }
3022
        $result = Database::query($sql);
3023
3024
        return $result ? true : false;
3025
    }
3026
3027
    /**
3028
     * Delete sessions categories.
3029
     *
3030
     * @author Jhon Hinojosa <[email protected]>, from existing code
3031
     *
3032
     * @param    array    id_checked
3033
     * @param    bool    include delete session
3034
     * @param    bool    optional, true if the function is called by a webservice, false otherwise
3035
     *
3036
     * @return bool Nothing, or false on error
3037
     *              The parameters is a array to delete sessions
3038
     * */
3039
    public static function delete_session_category($id_checked, $delete_session = false, $from_ws = false)
3040
    {
3041
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3042
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3043
        if (is_array($id_checked)) {
3044
            $id_checked = Database::escape_string(implode(',', $id_checked));
3045
        } else {
3046
            $id_checked = intval($id_checked);
3047
        }
3048
3049
        //Setting session_category_id to 0
3050
        $sql = "UPDATE $tbl_session SET session_category_id = NULL
3051
                WHERE session_category_id IN (".$id_checked.")";
3052
        Database::query($sql);
3053
3054
        $sql = "SELECT id FROM $tbl_session WHERE session_category_id IN (".$id_checked.")";
3055
        $result = Database::query($sql);
3056
        while ($rows = Database::fetch_array($result)) {
3057
            $session_id = $rows['id'];
3058
            if ($delete_session) {
3059
                if ($from_ws) {
3060
                    self::delete($session_id, true);
3061
                } else {
3062
                    self::delete($session_id);
3063
                }
3064
            }
3065
        }
3066
        $sql = "DELETE FROM $tbl_session_category WHERE id IN (".$id_checked.")";
3067
        Database::query($sql);
3068
3069
        // Add event to system log
3070
        $user_id = api_get_user_id();
3071
        Event::addEvent(
3072
            LOG_SESSION_CATEGORY_DELETE,
3073
            LOG_SESSION_CATEGORY_ID,
3074
            $id_checked,
3075
            api_get_utc_datetime(),
3076
            $user_id
3077
        );
3078
3079
        return true;
3080
    }
3081
3082
    /**
3083
     * Get a list of sessions of which the given conditions match with an = 'cond'.
3084
     *
3085
     * @param array $conditions a list of condition example :
3086
     *                          array('status' => STUDENT) or
3087
     *                          array('s.name' => array('operator' => 'LIKE', value = '%$needle%'))
3088
     * @param array $order_by   a list of fields on which sort
3089
     *
3090
     * @return array an array with all sessions of the platform
3091
     *
3092
     * @todo   optional course code parameter, optional sorting parameters...
3093
     */
3094
    public static function get_sessions_list($conditions = [], $order_by = [], $from = null, $to = null)
3095
    {
3096
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3097
        $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3098
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
3099
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3100
        $session_course_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3101
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
3102
        $access_url_id = api_get_current_access_url_id();
3103
        $return_array = [];
3104
3105
        $sql_query = " SELECT
3106
                    DISTINCT(s.id),
3107
                    s.name,
3108
                    s.nbr_courses,
3109
                    s.access_start_date,
3110
                    s.access_end_date,
3111
                    u.firstname,
3112
                    u.lastname,
3113
                    sc.name as category_name,
3114
                    s.promotion_id
3115
				FROM $session_table s
3116
				INNER JOIN $user_table u ON s.id_coach = u.user_id
3117
				INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
3118
				LEFT JOIN  $session_category_table sc ON s.session_category_id = sc.id
3119
				LEFT JOIN $session_course_table sco ON (sco.session_id = s.id)
3120
				INNER JOIN $course_table c ON sco.c_id = c.id
3121
				WHERE ar.access_url_id = $access_url_id ";
3122
3123
        $availableFields = [
3124
            's.id',
3125
            's.name',
3126
            'c.id',
3127
        ];
3128
3129
        $availableOperator = [
3130
            'like',
3131
            '>=',
3132
            '<=',
3133
            '=',
3134
        ];
3135
3136
        if (count($conditions) > 0) {
3137
            foreach ($conditions as $field => $options) {
3138
                $operator = strtolower($options['operator']);
3139
                $value = Database::escape_string($options['value']);
3140
                $sql_query .= ' AND ';
3141
                if (in_array($field, $availableFields) && in_array($operator, $availableOperator)) {
3142
                    $sql_query .= $field." $operator '".$value."'";
3143
                }
3144
            }
3145
        }
3146
3147
        $orderAvailableList = ['name'];
3148
        if (count($order_by) > 0) {
3149
            $order = null;
3150
            $direction = null;
3151
            if (isset($order_by[0]) && in_array($order_by[0], $orderAvailableList)) {
3152
                $order = $order_by[0];
3153
            }
3154
            if (isset($order_by[1]) && in_array(strtolower($order_by[1]), ['desc', 'asc'])) {
3155
                $direction = $order_by[1];
3156
            }
3157
3158
            if (!empty($order)) {
3159
                $sql_query .= " ORDER BY $order $direction ";
3160
            }
3161
        }
3162
3163
        if (!is_null($from) && !is_null($to)) {
3164
            $to = intval($to);
3165
            $from = intval($from);
3166
            $sql_query .= "LIMIT $from, $to";
3167
        }
3168
3169
        $sql_result = Database::query($sql_query);
3170
        if (Database::num_rows($sql_result) > 0) {
3171
            while ($result = Database::fetch_array($sql_result)) {
3172
                $return_array[$result['id']] = $result;
3173
            }
3174
        }
3175
3176
        return $return_array;
3177
    }
3178
3179
    /**
3180
     * Get the session category information by id.
3181
     *
3182
     * @param string session category ID
3183
     *
3184
     * @return mixed false if the session category does not exist, array if the session category exists
3185
     */
3186
    public static function get_session_category($id)
3187
    {
3188
        $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3189
        $id = intval($id);
3190
        $sql = "SELECT id, name, date_start, date_end
3191
                FROM $table
3192
                WHERE id= $id";
3193
        $result = Database::query($sql);
3194
        $num = Database::num_rows($result);
3195
        if ($num > 0) {
3196
            return Database::fetch_array($result);
3197
        } else {
3198
            return false;
3199
        }
3200
    }
3201
3202
    /**
3203
     * Get the session image.
3204
     *
3205
     * @return image path
3206
     */
3207
    public static function getSessionImage($id)
3208
    {
3209
        $extraFieldValuesTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
3210
        $sql = "SELECT value  FROM extra_field_values WHERE field_id = 16 AND item_id = ".intval($id);
3211
        $result = Database::query($sql);
3212
        if (Database::num_rows($result) > 0) {
3213
            while ($row = Database::fetch_array($result, 'ASSOC')) {
3214
                $sessionImage = $row['value'];
3215
                $sessionImage = api_get_path(WEB_UPLOAD_PATH).$sessionImage;
3216
            }
3217
3218
            return $sessionImage;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sessionImage does not seem to be defined for all execution paths leading up to this point.
Loading history...
3219
        } else {
3220
            $sessionImage = api_get_path(WEB_IMG_PATH)."session_default.png";
3221
3222
            return $sessionImage;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $sessionImage returns the type string which is incompatible with the documented return type image.
Loading history...
3223
        }
3224
    }
3225
3226
    /**
3227
     * Get Hot Sessions (limit 8).
3228
     *
3229
     * @return array with sessions
3230
     */
3231
    public static function getHotSessions()
3232
    {
3233
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3234
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3235
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
3236
        $sql = "SELECT 
3237
                s.id,
3238
                s.name,
3239
                s.id_coach,
3240
                u.firstname,
3241
                u.lastname,
3242
                s.session_category_id,
3243
                c.name as category_name,
3244
                s.description,
3245
                (SELECT COUNT(*) FROM session_rel_user WHERE session_id = s.id) as users,
3246
				(SELECT COUNT(*) FROM c_lp WHERE session_id = s.id) as lessons,
3247
                (SELECT value FROM extra_field_values WHERE field_id = 16 AND item_id = s.id) as image
3248
                FROM $tbl_session s
3249
                LEFT JOIN $tbl_session_category c
3250
                    ON s.session_category_id = c.id
3251
                INNER JOIN $tbl_users u
3252
                    ON s.id_coach = u.id
3253
                ORDER BY 9 DESC
3254
                LIMIT 8";
3255
        $result = Database::query($sql);
3256
3257
        $plugin = BuyCoursesPlugin::create();
3258
        $checker = $plugin->isEnabled();
3259
        $sessions = [];
3260
        if (Database::num_rows($result) > 0) {
3261
            while ($row = Database::fetch_array($result, 'ASSOC')) {
3262
                if ($checker) {
3263
                    $row['on_sale'] = $plugin->getItemByProduct(
3264
                        $row['id'],
3265
                        BuyCoursesPlugin::PRODUCT_TYPE_SESSION
3266
                    );
3267
                }
3268
                $sessions[] = $row;
3269
            }
3270
3271
            return $sessions;
3272
        } else {
3273
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
3274
        }
3275
    }
3276
3277
    /**
3278
     * Get all session categories (filter by access_url_id).
3279
     *
3280
     * @return mixed false if the session category does not exist, array if the session category exists
3281
     */
3282
    public static function get_all_session_category()
3283
    {
3284
        $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3285
        $id = api_get_current_access_url_id();
3286
        $sql = 'SELECT * FROM '.$table.'
3287
                WHERE access_url_id = '.$id.'
3288
                ORDER BY name ASC';
3289
        $result = Database::query($sql);
3290
        if (Database::num_rows($result) > 0) {
3291
            $data = Database::store_result($result, 'ASSOC');
3292
3293
            return $data;
3294
        } else {
3295
            return false;
3296
        }
3297
    }
3298
3299
    /**
3300
     * Assign a coach to course in session with status = 2.
3301
     *
3302
     * @param int  $userId
3303
     * @param int  $sessionId
3304
     * @param int  $courseId
3305
     * @param bool $noCoach   optional, if is true the user don't be a coach now,
3306
     *                        otherwise it'll assign a coach
3307
     *
3308
     * @return bool true if there are affected rows, otherwise false
3309
     */
3310
    public static function set_coach_to_course_session(
3311
        $userId,
3312
        $sessionId = 0,
3313
        $courseId = 0,
3314
        $noCoach = false
3315
    ) {
3316
        // Definition of variables
3317
        $userId = intval($userId);
3318
3319
        $sessionId = !empty($sessionId) ? intval($sessionId) : api_get_session_id();
3320
        $courseId = !empty($courseId) ? intval($courseId) : api_get_course_id();
3321
3322
        if (empty($sessionId) || empty($courseId) || empty($userId)) {
3323
            return false;
3324
        }
3325
3326
        // Table definition
3327
        $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3328
        $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3329
        $tblUser = Database::get_main_table(TABLE_MAIN_USER);
3330
3331
        // check if user is a teacher
3332
        $sql = "SELECT * FROM $tblUser
3333
                WHERE status = 1 AND user_id = $userId";
3334
3335
        $rsCheckUser = Database::query($sql);
3336
3337
        if (Database::num_rows($rsCheckUser) <= 0) {
3338
            return false;
3339
        }
3340
3341
        if ($noCoach) {
3342
            // check if user_id exists in session_rel_user (if the user is
3343
            // subscribed to the session in any manner)
3344
            $sql = "SELECT user_id FROM $tblSessionRelUser
3345
                    WHERE
3346
                        session_id = $sessionId AND
3347
                        user_id = $userId";
3348
            $res = Database::query($sql);
3349
3350
            if (Database::num_rows($res) > 0) {
3351
                // The user is already subscribed to the session. Change the
3352
                // record so the user is NOT a coach for this course anymore
3353
                // and then exit
3354
                $sql = "UPDATE $tblSessionRelCourseRelUser
3355
                        SET status = 0
3356
                        WHERE
3357
                            session_id = $sessionId AND
3358
                            c_id = $courseId AND
3359
                            user_id = $userId ";
3360
                $result = Database::query($sql);
3361
3362
                return Database::affected_rows($result) > 0;
3363
            }
3364
3365
            // The user is not subscribed to the session, so make sure
3366
            // he isn't subscribed to a course in this session either
3367
            // and then exit
3368
            $sql = "DELETE FROM $tblSessionRelCourseRelUser
3369
                    WHERE
3370
                        session_id = $sessionId AND
3371
                        c_id = $courseId AND
3372
                        user_id = $userId ";
3373
            $result = Database::query($sql);
3374
3375
            return Database::affected_rows($result) > 0;
3376
        }
3377
3378
        // Assign user as a coach to course
3379
        // First check if the user is registered to the course
3380
        $sql = "SELECT user_id FROM $tblSessionRelCourseRelUser
3381
                WHERE
3382
                    session_id = $sessionId AND
3383
                    c_id = $courseId AND
3384
                    user_id = $userId";
3385
        $rs_check = Database::query($sql);
3386
3387
        // Then update or insert.
3388
        if (Database::num_rows($rs_check) > 0) {
3389
            $sql = "UPDATE $tblSessionRelCourseRelUser SET status = 2
3390
                    WHERE
3391
                        session_id = $sessionId AND
3392
                        c_id = $courseId AND
3393
                        user_id = $userId ";
3394
            $result = Database::query($sql);
3395
3396
            return Database::affected_rows($result) > 0;
3397
        }
3398
3399
        $sql = "INSERT INTO $tblSessionRelCourseRelUser(session_id, c_id, user_id, status)
3400
                VALUES($sessionId, $courseId, $userId, 2)";
3401
        $result = Database::query($sql);
3402
3403
        return Database::affected_rows($result) > 0;
3404
    }
3405
3406
    /**
3407
     * @param int $sessionId
3408
     *
3409
     * @return bool
3410
     */
3411
    public static function removeAllDrhFromSession($sessionId)
3412
    {
3413
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3414
        $sessionId = (int) $sessionId;
3415
3416
        if (empty($sessionId)) {
3417
            return false;
3418
        }
3419
3420
        $sql = "DELETE FROM $tbl_session_rel_user
3421
                WHERE
3422
                    session_id = $sessionId AND                            
3423
                    relation_type =".SESSION_RELATION_TYPE_RRHH;
3424
        Database::query($sql);
3425
3426
        return true;
3427
    }
3428
3429
    /**
3430
     * Subscribes sessions to human resource manager (Dashboard feature).
3431
     *
3432
     * @param array $userInfo               Human Resource Manager info
3433
     * @param array $sessions_list          Sessions id
3434
     * @param bool  $sendEmail
3435
     * @param bool  $removeSessionsFromUser
3436
     *
3437
     * @return int
3438
     * */
3439
    public static function subscribeSessionsToDrh(
3440
        $userInfo,
3441
        $sessions_list,
3442
        $sendEmail = false,
3443
        $removeSessionsFromUser = true
3444
    ) {
3445
        // Database Table Definitions
3446
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3447
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3448
3449
        if (empty($userInfo)) {
3450
            return 0;
3451
        }
3452
3453
        $userId = $userInfo['user_id'];
3454
3455
        // Only subscribe DRH users.
3456
        $rolesAllowed = [
3457
            DRH,
3458
            SESSIONADMIN,
3459
            PLATFORM_ADMIN,
3460
            COURSE_TUTOR,
3461
        ];
3462
        $isAdmin = api_is_platform_admin_by_id($userInfo['user_id']);
3463
        if (!$isAdmin && !in_array($userInfo['status'], $rolesAllowed)) {
3464
            return 0;
3465
        }
3466
3467
        $affected_rows = 0;
3468
        // Deleting assigned sessions to hrm_id.
3469
        if ($removeSessionsFromUser) {
3470
            if (api_is_multiple_url_enabled()) {
3471
                $sql = "SELECT s.session_id
3472
                        FROM $tbl_session_rel_user s
3473
                        INNER JOIN $tbl_session_rel_access_url a 
3474
                        ON (a.session_id = s.session_id)
3475
                        WHERE
3476
                            s.user_id = $userId AND
3477
                            relation_type = ".SESSION_RELATION_TYPE_RRHH." AND
3478
                            access_url_id = ".api_get_current_access_url_id();
3479
            } else {
3480
                $sql = "SELECT s.session_id 
3481
                        FROM $tbl_session_rel_user s
3482
                        WHERE user_id = $userId AND relation_type=".SESSION_RELATION_TYPE_RRHH;
3483
            }
3484
            $result = Database::query($sql);
3485
3486
            if (Database::num_rows($result) > 0) {
3487
                while ($row = Database::fetch_array($result)) {
3488
                    $sql = "DELETE FROM $tbl_session_rel_user
3489
                            WHERE
3490
                                session_id = {$row['session_id']} AND
3491
                                user_id = $userId AND
3492
                                relation_type =".SESSION_RELATION_TYPE_RRHH;
3493
                    Database::query($sql);
3494
                }
3495
            }
3496
        }
3497
3498
        // Inserting new sessions list.
3499
        if (!empty($sessions_list) && is_array($sessions_list)) {
3500
            foreach ($sessions_list as $session_id) {
3501
                $session_id = intval($session_id);
3502
                $sql = "SELECT session_id
3503
                        FROM $tbl_session_rel_user
3504
                        WHERE
3505
                            session_id = $session_id AND
3506
                            user_id = $userId AND
3507
                            relation_type = '".SESSION_RELATION_TYPE_RRHH."'";
3508
                $result = Database::query($sql);
3509
                if (Database::num_rows($result) == 0) {
3510
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, relation_type, registered_at)
3511
                            VALUES (
3512
                                $session_id,
3513
                                $userId,
3514
                                '".SESSION_RELATION_TYPE_RRHH."',
3515
                                '".api_get_utc_datetime()."'
3516
                            )";
3517
                    Database::query($sql);
3518
                    $affected_rows++;
3519
                }
3520
            }
3521
        }
3522
3523
        return $affected_rows;
3524
    }
3525
3526
    /**
3527
     * @param int $sessionId
3528
     *
3529
     * @return array
3530
     */
3531
    public static function getDrhUsersInSession($sessionId)
3532
    {
3533
        return self::get_users_by_session($sessionId, SESSION_RELATION_TYPE_RRHH);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::get_users_b...ION_RELATION_TYPE_RRHH) also could return the type integer which is incompatible with the documented return type array.
Loading history...
3534
    }
3535
3536
    /**
3537
     * @param int $userId
3538
     * @param int $sessionId
3539
     *
3540
     * @return array
3541
     */
3542
    public static function getSessionFollowedByDrh($userId, $sessionId)
3543
    {
3544
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3545
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3546
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3547
3548
        $userId = intval($userId);
3549
        $sessionId = intval($sessionId);
3550
3551
        $select = " SELECT * ";
3552
        if (api_is_multiple_url_enabled()) {
3553
            $sql = " $select FROM $tbl_session s
3554
                    INNER JOIN $tbl_session_rel_user sru ON (sru.session_id = s.id)
3555
                    LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
3556
                    WHERE
3557
                        sru.user_id = '$userId' AND
3558
                        sru.session_id = '$sessionId' AND
3559
                        sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
3560
                        access_url_id = ".api_get_current_access_url_id()."
3561
                        ";
3562
        } else {
3563
            $sql = "$select FROM $tbl_session s
3564
                     INNER JOIN $tbl_session_rel_user sru
3565
                     ON
3566
                        sru.session_id = s.id AND
3567
                        sru.user_id = '$userId' AND
3568
                        sru.session_id = '$sessionId' AND
3569
                        sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
3570
                    ";
3571
        }
3572
3573
        $result = Database::query($sql);
3574
        if (Database::num_rows($result)) {
3575
            $row = Database::fetch_array($result, 'ASSOC');
3576
            $row['course_list'] = self::get_course_list_by_session_id($sessionId);
3577
3578
            return $row;
3579
        }
3580
3581
        return [];
3582
    }
3583
3584
    /**
3585
     * Get sessions followed by human resources manager.
3586
     *
3587
     * @param int    $userId
3588
     * @param int    $start
3589
     * @param int    $limit
3590
     * @param bool   $getCount
3591
     * @param bool   $getOnlySessionId
3592
     * @param bool   $getSql
3593
     * @param string $orderCondition
3594
     * @param string $keyword
3595
     * @param string $description
3596
     *
3597
     * @return array sessions
3598
     */
3599
    public static function get_sessions_followed_by_drh(
3600
        $userId,
3601
        $start = null,
3602
        $limit = null,
3603
        $getCount = false,
3604
        $getOnlySessionId = false,
3605
        $getSql = false,
3606
        $orderCondition = null,
3607
        $keyword = '',
3608
        $description = ''
3609
    ) {
3610
        return self::getSessionsFollowedByUser(
3611
            $userId,
3612
            DRH,
3613
            $start,
3614
            $limit,
3615
            $getCount,
3616
            $getOnlySessionId,
3617
            $getSql,
3618
            $orderCondition,
3619
            $keyword,
3620
            $description
3621
        );
3622
    }
3623
3624
    /**
3625
     * Get sessions followed by human resources manager.
3626
     *
3627
     * @param int    $userId
3628
     * @param int    $status           DRH Optional
3629
     * @param int    $start
3630
     * @param int    $limit
3631
     * @param bool   $getCount
3632
     * @param bool   $getOnlySessionId
3633
     * @param bool   $getSql
3634
     * @param string $orderCondition
3635
     * @param string $keyword
3636
     * @param string $description
3637
     *
3638
     * @return array sessions
3639
     */
3640
    public static function getSessionsFollowedByUser(
3641
        $userId,
3642
        $status = null,
3643
        $start = null,
3644
        $limit = null,
3645
        $getCount = false,
3646
        $getOnlySessionId = false,
3647
        $getSql = false,
3648
        $orderCondition = null,
3649
        $keyword = '',
3650
        $description = ''
3651
    ) {
3652
        // Database Table Definitions
3653
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3654
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3655
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3656
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3657
3658
        $userId = (int) $userId;
3659
3660
        $select = " SELECT DISTINCT * ";
3661
        if ($getCount) {
3662
            $select = " SELECT count(DISTINCT(s.id)) as count ";
3663
        }
3664
3665
        if ($getOnlySessionId) {
3666
            $select = " SELECT DISTINCT(s.id) ";
3667
        }
3668
3669
        $limitCondition = null;
3670
        if (!is_null($start) && !is_null($limit)) {
3671
            $limitCondition = " LIMIT ".intval($start).", ".intval($limit);
3672
        }
3673
3674
        if (empty($orderCondition)) {
3675
            $orderCondition = " ORDER BY s.name ";
3676
        }
3677
3678
        $whereConditions = null;
3679
        $sessionCourseConditions = null;
3680
        $sessionConditions = null;
3681
        $sessionQuery = '';
3682
        $courseSessionQuery = null;
3683
3684
        switch ($status) {
3685
            case DRH:
3686
                $sessionQuery = "SELECT sru.session_id
3687
                                 FROM
3688
                                 $tbl_session_rel_user sru
3689
                                 WHERE
3690
                                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
3691
                                    sru.user_id = $userId";
3692
                break;
3693
            case COURSEMANAGER:
3694
                $courseSessionQuery = "
3695
                    SELECT scu.session_id as id
3696
                    FROM $tbl_session_rel_course_rel_user scu
3697
                    WHERE (scu.status = 2 AND scu.user_id = $userId)";
3698
3699
                $whereConditions = " OR (s.id_coach = $userId) ";
3700
                break;
3701
            default:
3702
                $sessionQuery = "SELECT sru.session_id
3703
                                 FROM
3704
                                 $tbl_session_rel_user sru
3705
                                 WHERE
3706
                                    sru.user_id = $userId";
3707
                break;
3708
        }
3709
3710
        $keywordCondition = '';
3711
        if (!empty($keyword)) {
3712
            $keyword = Database::escape_string($keyword);
3713
            $keywordCondition = " AND (s.name LIKE '%$keyword%' ) ";
3714
3715
            if (!empty($description)) {
3716
                $description = Database::escape_string($description);
3717
                $keywordCondition = " AND (s.name LIKE '%$keyword%' OR s.description LIKE '%$description%' ) ";
3718
            }
3719
        }
3720
3721
        $whereConditions .= $keywordCondition;
3722
        $subQuery = $sessionQuery.$courseSessionQuery;
3723
3724
        $sql = " $select FROM $tbl_session s
3725
                INNER JOIN $tbl_session_rel_access_url a 
3726
                ON (s.id = a.session_id)
3727
                WHERE
3728
                    access_url_id = ".api_get_current_access_url_id()." AND
3729
                    s.id IN (
3730
                        $subQuery
3731
                    )
3732
                    $whereConditions
3733
                    $orderCondition
3734
                    $limitCondition";
3735
3736
        if ($getSql) {
3737
            return $sql;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $sql returns the type string which is incompatible with the documented return type array.
Loading history...
3738
        }
3739
        $result = Database::query($sql);
3740
3741
        if ($getCount) {
3742
            $row = Database::fetch_array($result);
3743
3744
            return $row['count'];
3745
        }
3746
3747
        $sessions = [];
3748
        if (Database::num_rows($result) > 0) {
3749
            $sysUploadPath = api_get_path(SYS_UPLOAD_PATH).'sessions/';
3750
            $webUploadPath = api_get_path(WEB_UPLOAD_PATH).'sessions/';
3751
            $imgPath = Display::return_icon(
3752
                'session_default_small.png',
3753
                null,
3754
                [],
3755
                ICON_SIZE_SMALL,
3756
                false,
3757
                true
3758
            );
3759
3760
            while ($row = Database::fetch_array($result)) {
3761
                if ($getOnlySessionId) {
3762
                    $sessions[$row['id']] = $row;
3763
                    continue;
3764
                }
3765
                $imageFilename = \ExtraField::FIELD_TYPE_FILE_IMAGE.'_'.$row['id'].'.png';
3766
                $row['image'] = is_file($sysUploadPath.$imageFilename) ? $webUploadPath.$imageFilename : $imgPath;
3767
3768
                if ($row['display_start_date'] == '0000-00-00 00:00:00' || $row['display_start_date'] == '0000-00-00') {
3769
                    $row['display_start_date'] = null;
3770
                }
3771
3772
                if ($row['display_end_date'] == '0000-00-00 00:00:00' || $row['display_end_date'] == '0000-00-00') {
3773
                    $row['display_end_date'] = null;
3774
                }
3775
3776
                if ($row['access_start_date'] == '0000-00-00 00:00:00' || $row['access_start_date'] == '0000-00-00') {
3777
                    $row['access_start_date'] = null;
3778
                }
3779
3780
                if ($row['access_end_date'] == '0000-00-00 00:00:00' || $row['access_end_date'] == '0000-00-00') {
3781
                    $row['access_end_date'] = null;
3782
                }
3783
3784
                if ($row['coach_access_start_date'] == '0000-00-00 00:00:00' ||
3785
                    $row['coach_access_start_date'] == '0000-00-00'
3786
                ) {
3787
                    $row['coach_access_start_date'] = null;
3788
                }
3789
3790
                if ($row['coach_access_end_date'] == '0000-00-00 00:00:00' ||
3791
                    $row['coach_access_end_date'] == '0000-00-00'
3792
                ) {
3793
                    $row['coach_access_end_date'] = null;
3794
                }
3795
3796
                $sessions[$row['id']] = $row;
3797
            }
3798
        }
3799
3800
        return $sessions;
3801
    }
3802
3803
    /**
3804
     * Gets the list (or the count) of courses by session filtered by access_url.
3805
     *
3806
     * @param int    $session_id  The session id
3807
     * @param string $course_name The course code
3808
     * @param string $orderBy     Field to order the data
3809
     * @param bool   $getCount    Optional. Count the session courses
3810
     *
3811
     * @return array|int List of courses. Whether $getCount is true, return the count
3812
     */
3813
    public static function get_course_list_by_session_id(
3814
        $session_id,
3815
        $course_name = '',
3816
        $orderBy = null,
3817
        $getCount = false
3818
    ) {
3819
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3820
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3821
        $session_id = intval($session_id);
3822
        $sqlSelect = "*, c.id, c.id as real_id";
3823
3824
        if ($getCount) {
3825
            $sqlSelect = "COUNT(1) as count";
3826
        }
3827
3828
        // select the courses
3829
        $sql = "SELECT $sqlSelect
3830
                FROM $tbl_course c
3831
                INNER JOIN $tbl_session_rel_course src
3832
                ON (c.id = src.c_id)
3833
		        WHERE src.session_id = '$session_id' ";
3834
3835
        if (!empty($course_name)) {
3836
            $course_name = Database::escape_string($course_name);
3837
            $sql .= " AND c.title LIKE '%$course_name%' ";
3838
        }
3839
3840
        if (!empty($orderBy)) {
3841
            $orderBy = Database::escape_string($orderBy);
3842
            $orderBy = " ORDER BY $orderBy";
3843
        } else {
3844
            if (self::orderCourseIsEnabled()) {
3845
                $orderBy .= " ORDER BY position ";
3846
            } else {
3847
                $orderBy .= " ORDER BY title ";
3848
            }
3849
        }
3850
3851
        $sql .= Database::escape_string($orderBy);
3852
        $result = Database::query($sql);
3853
        $num_rows = Database::num_rows($result);
3854
        $courses = [];
3855
        if ($num_rows > 0) {
3856
            if ($getCount) {
3857
                $count = Database::fetch_assoc($result);
3858
3859
                return intval($count['count']);
3860
            }
3861
3862
            while ($row = Database::fetch_array($result, 'ASSOC')) {
3863
                $courses[$row['real_id']] = $row;
3864
            }
3865
        }
3866
3867
        return $courses;
3868
    }
3869
3870
    /**
3871
     * Gets the list of courses by session filtered by access_url.
3872
     *
3873
     * @param $userId
3874
     * @param $sessionId
3875
     * @param null   $from
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $limit is correct as it would always require null to be passed?
Loading history...
Documentation Bug introduced by
Are you sure the doc-type for parameter $from is correct as it would always require null to be passed?
Loading history...
Documentation Bug introduced by
Are you sure the doc-type for parameter $direction is correct as it would always require null to be passed?
Loading history...
Documentation Bug introduced by
Are you sure the doc-type for parameter $column is correct as it would always require null to be passed?
Loading history...
3876
     * @param null   $limit
3877
     * @param null   $column
3878
     * @param null   $direction
3879
     * @param bool   $getCount
3880
     * @param string $keyword
3881
     *
3882
     * @return array
3883
     */
3884
    public static function getAllCoursesFollowedByUser(
3885
        $userId,
3886
        $sessionId,
3887
        $from = null,
3888
        $limit = null,
3889
        $column = null,
3890
        $direction = null,
3891
        $getCount = false,
3892
        $keyword = ''
3893
    ) {
3894
        if (empty($sessionId)) {
3895
            $sessionsSQL = self::get_sessions_followed_by_drh(
3896
                $userId,
3897
                null,
3898
                null,
3899
                null,
3900
                true,
3901
                true
3902
            );
3903
        } else {
3904
            $sessionsSQL = intval($sessionId);
3905
        }
3906
3907
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3908
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3909
3910
        if ($getCount) {
3911
            $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
3912
        } else {
3913
            $select = "SELECT DISTINCT c.* ";
3914
        }
3915
3916
        $keywordCondition = null;
3917
        if (!empty($keyword)) {
3918
            $keyword = Database::escape_string($keyword);
3919
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
3920
        }
3921
3922
        // Select the courses
3923
        $sql = "$select
3924
                FROM $tbl_course c
3925
                INNER JOIN $tbl_session_rel_course src
3926
                ON c.id = src.c_id
3927
		        WHERE
3928
		            src.session_id IN ($sessionsSQL)
3929
		            $keywordCondition
3930
		        ";
3931
        if ($getCount) {
3932
            $result = Database::query($sql);
3933
            $row = Database::fetch_array($result, 'ASSOC');
3934
3935
            return $row['count'];
3936
        }
3937
3938
        if (isset($from) && isset($limit)) {
3939
            $from = intval($from);
3940
            $limit = intval($limit);
3941
            $sql .= " LIMIT $from, $limit";
3942
        }
3943
3944
        $result = Database::query($sql);
3945
        $num_rows = Database::num_rows($result);
3946
        $courses = [];
3947
3948
        if ($num_rows > 0) {
3949
            while ($row = Database::fetch_array($result, 'ASSOC')) {
3950
                $courses[$row['id']] = $row;
3951
            }
3952
        }
3953
3954
        return $courses;
3955
    }
3956
3957
    /**
3958
     * Gets the list of courses by session filtered by access_url.
3959
     *
3960
     * @param int    $session_id
3961
     * @param string $course_name
3962
     *
3963
     * @return array list of courses
3964
     */
3965
    public static function get_course_list_by_session_id_like($session_id, $course_name = '')
3966
    {
3967
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3968
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3969
3970
        $session_id = intval($session_id);
3971
        $course_name = Database::escape_string($course_name);
3972
3973
        // select the courses
3974
        $sql = "SELECT c.id, c.title FROM $tbl_course c
3975
                INNER JOIN $tbl_session_rel_course src
3976
                ON c.id = src.c_id
3977
		        WHERE ";
3978
3979
        if (!empty($session_id)) {
3980
            $sql .= "src.session_id LIKE '$session_id' AND ";
3981
        }
3982
3983
        if (!empty($course_name)) {
3984
            $sql .= "UPPER(c.title) LIKE UPPER('%$course_name%') ";
3985
        }
3986
3987
        $sql .= "ORDER BY title;";
3988
        $result = Database::query($sql);
3989
        $num_rows = Database::num_rows($result);
3990
        $courses = [];
3991
        if ($num_rows > 0) {
3992
            while ($row = Database::fetch_array($result, 'ASSOC')) {
3993
                $courses[$row['id']] = $row;
3994
            }
3995
        }
3996
3997
        return $courses;
3998
    }
3999
4000
    /**
4001
     * Gets the count of courses by session filtered by access_url.
4002
     *
4003
     * @param int session id
4004
     * @param string $keyword
4005
     *
4006
     * @return array list of courses
4007
     */
4008
    public static function getCourseCountBySessionId($session_id, $keyword = '')
4009
    {
4010
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4011
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4012
        $session_id = intval($session_id);
4013
4014
        // select the courses
4015
        $sql = "SELECT COUNT(c.code) count
4016
                FROM $tbl_course c
4017
                INNER JOIN $tbl_session_rel_course src
4018
                ON c.id = src.c_id
4019
		        WHERE src.session_id = '$session_id' ";
4020
4021
        $keywordCondition = null;
4022
        if (!empty($keyword)) {
4023
            $keyword = Database::escape_string($keyword);
4024
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
4025
        }
4026
        $sql .= $keywordCondition;
4027
4028
        $result = Database::query($sql);
4029
        $num_rows = Database::num_rows($result);
4030
        if ($num_rows > 0) {
4031
            $row = Database::fetch_array($result, 'ASSOC');
4032
4033
            return $row['count'];
4034
        }
4035
4036
        return null;
4037
    }
4038
4039
    /**
4040
     * Get the session id based on the original id and field name in the extra fields.
4041
     * Returns 0 if session was not found.
4042
     *
4043
     * @param string $value    Original session id
4044
     * @param string $variable Original field name
4045
     *
4046
     * @return int Session id
4047
     */
4048
    public static function getSessionIdFromOriginalId($value, $variable)
4049
    {
4050
        $extraFieldValue = new ExtraFieldValue('session');
4051
        $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
4052
            $variable,
4053
            $value
4054
        );
4055
4056
        if (!empty($result)) {
4057
            return $result['item_id'];
4058
        }
4059
4060
        return 0;
4061
    }
4062
4063
    /**
4064
     * Get users by session.
4065
     *
4066
     * @param int  $id       session id
4067
     * @param int  $status   filter by status coach = 2
4068
     * @param bool $getCount Optional. Allow get the number of rows from the result
4069
     * @param int  $urlId
4070
     *
4071
     * @return array|int A list with an user list. If $getCount is true then return a the count of registers
4072
     */
4073
    public static function get_users_by_session(
4074
        $id,
4075
        $status = null,
4076
        $getCount = false,
4077
        $urlId = 0
4078
    ) {
4079
        if (empty($id)) {
4080
            return [];
4081
        }
4082
        $id = intval($id);
4083
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
4084
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4085
        $table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
4086
4087
        $selectedField = '
4088
            u.user_id, u.lastname, u.firstname, u.username, su.relation_type, au.access_url_id,
4089
            su.moved_to, su.moved_status, su.moved_at
4090
        ';
4091
4092
        if ($getCount) {
4093
            $selectedField = 'count(1) AS count';
4094
        }
4095
4096
        $sql = "SELECT $selectedField
4097
                FROM $tbl_user u
4098
                INNER JOIN $tbl_session_rel_user su
4099
                ON u.user_id = su.user_id AND
4100
                su.session_id = $id
4101
                LEFT OUTER JOIN $table_access_url_user au
4102
                ON (au.user_id = u.user_id)
4103
                ";
4104
4105
        $urlId = empty($urlId) ? api_get_current_access_url_id() : (int) $urlId;
4106
4107
        if ($status != '') {
4108
            $status = intval($status);
4109
            $sql .= " WHERE su.relation_type = $status AND (au.access_url_id = $urlId OR au.access_url_id is null)";
4110
        } else {
4111
            $sql .= " WHERE (au.access_url_id = $urlId OR au.access_url_id is null )";
4112
        }
4113
4114
        $sql .= " ORDER BY su.relation_type, ";
4115
        $sql .= api_sort_by_first_name() ? ' u.firstname, u.lastname' : '  u.lastname, u.firstname';
4116
4117
        $result = Database::query($sql);
4118
        if ($getCount) {
4119
            $count = Database::fetch_assoc($result);
4120
4121
            return $count['count'];
4122
        }
4123
4124
        $return = [];
4125
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4126
            $return[] = $row;
4127
        }
4128
4129
        return $return;
4130
    }
4131
4132
    /**
4133
     * The general coach (field: session.id_coach).
4134
     *
4135
     * @param int  $user_id         user id
4136
     * @param bool $asPlatformAdmin The user is platform admin, return everything
4137
     *
4138
     * @return array
4139
     */
4140
    public static function get_sessions_by_general_coach($user_id, $asPlatformAdmin = false)
4141
    {
4142
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4143
        $user_id = intval($user_id);
4144
4145
        // Session where we are general coach
4146
        $sql = "SELECT DISTINCT *
4147
                FROM $session_table";
4148
4149
        if (!$asPlatformAdmin) {
4150
            $sql .= " WHERE id_coach = $user_id";
4151
        }
4152
4153
        if (api_is_multiple_url_enabled()) {
4154
            $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4155
            $access_url_id = api_get_current_access_url_id();
4156
4157
            $sqlCoach = '';
4158
            if (!$asPlatformAdmin) {
4159
                $sqlCoach = " id_coach = $user_id AND ";
4160
            }
4161
4162
            if ($access_url_id != -1) {
4163
                $sql = 'SELECT DISTINCT session.*
4164
                    FROM '.$session_table.' session INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
4165
                    ON (session.id = session_rel_url.session_id)
4166
                    WHERE '.$sqlCoach.' access_url_id = '.$access_url_id;
4167
            }
4168
        }
4169
        $sql .= ' ORDER by name';
4170
        $result = Database::query($sql);
4171
4172
        return Database::store_result($result, 'ASSOC');
4173
    }
4174
4175
    /**
4176
     * @param int $user_id
4177
     *
4178
     * @return array
4179
     *
4180
     * @deprecated use get_sessions_by_general_coach()
4181
     */
4182
    public static function get_sessions_by_coach($user_id)
4183
    {
4184
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4185
4186
        return Database::select(
4187
            '*',
4188
            $session_table,
4189
            ['where' => ['id_coach = ?' => $user_id]]
4190
        );
4191
    }
4192
4193
    /**
4194
     * @param int $user_id
4195
     * @param int $courseId
4196
     * @param int $session_id
4197
     *
4198
     * @return array|bool
4199
     */
4200
    public static function get_user_status_in_course_session($user_id, $courseId, $session_id)
4201
    {
4202
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4203
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
4204
        $sql = "SELECT session_rcru.status
4205
                FROM $table session_rcru 
4206
                INNER JOIN $tbl_user user
4207
                ON (session_rcru.user_id = user.user_id)
4208
                WHERE                    
4209
                    session_rcru.session_id = '".intval($session_id)."' AND
4210
                    session_rcru.c_id ='".intval($courseId)."' AND
4211
                    user.user_id = ".intval($user_id);
4212
4213
        $result = Database::query($sql);
4214
        $status = false;
4215
        if (Database::num_rows($result)) {
4216
            $status = Database::fetch_row($result);
4217
            $status = $status['0'];
4218
        }
4219
4220
        return $status;
4221
    }
4222
4223
    /**
4224
     * Gets user status within a session.
4225
     *
4226
     * @param int $userId
4227
     * @param int $sessionId
4228
     *
4229
     * @return SessionRelUser
4230
     */
4231
    public static function getUserStatusInSession($userId, $sessionId)
4232
    {
4233
        $em = Database::getManager();
4234
        $subscriptions = $em
4235
            ->getRepository('ChamiloCoreBundle:SessionRelUser')
4236
            ->findBy(['session' => $sessionId, 'user' => $userId]);
4237
4238
        /** @var SessionRelUser $subscription */
4239
        $subscription = current($subscriptions);
4240
4241
        return $subscription;
4242
    }
4243
4244
    /**
4245
     * @param int $id
4246
     *
4247
     * @return array
4248
     */
4249
    public static function get_all_sessions_by_promotion($id)
4250
    {
4251
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
4252
4253
        return Database::select(
4254
            '*',
4255
            $table,
4256
            ['where' => ['promotion_id = ?' => $id]]
4257
        );
4258
    }
4259
4260
    /**
4261
     * @param int   $promotion_id
4262
     * @param array $list
4263
     */
4264
    public static function subscribe_sessions_to_promotion($promotion_id, $list)
4265
    {
4266
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
4267
        $params = [];
4268
        $params['promotion_id'] = 0;
4269
        Database::update(
4270
            $table,
4271
            $params,
4272
            ['promotion_id = ?' => $promotion_id]
4273
        );
4274
4275
        $params['promotion_id'] = $promotion_id;
4276
        if (!empty($list)) {
4277
            foreach ($list as $session_id) {
4278
                $session_id = intval($session_id);
4279
                Database::update($table, $params, ['id = ?' => $session_id]);
4280
            }
4281
        }
4282
    }
4283
4284
    /**
4285
     * Updates a session status.
4286
     *
4287
     * @param int session id
4288
     * @param int status
4289
     */
4290
    public static function set_session_status($session_id, $status)
4291
    {
4292
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
4293
        $params['visibility'] = $status;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
4294
        Database::update($t, $params, ['id = ?' => $session_id]);
4295
    }
4296
4297
    /**
4298
     * Copies a session with the same data to a new session.
4299
     * The new copy is not assigned to the same promotion. @see subscribe_sessions_to_promotions() for that.
4300
     *
4301
     * @param   int     Session ID
4302
     * @param   bool    Whether to copy the relationship with courses
4303
     * @param   bool    Whether to copy the relationship with users
4304
     * @param   bool    New courses will be created
4305
     * @param   bool    Whether to set exercises and learning paths in the new session to invisible by default
4306
     *
4307
     * @return int The new session ID on success, 0 otherwise
4308
     *
4309
     * @todo make sure the extra session fields are copied too
4310
     */
4311
    public static function copy(
4312
        $id,
4313
        $copy_courses = true,
4314
        $copy_users = true,
4315
        $create_new_courses = false,
4316
        $set_exercises_lp_invisible = false
4317
    ) {
4318
        $id = intval($id);
4319
        $s = self::fetch($id);
4320
        // Check all dates before copying
4321
        // Get timestamp for now in UTC - see http://php.net/manual/es/function.time.php#117251
4322
        $now = time() - date('Z');
4323
        // Timestamp in one month
4324
        $inOneMonth = $now + (30 * 24 * 3600);
4325
        $inOneMonth = api_get_local_time($inOneMonth);
4326
        if (api_strtotime($s['access_start_date']) < $now) {
4327
            $s['access_start_date'] = api_get_local_time($now);
4328
        }
4329
        if (api_strtotime($s['display_start_date']) < $now) {
4330
            $s['display_start_date'] = api_get_local_time($now);
4331
        }
4332
        if (api_strtotime($s['coach_access_start_date']) < $now) {
4333
            $s['coach_access_start_date'] = api_get_local_time($now);
4334
        }
4335
        if (api_strtotime($s['access_end_date']) < $now) {
4336
            $s['access_end_date'] = $inOneMonth;
4337
        }
4338
        if (api_strtotime($s['display_end_date']) < $now) {
4339
            $s['display_end_date'] = $inOneMonth;
4340
        }
4341
        if (api_strtotime($s['coach_access_end_date']) < $now) {
4342
            $s['coach_access_end_date'] = $inOneMonth;
4343
        }
4344
        // Now try to create the session
4345
        $sid = self::create_session(
4346
            $s['name'].' '.get_lang('CopyLabelSuffix'),
4347
            $s['access_start_date'],
4348
            $s['access_end_date'],
4349
            $s['display_start_date'],
4350
            $s['display_end_date'],
4351
            $s['coach_access_start_date'],
4352
            $s['coach_access_end_date'],
4353
            (int) $s['id_coach'],
4354
            $s['session_category_id'],
4355
            (int) $s['visibility'],
4356
            true
4357
        );
4358
4359
        if (!is_numeric($sid) || empty($sid)) {
4360
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
4361
        }
4362
4363
        if ($copy_courses) {
4364
            // Register courses from the original session to the new session
4365
            $courses = self::get_course_list_by_session_id($id);
4366
4367
            $short_courses = $new_short_courses = [];
4368
            if (is_array($courses) && count($courses) > 0) {
4369
                foreach ($courses as $course) {
4370
                    $short_courses[] = $course;
4371
                }
4372
            }
4373
4374
            $courses = null;
4375
            // We will copy the current courses of the session to new courses
4376
            if (!empty($short_courses)) {
4377
                if ($create_new_courses) {
4378
                    //Just in case
4379
                    if (function_exists('ini_set')) {
4380
                        api_set_memory_limit('256M');
4381
                        ini_set('max_execution_time', 0);
4382
                    }
4383
                    $params = [];
4384
                    $params['skip_lp_dates'] = true;
4385
4386
                    foreach ($short_courses as $course_data) {
4387
                        $course_info = CourseManager::copy_course_simple(
4388
                            $course_data['title'].' '.get_lang(
4389
                                'CopyLabelSuffix'
4390
                            ),
4391
                            $course_data['course_code'],
4392
                            $id,
4393
                            $sid,
4394
                            $params
4395
                        );
4396
4397
                        if ($course_info) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $course_info of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
4398
                            //By default new elements are invisible
4399
                            if ($set_exercises_lp_invisible) {
4400
                                $list = new LearnpathList('', $course_info['code'], $sid);
0 ignored issues
show
Bug introduced by
It seems like $sid can also be of type string; however, parameter $session_id of LearnpathList::__construct() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

4400
                                $list = new LearnpathList('', $course_info['code'], /** @scrutinizer ignore-type */ $sid);
Loading history...
4401
                                $flat_list = $list->get_flat_list();
4402
                                if (!empty($flat_list)) {
4403
                                    foreach ($flat_list as $lp_id => $data) {
4404
                                        api_item_property_update(
4405
                                            $course_info,
4406
                                            TOOL_LEARNPATH,
4407
                                            $lp_id,
4408
                                            'invisible',
4409
                                            api_get_user_id(),
4410
                                            0,
4411
                                            0,
4412
                                            0,
4413
                                            0,
4414
                                            $sid
0 ignored issues
show
Bug introduced by
It seems like $sid can also be of type string; however, parameter $session_id of api_item_property_update() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

4414
                                            /** @scrutinizer ignore-type */ $sid
Loading history...
4415
                                        );
4416
                                    }
4417
                                }
4418
                                $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
4419
                                $course_id = $course_info['real_id'];
4420
                                //@todo check this query
4421
                                $sql = "UPDATE $quiz_table SET active = 0
4422
                                        WHERE c_id = $course_id AND session_id = $sid";
4423
                                Database::query($sql);
4424
                            }
4425
                            $new_short_courses[] = $course_info['real_id'];
4426
                        }
4427
                    }
4428
                } else {
4429
                    foreach ($short_courses as $course_data) {
4430
                        $new_short_courses[] = $course_data['id'];
4431
                    }
4432
                }
4433
4434
                $short_courses = $new_short_courses;
4435
                self::add_courses_to_session($sid, $short_courses, true);
0 ignored issues
show
Bug introduced by
It seems like $sid can also be of type string; however, parameter $sessionId of SessionManager::add_courses_to_session() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

4435
                self::add_courses_to_session(/** @scrutinizer ignore-type */ $sid, $short_courses, true);
Loading history...
4436
                $short_courses = null;
4437
            }
4438
        }
4439
        if ($copy_users) {
4440
            // Register users from the original session to the new session
4441
            $users = self::get_users_by_session($id);
4442
            $short_users = [];
4443
            if (is_array($users) && count($users) > 0) {
4444
                foreach ($users as $user) {
4445
                    $short_users[] = $user['user_id'];
4446
                }
4447
            }
4448
            $users = null;
4449
            //Subscribing in read only mode
4450
            self::subscribe_users_to_session(
4451
                $sid,
0 ignored issues
show
Bug introduced by
It seems like $sid can also be of type string; however, parameter $id_session of SessionManager::subscribe_users_to_session() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

4451
                /** @scrutinizer ignore-type */ $sid,
Loading history...
4452
                $short_users,
4453
                SESSION_VISIBLE_READ_ONLY,
4454
                true
4455
            );
4456
            $short_users = null;
4457
        }
4458
4459
        return $sid;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $sid also could return the type string which is incompatible with the documented return type integer.
Loading history...
4460
    }
4461
4462
    /**
4463
     * @param int $user_id
4464
     * @param int $session_id
4465
     *
4466
     * @return bool
4467
     */
4468
    public static function user_is_general_coach($user_id, $session_id)
4469
    {
4470
        $session_id = intval($session_id);
4471
        $user_id = intval($user_id);
4472
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
4473
        $sql = "SELECT DISTINCT id
4474
	         	FROM $table
4475
	         	WHERE session.id_coach =  '".$user_id."' AND id = '$session_id'";
4476
        $result = Database::query($sql);
4477
        if ($result && Database::num_rows($result)) {
4478
            return true;
4479
        }
4480
4481
        return false;
4482
    }
4483
4484
    /**
4485
     * Get the number of sessions.
4486
     *
4487
     * @param  int ID of the URL we want to filter on (optional)
4488
     *
4489
     * @return int Number of sessions
4490
     */
4491
    public static function count_sessions($access_url_id = null)
4492
    {
4493
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4494
        $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4495
        $sql = "SELECT count(id) FROM $session_table s";
4496
        if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
4497
            $sql .= ", $access_url_rel_session_table u ".
4498
                " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
4499
        }
4500
        $res = Database::query($sql);
4501
        $row = Database::fetch_row($res);
4502
4503
        return $row[0];
4504
    }
4505
4506
    /**
4507
     * Protect a session to be edited.
4508
     *
4509
     * @param int  $id
4510
     * @param bool $checkSession
4511
     *
4512
     * @return mixed | bool true if pass the check, api_not_allowed otherwise
4513
     */
4514
    public static function protectSession($id, $checkSession = true)
4515
    {
4516
        if (self::allowToManageSessions()) {
4517
            if (api_is_platform_admin() && self::allowed($id)) {
4518
                return true;
4519
            }
4520
4521
            if ($checkSession) {
4522
                if (self::allowed($id)) {
4523
                    return true;
4524
                } else {
4525
                    api_not_allowed(true);
4526
                }
4527
            }
4528
        } else {
4529
            api_not_allowed(true);
4530
        }
4531
    }
4532
4533
    /**
4534
     * @return bool
4535
     */
4536
    public static function allowToManageSessions()
4537
    {
4538
        if (self::allowManageAllSessions()) {
4539
            return true;
4540
        }
4541
4542
        $setting = api_get_setting('allow_teachers_to_create_sessions');
4543
4544
        if (api_is_teacher() && $setting == 'true') {
4545
            return true;
4546
        }
4547
4548
        return false;
4549
    }
4550
4551
    /**
4552
     * @return bool
4553
     */
4554
    public static function allowOnlyMySessions()
4555
    {
4556
        if (self::allowToManageSessions() &&
4557
            !api_is_platform_admin() &&
4558
            api_is_teacher()
4559
        ) {
4560
            return true;
4561
        }
4562
4563
        return false;
4564
    }
4565
4566
    /**
4567
     * @return bool
4568
     */
4569
    public static function allowManageAllSessions()
4570
    {
4571
        if (api_is_platform_admin() || api_is_session_admin()) {
4572
            return true;
4573
        }
4574
4575
        return false;
4576
    }
4577
4578
    /**
4579
     * @param $id
4580
     *
4581
     * @return bool
4582
     */
4583
    public static function protect_teacher_session_edit($id)
4584
    {
4585
        if (!api_is_coach($id) && !api_is_platform_admin()) {
4586
            api_not_allowed(true);
4587
        } else {
4588
            return true;
4589
        }
4590
    }
4591
4592
    /**
4593
     * @param int $courseId
4594
     *
4595
     * @return array
4596
     */
4597
    public static function get_session_by_course($courseId)
4598
    {
4599
        $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4600
        $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
4601
        $url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4602
        $courseId = intval($courseId);
4603
        $urlId = api_get_current_access_url_id();
4604
4605
        if (empty($courseId)) {
4606
            return [];
4607
        }
4608
4609
        $sql = "SELECT name, s.id
4610
                FROM $table_session_course sc
4611
                INNER JOIN $table_session s 
4612
                ON (sc.session_id = s.id)
4613
                INNER JOIN $url u
4614
                ON (u.session_id = s.id)
4615
                WHERE 
4616
                    u.access_url_id = $urlId AND 
4617
                    sc.c_id = '$courseId' ";
4618
        $result = Database::query($sql);
4619
4620
        return Database::store_result($result);
4621
    }
4622
4623
    /**
4624
     * @param int  $user_id
4625
     * @param bool $ignoreVisibilityForAdmins
4626
     * @param bool $ignoreTimeLimit
4627
     *
4628
     * @return array
4629
     */
4630
    public static function get_sessions_by_user(
4631
        $user_id,
4632
        $ignoreVisibilityForAdmins = false,
4633
        $ignoreTimeLimit = false
4634
    ) {
4635
        $sessionCategories = UserManager::get_sessions_by_category(
4636
            $user_id,
4637
            false,
4638
            $ignoreVisibilityForAdmins,
4639
            $ignoreTimeLimit
4640
        );
4641
4642
        $sessionArray = [];
4643
        if (!empty($sessionCategories)) {
4644
            foreach ($sessionCategories as $category) {
4645
                if (isset($category['sessions'])) {
4646
                    foreach ($category['sessions'] as $session) {
4647
                        $sessionArray[] = $session;
4648
                    }
4649
                }
4650
            }
4651
        }
4652
4653
        return $sessionArray;
4654
    }
4655
4656
    /**
4657
     * @param string $file
4658
     * @param bool   $updateSession                                   options:
4659
     *                                                                true: if the session exists it will be updated.
4660
     *                                                                false: if session exists a new session will be created adding a counter session1, session2, etc
4661
     * @param int    $defaultUserId
4662
     * @param mixed  $logger
4663
     * @param array  $extraFields                                     convert a file row to an extra field. Example in CSV file there's a SessionID
4664
     *                                                                then it will converted to extra_external_session_id if you set: array('SessionId' => 'extra_external_session_id')
4665
     * @param string $extraFieldId
4666
     * @param int    $daysCoachAccessBeforeBeginning
4667
     * @param int    $daysCoachAccessAfterBeginning
4668
     * @param int    $sessionVisibility
4669
     * @param array  $fieldsToAvoidUpdate
4670
     * @param bool   $deleteUsersNotInList
4671
     * @param bool   $updateCourseCoaches
4672
     * @param bool   $sessionWithCoursesModifier
4673
     * @param bool   $addOriginalCourseTeachersAsCourseSessionCoaches
4674
     * @param bool   $removeAllTeachersFromCourse
4675
     * @param int    $showDescription
4676
     * @param array  $teacherBackupList
4677
     * @param array  $groupBackup
4678
     *
4679
     * @return array
4680
     */
4681
    public static function importCSV(
4682
        $file,
4683
        $updateSession,
4684
        $defaultUserId = null,
4685
        $logger = null,
4686
        $extraFields = [],
4687
        $extraFieldId = null,
4688
        $daysCoachAccessBeforeBeginning = null,
4689
        $daysCoachAccessAfterBeginning = null,
4690
        $sessionVisibility = 1,
4691
        $fieldsToAvoidUpdate = [],
4692
        $deleteUsersNotInList = false,
4693
        $updateCourseCoaches = false,
4694
        $sessionWithCoursesModifier = false,
4695
        $addOriginalCourseTeachersAsCourseSessionCoaches = true,
4696
        $removeAllTeachersFromCourse = true,
4697
        $showDescription = null,
4698
        &$teacherBackupList = [],
4699
        &$groupBackup = []
4700
    ) {
4701
        $content = file($file);
4702
        $error_message = null;
4703
        $session_counter = 0;
4704
        $defaultUserId = empty($defaultUserId) ? api_get_user_id() : (int) $defaultUserId;
4705
4706
        $eol = PHP_EOL;
4707
        if (PHP_SAPI != 'cli') {
4708
            $eol = '<br />';
4709
        }
4710
4711
        $debug = false;
4712
        if (isset($logger)) {
4713
            $debug = true;
4714
        }
4715
4716
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
4717
        $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4718
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4719
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4720
        $sessions = [];
4721
        if (!api_strstr($content[0], ';')) {
4722
            $error_message = get_lang('NotCSV');
4723
        } else {
4724
            $tag_names = [];
4725
            foreach ($content as $key => $enreg) {
4726
                $enreg = explode(';', trim($enreg));
4727
                if ($key) {
4728
                    foreach ($tag_names as $tag_key => $tag_name) {
4729
                        if (isset($enreg[$tag_key])) {
4730
                            $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
4731
                        }
4732
                    }
4733
                } else {
4734
                    foreach ($enreg as $tag_name) {
4735
                        $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
4736
                    }
4737
                    if (!in_array('SessionName', $tag_names) ||
4738
                        !in_array('DateStart', $tag_names) ||
4739
                        !in_array('DateEnd', $tag_names)
4740
                    ) {
4741
                        $error_message = get_lang('NoNeededData');
4742
                        break;
4743
                    }
4744
                }
4745
            }
4746
4747
            $sessionList = [];
4748
            $report = [];
4749
4750
            // Looping the sessions.
4751
            foreach ($sessions as $enreg) {
4752
                $user_counter = 0;
4753
                $course_counter = 0;
4754
4755
                if (isset($extraFields) && !empty($extraFields)) {
4756
                    foreach ($extraFields as $original => $to) {
4757
                        $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
4758
                    }
4759
                }
4760
4761
                $session_name = $enreg['SessionName'];
4762
                // Default visibility
4763
                $visibilityAfterExpirationPerSession = $sessionVisibility;
4764
4765
                if (isset($enreg['VisibilityAfterExpiration'])) {
4766
                    $visibility = $enreg['VisibilityAfterExpiration'];
4767
                    switch ($visibility) {
4768
                        case 'read_only':
4769
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
4770
                            break;
4771
                        case 'accessible':
4772
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
4773
                            break;
4774
                        case 'not_accessible':
4775
                            $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
4776
                            break;
4777
                    }
4778
                }
4779
4780
                if (empty($session_name)) {
4781
                    continue;
4782
                }
4783
4784
                $displayAccessStartDate = isset($enreg['DisplayStartDate']) ? $enreg['DisplayStartDate'] : $enreg['DateStart'];
4785
                $displayAccessEndDate = isset($enreg['DisplayEndDate']) ? $enreg['DisplayEndDate'] : $enreg['DateEnd'];
4786
                $coachAccessStartDate = isset($enreg['CoachStartDate']) ? $enreg['CoachStartDate'] : $enreg['DateStart'];
4787
                $coachAccessEndDate = isset($enreg['CoachEndDate']) ? $enreg['CoachEndDate'] : $enreg['DateEnd'];
4788
                // We assume the dates are already in UTC
4789
                $dateStart = explode('/', $enreg['DateStart']);
4790
                $dateEnd = explode('/', $enreg['DateEnd']);
4791
                $dateStart = $dateStart[0].'-'.$dateStart[1].'-'.$dateStart[2].' 00:00:00';
4792
                $dateEnd = $dateEnd[0].'-'.$dateEnd[1].'-'.$dateEnd[2].' 23:59:59';
4793
                $displayAccessStartDate = explode('/', $displayAccessStartDate);
4794
                $displayAccessStartDate = implode('-', $displayAccessStartDate).' 00:00:00';
4795
                $displayAccessEndDate = explode('/', $displayAccessEndDate);
4796
                $displayAccessEndDate = implode('-', $displayAccessEndDate).' 23:59:59';
4797
                $coachAccessStartDate = explode('/', $coachAccessStartDate);
4798
                $coachAccessStartDate = implode('-', $coachAccessStartDate).' 00:00:00';
4799
                $coachAccessEndDate = explode('/', $coachAccessEndDate);
4800
                $coachAccessEndDate = implode('-', $coachAccessEndDate).' 23:59:59';
4801
                $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
4802
                $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
4803
                $classes = isset($enreg['Classes']) ? explode('|', $enreg['Classes']) : [];
4804
                $extraParams = [];
4805
                if (!is_null($showDescription)) {
4806
                    $extraParams['show_description'] = intval($showDescription);
4807
                }
4808
4809
                $coachBefore = '';
4810
                $coachAfter = '';
4811
                if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
4812
                    $date = new \DateTime($dateStart);
4813
                    $interval = new DateInterval('P'.$daysCoachAccessBeforeBeginning.'D');
4814
                    $date->sub($interval);
4815
                    $coachBefore = $date->format('Y-m-d h:i');
4816
                    $coachAccessStartDate = $coachBefore;
4817
                    $coachBefore = api_get_utc_datetime($coachBefore);
4818
4819
                    $date = new \DateTime($dateEnd);
4820
                    $interval = new DateInterval('P'.$daysCoachAccessAfterBeginning.'D');
4821
                    $date->add($interval);
4822
                    $coachAfter = $date->format('Y-m-d h:i');
4823
                    $coachAccessEndDate = $coachAfter;
4824
                    $coachAfter = api_get_utc_datetime($coachAfter);
4825
                }
4826
4827
                $dateStart = api_get_utc_datetime($dateStart);
4828
                $dateEnd = api_get_utc_datetime($dateEnd);
4829
                $displayAccessStartDate = api_get_utc_datetime($displayAccessStartDate);
4830
                $displayAccessEndDate = api_get_utc_datetime($displayAccessEndDate);
4831
                $coachAccessStartDate = api_get_utc_datetime($coachAccessStartDate);
4832
                $coachAccessEndDate = api_get_utc_datetime($coachAccessEndDate);
4833
4834
                if (!empty($sessionDescription)) {
4835
                    $extraParams['description'] = $sessionDescription;
4836
                }
4837
4838
                if (!empty($session_category_id)) {
4839
                    $extraParams['session_category_id'] = $session_category_id;
4840
                }
4841
4842
                // Searching a general coach.
4843
                if (!empty($enreg['Coach'])) {
4844
                    $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
4845
                    if ($coach_id === false) {
4846
                        // If the coach-user does not exist - I'm the coach.
4847
                        $coach_id = $defaultUserId;
4848
                    }
4849
                } else {
4850
                    $coach_id = $defaultUserId;
4851
                }
4852
4853
                $users = explode('|', $enreg['Users']);
4854
                $courses = explode('|', $enreg['Courses']);
4855
4856
                $deleteOnlyCourseCoaches = false;
4857
                if (count($courses) == 1) {
4858
                    if ($logger) {
4859
                        $logger->addInfo('Only one course delete old coach list');
4860
                    }
4861
                    $deleteOnlyCourseCoaches = true;
4862
                }
4863
4864
                if (!$updateSession) {
4865
                    // Create a session.
4866
                    $unique_name = false;
4867
                    $i = 0;
4868
                    // Change session name, verify that session doesn't exist.
4869
                    $suffix = null;
4870
                    while (!$unique_name) {
4871
                        if ($i > 1) {
4872
                            $suffix = ' - '.$i;
4873
                        }
4874
                        $sql = 'SELECT 1 FROM '.$tbl_session.'
4875
                                WHERE name="'.Database::escape_string($session_name).$suffix.'"';
4876
                        $rs = Database::query($sql);
4877
                        if (Database::result($rs, 0, 0)) {
4878
                            $i++;
4879
                        } else {
4880
                            $unique_name = true;
4881
                            $session_name .= $suffix;
4882
                        }
4883
                    }
4884
4885
                    $sessionParams = [
4886
                        'name' => $session_name,
4887
                        'id_coach' => $coach_id,
4888
                        'access_start_date' => $dateStart,
4889
                        'access_end_date' => $dateEnd,
4890
                        'display_start_date' => $displayAccessStartDate,
4891
                        'display_end_date' => $displayAccessEndDate,
4892
                        'coach_access_start_date' => $coachAccessStartDate,
4893
                        'coach_access_end_date' => $coachAccessEndDate,
4894
                        'visibility' => $visibilityAfterExpirationPerSession,
4895
                        'session_admin_id' => $defaultUserId,
4896
                    ];
4897
4898
                    if (!empty($extraParams)) {
4899
                        $sessionParams = array_merge($sessionParams, $extraParams);
4900
                    }
4901
                    // Creating the session.
4902
                    $session_id = Database::insert($tbl_session, $sessionParams);
4903
                    if ($debug) {
4904
                        if ($session_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $session_id of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

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

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
4905
                            foreach ($enreg as $key => $value) {
4906
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
4907
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
4908
                                }
4909
                            }
4910
                            $logger->addInfo("Sessions - Session created: #$session_id - $session_name");
0 ignored issues
show
Bug introduced by
The method addInfo() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

4910
                            $logger->/** @scrutinizer ignore-call */ 
4911
                                     addInfo("Sessions - Session created: #$session_id - $session_name");

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4911
                        } else {
4912
                            $logger->addError("Sessions - Session NOT created: $session_name");
4913
                        }
4914
                    }
4915
                    $session_counter++;
4916
                } else {
4917
                    $sessionId = null;
4918
                    if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
4919
                        $sessionId = self::getSessionIdFromOriginalId($enreg['extra_'.$extraFieldId], $extraFieldId);
4920
                        if (empty($sessionId)) {
4921
                            $my_session_result = false;
4922
                        } else {
4923
                            $my_session_result = true;
4924
                        }
4925
                    } else {
4926
                        $my_session_result = self::get_session_by_name($enreg['SessionName']);
4927
                    }
4928
4929
                    if ($my_session_result === false) {
4930
                        // One more check
4931
                        $sessionExistsWithName = self::get_session_by_name($session_name);
4932
4933
                        if ($sessionExistsWithName) {
4934
                            if ($debug) {
4935
                                $logger->addError(
4936
                                    "Sessions - Trying to update a session, but name already exists: $session_name"
4937
                                );
4938
                            }
4939
                            continue;
4940
                        }
4941
4942
                        $sessionParams = [
4943
                            'name' => $session_name,
4944
                            'id_coach' => $coach_id,
4945
                            'access_start_date' => $dateStart,
4946
                            'access_end_date' => $dateEnd,
4947
                            'display_start_date' => $displayAccessStartDate,
4948
                            'display_end_date' => $displayAccessEndDate,
4949
                            'coach_access_start_date' => $coachAccessStartDate,
4950
                            'coach_access_end_date' => $coachAccessEndDate,
4951
                            'visibility' => $visibilityAfterExpirationPerSession,
4952
                            'session_admin_id' => $defaultUserId,
4953
                        ];
4954
4955
                        if (!empty($extraParams)) {
4956
                            $sessionParams = array_merge($sessionParams, $extraParams);
4957
                        }
4958
                        Database::insert($tbl_session, $sessionParams);
4959
4960
                        // We get the last insert id.
4961
                        $my_session_result = self::get_session_by_name($session_name);
4962
                        $session_id = $my_session_result['id'];
4963
4964
                        if ($session_id) {
4965
                            foreach ($enreg as $key => $value) {
4966
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
4967
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
4968
                                }
4969
                            }
4970
                            if ($debug) {
4971
                                $logger->addInfo("Sessions - #$session_id created: $session_name");
4972
                            }
4973
4974
                            // Delete session-user relation only for students
4975
                            $sql = "DELETE FROM $tbl_session_user
4976
                                    WHERE session_id = '$session_id' AND relation_type <> ".SESSION_RELATION_TYPE_RRHH;
4977
                            Database::query($sql);
4978
4979
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
4980
                            Database::query($sql);
4981
4982
                            // Delete session-course-user relationships students and coaches.
4983
                            if ($updateCourseCoaches) {
4984
                                $sql = "DELETE FROM $tbl_session_course_user
4985
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
4986
                                Database::query($sql);
4987
                            } else {
4988
                                // Delete session-course-user relation ships *only* for students.
4989
                                $sql = "DELETE FROM $tbl_session_course_user
4990
                                        WHERE session_id = '$session_id' AND status <> 2";
4991
                                Database::query($sql);
4992
                            }
4993
                            if ($deleteOnlyCourseCoaches) {
4994
                                $sql = "DELETE FROM $tbl_session_course_user
4995
                                        WHERE session_id = '$session_id' AND status in ('2')";
4996
                                Database::query($sql);
4997
                            }
4998
                        }
4999
                    } else {
5000
                        // Updating the session.
5001
                        $params = [
5002
                            'id_coach' => $coach_id,
5003
                            'access_start_date' => $dateStart,
5004
                            'access_end_date' => $dateEnd,
5005
                            'display_start_date' => $dateStart,
5006
                            'display_end_date' => $dateEnd,
5007
                            'display_start_date' => $displayAccessStartDate,
5008
                            'display_end_date' => $displayAccessEndDate,
5009
                            'coach_access_start_date' => $coachAccessStartDate,
5010
                            'coach_access_end_date' => $coachAccessEndDate,
5011
                            'visibility' => $visibilityAfterExpirationPerSession,
5012
                            'session_category_id' => $session_category_id,
5013
                        ];
5014
5015
                        if (!empty($sessionDescription)) {
5016
                            $params['description'] = $sessionDescription;
5017
                        }
5018
5019
                        if (!empty($fieldsToAvoidUpdate)) {
5020
                            foreach ($fieldsToAvoidUpdate as $field) {
5021
                                unset($params[$field]);
5022
                            }
5023
                        }
5024
5025
                        if (isset($sessionId) && !empty($sessionId)) {
5026
                            $session_id = $sessionId;
5027
                            if (!empty($enreg['SessionName'])) {
5028
                                $sessionExistsWithName = self::get_session_by_name($session_name);
5029
                                if ($sessionExistsWithName === false) {
5030
                                    $sessionName = Database::escape_string($enreg['SessionName']);
5031
                                    $sql = "UPDATE $tbl_session SET name = '$sessionName' WHERE id = $session_id";
5032
                                    Database::query($sql);
5033
                                } else {
5034
                                    if ($debug) {
5035
                                        $report[] = "Error when update session: Name already exists: Session #$session_id Name: '$session_name' External id: ".$enreg['extra_'.$extraFieldId];
5036
                                    }
5037
                                    continue;
5038
                                }
5039
                            }
5040
                        } else {
5041
                            $my_session_result = self::get_session_by_name($session_name);
5042
                            $session_id = $my_session_result['id'];
5043
                        }
5044
5045
                        if ($debug) {
5046
                            $logger->addError("Sessions - Session #$session_id to be updated: '$session_name'");
5047
                        }
5048
5049
                        if ($session_id) {
5050
                            if ($debug) {
5051
                                $logger->addError("Sessions - Session to be updated #$session_id");
5052
                            }
5053
5054
                            $sessionInfo = api_get_session_info($session_id);
5055
                            $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
5056
5057
                            if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
5058
                                if (empty($sessionInfo['nb_days_access_before_beginning']) ||
5059
                                    (!empty($sessionInfo['nb_days_access_before_beginning']) &&
5060
                                        $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning)
5061
                                ) {
5062
                                    $params['coach_access_start_date'] = $coachBefore;
5063
                                }
5064
5065
                                if (empty($sessionInfo['nb_days_access_after_end']) ||
5066
                                    (!empty($sessionInfo['nb_days_access_after_end']) &&
5067
                                        $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning)
5068
                                ) {
5069
                                    $params['coach_access_end_date'] = $coachAfter;
5070
                                }
5071
                            }
5072
5073
                            Database::update($tbl_session, $params, ['id = ?' => $session_id]);
5074
5075
                            foreach ($enreg as $key => $value) {
5076
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
5077
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
5078
                                }
5079
                            }
5080
5081
                            // Delete session-user relation only for students
5082
                            $sql = "DELETE FROM $tbl_session_user
5083
                                    WHERE session_id = '$session_id' AND relation_type <> ".SESSION_RELATION_TYPE_RRHH;
5084
                            Database::query($sql);
5085
5086
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
5087
                            Database::query($sql);
5088
5089
                            // Delete session-course-user relationships students and coaches.
5090
                            if ($updateCourseCoaches) {
5091
                                $sql = "DELETE FROM $tbl_session_course_user
5092
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
5093
                                Database::query($sql);
5094
                            } else {
5095
                                // Delete session-course-user relation ships *only* for students.
5096
                                $sql = "DELETE FROM $tbl_session_course_user
5097
                                        WHERE session_id = '$session_id' AND status <> 2";
5098
                                Database::query($sql);
5099
                            }
5100
5101
                            if ($deleteOnlyCourseCoaches) {
5102
                                $sql = "DELETE FROM $tbl_session_course_user
5103
                                        WHERE session_id = '$session_id' AND status in ('2')";
5104
                                Database::query($sql);
5105
                            }
5106
                        } else {
5107
                            if ($debug) {
5108
                                $logger->addError(
5109
                                    "Sessions - Session not found"
5110
                                );
5111
                            }
5112
                        }
5113
                    }
5114
                    $session_counter++;
5115
                }
5116
5117
                $sessionList[] = $session_id;
5118
5119
                // Adding the relationship "Session - User" for students
5120
                $userList = [];
5121
                if (is_array($users)) {
5122
                    foreach ($users as $user) {
5123
                        $user_id = UserManager::get_user_id_from_username($user);
5124
                        if ($user_id !== false) {
5125
                            $userList[] = $user_id;
5126
                            // Insert new users.
5127
                            $sql = "INSERT IGNORE INTO $tbl_session_user SET
5128
                                    user_id = '$user_id',
5129
                                    session_id = '$session_id',
5130
                                    registered_at = '".api_get_utc_datetime()."'";
5131
                            Database::query($sql);
5132
                            if ($debug) {
5133
                                $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id");
5134
                            }
5135
                            $user_counter++;
5136
                        }
5137
                    }
5138
                }
5139
5140
                if ($deleteUsersNotInList) {
5141
                    // Getting user in DB in order to compare to the new list.
5142
                    $usersListInDatabase = self::get_users_by_session($session_id, 0);
5143
                    if (!empty($usersListInDatabase)) {
5144
                        if (empty($userList)) {
5145
                            foreach ($usersListInDatabase as $userInfo) {
5146
                                self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
5147
                            }
5148
                        } else {
5149
                            foreach ($usersListInDatabase as $userInfo) {
5150
                                if (!in_array($userInfo['user_id'], $userList)) {
5151
                                    self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
5152
                                }
5153
                            }
5154
                        }
5155
                    }
5156
                }
5157
5158
                // See BT#6449
5159
                $onlyAddFirstCoachOrTeacher = false;
5160
                if ($sessionWithCoursesModifier) {
5161
                    if (count($courses) >= 2) {
5162
                        // Only first teacher in course session;
5163
                        $onlyAddFirstCoachOrTeacher = true;
5164
                        // Remove all teachers from course.
5165
                        $removeAllTeachersFromCourse = false;
5166
                    }
5167
                }
5168
5169
                foreach ($courses as $course) {
5170
                    $courseArray = bracketsToArray($course);
5171
                    $course_code = $courseArray[0];
5172
5173
                    if (CourseManager::course_exists($course_code)) {
5174
                        $courseInfo = api_get_course_info($course_code);
5175
                        $courseId = $courseInfo['real_id'];
5176
5177
                        // Adding the course to a session.
5178
                        $sql = "INSERT IGNORE INTO $tbl_session_course
5179
                                SET c_id = '$courseId', session_id='$session_id'";
5180
                        Database::query($sql);
5181
5182
                        self::installCourse($session_id, $courseInfo['real_id']);
5183
5184
                        if ($debug) {
5185
                            $logger->addInfo("Sessions - Adding course '$course_code' to session #$session_id");
5186
                        }
5187
5188
                        $course_counter++;
5189
                        $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
5190
                        $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
5191
                        $course_users = explode(',', $course_users);
5192
                        $course_coaches = explode(',', $course_coaches);
5193
5194
                        // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
5195
                        $addTeachersToSession = true;
5196
5197
                        if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
5198
                            $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
5199
                        }
5200
5201
                        // If any user provided for a course, use the users array.
5202
                        if (empty($course_users)) {
5203
                            if (!empty($userList)) {
5204
                                self::subscribe_users_to_session_course(
5205
                                    $userList,
5206
                                    $session_id,
5207
                                    $course_code
5208
                                );
5209
                                if ($debug) {
5210
                                    $msg = "Sessions - Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
5211
                                    $logger->addInfo($msg);
5212
                                }
5213
                            }
5214
                        }
5215
5216
                        // Adding coaches to session course user.
5217
                        if (!empty($course_coaches)) {
5218
                            $savedCoaches = [];
5219
                            // only edit if add_teachers_to_sessions_courses is set.
5220
                            if ($addTeachersToSession) {
5221
                                if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
5222
                                    // Adding course teachers as course session teachers.
5223
                                    $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code(
5224
                                        $course_code
5225
                                    );
5226
5227
                                    if (!empty($alreadyAddedTeachers)) {
5228
                                        $teachersToAdd = [];
5229
                                        foreach ($alreadyAddedTeachers as $user) {
5230
                                            $teachersToAdd[] = $user['username'];
5231
                                        }
5232
                                        $course_coaches = array_merge(
5233
                                            $course_coaches,
5234
                                            $teachersToAdd
5235
                                        );
5236
                                    }
5237
                                }
5238
5239
                                foreach ($course_coaches as $course_coach) {
5240
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
5241
                                    if ($coach_id !== false) {
5242
                                        // Just insert new coaches
5243
                                        self::updateCoaches(
5244
                                            $session_id,
5245
                                            $courseId,
5246
                                            [$coach_id],
5247
                                            false
5248
                                        );
5249
5250
                                        if ($debug) {
5251
                                            $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
5252
                                        }
5253
                                        $savedCoaches[] = $coach_id;
5254
                                    } else {
5255
                                        $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
5256
                                    }
5257
                                }
5258
                            }
5259
5260
                            // Custom courses/session coaches
5261
                            $teacherToAdd = null;
5262
                            // Only one coach is added.
5263
                            if ($onlyAddFirstCoachOrTeacher == true) {
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...
5264
                                if ($debug) {
5265
                                    $logger->addInfo("onlyAddFirstCoachOrTeacher : true");
5266
                                }
5267
5268
                                foreach ($course_coaches as $course_coach) {
5269
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
5270
                                    if ($coach_id !== false) {
5271
                                        $teacherToAdd = $coach_id;
5272
                                        break;
5273
                                    }
5274
                                }
5275
5276
                                // Un subscribe everyone that's not in the list.
5277
                                $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
5278
                                if (!empty($teacherList)) {
5279
                                    foreach ($teacherList as $teacher) {
5280
                                        if ($teacherToAdd != $teacher['user_id']) {
5281
                                            $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
5282
                                                    WHERE
5283
                                                        user_id = ".$teacher['user_id']." AND
5284
                                                        c_id = '".$courseId."'
5285
                                                    ";
5286
5287
                                            $result = Database::query($sql);
5288
                                            $rows = Database::num_rows($result);
5289
                                            if ($rows > 0) {
5290
                                                $userCourseData = Database::fetch_array($result, 'ASSOC');
5291
                                                if (!empty($userCourseData)) {
5292
                                                    $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
5293
                                                }
5294
                                            }
5295
5296
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
5297
                                                    WHERE
5298
                                                        user_id = ".$teacher['user_id']." AND
5299
                                                        c_id = '".$courseInfo['real_id']."'
5300
                                                    ";
5301
5302
                                            $result = Database::query($sql);
5303
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5304
                                                $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5305
                                            }
5306
5307
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
5308
                                                    WHERE
5309
                                                        user_id = ".$teacher['user_id']." AND
5310
                                                        c_id = '".$courseInfo['real_id']."'
5311
                                                    ";
5312
5313
                                            $result = Database::query($sql);
5314
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5315
                                                $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5316
                                            }
5317
5318
                                            CourseManager::unsubscribe_user(
5319
                                                $teacher['user_id'],
5320
                                                $course_code
5321
                                            );
5322
5323
                                            if ($debug) {
5324
                                                $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
5325
                                            }
5326
                                        }
5327
                                    }
5328
                                }
5329
5330
                                if (!empty($teacherToAdd)) {
5331
                                    self::updateCoaches(
5332
                                        $session_id,
5333
                                        $courseId,
5334
                                        [$teacherToAdd],
5335
                                        true
5336
                                    );
5337
5338
                                    if ($debug) {
5339
                                        $logger->addInfo("Add coach #$teacherToAdd to course $courseId and session $session_id");
5340
                                    }
5341
5342
                                    $userCourseCategory = '';
5343
                                    if (isset($teacherBackupList[$teacherToAdd]) &&
5344
                                        isset($teacherBackupList[$teacherToAdd][$course_code])
5345
                                    ) {
5346
                                        $courseUserData = $teacherBackupList[$teacherToAdd][$course_code];
5347
                                        $userCourseCategory = $courseUserData['user_course_cat'];
5348
                                    }
5349
5350
                                    CourseManager::subscribe_user(
5351
                                        $teacherToAdd,
5352
                                        $course_code,
5353
                                        COURSEMANAGER,
5354
                                        0,
5355
                                        $userCourseCategory
5356
                                    );
5357
5358
                                    if ($debug) {
5359
                                        $logger->addInfo("Subscribe user #$teacherToAdd as teacher in course $course_code with user userCourseCategory $userCourseCategory");
5360
                                    }
5361
5362
                                    if (isset($groupBackup['user'][$teacherToAdd]) &&
5363
                                        isset($groupBackup['user'][$teacherToAdd][$course_code]) &&
5364
                                        !empty($groupBackup['user'][$teacherToAdd][$course_code])
5365
                                    ) {
5366
                                        foreach ($groupBackup['user'][$teacherToAdd][$course_code] as $data) {
5367
                                            $groupInfo = GroupManager::get_group_properties($data['group_id']);
5368
                                            GroupManager::subscribe_users(
5369
                                                $teacherToAdd,
5370
                                                $groupInfo,
5371
                                                $data['c_id']
5372
                                            );
5373
                                        }
5374
                                    }
5375
5376
                                    if (isset($groupBackup['tutor'][$teacherToAdd]) &&
5377
                                        isset($groupBackup['tutor'][$teacherToAdd][$course_code]) &&
5378
                                        !empty($groupBackup['tutor'][$teacherToAdd][$course_code])
5379
                                    ) {
5380
                                        foreach ($groupBackup['tutor'][$teacherToAdd][$course_code] as $data) {
5381
                                            $groupInfo = GroupManager::get_group_properties($data['group_id']);
5382
                                            GroupManager::subscribe_tutors(
5383
                                                $teacherToAdd,
5384
                                                $groupInfo,
5385
                                                $data['c_id']
5386
                                            );
5387
                                        }
5388
                                    }
5389
                                }
5390
                            }
5391
5392
                            // See BT#6449#note-195
5393
                            // All coaches are added.
5394
                            if ($removeAllTeachersFromCourse) {
5395
                                if ($debug) {
5396
                                    $logger->addInfo("removeAllTeachersFromCourse true");
5397
                                }
5398
                                $teacherToAdd = null;
5399
                                foreach ($course_coaches as $course_coach) {
5400
                                    $coach_id = UserManager::get_user_id_from_username(
5401
                                        $course_coach
5402
                                    );
5403
                                    if ($coach_id !== false) {
5404
                                        $teacherToAdd[] = $coach_id;
5405
                                    }
5406
                                }
5407
5408
                                if (!empty($teacherToAdd)) {
5409
                                    // Deleting all course teachers and adding the only coach as teacher.
5410
                                    $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
5411
5412
                                    if (!empty($teacherList)) {
5413
                                        foreach ($teacherList as $teacher) {
5414
                                            if (!in_array($teacher['user_id'], $teacherToAdd)) {
5415
                                                $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
5416
                                                        WHERE
5417
                                                            user_id = ".$teacher['user_id']." AND
5418
                                                            c_id = '".$courseId."'
5419
                                                        ";
5420
5421
                                                $result = Database::query($sql);
5422
                                                $rows = Database::num_rows($result);
5423
                                                if ($rows > 0) {
5424
                                                    $userCourseData = Database::fetch_array($result, 'ASSOC');
5425
                                                    if (!empty($userCourseData)) {
5426
                                                        $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
5427
                                                    }
5428
                                                }
5429
5430
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
5431
                                                        WHERE
5432
                                                            user_id = ".$teacher['user_id']." AND
5433
                                                            c_id = '".$courseInfo['real_id']."'
5434
                                                        ";
5435
5436
                                                $result = Database::query($sql);
5437
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5438
                                                    $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5439
                                                }
5440
5441
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
5442
                                                        WHERE
5443
                                                            user_id = ".$teacher['user_id']." AND
5444
                                                            c_id = '".$courseInfo['real_id']."'
5445
                                                        ";
5446
5447
                                                $result = Database::query($sql);
5448
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5449
                                                    $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5450
                                                }
5451
5452
                                                CourseManager::unsubscribe_user(
5453
                                                    $teacher['user_id'],
5454
                                                    $course_code
5455
                                                );
5456
5457
                                                if ($debug) {
5458
                                                    $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
5459
                                                }
5460
                                            }
5461
                                        }
5462
                                    }
5463
5464
                                    foreach ($teacherToAdd as $teacherId) {
5465
                                        $userCourseCategory = '';
5466
                                        if (isset($teacherBackupList[$teacherId]) &&
5467
                                            isset($teacherBackupList[$teacherId][$course_code])
5468
                                        ) {
5469
                                            $courseUserData = $teacherBackupList[$teacherId][$course_code];
5470
                                            $userCourseCategory = $courseUserData['user_course_cat'];
5471
                                        }
5472
5473
                                        CourseManager::subscribe_user(
5474
                                            $teacherId,
5475
                                            $course_code,
5476
                                            COURSEMANAGER,
5477
                                            0,
5478
                                            $userCourseCategory
5479
                                        );
5480
5481
                                        if ($debug) {
5482
                                            $logger->addInfo("Add user as teacher #".$teacherId." in base course: $course_code with userCourseCategory: $userCourseCategory");
5483
                                        }
5484
5485
                                        if (isset($groupBackup['user'][$teacherId]) &&
5486
                                            isset($groupBackup['user'][$teacherId][$course_code]) &&
5487
                                            !empty($groupBackup['user'][$teacherId][$course_code])
5488
                                        ) {
5489
                                            foreach ($groupBackup['user'][$teacherId][$course_code] as $data) {
5490
                                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
5491
                                                GroupManager::subscribe_users(
5492
                                                    $teacherId,
5493
                                                    $groupInfo,
5494
                                                    $data['c_id']
5495
                                                );
5496
                                            }
5497
                                        }
5498
5499
                                        if (isset($groupBackup['tutor'][$teacherId]) &&
5500
                                            isset($groupBackup['tutor'][$teacherId][$course_code]) &&
5501
                                            !empty($groupBackup['tutor'][$teacherId][$course_code])
5502
                                        ) {
5503
                                            foreach ($groupBackup['tutor'][$teacherId][$course_code] as $data) {
5504
                                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
5505
                                                GroupManager::subscribe_tutors(
5506
                                                    $teacherId,
5507
                                                    $groupInfo,
5508
                                                    $data['c_id']
5509
                                                );
5510
                                            }
5511
                                        }
5512
                                    }
5513
                                }
5514
                            }
5515
5516
                            // Continue default behaviour.
5517
                            if ($onlyAddFirstCoachOrTeacher == false) {
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...
5518
                                // Checking one more time see BT#6449#note-149
5519
                                $coaches = self::getCoachesByCourseSession($session_id, $courseId);
5520
                                // Update coaches if only there's 1 course see BT#6449#note-189
5521
                                if (empty($coaches) || count($courses) == 1) {
5522
                                    foreach ($course_coaches as $course_coach) {
5523
                                        $course_coach = trim($course_coach);
5524
                                        $coach_id = UserManager::get_user_id_from_username($course_coach);
5525
                                        if ($coach_id !== false) {
5526
                                            // Just insert new coaches
5527
                                            self::updateCoaches(
5528
                                                $session_id,
5529
                                                $courseId,
5530
                                                [$coach_id],
5531
                                                false
5532
                                            );
5533
5534
                                            if ($debug) {
5535
                                                $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
5536
                                            }
5537
                                            $savedCoaches[] = $coach_id;
5538
                                        } else {
5539
                                            $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
5540
                                        }
5541
                                    }
5542
                                }
5543
                            }
5544
                        }
5545
5546
                        // Adding Students, updating relationship "Session - Course - User".
5547
                        $course_users = array_filter($course_users);
5548
                        if (!empty($course_users)) {
5549
                            foreach ($course_users as $user) {
5550
                                $user_id = UserManager::get_user_id_from_username($user);
5551
5552
                                if ($user_id !== false) {
5553
                                    self::subscribe_users_to_session_course(
5554
                                        [$user_id],
5555
                                        $session_id,
5556
                                        $course_code
5557
                                    );
5558
                                    if ($debug) {
5559
                                        $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
5560
                                    }
5561
                                } else {
5562
                                    $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
5563
                                }
5564
                            }
5565
                        }
5566
                        $inserted_in_course[$course_code] = $courseInfo['title'];
5567
                    }
5568
                }
5569
                $access_url_id = api_get_current_access_url_id();
5570
                UrlManager::add_session_to_url($session_id, $access_url_id);
5571
                $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter' 
5572
                        WHERE id = '$session_id'";
5573
                Database::query($sql);
5574
5575
                self::addClassesByName($session_id, $classes, false);
5576
            }
5577
5578
            if (!empty($report)) {
5579
                if ($debug) {
5580
                    $logger->addInfo("--Summary--");
5581
                    foreach ($report as $line) {
5582
                        $logger->addInfo($line);
5583
                    }
5584
                }
5585
            }
5586
        }
5587
5588
        return [
5589
            'error_message' => $error_message,
5590
            'session_counter' => $session_counter,
5591
            'session_list' => $sessionList,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sessionList does not seem to be defined for all execution paths leading up to this point.
Loading history...
5592
        ];
5593
    }
5594
5595
    /**
5596
     * @param int $sessionId
5597
     * @param int $courseId
5598
     *
5599
     * @return array
5600
     */
5601
    public static function getCoachesByCourseSession($sessionId, $courseId)
5602
    {
5603
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5604
        $sessionId = intval($sessionId);
5605
        $courseId = intval($courseId);
5606
5607
        $sql = "SELECT user_id FROM $table
5608
                WHERE
5609
                    session_id = '$sessionId' AND
5610
                    c_id = '$courseId' AND
5611
                    status = 2";
5612
        $result = Database::query($sql);
5613
5614
        $coaches = [];
5615
        if (Database::num_rows($result) > 0) {
5616
            while ($row = Database::fetch_array($result)) {
5617
                $coaches[] = $row['user_id'];
5618
            }
5619
        }
5620
5621
        return $coaches;
5622
    }
5623
5624
    /**
5625
     * @param int $sessionId
5626
     * @param int $courseId
5627
     *
5628
     * @return string
5629
     */
5630
    public static function getCoachesByCourseSessionToString(
5631
        $sessionId,
5632
        $courseId
5633
    ) {
5634
        $coaches = self::getCoachesByCourseSession($sessionId, $courseId);
5635
        $list = [];
5636
        if (!empty($coaches)) {
5637
            foreach ($coaches as $coachId) {
5638
                $userInfo = api_get_user_info($coachId);
5639
                if ($userInfo) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $userInfo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
5640
                    $list[] = $userInfo['complete_name'];
5641
                }
5642
            }
5643
        }
5644
5645
        return array_to_string($list, CourseManager::USER_SEPARATOR);
5646
    }
5647
5648
    /**
5649
     * Get all coaches added in the session - course relationship.
5650
     *
5651
     * @param int $sessionId
5652
     *
5653
     * @return array
5654
     */
5655
    public static function getCoachesBySession($sessionId)
5656
    {
5657
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5658
        $sessionId = intval($sessionId);
5659
5660
        $sql = "SELECT DISTINCT user_id
5661
                FROM $table
5662
                WHERE session_id = '$sessionId' AND status = 2";
5663
        $result = Database::query($sql);
5664
5665
        $coaches = [];
5666
        if (Database::num_rows($result) > 0) {
5667
            while ($row = Database::fetch_array($result)) {
5668
                $coaches[] = $row['user_id'];
5669
            }
5670
        }
5671
5672
        return $coaches;
5673
    }
5674
5675
    /**
5676
     * @param int $userId
5677
     *
5678
     * @return array
5679
     */
5680
    public static function getAllCoursesFromAllSessionFromDrh($userId)
5681
    {
5682
        $sessions = self::get_sessions_followed_by_drh($userId);
5683
        $coursesFromSession = [];
5684
        if (!empty($sessions)) {
5685
            foreach ($sessions as $session) {
5686
                $courseList = self::get_course_list_by_session_id($session['id']);
5687
                foreach ($courseList as $course) {
5688
                    $coursesFromSession[] = $course['code'];
5689
                }
5690
            }
5691
        }
5692
5693
        return $coursesFromSession;
5694
    }
5695
5696
    /**
5697
     * getAllCoursesFromAllSessions.
5698
     *
5699
     * @return array
5700
     */
5701
    public static function getAllCoursesFromAllSessions()
5702
    {
5703
        $sessions = self::get_sessions_list();
5704
        $coursesFromSession = [];
5705
        if (!empty($sessions)) {
5706
            foreach ($sessions as $session) {
5707
                $courseList = self::get_course_list_by_session_id($session['id']);
5708
                foreach ($courseList as $course) {
5709
                    $coursesFromSession[$course['code'].':'.$session['id']] = $course['visual_code'].' - '.$course['title'].' ('.$session['name'].')';
5710
                }
5711
            }
5712
        }
5713
5714
        return $coursesFromSession;
5715
    }
5716
5717
    /**
5718
     * @param string $status
5719
     * @param int    $userId
5720
     * @param bool   $getCount
5721
     * @param int    $from
5722
     * @param int    $numberItems
5723
     * @param int    $column
5724
     * @param string $direction
5725
     * @param string $keyword
5726
     * @param string $active
5727
     * @param string $lastConnectionDate
5728
     * @param array  $sessionIdList
5729
     * @param array  $studentIdList
5730
     * @param int    $filterByStatus
5731
     *
5732
     * @return array|int
5733
     */
5734
    public static function getAllUsersFromCoursesFromAllSessionFromStatus(
5735
        $status,
5736
        $userId,
5737
        $getCount = false,
5738
        $from = null,
5739
        $numberItems = null,
5740
        $column = 1,
5741
        $direction = 'asc',
5742
        $keyword = null,
5743
        $active = null,
5744
        $lastConnectionDate = null,
5745
        $sessionIdList = [],
5746
        $studentIdList = [],
5747
        $filterByStatus = null
5748
    ) {
5749
        $filterByStatus = intval($filterByStatus);
5750
5751
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
5752
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
5753
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
5754
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
5755
        $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
5756
        $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
5757
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5758
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
5759
5760
        $direction = in_array(strtolower($direction), ['asc', 'desc']) ? $direction : 'asc';
5761
        $column = Database::escape_string($column);
5762
        $userId = intval($userId);
5763
5764
        $limitCondition = '';
5765
        if (isset($from) && isset($numberItems)) {
5766
            $from = intval($from);
5767
            $numberItems = intval($numberItems);
5768
            $limitCondition = "LIMIT $from, $numberItems";
5769
        }
5770
5771
        $urlId = api_get_current_access_url_id();
5772
5773
        $sessionConditions = '';
5774
        $courseConditions = '';
5775
        $userConditions = '';
5776
5777
        if (isset($active)) {
5778
            $active = intval($active);
5779
            $userConditions .= " AND active = $active";
5780
        }
5781
5782
        $courseList = CourseManager::get_courses_followed_by_drh($userId, DRH);
5783
        if (!empty($courseList)) {
5784
            $courseIdList = array_column($courseList, 'id');
5785
            $courseConditions = ' AND c.id IN ("'.implode('","', $courseIdList).'")';
5786
        }
5787
5788
        $userConditionsFromDrh = '';
5789
5790
        // Classic DRH
5791
        if (empty($studentIdList)) {
5792
            $studentListSql = UserManager::get_users_followed_by_drh(
5793
                $userId,
5794
                $filterByStatus,
5795
                true,
5796
                false
5797
            );
5798
            if (!empty($studentListSql)) {
5799
                $studentIdList = array_keys($studentListSql);
5800
                $studentListSql = "'".implode("','", $studentIdList)."'";
5801
            }
5802
        } else {
5803
            $studentIdList = array_map('intval', $studentIdList);
5804
            $studentListSql = "'".implode("','", $studentIdList)."'";
5805
        }
5806
        if (!empty($studentListSql)) {
5807
            $userConditionsFromDrh = " AND u.user_id IN (".$studentListSql.") ";
5808
        }
5809
5810
        switch ($status) {
5811
            case 'drh':
5812
                break;
5813
            case 'drh_all':
5814
                // Show all by DRH
5815
                if (empty($sessionIdList)) {
5816
                    $sessionsListSql = self::get_sessions_followed_by_drh(
5817
                        $userId,
5818
                        null,
5819
                        null,
5820
                        false,
5821
                        true,
5822
                        true
5823
                    );
5824
                } else {
5825
                    $sessionIdList = array_map('intval', $sessionIdList);
5826
                    $sessionsListSql = "'".implode("','", $sessionIdList)."'";
5827
                }
5828
                if (!empty($sessionsListSql)) {
5829
                    $sessionConditions = " AND s.id IN (".$sessionsListSql.") ";
0 ignored issues
show
Bug introduced by
Are you sure $sessionsListSql of type string|array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

5829
                    $sessionConditions = " AND s.id IN ("./** @scrutinizer ignore-type */ $sessionsListSql.") ";
Loading history...
5830
                }
5831
                break;
5832
            case 'session_admin':
5833
                $sessionConditions = " AND s.id_coach = $userId ";
5834
                $userConditionsFromDrh = '';
5835
                break;
5836
            case 'admin':
5837
                break;
5838
            case 'teacher':
5839
                $sessionConditions = " AND s.id_coach = $userId ";
5840
                $userConditionsFromDrh = '';
5841
                break;
5842
        }
5843
5844
        $select = "SELECT DISTINCT u.* ";
5845
        $masterSelect = "SELECT DISTINCT * FROM ";
5846
5847
        if ($getCount) {
5848
            $select = "SELECT DISTINCT u.user_id ";
5849
            $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
5850
        }
5851
5852
        if (!empty($filterByStatus)) {
5853
            $userConditions .= " AND u.status = ".$filterByStatus;
5854
        }
5855
5856
        if (!empty($lastConnectionDate)) {
5857
            $lastConnectionDate = Database::escape_string($lastConnectionDate);
5858
            $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
5859
        }
5860
5861
        if (!empty($keyword)) {
5862
            $keyword = Database::escape_string($keyword);
5863
            $userConditions .= " AND (
5864
                u.username LIKE '%$keyword%' OR
5865
                u.firstname LIKE '%$keyword%' OR
5866
                u.lastname LIKE '%$keyword%' OR
5867
                u.official_code LIKE '%$keyword%' OR
5868
                u.email LIKE '%$keyword%'
5869
            )";
5870
        }
5871
5872
        $where = " WHERE
5873
                   access_url_id = $urlId
5874
                   $userConditions
5875
        ";
5876
5877
        $userUnion = '';
5878
        if (!empty($userConditionsFromDrh)) {
5879
            $userUnion = "
5880
            UNION (
5881
                $select                    
5882
                FROM $tbl_user u
5883
                INNER JOIN $tbl_user_rel_access_url url ON (url.user_id = u.id)
5884
                $where
5885
                $userConditionsFromDrh
5886
            )";
5887
        }
5888
5889
        $sql = "$masterSelect (
5890
                ($select
5891
                FROM $tbl_session s
5892
                    INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.session_id)
5893
                    INNER JOIN $tbl_user u ON (u.user_id = su.user_id)
5894
                    INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
5895
                    $where
5896
                    $sessionConditions
5897
                    $userConditionsFromDrh
5898
                ) UNION (
5899
                    $select
5900
                    FROM $tbl_course c
5901
                    INNER JOIN $tbl_course_user cu ON (cu.c_id = c.id)
5902
                    INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
5903
                    INNER JOIN $tbl_course_rel_access_url url ON (url.c_id = c.id)
5904
                    $where
5905
                    $courseConditions
5906
                    $userConditionsFromDrh
5907
                ) $userUnion
5908
                ) as t1
5909
                ";
5910
5911
        if ($getCount) {
5912
            $result = Database::query($sql);
5913
5914
            $count = 0;
5915
            if (Database::num_rows($result)) {
5916
                $rows = Database::fetch_array($result);
5917
                $count = $rows['count'];
5918
            }
5919
5920
            return $count;
5921
        }
5922
5923
        if (!empty($column) && !empty($direction)) {
5924
            $column = str_replace('u.', '', $column);
5925
            $sql .= " ORDER BY $column $direction ";
5926
        }
5927
        $sql .= $limitCondition;
5928
        $result = Database::query($sql);
5929
        $result = Database::store_result($result);
5930
5931
        return $result;
5932
    }
5933
5934
    /**
5935
     * @param int   $sessionId
5936
     * @param int   $courseId
5937
     * @param array $coachList
5938
     * @param bool  $deleteCoachesNotInList
5939
     */
5940
    public static function updateCoaches(
5941
        $sessionId,
5942
        $courseId,
5943
        $coachList,
5944
        $deleteCoachesNotInList = false
5945
    ) {
5946
        $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseId);
5947
5948
        if (!empty($coachList)) {
5949
            foreach ($coachList as $userId) {
5950
                self::set_coach_to_course_session($userId, $sessionId, $courseId);
5951
            }
5952
        }
5953
5954
        if ($deleteCoachesNotInList) {
5955
            if (!empty($coachList)) {
5956
                $coachesToDelete = array_diff($currentCoaches, $coachList);
5957
            } else {
5958
                $coachesToDelete = $currentCoaches;
5959
            }
5960
5961
            if (!empty($coachesToDelete)) {
5962
                foreach ($coachesToDelete as $userId) {
5963
                    self::set_coach_to_course_session(
5964
                        $userId,
5965
                        $sessionId,
5966
                        $courseId,
5967
                        true
5968
                    );
5969
                }
5970
            }
5971
        }
5972
    }
5973
5974
    /**
5975
     * @param array $sessions
5976
     * @param array $sessionsDestination
5977
     *
5978
     * @return array
5979
     */
5980
    public static function copyStudentsFromSession($sessions, $sessionsDestination)
5981
    {
5982
        $messages = [];
5983
        if (!empty($sessions)) {
5984
            foreach ($sessions as $sessionId) {
5985
                $sessionInfo = self::fetch($sessionId);
5986
                $userList = self::get_users_by_session($sessionId, 0);
5987
                if (!empty($userList)) {
5988
                    $newUserList = [];
5989
                    $userToString = null;
5990
                    foreach ($userList as $userInfo) {
5991
                        $newUserList[] = $userInfo['user_id'];
5992
                        $userToString .= $userInfo['firstname'].' '.$userInfo['lastname'].'<br />';
5993
                    }
5994
5995
                    if (!empty($sessionsDestination)) {
5996
                        foreach ($sessionsDestination as $sessionDestinationId) {
5997
                            $sessionDestinationInfo = self::fetch($sessionDestinationId);
5998
                            $messages[] = Display::return_message(
5999
                                sprintf(
6000
                                    get_lang(
6001
                                        'AddingStudentsFromSessionXToSessionY'
6002
                                    ),
6003
                                    $sessionInfo['name'],
6004
                                    $sessionDestinationInfo['name']
6005
                                ),
6006
                                'info',
6007
                                false
6008
                            );
6009
                            if ($sessionId == $sessionDestinationId) {
6010
                                $messages[] = Display::return_message(
6011
                                    sprintf(
6012
                                        get_lang('SessionXSkipped'),
6013
                                        $sessionDestinationId
6014
                                    ),
6015
                                    'warning',
6016
                                    false
6017
                                );
6018
                                continue;
6019
                            }
6020
                            $messages[] = Display::return_message(get_lang('StudentList').'<br />'.$userToString, 'info', false);
6021
                            self::subscribe_users_to_session(
6022
                                $sessionDestinationId,
6023
                                $newUserList,
6024
                                SESSION_VISIBLE_READ_ONLY,
6025
                                false
6026
                            );
6027
                        }
6028
                    } else {
6029
                        $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
6030
                    }
6031
                } else {
6032
                    $messages[] = Display::return_message(
6033
                        get_lang('NoStudentsFoundForSession').' #'.$sessionInfo['name'],
6034
                        'warning'
6035
                    );
6036
                }
6037
            }
6038
        } else {
6039
            $messages[] = Display::return_message(get_lang('NoData'), 'warning');
6040
        }
6041
6042
        return $messages;
6043
    }
6044
6045
    /**
6046
     * Assign coaches of a session(s) as teachers to a given course (or courses).
6047
     *
6048
     * @param array A list of session IDs
6049
     * @param array A list of course IDs
6050
     *
6051
     * @return string
6052
     */
6053
    public static function copyCoachesFromSessionToCourse($sessions, $courses)
6054
    {
6055
        $coachesPerSession = [];
6056
        foreach ($sessions as $sessionId) {
6057
            $coaches = self::getCoachesBySession($sessionId);
6058
            $coachesPerSession[$sessionId] = $coaches;
6059
        }
6060
6061
        $result = [];
6062
6063
        if (!empty($courses)) {
6064
            foreach ($courses as $courseId) {
6065
                $courseInfo = api_get_course_info_by_id($courseId);
6066
                foreach ($coachesPerSession as $sessionId => $coachList) {
6067
                    CourseManager::updateTeachers(
6068
                        $courseInfo,
6069
                        $coachList,
6070
                        false,
6071
                        false,
6072
                        false
6073
                    );
6074
                    $result[$courseInfo['code']][$sessionId] = $coachList;
6075
                }
6076
            }
6077
        }
6078
        $sessionUrl = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session=';
6079
        $htmlResult = null;
6080
6081
        if (!empty($result)) {
6082
            foreach ($result as $courseCode => $data) {
6083
                $url = api_get_course_url($courseCode);
6084
                $htmlResult .= sprintf(
6085
                    get_lang('CoachesSubscribedAsATeacherInCourseX'),
6086
                    Display::url($courseCode, $url, ['target' => '_blank'])
6087
                );
6088
                foreach ($data as $sessionId => $coachList) {
6089
                    $sessionInfo = self::fetch($sessionId);
6090
                    $htmlResult .= '<br />';
6091
                    $htmlResult .= Display::url(
6092
                        get_lang('Session').': '.$sessionInfo['name'].' <br />',
6093
                        $sessionUrl.$sessionId,
6094
                        ['target' => '_blank']
6095
                    );
6096
                    $teacherList = [];
6097
                    foreach ($coachList as $coachId) {
6098
                        $userInfo = api_get_user_info($coachId);
6099
                        $teacherList[] = $userInfo['complete_name'];
6100
                    }
6101
                    if (!empty($teacherList)) {
6102
                        $htmlResult .= implode(', ', $teacherList);
6103
                    } else {
6104
                        $htmlResult .= get_lang('NothingToAdd');
6105
                    }
6106
                }
6107
                $htmlResult .= '<br />';
6108
            }
6109
            $htmlResult = Display::return_message($htmlResult, 'normal', false);
6110
        }
6111
6112
        return $htmlResult;
6113
    }
6114
6115
    /**
6116
     * @param string $keyword
6117
     * @param string $active
6118
     * @param string $lastConnectionDate
6119
     * @param array  $sessionIdList
6120
     * @param array  $studentIdList
6121
     * @param int    $filterUserStatus   STUDENT|COURSEMANAGER constants
6122
     *
6123
     * @return array|int
6124
     */
6125
    public static function getCountUserTracking(
6126
        $keyword = null,
6127
        $active = null,
6128
        $lastConnectionDate = null,
6129
        $sessionIdList = [],
6130
        $studentIdList = [],
6131
        $filterUserStatus = null
6132
    ) {
6133
        $userId = api_get_user_id();
6134
        $drhLoaded = false;
6135
6136
        if (api_is_drh()) {
6137
            if (api_drh_can_access_all_session_content()) {
6138
                $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
6139
                    'drh_all',
6140
                    $userId,
6141
                    true,
6142
                    null,
6143
                    null,
6144
                    null,
6145
                    null,
6146
                    $keyword,
6147
                    $active,
6148
                    $lastConnectionDate,
6149
                    $sessionIdList,
6150
                    $studentIdList,
6151
                    $filterUserStatus
6152
                );
6153
                $drhLoaded = true;
6154
            }
6155
        }
6156
6157
        if ($drhLoaded == false) {
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...
6158
            $count = UserManager::getUsersFollowedByUser(
6159
                $userId,
6160
                $filterUserStatus,
6161
                false,
6162
                false,
6163
                true,
6164
                null,
6165
                null,
6166
                null,
6167
                null,
6168
                $active,
0 ignored issues
show
Bug introduced by
It seems like $active can also be of type string; however, parameter $active of UserManager::getUsersFollowedByUser() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6168
                /** @scrutinizer ignore-type */ $active,
Loading history...
6169
                $lastConnectionDate,
6170
                api_is_student_boss() ? STUDENT_BOSS : COURSEMANAGER,
6171
                $keyword
6172
            );
6173
        }
6174
6175
        return $count;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $count does not seem to be defined for all execution paths leading up to this point.
Loading history...
6176
    }
6177
6178
    /**
6179
     * Get teachers followed by a user.
6180
     *
6181
     * @param int    $userId
6182
     * @param int    $active
6183
     * @param string $lastConnectionDate
6184
     * @param bool   $getCount
6185
     * @param array  $sessionIdList
6186
     *
6187
     * @return array|int
6188
     */
6189
    public static function getTeacherTracking(
6190
        $userId,
6191
        $active = 1,
6192
        $lastConnectionDate = null,
6193
        $getCount = false,
6194
        $sessionIdList = []
6195
    ) {
6196
        $teacherListId = [];
6197
        if (api_is_drh() || api_is_platform_admin()) {
6198
            // Followed teachers by drh
6199
            if (api_drh_can_access_all_session_content()) {
6200
                if (empty($sessionIdList)) {
6201
                    $sessions = self::get_sessions_followed_by_drh($userId);
6202
                    $sessionIdList = [];
6203
                    foreach ($sessions as $session) {
6204
                        $sessionIdList[] = $session['id'];
6205
                    }
6206
                }
6207
6208
                $sessionIdList = array_map('intval', $sessionIdList);
6209
                $sessionToString = implode("', '", $sessionIdList);
6210
6211
                $course = Database::get_main_table(TABLE_MAIN_COURSE);
6212
                $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
6213
                $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
6214
6215
                // Select the teachers.
6216
                $sql = "SELECT DISTINCT(cu.user_id) 
6217
                        FROM $course c
6218
                        INNER JOIN $sessionCourse src 
6219
                        ON c.id = src.c_id
6220
                        INNER JOIN $courseUser cu 
6221
                        ON (cu.c_id = c.id)
6222
		                WHERE src.session_id IN ('$sessionToString') AND cu.status = 1";
6223
                $result = Database::query($sql);
6224
                while ($row = Database::fetch_array($result, 'ASSOC')) {
6225
                    $teacherListId[$row['user_id']] = $row['user_id'];
6226
                }
6227
            } else {
6228
                $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
6229
                foreach ($teacherResult as $userInfo) {
6230
                    $teacherListId[] = $userInfo['user_id'];
6231
                }
6232
            }
6233
        }
6234
6235
        if (!empty($teacherListId)) {
6236
            $tableUser = Database::get_main_table(TABLE_MAIN_USER);
6237
6238
            $select = "SELECT DISTINCT u.* ";
6239
            if ($getCount) {
6240
                $select = "SELECT count(DISTINCT(u.user_id)) as count";
6241
            }
6242
6243
            $sql = "$select FROM $tableUser u";
6244
6245
            if (!empty($lastConnectionDate)) {
6246
                $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
6247
                //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
6248
            }
6249
            $active = intval($active);
6250
            $teacherListId = implode("','", $teacherListId);
6251
            $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
6252
6253
            if (!empty($lastConnectionDate)) {
6254
                $lastConnectionDate = Database::escape_string($lastConnectionDate);
6255
                //$where .= " AND l.login_date <= '$lastConnectionDate' ";
6256
            }
6257
6258
            $sql .= $where;
6259
            $result = Database::query($sql);
6260
            if (Database::num_rows($result)) {
6261
                if ($getCount) {
6262
                    $row = Database::fetch_array($result);
6263
6264
                    return $row['count'];
6265
                } else {
6266
                    return Database::store_result($result, 'ASSOC');
6267
                }
6268
            }
6269
        }
6270
6271
        return 0;
6272
    }
6273
6274
    /**
6275
     * Get the list of course tools that have to be dealt with in case of
6276
     * registering any course to a session.
6277
     *
6278
     * @return array The list of tools to be dealt with (literal names)
6279
     */
6280
    public static function getCourseToolToBeManaged()
6281
    {
6282
        return [
6283
            'courseDescription',
6284
            'courseIntroduction',
6285
        ];
6286
    }
6287
6288
    /**
6289
     * Calls the methods bound to each tool when a course is registered into a session.
6290
     *
6291
     * @param int $sessionId
6292
     * @param int $courseId
6293
     *
6294
     * @return bool
6295
     */
6296
    public static function installCourse($sessionId, $courseId)
6297
    {
6298
        return true;
6299
        $toolList = self::getCourseToolToBeManaged();
0 ignored issues
show
Unused Code introduced by
$toolList = self::getCourseToolToBeManaged() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
6300
6301
        foreach ($toolList as $tool) {
6302
            $method = 'add'.$tool;
6303
            if (method_exists(get_class(), $method)) {
6304
                self::$method($sessionId, $courseId);
6305
            }
6306
        }
6307
    }
6308
6309
    /**
6310
     * Calls the methods bound to each tool when a course is unregistered from
6311
     * a session.
6312
     *
6313
     * @param int $sessionId
6314
     * @param int $courseId
6315
     */
6316
    public static function unInstallCourse($sessionId, $courseId)
6317
    {
6318
        return true;
6319
        $toolList = self::getCourseToolToBeManaged();
0 ignored issues
show
Unused Code introduced by
$toolList = self::getCourseToolToBeManaged() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
6320
6321
        foreach ($toolList as $tool) {
6322
            $method = 'remove'.$tool;
6323
            if (method_exists(get_class(), $method)) {
6324
                self::$method($sessionId, $courseId);
6325
            }
6326
        }
6327
    }
6328
6329
    /**
6330
     * @param int $sessionId
6331
     * @param int $courseId
6332
     */
6333
    public static function addCourseIntroduction($sessionId, $courseId)
6334
    {
6335
        // @todo create a tool intro lib
6336
        $sessionId = intval($sessionId);
6337
        $courseId = intval($courseId);
6338
6339
        $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
6340
        $sql = "SELECT * FROM $TBL_INTRODUCTION WHERE c_id = $courseId";
6341
        $result = Database::query($sql);
6342
        $result = Database::store_result($result, 'ASSOC');
6343
6344
        if (!empty($result)) {
6345
            foreach ($result as $result) {
6346
                // @todo check if relation exits.
6347
                $result['session_id'] = $sessionId;
6348
                Database::insert($TBL_INTRODUCTION, $result);
6349
            }
6350
        }
6351
    }
6352
6353
    /**
6354
     * @param int $sessionId
6355
     * @param int $courseId
6356
     */
6357
    public static function removeCourseIntroduction($sessionId, $courseId)
6358
    {
6359
        $sessionId = intval($sessionId);
6360
        $courseId = intval($courseId);
6361
        $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
6362
        $sql = "DELETE FROM $TBL_INTRODUCTION
6363
                WHERE c_id = $courseId AND session_id = $sessionId";
6364
        Database::query($sql);
6365
    }
6366
6367
    /**
6368
     * @param int $sessionId
6369
     * @param int $courseId
6370
     */
6371
    public static function addCourseDescription($sessionId, $courseId)
6372
    {
6373
        /* $description = new CourseDescription();
6374
          $descriptions = $description->get_descriptions($courseId);
6375
          foreach ($descriptions as $description) {
6376
          } */
6377
    }
6378
6379
    /**
6380
     * @param int $sessionId
6381
     * @param int $courseId
6382
     */
6383
    public static function removeCourseDescription($sessionId, $courseId)
6384
    {
6385
    }
6386
6387
    /**
6388
     * @param array $userSessionList        format see self::importSessionDrhCSV()
6389
     * @param bool  $sendEmail
6390
     * @param bool  $removeOldRelationShips
6391
     */
6392
    public static function subscribeDrhToSessionList(
6393
        $userSessionList,
6394
        $sendEmail,
6395
        $removeOldRelationShips
6396
    ) {
6397
        if (!empty($userSessionList)) {
6398
            foreach ($userSessionList as $userId => $data) {
6399
                $sessionList = [];
6400
                foreach ($data['session_list'] as $sessionInfo) {
6401
                    $sessionList[] = $sessionInfo['session_id'];
6402
                }
6403
                $userInfo = $data['user_info'];
6404
                self::subscribeSessionsToDrh(
6405
                    $userInfo,
6406
                    $sessionList,
6407
                    $sendEmail,
6408
                    $removeOldRelationShips
6409
                );
6410
            }
6411
        }
6412
    }
6413
6414
    /**
6415
     * @param array $userSessionList format see self::importSessionDrhCSV()
6416
     *
6417
     * @return string
6418
     */
6419
    public static function checkSubscribeDrhToSessionList($userSessionList)
6420
    {
6421
        $message = null;
6422
        if (!empty($userSessionList)) {
6423
            if (!empty($userSessionList)) {
6424
                foreach ($userSessionList as $userId => $data) {
6425
                    $userInfo = $data['user_info'];
6426
6427
                    $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
6428
                    if (!empty($sessionListSubscribed)) {
6429
                        $sessionListSubscribed = array_keys($sessionListSubscribed);
6430
                    }
6431
6432
                    $sessionList = [];
6433
                    if (!empty($data['session_list'])) {
6434
                        foreach ($data['session_list'] as $sessionInfo) {
6435
                            if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
6436
                                $sessionList[] = $sessionInfo['session_info']['name'];
6437
                            }
6438
                        }
6439
                    }
6440
6441
                    $message .= '<strong>'.get_lang('User').'</strong>: '.$userInfo['complete_name'].' <br />';
6442
6443
                    if (!in_array($userInfo['status'], [DRH]) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
6444
                        $message .= get_lang('UserMustHaveTheDrhRole').'<br />';
6445
                        continue;
6446
                    }
6447
6448
                    if (!empty($sessionList)) {
6449
                        $message .= '<strong>'.get_lang('Sessions').':</strong> <br />';
6450
                        $message .= implode(', ', $sessionList).'<br /><br />';
6451
                    } else {
6452
                        $message .= get_lang('NoSessionProvided').' <br /><br />';
6453
                    }
6454
                }
6455
            }
6456
        }
6457
6458
        return $message;
6459
    }
6460
6461
    /**
6462
     * @param string $file
6463
     * @param bool   $sendEmail
6464
     * @param bool   $removeOldRelationShips
6465
     *
6466
     * @return string
6467
     */
6468
    public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
6469
    {
6470
        $list = Import::csv_reader($file);
6471
6472
        if (!empty($list)) {
6473
            $userSessionList = [];
6474
            foreach ($list as $data) {
6475
                $userInfo = api_get_user_info_from_username($data['Username']);
6476
                $sessionInfo = self::get_session_by_name($data['SessionName']);
6477
6478
                if (!empty($userInfo) && !empty($sessionInfo)) {
6479
                    $userSessionList[$userInfo['user_id']]['session_list'][] = [
6480
                        'session_id' => $sessionInfo['id'],
6481
                        'session_info' => $sessionInfo,
6482
                    ];
6483
                    $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
6484
                }
6485
            }
6486
6487
            self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
6488
6489
            return self::checkSubscribeDrhToSessionList($userSessionList);
6490
        }
6491
    }
6492
6493
    /**
6494
     * Courses re-ordering in resume_session.php flag see BT#8316.
6495
     */
6496
    public static function orderCourseIsEnabled()
6497
    {
6498
        $sessionCourseOrder = api_get_setting('session_course_ordering');
6499
        if ($sessionCourseOrder === 'true') {
6500
            return true;
6501
        }
6502
6503
        return false;
6504
    }
6505
6506
    /**
6507
     * @param string $direction (up/down)
6508
     * @param int    $sessionId
6509
     * @param int    $courseId
6510
     *
6511
     * @return bool
6512
     */
6513
    public static function move($direction, $sessionId, $courseId)
6514
    {
6515
        if (!self::orderCourseIsEnabled()) {
6516
            return false;
6517
        }
6518
6519
        $sessionId = intval($sessionId);
6520
        $courseId = intval($courseId);
6521
6522
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
6523
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
6524
6525
        $position = [];
6526
        $count = 0;
6527
        foreach ($courseList as $course) {
6528
            if ($course['position'] == '') {
6529
                $course['position'] = $count;
6530
            }
6531
            $position[$course['code']] = $course['position'];
6532
            // Saving current order.
6533
            $sql = "UPDATE $table SET position = $count
6534
                    WHERE session_id = $sessionId AND c_id = '".$course['real_id']."'";
6535
            Database::query($sql);
6536
            $count++;
6537
        }
6538
6539
        // Loading new positions.
6540
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
6541
6542
        $found = false;
6543
6544
        switch ($direction) {
6545
            case 'up':
6546
                $courseList = array_reverse($courseList);
6547
                break;
6548
            case 'down':
6549
                break;
6550
        }
6551
6552
        foreach ($courseList as $course) {
6553
            if ($found) {
6554
                $nextId = $course['real_id'];
6555
                $nextOrder = $course['position'];
6556
                break;
6557
            }
6558
6559
            if ($courseId == $course['real_id']) {
6560
                $thisCourseCode = $course['real_id'];
6561
                $thisOrder = $course['position'];
6562
                $found = true;
6563
            }
6564
        }
6565
6566
        $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $nextOrder does not seem to be defined for all execution paths leading up to this point.
Loading history...
6567
                 WHERE session_id = $sessionId AND c_id =  $thisCourseCode";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $thisCourseCode does not seem to be defined for all execution paths leading up to this point.
Loading history...
6568
        Database::query($sql1);
6569
6570
        $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $thisOrder does not seem to be defined for all execution paths leading up to this point.
Loading history...
6571
                 WHERE session_id = $sessionId AND c_id = $nextId";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $nextId does not seem to be defined for all execution paths leading up to this point.
Loading history...
6572
        Database::query($sql2);
6573
6574
        return true;
6575
    }
6576
6577
    /**
6578
     * @param int $sessionId
6579
     * @param int $courseId
6580
     *
6581
     * @return bool
6582
     */
6583
    public static function moveUp($sessionId, $courseId)
6584
    {
6585
        return self::move('up', $sessionId, $courseId);
6586
    }
6587
6588
    /**
6589
     * @param int    $sessionId
6590
     * @param string $courseCode
6591
     *
6592
     * @return bool
6593
     */
6594
    public static function moveDown($sessionId, $courseCode)
6595
    {
6596
        return self::move('down', $sessionId, $courseCode);
6597
    }
6598
6599
    /**
6600
     * Use the session duration to allow/block user access see BT#8317
6601
     * Needs these DB changes
6602
     * ALTER TABLE session ADD COLUMN duration int;
6603
     * ALTER TABLE session_rel_user ADD COLUMN duration int;.
6604
     */
6605
    public static function durationPerUserIsEnabled()
6606
    {
6607
        return api_get_configuration_value('session_duration_feature');
6608
    }
6609
6610
    /**
6611
     * Returns the number of days the student has left in a session when using
6612
     * sessions durations.
6613
     *
6614
     * @param array $sessionInfo
6615
     * @param int   $userId
6616
     *
6617
     * @return int
6618
     */
6619
    public static function getDayLeftInSession(array $sessionInfo, $userId)
6620
    {
6621
        $sessionId = $sessionInfo['id'];
6622
        $subscription = self::getUserSession($userId, $sessionId);
6623
        $duration = empty($subscription['duration'])
6624
            ? $sessionInfo['duration']
6625
            : $sessionInfo['duration'] + $subscription['duration'];
6626
6627
        // Get an array with the details of the first access of the student to
6628
        // this session
6629
        $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
6630
            $sessionId,
6631
            $userId
6632
        );
6633
6634
        $currentTime = time();
6635
6636
        // If no previous access, return false
6637
        if (count($courseAccess) == 0) {
6638
            return $duration;
6639
        }
6640
6641
        $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
6642
        $endDateInSeconds = $firstAccess + $duration * 24 * 60 * 60;
6643
        $leftDays = round(($endDateInSeconds - $currentTime) / 60 / 60 / 24);
6644
6645
        return $leftDays;
6646
    }
6647
6648
    /**
6649
     * @param int $duration
6650
     * @param int $userId
6651
     * @param int $sessionId
6652
     *
6653
     * @return bool
6654
     */
6655
    public static function editUserSessionDuration($duration, $userId, $sessionId)
6656
    {
6657
        $duration = intval($duration);
6658
        $userId = intval($userId);
6659
        $sessionId = intval($sessionId);
6660
6661
        if (empty($userId) || empty($sessionId)) {
6662
            return false;
6663
        }
6664
6665
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
6666
        $parameters = ['duration' => $duration];
6667
        $where = ['session_id = ? AND user_id = ? ' => [$sessionId, $userId]];
6668
        Database::update($table, $parameters, $where);
6669
6670
        return true;
6671
    }
6672
6673
    /**
6674
     * Gets one row from the session_rel_user table.
6675
     *
6676
     * @param int $userId
6677
     * @param int $sessionId
6678
     *
6679
     * @return array
6680
     */
6681
    public static function getUserSession($userId, $sessionId)
6682
    {
6683
        $userId = intval($userId);
6684
        $sessionId = intval($sessionId);
6685
6686
        if (empty($userId) || empty($sessionId)) {
6687
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
6688
        }
6689
6690
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
6691
        $sql = "SELECT * FROM $table
6692
                WHERE session_id = $sessionId AND user_id = $userId";
6693
        $result = Database::query($sql);
6694
        $values = [];
6695
        if (Database::num_rows($result)) {
6696
            $values = Database::fetch_array($result, 'ASSOC');
6697
        }
6698
6699
        return $values;
6700
    }
6701
6702
    /**
6703
     * Check if user is subscribed inside a session as student.
6704
     *
6705
     * @param int $sessionId The session id
6706
     * @param int $userId    The user id
6707
     *
6708
     * @return bool Whether is subscribed
6709
     */
6710
    public static function isUserSubscribedAsStudent($sessionId, $userId)
6711
    {
6712
        $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
6713
        $sessionId = intval($sessionId);
6714
        $userId = intval($userId);
6715
6716
        // COUNT(1) actually returns the number of rows from the table (as if
6717
        // counting the results from the first column)
6718
        $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
6719
                WHERE
6720
                    session_id = $sessionId AND
6721
                    user_id = $userId AND
6722
                    relation_type = 0";
6723
6724
        $result = Database::fetch_assoc(Database::query($sql));
6725
6726
        if (!empty($result) && $result['qty'] > 0) {
6727
            return true;
6728
        }
6729
6730
        return false;
6731
    }
6732
6733
    /**
6734
     * Check if user is subscribed inside a session as a HRM.
6735
     *
6736
     * @param int $sessionId The session id
6737
     * @param int $userId    The user id
6738
     *
6739
     * @return bool Whether is subscribed
6740
     */
6741
    public static function isUserSubscribedAsHRM($sessionId, $userId)
6742
    {
6743
        $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
6744
6745
        $sessionId = intval($sessionId);
6746
        $userId = intval($userId);
6747
6748
        // COUNT(1) actually returns the number of rows from the table (as if
6749
        // counting the results from the first column)
6750
        $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
6751
                WHERE
6752
                    session_id = $sessionId AND
6753
                    user_id = $userId AND
6754
                    relation_type = ".SESSION_RELATION_TYPE_RRHH;
6755
6756
        $result = Database::fetch_assoc(Database::query($sql));
6757
6758
        if (!empty($result) && $result['qty'] > 0) {
6759
            return true;
6760
        }
6761
6762
        return false;
6763
    }
6764
6765
    /**
6766
     * Get the session coached by a user (general coach and course-session coach).
6767
     *
6768
     * @param int  $coachId                       The coach id
6769
     * @param bool $checkSessionRelUserVisibility Check the session visibility
6770
     * @param bool $asPlatformAdmin               The user is a platform admin and we want all sessions
6771
     *
6772
     * @return array The session list
6773
     */
6774
    public static function getSessionsCoachedByUser(
6775
        $coachId,
6776
        $checkSessionRelUserVisibility = false,
6777
        $asPlatformAdmin = false
6778
    ) {
6779
        // Get all sessions where $coachId is the general coach
6780
        $sessions = self::get_sessions_by_general_coach($coachId, $asPlatformAdmin);
6781
        // Get all sessions where $coachId is the course - session coach
6782
        $courseSessionList = self::getCoursesListByCourseCoach($coachId);
6783
        $sessionsByCoach = [];
6784
        if (!empty($courseSessionList)) {
6785
            foreach ($courseSessionList as $userCourseSubscription) {
6786
                $session = $userCourseSubscription->getSession();
6787
                $sessionsByCoach[$session->getId()] = api_get_session_info(
6788
                    $session->getId()
6789
                );
6790
            }
6791
        }
6792
6793
        if (!empty($sessionsByCoach)) {
6794
            $sessions = array_merge($sessions, $sessionsByCoach);
6795
        }
6796
6797
        // Remove repeated sessions
6798
        if (!empty($sessions)) {
6799
            $cleanSessions = [];
6800
            foreach ($sessions as $session) {
6801
                $cleanSessions[$session['id']] = $session;
6802
            }
6803
            $sessions = $cleanSessions;
6804
        }
6805
6806
        if ($checkSessionRelUserVisibility) {
6807
            if (!empty($sessions)) {
6808
                $newSessions = [];
6809
                foreach ($sessions as $session) {
6810
                    $visibility = api_get_session_visibility($session['id']);
6811
                    if ($visibility == SESSION_INVISIBLE) {
6812
                        continue;
6813
                    }
6814
                    $newSessions[] = $session;
6815
                }
6816
                $sessions = $newSessions;
6817
            }
6818
        }
6819
6820
        return $sessions;
6821
    }
6822
6823
    /**
6824
     * Check if the course belongs to the session.
6825
     *
6826
     * @param int    $sessionId  The session id
6827
     * @param string $courseCode The course code
6828
     *
6829
     * @return bool
6830
     */
6831
    public static function sessionHasCourse($sessionId, $courseCode)
6832
    {
6833
        $sessionId = intval($sessionId);
6834
        $courseCode = Database::escape_string($courseCode);
6835
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
6836
        $sessionRelCourseTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
6837
6838
        $sql = "SELECT COUNT(1) AS qty
6839
                FROM $courseTable c
6840
                INNER JOIN $sessionRelCourseTable src
6841
                ON c.id = src.c_id
6842
                WHERE src.session_id = $sessionId
6843
                AND c.code = '$courseCode'  ";
6844
6845
        $result = Database::query($sql);
6846
6847
        if ($result !== false) {
6848
            $data = Database::fetch_assoc($result);
6849
6850
            if ($data['qty'] > 0) {
6851
                return true;
6852
            }
6853
        }
6854
6855
        return false;
6856
    }
6857
6858
    /**
6859
     * Get the list of course coaches.
6860
     *
6861
     * @return array The list
6862
     */
6863
    public static function getAllCourseCoaches()
6864
    {
6865
        $coaches = [];
6866
6867
        $scuTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6868
        $userTable = Database::get_main_table(TABLE_MAIN_USER);
6869
6870
        $idResult = Database::select('DISTINCT user_id', $scuTable, [
6871
            'where' => [
6872
                'status = ?' => 2,
6873
            ],
6874
        ]);
6875
6876
        if ($idResult != false) {
6877
            foreach ($idResult as $idData) {
6878
                $userResult = Database::select(
6879
                    'user_id, lastname, firstname, username',
6880
                    $userTable,
6881
                    [
6882
                        'where' => [
6883
                            'user_id = ?' => $idData['user_id'],
6884
                        ],
6885
                    ],
6886
                    'first'
6887
                );
6888
6889
                if ($userResult != false) {
6890
                    $coaches[] = [
6891
                        'id' => $userResult['user_id'],
6892
                        'lastname' => $userResult['lastname'],
6893
                        'firstname' => $userResult['firstname'],
6894
                        'username' => $userResult['username'],
6895
                        'completeName' => api_get_person_name(
6896
                            $userResult['firstname'],
6897
                            $userResult['lastname']
6898
                        ),
6899
                    ];
6900
                }
6901
            }
6902
        }
6903
6904
        return $coaches;
6905
    }
6906
6907
    /**
6908
     * Calculate the total user time in the platform.
6909
     *
6910
     * @param int    $userId The user id
6911
     * @param string $from   Optional. From date
6912
     * @param string $until  Optional. Until date
6913
     *
6914
     * @return string The time (hh:mm:ss)
6915
     */
6916
    public static function getTotalUserTimeInPlatform($userId, $from = '', $until = '')
6917
    {
6918
        $userId = intval($userId);
6919
        $trackLoginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
6920
        $whereConditions = [
6921
            'login_user_id = ? ' => $userId,
6922
        ];
6923
6924
        if (!empty($from) && !empty($until)) {
6925
            $whereConditions["AND (login_date >= '?' "] = $from;
6926
            $whereConditions["AND logout_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
6927
        }
6928
6929
        $trackResult = Database::select(
6930
            'SEC_TO_TIME(SUM(UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date))) as total_time',
6931
            $trackLoginTable,
6932
            [
6933
                'where' => $whereConditions,
6934
            ],
6935
            'first'
6936
        );
6937
6938
        if ($trackResult != false) {
6939
            return $trackResult['total_time'] ? $trackResult['total_time'] : '00:00:00';
6940
        }
6941
6942
        return '00:00:00';
6943
    }
6944
6945
    /**
6946
     * Get the courses list by a course coach.
6947
     *
6948
     * @param int $coachId The coach id
6949
     *
6950
     * @return array (id, user_id, session_id, c_id, visibility, status, legal_agreement)
6951
     */
6952
    public static function getCoursesListByCourseCoach($coachId)
6953
    {
6954
        $entityManager = Database::getManager();
6955
        $scuRepo = $entityManager->getRepository(
6956
            'ChamiloCoreBundle:SessionRelCourseRelUser'
6957
        );
6958
6959
        return $scuRepo->findBy([
6960
            'user' => $coachId,
6961
            'status' => SessionRelCourseRelUser::STATUS_COURSE_COACH,
6962
        ]);
6963
    }
6964
6965
    /**
6966
     * Get the count of user courses in session.
6967
     *
6968
     * @param int $sessionId The session id
6969
     *
6970
     * @return array
6971
     */
6972
    public static function getTotalUserCoursesInSession($sessionId)
6973
    {
6974
        $tableUser = Database::get_main_table(TABLE_MAIN_USER);
6975
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6976
6977
        if (empty($sessionId)) {
6978
            return [];
6979
        }
6980
6981
        $sql = "SELECT 
6982
                    COUNT(u.id) as count, 
6983
                    u.id, 
6984
                    scu.status status_in_session, 
6985
                    u.status user_status
6986
                FROM $table scu
6987
                INNER JOIN $tableUser u 
6988
                ON scu.user_id = u.id
6989
                WHERE scu.session_id = ".intval($sessionId)."
6990
                GROUP BY u.id";
6991
6992
        $result = Database::query($sql);
6993
6994
        $list = [];
6995
        while ($data = Database::fetch_assoc($result)) {
6996
            $list[] = $data;
6997
        }
6998
6999
        return $list;
7000
    }
7001
7002
    /**
7003
     * Returns list of a few data from session (name, short description, start
7004
     * date, end date) and the given extra fields if defined based on a
7005
     * session category Id.
7006
     *
7007
     * @param int    $categoryId  The internal ID of the session category
7008
     * @param string $target      Value to search for in the session field values
7009
     * @param array  $extraFields A list of fields to be scanned and returned
7010
     *
7011
     * @return mixed
7012
     */
7013
    public static function getShortSessionListAndExtraByCategory(
7014
        $categoryId,
7015
        $target,
7016
        $extraFields = null,
7017
        $publicationDate = null
7018
    ) {
7019
        $categoryId = (int) $categoryId;
7020
        $sessionList = [];
7021
        // Check if categoryId is valid
7022
        if ($categoryId > 0) {
7023
            $target = Database::escape_string($target);
7024
            $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
7025
            $sfTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7026
            $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7027
            // Join session field and session field values tables
7028
            $joinTable = $sfTable.' sf INNER JOIN '.$sfvTable.' sfv ON sf.id = sfv.field_id';
7029
            $fieldsArray = [];
7030
            foreach ($extraFields as $field) {
7031
                $fieldsArray[] = Database::escape_string($field);
7032
            }
7033
            $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
7034
            if (isset($publicationDate)) {
7035
                $publicationDateString = $publicationDate->format('Y-m-d H:i:s');
7036
                $wherePublication = " AND id NOT IN (
7037
                    SELECT sfv.item_id FROM $joinTable
7038
                    WHERE
7039
                        sf.extra_field_type = $extraFieldType AND
7040
                        ((sf.variable = 'publication_start_date' AND sfv.value > '$publicationDateString' and sfv.value != '') OR
7041
                        (sf.variable = 'publication_end_date' AND sfv.value < '$publicationDateString' and sfv.value != ''))
7042
                )";
7043
            }
7044
            // Get the session list from session category and target
7045
            $sessionList = Database::select(
7046
                'id, name, access_start_date, access_end_date',
7047
                $sTable,
7048
                [
7049
                    'where' => [
7050
                        "session_category_id = ? AND id IN (
7051
                            SELECT sfv.item_id FROM $joinTable
7052
                            WHERE
7053
                                sf.extra_field_type = $extraFieldType AND
7054
                                sfv.item_id = session.id AND
7055
                                sf.variable = 'target' AND
7056
                                sfv.value = ?
7057
                        ) $wherePublication" => [$categoryId, $target],
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $wherePublication does not seem to be defined for all execution paths leading up to this point.
Loading history...
7058
                    ],
7059
                ]
7060
            );
7061
            $whereFieldVariables = [];
7062
            $whereFieldIds = [];
7063
            if (
7064
                is_array($fieldsArray) &&
7065
                count($fieldsArray) > 0
7066
            ) {
7067
                $whereParams = '?';
7068
                for ($i = 1; $i < count($fieldsArray); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
7069
                    $whereParams .= ', ?';
7070
                }
7071
                $whereFieldVariables = ' variable IN ( '.$whereParams.' )';
7072
                $whereFieldIds = 'field_id IN ( '.$whereParams.' )';
7073
            }
7074
            // Get session fields
7075
            $extraField = new ExtraFieldModel('session');
7076
            $questionMarks = substr(str_repeat('?, ', count($fieldsArray)), 0, -2);
7077
            $fieldsList = $extraField->get_all([
7078
                ' variable IN ( '.$questionMarks.' )' => $fieldsArray,
7079
            ]);
7080
            // Index session fields
7081
            foreach ($fieldsList as $field) {
7082
                $fields[$field['id']] = $field['variable'];
7083
            }
7084
            // Get session field values
7085
            $extra = new ExtraFieldValue('session');
7086
            $questionMarksFields = substr(str_repeat('?, ', count($fields)), 0, -2);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fields seems to be defined by a foreach iteration on line 7081. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
7087
            $sessionFieldValueList = $extra->get_all(['where' => ['field_id IN ( '.$questionMarksFields.' )' => array_keys($fields)]]);
7088
            // Add session fields values to session list
7089
            foreach ($sessionList as $id => &$session) {
7090
                foreach ($sessionFieldValueList as $sessionFieldValue) {
7091
                    // Match session field values to session
7092
                    if ($sessionFieldValue['item_id'] == $id) {
7093
                        // Check if session field value is set in session field list
7094
                        if (isset($fields[$sessionFieldValue['field_id']])) {
7095
                            // Avoid overwriting the session's ID field
7096
                            if ($fields[$sessionFieldValue['field_id']] != 'id') {
7097
                                $var = $fields[$sessionFieldValue['field_id']];
7098
                                $val = $sessionFieldValue['value'];
7099
                                // Assign session field value to session
7100
                                $session[$var] = $val;
7101
                            }
7102
                        }
7103
                    }
7104
                }
7105
            }
7106
        }
7107
7108
        return $sessionList;
7109
    }
7110
7111
    /**
7112
     * Return the Session Category id searched by name.
7113
     *
7114
     * @param string $categoryName Name attribute of session category used for search query
7115
     * @param bool   $force        boolean used to get even if something is wrong (e.g not unique name)
7116
     *
7117
     * @return int|array If success, return category id (int), else it will return an array
7118
     *                   with the next structure:
7119
     *                   array('error' => true, 'errorMessage' => ERROR_MESSAGE)
7120
     */
7121
    public static function getSessionCategoryIdByName($categoryName, $force = false)
7122
    {
7123
        // Start error result
7124
        $errorResult = ['error' => true, 'errorMessage' => get_lang('ThereWasAnError')];
7125
        $categoryName = Database::escape_string($categoryName);
7126
        // Check if is not empty category name
7127
        if (!empty($categoryName)) {
7128
            $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
7129
            // Get all session category with same name
7130
            $result = Database::select(
7131
                'id',
7132
                $sessionCategoryTable,
7133
                [
7134
                    'where' => [
7135
                        'name = ?' => $categoryName,
7136
                    ],
7137
                ]
7138
            );
7139
            // Check the result
7140
            if ($result < 1) {
7141
                // If not found any result, update error message
7142
                $errorResult['errorMessage'] = 'Not found any session category name '.$categoryName;
7143
            } elseif (count($result) > 1 && !$force) {
7144
                // If found more than one result and force is disabled, update error message
7145
                $errorResult['errorMessage'] = 'Found many session categories';
7146
            } elseif (count($result) == 1 || $force) {
7147
                // If found just one session category or force option is enabled
7148
7149
                return key($result);
0 ignored issues
show
Bug Best Practice introduced by
The expression return key($result) also could return the type string which is incompatible with the documented return type integer|array.
Loading history...
7150
            }
7151
        } else {
7152
            // category name is empty, update error message
7153
            $errorResult['errorMessage'] = 'Not valid category name';
7154
        }
7155
7156
        return $errorResult;
7157
    }
7158
7159
    /**
7160
     * Return all data from sessions (plus extra field, course and coach data) by category id.
7161
     *
7162
     * @param int $sessionCategoryId session category id used to search sessions
7163
     *
7164
     * @return array If success, return session list and more session related data, else it will return an array
7165
     *               with the next structure:
7166
     *               array('error' => true, 'errorMessage' => ERROR_MESSAGE)
7167
     */
7168
    public static function getSessionListAndExtraByCategoryId($sessionCategoryId)
7169
    {
7170
        // Start error result
7171
        $errorResult = [
7172
            'error' => true,
7173
            'errorMessage' => get_lang('ThereWasAnError'),
7174
        ];
7175
7176
        $sessionCategoryId = intval($sessionCategoryId);
7177
        // Check if session category id is valid
7178
        if ($sessionCategoryId > 0) {
7179
            // Get table names
7180
            $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
7181
            $sessionFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7182
            $sessionFieldValueTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7183
            $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
7184
            $userTable = Database::get_main_table(TABLE_MAIN_USER);
7185
            $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
7186
7187
            // Get all data from all sessions whit the session category specified
7188
            $sessionList = Database::select(
7189
                '*',
7190
                $sessionTable,
7191
                [
7192
                    'where' => [
7193
                        'session_category_id = ?' => $sessionCategoryId,
7194
                    ],
7195
                ]
7196
            );
7197
7198
            $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
7199
7200
            // Check if session list query had result
7201
            if (!empty($sessionList)) {
7202
                // implode all session id
7203
                $sessionIdsString = '('.implode(', ', array_keys($sessionList)).')';
7204
                // Get all field variables
7205
                $sessionFieldList = Database::select(
7206
                    'id, variable',
7207
                    $sessionFieldTable,
7208
                    ['extra_field_type = ? ' => [$extraFieldType]]
7209
                );
7210
7211
                // Get all field values
7212
                $sql = "SELECT item_id, field_id, value FROM
7213
                        $sessionFieldValueTable v INNER JOIN $sessionFieldTable f
7214
                        ON (f.id = v.field_id)
7215
                        WHERE
7216
                            item_id IN $sessionIdsString AND
7217
                            extra_field_type = $extraFieldType
7218
                ";
7219
                $result = Database::query($sql);
7220
                $sessionFieldValueList = Database::store_result($result, 'ASSOC');
7221
7222
                // Check if session field values had result
7223
                if (!empty($sessionFieldValueList)) {
7224
                    $sessionFieldValueListBySession = [];
7225
                    foreach ($sessionFieldValueList as $key => $sessionFieldValue) {
7226
                        // Create an array to index ids to session id
7227
                        $sessionFieldValueListBySession[$sessionFieldValue['item_id']][] = $key;
7228
                    }
7229
                }
7230
                // Query used to find course-coaches from sessions
7231
                $sql = "SELECT
7232
                            scu.session_id,
7233
                            c.id AS course_id,
7234
                            c.code AS course_code,
7235
                            c.title AS course_title,
7236
                            u.username AS coach_username,
7237
                            u.firstname AS coach_firstname,
7238
                            u.lastname AS coach_lastname
7239
                        FROM $courseTable c
7240
                        INNER JOIN $sessionCourseUserTable scu ON c.id = scu.c_id
7241
                        INNER JOIN $userTable u ON scu.user_id = u.user_id
7242
                        WHERE scu.status = 2 AND scu.session_id IN $sessionIdsString
7243
                        ORDER BY scu.session_id ASC ";
7244
                $res = Database::query($sql);
7245
                $sessionCourseList = Database::store_result($res, 'ASSOC');
7246
                // Check if course list had result
7247
                if (!empty($sessionCourseList)) {
7248
                    foreach ($sessionCourseList as $key => $sessionCourse) {
7249
                        // Create an array to index ids to session_id
7250
                        $sessionCourseListBySession[$sessionCourse['session_id']][] = $key;
7251
                    }
7252
                }
7253
                // Join lists
7254
                if (is_array($sessionList)) {
7255
                    foreach ($sessionList as $id => &$row) {
7256
                        if (
7257
                            !empty($sessionFieldValueListBySession) &&
7258
                            is_array($sessionFieldValueListBySession[$id])
7259
                        ) {
7260
                            // If have an index array for session extra fields, use it to join arrays
7261
                            foreach ($sessionFieldValueListBySession[$id] as $key) {
7262
                                $row['extra'][$key] = [
7263
                                    'field_name' => $sessionFieldList[$sessionFieldValueList[$key]['field_id']]['variable'],
7264
                                    'value' => $sessionFieldValueList[$key]['value'],
7265
                                ];
7266
                            }
7267
                        }
7268
                        if (
7269
                            !empty($sessionCourseListBySession) &&
7270
                            is_array($sessionCourseListBySession[$id])
7271
                        ) {
7272
                            // If have an index array for session course coach, use it to join arrays
7273
                            foreach ($sessionCourseListBySession[$id] as $key) {
7274
                                $row['course'][$key] = [
7275
                                    'course_id' => $sessionCourseList[$key]['course_id'],
7276
                                    'course_code' => $sessionCourseList[$key]['course_code'],
7277
                                    'course_title' => $sessionCourseList[$key]['course_title'],
7278
                                    'coach_username' => $sessionCourseList[$key]['coach_username'],
7279
                                    'coach_firstname' => $sessionCourseList[$key]['coach_firstname'],
7280
                                    'coach_lastname' => $sessionCourseList[$key]['coach_lastname'],
7281
                                ];
7282
                            }
7283
                        }
7284
                    }
7285
                }
7286
7287
                return $sessionList;
7288
            } else {
7289
                // Not found result, update error message
7290
                $errorResult['errorMessage'] = 'Not found any session for session category id '.$sessionCategoryId;
7291
            }
7292
        }
7293
7294
        return $errorResult;
7295
    }
7296
7297
    /**
7298
     * Return session description from session id.
7299
     *
7300
     * @param int $sessionId
7301
     *
7302
     * @return string
7303
     */
7304
    public static function getDescriptionFromSessionId($sessionId)
7305
    {
7306
        // Init variables
7307
        $sessionId = intval($sessionId);
7308
        $description = '';
7309
        // Check if session id is valid
7310
        if ($sessionId > 0) {
7311
            // Select query from session id
7312
            $rows = Database::select(
7313
                'description',
7314
                Database::get_main_table(TABLE_MAIN_SESSION),
7315
                [
7316
                    'where' => [
7317
                        'id = ?' => $sessionId,
7318
                    ],
7319
                ]
7320
            );
7321
7322
            // Check if select query result is not empty
7323
            if (!empty($rows)) {
7324
                // Get session description
7325
                $description = $rows[0]['description'];
7326
            }
7327
        }
7328
7329
        return $description;
7330
    }
7331
7332
    /**
7333
     * Get a session list filtered by name, description or any of the given extra fields.
7334
     *
7335
     * @param string $term                 The term to search
7336
     * @param array  $extraFieldsToInclude Extra fields to include in the session data
7337
     *
7338
     * @return array The list
7339
     */
7340
    public static function searchSession($term, $extraFieldsToInclude = [])
7341
    {
7342
        $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
7343
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7344
        $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7345
        $term = Database::escape_string($term);
7346
        $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
7347
        if (is_array($extraFieldsToInclude) && count($extraFieldsToInclude) > 0) {
7348
            $resultData = Database::select('*', $sTable, [
7349
                'where' => [
7350
                    "name LIKE %?% " => $term,
7351
                    " OR description LIKE %?% " => $term,
7352
                    " OR id IN (
7353
                    SELECT item_id
7354
                    FROM $sfvTable v INNER JOIN $extraFieldTable e
7355
                    ON (v.field_id = e.id)
7356
                    WHERE value LIKE %?% AND extra_field_type = $extraFieldType
7357
                ) " => $term,
7358
                ],
7359
            ]);
7360
        } else {
7361
            $resultData = Database::select('*', $sTable, [
7362
                'where' => [
7363
                    "name LIKE %?% " => $term,
7364
                    "OR description LIKE %?% " => $term,
7365
                ],
7366
            ]);
7367
7368
            return $resultData;
7369
        }
7370
7371
        foreach ($resultData as $id => &$session) {
7372
            $session['extra'] = self::getFilteredExtraFields($id, $extraFieldsToInclude);
7373
        }
7374
7375
        return $resultData;
7376
    }
7377
7378
    /**
7379
     * @param int   $sessionId
7380
     * @param array $extraFieldsToInclude
7381
     *
7382
     * @return array
7383
     */
7384
    public static function getFilteredExtraFields($sessionId, $extraFieldsToInclude = [])
7385
    {
7386
        $extraData = [];
7387
        $variables = [];
7388
        $variablePlaceHolders = [];
7389
7390
        foreach ($extraFieldsToInclude as $sessionExtraField) {
7391
            $variablePlaceHolders[] = "?";
7392
            $variables[] = Database::escape_string($sessionExtraField);
7393
        }
7394
7395
        $sessionExtraField = new ExtraFieldModel('session');
7396
        $fieldList = $sessionExtraField->get_all([
7397
            "variable IN ( ".implode(", ", $variablePlaceHolders)." ) " => $variables,
7398
        ]);
7399
7400
        $fields = [];
7401
7402
        // Index session fields
7403
        foreach ($fieldList as $field) {
7404
            $fields[$field['id']] = $field['variable'];
7405
        }
7406
7407
        // Get session field values
7408
        $extra = new ExtraFieldValue('session');
7409
        $sessionFieldValueList = $extra->get_all(
7410
            [
7411
                "field_id IN ( ".implode(", ", $variablePlaceHolders)." )" => array_keys($fields),
7412
            ]
7413
        );
7414
7415
        foreach ($sessionFieldValueList as $sessionFieldValue) {
7416
            // Match session field values to session
7417
            if ($sessionFieldValue['item_id'] != $sessionId) {
7418
                continue;
7419
            }
7420
7421
            // Check if session field value is set in session field list
7422
            if (!isset($fields[$sessionFieldValue['field_id']])) {
7423
                continue;
7424
            }
7425
7426
            $extrafieldVariable = $fields[$sessionFieldValue['field_id']];
7427
            $extrafieldValue = $sessionFieldValue['value'];
7428
7429
            $extraData[] = [
7430
                'variable' => $extrafieldVariable,
7431
                'value' => $extrafieldValue,
7432
            ];
7433
        }
7434
7435
        return $extraData;
7436
    }
7437
7438
    /**
7439
     * @param int $sessionId
7440
     *
7441
     * @return bool
7442
     */
7443
    public static function isValidId($sessionId)
7444
    {
7445
        $sessionId = intval($sessionId);
7446
        if ($sessionId > 0) {
7447
            $rows = Database::select(
7448
                'id',
7449
                Database::get_main_table(TABLE_MAIN_SESSION),
7450
                ['where' => ['id = ?' => $sessionId]]
7451
            );
7452
            if (!empty($rows)) {
7453
                return true;
7454
            }
7455
        }
7456
7457
        return false;
7458
    }
7459
7460
    /**
7461
     * Get list of sessions based on users of a group for a group admin.
7462
     *
7463
     * @param int $userId The user id
7464
     *
7465
     * @return array
7466
     */
7467
    public static function getSessionsFollowedForGroupAdmin($userId)
7468
    {
7469
        $sessionList = [];
7470
        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
7471
        $sessionUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7472
        $userGroup = new UserGroup();
7473
        $userIdList = $userGroup->getGroupUsersByUser($userId);
7474
7475
        if (empty($userIdList)) {
7476
            return [];
7477
        }
7478
7479
        $sql = "SELECT DISTINCT s.*
7480
                FROM $sessionTable s
7481
                INNER JOIN $sessionUserTable sru 
7482
                ON s.id = sru.id_session
7483
                WHERE
7484
                    (sru.id_user IN (".implode(', ', $userIdList).")
7485
                    AND sru.relation_type = 0
7486
                )";
7487
7488
        if (api_is_multiple_url_enabled()) {
7489
            $sessionAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
7490
            $accessUrlId = api_get_current_access_url_id();
7491
7492
            if ($accessUrlId != -1) {
7493
                $sql = "SELECT DISTINCT s.*
7494
                        FROM $sessionTable s
7495
                        INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
7496
                        INNER JOIN $sessionAccessUrlTable srau ON s.id = srau.session_id
7497
                        WHERE
7498
                            srau.access_url_id = $accessUrlId
7499
                            AND (
7500
                                sru.id_user IN (".implode(', ', $userIdList).")
7501
                                AND sru.relation_type = 0
7502
                            )";
7503
            }
7504
        }
7505
7506
        $result = Database::query($sql);
7507
7508
        while ($row = Database::fetch_assoc($result)) {
7509
            $sessionList[] = $row;
7510
        }
7511
7512
        return $sessionList;
7513
    }
7514
7515
    /**
7516
     * @param array $sessionInfo
7517
     *
7518
     * @return string
7519
     */
7520
    public static function getSessionVisibility($sessionInfo)
7521
    {
7522
        switch ($sessionInfo['visibility']) {
7523
            case 1:
7524
                return get_lang('ReadOnly');
7525
            case 2:
7526
               return get_lang('Visible');
7527
            case 3:
7528
                return api_ucfirst(get_lang('Invisible'));
7529
        }
7530
    }
7531
7532
    /**
7533
     * Returns a human readable string.
7534
     *
7535
     * @params array $sessionInfo An array with all the session dates
7536
     *
7537
     * @param bool $showTime
7538
     *
7539
     * @return array
7540
     */
7541
    public static function parseSessionDates($sessionInfo, $showTime = false)
7542
    {
7543
        $displayDates = self::convertSessionDateToString(
7544
            $sessionInfo['display_start_date'],
7545
            $sessionInfo['display_end_date'],
7546
            $showTime,
7547
            true
7548
        );
7549
        $accessDates = self::convertSessionDateToString(
7550
            $sessionInfo['access_start_date'],
7551
            $sessionInfo['access_end_date'],
7552
            $showTime,
7553
            true
7554
        );
7555
7556
        $coachDates = self::convertSessionDateToString(
7557
            $sessionInfo['coach_access_start_date'],
7558
            $sessionInfo['coach_access_end_date'],
7559
            $showTime,
7560
            true
7561
        );
7562
7563
        $result = [
7564
            'access' => $accessDates,
7565
            'display' => $displayDates,
7566
            'coach' => $coachDates,
7567
        ];
7568
7569
        return $result;
7570
    }
7571
7572
    /**
7573
     * @param FormValidator $form
7574
     * @param array         $sessionInfo Optional
7575
     *
7576
     * @return array
7577
     */
7578
    public static function setForm(FormValidator $form, array $sessionInfo = [])
7579
    {
7580
        $sessionId = 0;
7581
        $coachInfo = [];
7582
7583
        if (!empty($sessionInfo)) {
7584
            $sessionId = intval($sessionInfo['id']);
7585
            $coachInfo = api_get_user_info($sessionInfo['id_coach']);
7586
        }
7587
7588
        $categoriesList = self::get_all_session_category();
7589
        $userInfo = api_get_user_info();
7590
7591
        $categoriesOptions = [
7592
            '0' => get_lang('None'),
7593
        ];
7594
7595
        if ($categoriesList != false) {
7596
            foreach ($categoriesList as $categoryItem) {
7597
                $categoriesOptions[$categoryItem['id']] = $categoryItem['name'];
7598
            }
7599
        }
7600
7601
        // Database Table Definitions
7602
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
7603
7604
        $form->addText(
7605
            'name',
7606
            get_lang('SessionName'),
7607
            true,
7608
            ['maxlength' => 150, 'aria-label' => get_lang('SessionName')]
7609
        );
7610
        $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
7611
7612
        if (!api_is_platform_admin() && api_is_teacher()) {
7613
            $form->addElement(
7614
                'select',
7615
                'coach_username',
7616
                get_lang('CoachName'),
7617
                [api_get_user_id() => $userInfo['complete_name']],
7618
                [
7619
                    'id' => 'coach_username',
7620
                    'style' => 'width:370px;',
7621
                ]
7622
            );
7623
        } else {
7624
            $sql = "SELECT COUNT(1) FROM $tbl_user WHERE status = 1";
7625
            $rs = Database::query($sql);
7626
            $countUsers = Database::result($rs, 0, 0);
7627
7628
            if (intval($countUsers) < 50) {
7629
                $orderClause = "ORDER BY ";
7630
                $orderClause .= api_sort_by_first_name() ? "firstname, lastname, username" : "lastname, firstname, username";
7631
7632
                $sql = "SELECT user_id, lastname, firstname, username
7633
                        FROM $tbl_user
7634
                        WHERE status = '1' ".
7635
                        $orderClause;
7636
7637
                if (api_is_multiple_url_enabled()) {
7638
                    $userRelAccessUrlTable = Database::get_main_table(
7639
                        TABLE_MAIN_ACCESS_URL_REL_USER
7640
                    );
7641
                    $accessUrlId = api_get_current_access_url_id();
7642
7643
                    if ($accessUrlId != -1) {
7644
                        $sql = "SELECT user.user_id, username, lastname, firstname
7645
                        FROM $tbl_user user
7646
                        INNER JOIN $userRelAccessUrlTable url_user
7647
                        ON (url_user.user_id = user.user_id)
7648
                        WHERE
7649
                            access_url_id = $accessUrlId AND
7650
                            status = 1 "
7651
                            .$orderClause;
7652
                    }
7653
                }
7654
7655
                $result = Database::query($sql);
7656
                $coachesList = Database::store_result($result);
7657
7658
                $coachesOptions = [];
7659
                foreach ($coachesList as $coachItem) {
7660
                    $coachesOptions[$coachItem['user_id']] =
7661
                        api_get_person_name($coachItem['firstname'], $coachItem['lastname']).' ('.$coachItem['username'].')';
7662
                }
7663
7664
                $form->addElement(
7665
                    'select',
7666
                    'coach_username',
7667
                    get_lang('CoachName'),
7668
                    $coachesOptions,
7669
                    [
7670
                        'id' => 'coach_username',
7671
                        'style' => 'width:370px;',
7672
                    ]
7673
                );
7674
            } else {
7675
                $form->addElement(
7676
                    'select_ajax',
7677
                    'coach_username',
7678
                    get_lang('CoachName'),
7679
                    $coachInfo ? [$coachInfo['id'] => $coachInfo['complete_name_with_username']] : [],
7680
                    [
7681
                        'url' => api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=search_general_coach',
7682
                        'width' => '100%',
7683
                        'id' => 'coach_username',
7684
                    ]
7685
                );
7686
            }
7687
        }
7688
7689
        $form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required');
7690
        $form->addHtml('<div id="ajax_list_coachs"></div>');
7691
7692
        $form->addButtonAdvancedSettings('advanced_params');
7693
        $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
7694
7695
        if (empty($sessionId)) {
7696
            $sessions = SessionManager::get_sessions_admin();
7697
            $sessionList = [];
7698
            $sessionList[] = '';
7699
            foreach ($sessions as $session) {
7700
                $sessionList[$session['id']] = strip_tags($session['name']);
7701
            }
7702
7703
            $form->addSelect(
7704
                'session_template',
7705
                get_lang('SessionTemplate'),
7706
                $sessionList,
7707
                ['id' => 'system_template']
7708
            );
7709
        }
7710
7711
        $form->addSelect(
7712
            'session_category',
7713
            get_lang('SessionCategory'),
7714
            $categoriesOptions,
7715
            [
7716
                'id' => 'session_category',
7717
            ]
7718
        );
7719
7720
        $form->addHtmlEditor(
7721
            'description',
7722
            get_lang('Description'),
7723
            false,
7724
            false,
7725
            [
7726
                'ToolbarSet' => 'Minimal',
7727
            ]
7728
        );
7729
7730
        $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'));
7731
7732
        $visibilityGroup = [];
7733
        $visibilityGroup[] = $form->createElement('select', 'session_visibility', null, [
7734
            SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
7735
            SESSION_VISIBLE => get_lang('SessionAccessible'),
7736
            SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible')),
7737
        ]);
7738
        $form->addGroup(
7739
            $visibilityGroup,
7740
            'visibility_group',
7741
            get_lang('SessionVisibility'),
7742
            null,
7743
            false
7744
        );
7745
7746
        $options = [
7747
            0 => get_lang('ByDuration'),
7748
            1 => get_lang('ByDates'),
7749
        ];
7750
7751
        $form->addSelect('access', get_lang('Access'), $options, [
7752
            'onchange' => 'accessSwitcher()',
7753
            'id' => 'access',
7754
        ]);
7755
7756
        $form->addHtml('<div id="duration_div" style="display:none">');
7757
7758
        $form->addElement(
7759
            'number',
7760
            'duration',
7761
            [
7762
                get_lang('SessionDurationTitle'),
7763
                get_lang('SessionDurationDescription'),
7764
            ],
7765
            [
7766
                'maxlength' => 50,
7767
            ]
7768
        );
7769
7770
        $form->addHtml('</div>');
7771
        $form->addHtml('<div id="date_fields" style="display:none">');
7772
7773
        // Dates
7774
        $form->addDateTimePicker(
7775
            'access_start_date',
7776
            [get_lang('SessionStartDate'), get_lang('SessionStartDateComment')],
7777
            ['id' => 'access_start_date']
7778
        );
7779
7780
        $form->addDateTimePicker(
7781
            'access_end_date',
7782
            [get_lang('SessionEndDate'), get_lang('SessionEndDateComment')],
7783
            ['id' => 'access_end_date']
7784
        );
7785
7786
        $form->addRule(
7787
            ['access_start_date', 'access_end_date'],
7788
            get_lang('StartDateMustBeBeforeTheEndDate'),
7789
            'compare_datetime_text',
7790
            '< allow_empty'
7791
        );
7792
7793
        $form->addDateTimePicker(
7794
            'display_start_date',
7795
            [
7796
                get_lang('SessionDisplayStartDate'),
7797
                get_lang('SessionDisplayStartDateComment'),
7798
            ],
7799
            ['id' => 'display_start_date']
7800
        );
7801
7802
        $form->addDateTimePicker(
7803
            'display_end_date',
7804
            [
7805
                get_lang('SessionDisplayEndDate'),
7806
                get_lang('SessionDisplayEndDateComment'),
7807
            ],
7808
            ['id' => 'display_end_date']
7809
        );
7810
7811
        $form->addRule(
7812
            ['display_start_date', 'display_end_date'],
7813
            get_lang('StartDateMustBeBeforeTheEndDate'),
7814
            'compare_datetime_text',
7815
            '< allow_empty'
7816
        );
7817
7818
        $form->addDateTimePicker(
7819
            'coach_access_start_date',
7820
            [
7821
                get_lang('SessionCoachStartDate'),
7822
                get_lang('SessionCoachStartDateComment'),
7823
            ],
7824
            ['id' => 'coach_access_start_date']
7825
        );
7826
7827
        $form->addDateTimePicker(
7828
            'coach_access_end_date',
7829
            [
7830
                get_lang('SessionCoachEndDate'),
7831
                get_lang('SessionCoachEndDateComment'),
7832
            ],
7833
            ['id' => 'coach_access_end_date']
7834
        );
7835
7836
        $form->addRule(
7837
            ['coach_access_start_date', 'coach_access_end_date'],
7838
            get_lang('StartDateMustBeBeforeTheEndDate'),
7839
            'compare_datetime_text',
7840
            '< allow_empty'
7841
        );
7842
7843
        $form->addElement('html', '</div>');
7844
7845
        $form->addCheckBox(
7846
            'send_subscription_notification',
7847
            [
7848
                get_lang('SendSubscriptionNotification'),
7849
                get_lang('SendAnEmailWhenAUserBeingSubscribed'),
7850
            ]
7851
        );
7852
7853
        // Extra fields
7854
        $extra_field = new ExtraFieldModel('session');
7855
        $extra = $extra_field->addElements($form, $sessionId);
7856
7857
        $form->addElement('html', '</div>');
7858
7859
        $js = $extra['jquery_ready_content'];
7860
7861
        return ['js' => $js];
7862
    }
7863
7864
    /**
7865
     * Gets the number of rows in the session table filtered through the given
7866
     * array of parameters.
7867
     *
7868
     * @param array Array of options/filters/keys
7869
     *
7870
     * @return int The number of rows, or false on wrong param
7871
     * @assert ('a') === false
7872
     */
7873
    public static function get_count_admin_complete($options = [])
7874
    {
7875
        if (!is_array($options)) {
7876
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
7877
        }
7878
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
7879
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
7880
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
7881
        $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
7882
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
7883
        $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7884
        $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
7885
7886
        $where = 'WHERE 1 = 1 ';
7887
        $user_id = api_get_user_id();
7888
7889
        if (api_is_session_admin() &&
7890
            api_get_setting('allow_session_admins_to_see_all_sessions') == 'false'
7891
        ) {
7892
            $where .= " WHERE s.session_admin_id = $user_id ";
7893
        }
7894
7895
        $extraFieldTables = '';
7896
        if (!empty($options['where'])) {
7897
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
7898
            $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
7899
7900
            $options['where'] = str_replace(
7901
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
7902
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
7903
                $options['where']
7904
            );
7905
7906
            $options['where'] = str_replace(
7907
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
7908
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
7909
                $options['where']
7910
            );
7911
7912
            if (!empty($options['extra'])) {
7913
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
7914
                $options['where'] = str_replace('AND', 'OR', $options['where']);
7915
7916
                foreach ($options['extra'] as $extra) {
7917
                    $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
7918
                    $extraFieldTables = "$tbl_session_field_values fv, $tbl_session_field_options fvo, ";
7919
                }
7920
            }
7921
            $where .= ' AND '.$options['where'];
7922
        }
7923
7924
        $today = api_get_utc_datetime();
7925
        $query_rows = "SELECT count(*) as total_rows, c.title as course_title, s.name,
7926
                        IF (
7927
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
7928
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
7929
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
7930
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
7931
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
7932
                        , 1, 0) as session_active
7933
                       FROM $extraFieldTables $tbl_session s
7934
                       LEFT JOIN  $tbl_session_category sc
7935
                       ON s.session_category_id = sc.id
7936
                       INNER JOIN $tbl_user u
7937
                       ON s.id_coach = u.user_id
7938
                       INNER JOIN $sessionCourseUserTable scu
7939
                       ON s.id = scu.session_id
7940
                       INNER JOIN $courseTable c
7941
                       ON c.id = scu.c_id
7942
                       $where ";
7943
7944
        if (api_is_multiple_url_enabled()) {
7945
            $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
7946
            $access_url_id = api_get_current_access_url_id();
7947
            if ($access_url_id != -1) {
7948
                $where .= " AND ar.access_url_id = $access_url_id ";
7949
7950
                $query_rows = "SELECT count(*) as total_rows
7951
                               FROM $tbl_session s
7952
                               LEFT JOIN  $tbl_session_category sc
7953
                               ON s.session_category_id = sc.id
7954
                               INNER JOIN $tbl_user u
7955
                               ON s.id_coach = u.user_id
7956
                               INNER JOIN $table_access_url_rel_session ar
7957
                               ON ar.session_id = s.id $where ";
7958
            }
7959
        }
7960
7961
        $result = Database::query($query_rows);
7962
        $num = 0;
7963
        if (Database::num_rows($result)) {
7964
            $rows = Database::fetch_array($result);
7965
            $num = $rows['total_rows'];
7966
        }
7967
7968
        return $num;
7969
    }
7970
7971
    /**
7972
     * @param string $list_type
7973
     * @param array  $extraFields
7974
     *
7975
     * @return array
7976
     */
7977
    public static function getGridColumns(
7978
        $list_type = 'simple',
7979
        $extraFields = []
7980
    ) {
7981
        $showCount = api_get_configuration_value('session_list_show_count_users');
7982
        // Column config
7983
        $operators = ['cn', 'nc'];
7984
        $date_operators = ['gt', 'ge', 'lt', 'le'];
7985
7986
        switch ($list_type) {
7987
            case 'simple':
7988
                $columns = [
7989
                    '#',
7990
                    get_lang('Name'),
7991
                    get_lang('Category'),
7992
                    get_lang('SessionDisplayStartDate'),
7993
                    get_lang('SessionDisplayEndDate'),
7994
                    //get_lang('Coach'),
7995
                    //get_lang('Status'),
7996
                    //get_lang('CourseTitle'),
7997
                    get_lang('Visibility'),
7998
                ];
7999
8000
                $column_model = [
8001
                    [
8002
                        'name' => 'id',
8003
                        'index' => 's.id',
8004
                        'width' => '160',
8005
                        'width' => '160',
8006
                        'hidden' => 'true',
8007
                    ],
8008
                    [
8009
                        'name' => 'name',
8010
                        'index' => 's.name',
8011
                        'width' => '160',
8012
                        'align' => 'left',
8013
                        'search' => 'true',
8014
                        'searchoptions' => ['sopt' => $operators],
8015
                    ],
8016
                    [
8017
                        'name' => 'category_name',
8018
                        'index' => 'category_name',
8019
                        'width' => '40',
8020
                        'align' => 'left',
8021
                        'search' => 'true',
8022
                        'searchoptions' => ['sopt' => $operators],
8023
                    ],
8024
                    [
8025
                        'name' => 'display_start_date',
8026
                        'index' => 'display_start_date',
8027
                        'width' => '50',
8028
                        'align' => 'left',
8029
                        'search' => 'true',
8030
                        'searchoptions' => [
8031
                            'dataInit' => 'date_pick_today',
8032
                            'sopt' => $date_operators,
8033
                        ],
8034
                    ],
8035
                    [
8036
                        'name' => 'display_end_date',
8037
                        'index' => 'display_end_date',
8038
                        'width' => '50',
8039
                        'align' => 'left',
8040
                        'search' => 'true',
8041
                        'searchoptions' => [
8042
                            'dataInit' => 'date_pick_one_month',
8043
                            'sopt' => $date_operators,
8044
                        ],
8045
                    ],
8046
                    [
8047
                        'name' => 'visibility',
8048
                        'index' => 'visibility',
8049
                        'width' => '40',
8050
                        'align' => 'left',
8051
                        'search' => 'false',
8052
                    ],
8053
                ];
8054
8055
                if ($showCount) {
8056
                    $columns[] = get_lang('Users');
8057
                    $column_model[] = [
8058
                        'name' => 'users',
8059
                        'index' => 'users',
8060
                        'width' => '20',
8061
                        'align' => 'left',
8062
                        'search' => 'false',
8063
                    ];
8064
                }
8065
                break;
8066
            case 'complete':
8067
                $columns = [
8068
                    get_lang('Name'),
8069
                    get_lang('SessionDisplayStartDate'),
8070
                    get_lang('SessionDisplayEndDate'),
8071
                    get_lang('Coach'),
8072
                    get_lang('Status'),
8073
                    get_lang('Visibility'),
8074
                    get_lang('CourseTitle'),
8075
                ];
8076
                $column_model = [
8077
                    ['name' => 'name', 'index' => 's.name', 'width' => '200', 'align' => 'left', 'search' => 'true', 'searchoptions' => ['sopt' => $operators]],
8078
                    ['name' => 'display_start_date', 'index' => 'display_start_date', 'width' => '70', 'align' => 'left', 'search' => 'true', 'searchoptions' => ['dataInit' => 'date_pick_today', 'sopt' => $date_operators]],
8079
                    ['name' => 'display_end_date', 'index' => 'display_end_date', 'width' => '70', 'align' => 'left', 'search' => 'true', 'searchoptions' => ['dataInit' => 'date_pick_one_month', 'sopt' => $date_operators]],
8080
                    ['name' => 'coach_name', 'index' => 'coach_name', 'width' => '70', 'align' => 'left', 'search' => 'false', 'searchoptions' => ['sopt' => $operators]],
8081
                    ['name' => 'session_active', 'index' => 'session_active', 'width' => '25', 'align' => 'left', 'search' => 'true', 'stype' => 'select',
8082
                        // for the bottom bar
8083
                        'searchoptions' => [
8084
                            'defaultValue' => '1',
8085
                            'value' => '1:'.get_lang('Active').';0:'.get_lang('Inactive'), ],
8086
                        // for the top bar
8087
                        'editoptions' => ['value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive')],
8088
                    ],
8089
                    ['name' => 'visibility', 'index' => 'visibility', 'width' => '40', 'align' => 'left', 'search' => 'false'],
8090
                    ['name' => 'course_title', 'index' => 'course_title', 'width' => '50', 'hidden' => 'true', 'search' => 'true', 'searchoptions' => ['searchhidden' => 'true', 'sopt' => $operators]],
8091
                ];
8092
                break;
8093
        }
8094
8095
        if (!empty($extraFields)) {
8096
            foreach ($extraFields as $field) {
8097
                $columns[] = $field['display_text'];
8098
                $column_model[] = [
8099
                    'name' => $field['variable'],
8100
                    'index' => $field['variable'],
8101
                    'width' => '80',
8102
                    'align' => 'center',
8103
                    'search' => 'false',
8104
                ];
8105
            }
8106
        }
8107
8108
        // Inject extra session fields
8109
        $session_field = new ExtraFieldModel('session');
8110
        $rules = $session_field->getRules($columns, $column_model);
8111
8112
        $column_model[] = [
8113
            'name' => 'actions',
8114
            'index' => 'actions',
8115
            'width' => '80',
8116
            'align' => 'left',
8117
            'formatter' => 'action_formatter',
8118
            'sortable' => 'false',
8119
            'search' => 'false',
8120
        ];
8121
        $columns[] = get_lang('Actions');
8122
8123
        foreach ($column_model as $col_model) {
8124
            $simple_column_name[] = $col_model['name'];
8125
        }
8126
8127
        $return_array = [
8128
            'columns' => $columns,
8129
            'column_model' => $column_model,
8130
            'rules' => $rules,
8131
            'simple_column_name' => $simple_column_name,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $simple_column_name seems to be defined by a foreach iteration on line 8123. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
8132
        ];
8133
8134
        return $return_array;
8135
    }
8136
8137
    /**
8138
     * Converts all dates sent through the param array (given form) to correct dates with timezones.
8139
     *
8140
     * @param array The dates The same array, with times converted
8141
     * @param bool $applyFormat Whether apply the DATE_TIME_FORMAT_SHORT format for sessions
8142
     *
8143
     * @return array The same array, with times converted
8144
     */
8145
    public static function convert_dates_to_local($params, $applyFormat = false)
8146
    {
8147
        if (!is_array($params)) {
8148
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
8149
        }
8150
        $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
8151
        $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
8152
8153
        $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
8154
        $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
8155
8156
        $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
8157
        $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
8158
8159
        if ($applyFormat) {
8160
            if (isset($params['display_start_date'])) {
8161
                $params['display_start_date'] = api_format_date($params['display_start_date'], DATE_TIME_FORMAT_SHORT);
8162
            }
8163
8164
            if (isset($params['display_end_date'])) {
8165
                $params['display_end_date'] = api_format_date($params['display_end_date'], DATE_TIME_FORMAT_SHORT);
8166
            }
8167
8168
            if (isset($params['access_start_date'])) {
8169
                $params[''] = api_format_date($params['access_start_date'], DATE_TIME_FORMAT_SHORT);
8170
            }
8171
8172
            if (isset($params['access_end_date'])) {
8173
                $params['access_end_date'] = api_format_date($params['access_end_date'], DATE_TIME_FORMAT_SHORT);
8174
            }
8175
8176
            if (isset($params['coach_access_start_date'])) {
8177
                $params['coach_access_start_date'] = api_format_date($params['coach_access_start_date'], DATE_TIME_FORMAT_SHORT);
8178
            }
8179
8180
            if (isset($params['coach_access_end_date'])) {
8181
                $params['coach_access_end_date'] = api_format_date($params['coach_access_end_date'], DATE_TIME_FORMAT_SHORT);
8182
            }
8183
        }
8184
8185
        return $params;
8186
    }
8187
8188
    /**
8189
     * Gets the admin session list callback of the session/session_list.php
8190
     * page with all user/details in the right fomat.
8191
     *
8192
     * @param array $options
8193
     *
8194
     * @return array Array of rows results
8195
     * @asset ('a') === false
8196
     */
8197
    public static function get_sessions_admin_complete($options = [])
8198
    {
8199
        if (!is_array($options)) {
8200
            return false;
8201
        }
8202
8203
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
8204
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
8205
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
8206
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
8207
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
8208
8209
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
8210
        $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
8211
        $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
8212
8213
        $where = 'WHERE 1 = 1 ';
8214
        $user_id = api_get_user_id();
8215
8216
        if (!api_is_platform_admin()) {
8217
            if (api_is_session_admin() &&
8218
                api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
8219
            ) {
8220
                $where .= " AND s.session_admin_id = $user_id ";
8221
            }
8222
        }
8223
8224
        $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
8225
        if (api_is_western_name_order()) {
8226
            $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
8227
        }
8228
8229
        $today = api_get_utc_datetime();
8230
        $inject_extra_fields = null;
8231
        $extra_fields = [];
8232
        $extra_fields_info = [];
8233
8234
        //for now only sessions
8235
        $extra_field = new ExtraFieldModel('session');
8236
        $double_fields = [];
8237
        $extra_field_option = new ExtraFieldOption('session');
8238
8239
        if (isset($options['extra'])) {
8240
            $extra_fields = $options['extra'];
8241
            if (!empty($extra_fields)) {
8242
                foreach ($extra_fields as $extra) {
8243
                    $inject_extra_fields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
8244
                    if (isset($extra_fields_info[$extra['id']])) {
8245
                        $info = $extra_fields_info[$extra['id']];
8246
                    } else {
8247
                        $info = $extra_field->get($extra['id']);
8248
                        $extra_fields_info[$extra['id']] = $info;
8249
                    }
8250
8251
                    if ($info['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
0 ignored issues
show
Bug introduced by
The constant Chamilo\CoreBundle\Entit...IELD_TYPE_DOUBLE_SELECT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
8252
                        $double_fields[$info['id']] = $info;
8253
                    }
8254
                }
8255
            }
8256
        }
8257
8258
        $options_by_double = [];
8259
        foreach ($double_fields as $double) {
8260
            $my_options = $extra_field_option->get_field_options_by_field(
8261
                $double['id'],
8262
                true
8263
            );
8264
            $options_by_double['extra_'.$double['field_variable']] = $my_options;
8265
        }
8266
8267
        //sc.name as category_name,
8268
        $select = "
8269
                SELECT * FROM (
8270
                    SELECT DISTINCT
8271
                        IF (
8272
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
8273
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
8274
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
8275
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
8276
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
8277
                        , 1, 0) as session_active,
8278
                s.name,
8279
                s.nbr_courses,
8280
                s.nbr_users,
8281
                s.display_start_date,
8282
                s.display_end_date,
8283
                $coach_name,
8284
                access_start_date,
8285
                access_end_date,
8286
                s.visibility,
8287
                u.user_id,
8288
                $inject_extra_fields
8289
                c.title as course_title,
8290
                s.id ";
8291
8292
        if (!empty($options['where'])) {
8293
            if (!empty($options['extra'])) {
8294
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
8295
                $options['where'] = str_replace('AND', 'OR', $options['where']);
8296
                foreach ($options['extra'] as $extra) {
8297
                    $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
8298
                }
8299
            }
8300
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
8301
            $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
8302
            $options['where'] = str_replace(
8303
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
8304
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
8305
                $options['where']
8306
            );
8307
8308
            $options['where'] = str_replace(
8309
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
8310
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
8311
                $options['where']
8312
            );
8313
8314
            $where .= ' AND '.$options['where'];
8315
        }
8316
8317
        $limit = '';
8318
        if (!empty($options['limit'])) {
8319
            $limit = " LIMIT ".$options['limit'];
8320
        }
8321
8322
        $query = "$select FROM $tbl_session s
8323
                    LEFT JOIN $tbl_session_field_values fv
8324
                    ON (fv.item_id = s.id)
8325
                    LEFT JOIN $extraFieldTable f
8326
                    ON f.id = fv.field_id
8327
                    LEFT JOIN $tbl_session_field_options fvo
8328
                    ON (fv.field_id = fvo.field_id)
8329
                    LEFT JOIN $tbl_session_rel_course src
8330
                    ON (src.session_id = s.id)
8331
                    LEFT JOIN $tbl_course c
8332
                    ON (src.c_id = c.id)
8333
                    LEFT JOIN $tbl_session_category sc
8334
                    ON (s.session_category_id = sc.id)
8335
                    INNER JOIN $tbl_user u
8336
                    ON (s.id_coach = u.user_id) 
8337
                    $where
8338
                    $limit
8339
        ";
8340
8341
        if (api_is_multiple_url_enabled()) {
8342
            $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
8343
            $access_url_id = api_get_current_access_url_id();
8344
            if ($access_url_id != -1) {
8345
                $query = "$select
8346
                    FROM $tbl_session s
8347
                    LEFT JOIN $tbl_session_field_values fv 
8348
                    ON (fv.item_id = s.id)
8349
                    LEFT JOIN $tbl_session_field_options fvo 
8350
                    ON (fv.field_id = fvo.field_id)
8351
                    LEFT JOIN $tbl_session_rel_course src 
8352
                    ON (src.session_id = s.id)
8353
                    LEFT JOIN $tbl_course c 
8354
                    ON (src.c_id = c.id)
8355
                    LEFT JOIN $tbl_session_category sc 
8356
                    ON (s.session_category_id = sc.id)
8357
                    INNER JOIN $tbl_user u 
8358
                    ON (s.id_coach = u.user_id)
8359
                    INNER JOIN $table_access_url_rel_session ar 
8360
                    ON (ar.session_id = s.id AND ar.access_url_id = $access_url_id)
8361
                    $where
8362
                    $limit
8363
                ";
8364
            }
8365
        }
8366
8367
        $query .= ") AS session_table";
8368
8369
        if (!empty($options['order'])) {
8370
            $query .= " ORDER BY ".$options['order'];
8371
        }
8372
8373
        $result = Database::query($query);
8374
8375
        $acceptIcon = Display::return_icon(
8376
            'accept.png',
8377
            get_lang('Active'),
8378
            [],
8379
            ICON_SIZE_SMALL
8380
        );
8381
8382
        $errorIcon = Display::return_icon(
8383
            'error.png',
8384
            get_lang('Inactive'),
8385
            [],
8386
            ICON_SIZE_SMALL
8387
        );
8388
8389
        $formatted_sessions = [];
8390
        if (Database::num_rows($result)) {
8391
            $sessions = Database::store_result($result, 'ASSOC');
8392
            foreach ($sessions as $session) {
8393
                $session_id = $session['id'];
8394
                $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
8395
                $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
8396
                if ($session['session_active'] == 1) {
8397
                    $session['session_active'] = $acceptIcon;
8398
                } else {
8399
                    $session['session_active'] = $errorIcon;
8400
                }
8401
8402
                $session = self::convert_dates_to_local($session);
8403
8404
                switch ($session['visibility']) {
8405
                    case SESSION_VISIBLE_READ_ONLY: //1
8406
                        $session['visibility'] = get_lang('ReadOnly');
8407
                        break;
8408
                    case SESSION_VISIBLE:           //2
8409
                    case SESSION_AVAILABLE:         //4
8410
                        $session['visibility'] = get_lang('Visible');
8411
                        break;
8412
                    case SESSION_INVISIBLE:         //3
8413
                        $session['visibility'] = api_ucfirst(get_lang('Invisible'));
8414
                        break;
8415
                }
8416
8417
                // Cleaning double selects
8418
                foreach ($session as $key => &$value) {
8419
                    if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
8420
                        $options = explode('::', $value);
8421
                    }
8422
                    $original_key = $key;
8423
8424
                    if (strpos($key, '_second') === false) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
8425
                    } else {
8426
                        $key = str_replace('_second', '', $key);
8427
                    }
8428
8429
                    if (isset($options_by_double[$key])) {
8430
                        if (isset($options[0])) {
8431
                            if (isset($options_by_double[$key][$options[0]])) {
8432
                                if (strpos($original_key, '_second') === false) {
8433
                                    $value = $options_by_double[$key][$options[0]]['option_display_text'];
8434
                                } else {
8435
                                    $value = $options_by_double[$key][$options[1]]['option_display_text'];
8436
                                }
8437
                            }
8438
                        }
8439
                    }
8440
                }
8441
8442
                // Magic filter
8443
                if (isset($formatted_sessions[$session_id])) {
8444
                    $formatted_sessions[$session_id] = self::compareArraysToMerge(
8445
                        $formatted_sessions[$session_id],
8446
                        $session
8447
                    );
8448
                } else {
8449
                    $formatted_sessions[$session_id] = $session;
8450
                }
8451
            }
8452
        }
8453
8454
        return $formatted_sessions;
8455
    }
8456
8457
    /**
8458
     * Compare two arrays.
8459
     *
8460
     * @param array $array1
8461
     * @param array $array2
8462
     *
8463
     * @return array
8464
     */
8465
    public static function compareArraysToMerge($array1, $array2)
8466
    {
8467
        if (empty($array2)) {
8468
            return $array1;
8469
        }
8470
        foreach ($array1 as $key => $item) {
8471
            if (!isset($array1[$key])) {
8472
                //My string is empty try the other one
8473
                if (isset($array2[$key]) && !empty($array2[$key])) {
8474
                    $array1[$key] = $array2[$key];
8475
                }
8476
            }
8477
        }
8478
8479
        return $array1;
8480
    }
8481
8482
    /**
8483
     * Get link to the admin page for this session.
8484
     *
8485
     * @param int $id Session ID
8486
     *
8487
     * @return mixed URL to the admin page to manage the session, or false on error
8488
     */
8489
    public static function getAdminPath($id)
8490
    {
8491
        $id = intval($id);
8492
        $session = self::fetch($id);
8493
        if (empty($session)) {
8494
            return false;
8495
        }
8496
8497
        return api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$id;
8498
    }
8499
8500
    /**
8501
     * Get link to the user page for this session.
8502
     * If a course is provided, build the link to the course.
8503
     *
8504
     * @param int $id       Session ID
8505
     * @param int $courseId Course ID (optional) in case the link has to send straight to the course
8506
     *
8507
     * @return mixed URL to the page to use the session, or false on error
8508
     */
8509
    public static function getPath($id, $courseId = 0)
8510
    {
8511
        $id = intval($id);
8512
        $session = self::fetch($id);
8513
        if (empty($session)) {
8514
            return false;
8515
        }
8516
        if (empty($courseId)) {
8517
            return api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$id;
8518
        } else {
8519
            $courseInfo = api_get_course_info_by_id($courseId);
8520
            if ($courseInfo) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $courseInfo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
8521
                return $courseInfo['course_public_url'].'?id_session='.$id;
8522
            }
8523
        }
8524
8525
        return false;
8526
    }
8527
8528
    /**
8529
     * Return an associative array 'id_course' => [id_session1, id_session2...]
8530
     * where course id_course is in sessions id_session1, id_session2
8531
     * for course where user is coach
8532
     * i.e. coach for the course or
8533
     * main coach for a session the course is in
8534
     * for a session category (or woth no session category if empty).
8535
     *
8536
     * @param int $userId
8537
     *
8538
     * @return array
8539
     */
8540
    public static function getSessionCourseForUser($userId)
8541
    {
8542
        // list of COURSES where user is COURSE session coach
8543
        $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
8544
        // list of courses where user is MAIN session coach
8545
        $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
8546
        // merge these 2 array
8547
        $listResCourseSession = $listCourseCourseCoachSession;
8548
        foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
8549
            if (isset($listResCourseSession[$courseId2])) {
8550
                // if sessionId array exists for this course
8551
                // same courseId, merge the list of session
8552
                foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
8553
                    if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
8554
                        $listResCourseSession[$courseId2][] = $sessionId2;
8555
                    }
8556
                }
8557
            } else {
8558
                $listResCourseSession[$courseId2] = $listSessionId2;
8559
            }
8560
        }
8561
8562
        return $listResCourseSession;
8563
    }
8564
8565
    /**
8566
     * Return an associative array 'id_course' => [id_session1, id_session2...]
8567
     * where course id_course is in sessions id_session1, id_session2.
8568
     *
8569
     * @param $userId
8570
     *
8571
     * @return array
8572
     */
8573
    public static function getCoursesForCourseSessionCoach($userId)
8574
    {
8575
        $listResCourseSession = [];
8576
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
8577
        $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
8578
8579
        $sql = "SELECT session_id, c_id, c.id
8580
                FROM $tblSessionRelCourseRelUser srcru
8581
                LEFT JOIN $tblCourse c
8582
                ON c.id = srcru.c_id
8583
                WHERE
8584
                    srcru.user_id =".intval($userId)." AND
8585
                    srcru.status = 2";
8586
8587
        $res = Database::query($sql);
8588
8589
        while ($data = Database::fetch_assoc($res)) {
8590
            if (api_get_session_visibility($data['session_id'])) {
8591
                if (!isset($listResCourseSession[$data['id']])) {
8592
                    $listResCourseSession[$data['id']] = [];
8593
                }
8594
                $listResCourseSession[$data['id']][] = $data['session_id'];
8595
            }
8596
        }
8597
8598
        return $listResCourseSession;
8599
    }
8600
8601
    /**
8602
     * Return an associative array 'id_course' => [id_session1, id_session2...]
8603
     * where course id_course is in sessions id_session1, id_session2.
8604
     *
8605
     * @param $userId
8606
     *
8607
     * @return array
8608
     */
8609
    public static function getCoursesForMainSessionCoach($userId)
8610
    {
8611
        $listResCourseSession = [];
8612
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
8613
8614
        // list of SESSION where user is session coach
8615
        $sql = "SELECT id FROM $tblSession
8616
                WHERE id_coach = ".intval($userId);
8617
        $res = Database::query($sql);
8618
8619
        while ($data = Database::fetch_assoc($res)) {
8620
            $sessionId = $data['id'];
8621
            $listCoursesInSession = self::getCoursesInSession($sessionId);
8622
            foreach ($listCoursesInSession as $i => $courseId) {
8623
                if (api_get_session_visibility($sessionId)) {
8624
                    if (!isset($listResCourseSession[$courseId])) {
8625
                        $listResCourseSession[$courseId] = [];
8626
                    }
8627
                    $listResCourseSession[$courseId][] = $sessionId;
8628
                }
8629
            }
8630
        }
8631
8632
        return $listResCourseSession;
8633
    }
8634
8635
    /**
8636
     * Return an array of course_id used in session $sessionId.
8637
     *
8638
     * @param $sessionId
8639
     *
8640
     * @return array
8641
     */
8642
    public static function getCoursesInSession($sessionId)
8643
    {
8644
        if (empty($sessionId)) {
8645
            return [];
8646
        }
8647
8648
        $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
8649
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
8650
8651
        // list of course in this session
8652
        $sql = "SELECT session_id, c.id
8653
                FROM $tblSessionRelCourse src
8654
                LEFT JOIN $tblCourse c
8655
                ON c.id = src.c_id
8656
                WHERE session_id = ".intval($sessionId);
8657
        $res = Database::query($sql);
8658
8659
        $listResultsCourseId = [];
8660
        while ($data = Database::fetch_assoc($res)) {
8661
            $listResultsCourseId[] = $data['id'];
8662
        }
8663
8664
        return $listResultsCourseId;
8665
    }
8666
8667
    /**
8668
     * Return an array of courses in session for user
8669
     * and for each courses the list of session that use this course for user.
8670
     *
8671
     * [0] => array
8672
     *      userCatId
8673
     *      userCatTitle
8674
     *      courseInUserCatList
8675
     *          [0] => array
8676
     *              courseId
8677
     *              title
8678
     *              courseCode
8679
     *              sessionCatList
8680
     *                  [0] => array
8681
     *                      catSessionId
8682
     *                      catSessionName
8683
     *                      sessionList
8684
     *                          [0] => array
8685
     *                              sessionId
8686
     *                              sessionName
8687
     *
8688
     * @param int $userId
8689
     *
8690
     * @return array
8691
     */
8692
    public static function getNamedSessionCourseForCoach($userId)
8693
    {
8694
        $listResults = [];
8695
        $listCourseSession = self::getSessionCourseForUser($userId);
8696
        foreach ($listCourseSession as $courseId => $listSessionId) {
8697
            // Course info
8698
            $courseInfo = api_get_course_info_by_id($courseId);
8699
            $listOneCourse = [];
8700
            $listOneCourse['courseId'] = $courseId;
8701
            $listOneCourse['title'] = $courseInfo['title'];
8702
            //$listOneCourse['courseCode'] = $courseInfo['code'];
8703
            $listOneCourse['course'] = $courseInfo;
8704
            $listOneCourse['sessionCatList'] = [];
8705
            $listCat = [];
8706
            foreach ($listSessionId as $i => $sessionId) {
8707
                // here we got all session for this course
8708
                // lets check there session categories
8709
                $sessionInfo = self::fetch($sessionId);
8710
                $catId = $sessionInfo['session_category_id'];
8711
                if (!isset($listCat[$catId])) {
8712
                    $listCatInfo = self::get_session_category($catId);
8713
                    $listCat[$catId] = [];
8714
                    $listCat[$catId]['catSessionId'] = $catId;
8715
                    $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
8716
                    $listCat[$catId]['sessionList'] = [];
8717
                }
8718
                $listSessionInfo = self::fetch($sessionId);
8719
                $listSessionIdName = [
8720
                    "sessionId" => $sessionId,
8721
                    "sessionName" => $listSessionInfo['name'],
8722
                ];
8723
                $listCat[$catId]['sessionList'][] = $listSessionIdName;
8724
            }
8725
            // sort $listCat by catSessionName
8726
            usort($listCat, 'self::compareBySessionName');
8727
            // in each catSession sort sessionList by sessionName
8728
            foreach ($listCat as $i => $listCatSessionInfo) {
8729
                $listSessionList = $listCatSessionInfo['sessionList'];
8730
                usort($listSessionList, 'self::compareCatSessionInfo');
8731
                $listCat[$i]['sessionList'] = $listSessionList;
8732
            }
8733
8734
            $listOneCourse['sessionCatList'] = $listCat;
8735
8736
            // user course category
8737
            $courseCategory = CourseManager::getUserCourseCategoryForCourse(
8738
                $userId,
8739
                $courseId
8740
            );
8741
8742
            $userCatTitle = '';
8743
            $userCatId = 0;
8744
            if ($courseCategory) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $courseCategory of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
8745
                $userCatId = $courseCategory['user_course_cat'];
8746
                $userCatTitle = $courseCategory['title'];
8747
            }
8748
8749
            $listResults[$userCatId]['courseInUserCategoryId'] = $userCatId;
8750
            $listResults[$userCatId]['courseInUserCategoryTitle'] = $userCatTitle;
8751
            $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
8752
        }
8753
8754
        // sort by user course cat
8755
        uasort($listResults, 'self::compareByUserCourseCat');
8756
8757
        // sort by course title
8758
        foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
8759
            $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
8760
            uasort($courseInUserCatList, 'self::compareByCourse');
8761
            $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
8762
        }
8763
8764
        return $listResults;
8765
    }
8766
8767
    /**
8768
     * Return HTML code for displaying session_course_for_coach.
8769
     *
8770
     * @param $userId
8771
     *
8772
     * @return string
8773
     */
8774
    public static function getHtmlNamedSessionCourseForCoach($userId)
8775
    {
8776
        $htmlRes = '';
8777
        $listInfo = self::getNamedSessionCourseForCoach($userId);
8778
        foreach ($listInfo as $i => $listCoursesInfo) {
8779
            $courseInfo = $listCoursesInfo['course'];
8780
            $courseCode = $listCoursesInfo['course']['code'];
8781
8782
            $listParamsCourse = [];
8783
            $listParamsCourse['icon'] = '<div style="float:left">
8784
                <input style="border:none;" type="button" onclick="$(\'#course-'.$courseCode.'\').toggle(\'fast\')" value="+" /></div>'.
8785
                Display::return_icon('blackboard.png', $courseInfo['title'], [], ICON_SIZE_LARGE);
8786
            $listParamsCourse['link'] = '';
8787
            $listParamsCourse['title'] = Display::tag(
8788
                'a',
8789
                $courseInfo['title'],
8790
                ['href' => $listParamsCourse['link']]
8791
            );
8792
            $htmlCourse = '<div class="well" style="border-color:#27587D">'.
8793
                CourseManager::course_item_html($listParamsCourse, true);
0 ignored issues
show
Bug introduced by
The method course_item_html() does not exist on CourseManager. Did you maybe mean course_item_html_no_icon()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

8793
                CourseManager::/** @scrutinizer ignore-call */ 
8794
                               course_item_html($listParamsCourse, true);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
8794
            // for each category of session
8795
            $htmlCatSessions = '';
8796
            foreach ($listCoursesInfo['sessionCatList'] as $j => $listCatSessionsInfo) {
8797
                // we got an array of session categories
8798
                $catSessionId = $listCoursesInfo['sessionCatList'][$j]['catSessionId'];
8799
                $catSessionName = $listCoursesInfo['sessionCatList'][$j]['catSessionName'];
8800
8801
                $listParamsCatSession['icon'] = Display::return_icon('folder_blue.png', $catSessionName, [], ICON_SIZE_LARGE);
8802
                $listParamsCatSession['link'] = '';
8803
                $listParamsCatSession['title'] = $catSessionName;
8804
8805
                $marginShift = 20;
8806
                if ($catSessionName != '') {
8807
                    $htmlCatSessions .= '<div style="margin-left:'.$marginShift.'px;">'.
8808
                        CourseManager::course_item_html($listParamsCatSession, true).'</div>';
8809
                    $marginShift = 40;
8810
                }
8811
8812
                // for each sessions
8813
                $listCatSessionSessionList = $listCoursesInfo['sessionCatList'][$j]['sessionList'];
8814
                $htmlSession = '';
8815
                foreach ($listCatSessionSessionList as $k => $listSessionInfo) {
8816
                    // we got an array of session info
8817
                    $sessionId = $listSessionInfo['sessionId'];
8818
                    $sessionName = $listSessionInfo['sessionName'];
8819
8820
                    $listParamsSession['icon'] = Display::return_icon('blackboard_blue.png', $sessionName, [], ICON_SIZE_LARGE);
8821
                    $listParamsSession['link'] = '';
8822
                    $linkToCourseSession = $courseInfo['course_public_url'].'?id_session='.$sessionId;
8823
                    $listParamsSession['title'] =
8824
                        $sessionName.'<div style="font-weight:normal; font-style:italic">
8825
                            <a href="'.$linkToCourseSession.'">'.get_lang('GoToCourseInsideSession').'</a>
8826
                            </div>';
8827
                    $htmlSession .= '<div style="margin-left:'.$marginShift.'px;">'.
8828
                        CourseManager::course_item_html($listParamsSession, true).'</div>';
8829
                }
8830
                $htmlCatSessions .= $htmlSession;
8831
            }
8832
            $htmlRes .= $htmlCourse.'<div style="display:none" id="course-'.$courseCode.'">'.$htmlCatSessions.'</div></div>';
8833
        }
8834
8835
        return $htmlRes;
8836
    }
8837
8838
    /**
8839
     * @param int $userId
8840
     * @param int $courseId
8841
     *
8842
     * @return array
8843
     */
8844
    public static function searchCourseInSessionsFromUser($userId, $courseId)
8845
    {
8846
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
8847
        $userId = (int) $userId;
8848
        $courseId = (int) $courseId;
8849
        if (empty($userId) || empty($courseId)) {
8850
            return [];
8851
        }
8852
8853
        $sql = "SELECT * FROM $table 
8854
                WHERE c_id = $courseId AND user_id = $userId";
8855
        $result = Database::query($sql);
8856
8857
        return Database::store_result($result, 'ASSOC');
8858
    }
8859
8860
    /**
8861
     * Subscribe and redirect to session after inscription.
8862
     */
8863
    public static function redirectToSession()
8864
    {
8865
        $sessionId = ChamiloSession::read('session_redirect');
8866
        $onlyOneCourseSessionToRedirect = ChamiloSession::read('only_one_course_session_redirect');
8867
        if ($sessionId) {
8868
            $sessionInfo = api_get_session_info($sessionId);
8869
            if (!empty($sessionInfo)) {
8870
                $userId = api_get_user_id();
8871
                $response = self::isUserSubscribedAsStudent($sessionId, $userId);
8872
                if ($response) {
8873
                    $urlToRedirect = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
8874
                    if (!empty($onlyOneCourseSessionToRedirect)) {
8875
                        $urlToRedirect = api_get_path(WEB_PATH).'courses/'.$onlyOneCourseSessionToRedirect.'/index.php?id_session='.$sessionId;
8876
                    }
8877
8878
                    header('Location: '.$urlToRedirect);
8879
                    exit;
8880
                }
8881
            }
8882
        }
8883
    }
8884
8885
    /**
8886
     * @param Course  $course
8887
     * @param Session $session
8888
     *
8889
     * @return int
8890
     */
8891
    public static function getCountUsersInCourseSession(
8892
        Course $course,
8893
        Session $session
8894
    ) {
8895
        return Database::getManager()
8896
            ->createQuery("
8897
                SELECT COUNT(scu)
8898
                FROM ChamiloCoreBundle:SessionRelCourseRelUser scu
8899
                INNER JOIN ChamiloCoreBundle:SessionRelUser su
8900
                    WITH scu.user = su.user
8901
                    AND scu.session = su.session
8902
                WHERE 
8903
                    scu.course = :course AND 
8904
                    su.relationType <> :relationType AND 
8905
                    scu.session = :session
8906
            ")
8907
            ->setParameters([
8908
                'course' => $course->getId(),
8909
                'relationType' => SESSION_RELATION_TYPE_RRHH,
8910
                'session' => $session->getId(),
8911
            ])
8912
            ->getSingleScalarResult();
8913
    }
8914
8915
    /**
8916
     * Get course IDs where user in not subscribed in session.
8917
     *
8918
     * @param User    $user
8919
     * @param Session $session
8920
     *
8921
     * @return array
8922
     */
8923
    public static function getAvoidedCoursesInSession(User $user, Session $session)
8924
    {
8925
        $courseIds = [];
8926
8927
        /** @var SessionRelCourse $sessionCourse */
8928
        foreach ($session->getCourses() as $sessionCourse) {
8929
            /** @var Course $course */
8930
            $course = $sessionCourse->getCourse();
8931
8932
            if ($session->getUserInCourse($user, $course)->count()) {
0 ignored issues
show
Bug introduced by
The method count() does not exist on Chamilo\CoreBundle\Entity\Session. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

8932
            if ($session->getUserInCourse($user, $course)->/** @scrutinizer ignore-call */ count()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
8933
                continue;
8934
            }
8935
8936
            $courseIds[] = $course->getId();
8937
        }
8938
8939
        return $courseIds;
8940
    }
8941
8942
    /**
8943
     * @param int $id
8944
     *
8945
     * @return bool
8946
     */
8947
    private static function allowed($id)
8948
    {
8949
        $sessionInfo = self::fetch($id);
8950
8951
        if (empty($sessionInfo)) {
8952
            return false;
8953
        }
8954
8955
        if (api_is_platform_admin()) {
8956
            return true;
8957
        }
8958
8959
        $userId = api_get_user_id();
8960
8961
        if (api_is_session_admin() &&
8962
            api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
8963
        ) {
8964
            if ($sessionInfo['session_admin_id'] != $userId) {
8965
                return false;
8966
            }
8967
        }
8968
8969
        if (api_is_teacher() &&
8970
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
8971
        ) {
8972
            if ($sessionInfo['id_coach'] != $userId) {
8973
                return false;
8974
            }
8975
        }
8976
8977
        return true;
8978
    }
8979
8980
    /**
8981
     * Add classes (by their names) to a session.
8982
     *
8983
     * @param int   $sessionId
8984
     * @param array $classesNames
8985
     * @param bool  $deleteClassSessions Optional. Empty the session list for the usergroup (class)
8986
     */
8987
    private static function addClassesByName($sessionId, $classesNames, $deleteClassSessions = true)
8988
    {
8989
        if (!$classesNames) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $classesNames of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
8990
            return;
8991
        }
8992
8993
        $usergroup = new UserGroup();
8994
8995
        foreach ($classesNames as $className) {
8996
            if (empty($className)) {
8997
                continue;
8998
            }
8999
9000
            $usergroup->subscribe_sessions_to_usergroup(
9001
                $usergroup->get_id_by_name($className),
9002
                [$sessionId],
9003
                $deleteClassSessions
9004
            );
9005
        }
9006
    }
9007
9008
    /**
9009
     * Converts "start date" and "end date" to "From start date to end date" string.
9010
     *
9011
     * @param string $startDate
9012
     * @param string $endDate
9013
     * @param bool   $showTime
9014
     * @param bool   $dateHuman
9015
     *
9016
     * @return string
9017
     */
9018
    private static function convertSessionDateToString($startDate, $endDate, $showTime, $dateHuman)
9019
    {
9020
        // api_get_local_time returns empty if date is invalid like 0000-00-00 00:00:00
9021
        $startDateToLocal = api_get_local_time(
9022
            $startDate,
9023
            null,
9024
            null,
9025
            true,
9026
            $showTime,
9027
            $dateHuman
9028
        );
9029
        $endDateToLocal = api_get_local_time(
9030
            $endDate,
9031
            null,
9032
            null,
9033
            true,
9034
            $showTime,
9035
            $dateHuman
9036
        );
9037
9038
        $result = '';
9039
        if (!empty($startDateToLocal) && !empty($endDateToLocal)) {
9040
            $result = sprintf(
9041
                get_lang('FromDateXToDateY'),
9042
                api_format_date($startDateToLocal, DATE_TIME_FORMAT_LONG_24H),
9043
                api_format_date($endDateToLocal, DATE_TIME_FORMAT_LONG_24H)
9044
            );
9045
        } else {
9046
            if (!empty($startDateToLocal)) {
9047
                $result = get_lang('From').' '.api_format_date($startDateToLocal, DATE_TIME_FORMAT_LONG_24H);
9048
            }
9049
            if (!empty($endDateToLocal)) {
9050
                $result = get_lang('Until').' '.api_format_date($endDateToLocal, DATE_TIME_FORMAT_LONG_24H);
9051
            }
9052
        }
9053
        if (empty($result)) {
9054
            $result = get_lang('NoTimeLimits');
9055
        }
9056
9057
        return $result;
9058
    }
9059
9060
    /**
9061
     * @param array $listA
9062
     * @param array $listB
9063
     *
9064
     * @return int
9065
     */
9066
    private static function compareCatSessionInfo($listA, $listB)
9067
    {
9068
        if ($listA['sessionName'] == $listB['sessionName']) {
9069
            return 0;
9070
        } elseif ($listA['sessionName'] > $listB['sessionName']) {
9071
            return 1;
9072
        } else {
9073
            return -1;
9074
        }
9075
    }
9076
9077
    /**
9078
     * @param array $listA
9079
     * @param array $listB
9080
     *
9081
     * @return int
9082
     */
9083
    private static function compareBySessionName($listA, $listB)
9084
    {
9085
        if ($listB['catSessionName'] == '') {
9086
            return -1;
9087
        } elseif ($listA['catSessionName'] == '') {
9088
            return 1;
9089
        } elseif ($listA['catSessionName'] == $listB['catSessionName']) {
9090
            return 0;
9091
        } elseif ($listA['catSessionName'] > $listB['catSessionName']) {
9092
            return 1;
9093
        } else {
9094
            return -1;
9095
        }
9096
    }
9097
9098
    /**
9099
     * @param array $listA
9100
     * @param array $listB
9101
     *
9102
     * @return int
9103
     */
9104
    private static function compareByUserCourseCat($listA, $listB)
9105
    {
9106
        if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
9107
            return 0;
9108
        } elseif ($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
9109
            return 1;
9110
        } else {
9111
            return -1;
9112
        }
9113
    }
9114
9115
    /**
9116
     * @param array $listA
9117
     * @param array $listB
9118
     *
9119
     * @return int
9120
     */
9121
    private static function compareByCourse($listA, $listB)
9122
    {
9123
        if ($listA['title'] == $listB['title']) {
9124
            return 0;
9125
        } elseif ($listA['title'] > $listB['title']) {
9126
            return 1;
9127
        } else {
9128
            return -1;
9129
        }
9130
    }
9131
}
9132