Passed
Push — master ( 930ebb...f10e67 )
by Julito
10:07
created

dateDiffInWeeks()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 9
rs 10
c 1
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\ExtraFieldSavedSearch;
6
use ChamiloSession as Session;
7
8
$cidReset = true;
9
10
require_once 'main/inc/global.inc.php';
11
12
$htmlHeadXtra[] = '<link  href="'.api_get_path(WEB_PATH).'web/assets/cropper/dist/cropper.min.css" rel="stylesheet">';
13
$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_PATH).'web/assets/cropper/dist/cropper.min.js"></script>';
14
15
$htmlHeadXtra[] = '<script>
16
$(function() {
17
    $("#filiere").on("click", function() {
18
        $("#filiere_panel").toggle();
19
        return false;
20
    });
21
22
    $("#dispo").on("click", function() {
23
        $("#dispo_panel").toggle();
24
        return false;
25
    });
26
27
    $("#dispo_pendant").on("click", function() {
28
        $("#dispo_pendant_panel").toggle();
29
        return false;
30
    });
31
32
    $("#niveau").on("click", function() {
33
        $("#niveau_panel").toggle();
34
        return false;
35
    });
36
37
    $("#methode").on("click", function() {
38
        $("#methode_panel").toggle();
39
        return false;
40
    });
41
42
    $("#themes").on("click", function() {
43
        $("#themes_panel").toggle();
44
        return false;
45
    });
46
47
    $("#objectifs").on("click", function() {
48
        $("#objectifs_panel").toggle();
49
        return false;
50
    });
51
});
52
</script>';
53
54
api_block_anonymous_users();
55
$allowToSee = api_is_drh() || api_is_student_boss() || api_is_platform_admin();
56
57
if ($allowToSee === false) {
58
    api_not_allowed(true);
59
}
60
$userId = api_get_user_id();
61
$userInfo = api_get_user_info();
62
63
$userToLoad = isset($_GET['user_id']) ? $_GET['user_id'] : '';
64
65
$userToLoadInfo = [];
66
if ($userToLoad) {
67
    $userToLoadInfo = api_get_user_info($userToLoad);
68
}
69
$action = isset($_GET['action']) ? $_GET['action'] : '';
70
71
switch ($action) {
72
    case 'subscribe_user':
73
        $sessionId = isset($_GET['session_id']) ? $_GET['session_id'] : '';
74
        SessionManager::subscribeUsersToSession(
75
            $sessionId,
76
            [$userToLoad],
77
            SESSION_VISIBLE_READ_ONLY,
78
            false
79
        );
80
        Display::addFlash(Display::return_message(get_lang('UserAdded')));
81
        header("Location: ".api_get_self().'?user_id='.$userToLoad.'#session-table');
82
        exit;
83
        break;
84
    case 'unsubscribe_user':
85
        $sessionId = isset($_GET['session_id']) ? $_GET['session_id'] : '';
86
        SessionManager::unsubscribe_user_from_session($sessionId, $userToLoad);
87
        Display::addFlash(Display::return_message(get_lang('Unsubscribed')));
88
        header("Location: ".api_get_self().'?user_id='.$userToLoad.'#session-table');
89
        break;
90
}
91
92
$em = Database::getManager();
93
94
$formSearch = new FormValidator('load', 'get', api_get_self());
95
$formSearch->addHeader(get_lang('LoadDiagnosis'));
96
if (!empty($userInfo)) {
97
    $users = [];
98
    switch ($userInfo['status']) {
99
        case DRH:
100
            $users = UserManager::get_users_followed_by_drh(
101
                $userId,
102
                0,
103
                false,
104
                false,
105
                false,
106
                null,
107
                null,
108
                null,
109
                null,
110
                1
111
            );
112
            break;
113
        case STUDENT_BOSS:
114
            $users = UserManager::getUsersFollowedByStudentBoss(
115
                $userId,
116
                0,
117
                false,
118
                false,
119
                false,
120
                null,
121
                null,
122
                null,
123
                null,
124
                1
125
            );
126
            break;
127
    }
128
129
    if (!empty($users)) {
130
        $userList = [];
131
        foreach ($users as $user) {
132
            $userList[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
133
        }
134
        $formSearch->addSelect('user_id', get_lang('User'), $userList);
135
    }
136
}
137
if ($userToLoad) {
138
    $formSearch->setDefaults(['user_id' => $userToLoad]);
139
}
140
141
$formSearch->addButtonSearch(get_lang('ShowDiagnostic'), 'save');
142
143
$form = new FormValidator('search', 'post', api_get_self().'?user_id='.$userToLoad.'#session-table');
144
$form->addHeader(get_lang('Diagnosis'));
145
$form->addHidden('user_id', $userToLoad);
146
147
/** @var ExtraFieldSavedSearch $saved */
148
$search = [
149
    'user' => $userToLoad,
150
];
151
152
$items = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findBy($search);
153
if (empty($items)) {
154
    Display::addFlash(Display::return_message('NoData'));
155
}
156
157
$defaults = [];
158
$tagsData = [];
159
if (!empty($items)) {
160
    /** @var ExtraFieldSavedSearch $item */
161
    foreach ($items as $item) {
162
        $variable = 'extra_'.$item->getField()->getVariable();
163
        if ($item->getField()->getFieldType() == ExtraField::FIELD_TYPE_TAG) {
164
            $tagsData[$variable] = $item->getValue();
165
        }
166
        $defaults[$variable] = $item->getValue();
167
    }
168
}
169
170
$extraField = new ExtraField('session');
171
$extraFieldValue = new ExtraFieldValue('session');
172
$extraFieldValueUser = new ExtraFieldValue('user');
173
174
$theme = 'theme_fr';
175
$lang = $defaultLangCible = api_get_interface_language();
0 ignored issues
show
Bug introduced by
The function api_get_interface_language was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

175
$lang = $defaultLangCible = /** @scrutinizer ignore-call */ api_get_interface_language();
Loading history...
176
177
if ($userToLoadInfo) {
178
    $lang = $userToLoadInfo['language'];
179
    $targetLanguageInfo = $extraFieldValueUser->get_values_by_handler_and_field_variable(
180
        $userToLoad,
181
        'langue_cible'
182
    );
183
184
    if (!empty($targetLanguageInfo)) {
185
        $defaultLangCible = $targetLanguageInfo['value'];
186
    }
187
188
    switch ($lang) {
189
        case 'italian':
190
            $theme = 'theme_it';
191
            break;
192
        case 'polish':
193
            $theme = 'theme_pl';
194
            break;
195
        case 'spanish':
196
            $theme = 'theme_es';
197
            break;
198
        case 'french2':
199
        case 'french':
200
            $theme = 'theme_fr';
201
            break;
202
        case 'german2':
203
        case 'german':
204
            $theme = 'theme_de';
205
            break;
206
    }
207
}
208
209
$extraFieldUser = new ExtraField('user');
210
211
$userForm = new FormValidator('user_form', 'post', api_get_self());
212
$jqueryExtra = '';
213
$userForm->addHtml('<div class="panel-group" id="search_extrafield" role="tablist" aria-multiselectable="true">');
214
$userForm->addHtml('<div class="panel panel-default">');
215
$userForm->addHtml('<div class="panel-heading"><a role="button" data-toggle="collapse" data-parent="#search_extrafield" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">'.get_lang('Filiere').'</a></div>');
216
$userForm->addHtml('<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">');
217
$userForm->addHtml('<div class="panel-body"><p class="text-info">'.get_lang('FiliereExplanation').'</p>');
218
219
$fieldsToShow = [
220
    'statusocial',
221
    'filiere_user',
222
    'filiereprecision',
223
    'filiere_want_stage',
224
];
225
$forceShowFields = true;
226
$filter = false;
227
$extra = $extraFieldUser->addElements(
228
    $userForm,
229
    $userToLoad,
230
    [],
231
    $filter,
232
    true,
233
    $fieldsToShow,
234
    $fieldsToShow,
235
    [],
236
    false,
237
    $forceShowFields, //$forceShowFields = false
238
    [],
239
    []
240
);
241
242
$userForm->addHtml('</div></div></div>');
243
244
$userForm->addHtml('<div class="panel panel-default">');
245
$userForm->addHtml('<div class="panel-heading"><a role="button" data-toggle="collapse" data-parent="#search_extrafield" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">'.get_lang('DisponibilitePendantMonStage').'</a></div>');
246
$userForm->addHtml('<div id="collapseThree" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingThree">');
247
$userForm->addHtml('<div class="panel-body"><p class="text-info">'.get_lang('DisponibilitePendantMonStageExplanation').'</p>');
248
249
$fieldsToShow = [
250
    'datedebutstage',
251
    'datefinstage',
252
    'deja_sur_place',
253
    'poursuiteapprentissagestage',
254
    'heures_disponibilite_par_semaine_stage',
255
];
256
257
$extra = $extraFieldUser->addElements(
258
    $userForm,
259
    $userToLoad,
260
    [],
261
    $filter,
262
    true,
263
    $fieldsToShow,
264
    $fieldsToShow,
265
    [],
266
    false,
267
    $forceShowFields, //$forceShowFields = false
268
    [],
269
    []
270
);
271
272
$userForm->addHtml('</div></div></div>');
273
274
$userForm->addHtml('<div class="panel panel-default">');
275
$userForm->addHtml('<div class="panel-heading"><a role="button" data-toggle="collapse" data-parent="#search_extrafield" href="#collapseSix" aria-expanded="true" aria-controls="collapseSix">'.get_lang('ObjectifsApprentissage').'</a></div>');
276
$userForm->addHtml('<div id="collapseSix" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingSix">');
277
$userForm->addHtml('<div class="panel-body"><p class="text-info">'.get_lang('ObjectifsApprentissageExplanation').'</p>');
278
279
$fieldsToShow = [
280
    'objectif_apprentissage',
281
];
282
283
$extra = $extraFieldUser->addElements(
284
    $userForm,
285
    $userToLoad,
286
    [],
287
    $filter,
288
    false,
289
    $fieldsToShow,
290
    $fieldsToShow,
291
    $defaults,
292
    false,
293
    $forceShowFields,//$forceShowFields = false
294
    [],
295
    []
296
);
297
298
$userForm->addHtml('</div></div></div>');
299
300
$userForm->addHtml('<div class="panel panel-default">');
301
$userForm->addHtml('<div class="panel-heading"><a role="button" data-toggle="collapse" data-parent="#search_extrafield" href="#collapseSeven" aria-expanded="true" aria-controls="collapseSeven">'.get_lang('MethodeTravail').'</a></div>');
302
$userForm->addHtml('<div id="collapseSeven" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingSeven">');
303
$userForm->addHtml('<div class="panel-body"><p class="text-info">'.get_lang('MethodeTravailExplanation').'</p>');
304
305
$fieldsToShow = [
306
    'methode_de_travaille',
307
    'accompagnement',
308
];
309
310
$extra = $extraFieldUser->addElements(
311
    $userForm,
312
    $userToLoad,
313
    [],
314
    $filter,
315
    true,
316
    $fieldsToShow,
317
    $fieldsToShow,
318
    [],
319
    false,
320
    $forceShowFields, //$forceShowFields = false
321
    [],
322
    []
323
);
324
325
$userForm->addHtml('</div></div></div>');
326
327
if (isset($_POST) && !empty($_POST)) {
328
    $searchChecked1 = isset($_POST['search_using_1']) ? 'checked' : '';
329
    $searchChecked2 = isset($_POST['search_using_2']) ? 'checked' : '';
330
    $searchChecked3 = isset($_POST['search_using_3']) ? 'checked' : '';
331
    Session::write('search_using_1', $searchChecked1);
332
    Session::write('search_using_2', $searchChecked2);
333
    Session::write('search_using_3', $searchChecked3);
334
} else {
335
    $searchChecked1 = Session::read('search_using_1');
336
    $searchChecked1 = $searchChecked1 === null ? 'checked' : $searchChecked1;
337
338
    $searchChecked2 = Session::read('search_using_2');
339
    $searchChecked2 = $searchChecked2 === null ? 'checked' : $searchChecked2;
340
341
    $searchChecked3 = Session::read('search_using_3');
342
    $searchChecked3 = $searchChecked3 === null ? 'checked' : $searchChecked3;
343
}
344
345
$form->addHtml('<div class="panel panel-default">');
346
$form->addHtml('<div class="panel-heading"><input type="checkbox" name="search_using_1" '.$searchChecked1.' />&nbsp;<a role="button" data-toggle="collapse" data-parent="#search_extrafield" href="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">'.get_lang('DisponibiliteAvant').'</a></div>');
347
$form->addHtml('<div id="collapseTwo" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingTwo">');
348
$form->addHtml('<div class="panel-body"><p class="text-info">'.get_lang('DisponibiliteAvantExplanation').'</p>');
349
350
// Session fields
351
$showOnlyThisFields = [
352
    'access_start_date',
353
    'access_end_date',
354
];
355
356
$extra = $extraField->addElements(
357
    $form,
358
    '',
359
    [],
360
    false, //filter
361
    true,
362
    $showOnlyThisFields,
363
    $showOnlyThisFields,
364
    $defaults,
365
    false, //$orderDependingDefaults
366
    true, // force
367
    [], // $separateExtraMultipleSelect
368
    []
369
);
370
371
$fieldsToShow = [
372
    'heures_disponibilite_par_semaine',
373
    'moment_de_disponibilite',
374
    //'langue_cible',
375
];
376
377
$extra = $extraFieldUser->addElements(
378
    $form,
379
    $userToLoad,
380
    [],
381
    $filter,
382
    true,
383
    $fieldsToShow,
384
    $fieldsToShow,
385
    [],
386
    false,
387
    $forceShowFields //$forceShowFields = false
388
);
389
390
$form->addHtml('</div></div></div>');
391
392
$form->addHtml('<div class="panel panel-default">');
393
$form->addHtml('<div class="panel-heading"><input type="checkbox" name="search_using_2" '.$searchChecked2.' />&nbsp;<a role="button" data-toggle="collapse" data-parent="#search_extrafield" href="#collapseFour" aria-expanded="true" aria-controls="collapseFour">'.get_lang('ThemesObjectifs').'</a></div>');
394
$form->addHtml('<div id="collapseFour" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingFour">');
395
$form->addHtml('<div class="panel-body"><p class="text-info">'.get_lang('ThemesObjectifsExplanation').'</p>');
396
397
$showOnlyThisFields = [
398
    'domaine',
399
    'filiere',
400
    $theme,
401
];
402
403
$extra = $extraField->addElements(
404
    $form,
405
    '',
406
    [],
407
    false, //filter
408
    true,
409
    $showOnlyThisFields,
410
    $showOnlyThisFields,
411
    $defaults,
412
    false, //$orderDependingDefaults
413
    true, // force
414
    ['domaine' => 3, $theme => 5], // $separateExtraMultipleSelect
415
    [
416
        'domaine' => [
417
            get_lang('Domaine').' 1',
418
            get_lang('Domaine').' 2',
419
            get_lang('Domaine').' 3',
420
        ],
421
        $theme => [
422
            get_lang('ThemeField').' 1',
423
            get_lang('ThemeField').' 2',
424
            get_lang('ThemeField').' 3',
425
            get_lang('ThemeField').' 4',
426
            get_lang('ThemeField').' 5',
427
        ],
428
    ],
429
    true
430
);
431
432
// Commented because BT#15776
433
$fieldsToShow = [
434
    'langue_cible',
435
];
436
437
$extra = $extraFieldUser->addElements(
438
    $form,
439
    $userToLoad,
440
    [],
441
    $filter,
442
    true,
443
    $fieldsToShow,
444
    $fieldsToShow,
445
    [],
446
    false,
447
    $forceShowFields //$forceShowFields = false
448
);
449
450
$form->addHtml('</div></div></div>');
451
$form->addHtml('<div class="panel panel-default">');
452
$form->addHtml('<div class="panel-heading"><input type="checkbox" name="search_using_3" '.$searchChecked3.' />&nbsp;<a role="button" data-toggle="collapse" data-parent="#search_extrafield" href="#collapseFive" aria-expanded="true" aria-controls="collapseFive">'.get_lang('NiveauLangue').'</a></div>');
453
$form->addHtml('<div id="collapseFive" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingFive">');
454
$form->addHtml('<div class="panel-body"><p class="text-info">'.get_lang('NiveauLangueExplanation').'</p>');
455
456
$showOnlyThisFields = [
457
    'ecouter',
458
    'lire',
459
    'participer_a_une_conversation',
460
    's_exprimer_oralement_en_continu',
461
    'ecrire',
462
];
463
464
$extra = $extraField->addElements(
465
    $form,
466
    '',
467
    [],
468
    false, //filter
469
    true,
470
    $showOnlyThisFields,
471
    $showOnlyThisFields,
472
    $defaults,
473
    false, //$orderDependingDefaults
474
    true, // force
475
    ['domaine' => 3, $theme => 5], // $separateExtraMultipleSelect
476
    [
477
        'domaine' => [
478
            get_lang('Domaine').' 1',
479
            get_lang('Domaine').' 2',
480
            get_lang('Domaine').' 3',
481
        ],
482
        $theme => [
483
            get_lang('Theme').' 1',
484
            get_lang('Theme').' 2',
485
            get_lang('Theme').' 3',
486
            get_lang('Theme').' 4',
487
            get_lang('Theme').' 5',
488
        ],
489
    ]
490
);
491
492
$form->addHtml('</div></div></div>');
493
494
// Enviroment
495
$userForm->addHtml('<div class="panel panel-default">');
496
$userForm->addHtml(
497
    '<div class="panel-heading">
498
    <a role="button" data-toggle="collapse" data-parent="#search_extrafield" href="#collapseEight" aria-expanded="true" aria-controls="collapseEight">'.
499
    get_lang('MonEnvironnementDeTravail').'</a></div>');
500
$userForm->addHtml('<div id="collapseEight" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingEight">');
501
$userForm->addHtml('<div class="panel-body"><p class="text-info">'.get_lang('MonEnvironnementDeTravailExplanation').'</p>');
502
503
$fieldsToShow = [
504
    'outil_de_travail_ordinateur',
505
    'outil_de_travail_ordinateur_so',
506
    'outil_de_travail_tablette',
507
    'outil_de_travail_tablette_so',
508
    'outil_de_travail_smartphone',
509
    'outil_de_travail_smartphone_so',
510
];
511
512
$userForm->addLabel(null, get_lang('MonEnvironnementDeTravailExplanationIntro1'));
513
514
$extra = $extraFieldUser->addElements(
515
    $userForm,
516
    $userToLoad,
517
    [],
518
    $filter,
519
    true,
520
    $fieldsToShow,
521
    $fieldsToShow,
522
    [],
523
    false,
524
    $forceShowFields
525
);
526
527
$userForm->addLabel(null, get_lang('MonEnvironnementDeTravailExplanationIntro2'));
528
529
$jqueryExtra .= $extra['jquery_ready_content'];
530
531
$fieldsToShow = [
532
    'browser_platforme',
533
    'browser_platforme_autre',
534
    'browser_platforme_version',
535
];
536
$extra = $extraFieldUser->addElements(
537
    $userForm,
538
    $userToLoad,
539
    [],
540
    $filter,
541
    true,
542
    $fieldsToShow,
543
    $fieldsToShow,
544
    [],
545
    false,
546
    $forceShowFields, //$forceShowFields = false
547
    [],
548
    []
549
);
550
551
$jqueryExtra .= $extra['jquery_ready_content'];
552
553
$userForm->addHtml('<p class="text-info">'.get_lang('MonEnvironnementDeTravailRenvoiFAQ').'</p>');
554
555
$userForm->addButtonSave(get_lang('Save'), 'submit_partial[collapseEight]');
556
$userForm->addHtml('</div></div></div>');
557
558
$form->addButtonSave(get_lang('SaveDiagnosticChanges'), 'save');
559
$form->addButtonSearch(get_lang('SearchSessions'), 'search');
560
561
$extraFieldsToFilter = $extraField->get_all(['variable = ?' => 'temps_de_travail']);
562
$extraFieldToSearch = [];
563
if (!empty($extraFieldsToFilter)) {
564
    foreach ($extraFieldsToFilter as $filter) {
565
        $extraFieldToSearch[] = $filter['id'];
566
    }
567
}
568
$extraFieldListToString = implode(',', $extraFieldToSearch);
569
570
$result = SessionManager::getGridColumns('simple', $extraFieldsToFilter);
571
$columns = $result['columns'];
572
$column_model = $result['column_model'];
573
574
$form->setDefaults($defaults);
575
576
/** @var HTML_QuickForm_select $element */
577
$domaine1 = $form->getElementByName('extra_domaine[0]');
578
$domaine2 = $form->getElementByName('extra_domaine[1]');
579
$domaine3 = $form->getElementByName('extra_domaine[2]');
580
$userForm->setDefaults($defaults);
581
582
$domainList = array_merge(
583
    is_object($domaine1) && !empty($domaine1->getValue()) ? $domaine1->getValue() : [],
584
    is_object($domaine3) && !empty($domaine3->getValue()) ? $domaine3->getValue() : [],
585
    is_object($domaine2) && !empty($domaine2->getValue()) ? $domaine2->getValue() : []
586
);
587
588
$themeList = [];
589
$extraField = new ExtraField('session');
590
$resultOptions = $extraField->searchOptionsFromTags('extra_domaine', 'extra_'.$theme, $domainList);
591
592
if ($resultOptions) {
593
    $resultOptions = array_column($resultOptions, 'tag', 'id');
594
    $resultOptions = array_filter($resultOptions);
595
596
    for ($i = 0; $i < 5; $i++) {
597
        /** @var HTML_QuickForm_select $theme */
598
        $themeElement = $form->getElementByName('extra_'.$theme.'['.$i.']');
599
        foreach ($resultOptions as $key => $value) {
600
            $themeElement->addOption($value, $value);
601
        }
602
    }
603
}
604
605
$filterToSend = '';
606
if ($formSearch->validate()) {
607
    $formSearchParams = $formSearch->getSubmitValues();
608
}
609
610
// Search filter
611
$filters = [];
612
foreach ($defaults as $key => $value) {
613
    if (substr($key, 0, 6) != 'extra_' && substr($key, 0, 7) != '_extra_') {
614
        continue;
615
    }
616
    if (!empty($value)) {
617
        $filters[$key] = $value;
618
    }
619
}
620
621
$filterToSend = [];
622
if (!empty($filters)) {
623
    $filterToSend = ['groupOp' => 'AND'];
624
    if ($filters) {
625
        $count = 1;
626
        $countExtraField = 1;
627
        foreach ($result['column_model'] as $column) {
628
            if ($count > 5) {
629
                if (isset($filters[$column['name']])) {
630
                    $defaultValues['jqg'.$countExtraField] = $filters[$column['name']];
631
                    /*switch ($column['name']) {
632
                        case 'extra_theme_it':
633
                        case 'extra_theme_de':
634
                        case 'extra_theme_es':
635
                        case 'extra_theme_fr':
636
                            break;
637
                        case 'extra_domaine':
638
                            break;
639
                        case '':
640
                            break;
641
                    }*/
642
                    $filterToSend['rules'][] = ['field' => $column['name'], 'op' => 'cn', 'data' => $filters[$column['name']]];
643
                }
644
                $countExtraField++;
645
            }
646
            $count++;
647
        }
648
    }
649
}
650
651
$params = [];
652
if ($form->validate()) {
653
    $params = $form->getSubmitValues();
654
    $save = false;
655
    $search = false;
656
    if (isset($params['search'])) {
657
        unset($params['search']);
658
        $search = true;
659
    }
660
661
    if (isset($params['save'])) {
662
        $save = true;
663
        unset($params['save']);
664
    }
665
666
    $form->setDefaults($params);
667
668
    $filters = [];
669
670
    // Search
671
    if ($search) {
672
        // Parse params.
673
        foreach ($params as $key => $value) {
674
            if (substr($key, 0, 6) != 'extra_' && substr($key, 0, 7) != '_extra_') {
675
                continue;
676
            }
677
            if (!empty($value)) {
678
                $filters[$key] = $value;
679
            }
680
        }
681
682
        $filterToSend = [];
683
        if (!empty($filters)) {
684
            $filterToSend = ['groupOp' => 'AND'];
685
            if ($filters) {
686
                $count = 1;
687
                $countExtraField = 1;
688
                foreach ($result['column_model'] as $column) {
689
                    if ($count > 5) {
690
                        if (isset($filters[$column['name']])) {
691
                            $defaultValues['jqg'.$countExtraField] = $filters[$column['name']];
692
                            $filterToSend['rules'][] = [
693
                                'field' => $column['name'],
694
                                'op' => 'cn',
695
                                'data' => $filters[$column['name']],
696
                            ];
697
                        }
698
                        $countExtraField++;
699
                    }
700
                    $count++;
701
                }
702
            }
703
        }
704
    }
705
706
    if ($save) {
707
        $userData = $params;
708
        // Update extra_heures_disponibilite_par_semaine
709
        $extraFieldValue = new ExtraFieldValue('user');
710
        $userDataToSave = [
711
            'item_id' => $userToLoad,
712
            'extra_heures_disponibilite_par_semaine' => isset($userData['extra_heures_disponibilite_par_semaine']) ? $userData['extra_heures_disponibilite_par_semaine'] : '',
713
            'extra_langue_cible' => isset($userData['extra_langue_cible']) ? $userData['extra_langue_cible'] : '',
714
        ];
715
        $extraFieldValue->saveFieldValues(
716
            $userDataToSave,
717
            true,
718
            false,
719
            ['heures_disponibilite_par_semaine', 'langue_cible'],
720
            [],
721
            true
722
        );
723
724
        // Save session search
725
        /** @var \Chamilo\UserBundle\Entity\User $user */
726
        $user = $em->getRepository('ChamiloUserBundle:User')->find($userToLoad);
727
        $extraFieldValueSession = new ExtraFieldValue('session');
728
729
        $sessionFields = [
730
            'extra_access_start_date',
731
            'extra_access_end_date',
732
            'extra_filiere',
733
            'extra_domaine',
734
            'extra_domaine[0]',
735
            'extra_domaine[1]',
736
            'extra_domaine[3]',
737
            'extra_temps_de_travail',
738
            //'extra_competenceniveau',
739
            'extra_'.$theme,
740
            'extra_ecouter',
741
            'extra_lire',
742
            'extra_participer_a_une_conversation',
743
            'extra_s_exprimer_oralement_en_continu',
744
            'extra_ecrire',
745
        ];
746
747
        foreach ($userData as $key => $value) {
748
            $found = strpos($key, '__persist__');
749
            if ($found === false) {
750
                continue;
751
            }
752
        }
753
754
        if (isset($userData['extra_filiere_want_stage']) &&
755
            isset($userData['extra_filiere_want_stage']['extra_filiere_want_stage'])
756
        ) {
757
            $wantStage = $userData['extra_filiere_want_stage']['extra_filiere_want_stage'];
758
759
            if ($wantStage === 'yes') {
760
                if (isset($userData['extra_filiere_user'])) {
761
                    $userData['extra_filiere'] = [];
762
                    $userData['extra_filiere']['extra_filiere'] = $userData['extra_filiere_user']['extra_filiere_user'];
763
                }
764
            }
765
        }
766
767
        // save in ExtraFieldSavedSearch.
768
        foreach ($userData as $key => $value) {
769
            if (substr($key, 0, 6) != 'extra_' && substr($key, 0, 7) != '_extra_') {
770
                continue;
771
            }
772
773
            if (!in_array($key, $sessionFields)) {
774
                continue;
775
            }
776
777
            $field_variable = substr($key, 6);
778
            $extraFieldInfo = $extraFieldValueSession
779
                ->getExtraField()
780
                ->get_handler_field_info_by_field_variable($field_variable);
781
782
            if (!$extraFieldInfo) {
783
                continue;
784
            }
785
786
            $extraFieldObj = $em->getRepository('ChamiloCoreBundle:ExtraField')->find($extraFieldInfo['id']);
787
788
            $search = [
789
                'field' => $extraFieldObj,
790
                'user' => $user,
791
            ];
792
793
            /** @var ExtraFieldSavedSearch $saved */
794
            $saved = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findOneBy($search);
795
796
            if ($saved) {
797
                $saved
798
                    ->setField($extraFieldObj)
799
                    ->setUser($user)
800
                    ->setValue($value)
801
                ;
802
                $em->merge($saved);
803
            } else {
804
                $saved = new ExtraFieldSavedSearch();
805
                $saved
806
                    ->setField($extraFieldObj)
807
                    ->setUser($user)
808
                    ->setValue($value)
809
                ;
810
                $em->persist($saved);
811
            }
812
            $em->flush();
813
        }
814
        Display::addFlash(Display::return_message(get_lang('Saved'), 'success'));
815
        header('Location: '.api_get_self().'?user_id='.$userToLoad);
816
        exit;
817
    }
818
}
819
820
$view = $form->returnForm();
821
822
$jsTag = '';
823
if (!empty($tagsData)) {
824
    foreach ($tagsData as $extraField => $tags) {
825
        foreach ($tags as $tag) {
826
            $tag = api_htmlentities($tag);
827
        }
828
    }
829
}
830
831
$htmlHeadXtra[] = '<script>
832
$(function() {
833
    '.$jqueryExtra.'
834
    '.$jsTag.'
835
});
836
</script>';
837
838
if (!empty($filterToSend)) {
839
    if (isset($params['search_using_1'])) {
840
        // Get start and end date from ExtraFieldSavedSearch
841
        $defaultExtraStartDate = isset($defaults['extra_access_start_date']) ? $defaults['extra_access_start_date'] : '';
842
        $defaultExtraEndDate = isset($defaults['extra_access_end_date']) ? $defaults['extra_access_end_date'] : '';
843
844
        $userStartDate = isset($params['extra_access_start_date']) ? $params['extra_access_start_date'] : $defaultExtraStartDate;
845
        $userEndDate = isset($params['extra_access_end_date']) ? $params['extra_access_end_date'] : $defaultExtraEndDate;
846
847
        // Minus 3 days
848
        $date = new DateTime($userStartDate);
849
        $date->sub(new DateInterval('P3D'));
850
        $userStartDateMinus = $date->format('Y-m-d h:i:s');
851
852
        // Plus 2 days
853
        $date = new DateTime($userEndDate);
854
        $date->add(new DateInterval('P2D'));
855
        $userEndDatePlus = $date->format('Y-m-d h:i:s');
856
857
        // Ofaj fix
858
        $userStartDateMinus = api_get_utc_datetime(substr($userStartDateMinus, 0, 11).'00:00:00');
859
        $userEndDatePlus = api_get_utc_datetime(substr($userEndDatePlus, 0, 11).'23:59:59');
860
861
        // Special OFAJ date logic
862
        if ($userEndDate == '') {
863
            $sql = " AND (
864
                (s.access_start_date >= '$userStartDateMinus') OR
865
                ((s.access_start_date = '' OR s.access_start_date IS NULL) AND (s.access_end_date = '' OR s.access_end_date IS NULL))
866
            )";
867
        } else {
868
            $sql = " AND (
869
                (s.access_start_date >= '$userStartDateMinus' AND s.access_end_date < '$userEndDatePlus') OR
870
                (s.access_start_date >= '$userStartDateMinus' AND (s.access_end_date = '' OR s.access_end_date IS NULL)) OR
871
                ((s.access_start_date = '' OR s.access_start_date IS NULL) AND (s.access_end_date = '' OR s.access_end_date IS NULL))
872
            )";
873
        }
874
    }
875
876
    $deleteFiliere = false;
877
    $extraFieldOptions = new ExtraFieldOption('session');
878
    $extraFieldSession = new ExtraField('session');
879
880
    // Special filters
881
    // see https://task.beeznest.com/issues/10849#change-81902
882
    foreach ($filterToSend['rules'] as &$filterItem) {
883
        if (isset($filterItem['field'])) {
884
            switch ($filterItem['field']) {
885
                case 'extra_filiere':
886
                case 'extra_domaine':
887
                case 'extra_theme_it':
888
                case 'extra_theme_fr':
889
                case 'extra_theme_de':
890
                case 'extra_theme_pl':
891
                    if (!isset($params['search_using_2'])) {
892
                        $filterItem = null;
893
                    }
894
                    break;
895
            }
896
897
            switch ($filterItem['field']) {
898
                case 'extra_ecouter':
899
                case 'extra_lire':
900
                case 'extra_participer_a_une_conversation':
901
                case 'extra_s_exprimer_oralement_en_continu':
902
                case 'extra_ecrire':
903
                    if (!isset($params['search_using_3'])) {
904
                        $filterItem = null;
905
                        break;
906
                    }
907
                    $selectedValue = '';
908
                    $fieldExtra = str_replace('extra_', '', $filterItem['field']);
909
                    $extraFieldSessionData = $extraFieldSession->get_handler_field_info_by_field_variable($fieldExtra);
910
911
                    if (is_array($filterItem['data'])) {
912
                        $myOrder = [];
913
                        foreach ($filterItem['data'] as $option) {
914
                            foreach ($extraFieldSessionData['options'] as $optionValue) {
915
                                if ($option == $optionValue['option_value']) {
916
                                    $myOrder[$optionValue['option_order']] = $optionValue['option_value'];
917
                                }
918
                            }
919
                        }
920
921
                        if (!empty($myOrder)) {
922
                            // Taking last from list
923
                            $selectedValue = end($myOrder);
924
                        }
925
                    } else {
926
                        $selectedValue = $filterItem['data'];
927
                    }
928
929
                    $newOptions = array_column(
930
                        $extraFieldSessionData['options'],
931
                        'option_value',
932
                        'option_order'
933
                    );
934
935
                    $searchOptions = [];
936
                    for ($i = 1; $i < count($newOptions); $i++) {
937
                        if ($selectedValue == $newOptions[$i]) {
938
                            if (isset($newOptions[$i - 1])) {
939
                                $searchOptions[] = $newOptions[$i - 1];
940
                            }
941
                            if (isset($newOptions[$i])) {
942
                                $searchOptions[] = $newOptions[$i];
943
                            }
944
                            if (isset($newOptions[$i + 1])) {
945
                                $searchOptions[] = $newOptions[$i + 1];
946
                            }
947
                            break;
948
                        }
949
                    }
950
951
                    $filterItem['data'] = $searchOptions;
952
                    break;
953
                case 'extra_domaine':
954
                    if (!isset($params['search_using_2'])) {
955
                        break;
956
                    }
957
                    // Special condition see:
958
                    // https://task.beeznest.com/issues/10849#note-218
959
                    // Remove filiere
960
                    $list = [
961
                        'vie-quotidienne',
962
                        //'competente-dans-mon-domaine-de-specialite',
963
                        'arrivee-sur-mon-poste-de-travail',
964
                    ];
965
966
                    $deleteFiliere = false;
967
                    if (is_array($filterItem['data'])) {
968
                        $myOrder = [];
969
                        foreach ($filterItem['data'] as $option) {
970
                            if (in_array($option, $list)) {
971
                                $deleteFiliere = true;
972
                                break;
973
                            }
974
                        }
975
                    } else {
976
                        if (in_array($filterItem['data'], $list)) {
977
                            $deleteFiliere = true;
978
                        }
979
                    }
980
                    break;
981
            }
982
        }
983
984
        if ($deleteFiliere) {
985
            foreach ($filterToSend['rules'] as &$filterItem) {
0 ignored issues
show
Comprehensibility Bug introduced by
$filterItem is overwriting a variable from outer foreach loop.
Loading history...
986
                if (isset($filterItem['field']) && $filterItem['field'] == 'extra_filiere') {
987
                    $filterItem = [];
988
                }
989
            }
990
        }
991
    }
992
993
    // Language
994
    $lang = isset($params['extra_langue_cible']) ? $params['extra_langue_cible'] : $defaultLangCible;
995
    $lang = strtolower($lang);
996
997
    if (isset($params['search_using_1'])) {
998
        if ($userStartDate && !empty($userStartDate)) {
999
            $filterToSend['custom_dates'] = $sql;
1000
        }
1001
    }
1002
1003
    $filterToSend = json_encode($filterToSend);
1004
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&load_extra_field='.
1005
        $extraFieldListToString.'&_force_search=true&rows=20&page=1&sidx=&sord=asc&filters2='.$filterToSend;
1006
    if (isset($params['search_using_2'])) {
1007
        $url .= '&lang='.$lang;
1008
    }
1009
} else {
1010
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&load_extra_field='.
1011
        $extraFieldListToString.'&_force_search=true&rows=20&page=1&sidx=&sord=asc';
1012
}
1013
1014
// Autowidth
1015
$extra_params['autowidth'] = 'true';
1016
1017
// height auto
1018
$extra_params['height'] = 'auto';
1019
$extra_params['postData'] = [
1020
    'filters' => [
1021
        'groupOp' => 'AND',
1022
        'rules' => $result['rules'],
1023
    ],
1024
];
1025
1026
$sessionByUserList = SessionManager::get_sessions_by_user($userToLoad, true, true);
1027
1028
$sessionUserList = [];
1029
if (!empty($sessionByUserList)) {
1030
    foreach ($sessionByUserList as $sessionByUser) {
1031
        $sessionUserList[] = (string) $sessionByUser['session_id'];
1032
    }
1033
}
1034
$action_links = 'function action_formatter(cellvalue, options, rowObject) {
1035
    var sessionList = '.json_encode($sessionUserList).';
1036
    var id = options.rowId.toString();
1037
    if (sessionList.indexOf(id) == -1) {
1038
        return \'<a href="'.api_get_self().'?action=subscribe_user&user_id='.$userToLoad.'&session_id=\'+id+\'">'.Display::return_icon('add.png', addslashes(get_lang('Subscribe')), '', ICON_SIZE_SMALL).'</a>'.'\';
1039
    } else {
1040
        return \'<a href="'.api_get_self().'?action=unsubscribe_user&user_id='.$userToLoad.'&session_id=\'+id+\'">'.Display::return_icon('delete.png', addslashes(get_lang('Delete')), '', ICON_SIZE_SMALL).'</a>'.'\';
1041
    }
1042
}';
1043
1044
$htmlHeadXtra[] = api_get_jqgrid_js();
1045
1046
$griJs = Display::grid_js(
1047
    'sessions',
1048
    $url,
1049
    $columns,
1050
    $column_model,
1051
    $extra_params,
1052
    [],
1053
    $action_links,
1054
    true
1055
);
1056
1057
$grid = '<div id="session-table" class="table-responsive">';
1058
$grid .= Display::grid_html('sessions');
1059
$grid .= '</div>';
1060
1061
$htmlHeadXtra[] = '<style>
1062
	.control-label {
1063
	    width: 25% !important;
1064
	}
1065
</style>';
1066
1067
$htmlHeadXtra[] = '<script>
1068
$(function() {
1069
	var blocks = [
1070
        "#collapseOne",
1071
        "#collapseTwo",
1072
        "#collapseThree",
1073
        "#collapseFour",
1074
        "#collapseFive",
1075
        "#collapseSix",
1076
        "#collapseSeven",
1077
        "#collapseEight"
1078
    ];
1079
1080
    $.each(blocks, function( index, value ) {
1081
        $(value).collapse("hide");
1082
    });
1083
});
1084
</script>';
1085
1086
$tpl = new Template(get_lang('Diagnosis'));
1087
1088
if (empty($items)) {
1089
    $view = '';
1090
    $grid = '';
1091
    $griJs = '';
1092
}
1093
$tpl->assign('form', $view);
1094
$tpl->assign('form_search', $formSearch->returnForm().$userForm->returnForm());
1095
1096
$table = new HTML_Table(['class' => 'data_table']);
1097
$column = 0;
1098
$row = 0;
1099
1100
$total = '0';
1101
$sumHours = '0';
1102
$numHours = '0';
1103
1104
$field = 'heures_disponibilite_par_semaine';
1105
$extraField = new ExtraFieldValue('user');
1106
$data = $extraField->get_values_by_handler_and_field_variable($userToLoad, $field);
1107
1108
$availableHoursPerWeek = 0;
1109
1110
function dateDiffInWeeks($date1, $date2)
1111
{
1112
    if ($date1 > $date2) {
1113
        return dateDiffInWeeks($date2, $date1);
1114
    }
1115
    $first = new \DateTime($date1);
1116
    $second = new \DateTime($date2);
1117
1118
    return floor($first->diff($second)->days / 7);
1119
}
1120
1121
if ($data) {
1122
    $availableHoursPerWeek = $data['value'];
1123
    $numberWeeks = 0;
1124
    if ($form->validate()) {
1125
        $formData = $form->getSubmitValues();
1126
1127
        if (isset($formData['extra_access_start_date']) && isset($formData['extra_access_end_date'])) {
1128
            $startDate = $formData['extra_access_start_date'];
1129
            $endDate = $formData['extra_access_end_date'];
1130
            $numberWeeks = dateDiffInWeeks($startDate, $endDate);
1131
        }
1132
    } else {
1133
        if ($defaults) {
1134
            if (isset($defaults['extra_access_start_date']) && isset($defaults['extra_access_end_date'])) {
1135
                $startDate = $defaults['extra_access_start_date'];
1136
                $endDate = $defaults['extra_access_end_date'];
1137
                $numberWeeks = dateDiffInWeeks($startDate, $endDate);
1138
            }
1139
        }
1140
    }
1141
1142
    $total = $numberWeeks * $availableHoursPerWeek;
1143
    $sessions = SessionManager::getSessionsFollowedByUser($userToLoad);
1144
1145
    if ($sessions) {
1146
        $sessionFieldValue = new ExtraFieldValue('session');
1147
1148
        foreach ($sessions as $session) {
1149
            $sessionId = $session['id'];
1150
            $data = $sessionFieldValue->get_values_by_handler_and_field_variable(
1151
                $sessionId,
1152
                'temps_de_travail'
1153
            );
1154
            if ($data) {
1155
                $sumHours += $data['value'];
1156
            }
1157
        }
1158
    }
1159
}
1160
1161
$numHours = $total - $sumHours;
1162
$headers = [
1163
    get_lang('TotalAvailableHours') => $total,
1164
    get_lang('SumHoursSessionsSubscribed') => $sumHours,
1165
    get_lang('CountHoursAvailable') => $numHours,
1166
];
1167
foreach ($headers as $header => $value) {
1168
    $table->setCellContents($row, 0, $header);
1169
    $table->updateCellAttributes($row, 0, 'width="250px"');
1170
    $table->setCellContents($row, 1, $value);
1171
    $row++;
1172
}
1173
1174
$button = '';
1175
if ($userToLoad) {
1176
    $button = Display::url(
1177
        get_lang('OfajEndOfLearnPath'),
1178
        api_get_path(WEB_CODE_PATH).'messages/new_message.php?prefill=ofaj&send_to_user='.$userToLoad,
1179
        ['class' => 'btn btn-default']
1180
    );
1181
    $button .= '<br /><br />';
1182
}
1183
1184
$userReportButton = Display::url(
1185
    get_lang('DiagnosticValidateLearningPath'),
1186
    api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$userToLoad,
1187
    ['class' => 'btn btn-primary']
1188
);
1189
$tpl->assign('grid', $grid.$button.$table->toHtml().$userReportButton);
1190
$tpl->assign('grid_js', $griJs);
1191
1192
$content = $tpl->fetch('default/user_portal/search_extra_field.tpl');
1193
$tpl->assign('content', $content);
1194
$tpl->display_one_col_template();
1195