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.
Completed
Push — develop ( 64c0c8...2d0c86 )
by Luis Ramón
05:14
created

event.php ➔ getParsedDeliveriesByOrganization()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 44
Code Lines 35

Duplication

Lines 6
Ratio 13.64 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 35
c 3
b 0
f 0
nc 10
nop 1
dl 6
loc 44
rs 8.439
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('/actividad/:pid/:aid/:id', function ($pid, $aid, $id) use ($app, $user, $organization) {
20
    if (!$user) {
21
        $app->redirect($app->urlFor('login'));
22
    }
23
24
    // obtener evento
25
    // TODO: Comprobar que el evento es válido
26
    $event = getActivityEvent($id, $aid, $user)->as_array();
27
28
    if (!$event) {
29
        $app->redirect($app->urlFor('frontpage'));
30
    }
31
32
    // marcar evento como no completado
33 View Code Duplication
    if ($event['is_manual'] && ($event['completed_date'] != null) && isset($_POST['unmark'])) {
34
        removeCompletedEvent($id, $user['id']);
35
        $app->redirect($app->urlFor('activities', array('id' => $pid)));
36
    }
37
38
    // marcar evento como completado
39 View Code Duplication
    if ($event['is_manual'] && ($event['completed_date'] == null) && isset($_POST['mark'])) {
40
        addCompletedEvent($id, $user['id']);
41
        $app->redirect($app->urlFor('activities', array('id' => $pid)));
42
    }
43
44
    // obtener carpeta
45
    $folder = getFolder($organization['id'], $event['folder_id']);
46
47
    // obtener entregas asociadas
48
    $deliveries = getDeliveriesFromEvent($id);
49
50
    // obtener perfiles
51
    $profiles = parseArray(getUserProfiles($user['id'], $organization['id'], false));
52
    $userProfiles = getUserProfiles($user['id'], $organization['id'], true);
53
    $userProfilesList = array();
54 View Code Duplication
    foreach($userProfiles as $prof) {
55
        $userProfilesList[$prof['id']] = $prof['id'];
56
        $userProfilesList[$prof['profile_group_id']] = $prof['profile_group_id'];
57
    }
58
   
59
    $isMine = isset($profiles[$pid]);
60
    foreach ($profiles as $p) {
61
        $isMine = $isMine || ($p['profile_group_id'] == $pid);
62
    }
63
64
    $breadcrumb = array(
65
        array('display_name' => 'Actividades', 'target' => $app->urlFor('activities')),
66
        array('display_name' => 'Gestionar actividades', 'target' => $app->urlFor('manageallevents')),
67
        array('display_name' => $event['activity_display_name'], 'target' => $app->urlFor('activities', array('id' => $pid))),
68
        array('display_name' => $event['display_name'])
69
    );
70
71
    if ($folder && isset($folder['id'])) {
72
        $profileGender = array();
73
        $data = getParsedFolderById($organization['id'], $folder['id'], $userProfilesList, $profileGender, $user['id']);
74
        $folderProfiles = getProfilesByFolderId($folder['id']);
75
        $folders = getFoldersById($folder['id']);
76
        $persons = getFolderPersonsByFolderId($folder['id']);
77
    }
78
    else {
79
        $profileGender = array();
80
        $data = array();
81
        $folderProfiles = array();
82
        $folders = array();
83
        $persons = array();
84
    }
85
    $app->flash('last_url', $app->request()->getPathInfo());
86
87
    // generar página
88
    $app->render('event.html.twig', array(
89
        'navigation' => $breadcrumb, 'search' => true,
90
        'url' => $app->request()->getPathInfo(),
91
        'pid' => $pid,
92
        'aid' => $aid,
93
        'user' => $user,
94
        'profiles' => $profiles,
95
        'profileGender' => $profileGender,
96
        'folder' => $folder,
97
        'folders' => $folders,
98
        'folderProfiles' => $folderProfiles,
99
        'persons' => $persons,
100
        'data' => $data,
101
        'isMine' => $isMine,
102
        'deliveries' => $deliveries,
103
        'backurl' => array('return' => 1, 'data1' => $pid, 'data2' => $aid, 'data3' => $id),
104
        'event' => $event));
105
})->name('event')->via('GET', 'POST');
106
107
$app->map('/actividad/:id(/:actid)', function ($id, $actid = null) use ($app, $user, $organization) {
108
    if (!$user || !$user['is_admin']) {
109
        $app->redirect($app->urlFor('login'));
110
    }
111
112
    // obtener evento
113
    // TODO: Comprobar que el evento es válido
114
    if ($id != 0) {
115
        $event = getEventByIdObject($organization['id'], $id);
116
    }
117
    else {
118
        $event = array(
119
            'is_visible' => 1,
120
            'is_manual' => 0,
121
            'is_automatic' => 0,
122
            'force_period' => 0,
123
            'grace_period' => 0
124
        );
125
    }
126
127
    if (!$event) {
128
        $app->redirect($app->urlFor('frontpage'));
129
    }
130
131
    if (isset($_POST['saveevent'])) {
132
        ORM::get_db()->beginTransaction();
133
134
        if ($id == 0) {
135
            $local = ORM::for_table('event')->create();
136
        }
137
        else {
138
            $local = $event;
139
        }
140
        $local->set('organization_id', $organization['id']);
141
        $local->set('display_name', $_POST['displayname']);
142
        $local->set('description', strlen($_POST['description'])>0 ? $_POST['description'] : $_POST['displayname']);
143
        $local->set('is_visible', $_POST['visible']);
144
        $local->set('is_manual', $_POST['manual']);
145
        $local->set('is_automatic', $_POST['automatic']);
146
        $local->set('force_period', $_POST['forceperiod']);
147
        $local->set('grace_period', $_POST['graceperiod']);
148
        $local->set('is_automatic', $_POST['automatic']);
149
        $folder_change = ($local['folder_id'] != $_POST['folder']);
150
        if ($_POST['folder']) {
151
            if ($local['folder_id'] && $folder_change) {
152
                checkItemUpdateStatusByFolder($local['folder_id']);
153
            }
154
            $local->set('folder_id', $_POST['folder']);
155
156
        }
157
        $local->set('from_week', $_POST['fromweek']+4*$_POST['frommonth']);
158
        $local->set('to_week', $_POST['toweek']+4*$_POST['tomonth']);
159
160
        if ($local->save()) {
161
            $id = $local['id'];
162
            $ok = setEventProfiles($id, $_POST['profiles']);
163
            if (isset($_POST['categories'])) {
164
                $ok = $ok && setEventActivities($id, $_POST['categories']);
165
            }
166
            if (isset($_POST['deliveries'])) {
167
                $ok = $ok && setEventDeliveries($id, $_POST['deliveries']);
168
            }
169
            if ($ok) {
170
                if ($_POST['folder'] && $folder_change) {
171
                    checkItemUpdateStatusByFolder($local['folder_id']);
172
                }
173
                $app->flash('save_ok', 'ok');
174
                ORM::get_db()->commit();
175
            }
176
            else {
177
                $app->flash('save_error', 'error');
178
                ORM::get_db()->rollBack();
179
            }
180
        }
181
        else {
182
            $app->flash('save_error', 'error');
183
            ORM::get_db()->rollBack();
184
        }
185
186
        $app->redirect($app->request()->getPathInfo());
187
    }
188
189
    // obtener carpeta
190
    $folders = getParsedFolderTree($organization['id']);
191
192
    // obtener todas las categorías de eventos
193
    $categories = getActivities($organization['id']);
194
195
    // obtener las activas en este evento
196
    if ($id == 0) {
197
        $selectedCategories = ($actid != 0) ? array($actid => array('id' => $actid)) : array();
198
    }
199
    else {
200
        $selectedCategories = getEventActivitiesId($id);
201
    }
202
203
    // obtener todos los perfiles
204
    $allProfiles = getProfilesByOrganization($organization['id'], true, true);
205
206
    // obtener los perfiles asociados a este evento
207
    $profiles = ($id == 0) ? array() : getEventProfilesId($id);
208
209
    // obtener todas las entregas de la organización (!!!)
210
    $allDeliveries = getParsedDeliveriesByOrganization($organization['id']);
211
212
    // obtener las entregas asociadas
213
    $deliveries = ($id == 0) ? array() : parseArray(getDeliveriesFromEvent($id));
214
215
    $breadcrumb = array(
216
        array('display_name' => 'Actividades', 'target' => $app->urlFor('activities')),
217
        array('display_name' => 'Gestionar actividades', 'target' => $app->urlFor('manageallevents')),
218
        array('display_name' => ($id == 0) ? 'Nueva actividad' : $event['display_name'])
219
    );
220
221
    // generar página
222
    $app->render('manage_event.html.twig', array(
223
        'navigation' => $breadcrumb,
224
        'select2' => true,
225
        'url' => $app->request()->getPathInfo(),
226
        'folders' => $folders,
227
        'profiles' => $profiles,
228
        'allProfiles' => $allProfiles,
229
        'deliveries' => $deliveries,
230
        'allDeliveries' => $allDeliveries,
231
        'new' => ($id == 0),
232
        'categories' => $categories,
233
        'selectedCategories' => $selectedCategories,
234
        'event' => $event));
235
})->name('manageevent')->via('GET', 'POST');
236
237
$app->map('/elemento/:id/:profileid/(:actid)', function ($id, $profileid, $actid = null) use ($app, $user, $organization) {
238
    if (!$user && $user['is_admin']) {
239
        $app->redirect($app->urlFor('login'));
240
    }
241
242
    $event = getEventByIdObject($organization['id'], $id);
243
    $uploadProfiles = parseArray(getPermissionProfiles($event['folder_id'], 1));
244
245
    if (isset($_POST['changeprofile'])) {
246
        $app->redirect($app->urlFor('manageitem', array('id' => $id, 'profileid' => $_POST['profile'], 'actid' => $actid )));
247
    }
248
249 View Code Duplication
    if (isset($_POST['up']) || isset($_POST['down'])) {
250
        if (isset($_POST['up'])) {
251
            $item1 = getItemById($organization['id'], $_POST['up']);
252
            $item2 = getPreviousItem($organization['id'], $_POST['up'], $profileid);
253
        }
254
        else {
255
            $item1 = getItemById($organization['id'], $_POST['down']);
256
            $item2 = getNextItem($organization['id'], $_POST['down'], $profileid);
257
        }
258
259
        if (!$item1 || !$item2) {
260
            $app->redirect($app->urlFor('login'));
261
        }
262
263
        $order_nr = $item1['order_nr'];
264
        $item1->set('order_nr', $item2['order_nr'])->save();
265
        $item2->set('order_nr', $order_nr)->save();
266
    }
267
268
    if (isset($_POST['new'])) {
269
        $lines = explode("\n", $_POST['newelements']);
270
        $ok = true;
271
        ORM::get_db()->beginTransaction();
272
        foreach($lines as $line) {
273
            $line = str_replace('\r', '', $line);
274
            if ($line) {
275
                $item = explode("*", trim($line));
276
                $ok = $ok && createEventItem($id, $_POST['profile'], $item[0], isset($item[1]) ? $item[1] : $item[0]);
277
            }
278
        }
279
        if ($ok) {
280
            if ($event['folder_id']) {
281
                checkItemUpdateStatusByFolder($event['folder_id']);
282
            }
283
            $app->flash('save_ok', 'ok');
284
            ORM::get_db()->commit();
285
        }
286
        else {
287
            $app->flash('save_error', 'error');
288
            ORM::get_db()->rollBack();
289
        }
290
        $app->redirect($app->request()->getPathInfo());
291
    }
292
293 View Code Duplication
    if (isset($_POST['delete']) && isset($_POST['item'])) {
294
        ORM::get_db()->beginTransaction();
295
        if (deleteEventItems($id, $_POST['item'])) {
296
            if ($event['folder_id']) {
297
                checkItemUpdateStatusByFolder($event['folder_id']);
298
            }
299
            ORM::get_db()->commit();
300
            $app->flash('save_ok', 'ok');
301
        }
302
        else {
303
            ORM::get_db()->rollBack();
304
            $app->flash('save_error', 'error');
305
        }
306
        $app->redirect($app->request()->getPathInfo());
307
    }
308
309
    if (isset($_POST['order'])) {
310
        ORM::get_db()->beginTransaction();
311
        if (orderEventItems($id, $_POST['profile'])) {
312
            ORM::get_db()->commit();
313
            $app->flash('save_ok', 'ok');
314
        }
315
        else {
316
            ORM::get_db()->rollBack();
317
            $app->flash('save_error', 'error');
318
        }
319
        $app->redirect($app->request()->getPathInfo());
320
    }
321
322
    $uploadAs = array();
323
324
    foreach ($uploadProfiles as $item) {
325
        if (null == $item['display_name']) {
326
            $data = parseArray(getSubprofiles($item['id']));
327
            if (count($data)>1) {
328
                foreach($data as $subItem) {
329
                    if (null != $subItem['display_name']) {
330
                        $uploadAs[$subItem['id']] = $subItem;
331
                        if ($profileid == 0) {
332
                            $profileid = $subItem['id'];
333
                        }
334
                    }
335
                }
336
            }
337 View Code Duplication
            else {
338
                $uploadAs[$item['id']] = $item;
339
                if ($profileid == 0) {
340
                    $profileid = $item['id'];
341
                }
342
            }
343
        }
344 View Code Duplication
        else {
345
            $uploadAs[$item['id']] = $item;
346
            if ($profileid == 0) {
347
                $profileid = $item['id'];
348
            }
349
        }
350
    }
351
352
    if (isset($_POST['move']) && isset($_POST['item']) && isset($uploadAs[$_POST['profileto']])) {
353
        ORM::get_db()->beginTransaction();
354
        $ok = true;
355
        foreach($_POST['item'] as $itemId) {
356
            $item = getItemById($organization['id'], $itemId);
357
            $item->set('profile_id', $_POST['profileto']);
358
            $item->set('order_nr', getLastItemOrderNr($event['id'],$_POST['profileto']) + 1000);
359
            $ok = $ok && $item->save();
360
        }
361
        if ($ok) {
362
            ORM::get_db()->commit();
363
            $app->flash('save_ok', 'ok');
364
        }
365
        else {
366
            ORM::get_db()->rollBack();
367
            $app->flash('save_error', 'error');
368
        }
369
        $app->redirect($app->request()->getPathInfo());
370
    }
371
372
    $folder = getFolder($organization['id'], $event['folder_id']);
373
374
    $items = parseArray(getEventProfileDeliveryItems($profileid, $id));
375
376
    $breadcrumb = array(
377
        array('display_name' => 'Actividades', 'target' => $app->urlFor('activities')),
378
        array('display_name' => $event['display_name'], 'target' => $app->urlFor('manageevent', array('id' => $id))),
379
        array('display_name' => 'Gestionar entregas')
380
    );
381
382
    $app->flashKeep();
383
384
    $app->render('manage_item.html.twig', array(
385
        'navigation' => $breadcrumb, 'search' => true,
386
        'select2' => true,
387
        'url' => $app->request()->getPathInfo(),
388
        'uploaders' => $uploadAs,
389
        'items' => $items,
390
        'profileid' => $profileid,
391
        'id' => $id,
392
        'event' => $event,
393
        'actid' => $actid,
394
        'back_url' => $app->urlFor('manageevent', array('id' => $id)),
395
        'folder' => $folder));
396
})->name('manageitem')->via('GET', 'POST');
397
398
$app->map('/elemento/:id', function ($id) use ($app, $user, $organization) {
399
    if (!$user && $user['is_admin']) {
400
        $app->redirect($app->urlFor('login'));
401
    }
402
403
    $event = getEventByIdObject($organization['id'], $id);
404
    $uploadProfiles = parseArray(getPermissionProfiles($event['folder_id'], 1));
405
406
    if (isset($_POST['up']) || isset($_POST['down'])) {
407
        if (isset($_POST['up'])) {
408
            $split = explode("!", $_POST['up']);
409
            $item1 = getItemById($organization['id'], $split[0]);
410
            $item2 = getPreviousItem($organization['id'], $split[0], $split[1]);
411
        }
412
        else {
413
            $split = explode("!", $_POST['down']);
414
            $item1 = getItemById($organization['id'], $split[0]);
415
            $item2 = getNextItem($organization['id'], $split[0], $split[1]);
416
        }
417
418
        if (!$item1 || !$item2) {
419
            $app->redirect($app->urlFor('login'));
420
        }
421
422
        $order_nr = $item1['order_nr'];
423
        $item1->set('order_nr', $item2['order_nr'])->save();
424
        $item2->set('order_nr', $order_nr)->save();
425
    }
426
427 View Code Duplication
    if (isset($_POST['delete'])) {
428
        ORM::get_db()->beginTransaction();
429
        if (deleteEventItems($id, $_POST['item'])) {
430
            if ($event['folder_id']) {
431
                checkItemUpdateStatusByFolder($event['folder_id']);
432
            }
433
            ORM::get_db()->commit();
434
            $app->flash('save_ok', 'ok');
435
        }
436
        else {
437
            ORM::get_db()->rollBack();
438
            $app->flash('save_error', 'error');
439
        }
440
        $app->redirect($app->request()->getPathInfo());
441
    }
442
443
    $uploadAs = array();
444
445
    foreach ($uploadProfiles as $item) {
446
        if (null == $item['display_name']) {
447
            $data = parseArray(getSubprofiles($item['id']));
448
            if (count($data)>1) {
449
                foreach($data as $subItem) {
450
                    if (null != $subItem['display_name']) {
451
                        $uploadAs[$subItem['id']] = $subItem;
452
                    }
453
                }
454
            }
455
            else {
456
                $uploadAs[$item['id']] = $item;
457
            }
458
        }
459
        else {
460
            $uploadAs[$item['id']] = $item;
461
        }
462
    }
463
464
    if (isset($_POST['new'])) {
465
        $lines = explode("\n", $_POST['newelements']);
466
        $ok = true;
467
        ORM::get_db()->beginTransaction();
468
        foreach($lines as $line) {
469
            $line = trim($line);
470
            $line = str_replace('\r', '', $line);
471
            if ($line) {
472
                $item = explode("*", trim($line));
473
                foreach($_POST['profilenew'] as $profile) {
474
                    if (isset($uploadAs[$profile])) {
475
                        $ok = $ok && createEventItem($id, $profile, $item[0], isset($item[1]) ? $item[1] : $item[0]);
476
                    }
477
                }
478
            }
479
        }
480
        if ($ok) {
481
            if ($event['folder_id']) {
482
                checkItemUpdateStatusByFolder($event['folder_id']);
483
            }
484
            $app->flash('save_ok', 'ok');
485
            ORM::get_db()->commit();
486
        }
487
        else {
488
            $app->flash('save_error', 'error');
489
            ORM::get_db()->rollBack();
490
        }
491
        $app->redirect($app->request()->getPathInfo());
492
    }
493
494
    if (isset($_POST['import']) && isset($_POST['event']) && $_POST['event']) {
495
        $ok = true;
496
        ORM::get_db()->beginTransaction();
497
498
        $origin = getEventDeliveryItems($organization['id'], $_POST['event']);
499
500
        foreach($origin as $it) {
501
            if (isset($uploadAs[$it['profile_id']])) {
502
                $ok = $ok && createEventItem($id, $it['profile_id'], $it['display_name'], $it['document_name']);
503
            }
504
        }
505
506
        if ($ok) {
507
            if ($event['folder_id']) {
508
                checkItemUpdateStatusByFolder($event['folder_id']);
509
            }
510
            $app->flash('save_ok', 'ok');
511
            ORM::get_db()->commit();
512
        }
513
        else {
514
            $app->flash('save_error', 'error');
515
            ORM::get_db()->rollBack();
516
        }
517
        $app->redirect($app->request()->getPathInfo());
518
    }
519
520
    if (isset($_POST['replace']) && isset($_POST['replace_this']) && $_POST['replace_this']) {
521
        $items = getEventDeliveryItems($organization['id'], $id);
522
523
        ORM::get_db()->beginTransaction();
524
        $ok = true;
525
526
        foreach($items as $it) {
527
            $it->set('display_name', str_replace($_POST['replace_this'], $_POST['replace_with'], $it['display_name']));
528
            $it->set('document_name', str_replace($_POST['replace_this'], $_POST['replace_with'], $it['document_name']));
529
            $ok = $ok && $it->save();
530
        }
531
532
        if ($ok) {
533
            $app->flash('save_ok', 'ok');
534
            ORM::get_db()->commit();
535
        }
536
        else {
537
            $app->flash('save_error', 'error');
538
            ORM::get_db()->rollBack();
539
        }
540
        $app->redirect($app->request()->getPathInfo());
541
    }
542
543
    $folder = getFolder($organization['id'], $event['folder_id']);
544
545
    $profiles1 = parseArrayMix(getEventDeliveryItems($organization['id'], $id), 'profile_id');
546
547
    $profiles = array();
548
    
549
    // damos una vuelta a la lista por si hay perfiles sin elementos
550
    // hay que ponerlos en orden, de ahí la chapuza
551
    foreach($uploadAs as $prof) {
552
        if (!isset($profiles1[$prof['id']])) {
553
            $profiles[$prof['id']] = array();
554
        }
555
        else {
556
            $profiles[$prof['id']] = $profiles1[$prof['id']];
557
        }
558
    }
559
560
    $breadcrumb = array(
561
        array('display_name' => 'Actividades', 'target' => $app->urlFor('activities')),
562
        array('display_name' => $event['display_name'], 'target' => $app->urlFor('manageevent', array('id' => $id))),
563
        array('display_name' => 'Gestionar entregas')
564
    );
565
566
    $events = getAllEventsGroupedByActivity($organization['id']);
567
    $activities = getAllActivities($organization['id']);
568
569
    $app->render('manage_all_item.html.twig', array(
570
        'navigation' => $breadcrumb, 'search' => true,
571
        'select2' => true,
572
        'url' => $app->request()->getPathInfo(),
573
        'uploaders' => $uploadAs,
574
        'profiles' => $profiles,
575
        'id' => $id,
576
        'event' => $event,
577
        'events' => $events,
578
        'activities' => $activities,
579
        'back_url' => $app->urlFor('manageevent', array('id' => $id)),
580
        'folder' => $folder));
581
})->name('manageallitems')->via('GET', 'POST');
582
583
$app->map('/elemento/modificar/:id/:all', function ($id, $all) use ($app, $user, $organization) {
584
    if (!$user && $user['is_admin']) {
585
        $app->redirect($app->urlFor('login'));
586
    }
587
588
    $item = getItemById($organization['id'], $id);
589
    if ($item === false) {
590
        $app->redirect($app->urlFor('login'));
591
    }
592
    $event = getEventByIdObject($organization['id'], $item['event_id']);
593
    if ($event === false) {
594
        $app->redirect($app->urlFor('login'));
595
    }
596
597
    $uploadProfiles = parseArray(getPermissionProfiles($event['folder_id'], 1));
598
599
    $uploadAs = array();
600
    $profileid = $item['profile_id'];
601
    $profile = getProfileById($organization['id'], $profileid);
602
    foreach ($uploadProfiles as $newitem) {
603
        if (null == $newitem['display_name']) {
604
            $data = parseArray(getSubprofiles($newitem['id']));
605
            if (count($data)>1) {
606
                foreach($data as $subItem) {
607
                    if (null != $subItem['display_name']) {
608
                        $uploadAs[$subItem['id']] = $subItem;
609
                    }
610
                }
611
            }
612
            else {
613
                $uploadAs[$newitem['id']] = $newitem;
614
            }
615
        }
616
        else {
617
            $uploadAs[$newitem['id']] = $newitem;
618
        }
619
    }
620
621
    if ($all) {
622
        $backUrl = $app->urlFor('manageallitems', array('id' => $event['id']));
623
    }
624
    else {
625
        $backUrl = $app->urlFor('manageitem', array('id' => $event['id'], 'profileid' => $item['profile_id']));
626
    }
627
628
    if (isset($_POST['save']) && isset($uploadAs[$_POST['profile']])) {
629
        $item->set('profile_id', $_POST['profile']);
630
        $displayName = trim($_POST['displayname']);
631
        $item->set('display_name', $displayName);
632
        $documentName = trim($_POST['documentname']);
633
        $item->set('document_name', $documentName ? $documentName : $displayName);
634
635
        $ok = $item->save();
636
637
        if ($ok) {
638
            $app->flash('save_ok', 'ok');
639
            $app->redirect($backUrl);
640
        }
641
        else {
642
            $app->flash('save_error', 'error');
643
        }
644
    }
645
646
    $breadcrumb = array(
647
        array('display_name' => 'Actividades', 'target' => $app->urlFor('activities')),
648
        array('display_name' => $event['display_name'], 'target' => $app->urlFor('manageevent', array('id' => $event['id']))),
649
        array('display_name' => $profile['display_name_neutral'] . ' ' . $profile['display_name'], 'target' => $backUrl),
650
        array('display_name' => $item['display_name'])
651
    );
652
653
    $app->render('manage_delivery_item.html.twig', array(
654
        'navigation' => $breadcrumb, 'search' => true,
655
        'select2' => true,
656
        'url' => $app->request()->getPathInfo(),
657
        'upload_as' => $uploadAs,
658
        'id' => $id,
659
        'event' => $event,
660
        'item' => $item,
661
        'all' => $all,
662
        'back_url' => $backUrl
663
    ));
664
})->name('managedeliveryitem')->via('GET', 'POST');
665
666
$app->map('/elemento/nuevo/:id/:profileid', function ($id, $profileid) use ($app, $user, $organization) {
667
    if (!$user && $user['is_admin']) {
668
        $app->redirect($app->urlFor('login'));
669
    }
670
671
    $event = getEventByIdObject($organization['id'], $id);
672
    if ($event === false) {
673
        $app->redirect($app->urlFor('login'));
674
    }
675
676
    $uploadProfiles = parseArray(getPermissionProfiles($event['folder_id'], 1));
677
678
    $uploadAs = array();
679
    $profile = getProfileById($organization['id'], $profileid);
680
    foreach ($uploadProfiles as $newitem) {
681
        if (null == $newitem['display_name']) {
682
            $data = parseArray(getSubprofiles($newitem['id']));
683
            if (count($data)>1) {
684
                foreach($data as $subItem) {
685
                    if (null != $subItem['display_name']) {
686
                        $uploadAs[$subItem['id']] = $subItem;
687
                    }
688
                }
689
            }
690
            else {
691
                $uploadAs[$newitem['id']] = $newitem;
692
            }
693
        }
694
        else {
695
            $uploadAs[$newitem['id']] = $newitem;
696
        }
697
    }
698
    $item = ORM::for_table('event_profile_delivery_item')->create();
699
    $item->set('event_id', $id);
700
    $item->set('profile_id', $profileid);
701
    $item->set('display_name', '');
702
    $item->set('document_name', '');
703
704
    if (!isset($uploadAs[$profileid])) {
705
        $app->redirect($app->urlFor('login'));
706
    }
707
708
    $backUrl = $app->urlFor('manageitem', array('id' => $event['id'], 'profileid' => $item['profile_id']));
709
710
    if (isset($_POST['save'])) {
711
        $displayName = trim($_POST['displayname']);
712
        $item->set('display_name', $displayName);
713
        $documentName = trim($_POST['documentname']);
714
        $item->set('document_name', $documentName ? $documentName : $displayName);
715
        $item->set('order_nr', getLastItemOrderNr($event['id'], $profileid) + 1000);
716
        $ok = $item->save();
717
718
        if ($ok) {
719
            $app->flash('save_ok', 'ok');
720
            $app->redirect($backUrl);
721
        }
722
        else {
723
            $app->flash('save_error', 'error');
724
        }
725
    }
726
727
    $breadcrumb = array(
728
        array('display_name' => 'Actividades', 'target' => $app->urlFor('activities')),
729
        array('display_name' => $event['display_name'], 'target' => $app->urlFor('manageevent', array('id' => $event['id']))),
730
        array('display_name' => $profile['display_name_neutral'] . ' ' . $profile['display_name'], 'target' => $backUrl),
731
        array('display_name' => 'Nueva entrada')
732
    );
733
734
    $app->render('manage_delivery_item.html.twig', array(
735
        'navigation' => $breadcrumb, 'search' => true,
736
        'select2' => true,
737
        'url' => $app->request()->getPathInfo(),
738
        'upload_as' => $uploadAs,
739
        'id' => $id,
740
        'event' => $event,
741
        'item' => $item,
742
        'new' => true,
743
        'back_url' => $backUrl
744
    ));
745
})->name('newdeliveryitem')->via('GET', 'POST');
746
747
function getActivityEvent($eventId, $activityId, $user) {
748
    return ORM::for_table('event')->
749
            select('event.*')->
750
            select('activity.id', 'activity_id')->
751
            select('activity.display_name', 'activity_display_name')->
752
            select('completed_event.completed_date')->
753
            inner_join('activity_event', array('activity_event.event_id','=','event.id'))->
754
            inner_join('activity', array('activity.id','=','activity_event.activity_id'))->
755
            left_outer_join('completed_event', 'completed_event.event_id = event.id AND completed_event.person_id = ' . $user['id'])->
756
            where('activity_event.activity_id', $activityId)->
757
            find_one($eventId);
758
}
759
760
function getEventByIdObject($orgId, $eventId) {
761
    return ORM::for_table('event')->
762
            select('event.*')->
763
            inner_join('activity_event', array('activity_event.event_id','=','event.id'))->
764
            inner_join('activity', array('activity.id','=','activity_event.activity_id'))->
765
            where('activity.organization_id', $orgId)->
766
            find_one($eventId);
767
}
768
769
function getDeliveriesFromEvent($eventId) {
770
771
    $data = ORM::for_table('delivery')->
772
            select('delivery.*')->
773
            select('event_delivery.description', 'event_delivery_description')->
774
            select('revision.upload_date')->
775
            select('revision.uploader_person_id')->
776
            select('person.display_name', 'person_display_name')->
777
            inner_join('event_delivery', array('event_delivery.delivery_id','=','delivery.id'))->
778
            inner_join('revision', array('delivery.current_revision_id', '=', 'revision.id'))->
779
            inner_join('person', array('person.id', '=', 'revision.uploader_person_id'))->
780
            order_by_asc('delivery.display_name')->
781
            where('event_delivery.event_id', $eventId)->
782
            find_array();
783
784
    return (!$data) ? array() : $data;
785
}
786
787
function getParsedFolderById($orgId, $folderId, $profiles, &$profileGender, $userId, $filter = true) {
788
789
    $folders = getFoldersByOrganization($orgId, $filter)->
790
                where('id', $folderId)->
791
                find_array();
792
793
    return getDeliveriesFromFolders($folders, $profiles, $profileGender, $userId);
794
}
795
796
function getFoldersById($folderId) {
797
    return parseArray(getFolders()->
798
            where('folder.id', $folderId)->
799
            find_array());
800
}
801
802
function getFolderPersonsByFolderId($folderId) {
803
    return parseArray(getFolderPersons()->
804
            where('folder.id', $folderId)->
805
            find_array());
806
}
807
808
function getProfilesByFolderId($folderId) {
809
    return parseArray(getProfiles()->
810
            where('folder.id', $folderId)->
811
            find_array());
812
}
813
814
function addCompletedEvent($eventId, $personId) {
815
    $completedEvent = ORM::for_table('completed_event')->create();
816
    $completedEvent->set('event_id', $eventId);
817
    $completedEvent->set('person_id', $personId);
818
    $completedEvent->set('completed_date', date('Y-m-d H:i:s'));
819
820
    return $completedEvent->save();
821
}
822
823
function removeCompletedEvent($eventId, $personId) {
824
    return ORM::for_table('completed_event')->
825
            where('event_id', $eventId)->
826
            where('person_id', $personId)->
827
            delete_many();
828
}
829
830
function getActivities($orgId) {
831
    $data = ORM::for_table('activity')->
832
            where('organization_id', $orgId)->
833
            order_by_asc('display_name')->
834
            find_array();
835
836
    return $data;
837
}
838
839
function getEventActivitiesId($eventId) {
840
    return parseArray(ORM::for_table('activity')->
841
            select('activity.id')->
842
            inner_join('activity_event', array('activity_event.activity_id', '=', 'activity.id'))->
843
            where('activity_event.event_id', $eventId)->
844
            find_array());
845
}
846
847
function getAllFoldersByOrganization($orgId, $filter = true) {
848
    $folders = ORM::for_table('folder')->
849
            select('folder.*')->
850
            select('category.display_name', 'category_display_name')->
851
            inner_join('category', array('category.id', '=', 'folder.category_id'))->
852
            where('category.organization_id', $orgId)->
853
            order_by_asc('category.category_left')->
854
            order_by_asc('category.id')->
855
            order_by_asc('order_nr');
856
857
    if ($filter) {
858
        $folders = $folders->where('is_visible', 1);
859
    }
860
    return $folders->find_array();
861
}
862
863
function getParsedFolderTree($orgId) {
864
    $data = getAllFoldersByOrganization($orgId);
865
    $return = array();
866
    $currentData = array();
867
    $currentCategory = null;
868
    $currentCategoryDisplayName = null;
869
    $first = true;
870
871
    foreach($data as $folder) {
872
        if ($first) {
873
            $currentCategory = $folder['category_id'];
874
            $currentCategoryDisplayName = $folder['category_display_name'];
875
            $first = false;
876
        }
877
        if ($currentCategory != $folder['category_id']) {
878
            $return[] = array(
879
                'info' => array('id' => $currentCategory, 'display_name' => $currentCategoryDisplayName),
880
                'data' => $currentData
881
            );
882
            $currentCategory = $folder['category_id'];
883
            $currentCategoryDisplayName = $folder['category_display_name'];
884
            $currentData = array();
885
        }
886
        $currentData[] = $folder;
887
    }
888 View Code Duplication
    if (count($currentData) > 0) {
889
        $return[] = array(
890
            'info' => array('id' => $currentCategory, 'display_name' => $currentCategoryDisplayName),
891
            'data' => $currentData
892
        );
893
    }
894
    return $return;
895
}
896
897
function getEventProfilesId($eventId) {
898
    $data = ORM::for_table('event_profile')->
899
            select('event_profile.profile_id', 'id')->
900
            where('event_profile.event_id', $eventId)->
901
            find_array();
902
903
    return !$data ? false : parseArray($data);
904
}
905
906
function getParsedDeliveriesByOrganization($orgId) {
907
    $data = ORM::for_table('delivery')->
908
            select('delivery.*')->
909
            select('folder.display_name', 'folder_display_name')->
910
            select('category.display_name', 'category_display_name')->
911
            inner_join('folder_delivery', array('folder_delivery.delivery_id', '=', 'delivery.id'))->
912
            inner_join('folder', array('folder.id', '=', 'folder_delivery.folder_id'))->
913
            inner_join('category', array('category.id', '=', 'folder.category_id'))->
914
            where('category.organization_id', $orgId)->
915
            where_null('folder_delivery.snapshot_id')->
916
            order_by_asc('category.category_left')->
917
            order_by_asc('folder.order_nr')->
918
            order_by_asc('folder_delivery.order_nr')->
919
            find_array();
920
921
    $return = array();
922
    $currentData = array();
923
    $currentCategory = null;
924
    $first = true;
925
926
    foreach($data as $delivery) {
927
        $category = $delivery['category_display_name'] . ': ' . $delivery['folder_display_name'];
928
        if ($first) {
929
            $currentCategory = $category;
930
            $first = false;
931
        }
932
        if ($currentCategory != $category) {
933
            $return[] = array(
934
                'info' => array('display_name' => $currentCategory),
935
                'data' => $currentData
936
            );
937
            $currentCategory = $category;
938
            $currentData = array();
939
        }
940
        $currentData[] = $delivery;
941
    }
942 View Code Duplication
    if (count($currentData) > 0) {
943
        $return[] = array(
944
            'info' => array('display_name' => $currentCategory),
945
            'data' => $currentData
946
        );
947
    }
948
    return $return;
949
}
950
951 View Code Duplication
function setEventProfiles($eventId, $profiles) {
952
    ORM::for_table('event_profile')->
953
            where('event_id', $eventId)->
954
            delete_many();
955
956
    $ok = true;
957
    foreach ($profiles as $profile) {
958
        $insert = ORM::for_table('event_profile')->create();
959
        $insert->set('event_id', $eventId);
960
        $insert->set('profile_id', $profile);
961
        $ok = $ok && $insert->save();
962
    }
963
964
    return $ok;
965
}
966
967 View Code Duplication
function setEventActivities($eventId, $activities) {
968
    ORM::for_table('activity_event')->
969
            where('event_id', $eventId)->
970
            delete_many();
971
972
    $ok = true;
973
    foreach ($activities as $activity) {
974
        $insert = ORM::for_table('activity_event')->create();
975
        $insert->set('event_id', $eventId);
976
        $insert->set('activity_id', $activity);
977
        $ok = $ok && $insert->save();
978
    }
979
980
    return $ok;
981
}
982
983 View Code Duplication
function setEventDeliveries($eventId, $deliveries) {
984
    ORM::for_table('event_delivery')->
985
            where('event_id', $eventId)->
986
            delete_many();
987
988
    $ok = true;
989
    foreach ($deliveries as $delivery) {
990
        $insert = ORM::for_table('event_delivery')->create();
991
        $insert->set('event_id', $eventId);
992
        $insert->set('delivery_id', $delivery);
993
        $ok = $ok && $insert->save();
994
    }
995
996
    return $ok;
997
}
998
999
function getItemById($orgId, $id) {
1000
    $data = ORM::for_table('event_profile_delivery_item')->
1001
            select('event_profile_delivery_item.*')->
1002
            select('event.display_name', 'event_display_name')->
1003
            select('event.from_week')->
1004
            select('event.to_week')->
1005
            select('event.force_period')->
1006
            select('event.grace_period')->
1007
            inner_join('event', array('event.id', '=', 'event_profile_delivery_item.event_id'))->
1008
            where('event.organization_id', $orgId)->
1009
            find_one($id);
1010
1011
    return $data;
1012
}
1013
1014 View Code Duplication
function getNextItem($orgId, $itemId, $profileId) {
1015
    $item = getItemById($orgId, $itemId);
1016
1017
    if ($item === false) {
1018
        return false;
1019
    }
1020
1021
    return ORM::for_table('event_profile_delivery_item')->
1022
        where('event_id', $item['event_id'])->
1023
        where('profile_id',  $profileId)->
1024
        where_gt('order_nr', $item['order_nr'])->
1025
        order_by_asc('order_nr')->
1026
        find_one();
1027
}
1028
1029 View Code Duplication
function getPreviousItem($orgId, $itemId, $profileId) {
1030
    $item = getItemById($orgId, $itemId);
1031
1032
    if ($item === false) {
1033
        return false;
1034
    }
1035
1036
    return ORM::for_table('event_profile_delivery_item')->
1037
        where('event_id', $item['event_id'])->
1038
        where('profile_id',  $profileId)->
1039
        where_lt('order_nr', $item['order_nr'])->
1040
        order_by_desc('order_nr')->
1041
        find_one();
1042
}
1043
1044
function getLastItemOrderNr($eventId, $profileId) {
1045
    $data = ORM::for_table('event_profile_delivery_item')->
1046
        where('event_id', $eventId)->
1047
        where('profile_id',  $profileId)->
1048
        order_by_desc('order_nr')->
1049
        find_one();
1050
1051
    if (false === $data) {
1052
        return 0;
1053
    }
1054
    return $data['order_nr'];
1055
}
1056
1057
function getAllActivities($orgId) {
1058
    return parseArray(ORM::for_table('activity')->
1059
        where('organization_id', $orgId)->
1060
        order_by_asc('display_name')->
1061
        find_many());
1062
}
1063
1064
function getAllEventsGroupedByActivity($orgId) {
1065
    $events = ORM::for_table('activity_event')->
1066
        inner_join('event', array('event.id', '=', 'event_id'))->
1067
        where('event.organization_id', $orgId)->
1068
        order_by_asc('event.display_name')->
1069
        find_many();
1070
1071
    $data = parseArrayMix($events, 'activity_id');
1072
1073
    return $data;
1074
}
1075
1076
function deleteEvent($orgId, $id) {
1077
    return ORM::for_table('event')->
1078
        where('organization_id', $orgId)->
1079
        where('event.id', $id)->
1080
        delete_many();
1081
}
1082
1083