Passed
Push — master ( 65d552...4599b6 )
by Angel Fernando Quiroz
10:41
created

search_coachs()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 48
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 29
nc 7
nop 1
dl 0
loc 48
rs 8.8337
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Asset;
6
use Chamilo\CoreBundle\Framework\Container;
7
use Chamilo\CoreBundle\Entity\User;
8
use Chamilo\CoreBundle\Component\Utils\ActionIcon;
9
10
$cidReset = true;
11
12
require_once __DIR__.'/../inc/global.inc.php';
13
14
$xajax = new xajax();
15
$xajax->registerFunction('search_coachs');
16
17
// setting the section (for the tabs)
18
$this_section = SECTION_PLATFORM_ADMIN;
19
20
SessionManager::protectSession(null, false);
21
22
api_protect_limit_for_session_admin();
23
24
$formSent = 0;
25
$errorMsg = '';
26
27
$interbreadcrumb[] = [
28
    'url' => 'session_list.php',
29
    'name' => get_lang('Session list'),
30
];
31
32
function search_coachs($needle)
33
{
34
    $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
35
    $xajax_response = new xajaxResponse();
36
    $return = '';
37
38
    if (!empty($needle)) {
39
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
40
41
        // search users where username or firstname or lastname begins likes $needle
42
        $sql = 'SELECT username, lastname, firstname
43
                FROM '.$tbl_user.' user
44
                WHERE (username LIKE "'.$needle.'%"
45
                OR firstname LIKE "'.$needle.'%"
46
                OR lastname LIKE "'.$needle.'%")
47
                AND status=1'.
48
            $order_clause.
49
            ' LIMIT 10';
50
51
        if (api_is_multiple_url_enabled()) {
0 ignored issues
show
Deprecated Code introduced by
The function api_is_multiple_url_enabled() has been deprecated: Use AccessUrlHelper::isMultiple ( Ignorable by Annotation )

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

51
        if (/** @scrutinizer ignore-deprecated */ api_is_multiple_url_enabled()) {

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
52
            $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
53
            $access_url_id = api_get_current_access_url_id();
54
            if (-1 != $access_url_id) {
55
                $sql = 'SELECT username, lastname, firstname
56
                        FROM '.$tbl_user.' user
57
                        INNER JOIN '.$tbl_user_rel_access_url.' url_user
58
                        ON (url_user.user_id=user.user_id)
59
                        WHERE
60
                            access_url_id = '.$access_url_id.'  AND
61
                            (
62
                                username LIKE "'.$needle.'%" OR
63
                                firstname LIKE "'.$needle.'%" OR
64
                                lastname LIKE "'.$needle.'%"
65
                            )
66
                            AND status=1'.
67
                    $order_clause.'
68
                        LIMIT 10';
69
            }
70
        }
71
72
        $rs = Database::query($sql);
73
        while ($user = Database :: fetch_array($rs)) {
74
            $return .= '<a href="javascript: void(0);" onclick="javascript: fill_coach_field(\''.$user['username'].'\')">'.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')</a><br />';
75
        }
76
    }
77
    $xajax_response->addAssign('ajax_list_coachs', 'innerHTML', api_utf8_encode($return));
78
79
    return $xajax_response;
80
}
81
82
$urlAction = api_get_self();
83
$session = null;
84
$fromSessionId = null;
85
$accessSelected = 1;
86
if (isset($_GET['fromSessionId'])) {
87
    $fromSessionId = (int) $_GET['fromSessionId'];
88
    $session = api_get_session_entity($fromSessionId);
89
    if ($session && 0 === (int) $session->getDuration()) {
90
        $accessSelected = 1;
91
    }
92
    $urlAction .= '?fromSessionId=' . $fromSessionId;
93
}
94
95
$xajax->processRequests();
96
$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
97
$htmlHeadXtra[] = "
98
<script>
99
$(function() {
100
   setTimeout(function() {
101
        $('#access').val('".$accessSelected."').trigger('change');
102
        accessSwitcher('".$accessSelected."');
103
    }, 1000);
104
});
105
106
function fill_coach_field (username) {
107
    document.getElementById('coach_username').value = username;
108
    document.getElementById('ajax_list_coachs').innerHTML = '';
109
}
110
111
function accessSwitcher(accessFromReady) {
112
    var access = $('#access option:selected').val();
113
114
    if (accessFromReady >= 0) {
115
        access  = accessFromReady;
116
    }
117
118
    if (access == 1) {
119
        $('#duration_div').hide();
120
        $('#date_fields').show();
121
    } else {
122
        $('#duration_div').show();
123
        $('#date_fields').hide();
124
    }
125
    emptyDuration();
126
}
127
128
function emptyDuration() {
129
    if ($('#duration').val()) {
130
        $('#duration').val('');
131
    }
132
}
133
</script>";
134
135
if (isset($_POST['formSent']) && $_POST['formSent']) {
136
    $formSent = 1;
137
}
138
139
$tool_name = get_lang('Add a training session');
140
141
function check_session_name($name)
142
{
143
    $session = SessionManager::get_session_by_name($name);
144
145
    return empty($session) ? true : false;
146
}
147
148
$form = new FormValidator('add_session', 'post', $urlAction);
149
$form->addElement('header', $tool_name);
150
$result = SessionManager::setForm($form, null, $fromSessionId);
151
152
$url = api_get_path(WEB_AJAX_PATH).'session.ajax.php';
153
$urlAjaxExtraField = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?1=1';
154
155
$htmlHeadXtra[] = "
156
<script>
157
$(function() {
158
    var currentSessionId = new URL(window.location.href).searchParams.get('fromSessionId');
159
160
    function storeFormValues() {
161
        var formValues = $('#add_session').serializeArray();
162
        sessionStorage.setItem('formValues', JSON.stringify(formValues));
163
    }
164
165
    function repopulateFormValues() {
166
        var formValues = JSON.parse(sessionStorage.getItem('formValues'));
167
        $.each(formValues, function(i, field) {
168
            if (field.name === 'coach_username' || field.name === 'title' || field.name === 'system_template') {
169
                $('[name=\"' + field.name + '\"]').val(field.value);
170
            }
171
        });
172
    }
173
174
    function storeSelect2Values(selectId) {
175
        var selectedValues = $('#' + selectId).select2('data').map(function(item) {
176
            return {id: item.id, text: item.text};
177
        });
178
        sessionStorage.setItem(selectId + 'Values', JSON.stringify(selectedValues));
179
    }
180
181
    function repopulateSelect2Values(selectId) {
182
        if(sessionStorage.getItem(selectId + 'Values')) {
183
            var storedValues = JSON.parse(sessionStorage.getItem(selectId + 'Values'));
184
            $('#' + selectId).empty(); // Clear the select
185
            storedValues.forEach(function(item) {
186
                var newOption = new Option(item.text, item.id, true, true);
187
                $('#' + selectId).append(newOption).trigger('change');
188
            });
189
        }
190
    }
191
192
    if(currentSessionId) {
193
        if(sessionStorage.getItem('formValues')) {
194
            repopulateFormValues();
195
        }
196
        repopulateSelect2Values('coach_username');
197
        repopulateSelect2Values('system_template');
198
    } else {
199
        sessionStorage.clear(); // Clear session storage if no currentSessionId
200
    }
201
202
    $('#system_template').on('change', function() {
203
        storeFormValues();
204
        storeSelect2Values('coach_username');
205
        storeSelect2Values('system_template');
206
        var selectedSessionId = $(this).find('option:selected').val();
207
        window.location.href = '/main/session/session_add.php?fromSessionId=' + selectedSessionId;
208
    });
209
210
    // Attach event to form submit to clear sessionStorage
211
    $('#add_session').on('submit', function() {
212
        sessionStorage.removeItem('coach_usernameValues');
213
        sessionStorage.removeItem('system_templateValues');
214
        sessionStorage.removeItem('formValues');
215
    });
216
217
    ".$result['js']."
218
});
219
</script>";
220
221
$form->addButtonNext(get_lang('Next step'));
222
223
$formDefaults = [];
224
if (!$formSent) {
225
    if ($session) {
226
        $formDefaults = [
227
            'id' => $session->getId(),
228
            'session_category' => $session->getCategory()?->getId(),
229
            'description' => $session->getDescription(),
230
            'show_description' => $session->getShowDescription(),
231
            'duration' => $session->getDuration(),
232
            'session_visibility' => $session->getVisibility(),
233
            'display_start_date' => $session->getDisplayStartDate() ? api_get_local_time($session->getDisplayStartDate()) : null,
234
            'display_end_date' => $session->getDisplayEndDate() ? api_get_local_time($session->getDisplayEndDate()) : null,
235
            'access_start_date' => $session->getAccessStartDate() ? api_get_local_time($session->getAccessStartDate()) : null,
236
            'access_end_date' => $session->getAccessEndDate() ? api_get_local_time($session->getAccessEndDate()) : null,
237
            'coach_access_start_date' => $session->getCoachAccessStartDate() ? api_get_local_time($session->getCoachAccessStartDate()) : null,
238
            'coach_access_end_date' => $session->getCoachAccessEndDate() ? api_get_local_time($session->getCoachAccessEndDate()) : null,
239
            'send_subscription_notification' => $session->getSendSubscriptionNotification(),
240
            'coach_username' => array_map(
241
                function (User $user) {
242
                    return $user->getId();
243
                },
244
                $session->getGeneralCoaches()->getValues()
245
            ),
246
            'session_template' => $session->getTitle(),
247
        ];
248
    } else {
249
        $formDefaults['access_start_date'] = $formDefaults['display_start_date'] = api_get_local_time();
250
        $formDefaults['coach_username'] = [api_get_user_id()];
251
    }
252
}
253
254
$form->setDefaults($formDefaults);
255
256
if ($form->validate()) {
257
    $params = $form->getSubmitValues();
258
    $title = $params['title'];
259
    $startDate = $params['access_start_date'];
260
    $endDate = $params['access_end_date'];
261
    $displayStartDate = $params['display_start_date'];
262
    $displayEndDate = $params['display_end_date'];
263
    $coachStartDate = $params['coach_access_start_date'];
264
    if (empty($coachStartDate)) {
265
        $coachStartDate = $displayStartDate;
266
    }
267
    $coachEndDate = $params['coach_access_end_date'];
268
    $coachUsername = $params['coach_username'];
269
    $id_session_category = (int) $params['session_category'];
270
    $id_visibility = $params['session_visibility'];
271
    $duration = isset($params['duration']) ? $params['duration'] : null;
272
    $description = $params['description'];
273
    $showDescription = isset($params['show_description']) ? 1 : 0;
274
    $sendSubscriptionNotification = isset($params['send_subscription_notification']);
275
    $isThisImageCropped = isset($params['picture_crop_result']);
276
    $status = isset($params['status']) ? $params['status'] : 0;
277
278
    $extraFields = [];
279
    foreach ($params as $key => $value) {
280
        if (0 === strpos($key, 'extra_')) {
281
            $extraFields[$key] = $value;
282
        }
283
    }
284
285
    if (isset($extraFields['extra_image']) && !empty($extraFields['extra_image']['name']) && $isThisImageCropped) {
286
        $extraFields['extra_image']['crop_parameters'] = $params['picture_crop_result'];
287
    }
288
289
    // Check if the session image will be copied from the template
290
    $importImageFromSession = false;
291
    $sessionIdToImport = !empty($params['extra_image_crop_result']) ? explode('::', $params['extra_image_crop_result']) : [];
292
    $sessionIdToImport = isset($sessionIdToImport[1]) ? (int) $sessionIdToImport[1] : 0;
293
    if (!empty($sessionIdToImport)) {
294
        $extraField = new ExtraField('session');
295
        $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable('image');
296
297
        $extraFieldValue = new ExtraFieldValue('session');
298
        $extraFieldValueData = $extraFieldValue->get_values_by_handler_and_field_id(
299
            $sessionIdToImport,
300
            $extraFieldInfo['id']
301
        );
302
303
        if ($extraFieldValueData) {
304
            $repo = Container::getAssetRepository();
305
            /** @var Asset $asset */
306
            $asset = $repo->find($extraFieldValueData);
307
            if ($asset) {
0 ignored issues
show
introduced by
$asset is of type Asset, thus it always evaluated to true.
Loading history...
308
                $extraFields['extra_image']['id'] = $extraFieldValueData;
309
            }
310
        }
311
    }
312
313
    $return = SessionManager::create_session(
314
        $title,
315
        $startDate,
316
        $endDate,
317
        $displayStartDate,
318
        $displayEndDate,
319
        $coachStartDate,
320
        $coachEndDate,
321
        $coachUsername,
322
        $id_session_category,
323
        $id_visibility,
324
        false,
325
        $duration,
326
        $description,
327
        $showDescription,
328
        $extraFields,
329
        null,
330
        $sendSubscriptionNotification,
331
        api_get_current_access_url_id(),
332
        $status
333
    );
334
335
    if ($return == strval(intval($return))) {
336
        if (!empty($_FILES['picture']['tmp_name'])) {
337
            // Add image
338
            $picture = $_FILES['picture'];
339
            if (!empty($picture['name'])) {
340
                SessionManager::updateSessionPicture(
341
                    $return,
342
                    $picture,
343
                    $params['picture_crop_result']
344
                );
345
            }
346
        } else {
347
            if (isset($_POST['image_session_template'])) {
348
                $assetUrl = Security::remove_XSS($_POST['image_session_template']);
349
                $path = parse_url($assetUrl, PHP_URL_PATH);
350
                $filename = basename($path);
351
                $tmpName = api_get_path(SYS_PATH).'../var/upload'.$path;
352
                $fileArray = [
353
                    'tmp_name' => $tmpName,
354
                    'name' => $filename,
355
                    'error' => 0,
356
                    'size' => filesize($tmpName),
357
                ];
358
                SessionManager::updateSessionPicture(
359
                    $return,
360
                    $fileArray
361
                );
362
            }
363
        }
364
365
        // integer => no error on session creation
366
        header('Location: add_courses_to_session.php?id_session='.$return.'&add=true');
367
        exit();
368
    }
369
}
370
371
Display::display_header($tool_name);
372
373
if (!empty($return)) {
374
    echo Display::return_message($return, 'error', false);
375
}
376
377
$actions = '<a href="../session/session_list.php">'.
378
    Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back to').' '.get_lang('Administration')).'</a>';
379
echo Display::toolbarAction('session', [$actions]);
380
$form->display();
381
382
Display::display_footer();
383