Passed
Push — master ( eb5e0a...958cb0 )
by
unknown
17:45 queued 08:42
created

is_fallback_username()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/*
6
 * @author Julio Montoya <[email protected]>
7
 */
8
9
use Chamilo\CoreBundle\Entity\User;
10
use Chamilo\CoreBundle\Enums\ActionIcon;
11
use Chamilo\CoreBundle\Framework\Container;
12
13
$cidReset = true;
14
15
require_once __DIR__.'/../inc/global.inc.php';
16
$xajax = new xajax();
17
$xajax->registerFunction(['search_users', 'AccessUrlEditUsersToUrl', 'search_users']);
18
19
// setting the section (for the tabs)
20
$this_section = SECTION_PLATFORM_ADMIN;
21
22
api_protect_global_admin_script();
23
24
if (!api_get_multiple_access_url()) {
25
    header('Location: index.php');
26
27
    exit;
28
}
29
30
// Database Table Definitions
31
$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
32
// setting breadcrumbs
33
$tool_name = get_lang('Edit users and URLs');
34
$interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('Administration')];
35
$interbreadcrumb[] = ['url' => 'access_urls.php', 'name' => get_lang('Multiple access URL / Branding')];
36
37
$add_type = 'multiple';
38
if (isset($_REQUEST['add_type']) && '' != $_REQUEST['add_type']) {
39
    $add_type = Security::remove_XSS($_REQUEST['add_type']);
40
}
41
42
$access_url_id = 1;
43
if (isset($_REQUEST['access_url_id']) && '' != $_REQUEST['access_url_id']) {
44
    $access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
45
}
46
47
$xajax->processRequests();
48
$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
49
$htmlHeadXtra[] = '<script>
50
function add_user_to_url(code, content) {
51
	document.getElementById("user_to_add").value = "";
52
	document.getElementById("ajax_list_users").innerHTML = "";
53
	destination = document.getElementById("destination_users");
54
	destination.options[destination.length] = new Option(content,code);
55
	destination.selectedIndex = -1;
56
	sortOptions(destination.options);
57
}
58
59
function send() {
60
	if (document.formulaire.access_url_id.value!=0) {
61
		document.formulaire.form_sent.value=0;
62
		document.formulaire.add_type.value=\''.$add_type.'\';
63
		document.formulaire.submit();
64
	}
65
}
66
67
function remove_item(origin) {
68
	for(var i = 0 ; i<origin.options.length ; i++) {
69
		if(origin.options[i].selected) {
70
			origin.options[i]=null;
71
			i = i-1;
72
		}
73
	}
74
}
75
</script>';
76
77
$message = '';
78
79
if (isset($_POST['form_sent']) && $_POST['form_sent']) {
80
    $form_sent = $_POST['form_sent'];
81
    $UserList = $_POST['sessionUsersList'] ?? [];
82
    if (!is_array($UserList)) {
83
        $UserList = [];
84
    }
85
    if (1 == $form_sent) {
86
        if (0 == $access_url_id) {
87
            Display::addFlash(Display::return_message(get_lang('Select a URL')));
88
            header('Location: access_url_edit_users_to_url.php');
89
90
            exit;
91
        }
92
        if (is_array($UserList)) {
93
            $result = UrlManager::update_urls_rel_user($UserList, $access_url_id, true);
94
            $url_info = UrlManager::get_url_data_from_id($access_url_id);
95
            if (!empty($result)) {
96
                $message .= 'URL: '.$url_info['url'].'<br />';
97
            }
98
99
            if (!empty($result['users_added'])) {
100
                $message .= '<h4>'.get_lang('Users added').':</h4>';
101
                $i = 1;
102
                $user_added_list = [];
103
                foreach ($result['users_added'] as $user) {
104
                    $user_info = api_get_user_info($user);
105
                    if (!empty($user_info)) {
106
                        $user_added_list[] = $i.'. '.api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, null, $user_info['username']);
107
                        $i++;
108
                    }
109
                }
110
                if (!empty($user_added_list)) {
111
                    $message .= implode(', ', $user_added_list);
112
                }
113
            }
114
115
            if (!empty($result['users_deleted'])) {
116
                $message .= '<br /><h4>'.get_lang('Users deleted').': </h4>';
117
                $user_deleted_list = [];
118
                $i = 1;
119
                foreach ($result['users_deleted'] as $user) {
120
                    $user_info = api_get_user_info($user);
121
                    if (!empty($user_info)) {
122
                        $user_deleted_list[] = $i.'. '.api_get_person_name($user_info['firstname'], $user_info['lastname']);
123
                        $i++;
124
                    }
125
                }
126
                if (!empty($user_deleted_list)) {
127
                    $message .= implode(', ', $user_deleted_list);
128
                }
129
            }
130
        }
131
    }
132
}
133
134
Display::display_header($tool_name);
135
136
if (!empty($message)) {
137
    echo Display::return_message($message, 'normal', false);
138
}
139
140
echo '<div class="flex gap-2 items-center mb-4 mt-4">';
141
echo Display::url(
142
    Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
143
    api_get_path(WEB_CODE_PATH).'admin/access_urls.php'
144
);
145
echo Display::url(
146
    Display::getMdiIcon(ActionIcon::MULTI_COURSE_URL_ASSIGN, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add user to this URL')),
147
    api_get_path(WEB_CODE_PATH).'admin/access_url_add_users_to_url.php'
148
);
149
150
$urlAddCsv = Container::getRouter()->generate('chamilo_core_access_url_users_import');
151
$urlRemoveCsv = Container::getRouter()->generate('chamilo_core_access_url_users_remove');
152
echo Display::url(
153
    Display::getMdiIcon(ActionIcon::IMPORT_USERS_TO_URL, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Assign users to URLs from CSV')),
154
    $urlAddCsv
155
);
156
157
echo Display::url(
158
    Display::getMdiIcon(ActionIcon::REMOVE_USERS_FROM_URL, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Remove users from URLs with a CSV file')),
159
    $urlRemoveCsv
160
);
161
echo '</div>';
162
163
Display::page_subheader2($tool_name);
164
165
/**
166
 * Small helper to skip technical/fallback users from lists.
167
 *
168
 * We avoid relying only on status when data comes from UrlManager::get_url_rel_user_data(),
169
 * because that result might not include the status field.
170
 */
171
function is_fallback_username(array $user): bool
172
{
173
    return isset($user['username']) && 'fallback_user' === $user['username'];
174
}
175
176
?>
177
    <h2 class="text-xl font-semibold text-gray-800 mt-4 mb-2">
178
        <?php echo $tool_name; ?>
179
    </h2>
180
<?php
181
$nosessionUsersList = $sessionUsersList = [];
182
$ajax_search = 'unique' === $add_type ? true : false;
183
184
if ($ajax_search) {
185
    $Users = UrlManager::get_url_rel_user_data($access_url_id);
186
    foreach ($Users as $user) {
187
        if (is_fallback_username($user)) {
188
            continue;
189
        }
190
191
        $sessionUsersList[$user['user_id']] = $user;
192
    }
193
} else {
194
    $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
195
196
    $Users = UrlManager::get_url_rel_user_data(null, $order_clause);
197
    foreach ($Users as $user) {
198
        if (is_fallback_username($user)) {
199
            continue;
200
        }
201
202
        if ($user['access_url_id'] == $access_url_id) {
203
            $sessionUsersList[$user['user_id']] = $user;
204
        }
205
    }
206
207
    $sql = "SELECT
208
                u.id as user_id,
209
                u.lastname,
210
                u.firstname,
211
                u.username
212
            FROM $tbl_user u
213
            WHERE u.status NOT IN (".ANONYMOUS.', '.User::ROLE_FALLBACK.')
214
            '.$order_clause;
215
216
    $result = Database::query($sql);
217
    $Users = Database::store_result($result);
218
    $user_list_leys = array_keys($sessionUsersList);
219
    foreach ($Users as $user) {
220
        if (is_fallback_username($user)) {
221
            continue;
222
        }
223
224
        if (!in_array($user['user_id'], $user_list_leys)) {
225
            $nosessionUsersList[$user['user_id']] = $user;
226
        }
227
    }
228
}
229
$total_users = count($nosessionUsersList) + count($sessionUsersList);
230
$urlList = Container::getAccessUrlRepository()->findAll();
231
232
$url_selected = '';
233
foreach ($urlList as $url) {
234
    if ($url->getId() == $access_url_id) {
235
        $url_selected = $url->getUrl();
236
237
        break;
238
    }
239
}
240
241
?>
242
    <div class="flex space-x-2 border-gray-300 pb-2 mb-4">
243
        <a href="<?php echo api_get_self(); ?>?add_type=unique&access_url_id=<?php echo $access_url_id; ?>"
244
           class="text-sm px-4 py-2 transition <?php echo 'unique' === $add_type
245
               ? 'border-b-2 border-primary text-primary font-semibold'
246
               : 'text-gray-500 hover:text-primary'; ?>">
247
            <?php echo get_lang('Single registration'); ?>
248
        </a>
249
250
        <a href="<?php echo api_get_self(); ?>?add_type=multiple&access_url_id=<?php echo $access_url_id; ?>"
251
           class="text-sm px-4 py-2 transition <?php echo 'multiple' === $add_type
252
               ? 'border-b-2 border-primary text-primary font-semibold'
253
               : 'text-gray-500 hover:text-primary'; ?>">
254
            <?php echo get_lang('Multiple registration'); ?>
255
        </a>
256
    </div>
257
258
<br /><br />
259
    <form
260
        name="formulaire"
261
        method="post"
262
        action="<?php echo api_get_self(); ?>"
263
        class="space-y-6"
264
        <?php if ($ajax_search) {
265
            echo 'onsubmit="valide();"';
266
        } ?>
267
    >
268
        <input type="hidden" name="form_sent" value="1" />
269
        <input type="hidden" name="add_type" value="<?php echo $add_type; ?>" />
270
271
        <!-- URL selector -->
272
        <div class="flex items-center space-x-4">
273
            <label for="access_url_id" class="text-sm font-medium text-gray-700">
274
                <?php echo get_lang('Select URL'); ?>
275
            </label>
276
            <select
277
                name="access_url_id"
278
                id="access_url_id"
279
                onchange="send();"
280
                class="w-1/2 rounded-md border border-gray-300 bg-white p-2 shadow-sm focus:border-primary focus:ring-primary"
281
            >
282
                <option value="0"><?php echo get_lang('Select URL'); ?></option>
283
                <?php foreach ($urlList as $url) { ?>
284
                    <?php
285
                    $selected = (!empty($access_url_id) && $url->getId() == $access_url_id) ? 'selected' : '';
286
                    if (1 == $url->getActive()) {
287
                        ?>
288
                        <option value="<?php echo $url->getId(); ?>" <?php echo $selected; ?>>
289
                            <?php echo $url->getUrl(); ?>
290
                        </option>
291
                    <?php } ?>
292
                <?php } ?>
293
            </select>
294
        </div>
295
296
        <div class="text-sm text-gray-600">
297
            <p><?php echo get_lang('Total available users').': '.$total_users; ?></p>
298
            <p class="mt-1"><?php echo get_lang('Portal users list').': '.count($nosessionUsersList); ?></p>
299
            <p class="mt-1"><?php echo get_lang('Users of').' '.$url_selected.': '.count($sessionUsersList); ?></p>
300
        </div>
301
302
        <div class="grid grid-cols-3 gap-4">
303
            <div>
304
                <label class="block mb-2 text-sm font-medium text-gray-700"><?php echo get_lang('Available users'); ?></label>
305
                <?php if ($ajax_search) { ?>
306
                    <input
307
                        type="text"
308
                        id="user_to_add"
309
                        onkeyup="xajax_search_users(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)"
310
                        class="w-full rounded-md border border-gray-300 p-2 text-sm focus:border-primary focus:ring-primary"
311
                    />
312
                    <div id="ajax_list_users" class="mt-2"></div>
313
                <?php } else { ?>
314
                    <select
315
                        id="origin_users"
316
                        name="nosessionUsersList[]"
317
                        multiple
318
                        size="15"
319
                        class="w-full h-[300px] rounded-md border border-gray-300 p-2 text-sm focus:outline-none"
320
                    >
321
                        <?php foreach ($nosessionUsersList as $user) { ?>
322
                            <option value="<?php echo $user['user_id']; ?>">
323
                                <?php echo $user['username'].' - '.api_get_person_name($user['firstname'], $user['lastname']); ?>
324
                            </option>
325
                        <?php } ?>
326
                    </select>
327
                <?php } ?>
328
            </div>
329
330
            <div class="flex flex-col items-center justify-center space-y-4">
331
                <?php if (!$ajax_search) { ?>
332
                    <button
333
                        type="button"
334
                        onclick="moveSelectedOptions('origin_users', 'destination_users')"
335
                        class="rounded-full bg-primary p-2 hover:bg-primary/80 focus:outline-none focus:ring"
336
                    >
337
                        <i class="mdi mdi-fast-forward-outline text-white text-2xl"></i>
338
                    </button>
339
                    <button
340
                        type="button"
341
                        onclick="moveSelectedOptions('destination_users', 'origin_users')"
342
                        class="rounded-full bg-secondary p-2 hover:bg-secondary/80 focus:outline-none focus:ring"
343
                    >
344
                        <i class="mdi mdi-rewind-outline text-white text-2xl"></i>
345
                    </button>
346
                <?php } else { ?>
347
                    <button
348
                        type="button"
349
                        onclick="removeSelectedOptions('destination_users')"
350
                        class="rounded-full bg-danger p-2 hover:bg-danger/80 focus:outline-none focus:ring"
351
                    >
352
                        <i class="mdi mdi-close text-white text-2xl"></i>
353
                    </button>
354
                <?php } ?>
355
            </div>
356
357
            <div>
358
                <label class="block mb-2 text-sm font-medium text-gray-700"><?php echo get_lang('Assigned users'); ?></label>
359
                <select
360
                    id="destination_users"
361
                    name="sessionUsersList[]"
362
                    multiple
363
                    size="15"
364
                    class="w-full h-[300px] rounded-md border border-gray-300 p-2 text-sm focus:outline-none"
365
                >
366
                    <?php foreach ($sessionUsersList as $user) { ?>
367
                        <option value="<?php echo $user['user_id']; ?>">
368
                            <?php echo $user['username'].' - '.api_get_person_name($user['firstname'], $user['lastname']); ?>
369
                        </option>
370
                    <?php } ?>
371
                </select>
372
            </div>
373
        </div>
374
375
        <div class="text-center mt-6">
376
            <button
377
                type="button"
378
                onclick="submitWithAllDestinationOptionsSelected('formulaire', 'destination_users')"
379
                class="inline-flex items-center justify-center rounded-lg bg-primary px-6 py-2 text-white shadow hover:bg-primary/90 focus:outline-none focus:ring"
380
            >
381
                <?php echo get_lang('Save'); ?>
382
            </button>
383
        </div>
384
    </form>
385
386
    <script>
387
        function moveSelectedOptions(originSelectId, targetSelectId) {
388
            const origin = document.getElementById(originSelectId);
389
            const target = document.getElementById(targetSelectId);
390
            const optionsToMove = [];
391
392
            Array.from(origin.options).forEach(option => {
393
                if (option.selected) {
394
                    optionsToMove.push(new Option(option.text, option.value));
395
                    option.remove();
396
                }
397
            });
398
399
            optionsToMove.forEach(option => target.add(option));
400
            sortSelectOptions(target);
401
            target.selectedIndex = -1;
402
        }
403
404
        function removeSelectedOptions(selectId) {
405
            const select = document.getElementById(selectId);
406
            Array.from(select.options).forEach(option => {
407
                if (option.selected) {
408
                    option.remove();
409
                }
410
            });
411
        }
412
413
        function sortSelectOptions(selectElement) {
414
            const sortedOptions = Array.from(selectElement.options)
415
                .sort((a, b) => a.text.toLowerCase().localeCompare(b.text.toLowerCase()));
416
417
            selectElement.innerHTML = '';
418
            sortedOptions.forEach(option => selectElement.add(option));
419
        }
420
421
        function submitWithAllDestinationOptionsSelected(formId, destinationSelectId) {
422
            const form = document.forms[formId];
423
            const select = document.getElementById(destinationSelectId);
424
425
            Array.from(select.options).forEach(option => {
426
                option.selected = true;
427
            });
428
429
            form.submit();
430
        }
431
    </script>
432
433
<?php
434
Display::display_footer();
435