Passed
Pull Request — master (#5678)
by Angel Fernando Quiroz
13:02 queued 06:11
created

search_coachs()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 35
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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