Passed
Push — master ( c35cf1...bf9907 )
by Yannick
10:24
created

dateDiffInWeeks()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 4
nop 2
dl 0
loc 17
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\ExtraFieldSavedSearch;
6
use Chamilo\CoreBundle\Enums\ActionIcon;
7
use ChamiloSession as Session;
8
9
$cidReset = true;
10
11
require_once __DIR__.'/../inc/global.inc.php';
12
13
api_block_anonymous_users();
14
15
if ('false' === api_get_setting('session.allow_search_diagnostic')) {
16
    api_not_allowed();
17
}
18
19
$allowToSee = api_is_drh() || api_is_student_boss() || api_is_platform_admin();
20
21
if (false === $allowToSee) {
22
    api_not_allowed(true);
23
}
24
$userId = api_get_user_id();
25
$userInfo = api_get_user_info();
26
27
$userToLoad = isset($_GET['user_id']) ? (int) $_GET['user_id'] : 0;
28
29
$userToLoadInfo = [];
30
if ($userToLoad) {
31
    $userToLoadInfo = api_get_user_info($userToLoad);
32
}
33
$action = $_GET['action'] ?? '';
34
35
switch ($action) {
36
    case 'subscribe_user':
37
        $sessionId = isset($_GET['session_id']) ? $_GET['session_id'] : '';
38
        SessionManager::subscribeUsersToSession(
39
            $sessionId,
40
            [$userToLoad],
41
            SESSION_VISIBLE_READ_ONLY,
42
            false
43
        );
44
        Display::addFlash(Display::return_message(get_lang('The user has been added')));
45
        header("Location: ".api_get_self().'?user_id='.$userToLoad.'#session-table');
46
        break;
47
    case 'unsubscribe_user':
48
        $sessionId = isset($_GET['session_id']) ? $_GET['session_id'] : '';
49
        SessionManager::unsubscribe_user_from_session($sessionId, $userToLoad);
50
        Display::addFlash(Display::return_message(get_lang('User is now unsubscribed')));
51
        header("Location: ".api_get_self().'?user_id='.$userToLoad.'#session-table');
52
        break;
53
}
54
55
$em = Database::getManager();
56
57
$formSearch = new FormValidator('load', 'get', api_get_self());
58
$formSearch->addHeader(get_lang('Load diagnosis'));
59
if (!empty($userInfo)) {
60
    $users = [];
61
    switch ($userInfo['status']) {
62
        case DRH:
63
            $users = UserManager::get_users_followed_by_drh(
64
                $userId,
65
                0,
66
                false,
67
                false,
68
                false,
69
                null,
70
                null,
71
                null,
72
                null,
73
                1
74
            );
75
            break;
76
        case STUDENT_BOSS:
77
            $users = UserManager::getUsersFollowedByStudentBoss(
78
                $userId,
79
                0,
80
                false,
81
                false,
82
                false,
83
                null,
84
                null,
85
                null,
86
                null,
87
                1
88
            );
89
            break;
90
    }
91
92
    // Allow access for admins.
93
    if (empty($users) && api_is_platform_admin()) {
94
        $users[] = $userToLoadInfo;
95
    }
96
97
    if (!empty($users)) {
98
        $userList = [];
99
        foreach ($users as $user) {
100
            if (empty($user)) {
101
                continue;
102
            }
103
            $userList[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
104
        }
105
        $formSearch->addSelect('user_id', get_lang('User'), $userList);
106
    }
107
}
108
109
$items = [];
110
if ($userToLoad) {
111
    $formSearch->setDefaults(['user_id' => $userToLoad]);
112
    $items = $em->getRepository(ExtraFieldSavedSearch::class)->findBy(['user' => api_get_user_entity($userToLoad)]);
113
    if (empty($items)) {
114
        Display::addFlash(Display::return_message('No data found'));
115
    }
116
}
117
118
$formSearch->addButtonSearch(get_lang('Show diagnosis'), 'save');
119
120
$form = new FormValidator('search', 'post', api_get_self().'?user_id='.$userToLoad.'#session-table');
121
$form->addHeader(get_lang('Diagnosis'));
122
$form->addHidden('user_id', $userToLoad);
123
124
$defaults = [];
125
$tagsData = [];
126
if (!empty($items)) {
127
    /** @var ExtraFieldSavedSearch $item */
128
    foreach ($items as $item) {
129
        $variable = 'extra_'.$item->getField()->getVariable();
130
        if (ExtraField::FIELD_TYPE_TAG === $item->getField()->getValueType()) {
131
            $tagsData[$variable] = $item->getValue();
132
        }
133
        $defaults[$variable] = $item->getValue();
134
    }
135
}
136
137
if (isset($defaults['extra_access_start_date']) && isset($defaults['extra_access_start_date'][0])) {
138
    $defaults['extra_access_start_date'] = $defaults['extra_access_start_date'][0];
139
}
140
141
if (isset($defaults['extra_access_end_date']) && isset($defaults['extra_access_end_date'][0])) {
142
    $defaults['extra_access_end_date'] = $defaults['extra_access_end_date'][0];
143
}
144
145
$extraField = new ExtraField('session');
146
$extraFieldValue = new ExtraFieldValue('session');
147
$extraFieldValueUser = new ExtraFieldValue('user');
148
149
$wantStage = $extraFieldValueUser->get_values_by_handler_and_field_variable(api_get_user_id(), 'filiere_want_stage');
150
$defaultValueStatus = '';
151
$hide = true;
152
if ($wantStage) {
153
    $hide = ('yes' === $wantStage['field_value'] || '' === $wantStage['field_value']);
154
}
155
156
$defaultValueStatus = 'extraFiliere.hide()';
157
if (false === $hide) {
158
    $defaultValueStatus = '';
159
}
160
161
$theme = 'theme_fr';
162
163
$lang = $defaultLangCible = api_get_language_isocode();
164
165
if ($userToLoadInfo) {
166
    $langInfo = api_get_language_from_iso($userToLoadInfo['locale']);
167
    $lang = $langInfo->getEnglishName();
168
    $targetLanguageInfo = $extraFieldValueUser->get_values_by_handler_and_field_variable(
169
        $userToLoad,
170
        'langue_cible'
171
    );
172
173
    if (!empty($targetLanguageInfo)) {
174
        $defaultLangCible = $targetLanguageInfo['value'];
175
    }
176
177
    switch ($lang) {
178
        case 'italian':
179
            $theme = 'theme_it';
180
            break;
181
        case 'polish':
182
            $theme = 'theme_pl';
183
            break;
184
        case 'spanish':
185
            $theme = 'theme_es';
186
            break;
187
        case 'french2':
188
        case 'french':
189
            $theme = 'theme_fr';
190
            break;
191
        case 'german2':
192
        case 'german':
193
            $theme = 'theme_de';
194
            break;
195
    }
196
}
197
198
$jqueryExtra = '';
199
$extraFieldUser = new ExtraField('user');
200
201
$userForm = new FormValidator('user_form', 'post', api_get_self());
202
203
$userForm->addStartPanel('filiere', get_lang('I would like to choose a sector'));
204
$userForm->addHtml('<p class="text-info">'.get_lang('The platform offers specialized course session. Your answers will allow you to access the island corresponding to your field if it exists.<br><br>Check one or more answers or fill in the blank.').'</p>');
205
206
$fieldsToShow = [
207
    'statusocial',
208
    'filiere_user',
209
    'filiereprecision',
210
    'filiere_want_stage',
211
];
212
$forceShowFields = true;
213
$filter = false;
214
$extra = $extraFieldUser->addElements(
215
    $userForm,
216
    $userToLoad,
217
    [],
218
    $filter,
219
    true,
220
    $fieldsToShow,
221
    $fieldsToShow,
222
    [],
223
    false,
224
    $forceShowFields, //$forceShowFields = false
225
    [],
226
    []
227
);
228
$userForm->addEndPanel();
229
230
$userForm->addStartPanel('dispo', get_lang('Availability during my internship/mobility'));
231
$userForm->addHtml('<p class="text-info">'.get_lang('You can continue working on the platform during your internship. Your answers will help us offer you a personalized program based on your availability. <br><br>Indicate the dates and your availability').'</p>');
232
233
$fieldsToShow = [
234
    'datedebutstage',
235
    'datefinstage',
236
    'deja_sur_place',
237
    'poursuiteapprentissagestage',
238
    'heures_disponibilite_par_semaine_stage',
239
];
240
241
$extra = $extraFieldUser->addElements(
242
    $userForm,
243
    $userToLoad,
244
    [],
245
    $filter,
246
    true,
247
    $fieldsToShow,
248
    $fieldsToShow,
249
    [],
250
    false,
251
    $forceShowFields, //$forceShowFields = false
252
    [],
253
    []
254
);
255
$userForm->addEndPanel();
256
257
$userForm->addStartPanel('objectifs', get_lang('My learning goals'));
258
$userForm->addHtml('<p class="text-info">'.get_lang('What do you want to learn? What area do you want to improve in? You can write your answers freely here.').'</p>');
259
$fieldsToShow = [
260
    'objectif_apprentissage',
261
];
262
$extra = $extraFieldUser->addElements(
263
    $userForm,
264
    $userToLoad,
265
    [],
266
    $filter,
267
    false,
268
    $fieldsToShow,
269
    $fieldsToShow,
270
    $defaults,
271
    false,
272
    $forceShowFields,//$forceShowFields = false
273
    [],
274
    []
275
);
276
$userForm->addEndPanel();
277
278
$userForm->addStartPanel('method', get_lang('My working method'));
279
$userForm->addHtml("<p class=\"text-info\">".get_lang("On the platform, you'll complete some activities independently, while others will be done in groups, accompanied by a tutor. Your answers will help us suggest a learning program that's tailored to your work style.")."</p>");
280
281
$fieldsToShow = [
282
    'methode_de_travaille',
283
    'accompagnement',
284
];
285
286
$extra = $extraFieldUser->addElements(
287
    $userForm,
288
    $userToLoad,
289
    [],
290
    $filter,
291
    true,
292
    $fieldsToShow,
293
    $fieldsToShow,
294
    [],
295
    false,
296
    $forceShowFields, //$forceShowFields = false
297
    [],
298
    []
299
);
300
$userForm->addEndPanel();
301
302
if (isset($_POST) && !empty($_POST)) {
303
    $searchChecked1 = isset($_POST['search_using_1']) ? 'checked' : '';
304
    $searchChecked2 = isset($_POST['search_using_2']) ? 'checked' : '';
305
    $searchChecked3 = isset($_POST['search_using_3']) ? 'checked' : '';
306
    Session::write('search_using_1', $searchChecked1);
307
    Session::write('search_using_2', $searchChecked2);
308
    Session::write('search_using_3', $searchChecked3);
309
} else {
310
    $searchChecked1 = Session::read('search_using_1');
311
    $searchChecked1 = null === $searchChecked1 ? 'checked' : $searchChecked1;
312
313
    $searchChecked2 = Session::read('search_using_2');
314
    $searchChecked2 = null === $searchChecked2 ? 'checked' : $searchChecked2;
315
316
    $searchChecked3 = Session::read('search_using_3');
317
    $searchChecked3 = null === $searchChecked3 ? 'checked' : $searchChecked3;
318
}
319
320
$form->addStartPanel('dispo_avant', '<input type="checkbox" name="search_using_1" '.$searchChecked1.' />&nbsp;'.get_lang('Availability before my internship/mobility'));
321
$form->addHtml('<p class="text-info">'.get_lang('The platform offers numerous resources and learning courses available on specific dates. The first step is to assess your availability to be able to offer you a suitable learning program.<br><br>Indicate the dates and your availability').'</p>');
322
323
// Session fields
324
$showOnlyThisFields = [
325
    'access_start_date',
326
    'access_end_date',
327
];
328
329
$extra = $extraField->addElements(
330
    $form,
331
    '',
332
    [],
333
    false, //filter
334
    true,
335
    $showOnlyThisFields,
336
    $showOnlyThisFields,
337
    $defaults,
338
    false, //$orderDependingDefaults
339
    true, // force
340
    [], // $separateExtraMultipleSelect
341
    []
342
);
343
344
$fieldsToShow = [
345
    'heures_disponibilite_par_semaine',
346
    'moment_de_disponibilite',
347
    //'langue_cible',
348
];
349
350
$extra = $extraFieldUser->addElements(
351
    $form,
352
    $userToLoad,
353
    [],
354
    $filter,
355
    true,
356
    $fieldsToShow,
357
    $fieldsToShow,
358
    [],
359
    false,
360
    $forceShowFields //$forceShowFields = false
361
);
362
363
$form->addEndPanel();
364
365
$form->addStartPanel('theme_obj', '<input type="checkbox" name="search_using_2" '.$searchChecked2.' />&nbsp;'.get_lang('The topics that interest me / My learning objectives'));
366
$form->addHtml("<p class=\"text-info\">".get_lang("The platform offers numerous resources and thematic learning courses to develop your skills. Now it's time to take stock of your interests to be offer you a personalized course program.")."</p>");
367
368
$showOnlyThisFields = [
369
    'domaine',
370
    'filiere',
371
    $theme,
372
];
373
374
$extra = $extraField->addElements(
375
    $form,
376
    '',
377
    [],
378
    false, //filter
379
    true,
380
    $showOnlyThisFields,
381
    $showOnlyThisFields,
382
    $defaults,
383
    false, //$orderDependingDefaults
384
    true, // force
385
    ['domaine' => 3, $theme => 5], // $separateExtraMultipleSelect
386
    [
387
        'domaine' => [
388
            sprintf(get_lang('Domain %s'),'1'),
389
            sprintf(get_lang('Domain %s'),'2'),
390
            sprintf(get_lang('Domain %s'),'3'),
391
        ],
392
        $theme => [
393
            sprintf(get_lang('Topic %s'),'1'),
394
            sprintf(get_lang('Topic %s'),'2'),
395
            sprintf(get_lang('Topic %s'),'3'),
396
            sprintf(get_lang('Topic %s'),'4'),
397
            sprintf(get_lang('Topic %s'),'5'),
398
        ],
399
    ],
400
    true
401
);
402
403
// Commented because BT#15776
404
$fieldsToShow = [
405
    'langue_cible',
406
];
407
408
$extra = $extraFieldUser->addElements(
409
    $form,
410
    $userToLoad,
411
    [],
412
    $filter,
413
    true,
414
    $fieldsToShow,
415
    $fieldsToShow,
416
    [],
417
    false,
418
    $forceShowFields //$forceShowFields = false
419
);
420
421
$form->addEndPanel();
422
423
$form->addStartPanel('niveau_langue', '<input type="checkbox" name="search_using_3" '.$searchChecked3.' />&nbsp;'.get_lang('My language level'));
424
$form->addHtml("<p class=\"text-info\">".get_lang("The platform's resources are adapted to different language levels. The goal here is to take stock of what you can or already know how to do.<br><br>Tick the level that best suits you for each skill (listening, reading, participating in a conversation, speaking continuously, and writing).<br><br>")."</p>");
425
426
$showOnlyThisFields = [
427
    'ecouter',
428
    'lire',
429
    'participer_a_une_conversation',
430
    's_exprimer_oralement_en_continu',
431
    'ecrire',
432
];
433
434
$extra = $extraField->addElements(
435
    $form,
436
    '',
437
    [],
438
    false, //filter
439
    true,
440
    $showOnlyThisFields,
441
    $showOnlyThisFields,
442
    $defaults,
443
    false, //$orderDependingDefaults
444
    true, // force
445
    ['domaine' => 3, $theme => 5], // $separateExtraMultipleSelect
446
    [
447
        'domaine' => [
448
            sprintf(get_lang('Domain %s'),'1'),
449
            sprintf(get_lang('Domain %s'),'2'),
450
            sprintf(get_lang('Domain %s'),'3'),
451
        ],
452
        $theme => [
453
            sprintf(get_lang('Topic %s'),'1'),
454
            sprintf(get_lang('Topic %s'),'2'),
455
            sprintf(get_lang('Topic %s'),'3'),
456
            sprintf(get_lang('Topic %s'),'4'),
457
            sprintf(get_lang('Topic %s'),'5'),
458
        ],
459
    ]
460
);
461
462
$form->addEndPanel();
463
464
$userForm->addStartPanel('environnement_travail', get_lang('My work environment'));
465
$userForm->addHtml('<p class="text-info"> </p>');
466
467
$fieldsToShow = [
468
    'outil_de_travail_ordinateur',
469
    'outil_de_travail_ordinateur_so',
470
    'outil_de_travail_tablette',
471
    'outil_de_travail_tablette_so',
472
    'outil_de_travail_smartphone',
473
    'outil_de_travail_smartphone_so',
474
];
475
476
$userForm->addLabel(null, get_lang('To work on the platform, I use:'));
477
478
$extra = $extraFieldUser->addElements(
479
    $userForm,
480
    $userToLoad,
481
    [],
482
    $filter,
483
    true,
484
    $fieldsToShow,
485
    $fieldsToShow,
486
    [],
487
    false,
488
    $forceShowFields
489
);
490
491
$userForm->addLabel(null, ' ');
492
493
$jqueryExtra .= $extra['jquery_ready_content'];
494
495
$fieldsToShow = [
496
    'browser_platforme',
497
    'browser_platforme_autre',
498
    'browser_platforme_version',
499
];
500
$extra = $extraFieldUser->addElements(
501
    $userForm,
502
    $userToLoad,
503
    [],
504
    $filter,
505
    true,
506
    $fieldsToShow,
507
    $fieldsToShow,
508
    [],
509
    false,
510
    $forceShowFields, //$forceShowFields = false
511
    [],
512
    []
513
);
514
515
$jqueryExtra .= $extra['jquery_ready_content'];
516
517
$userForm->addHtml('<p class="text-info">'.get_lang('You will find in the <a style="color:blue" href=\"/faq">FAQ</a> the recommended environment to work on the platform.').'</p>');
518
519
$userForm->addButtonSave(get_lang('Save'), 'submit_partial[collapseEight]');
520
521
$userForm->addEndPanel();
522
523
$form->addButtonSave(get_lang('Save diagnostic changes'), 'save');
524
525
// Get list of session status
526
$statusList = SessionManager::getStatusList();
527
$statusSelectList[0] = ' -- '.get_lang('All').' --';
528
foreach ($statusList as $nro => $name) {
529
    $statusSelectList[$nro] = $name;
530
}
531
$form->addSelect(
532
    'filter_status',
533
    get_lang('Session status'),
534
    $statusSelectList,
535
    ['id' => 'filter_status']
536
);
537
538
$form->addButtonSearch(get_lang('Search sessions'), 'search');
539
540
$extraFieldsToFilter = $extraField->get_all(['variable = ?' => 'temps_de_travail']);
541
$extraFieldToSearch = [];
542
if (!empty($extraFieldsToFilter)) {
543
    foreach ($extraFieldsToFilter as $filter) {
544
        $extraFieldToSearch[] = $filter['id'];
545
    }
546
}
547
$extraFieldListToString = implode(',', $extraFieldToSearch);
548
$result = SessionManager::getGridColumns('custom', $extraFieldsToFilter);
549
$columns = $result['columns'];
550
$columnModel = $result['column_model'];
551
552
$form->setDefaults($defaults);
553
554
/** @var HTML_QuickForm_select $element */
555
$domaine1 = $form->getElementByName('extra_domaine[0]');
556
$domaine2 = $form->getElementByName('extra_domaine[1]');
557
$domaine3 = $form->getElementByName('extra_domaine[2]');
558
$userForm->setDefaults($defaults);
559
560
$domainList = array_merge(
561
    is_object($domaine1) && !empty($domaine1->getValue()) ? $domaine1->getValue() : [],
562
    is_object($domaine3) && !empty($domaine3->getValue()) ? $domaine3->getValue() : [],
563
    is_object($domaine2) && !empty($domaine2->getValue()) ? $domaine2->getValue() : []
564
);
565
566
$themeList = [];
567
$extraField = new ExtraField('session');
568
$resultOptions = $extraField->searchOptionsFromTags('extra_domaine', 'extra_'.$theme, $domainList);
569
570
if ($resultOptions) {
571
    $resultOptions = array_column($resultOptions, 'tag', 'id');
572
    $resultOptions = array_filter($resultOptions);
573
574
    for ($i = 0; $i < 5; $i++) {
575
        /** @var HTML_QuickForm_select $theme */
576
        $themeElement = $form->getElementByName('extra_'.$theme.'['.$i.']');
577
        foreach ($resultOptions as $key => $value) {
578
            $themeElement->addOption($value, $value);
579
        }
580
    }
581
}
582
583
$filterToSend = '';
584
if ($formSearch->validate()) {
585
    $formSearchParams = $formSearch->getSubmitValues();
586
}
587
588
// Search filter
589
$filters = [];
590
foreach ($defaults as $key => $value) {
591
    if ('extra_' !== substr($key, 0, 6) && '_extra_' !== substr($key, 0, 7)) {
592
        continue;
593
    }
594
    if (!empty($value)) {
595
        $filters[$key] = $value;
596
    }
597
}
598
599
$filterToSend = [];
600
if (!empty($filters)) {
601
    $filterToSend = ['groupOp' => 'AND'];
602
    if ($filters) {
603
        $count = 1;
604
        $countExtraField = 1;
605
        foreach ($result['column_model'] as $column) {
606
            if ($count > 5) {
607
                if (isset($filters[$column['name']])) {
608
                    $defaultValues['jqg'.$countExtraField] = $filters[$column['name']];
609
                    $filterToSend['rules'][] = [
610
                        'field' => $column['name'],
611
                        'op' => 'cn',
612
                        'data' => $filters[$column['name']],
613
                    ];
614
                }
615
                $countExtraField++;
616
            }
617
            $count++;
618
        }
619
    }
620
}
621
622
$params = [];
623
if ($form->validate()) {
624
    $params = $form->getSubmitValues();
625
    $save = false;
626
    $search = false;
627
    if (isset($params['search'])) {
628
        unset($params['search']);
629
        $search = true;
630
    }
631
632
    if (isset($params['save'])) {
633
        $save = true;
634
        unset($params['save']);
635
    }
636
637
    $form->setDefaults($params);
638
639
    $filters = [];
640
641
    // Search
642
    if ($search) {
643
        // Parse params.
644
        foreach ($params as $key => $value) {
645
            if ('extra_' !== substr($key, 0, 6) && '_extra_' !== substr($key, 0, 7)) {
646
                continue;
647
            }
648
            if (!empty($value)) {
649
                if (is_array($value)) {
650
                    $valueArray = $value;
651
                    $filtered_value = array_filter($valueArray, function($valueFilter) {
652
                        return $valueFilter !== null && $valueFilter !== "";
653
                    });
654
                    $value = $filtered_value;
655
                }
656
                $filters[$key] = $value;
657
            }
658
        }
659
660
        $filterToSend = [];
661
        if (!empty($filters)) {
662
            $filterToSend = ['groupOp' => 'AND'];
663
            if ($filters) {
664
                $count = 1;
665
                $countExtraField = 1;
666
                foreach ($result['column_model'] as $column) {
667
                    if ($count > 5) {
668
                        if (isset($filters[$column['name']])) {
669
                            $defaultValues['jqg'.$countExtraField] = $filters[$column['name']];
670
                            $filterToSend['rules'][] = [
671
                                'field' => $column['name'],
672
                                'op' => 'cn',
673
                                'data' => $filters[$column['name']],
674
                            ];
675
                        }
676
                        $countExtraField++;
677
                    }
678
                    $count++;
679
                }
680
            }
681
        }
682
683
        if (!empty($_REQUEST['filter_status'])) {
684
            $filterToSend['filter_status'] = (int) $_REQUEST['filter_status'];
685
        }
686
    }
687
688
    if ($save) {
689
        $userData = $params;
690
        // Update extra_heures_disponibilite_par_semaine
691
        $extraFieldValue = new ExtraFieldValue('user');
692
        $userDataToSave = [
693
            'item_id' => $userToLoad,
694
            'extra_heures_disponibilite_par_semaine' => $userData['extra_heures_disponibilite_par_semaine'] ?? '',
695
            'extra_langue_cible' => $userData['extra_langue_cible'] ?? '',
696
        ];
697
        $extraFieldValue->saveFieldValues(
698
            $userDataToSave,
699
            true,
700
            false,
701
            ['heures_disponibilite_par_semaine', 'langue_cible'],
702
            [],
703
            true
704
        );
705
706
        $extraFieldValueSession = new ExtraFieldValue('session');
707
        $sessionFields = [
708
            'extra_access_start_date',
709
            'extra_access_end_date',
710
            'extra_filiere',
711
            'extra_domaine',
712
            'extra_domaine[0]',
713
            'extra_domaine[1]',
714
            'extra_domaine[3]',
715
            'extra_temps_de_travail',
716
            //'extra_competenceniveau',
717
            'extra_'.$theme,
718
            'extra_ecouter',
719
            'extra_lire',
720
            'extra_participer_a_une_conversation',
721
            'extra_s_exprimer_oralement_en_continu',
722
            'extra_ecrire',
723
        ];
724
725
        foreach ($userData as $key => $value) {
726
            $found = strpos($key, '__persist__');
727
            if (false === $found) {
728
                continue;
729
            }
730
        }
731
732
        if (isset($userData['extra_filiere_want_stage']) &&
733
            isset($userData['extra_filiere_want_stage']['extra_filiere_want_stage'])
734
        ) {
735
            $wantStage = $userData['extra_filiere_want_stage']['extra_filiere_want_stage'];
736
737
            if ('yes' === $wantStage) {
738
                if (isset($userData['extra_filiere_user'])) {
739
                    $userData['extra_filiere'] = [];
740
                    $userData['extra_filiere']['extra_filiere'] = $userData['extra_filiere_user']['extra_filiere_user'];
741
                }
742
            }
743
        }
744
745
        // save in ExtraFieldSavedSearch.
746
        foreach ($userData as $key => $value) {
747
            if ('extra_' !== substr($key, 0, 6) && '_extra_' !== substr($key, 0, 7)) {
748
                continue;
749
            }
750
751
            if (!in_array($key, $sessionFields)) {
752
                continue;
753
            }
754
755
            $field_variable = substr($key, 6);
756
            $extraFieldInfo = $extraFieldValueSession
757
                ->getExtraField()
758
                ->get_handler_field_info_by_field_variable($field_variable);
759
760
            if (!$extraFieldInfo) {
761
                continue;
762
            }
763
764
            $extraFieldObj = $em->getRepository(\Chamilo\CoreBundle\Entity\ExtraField::class)->find(
765
                $extraFieldInfo['id']
766
            );
767
768
            $search = [
769
                'field' => $extraFieldObj,
770
                'user' => $userToLoad,
771
            ];
772
773
            /** @var ExtraFieldSavedSearch $saved */
774
            $saved = $em->getRepository(ExtraFieldSavedSearch::class)->findOneBy($search);
775
776
            if (empty($value)) {
777
                $value = [];
778
            }
779
780
            if (is_string($value)) {
781
                $value = [$value];
782
            }
783
784
            if ($saved) {
785
                $saved
786
                    ->setField($extraFieldObj)
787
                    ->setUser(api_get_user_entity($userToLoad))
788
                    ->setValue($value)
789
                ;
790
            } else {
791
                $saved = new ExtraFieldSavedSearch();
792
                $saved
793
                    ->setField($extraFieldObj)
794
                    ->setUser(api_get_user_entity($userToLoad))
795
                    ->setValue($value)
796
                ;
797
            }
798
            $em->persist($saved);
799
            $em->flush();
800
        }
801
        Display::addFlash(Display::return_message(get_lang('Saved.'), 'success'));
802
        header('Location: '.api_get_self().'?user_id='.$userToLoad);
803
        exit;
804
    }
805
}
806
807
$view = $form->returnForm();
808
809
$jsTag = '';
810
if (!empty($tagsData)) {
811
    foreach ($tagsData as $extraField => $tags) {
812
        foreach ($tags as $tag) {
813
            $tag = api_htmlentities($tag);
814
        }
815
    }
816
}
817
818
$htmlHeadXtra[] = '<script>
819
$(function() {
820
    '.$jqueryExtra.'
821
    '.$jsTag.'
822
});
823
</script>';
824
825
$url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?a=order&user_id='.$userId;
826
$htmlHeadXtra[] = '
827
<script>
828
    document.addEventListener("DOMContentLoaded", function() {
829
      var targetBlock = window.location.hash;
830
      var targetBlockWithoutHash = targetBlock.substring(1);
831
      const diapoButton = document.querySelector("#card_"+targetBlockWithoutHash+" a");
832
833
      setTimeout(function() {
834
        diapoButton.click();
835
      }, 500);
836
    });
837
</script>
838
<script>
839
$(function() {
840
    var themeDefault = "extra_'.$theme.'";
841
    var extraFiliere = $("input[name=\'extra_filiere[extra_filiere]\']").parent().parent();
842
    '.$defaultValueStatus.'
843
844
    $("input[name=\'extra_filiere_want_stage[extra_filiere_want_stage]\']").change(function() {
845
        if ($(this).val() == "no") {
846
            extraFiliere.show();
847
        } else {
848
            extraFiliere.hide();
849
        }
850
    });
851
852
    $("#extra_theme").parent().append(
853
        $("<a>", {
854
            "class": "btn ajax btn--plain",
855
            "href": "'.$url.'&field_variable=extra_theme",
856
            "text": "'.get_lang('Order').'"
857
        })
858
    );
859
860
    $("#extra_theme_fr").parent().append(
861
        $("<a>", {
862
            "class": "btn ajax btn--plain",
863
            "href": "'.$url.'&field_variable=extra_theme_fr",
864
            "text": "'.get_lang('Order').'"
865
        })
866
    );
867
868
    $("#extra_theme_de").parent().append(
869
        $("<a>", {
870
            "class": "btn ajax btn--plain",
871
            "href": "'.$url.'&field_variable=extra_theme_de",
872
            "text": "'.get_lang('Order').'"
873
        })
874
    );
875
876
    $("#extra_theme_it").parent().append(
877
        $("<a>", {
878
            "class": "btn ajax btn--plain",
879
            "href": "'.$url.'&field_variable=extra_theme_it",
880
            "text": "'.get_lang('Order').'"
881
        })
882
    );
883
884
    $("#extra_theme_es").parent().append(
885
        $("<a>", {
886
            "class": "btn ajax btn--plain",
887
            "href": "'.$url.'&field_variable=extra_theme_es",
888
            "text": "'.get_lang('Order').'"
889
        })
890
    );
891
892
     $("#extra_theme_pl").parent().append(
893
        $("<a>", {
894
            "class": "btn ajax btn--plain",
895
            "href": "'.$url.'&field_variable=extra_theme_pl",
896
            "text": "'.get_lang('Order').'"
897
        })
898
    );
899
900
    $("#extra_domaine_0, #extra_domaine_1, #extra_domaine_2").on("change", function() {
901
        var domainList = [];
902
        $("#extra_domaine_0 option:selected").each(function() {
903
            domainList.push($(this).val());
904
        });
905
        $("#extra_domaine_1 option:selected").each(function() {
906
            domainList.push($(this).val());
907
        });
908
        $("#extra_domaine_2 option:selected").each(function() {
909
            domainList.push($(this).val());
910
        });
911
912
        var domainListToString = JSON.stringify(domainList);
913
914
        $.ajax({
915
            contentType: "application/x-www-form-urlencoded",
916
            type: "GET",
917
            url: "'.api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?a=search_options_from_tags&type=session&from=extra_domaine&search="+themeDefault+"&options="+domainListToString,
918
            success: function(data) {
919
                var selectToString = "";
920
                selectToString += "<option></option>";
921
                jQuery.each(JSON.parse(data), function(i, item) {
922
                    selectToString += "<optgroup label=\'"+item.text+"\'>";
923
                    jQuery.each(item.children, function(j, data) {
924
                        if (data.text != "") {
925
                            selectToString += "<option value=\'"+data.text+"\'> " +data.text+"</option>"
926
                        }
927
                    });
928
                    selectToString += "</optgroup>";
929
                });
930
931
                for (i = 0; i <= 5; i++) {
932
                    var themeId = "#"+themeDefault+"_"+i;
933
                    var beforeValue = $(themeId).find(":selected").val();
934
                    $(themeId).find("option").remove().end();
935
                    $(themeId).empty();
936
                    $(themeId).html(selectToString);
937
                    $(themeId).val(beforeValue);
938
                }
939
            }
940
         });
941
    });
942
});
943
</script>';
944
945
if (!empty($filterToSend)) {
946
    if (isset($params['search_using_1'])) {
947
        // Get start and end date from ExtraFieldSavedSearch
948
        $defaultExtraStartDate = isset($defaults['extra_access_start_date']) ? $defaults['extra_access_start_date'] : '';
949
        $defaultExtraEndDate = isset($defaults['extra_access_end_date']) ? $defaults['extra_access_end_date'] : '';
950
951
        $userStartDate = isset($params['extra_access_start_date']) ? $params['extra_access_start_date'] : $defaultExtraStartDate;
952
        $userEndDate = isset($params['extra_access_end_date']) ? $params['extra_access_end_date'] : $defaultExtraEndDate;
953
954
        // Minus 3 days
955
        $date = new DateTime($userStartDate);
956
        $date->sub(new DateInterval('P3D'));
957
        $userStartDateMinus = $date->format('Y-m-d h:i:s');
958
959
        // Plus 2 days
960
        $date = new DateTime($userEndDate);
961
        $date->add(new DateInterval('P2D'));
962
        $userEndDatePlus = $date->format('Y-m-d h:i:s');
963
964
        // Ofaj fix
965
        $userStartDateMinus = api_get_utc_datetime(substr($userStartDateMinus, 0, 11).'00:00:00');
966
        $userEndDatePlus = api_get_utc_datetime(substr($userEndDatePlus, 0, 11).'23:59:59');
967
968
        // Special OFAJ date logic
969
        if ('' == $userEndDate) {
970
            $sql = " AND (
971
                (s.access_start_date >= '$userStartDateMinus') OR
972
                ((s.access_start_date = '' OR s.access_start_date IS NULL) AND (s.access_end_date = '' OR s.access_end_date IS NULL))
973
            )";
974
        } else {
975
            $sql = " AND (
976
                (s.access_start_date >= '$userStartDateMinus' AND s.access_end_date < '$userEndDatePlus') OR
977
                (s.access_start_date >= '$userStartDateMinus' AND (s.access_end_date = '' OR s.access_end_date IS NULL)) OR
978
                ((s.access_start_date = '' OR s.access_start_date IS NULL) AND (s.access_end_date = '' OR s.access_end_date IS NULL))
979
            )";
980
        }
981
    }
982
983
    $deleteFiliere = false;
984
    $extraFieldOptions = new ExtraFieldOption('session');
985
    $extraFieldSession = new ExtraField('session');
986
987
    // Special filters
988
    // see https://task.beeznest.com/issues/10849#change-81902
989
    foreach ($filterToSend['rules'] as &$filterItem) {
990
        if (!isset($filterItem)) {
991
            continue;
992
        }
993
994
        if (isset($filterItem['field'])) {
995
            switch ($filterItem['field']) {
996
                case 'extra_filiere':
997
                case 'extra_domaine':
998
                case 'extra_theme_it':
999
                case 'extra_theme_fr':
1000
                case 'extra_theme_de':
1001
                case 'extra_theme_pl':
1002
                    if (!isset($params['search_using_2'])) {
1003
                        $filterItem = null;
1004
                    }
1005
                    break;
1006
            }
1007
        }
1008
1009
        if (isset($filterItem['field'])) {
1010
            switch ($filterItem['field']) {
1011
                case 'extra_ecouter':
1012
                case 'extra_lire':
1013
                case 'extra_participer_a_une_conversation':
1014
                case 'extra_s_exprimer_oralement_en_continu':
1015
                case 'extra_ecrire':
1016
                    if (!isset($params['search_using_3'])) {
1017
                        $filterItem = null;
1018
                        break;
1019
                    }
1020
                    $selectedValue = '';
1021
                    $fieldExtra = str_replace('extra_', '', $filterItem['field']);
1022
                    $extraFieldSessionData = $extraFieldSession->get_handler_field_info_by_field_variable($fieldExtra);
1023
1024
                    if (is_array($filterItem['data'])) {
1025
                        $myOrder = [];
1026
                        foreach ($filterItem['data'] as $option) {
1027
                            foreach ($extraFieldSessionData['options'] as $optionValue) {
1028
                                if ($option == $optionValue['option_value']) {
1029
                                    $myOrder[$optionValue['option_order']] = $optionValue['option_value'];
1030
                                }
1031
                            }
1032
                        }
1033
1034
                        if (!empty($myOrder)) {
1035
                            // Taking last from list
1036
                            $selectedValue = end($myOrder);
1037
                        }
1038
                    } else {
1039
                        $selectedValue = $filterItem['data'];
1040
                    }
1041
1042
                    $newOptions = array_column(
1043
                        $extraFieldSessionData['options'],
1044
                        'option_value',
1045
                        'option_order'
1046
                    );
1047
1048
                    $searchOptions = [];
1049
                    for ($i = 1; $i < count($newOptions); $i++) {
1050
                        if ($selectedValue == $newOptions[$i]) {
1051
                            if (isset($newOptions[$i - 1])) {
1052
                                $searchOptions[] = $newOptions[$i - 1];
1053
                            }
1054
                            if (isset($newOptions[$i])) {
1055
                                $searchOptions[] = $newOptions[$i];
1056
                            }
1057
                            if (isset($newOptions[$i + 1])) {
1058
                                $searchOptions[] = $newOptions[$i + 1];
1059
                            }
1060
                            break;
1061
                        }
1062
                    }
1063
1064
                    $filterItem['data'] = $searchOptions;
1065
                    break;
1066
                case 'extra_domaine':
1067
                    if (!isset($params['search_using_2'])) {
1068
                        break;
1069
                    }
1070
                    // Special condition see:
1071
                    // https://task.beeznest.com/issues/10849#note-218
1072
                    // Remove filiere
1073
                    $list = [
1074
                        'vie-quotidienne',
1075
                        //'competente-dans-mon-domaine-de-specialite',
1076
                        'arrivee-sur-mon-poste-de-travail',
1077
                    ];
1078
1079
                    $deleteFiliere = false;
1080
                    if (is_array($filterItem['data'])) {
1081
                        $myOrder = [];
1082
                        foreach ($filterItem['data'] as $option) {
1083
                            if (in_array($option, $list)) {
1084
                                $deleteFiliere = true;
1085
                                break;
1086
                            }
1087
                        }
1088
                    } else {
1089
                        if (in_array($filterItem['data'], $list)) {
1090
                            $deleteFiliere = true;
1091
                        }
1092
                    }
1093
                    break;
1094
                case 'extra_filiere':
1095
                    $filterItem['data'] = $filterItem['data']['extra_filiere'];
1096
                    break;
1097
            }
1098
        }
1099
1100
        if ($deleteFiliere) {
1101
            if (isset($filterItem['field']) && 'extra_filiere' == $filterItem['field']) {
1102
                $filterItem = [];
1103
            }
1104
        }
1105
    }
1106
1107
    // Language
1108
    $lang = isset($params['extra_langue_cible']) ? $params['extra_langue_cible'] : $defaultLangCible;
1109
    $lang = strtolower($lang);
1110
1111
    if (isset($params['search_using_1'])) {
1112
        if ($userStartDate && !empty($userStartDate)) {
1113
            $filterToSend['custom_dates'] = $sql;
1114
        }
1115
    }
1116
1117
    $filterToSend = json_encode($filterToSend);
1118
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&load_extra_field='.
1119
        $extraFieldListToString.'&_force_search=true&rows=20&page=1&origin=load_search&sidx=&sord=desc&filters2='.$filterToSend;
1120
    if (isset($params['search_using_2'])) {
1121
        $url .= '&lang='.$lang;
1122
    }
1123
} else {
1124
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&load_extra_field='.
1125
        $extraFieldListToString.'&_force_search=true&rows=20&page=1&origin=load_search&sidx=&sord=desc';
1126
}
1127
1128
// Autowidth
1129
$extra_params['autowidth'] = 'true';
1130
1131
// height auto
1132
$extra_params['height'] = 'auto';
1133
$extraParams['postData'] = [
1134
    'filters' => [
1135
        'groupOp' => 'AND',
1136
        'rules' => $result['rules'],
1137
    ],
1138
];
1139
1140
$sessionByUserList = SessionManager::get_sessions_by_user($userToLoad, true, true);
1141
1142
$sessionUserList = [];
1143
if (!empty($sessionByUserList)) {
1144
    foreach ($sessionByUserList as $sessionByUser) {
1145
        $sessionUserList[] = (string) $sessionByUser['session_id'];
1146
    }
1147
}
1148
1149
$actionLinks = 'function action_formatter(cellvalue, options, rowObject) {
1150
    var sessionList = '.json_encode($sessionUserList).';
1151
    var id = options.rowId.toString();
1152
    if (sessionList.indexOf(id) == -1) {
1153
        return \'<a href="'.api_get_self(
1154
    ).'?action=subscribe_user&user_id='.$userToLoad.'&session_id=\'+id+\'">'.Display::getMdiIcon(
1155
        ActionIcon::ADD,
1156
        'ch-tool-icon',
1157
        null,
1158
        ICON_SIZE_SMALL,
1159
        addslashes(get_lang('Subscribe'))
1160
    ).'</a>'.'\';
1161
    } else {
1162
        return \'<a href="'.api_get_self(
1163
    ).'?action=unsubscribe_user&user_id='.$userToLoad.'&session_id=\'+id+\'">'.Display::getMdiIcon(
1164
        ActionIcon::DELETE,
1165
        'ch-tool-icon',
1166
        null,
1167
        ICON_SIZE_SMALL,
1168
        addslashes(get_lang('Delete'))
1169
    ).'</a>'.'\';
1170
    }
1171
}';
1172
1173
$htmlHeadXtra[] = api_get_jqgrid_js();
1174
1175
$griJs = Display::grid_js(
1176
    'sessions',
1177
    $url,
1178
    $columns,
1179
    $columnModel,
1180
    $extraParams,
1181
    [],
1182
    $actionLinks,
1183
    true
1184
);
1185
1186
$grid = '<div id="session-table" class="table-responsive">';
1187
$grid .= Display::grid_html('sessions');
1188
$grid .= '</div>';
1189
1190
$htmlHeadXtra[] = '<style>
1191
	.control-label {
1192
	    width: 25% !important;
1193
	}
1194
</style>';
1195
1196
$tpl = new Template(get_lang('Diagnosis'));
1197
1198
if (empty($items)) {
1199
    $view = '';
1200
    $grid = '';
1201
    $griJs = '';
1202
}
1203
$tpl->assign('form', $view);
1204
$tpl->assign('form_search', $formSearch->returnForm().$userForm->returnForm());
1205
1206
$table = new HTML_Table(['class' => 'data_table']);
1207
$column = 0;
1208
$row = 0;
1209
1210
$total = 0;
1211
$sumHours = 0;
1212
$numHours = 0;
1213
1214
$field = 'heures_disponibilite_par_semaine';
1215
$data = null;
1216
$extraField = new ExtraFieldValue('user');
1217
if (!empty($userToLoad)) {
1218
    $data = $extraField->get_values_by_handler_and_field_variable($userToLoad, $field);
1219
}
1220
1221
$availableHoursPerWeek = 0;
1222
1223
function dateDiffInWeeks($date1, $date2)
1224
{
1225
    if (empty($date1) || empty($date2)) {
1226
        return 0;
1227
    }
1228
    // it validates a correct date format Y-m-d
1229
    if (false === DateTime::createFromFormat('Y-m-d', $date1) || false === DateTime::createFromFormat('Y-m-d', $date2)) {
1230
        return 0;
1231
    }
1232
1233
    if ($date1 > $date2) {
1234
        return dateDiffInWeeks($date2, $date1);
1235
    }
1236
    $first = new \DateTime($date1);
1237
    $second = new \DateTime($date2);
1238
1239
    return floor($first->diff($second)->days / 7);
1240
}
1241
1242
if ($data) {
1243
    $availableHoursPerWeek = (int) $data['value'];
1244
    $numberWeeks = 0;
1245
    if ($form->validate()) {
1246
        $formData = $form->getSubmitValues();
1247
1248
        if (isset($formData['extra_access_start_date']) && isset($formData['extra_access_end_date'])) {
1249
            $startDate = $formData['extra_access_start_date'];
1250
            $endDate = $formData['extra_access_end_date'];
1251
            $numberWeeks = dateDiffInWeeks($startDate, $endDate);
1252
        }
1253
    } else {
1254
        if ($defaults) {
1255
            if (isset($defaults['extra_access_start_date']) && isset($defaults['extra_access_end_date'])) {
1256
                $startDate = $defaults['extra_access_start_date'];
1257
                $endDate = $defaults['extra_access_end_date'];
1258
                $numberWeeks = dateDiffInWeeks($startDate, $endDate);
1259
            }
1260
        }
1261
    }
1262
1263
    $total = $numberWeeks * $availableHoursPerWeek;
1264
    $sessions = SessionManager::getSessionsFollowedByUser($userToLoad);
1265
1266
    if ($sessions) {
1267
        $sessionFieldValue = new ExtraFieldValue('session');
1268
1269
        foreach ($sessions as $session) {
1270
            $sessionId = $session['id'];
1271
            $dataTravails = $sessionFieldValue->get_values_by_handler_and_field_variable(
1272
                $sessionId,
1273
                'temps_de_travail'
1274
            );
1275
            if ($dataTravails) {
1276
                $sumHours += (int) $dataTravails['value'];
1277
            }
1278
        }
1279
    }
1280
}
1281
1282
$numHours = $total - $sumHours;
1283
if ($numHours < 0) {
1284
    $numHours = 0;
1285
}
1286
$headers = [
1287
    get_lang('Total available hours') => $total,
1288
    get_lang('Sum of hours in subscribed sessions') => $sumHours,
1289
    get_lang('Count of available hours') => $numHours,
1290
];
1291
foreach ($headers as $header => $value) {
1292
    $table->setCellContents($row, 0, $header);
1293
    $table->updateCellAttributes($row, 0, 'width="250px"');
1294
    $table->setCellContents($row, 1, $value);
1295
    $row++;
1296
}
1297
1298
$button = '';
1299
$userReportButton = '';
1300
if ($userToLoad) {
1301
    $button = Display::url(
1302
        get_lang('Send diagnostic finalization message'),
1303
        api_get_path(WEB_PATH).'resources/messages/new?'
1304
            .http_build_query(['send_to_user' => $userToLoad, 'prefill' => 'diagnosticFinalizationMessage']),
1305
        ['class' => 'btn btn--plain']
1306
    );
1307
    $button .= '<br /><br />';
1308
    $userReportButton = Display::url(
1309
        get_lang('Validate learning trail'),
1310
        api_get_path(WEB_CODE_PATH).'my_space/myStudents.php?student='.$userToLoad,
1311
        ['class' => 'btn btn--primary']
1312
    );
1313
}
1314
1315
$tpl->assign('grid', $grid.$button.$table->toHtml().$userReportButton);
1316
$tpl->assign('grid_js', $griJs);
1317
$templateName = $tpl->get_template('search/search_extra_field.html.twig');
1318
$contentTemplate = $tpl->fetch($templateName);
1319
$tpl->assign('content', $contentTemplate);
1320
$tpl->display_one_col_template();
1321