GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

personal.php ➔ setUserProfiles()   B
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 17
nc 6
nop 3
dl 0
loc 30
rs 8.5806
c 0
b 0
f 0
1
<?php
2
3
/*  ATICA - Web application for supporting Quality Management Systems
4
  Copyright (C) 2009-2015: Luis-Ramón López López
5
6
  This program is free software: you can redistribute it and/or modify
7
  it under the terms of the GNU Affero General Public License as published by
8
  the Free Software Foundation, either version 3 of the License, or
9
  (at your option) any later version.
10
11
  This program is distributed in the hope that it will be useful,
12
  but WITHOUT ANY WARRANTY; without even the implied warranty of
13
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
  GNU Affero General Public License for more details.
15
16
  You should have received a copy of the GNU Affero General Public License
17
  along with this program.  If not, see [http://www.gnu.org/licenses/]. */
18
19
$app->map('/personal/:section/:id', function ($section, $id) use ($app, $user, $organization, $preferences) {
20
    if (!$user) {
21
        $app->redirect($app->urlFor('login'));
22
    }
23
24
    // ¿se busca la información del usuario activo?
25
    $itsMe = ($id == null) || ($id == $user['id']);
26
27
    // si es un nuevo usuario, la única sección admitida es la cero
28
    if (($id == 0) && ($section != 0)) {
29
        $app->redirect($app->urlFor('frontpage'));
30
    }
31
32
    // si es así, asignar sus datos
33
    if ($itsMe) {
34
        $id = $user['id'];
35
        $userData = $user;
36
    } else {
37
        // cargar los datos del usuario indicado como parámetro si no es
38
        // el identificador 0, que significa nuevo usuario
39
        if ($id != 0) {
40
            $userData = getUserById($id, $organization['id']);
41
            if (!$userData) {
42
                // ¿no existe en la organización? Salir de aquí
43
                $app->redirect($app->urlFor('frontpage'));
44
            }
45
        }
46
        else {
47
            $userData = array( 'new' => true, 'is_active' => 1, 'gender' => 0, 'email_enabled' => 0 );
48
        }
49
    }
50
51
    $app->flashKeep();
52
53
    if (isset($_POST['deletepersonal']) && ($user['is_global_administrator'])) {
54
        $local = getUserObjectById($id, $organization['id']);
55
        if ($local) {
56
            $ok = $local->delete();
57
58
        }
59
        else {
60
            $ok = false;
61
        }
62
        if ($ok) {
63
            $app->flash('save_ok', 'delete');
64
        }
65
        else {
66
            $app->flash('save_error', 'delete');
67
        }
68
        $app->redirect($app->urlFor('personlist'));
69
    }
70
71
    // comprobar si se están cambiando datos
72
    if (isset($_POST['savepersonal']) && ($user['is_admin'] || $itsMe)) {
73
74
        ORM::get_db()->beginTransaction();
75
76
        $ok = true;
77
        if ($id == 0) {
78
            $local = ORM::for_table('person')->create();
79
        }
80
        else {
81
            $local = getUserObjectById($id, $organization['id']);
82
        }
83
        if (isset($_POST['displayname'])) {
84
            $local->set('display_name', $_POST['displayname']);
85
        }
86 View Code Duplication
        if (isset($_POST['description']) && (null != $_POST['description'])) {
87
            $local->set('description', $_POST['description']);
88
        }
89
        if (isset($_POST['firstname'])) {
90
            $local->set('first_name', $_POST['firstname']);
91
        }
92
        if (isset($_POST['lastname'])) {
93
            $local->set('last_name', $_POST['lastname']);
94
        }
95
        if (isset($_POST['initials'])) {
96
            $local->set('initials', $_POST['initials']);
97
        }
98
        if (isset($_POST['gender'])) {
99
            $local->set('gender', $_POST['gender']);
100
        }
101
        if (isset($_POST['email'])) {
102
            $local->set('email', $_POST['email']);
103
        }
104
        if (isset($_POST['notify'])) {
105
            $local->set('email_enabled', $_POST['notify']);
106
        }
107
        if (isset($_POST['external'])) {
108
            $local->set('is_external', $_POST['external']);
109
        }
110
        if ($user['is_admin']) {
111
            if (isset($_POST['username'])) {
112
                $local->set('user_name', $_POST['username']);
113
            }
114 View Code Duplication
            if (isset($_POST['description'])) {
115
                $local->set('description', strlen($_POST['description']) > 0 ? $_POST['description'] : null);
116
            }
117
            // los flags de usuario activo y administrador local se grabarán
118
            // luego si es un usuario nuevo
119
            if (($id != 0) && isset($_POST['active']) && isset($_POST['localadmin'])) {
120
                setPersonIsActiveAndLocalAdmin($_POST['active'], $_POST['localadmin'], $id, $organization['id']);
121
            }
122
            // permitir cambiar opción de administrador global si ya lo somos
123
            // y el usuario activo no somos nosotros (para evitar accidentes)
124
            if ($user['is_global_administrator'] && isset($_POST['globaladmin']) && !$itsMe) {
125
                $local->set('is_global_administrator', $_POST['globaladmin']);
126
            }
127
        }
128
129
        if ($ok && isset($_POST['password1']) && isset($_POST['password2']) && $_POST['password1'] && ($user['is_admin'] || $itsMe)) {
130
            if (!$user['is_admin'] && (!isset($_POST['oldpassword']) || !checkUserPassword($user['id'], $_POST['oldpassword'], $preferences['salt']))) {
131
                $app->flashNow('save_error', 'oldpassword');
132
                $ok = false;
133
            }
134
            elseif ($ok && $_POST['password1'] !== $_POST['password2']) {
135
                $app->flashNow('save_error', 'passwordmatch');
136
                $ok = false;
137
            }
138
            elseif (strlen($_POST['password1']) < 6) {
139
                $app->flashNow('save_error', 'passwordlength');
140
                $ok = false;
141
            }
142
            if ($ok) {
143
                $local->set('password', sha1($preferences['salt'] . $_POST['password1']));
144
            }
145
        }
146
147
        $ok = $ok && $local->save();
148
        // si es nuevo, añadirlo a la organización
149
        if ($ok && ($id == 0)) {
150
            $id = $local['id'];
151
            $personOrganization = ORM::for_table('person_organization')->
152
                    create();
153
            $personOrganization->set('person_id', $id);
154
            $personOrganization->set('organization_id', $organization['id']);
155
            $personOrganization->set('is_active', $_POST['active']);
156
            $personOrganization->set('is_local_administrator', $_POST['localadmin']);
157
            $ok = $ok && $personOrganization->save();
158
        }
159
160
        // cambio de perfiles
161
        if ($user['is_admin']) {
162
            $ok = $ok && setUserProfiles($id, $_POST['profiles'], $organization['id']);
163
        }
164
165
        if ($ok) {
166
            $app->flash('save_ok', 'ok');
167
            ORM::get_db()->commit();
168
169
            if (isset($_SESSION['slim.flash']['last_url'])) {
170
                $url = $_SESSION['slim.flash']['last_url'];
171
            } else {
172
                $url = ($user['is_admin'] ? $app->urlFor('personlist') : $app->urlFor('activities'));
173
            }
174
175
            $app->redirect($url);
176
177
        } else {
178
            $app->flash('save_error', 'error');
179
            ORM::get_db()->rollBack();
180
        }
181
    }
182
183
    // menú lateral de secciones
184
    $menu = array(
185
        array('caption' => ($itsMe ? 'Mis datos' : (($id != 0) ? $userData['display_name'] : 'Nuevo usuario')), 'icon' => 'user')
186
    );
187
188
    // las secciones vienen en este array
189
    $options = array(
190
        0 => array('caption' => 'Personal', 'template' => 'user_personal', 'select2' => true)
191
    );
192
193
    // comprobar que la sección existe
194
    if (!isset($options[$section])) {
195
        $app->redirect($app->urlFor('frontpage'));
196
    }
197
198
    // generar menú
199
    foreach ($options as $key => $i) {
200
        $menu[] = array('caption' => $i['caption'], 'active' => ($section == $key), 'target' => $app->urlFor('personal', array('id' => $id, 'section' => $key)));
201
    }
202
203
204
    if ($user['is_admin']) {
205
        $sidebar = getPersonManagementSidebar(($id == 0) ? 3 : 0, $app);
206
    }
207
    else {
208
        $sidebar = array();
209
    }
210
211
    // mostrar menú de perfil sólo si no estamos creando un nuevo usuario
212
    if ($id != 0) {
213
        $sidebar[] = $menu;
214
        // lista perfiles del usuario
215
        $profiles = parseArray(getProfilesByUser($organization['id'], $id));
216
    }
217
    else {
218
        $profiles = array();
219
    }
220
221
    if ($user['is_admin']) {
222
        $allProfiles = getProfilesByOrganization($organization['id']);
223
    }
224
    else {
225
        $allProfiles = array();
226
    }
227
228
    // generar barra de navegación
229
    $breadcrumb = array(
230
        array('display_name' => 'Usuarios', 'target' => $user['is_admin'] ? $app->urlFor('personlist') : $app->urlFor('personal', array('id' => $user['id'], 'section' => 0))),
231
        array('display_name' => ($id != 0) ? $userData['display_name'] : 'Nuevo usuario', 'target' => $app->urlFor('personal', array('id' => $id, 'section' => 0))),
232
        array('display_name' => $options[$section]['caption'])
233
    );
234
    // lanzar plantilla
235
    $app->render($options[$section]['template'] . '.html.twig', array(
236
        'navigation' => $breadcrumb,
237
        'sidebar' => $sidebar,
238
        'select2' => $options[$section]['select2'],
239
        'url' => $app->request()->getPathInfo(),
240
        'userData' => $userData,
241
        'profiles' => $profiles,
242
        'allProfiles' => $allProfiles,
243
        'local' => $itsMe
244
    ));
245
})->name('personal')->via('GET', 'POST')->
246
    conditions(array('section' => '[0-9]{1}'));
247
248
$app->map('/personal/listado(/:sort(/:filter))', function ($sort = 0, $filter = 1) use ($app, $user, $organization) {
249
    if ((!$user) || (!$user['is_admin'])) {
250
        $app->redirect($app->urlFor('login'));
251
    }
252
    $sidebar = getPersonManagementSidebar(1, $app);
253
254
    $persons = getOrganizationPersons($organization['id'], $sort, ($filter === 1));
255
256
    // generar barra de navegación
257
    $breadcrumb = array(
258
        array('display_name' => 'Usuarios', 'target' => $app->urlFor('personlist'),
259
        array('display_name' => $organization['display_name'])
260
    ));
261
262 View Code Duplication
    if (isset($_POST['enable']) || isset($_POST['disable'])) {
263
        if (enablePersons($organization['id'], $_POST['user'], isset($_POST['enable']))) {
264
            $app->flash('save_ok', 'ok');
265
        }
266
        else {
267
            $app->flash('save_error', 'error');
268
        }
269
        $app->redirect($app->request()->getPathInfo());
270
    }
271
272
    if (isset($_POST['delete']) && $user['is_global_administrator']) {
273
274
        $ok = true;
275
        foreach ($_POST['user'] as $item) {
276
            $local = getUserObjectById($item, $organization['id']);
277
            if ($local) {
278
                $ok = $local->delete();
279
280
            } else {
281
                $ok = false;
282
            }
283
        }
284
285
        if ($ok) {
286
            $app->flash('save_ok', 'delete');
287
        }
288
        else {
289
            $app->flash('save_error', 'delete');
290
        }
291
        $app->redirect($app->urlFor('personlist'));
292
    }
293
    $app->flash('last_url', $app->request()->getPathInfo());
294
295
    // lanzar plantilla
296
    $app->render('manage_person.html.twig', array(
297
        'navigation' => $breadcrumb,
298
        'search' => true,
299
        'sidebar' => $sidebar,
300
        'sort' => $sort,
301
        'filter' => $filter,
302
        'url' => $app->request()->getPathInfo(),
303
        'user' => $user,
304
        'persons' => $persons
305
    ));
306
})->name('personlist')->via('GET', 'POST');
307
308
309
$app->map('/perfiles', function () use ($app, $user, $organization) {
310
    if ((!$user) || (!$user['is_admin'])) {
311
        $app->redirect($app->urlFor('login'));
312
    }
313
    $sidebar = getPersonManagementSidebar(2, $app);
314
315
    $profiles = getProfileGroupsByOrganization($organization['id']);
316
317 View Code Duplication
    if (isset($_POST['delete']) && isset($_POST['profilegroup'])) {
318
        $ok = deleteProfileGroupsById($_POST['profilegroup'], $organization['id']);
319
        if ($ok) {
320
            $app->flash('save_ok', 'delete');
321
        }
322
        else {
323
            $app->flash('save_error', 'error');
324
        }
325
        $app->redirect($app->request()->getPathInfo());
326
    }
327
328
    // generar barra de navegación
329
    $breadcrumb = array(
330
        array('display_name' => 'Perfiles', 'target' => $app->urlFor('personlist'),
331
        array('display_name' => $organization['display_name'])
332
    ));
333
334
    // lanzar plantilla
335
    $app->render('manage_profile_groups.html.twig', array(
336
        'navigation' => $breadcrumb,
337
        'search' => true,
338
        'sidebar' => $sidebar,
339
        'profiles' => $profiles,
340
        'url' => $app->request()->getPathInfo()
341
    ));
342
})->name('profilelist')->via('GET', 'POST');
343
344
$app->map('/perfiles/:id(/:filter)', function ($id, $filter = 0) use ($app, $user, $config, $organization, $preferences) {
345
346
    if ((!$user) || (!$user['is_admin'])) {
347
        $app->redirect($app->urlFor('login'));
348
    }
349
350
    $sidebar = getPersonManagementSidebar(2, $app);
351
    array_push($sidebar, getProfileGroupsSidebar($id, $organization['id'], $app));
352
353
    $new = false;
354
355
    if (0 == $id) {
356
        // grupo de perfil nuevo
357
        $profileGroup = array(
358
            'id' => 0,
359
            'display_name_neutral' => '',
360
            'display_name_male' => '',
361
            'display_name_female' => '',
362
            'abbreviation' => '',
363
            'is_manager' => 0,
364
            'description' => null,
365
            'is_container' => 0
366
        );
367
        $profiles = array();
368
        $personCount = 0;
369
        $isContainer = false;
370
        $new = true;
371
    }
372
    else {
373
        $profileGroup = getProfileGroupById($id, $organization['id']);
374
375
        if (!$profileGroup) {
376
            $app->redirect($app->urlFor('login'));
377
        }
378
379 View Code Duplication
        if (isset($_POST['enable']) || isset($_POST['disable'])) {
380
            if (enableProfiles($organization['id'], $_POST['profile'], isset($_POST['enable']))) {
381
                $app->flash('save_ok', 'ok');
382
            }
383
            else {
384
                $app->flash('save_error', 'error');
385
            }
386
            $app->redirect($app->request()->getPathInfo());
387
        }
388
389
        $profiles = getProfilesByGroup($id, $organization['id'], ($filter === 1));
390
        $personCount = 0;
391
        foreach($profiles as $profile) {
392
            $personCount += count($profile['persons']);
393
        }
394
395
        $isContainer = isProfileGroupContainer($id);
396
    }
397
398
    if (!$isContainer) {
399
        $persons = parseArray(getPersonsByProfile($id, $organization['id']));
400
        $allPersons = getPersonsByOrganization($organization['id']);
401
    }
402
    else {
403
        $persons = array();
404
        $allPersons = array();
405
    }
406
407
    if (isset($_POST['saveprofilegroup'])) {
408
409
        $ok = true;
410
411
        if ($new) {
412
            ORM::get_db()->beginTransaction();
413
            $profile = ORM::for_table('profile')->create();
414
            $profile->set('is_active', 1);
415
            $profile->set('is_container', 0);
416
            $profile->save();
417
            $profileGroup = ORM::for_table('profile_group')->create();
418
            $profileGroup->set('id', $profile['id']);
419
            $profileGroup->set('organization_id', $organization['id']);
420
            $profileGroup->save();
421
            $profile->set('profile_group_id', $profileGroup['id']);
422
            $profile->save();
423
            $ok = $ok && ORM::get_db()->commit();
424
            $id = $profileGroup['id'];
425
        }
426
        $profileGroup->set('display_name_neutral', $_POST['displaynameneutral']);
427
        $profileGroup->set('display_name_male', $_POST['displaynamemale']);
428
        $profileGroup->set('display_name_female', $_POST['displaynamefemale']);
429
        $profileGroup->set('abbreviation', $_POST['abbreviation']);
430
        $profileGroup->set('is_manager', $_POST['ismanager']);
431
        $profileGroup->set('description', $_POST['description']);
432
433
        $ok = $ok && $profileGroup->save();
434
435
        // comprobar si no hay usuarios con el perfil y ha cambiado el tipo
436
        if (($personCount == 0) && ($isContainer ? "1" : "0") != $_POST['iscontainer']) {
437
            // sanity check: sólo usuarios de esta organización
438
439
            $ok = $ok && setProfileGroupContainer($id, $_POST['iscontainer']);
440
        }
441
442
        // si no es contenedor, actualizar la lista de usuarios asociados
443
        if (!$isContainer) {
444
            $ok = $ok && setProfilePersons($id, isset($_POST['persons']) ? $_POST['persons'] : array());
445
        }
446
447
        if ($ok) {
448
            $app->flash('save_ok', 'ok');
449
        }
450
        else {
451
            $app->flash('save_error', 'error');
452
        }
453
454
        if ($new) {
455
            $app->redirect($app->urlFor('profilelist'));
456
        }
457
        else {
458
            $app->redirect($app->request()->getPathInfo());
459
        }
460
    }
461
462 View Code Duplication
    if (isset($_POST['delete']) && isset($_POST['profile'])) {
463
        $ok = deleteProfilesById($_POST['profile'], $organization['id']);
464
        if ($ok) {
465
            $app->flash('save_ok', 'delete');
466
        }
467
        else {
468
            $app->flash('save_error', 'error');
469
        }
470
        $app->redirect($app->request()->getPathInfo());
471
    }
472
473
    // generar barra de navegación
474
    $breadcrumb = array(
475
        array('display_name' => 'Perfiles', 'target' => $app->urlFor('profilelist')),
476
        array('display_name' => $profileGroup['display_name_neutral'],
477
            $app->request()->getPathInfo()),
478
        array('display_name' => 'Detalles del perfil')
479
    );
480
481
    // lanzar plantilla
482
    $app->render('manage_profiles.html.twig', array(
483
        'select2' => true,
484
        'navigation' => $breadcrumb,
485
        'search' => true,
486
        'sidebar' => $sidebar,
487
        'profiles' => $profiles,
488
        'isContainer' => $isContainer,
489
        'profileGroup' => $profileGroup,
490
        'personCount' => $personCount,
491
        'persons' => $persons,
492
        'allPersons' => $allPersons,
493
        'new' => $new,
494
        'user' => $user,
495
        'filter' => $filter,
496
        'id' => $id,
497
        'url' => $app->request()->getPathInfo()
498
    ));
499
500
})->name('profile')->via('GET', 'POST');
501
502
$app->map('/detalleperfil/:id(/:gid)', function ($id, $gid = null) use ($app, $user, $config, $organization, $preferences) {
503
504
    if ((!$user) || (!$user['is_admin'])) {
505
        $app->redirect($app->urlFor('login'));
506
    }
507
508
    $sidebar = getPersonManagementSidebar(2, $app);
509
    $new = false;
510
511
    if (0 == $id) {
512
        $profile = array('id' => 0, 'profile_group_id' => $gid, 'is_active' => true);
513
        $new = true;
514
    }
515
    else {
516
        $profile = getProfileById($organization['id'], $id);
517
518
        if (!$profile) {
519
            $app->redirect($app->urlFor('login'));
520
        }
521
    }
522
523
    $profileGroup = getProfileGroupById($profile['profile_group_id'], $organization['id']);
524
    array_push($sidebar, getProfileGroupsSidebar($profileGroup['id'], $organization['id'], $app));
525
526
    if (!$profileGroup) {
527
        $app->redirect($app->urlFor('login'));
528
    }
529
530
    $persons = parseArray(getPersonsByProfile($id, $organization['id']));
531
    $allPersons = getPersonsByOrganization($organization['id']);
532
533
    if (isset($_POST['saveprofile'])) {
534
        if ($new) {
535
            $profile = ORM::for_table('profile')->create();
536
            $profile->set('profile_group_id', $gid);
537
        }
538
        $profile->set('display_name', $_POST['displayname']);
539
        $profile->set('initials', $_POST['initials']);
540
        $profile->set('is_active', $_POST['isactive']);
541
        $profile->set('description', $_POST['description']);
542
543
        $ok = $profile->save();
544
545
        $ok = $ok && setProfilePersons($profile['id'], isset($_POST['persons']) ? $_POST['persons'] : array());
546
547
        if ($ok) {
548
            $app->flash('save_ok', 'ok');
549
        }
550
        else {
551
            $app->flash('save_error', 'error');
552
        }
553
        if ($new) {
554
            $app->redirect($app->urlFor('profile', array('id' => $gid)));
555
        }
556
        else {
557
            $app->redirect($app->request()->getPathInfo());
558
        }
559
    }
560
561
    // generar barra de navegación
562
    $breadcrumb = array(
563
        array('display_name' => 'Perfiles', 'target' => $app->urlFor('profilelist')),
564
        array('display_name' => $profileGroup['display_name_neutral'], $app->request()->getPathInfo()),
565
        array('display_name' => 'Detalles del perfil')
566
    );
567
568
    // lanzar plantilla
569
    $app->render('manage_profile_details.html.twig', array(
570
        'select2' => true,
571
        'navigation' => $breadcrumb,
572
        'sidebar' => $sidebar,
573
        'profile' => $profile,
574
        'persons' => $persons,
575
        'allPersons' => $allPersons,
576
        'profileGroup' => $profileGroup,
577
        'new' => $new,
578
        'user' => $user,
579
        'id' => $id,
580
        'url' => $app->request()->getPathInfo()
581
    ));
582
583
})->name('profiledetail')->via('GET', 'POST');
584
585
function getUserById($personId, $orgId) {
586
    $data = getUserObjectById($personId, $orgId);
587
    if ($data) {
588
        return $data->as_array();
589
    }
590
    else {
591
        return false;
592
    }
593
}
594
595
function getUserObjectById($personId, $orgId) {
596
    return ORM::for_table('person')->
597
        select('person.*')->
598
        select('person_organization.is_local_administrator')->
599
        select('person_organization.is_active')->
600
        inner_join('person_organization', array('person_organization.person_id', '=', 'person.id'))->
601
        where('person_organization.person_id', $personId)->
602
        where('person_organization.organization_id', $orgId)->
603
        find_one();
604
}
605
606 View Code Duplication
function getProfilesByUser($orgId, $personId) {
607
    return ORM::for_table('profile')->
608
                    select('profile.*')->
609
                    select('profile_group.display_name_neutral')->
610
                    select('profile_group.display_name_male')->
611
                    select('profile_group.display_name_female')->
612
                    select('profile_group.description', 'profile_group_description')->
613
                    inner_join('profile_group', array('profile_group.id', '=', 'profile.profile_group_id'))->
614
                    inner_join('person_profile', array('person_profile.profile_id', '=', 'profile.id'))->
615
                    where('person_profile.person_id', $personId)->
616
                    where('profile_group.organization_id', $orgId)->
617
                    order_by_asc('profile_group.display_name_neutral')->
618
                    find_array();
619
}
620
621
function getProfilesListByUser($orgId, $personId) {
622
    $data = ORM::for_table('profile')->
623
                    select('profile.id')->
624
                    inner_join('profile_group', array('profile_group.id', '=', 'profile.profile_group_id'))->
625
                    inner_join('person_profile', array('person_profile.profile_id', '=', 'profile.id'))->
626
                    where('person_profile.person_id', $personId)->
627
                    where('profile_group.organization_id', $orgId)->
628
                    find_array();
629
630
    return array_column($data, 'id');
631
}
632
633
function setPersonIsActiveAndLocalAdmin($stateActive, $stateLocalAdmin, $personId, $orgId) {
634
    $personOrganization = ORM::for_table('person_organization')->
635
            where('person_id', $personId)->
636
            where('organization_id', $orgId)->
637
            delete_many();
638
639
    if (!$personOrganization) {
640
        return false;
641
    }
642
643
    $personOrganization2 = ORM::for_table('person_organization')->create();
644
    $personOrganization2->set('person_id', $personId);
645
    $personOrganization2->set('organization_id', $orgId);
646
    $personOrganization2->set('is_active', $stateActive);
647
    $personOrganization2->set('is_local_administrator', $stateLocalAdmin);
648
    $personOrganization2->save();
649
650
    return $personOrganization2->save();
651
}
652
653
function checkUserPassword($personId, $password, $salt) {
654
    return ORM::for_table('person')->
655
                    where('id', $personId)->
656
                    where('password', sha1($salt . $password))->
657
                    count() > 0;
658
}
659
660
function getPersonManagementSidebar($section, $app) {
661
    return array(
662
        array(
663
         array('caption' => 'Operaciones', 'icon' => 'group'),
664
         array('caption' => 'Gestionar usuarios', 'active' => (($section == 1) || ($section == 3)),'target' => $app->urlFor('personlist')),
665
         array('caption' => 'Administrar perfiles', 'active' => ($section == 2),'target' => $app->urlFor('profilelist'))
666
        )
667
    );
668
}
669
670
function getProfileGroupsSidebar($id, $orgId, $app) {
671
    $sidebar = array(
672
         array('caption' => 'Perfiles', 'icon' => 'list')
673
    );
674
    $profileGroups = getProfileGroupsByOrganization($orgId);
675
    foreach($profileGroups as $profileGroup) {
676
        array_push($sidebar, array('caption' => $profileGroup['display_name_neutral'], 'active' => $profileGroup['id'] == $id, 'target' => $app->urlFor('profile', array('id' => $profileGroup['id']))));
677
    }
678
679
    // array('caption' => 'Gestionar usuarios', 'active' => (($section == 1) || ($section == 3)),'target' => $app->urlFor('personlist')),
680
681
    return $sidebar;
682
}
683
684
function getOrganizationPersons($orgId, $sortIndex = 0, $filter = true) {
685
    $fields = array('user_name', 'first_name', 'email', 'last_login',
686
        'last_name', 'gender', 'email_enabled',
687
        'person_organization.is_local_administrator', 'is_global_administrator');
688
689
    $data = ORM::for_table('person')->
690
            select('person.*')->
691
            select('person_organization.is_active')->
692
            select('person_organization.is_local_administrator')->
693
            inner_join('person_organization', array('person_organization.person_id', '=', 'person.id'))->
694
            where('person_organization.organization_id', $orgId)->
695
            order_by_asc($fields[$sortIndex]);
696
697
    if ($filter) {
698
        $data = $data->where('person_organization.is_active', 1);
699
    }
700
701
    return $data->find_many();
702
}
703
704
function getProfileGroupsByOrganization($orgId) {
705
    $data = ORM::for_table('profile_group')->
706
            select('profile_group.*')->
707
            where('profile_group.organization_id', $orgId)->
708
            order_by_asc('profile_group.display_name_neutral');
709
710
    return $data->find_array();
711
}
712
713
function getProfilesByOrganization($orgId, $filter = true, $containers = false) {
714
    $data = ORM::for_table('profile')->
715
            select('profile.*')->
716
            select('profile_group.display_name_neutral')->
717
            select('profile_group.display_name_male')->
718
            select('profile_group.display_name_female')->
719
            select('profile_group.abbreviation')->
720
            inner_join('profile_group', array('profile_group.id', '=', 'profile.profile_group_id'))->
721
            where('profile_group.organization_id', $orgId)->
722
            order_by_asc('profile_group.display_name_neutral')->
723
            order_by_asc('profile.display_name');
724
725
    if ($containers === false) {
726
        $data = $data->where('profile.is_container', 0);
727
    }
728
    if ($filter) {
729
        $data = $data->where('profile.is_active', 1);
730
    }
731
732
    return $data->find_array();
733
}
734
735
function getProfileById($orgId, $id) {
736
    $data = ORM::for_table('profile')->
737
            select('profile.*')->
738
            select('profile_group.display_name_neutral')->
739
            select('profile_group.display_name_male')->
740
            select('profile_group.display_name_female')->
741
            inner_join('profile_group', array('profile_group.id', '=', 'profile.profile_group_id'))->
742
            where('profile_group.organization_id', $orgId)->
743
            where('profile.id', $id)->
744
            find_one();
745
746
    return $data;
747
}
748
749
function getProfileFullDisplayName($profile, $user) {
750
    $names = array(
751
        $profile['display_name_neutral'],
752
        $profile['display_name_male'],
753
        $profile['display_name_female']
754
    );
755
756
    $name = $names[$user['gender']];
757
758
    if ($profile['display_name']) {
759
        $name .= ' ' . $profile['display_name'];
760
    }
761
    return $name;
762
}
763
764
function getProfileGroupById($id, $orgId) {
765
    $data = ORM::for_table('profile_group')->
766
            select('profile_group.*')->
767
            where('profile_group.organization_id', $orgId)->
768
            where('profile_group.id', $id)->find_one();
769
770
    return $data;
771
}
772
773
function getPersonsByProfile($id, $orgId) {
774
    return ORM::for_table('person')->
775
                select('person.id', 'id')->
776
                select('person.display_name')->
777
                select('person.user_name')->
778
                select('person_organization.is_active')->
779
                inner_join('person_profile', array('person_profile.person_id', '=', 'person.id'))->
780
                inner_join('person_organization', array('person_organization.person_id', '=', 'person.id'))->
781
                where('person_organization.organization_id', $orgId)->
782
                where('person_profile.profile_id', $id)->
783
                order_by_asc('person.display_name')->
784
                find_array();
785
}
786
787 View Code Duplication
function getPersonsByOrganization($orgId) {
788
    $data = ORM::for_table('person')->
789
                select('person.id', 'id')->
790
                select('person.display_name')->
791
                select('person.user_name')->
792
                select('person_organization.is_active')->
793
                inner_join('person_organization', array('person_organization.person_id', '=', 'person.id'))->
794
                where('person_organization.organization_id', $orgId)->
795
                order_by_desc('person_organization.is_active')->
796
                order_by_asc('person.display_name')->
797
                find_array();
798
799
    return parseArray($data);
800
}
801
802
function getProfilesByGroup($id, $orgId, $filter = true) {
803
    $data = ORM::for_table('profile')->
804
            select('profile.*')->
805
            select('profile_group.display_name_neutral')->
806
            select('profile_group.display_name_male')->
807
            select('profile_group.display_name_female')->
808
            select('profile_group.abbreviation')->
809
            inner_join('profile_group', array('profile_group.id', '=', 'profile.profile_group_id'))->
810
            where('profile_group.id', $id)->
811
            where('profile.is_container', 0)->
812
            order_by_asc('profile_group.display_name_neutral')->
813
            order_by_asc('profile.display_name');
814
815
    if ($filter) {
816
        $data = $data->where('profile.is_active', 1);
817
    }
818
819
    $data = $data->find_array();
820
821
    foreach($data as $key => $profile) {
822
823
        $persons = getPersonsByProfile($profile['id'], $orgId);
824
825
        $data[$key]['persons'] = $persons;
826
    }
827
828
    return $data;
829
}
830
831
function isProfileGroupContainer($id) {
832
    return (ORM::for_table('profile')->
833
            where('profile_group_id', $id)->
834
            where('is_container', 1)->
835
            count())>0;
836
}
837
838
function setProfileGroupContainer($id, $value) {
839
    $profile = ORM::for_table('profile')->
840
            where('profile_group_id', $id)->
841
            find_one();
842
    $profile->set('is_container', $value);
843
    return $profile->save();
844
}
845
846
function setProfilePersons($profileId, $persons) {
847
    ORM::get_db()->beginTransaction();
848
849
    $ok = ORM::for_table('person_profile')->
850
            where('profile_id', $profileId)->
851
            delete_many();
852
853
    foreach ($persons as $person) {
854
        $insert = ORM::for_table('person_profile')->create();
855
        $insert->set('person_id', $person);
856
        $insert->set('profile_id', $profileId);
857
        $ok = $ok && $insert->save();
858
    }
859
860
    return $ok && ORM::get_db()->commit();
861
}
862
863
function setUserProfiles($userId, $profiles, $orgId) {
864
865
    // hay que eliminar los perfiles a los que pertenezca este usuario
866
    // dentro de la organización
867
    $oldProfiles = getProfilesListByUser($orgId, $userId);
868
869
    $addProfiles = array_diff($profiles, $oldProfiles);
870
    $deleteProfiles = array_diff($oldProfiles, $profiles);
871
872
    if (!empty($deleteProfiles)) {
873
        // primero eliminamos los perfiles antiguos que ya no están
874
        ORM::for_table('person_profile')->
875
            where('person_id', $userId)->
876
            where_in('profile_id', $deleteProfiles)->
877
            delete_many();
878
    }
879
880
    // añadimos los nuevos
881
    $ok = true;
882
    foreach ($addProfiles as $profile) {
883
        $insert = ORM::for_table('person_profile')->create();
884
        $insert->set('person_id', $userId);
885
        $insert->set('profile_id', $profile);
886
        $ok = $ok && $insert->save();
887
888
        checkItemUpdateStatusByProfile($profile);
889
    }
890
891
    return $ok;
892
}
893
894
function deleteProfilesById($profileIds, $orgId) {
895
    $data = ORM::for_table('profile')->
896
            select('profile.id')->
897
            inner_join('profile_group', array('profile_group.id', '=', 'profile.profile_group_id'))->
898
            where_in('profile.id', $profileIds)->
899
            where('profile_group.organization_id', $orgId)->
900
            find_result_set();
901
902
    return $data->delete();
903
}
904
905
function deleteProfileGroupsById($profileGroupsIds, $orgId) {
906
    $data = ORM::for_table('profile')->
907
            select('profile.id')->
908
            inner_join('profile_group', array('profile_group.id', '=', 'profile.profile_group_id'))->
909
            where_in('profile.profile_group_id', $profileGroupsIds)->
910
            where('profile_group.organization_id', $orgId)->
911
            find_result_set()->set('profile_group_id', null);
912
913
    $data->save();
914
915
    $ok = ORM::for_table('profile_group')->
916
            where('organization_id', $orgId)->
917
            where_in('id', $profileGroupsIds)->
918
            delete();
919
920
    $ok = $ok && $data->delete();
921
922
    return $ok;
923
}
924
925
function enablePersons($orgId, $persons, $status) {
926
    // Cuidado: ataque SQL injection. Usar clave primaria compuesta
927
    // para solucionarlo
928
    $organization = ORM::get_db()->quote($orgId);
929
    $active = $status ? 1 : 0;
930
    $list = implode(',', $persons);
931
    return ORM::get_db()->exec('UPDATE person_organization SET is_active=' . $active .
932
            ' WHERE organization_id=' . $organization . ' AND '.
933
            'person_id IN (' . $list . ');');
934
935
}
936
937
function enableProfiles($orgId, $profiles, $status) {
938
    ORM::get_db()->beginTransaction();
939
    foreach($profiles as $profile) {
940
        $row = ORM::for_table('profile')->
941
                select('profile.id')->
942
                select('is_active')->
943
                inner_join('profile_group', array('profile_group.id', '=', 'profile.profile_group_id'))->
944
                where('profile.id', $profile)->
945
                where('profile_group.organization_id', $orgId)->
946
                find_one();
947
        $row->set('is_active', $status);
948
        $row->save();
949
    }
950
    return ORM::get_db()->commit();
951
}
952