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.

tree.php ➔ getDeliveriesFromFolders()   D
last analyzed

Complexity

Conditions 17
Paths 195

Size

Total Lines 76
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 53
nc 195
nop 5
dl 0
loc 76
rs 4.8716
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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->get('/arbol(/:id)', function ($id = null) use ($app, $user, $organization) {
20
    if (!$user) {
21
        $app->redirect($app->urlFor('login'));
22
    }
23
24
    $data = array();
25
    $folders = array();
26
    $category = array();
27
    $parent = array();
28
    $persons = array();
29
    $folderProfiles = array();
30
    $profileGender = array();
31
32
    $topbar = getTree($organization['id'], $app, $id, $category, $parent);
33
34
    // obtener lista de perfiles para controlar la visibilidad de la carpeta
35
    $userProfiles = getUserProfiles($user['id'], $organization['id'], true);
36
    $userProfilesList = array();
37 View Code Duplication
    foreach($userProfiles as $prof) {
38
        $userProfilesList[$prof['id']] = $prof['id'];
39
        $userProfilesList[$prof['profile_group_id']] = $prof['profile_group_id'];
40
    }
41
    
42
    if (null !== $id) {
43
        $data = getParsedDeliveriesByCategory($organization['id'], $id, $user['is_admin'] ? null : $userProfilesList, $profileGender, $user['id']);
44
        // TODO: Optimizar leyendo todos los permisos de golpe para todas las
45
        // carpetas y colocándolos en un array
46
        $allFolders = getFoldersByCategory($id);
47
        $folders = getFoldersAndStatsByCategoryAndUser($id, $user) + $allFolders;
48
        $persons = getFolderPersonsByCategory($id);
49
        $folderProfiles = getProfilesByCategory($id);
50
51
        $breadcrumb = array(
52
            array('display_name' => 'Árbol', 'target' => $app->urlFor('tree')),
53
            array('display_name' => $parent['display_name'], 'target' => $app->urlFor('tree')),
54
                array('display_name' => $category['display_name'])
55
        );
56
    }
57
    else {
58
        $breadcrumb = array(
59
            array('display_name' => 'Árbol', 'target' => '#')
60
        );
61
    }
62
    $app->flash('last_url', $app->request()->getPathInfo());
63
64
    $app->render('tree.html.twig', array(
65
        'navigation' => $breadcrumb,
66
        'search' => !empty($allFolders),
67
        'topbar' => $topbar,
68
        'category' => $category,
69
        'data' => $data,
70
        'persons' => $persons,
71
        'folderProfiles' => $folderProfiles,
72
        'profileGender' => $profileGender,
73
        'backurl' => array('return' => 0, 'data1' => $id, 'data2' => 0, 'data3' => 0),
74
        'folders' => $folders));
75
})->name('tree');
76
77
$app->get('/descargar/:kind/:cid/:id/(:p1/)', function ($kind, $cid, $id, $p1 = null) use ($app, $user, $preferences, $organization) {
78
79
    $groupId = null;
80
    $eventId = null;
81
    // $kind =
82
    // 1 -> la descarga se produce desde una carpeta del árbol, $cid = category.id
83
    // 2 -> la descarga se produce desde un agrupamiento, $cid = grouping.id
84
    // 3 -> la descarga se produce desde un evento, $cid = event.id, $p1 pasan
85
    switch($kind) {
86
        case 1:
87
            // sólo usuarios autenticados
88
            if (!$user) {
89
                $app->redirect($app->urlFor('login'));
90
            }
91
            break;
92
        case 2:
93
            $groupId = $cid;
94
            break;
95
        case 3:
96
            $eventId = $cid;
97
            break;
98
        case 4:
99
            break;
100
        default:
101
            $app->redirect($app->urlFor('frontpage'));
102
    }
103
104
    if (is_null($p1)) {
105
        $delivery = getDelivery($id);
106
    }
107
    else {
108
        $delivery = getDeliveryWithRevision($id, $p1);
109
    }
110
111 View Code Duplication
    if (!$delivery) {
112
       doRegisterAction($app, $user, $organization, 'tree', 1, 'download_error', 'no delivery',
113
               null, null, null, $eventId, $groupId, null, null, $id,
114
               $delivery['current_revision_id'], null, null);
115
       $app->flash('home_error', 'no_delivery');
116
       $app->redirect($app->request->getReferrer());
117
    }
118
    $file = $preferences['upload.folder'] . $delivery['download_path'];
119
120 View Code Duplication
    if (!file_exists($file)) {
121
       doRegisterAction($app, $user, $organization, 'tree', 1, 'download_error', 'no document',
122
               null, null, null, $eventId, $groupId, null, null, $id,
123
               $delivery['current_revision_id'], null, null);
124
       $app->flash('home_error', 'no_document');
125
       $app->redirect($app->request->getReferrer());
126
    }
127
128
    $res = $app->response();
129
    $res['Content-Description'] = 'File Transfer';
130
    $res['Content-Type'] = ($delivery['mime'] == null) ?
131
            'application/octet-stream' : $delivery['mime'];
132
    $res['Content-Disposition'] ='attachment; filename=' . trim(basename($delivery['download_filename']));
133
    $res['Content-Transfer-Encoding'] = 'binary';
134
    $res['Expires'] = '0';
135
    $res['Cache-Control'] = 'must-revalidate';
136
    $res['Pragma'] = 'public';
137
    $res['Content-Length'] = $delivery['download_filesize'];
138
    doRegisterAction($app, $user, $organization, 'tree', 0, 'download',
139
            $delivery['download_filename'],
140
            null, null, null, $eventId, $groupId, null, null, $id,
141
            $delivery['current_delivery_id'], null, null);
142
143
    readfile($file);
144
})->name('download');
145
146
$app->map('/carpeta/:id(/:catid)', function ($id, $catid = null) use ($app, $user, $organization) {
147
    if (!$user['is_admin']) {
148
        $app->redirect($app->urlFor('login'));
149
    }
150
151
    $category = array();
152
    $parent = array();
153
154
    $data = getCategories($organization['id']);
155
    $allProfiles = getProfilesByOrganization($organization['id'], true, true);
156
    $uploadProfiles = parseArray(getPermissionProfiles($id, 1));
157
    $managerProfiles = parseArray(getPermissionProfiles($id, 0));
158
    $restrictedProfiles = parseArray(getPermissionProfiles($id, 2));
159
160
    if (isset($_POST['savefolder'])) {
161
        ORM::get_db()->beginTransaction();
162
163
        if ($id == 0) {
164
            $order = getMaxFolderOrder($_POST['category']) + 1000;
165
            $local = ORM::for_table('folder')->create();
166
            $local->set('order_nr', $order);
167
        }
168
        else {
169
            $local = getFolderById($organization['id'], $id);
170
        }
171
        $local->set('category_id', $_POST['category']);
172
        $local->set('display_name', $_POST['displayname']);
173
        $local->set('description', strlen($_POST['description'])>0 ? $_POST['description'] : null);
174
        $local->set('is_visible', 1);
175
        $local->set('is_divided', $_POST['divided']);
176
        $local->set('is_private_personal', ($_POST['private']==1));
177
        $local->set('is_private_profile', ($_POST['private']==2));
178
        $local->set('is_restricted', $_POST['restrictedaccess']);
179
        $local->set('show_revision_nr', $_POST['revisionnr']);
180
        $local->set('auto_clean', $_POST['autoclean']);
181
182
        if ($local->save()) {
183
            $id = $local['id'];
184
            $ok = true;
185 View Code Duplication
            if (isset($_POST['managers'])) {
186
                $ok = $ok && setFolderProfiles($id, 0, $_POST['managers']);
187
            }
188
            else {
189
                $ok = $ok && setFolderProfiles($id, 0, array());
190
            }
191 View Code Duplication
            if (isset($_POST['uploaders'])) {
192
                $ok = $ok && setFolderProfiles($id, 1, $_POST['uploaders']);
193
            }
194
            else {
195
                $ok = $ok && setFolderProfiles($id, 1, array());
196
            }
197 View Code Duplication
            if (isset($_POST['restricted'])) {
198
                $ok = $ok && setFolderProfiles($id, 2, $_POST['restricted']);
199
            }
200
            else {
201
                $ok = $ok && setFolderProfiles($id, 2, array());
202
            }
203
            if ($ok) {
204
                $app->flash('save_ok', 'ok');
205
                ORM::get_db()->commit();
206
            }
207
            else {
208
                $app->flash('save_error', 'error');
209
                ORM::get_db()->rollBack();
210
            }
211
        }
212
        else {
213
            $app->flash('save_error', 'error');
214
            ORM::get_db()->rollBack();
215
        }
216
        $url = isset($_SESSION['slim.flash']['last_url']) ?
217
                $_SESSION['slim.flash']['last_url'] :
218
                $app->request()->getPathInfo();
219
220
        $app->redirect($url);
221
    }
222
223 View Code Duplication
    if (isset($_POST['deletefolder'])) {
224
        // realizar los cambios en una transacción
225
        ORM::get_db()->beginTransaction();
226
227
        $folder = getFolderById($organization['id'], $id);
228
229
        $category = $folder['category_id'];
230
231
        $ok = $folder->delete();
232
233
        if ($ok) {
234
            $app->flash('save_ok', 'delete');
235
            ORM::get_db()->commit();
236
            $app->redirect($app->urlFor('tree', array('id' => $category)));
237
        }
238
        else {
239
            $app->flash('save_error', 'delete');
240
            ORM::get_db()->rollback();
241
        }
242
    }
243
244
    $folder = getFolder($organization['id'], $id);
245
246
    if (!$folder) {
247
        // valores por defecto de las carpetas nuevas
248
        $folder = array();
249
        $folder['is_visible'] = 1;
250
        $folder['category_id'] = $catid;
251
        $folder['is_private_profile'] = 0;
252
        $folder['is_private_personal'] = 0;
253
        $folder['is_divided'] = 1;
254
        $folder['show_revision_nr'] = 0;
255
        $folder['auto_clean'] = 0;
256
        $folder['is_restricted'] = 0;
257
    }
258
259
    if (null == $catid) {
260
        $catid = $folder['category_id'];
261
    }
262
263
    $query = getCategoryObjectById($organization['id'], $catid);
264
    if (!$query) {
265
        // error, no existe la categoría en la organización, posible
266
        // intento de ataque
267
        $app->redirect($app->urlFor('frontpage'));
268
    }
269
    $topbar = getTree($organization['id'], $app, $catid, $category, $parent);
270
271
    $breadcrumb = array(
272
        array('display_name' => 'Árbol', 'target' => $app->urlFor('tree')),
273
        array('display_name' => $parent['display_name'], 'target' => $app->urlFor('tree', array('id' => $catid))),
274
        array('display_name' => $category['display_name'], 'target' => $app->urlFor('tree', array('id' => $catid))),
275
        array('display_name' => 'Gestionar carpeta')
276
    );
277
    
278
    $private = $folder['is_private_profile'] ? 2 : ($folder['is_private_personal'] ? 1 : 0);
279
280
    $app->render('manage_folder.html.twig', array(
281
        'navigation' => $breadcrumb, 'search' => true, 'topbar' => $topbar,
282
        'select2' => true,
283
        'category' => $category,
284
        'url' => $app->request()->getPathInfo(),
285
        'data' => $data,
286
        'new' => ($id == 0),
287
        'private' => $private,
288
        'allProfiles' => $allProfiles,
289
        'uploaders' => $uploadProfiles,
290
        'managers' => $managerProfiles,
291
        'restricted' => $restrictedProfiles,
292
        'folder' => $folder));
293
})->name('managefolder')->via('GET', 'POST');
294
295
$app->get('/opcarpeta/:id/:oper(/:data)', function ($id, $oper, $data = null) use ($app, $user, $organization) {
296
    if (!$user['is_admin']) {
297
        $app->redirect($app->urlFor('login'));
298
    }
299
300
    $folder = getFolderById($organization['id'], $id);
301
302
    switch ($oper) {
303 View Code Duplication
        case 'swap':
304
            ORM::get_db()->beginTransaction();
305
            $folder2 = getFolderById($organization['id'], $data);
306
            $tmpOrderNr = $folder2['order_nr'];
307
            $folder2->set('order_nr', $folder['order_nr']);
308
            $folder->set('order_nr', $tmpOrderNr);
309
            $folder->save();
310
            $folder2->save();
311
            ORM::get_db()->commit();
312
            break;
313 View Code Duplication
        case 'swapnext':
314
            ORM::get_db()->beginTransaction();
315
            $folder2 = getNextFolderObject($folder);
316
            $tmpOrderNr = $folder2['order_nr'];
317
            $folder2->set('order_nr', $folder['order_nr']);
318
            $folder->set('order_nr', $tmpOrderNr);
319
            $folder->save();
320
            $folder2->save();
321
            ORM::get_db()->commit();
322
            break;
323
    }
324
325
    $app->redirect($app->urlFor('tree', array('id' => $folder['category_id'])));
326
})->name('folderoperation');
327
328
$app->get('/historial/:id(/:return/:data1(/:data2(/:data3)))', function ($id, $return=0, $data1=null, $data2=null, $data3=null)
329
        use ($app, $user, $organization, $config) {
330
    if (!$user) {
331
        $app->redirect($app->urlFor('login'));
332
    }
333
334
    $folder = getFolderById($organization['id'], $id);
335
    if (!$folder) {
336
        $app->redirect($app->urlFor('login'));
337
    }
338
339
    $restrictedProfiles = parseArray(getPermissionProfiles($id, 2));
340
    $uploadProfiles = parseArray(getPermissionProfiles($id, 1));
341
    $managerProfiles = parseArray(getPermissionProfiles($id, 0));
342
    $userProfiles = parseArray(getUserProfiles($user['id'], $organization['id'], true));
343
    $allProfiles = parseArray(getProfilesByOrganization($organization['id']));
344
    $userProfilesList = array();
345 View Code Duplication
    foreach($userProfiles as $prof) {
346
        $userProfilesList[$prof['id']] = $prof['id'];
347
        $userProfilesList[$prof['profile_group_id']] = $prof['profile_group_id'];
348
    }
349
350
    $isManager = $user['is_admin'];
351
    foreach ($managerProfiles as $upload) {
352
        if (isset($userProfiles[$upload['id']])) {
353
            $isManager = true;
354
            break;
355
        }
356
    }
357
358
    $isAllowed = false;
359
    if (!$isManager && $folder['is_restricted']) {
360
        foreach ($restrictedProfiles as $restrict) {
361
            if (isset($userProfiles[$restrict['id']])) {
362
                $isAllowed = true;
363
                break;
364
            }
365
        }
366
    }
367
    else {
368
        $isAllowed = true;
369
    }
370
371
    if (!$isAllowed) {
372
        $app->redirect($app->urlFor('login'));
373
    }
374
375
    $breadcrumb = array();
376
    $lastUrl = $app->request()->getPathInfo();
377
378 View Code Duplication
    switch ($return) {
379
        case 0:
380
            $breadcrumb = array(
381
                array('display_name' => 'Árbol', 'target' => $app->urlFor('tree'))
382
            );
383
            $category = getCategoryObjectById($organization['id'], $folder['category_id']);
384
            $parents = getCategoryParentsById($category['id']);
385
            foreach($parents as $parent) {
386
                $breadcrumb[] = array('display_name' => $parent['display_name'], 'target' => $app->urlFor('tree'));
387
            }
388
            $breadcrumb[] = array('display_name' => $category['display_name'], 'target' => $app->urlFor('tree', array('id' => $category['id'])));
389
            $breadcrumb[] = array('display_name' => 'Estadísticas');
390
            $lastUrl = $app->urlFor('tree', array('id' => $data1));
391
            break;
392
        case 1:
393
            $event = getEventByIdObject($organization['id'], $data3);
394
            $activityevent = getActivityEvent($data3, $data2, $user);
395
            $profile = getProfileById($organization['id'], $data1);
396
            if ((!$event) || (!$activityevent) || (!$profile) || ($event['folder_id'] != $id)) {
397
                $app->redirect($app->urlFor('login'));
398
            }
399
            $lastUrl = $app->urlFor('event', array('pid' => $data1, 'aid' => $data2, 'id' => $data3));
400
401
            $breadcrumb = array(
402
                array('display_name' => 'Actividades', 'target' => $app->urlFor('activities')),
403
                array('display_name' => getProfileFullDisplayName($profile, $user), 'target' => $app->urlFor('activities', array('id' => $data1))),
404
                array('display_name' => $activityevent['activity_display_name'], 'target' => $app->urlFor('activities', array('id' => $data1))),
405
                array('display_name' => $event['display_name'], 'target' => $app->urlFor('event', array('pid' => $data1, 'aid' => $data2, 'id' => $data3))),
406
                array('display_name' => 'Estadísticas')
407
            );
408
            break;
409
    }
410
411
    $snapshots = parseArray(getSnapshotsFromFolder($folder['id']), 'snapshot_id');
412
413
    $profileGender = array();
414
415
    foreach($snapshots as $key => $snapshot) {
416
        $snapshots[$key]['data'] = getDeliveriesFromFolders(array($folder), $isManager ? null : $userProfilesList, $profileGender, $user['id'], $key);
417
    }
418
419
    $folderProfiles = getProfilesByFolderId($folder['id']);
420
    $folders = getFoldersById($folder['id']);
421
    $persons = getFolderPersonsByFolderId($folder['id']);
422
423
    $app->render('folder_snapshots.html.twig', array(
424
        'navigation' => $breadcrumb,
425
        'search' => true,
426
        'url' => $app->request()->getPathInfo(),
427
        'backurl' => array('return' => $return, 'data1' => $data1, 'data2' => $data2, 'data3' => $data3),
428
        'last_url' => $lastUrl,
429
        'snapshots' => $snapshots,
430
        'folderProfiles' => $folderProfiles,
431
        'folders' => $folders,
432
        'persons' => $persons,
433
        'profileGender' => $profileGender,
434
        'restricted_profiles' => $restrictedProfiles,
435
        'upload_profiles' => $uploadProfiles,
436
        'manager_profiles' => $managerProfiles,
437
        'user_profiles' => $userProfiles,
438
        'all_profiles' => $allProfiles,
439
        'folder' => $folder));
440
441
})->name('foldersnapshots');
442
443
function getTree($orgId, $app, $id, &$matchedCategory, &$parentCategory) {
444
    $return = array();
445
    $currentData = array();
446
    $currentCategory = null;
447
    $match = false;
448
449
    $data = ORM::for_table('category')->
450
            order_by_asc('category_left')->
451
            where('organization_id', $orgId)->
452
            where_gt('category_level', 0)->
453
            find_array();
454
455
    foreach ($data as $category) {
456
        if ($category['category_level'] == 1) {
457 View Code Duplication
            if ($currentCategory != null) {
458
                $return[] = array(
459
                    'caption' => $currentCategory['display_name'],
460
                    'active' => $match,
461
                    'target' => '#',
462
                    'subitems' => $currentData
463
                );
464
                if ($match) {
465
                    $parentCategory = $currentCategory;
466
                }
467
            }
468
            $currentData = array();
469
            $currentCategory = $category;
470
            $match = false;
471
        }
472 View Code Duplication
        else {
473
            $localMatch = ($id == $category['id']);
474
            $currentData[] = array(
475
                'caption' => $category['display_name'],
476
                'active' => $localMatch,
477
                'target' => $app->urlFor('tree', array('id' => $category['id']))
478
            );
479
            if ($localMatch) {
480
                $matchedCategory = $category;
481
            }
482
            $match = $match || $localMatch;
483
        }
484
    }
485 View Code Duplication
    if ($currentCategory != null) {
486
        $return[] = array(
487
            'caption' => $currentCategory['display_name'],
488
            'active' => $match,
489
            'target' => '#',
490
            'subitems' => $currentData
491
        );
492
        if ($match) {
493
            $parentCategory = $currentCategory;
494
        }
495
    }
496
497
    return array($return);
498
}
499
500
function getFolderPersons() {
501
    return ORM::for_table('person')->distinct()->
502
            select('person.*')->
503
            inner_join('revision', array('person.id', '=', 'revision.uploader_person_id'))->
504
            inner_join('delivery', array('delivery.current_revision_id', '=', 'revision.id'))->
505
            inner_join('folder_delivery', array('folder_delivery.delivery_id','=','delivery.id'))->
506
            inner_join('folder', array('folder.id','=','folder_delivery.folder_id'))->
507
            where('folder.is_visible', 1);
508
}
509
510
function getFolderPersonsByCategory($categoryId) {
511
    return parseArray(getFolderPersons()->
512
            where('folder.category_id', $categoryId)->
513
            find_array());
514
}
515
516
function getFoldersByCategory($categoryId) {
517
    return parseArray(ORM::for_table('folder')->
518
            where('folder.category_id', $categoryId)->
519
            where('folder.is_visible', 1)->
520
            find_array());
521
}
522
523
function getFolders() {
524
    return ORM::for_table('folder')->
525
            select('folder.*')->
526
            select_expr('sum(person_profile.profile_id IS NOT NULL AND folder_permission.permission=0)','manage_permission')->
527
            select_expr('sum(person_profile.profile_id IS NOT NULL AND folder_permission.permission=1)','upload_permission')->
528
            left_outer_join('folder_permission', array('folder_permission.folder_id', '=', 'folder.id'))->
529
            left_outer_join('profile', 'folder_permission.profile_id IN (profile.profile_group_id, profile.id)')->
530
            left_outer_join('person_profile', array('person_profile.profile_id', '=', 'profile.id'))->
531
            where('folder.is_visible', 1)->
532
            group_by('folder.id');
533
}
534
535
function getFoldersAndStatsByCategoryAndUser($categoryId, $user) {
536
    $data = parseArray(getFolders()->
537
            where('person_profile.person_id', $user['id'])->
538
            where('folder.category_id', $categoryId)->
539
            where('folder.is_visible', 1)->
540
            find_array());
541
    return $data;
542
}
543
544
function getProfiles() {
545
    return ORM::for_table('profile')->distinct()->
546
            select('profile_group.*')->
547
            select('profile.*')->
548
            inner_join('profile_group', array('profile_group.id', '=', 'profile.profile_group_id'))->
549
            inner_join('delivery', array('delivery.profile_id', '=', 'profile.id'))->
550
            inner_join('folder_delivery', array('folder_delivery.delivery_id','=','delivery.id'))->
551
            inner_join('folder', array('folder.id','=','folder_delivery.folder_id'))->
552
            order_by_asc('profile_group_id')->
553
            order_by_asc('profile.id');
554
}
555
556
function getProfilesByCategory($category_id) {
557
    return parseArray(getProfiles()->
558
            where('folder.category_id', $category_id)->
559
            find_array());
560
}
561
562
function getFolderById($orgId, $folderId) {
563
    $data = ORM::for_table('folder')->
564
        select('folder.*')->
565
        inner_join('category', array('category.id', '=', 'category_id'))->
566
        where('category.organization_id', $orgId)->
567
        find_one($folderId);
568
569
    return $data;
570
}
571
572
function getFolder($orgId, $folderId) {
573
    if ((null === $folderId) || (0 === $folderId)) {
574
        return false;
575
    }
576
    return getFolderById($orgId, $folderId);
577
}
578
579
function getCategories($orgId) {
580
    $data = ORM::for_table('category')->
581
            select('category.*')->
582
            where('organization_id', $orgId)->
583
            order_by_asc('category_left')->
584
            find_array();
585
586
    $return = array();
587
588
    $current = null;
589
    $currentData = array();
590
591
    foreach($data as $element) {
592
        if ($element['category_level'] == 1) {
593
            if ($current != null) {
594
                $return[] = array(
595
                    'info' => $current,
596
                    'data' => $currentData
597
                );
598
            }
599
            $current = $element;
600
            $currentData = array();
601
        }
602
        else {
603
            $currentData[] = $element;
604
        }
605
    }
606
    if ($current != null) {
607
        $return[] = array(
608
                    'info' => $current,
609
                    'data' => $currentData
610
        );
611
    }
612
    return $return;
613
}
614
615
function setFolderProfiles($folderId, $permission, $profiles) {
616
    ORM::for_table('folder_permission')->
617
            where('folder_id', $folderId)->
618
            where('permission', $permission)->
619
            delete_many();
620
621
    $ok = true;
622
    foreach ($profiles as $profile) {
623
        $insert = ORM::for_table('folder_permission')->create();
624
        $insert->set('folder_id', $folderId);
625
        $insert->set('permission', $permission);
626
        $insert->set('profile_id', $profile);
627
        $ok = $ok && $insert->save();
628
    }
629
630
    return $ok;
631
}
632
633
function getCategoryObjectById($orgId, $catId) {
634
    return ORM::for_table('category')->
635
            where('organization_id', $orgId)->
636
            where('id', $catId)->
637
            find_one();
638
}
639
640
function getCategoryParentsById($catId) {
641
    $data = array();
642
    $category = ORM::for_table('category')->find_one($catId);
643
    while ($category['category_level']>1) {
644
        $category = ORM::for_table('category')->
645
                where('category_level', $category['category_level']-1)->
646
                where_lt('category_left', $category['category_left'])->
647
                order_by_desc('category_left')->
648
                find_one();
649
        array_unshift($data, $category);
650
    }
651
    return $data;
652
}
653
654
function getMaxFolderOrder($catId) {
655
    return ORM::for_table('folder')->
656
            where('category_id', $catId)->
657
            max('order_nr');
658
}
659
660
function getFoldersByOrganization($orgId, $filter = true) {
661
    $folders = ORM::for_table('folder')->
662
            select('folder.*')->
663
            inner_join('category', array('category.id', '=', 'folder.category_id'))->
664
            where('category.organization_id', $orgId)->
665
            order_by_asc('order_nr');
666
667
    if ($filter) {
668
        $folders = $folders->where('is_visible', 1);
669
    }
670
671
    return $folders;
672
}
673
674 View Code Duplication
function getSnapshotsFromFolder($folderId) {
675
    return ORM::for_table('folder_delivery')->
676
            distinct()->
677
            select('snapshot_id')->
678
            select('snapshot.display_name')->
679
            select('snapshot.order_nr')->
680
            inner_join('snapshot', array('snapshot.id', '=', 'folder_delivery.snapshot_id'))->
681
            where_not_null('snapshot_id')->
682
            where('folder_id', $folderId)->
683
            where('snapshot.visible', 1)->
684
            order_by_desc('snapshot.order_nr')->
685
            find_many();
686
}
687
688
function getDeliveriesFromFolders($folders, $userProfiles, &$profileGender, $userId, $snapshot = null) {
689
690
    $return = array();
691
    foreach($folders as $folder) {
692
        // comprobar si la carpeta es de acceso restringido
693
        $skip = false;
694
        if ($folder['is_restricted'] && ($userProfiles !== null)) {
695
            $visible = ORM::for_table('folder_permission')->
696
                    where('folder_id', $folder['id'])->
697
                    where('permission', 2)->
698
                    where_in('profile_id', $userProfiles)->
699
                    count();
700
            
701
            $skip = ($visible == 0);
702
        }
703
        if ($skip === false) {
704
            $deliveries = ORM::for_table('delivery')->
705
                    select('delivery.*')->
706
                    select('folder_delivery.order_nr')->
707
                    select('revision.upload_date')->
708
                    select('revision.uploader_person_id')->
709
                    select('revision.revision_nr')->
710
                    select('person.gender')->
711
                    inner_join('folder_delivery', array('folder_delivery.delivery_id', '=', 'delivery.id'))->
712
                    inner_join('revision', array('delivery.current_revision_id', '=', 'revision.id'))->
713
                    inner_join('person', array('person.id', '=', 'revision.uploader_person_id'))->
714
                    where('folder_delivery.folder_id', $folder['id'])->
715
                    order_by_asc('folder_delivery.snapshot_id')->
716
                    order_by_asc('delivery.profile_id')->
717
                    order_by_asc('order_nr');
718
719
            $isManager = false;
720
721
            if (!is_null($userProfiles) && ($folder['is_private_personal'] || $folder['is_private_profile'])) {
722
                $managerProfiles = array_keys(parseArray(getPermissionProfiles($folder['id'], 0)));
723
                $isManager = (count(array_intersect($managerProfiles, array_keys($userProfiles))) != 0);
724
            }
725
726
            if (!is_null($userProfiles) && !$isManager) {
727
                if ($folder['is_private_personal']) {
728
                    $deliveries = $deliveries->where('revision.uploader_person_id', $userId);
729
                } elseif ($folder['is_private_profile']) {
730
                    $deliveries = $deliveries->
731
                            where_in('delivery.profile_id', $userProfiles);
732
                }
733
            }
734
            if (is_null($snapshot)) {
735
                $deliveries = $deliveries->where_null('folder_delivery.snapshot_id');
736
            }
737
            elseif ($snapshot == 0) {
738
                $deliveries = $deliveries->where_not_null('folder_delivery.snapshot_id');
739
            }
740
            else {
741
                $deliveries = $deliveries->where('folder_delivery.snapshot_id', $snapshot);
742
            }
743
744
            $deliveries = $deliveries->find_array();
745
746
            $return[] = array(
747
                'id' => $folder['id'],
748
                'data' => $deliveries
749
            );
750
            foreach($deliveries as $delivery) {
751
                if (isset($profileGender[$delivery['profile_id']])) {
752
                    if ($profileGender[$delivery['profile_id']] != $delivery['gender']) {
753
                        $profileGender[$delivery['profile_id']] = 0;
754
                    }
755
                }
756
                else {
757
                    $profileGender[$delivery['profile_id']] = $delivery['gender'];
758
                }
759
            }
760
        }
761
    }
762
    return $return;
763
}
764
765
function getParsedDeliveriesByCategory($orgId, $catId, $userProfiles, &$profileGender, $userId, $filter = true) {
766
767
    $folders = getFoldersByOrganization($orgId, $filter)->
768
                where('category_id', $catId)->
769
                find_array();
770
771
    return getDeliveriesFromFolders($folders, $userProfiles, $profileGender, $userId);
772
}
773
774
function getNextFolderObject($folder) {
775
    return ORM::for_table('folder')->
776
            where('category_id', $folder['category_id'])->
777
            where_gt('order_nr', $folder['order_nr'])->
778
            find_one();
779
}
780
781
function createEventItem($id, $profileId, $displayName, $documentName) {
782
    $order = ORM::for_table('event_profile_delivery_item')->
783
            where('profile_id', $profileId)->
784
            where('event_id', $id)->max('order_nr');
785
786
    $order = ($order) ? ($order + 1000) : 1000;
787
788
    $item = ORM::for_table('event_profile_delivery_item')->create()->
789
            set('profile_id', $profileId)->
790
            set('event_id', $id)->
791
            set('display_name', $displayName)->
792
            set('order_nr', $order)->
793
            set('document_name', $documentName);
794
    return $item->save();
795
}
796
797
function deleteEventItems($id, $items) {
798
    $ok = true;
799
    foreach($items as $item) {
800
        $ok = $ok && ORM::for_table('event_profile_delivery_item')->
801
            where('id', $item)->
802
            where('event_id', $id)->delete_many();
803
    }
804
    return $ok;
805
}
806
807 View Code Duplication
function orderEventItems($id, $profileId) {
808
    $ok = true;
809
    $order = 0;
810
811
    $items = ORM::for_table('event_profile_delivery_item')->
812
            where('profile_id', $profileId)->
813
            where('event_id', $id)->
814
            order_by_asc('display_name')->
815
            find_many();
816
817
    foreach($items as $item) {
818
        $ok = $ok && $item->set('order_nr', $order)->save();
819
        $order += 1000;
820
    }
821
    return $ok;
822
}
823
824
function getEventProfileDeliveryItems($profileId, $eventId) {
825
    $data = ORM::for_table('event_profile_delivery_item')->
826
            where('event_id', $eventId)->
827
            where('profile_id', $profileId)->
828
            where('is_visible', 1)->
829
            order_by_asc('order_nr')->
830
            find_many();
831
    return $data;
832
}
833
834
function getEventDeliveryItems($orgId, $eventId) {
835
    $data = ORM::for_table('event_profile_delivery_item')->
836
        select('event_profile_delivery_item.*')->
837
        inner_join('profile',array('profile_id', '=', 'profile.id'))->
838
        inner_join('profile_group',array('profile.profile_group_id', '=', 'profile_group.id'))->
839
        where('event_id', $eventId)->
840
        where('is_visible', 1)->
841
        where('profile_group.organization_id', $orgId)->
842
        order_by_asc('profile_group.display_name_neutral')->
843
        order_by_asc('profile.display_name')->
844
        order_by_asc('order_nr')->
845
        find_many();
846
    return $data;
847
}
848