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.

manage.php ➔ deleteDocumentById()   B
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 6
nop 2
dl 0
loc 24
rs 8.5125
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('/modificar/:folderid/:id(/:return(/:data1(/:data2(/:data3(/:data4)))))', function ($folderId, $id, $return = null, $data1 = null, $data2 = null, $data3 = null, $data4 = null)
20
        use ($app, $user, $config, $organization, $preferences) {
21
    if (!$user) {
22
        $app->redirect($app->urlFor('login'));
23
    }
24
    $delivery = getDeliveryById($id);
25
    if (false == $delivery) {
26
        $app->redirect($app->urlFor('tree'));
27
    }
28
    $revisions = parseArray(getRevisionsObjectByDelivery($id));
29
    $uploaders = getDeliveryUploadersById($id);
30
31
    $data = array();
32
    $category = array();
33
    $parent = array();
34
35
    $folder = getFolder($organization['id'], $folderId);
36
    $uploadProfiles = parseArray(getPermissionProfiles($folderId, 1));
37
    $managerProfiles = parseArray(getPermissionProfiles($folderId, 0));
38
    $userProfiles = parseArray(getUserProfiles($user['id'], $organization['id'], true));
39
    $profile = getProfile($delivery['profile_id']);
40
41
    if (isset($_SESSION['slim.flash']['last_url'])) {
42
        $app->flash('last_url', $_SESSION['slim.flash']['last_url']);
43
    }
44
45
    if ($delivery['item_id']) {
46
        $deliveredItem = getItemById($organization['id'], $delivery['item_id']);
47
        $deliveredItem['display_name'] = parseVariables($deliveredItem['display_name'], $organization, $user, $profile);
48
    }
49
    else {
50
        $deliveredItem = array();
51
    }
52
53
    $items = parseArray(getFolderProfileDeliveryItems($delivery['profile_id'], $folderId));
54
55
    $isManager = $user['is_admin'];
56
    foreach ($managerProfiles as $upload) {
57
        if (isset($userProfiles[$upload['id']])) {
58
            $isManager = true;
59
            break;
60
        }
61
    }
62
    // si no tiene permisos para editar la entrega, salir
63
    // tiene permiso si:
64
    // - Es administrador o gestor de la carpeta ($isManager)
65
    // - La revisión activa es suya
66
    if ((!$isManager) && ($revisions[$delivery['current_revision_id']]['uploader_person_id'] != $user['id'])) {
67
        $app->redirect($app->urlFor('login'));
68
    }
69
70
    $uploadAs = array();
71
72
    foreach ($uploadProfiles as $item) {
73
        if (null == $item['display_name']) {
74
            $data = parseArray(getSubprofiles($item['id']));
75
            if (count($data)>1) {
76
                foreach($data as $subItem) {
77
                    if (null != $subItem['display_name']) {
78
                        $uploadAs[$subItem['id']] = $subItem;
79
                    }
80
                }
81
            }
82
            else {
83
                $uploadAs[$item['id']] = $item;
84
            }
85
        }
86
        else {
87
            $uploadAs[$item['id']] = $item;
88
        }
89
    }
90
91
    getTree($organization['id'], $app, $folder['category_id'], $category, $parent);
92
93
    if (isset($_POST['save'])) {
94
        $delivery->set('display_name', $_POST['displayname']);
95
        $delivery->set('description', strlen($_POST['description']) > 0 ? $_POST['description'] : null);
96
        if ($isManager) {
97
            if (isset($_POST['creation_year'])) {
98
                $delivery->set('creation_date', $_POST['creation_year'] . '-'. $_POST['creation_month'] . '-' . $_POST['creation_day'] . ' ' .$_POST['creation_hour'] . ':' . $_POST['creation_minute'] . ':00');
99
            }
100
        }
101
        if (isset($_POST['item']) && (($_POST['item'] == 0) || isset($items[$_POST['item']]))) {
102
            $delivery->set('item_id', ($_POST['item'] == 0) ? null : $_POST['item']);
103
        }
104
        if (isset($_POST['profile']) && isset($uploadAs[$_POST['profile']])) {
105
            $delivery->set('profile_id', ($_POST['profile'] == 0) ? null : $_POST['profile']);
106
        }
107
        $delivery->save();
108
        $app->flash('save_ok', 'ok');
109
        $app->redirect($app->request()->getPathInfo());
110
    }
111
112
    if (isset($_POST['default'])) {
113
        $delivery->set('current_revision_id', $_POST['default']);
114
        $delivery->save();
115
        $app->flash('save_ok', 'ok');
116
        $app->redirect($app->request()->getPathInfo());
117
    }
118
119
    if (isset($_POST['remove'])) {
120
        ORM::get_db()->beginTransaction();
121
122
        $revision = getRevisionById($organization['id'], $_POST['remove']);
123
124
        $ok = ($revision !== false);
125
126
        $ok = $ok && deleteDocumentById($revision['original_document_id'], $preferences);
127
        $ok = $ok && $revision->delete();
128
129
        if ($ok) {
130
            $app->flash('save_ok', 'delete');
131
            ORM::get_db()->commit();
132
        }
133
        else {
134
            $app->flash('save_error', 'delete');
135
            ORM::get_db()->rollback();
136
        }
137
        $app->redirect($app->request()->getPathInfo());
138
    }
139
140
    if (isset($_POST['delete'])) {
141
        ORM::get_db()->beginTransaction();
142
        $ok = true;
143
        foreach($revisions as $revision) {
144
            if ($ok) {
145
                $status = deleteDocumentById($revision['original_document_id'], $preferences);
146
                $ok = $ok && $status;
147
            }
148
        }
149
150
        foreach($revisions as $revision) {
151
            $ok = $ok && $revision->delete();
152
        }
153
154
        if ($delivery['profile_id']) {
155
            checkItemUpdateStatus($folderId, $delivery['profile_id']);
156
        }
157
158
        $ok = $ok && $delivery->delete();
159
160
        if ($ok) {
161
            $app->flash('save_ok', 'delete');
162
            ORM::get_db()->commit();
163
        }
164
        else {
165
            $app->flash('save_error', 'delete');
166
            ORM::get_db()->rollback();
167
        }
168
169
        $app->redirect($app->urlFor('tree', array('id' => $category['id'])));
170
    }
171
172
    if (isset($_POST['new']) && isset($_FILES['document']) && isset($_FILES['document']['name'][0]) && is_uploaded_file($_FILES['document']['tmp_name'][0])) {
173
174
        $newRevision = getMaxRevisionNrByDelivery($id) + 1;
175
176
        // añadir nueva revisión en una transacción
177
        ORM::get_db()->beginTransaction();
178
179
        $hash = sha1_file($_FILES['document']['tmp_name'][0]);
180
        $filesize = filesize($_FILES['document']['tmp_name'][0]);
181
        $documentDestination = createDocumentFolder($preferences['upload.folder'], $hash);
182
183
        if (null !== $delivery['item_id']) {
184
            $ext = pathinfo($_FILES['document']['name'][0], PATHINFO_EXTENSION);
185
            $filename = parseVariables($deliveredItem['document_name'], $organization, $user, $profile) . '.' . $ext;
186
        }
187
        else {
188
            $filename = $_FILES['document']['name'][0];
189
        }
190
191
        $documentData = getDocumentDataByHash($hash);
192
        $newData = (false == $documentData);
193
194
        $revision = createRevision($id, $user['id'], $filename, $documentDestination, $hash, $filesize, $newRevision, $_POST['description_new']);
195
196
        $ok = ($revision !== false);
197
198 View Code Duplication
        if ($ok && $newData) {
199
            $ok = move_uploaded_file($_FILES['document']['tmp_name'][0], $preferences['upload.folder'] . $documentDestination);
200
        }
201
202 View Code Duplication
        if ($ok) {
203
            $delivery->set('current_revision_id', $revision['id']);
204
            $delivery->save();
205
            $app->flash('save_ok', 'ok');
206
            ORM::get_db()->commit();
207
        }
208
        else {
209
            if ($newData) {
210
                unlink($documentDestination);
211
            }
212
            $app->flash('save_error', 'error');
213
            ORM::get_db()->rollback();
214
        }
215
216
        $app->redirect($app->request()->getPathInfo());
217
    }
218
219
    $breadcrumb = array(
220
        array('display_name' => 'Árbol', 'target' => $app->urlFor('tree')),
221
        array('display_name' => $parent['display_name'], 'target' => $app->urlFor('tree')),
222
        array('display_name' => $category['display_name'], 'target' => $app->urlFor('tree', array('id' => $category['id']))),
223
        array('display_name' => 'Modificar entrega')
224
    );
225
226 View Code Duplication
    switch ($return) {
227
        case 0:
228
            $lastUrl = $app->urlFor('tree', array('id' => $data1));
229
            break;
230
231
        case 1:
232
            $lastUrl = $app->urlFor('event', array('pid' => $data1, 'aid' => $data2, 'id' => $data3));
233
            break;
234
235
        case 2:
236
            $lastUrl = $app->urlFor('upload', array('id' => $folderId, 'return' => $data1, 'data1' => $data2, 'data2' => $data3, 'data3' => $data4));
237
            break;
238
239
        default:
240
            $lastUrl = $app->urlFor('frontpage');
241
    }
242
243
    $app->render('manage_delivery.html.twig', array(
244
        'navigation' => $breadcrumb, 'search' => false,
245
        'select2' => true,
246
        'url' => $app->request()->getPathInfo(),
247
        'category' => $category,
248
        'folder' => $folder,
249
        'item' => $deliveredItem,
250
        'items' => $items,
251
        'delivery' => $delivery,
252
        'revisions' => $revisions,
253
        'uploaders' => $uploaders,
254
        'is_manager' => $isManager,
255
        'base' => $config['calendar.base_week'],
256
        'upload_profiles' => $uploadProfiles,
257
        'manager_profiles' => $managerProfiles,
258
        'user_profiles' => $userProfiles,
259
        'upload_as' => $uploadAs,
260
        'last_url' => $lastUrl,
261
        'data' => $data));
262
263
})->name('modify')->via('GET', 'POST');
264
265
$app->map('/revision/:folderid/:id', function ($folderId, $id) use ($app, $user, $config, $organization, $preferences) {
266
    if (!$user['is_admin']) {
267
        $app->redirect($app->urlFor('login'));
268
    }
269
270
    $revision = getRevisionById($organization['id'], $id);
271
272
    if (false == $revision) {
273
        $app->redirect($app->urlFor('tree'));
274
    }
275
    $document = getDocumentById($revision['original_document_id']);
276
    $delivery = getDeliveryById($revision['delivery_id']);
277
    $revision_nrs = getRevisionNrArrayByDelivery($revision['delivery_id'], 100, $revision['revision_nr']);
278
    $persons = getActivePersonsByOrganization($organization['id']);
279
280
    $data = array();
281
    $category = array();
282
    $parent = array();
283
284
    $folder = getFolder($organization['id'], $folderId);
285
286
    getTree($organization['id'], $app, $folder['category_id'], $category, $parent);
287
288
    if (isset($_SESSION['slim.flash']['last_url'])) {
289
        $app->flash('last_url', $_SESSION['slim.flash']['last_url']);
290
    }
291
292
    if (isset($_POST['save'])) {
293
        $document->set('download_filename', $_POST['downloadname']);
294
        $document->save();
295
        $revision->set('revision_nr', $_POST['revisionnr']);
296
        $revision->set('uploader_person_id', $_POST['uploader']);
297
        $revision->set('upload_date', $_POST['upload_year'] . '-'. $_POST['upload_month'] . '-' . $_POST['upload_day'] . ' ' .$_POST['upload_hour'] . ':' . $_POST['upload_minute'] . ':00');
298
        $revision->save();
299
        $app->flash('save_ok', 'ok');
300
301
        $app->redirect($app->request()->getPathInfo());
302
    }
303
304 View Code Duplication
    if (isset($_POST['delete'])) {
305
        ORM::get_db()->beginTransaction();
306
        $ok = deleteDocumentById($revision['original_document_id'], $preferences);
307
        $ok = $ok && $revision->delete();
308
309
        if ($ok) {
310
            $app->flash('save_ok', 'delete');
311
            ORM::get_db()->commit();
312
        }
313
        else {
314
            $app->flash('save_error', 'delete');
315
            ORM::get_db()->rollback();
316
        }
317
318
        $app->redirect($app->urlFor('modify', array('id' => $delivery['id'], 'folderid' => $folder['id'])));
319
    }
320
321
    if (isset($_POST['replace']) && isset($_FILES['document']) && isset($_FILES['document']['name'][0]) && is_uploaded_file($_FILES['document']['tmp_name'][0])) {
322
323
        // reemplazar revisión en una transacción
324
        ORM::get_db()->beginTransaction();
325
326
        $hash = sha1_file($_FILES['document']['tmp_name'][0]);
327
        $filesize = filesize($_FILES['document']['tmp_name'][0]);
328
        $documentDestination = createDocumentFolder($preferences['upload.folder'], $hash);
329
        $filename = $_FILES['document']['name'][0];
330
331
        $documentData = getDocumentDataByHash($hash);
332
        $newData = (false == $documentData);
333
334
        if ($newData) {
335
            $document = createDocument($revision['id'], $filename, $hash, $documentDestination, $filesize);
336
        }
337
        else {
338
            $document = getDocumentByHash($hash);
339
        }
340
341
        $ok = ($document !== false);
342
343 View Code Duplication
        if ($ok && $newData) {
344
            $ok = move_uploaded_file($_FILES['document']['tmp_name'][0], $preferences['upload.folder'] . $documentDestination);
345
        }
346
347 View Code Duplication
        if ($ok) {
348
            $revision->set('original_document_id', $document['id']);
349
            $revision->save();
350
            $app->flash('save_ok', 'ok');
351
            ORM::get_db()->commit();
352
        }
353
        else {
354
            if ($newData) {
355
                unlink($documentDestination);
356
            }
357
            $app->flash('save_error', 'error');
358
            ORM::get_db()->rollback();
359
        }
360
361
        $app->redirect($app->urlFor('tree', array('id' => $category['id'])));
362
    }
363
364
    $breadcrumb = array(
365
        array('display_name' => 'Árbol', 'target' => $app->urlFor('tree')),
366
        array('display_name' => $parent['display_name'], 'target' => $app->urlFor('tree')),
367
        array('display_name' => $category['display_name'], 'target' => $app->urlFor('tree', array('id' => $category['id']))),
368
        array('display_name' => 'Modificar entrega')
369
    );
370
371
    $app->render('manage_revision.html.twig', array(
372
        'navigation' => $breadcrumb, 'search' => false,
373
        'select2' => true,
374
        'url' => $app->request()->getPathInfo(),
375
        'category' => $category,
376
        'folder' => $folder,
377
        'revision' => $revision,
378
        'document' => $document,
379
        'delivery' => $delivery,
380
        'persons' => $persons,
381
        'revisions' => $revision_nrs,
382
        'data' => $data));
383
384
})->name('revision')->via('GET', 'POST');
385
386
$app->map('/historial/archivar/masivo', function () use ($app, $user, $config, $organization, $preferences) {
387
388
    if ((!$user) || (!$user['is_admin'])) {
389
        $app->redirect($app->urlFor('login'));
390
    }
391
392 View Code Duplication
    if ((isset($_POST['archive']) && isset($_POST['displayname']) && strlen($_POST['displayname'])) ||
393
        (isset($_POST['archive_old']) && isset($_POST['snapshot']))) {
394
395
        // realizar los cambios en una transacción
396
        ORM::get_db()->beginTransaction();
397
398
        if (isset($_POST['archive'])) {
399
            // crear snapshot
400
            $snapshot = ORM::for_table('snapshot')->create();
401
            $snapshot->set('organization_id', $organization['id']);
402
            $snapshot->set('display_name', $_POST['displayname']);
403
            $snapshot->set('order_nr', getLastSnapshotOrder($organization['id']) + 1000);
404
            $ok = $snapshot->save();
405
        }
406
        else {
407
            // recuperar snapshot
408
            $snapshot = ORM::for_table('snapshot')->
409
                where('organization_id',  $organization['id'])->
410
                where('id', $_POST['snapshot'])->
411
                find_one();
412
413
            if (!$snapshot) {
414
                $app->redirect($app->urlFor('login'));
415
            }
416
417
            $ok = true;
418
        }
419
420
        // archivar carpetas
421
        $ok = $ok && archiveFolders($organization['id'], $snapshot['id'], $_POST['item']);
422
423
        // borrar eventos completados
424
        $ok = $ok && deleteAllCompletedEvents($organization['id']);
425
426
        if ($ok) {
427
            $app->flash('save_ok', 'ok');
428
            ORM::get_db()->commit();
429
430
            $app->redirect($app->urlFor('tree'));
431
        }
432
        else {
433
            $app->flash('save_error', 'ok');
434
            ORM::get_db()->rollback();
435
        }
436
    }
437
438
    $items = getAutoCleaningFolders($organization['id']);
439
    $snapshots = getSnapshots($organization['id']);
440
441
    // generar barra de navegación
442
    $breadcrumb = array(
443
        array('display_name' => 'Historial', 'target' => $app->urlFor('managesnapshots')),
444
        array('display_name' => 'Archivado masivo de carpetas en el historial')
445
    );
446
447
        // lanzar plantilla
448
    $app->render('create_snapshot.html.twig', array(
449
        'select2' => true,
450
        'navigation' => $breadcrumb,
451
        'snapshots' => $snapshots,
452
        'items' => $items,
453
        'url' => $app->request()->getPathInfo()
454
    ));
455
456
})->name('addsnapshot')->via('GET', 'POST');
457
458
$app->map('/historial/archivar/:id(/:return(/:data1(/:data2(/:data3(/:data4)))))', function ($id, $return = null, $data1 = null, $data2 = null, $data3 = null, $data4 = null) use ($app, $user, $config, $organization, $preferences) {
459
460
    if ((!$user) || (!$user['is_admin'])) {
461
        $app->redirect($app->urlFor('login'));
462
    }
463
464 View Code Duplication
    switch ($return) {
465
        case 0:
466
            $lastUrl = $app->urlFor('tree', array('id' => $data1));
467
            break;
468
469
        case 1:
470
            $lastUrl = $app->urlFor('event', array('pid' => $data1, 'aid' => $data2, 'id' => $data3));
471
            break;
472
473
        case 2:
474
            $lastUrl = $app->urlFor('upload', array('id' => $id, 'return' => $data1, 'data1' => $data2, 'data2' => $data3, 'data3' => $data4));
475
            break;
476
477
        default:
478
            $lastUrl = $app->urlFor('frontpage');
479
    }
480
481 View Code Duplication
    if ((isset($_POST['archive']) && isset($_POST['displayname']) && strlen($_POST['displayname'])) ||
482
        (isset($_POST['archive_old']) && isset($_POST['snapshot']))) {
483
484
        // realizar los cambios en una transacción
485
        ORM::get_db()->beginTransaction();
486
487
        if (isset($_POST['archive'])) {
488
            // crear snapshot
489
            $snapshot = ORM::for_table('snapshot')->create();
490
            $snapshot->set('organization_id', $organization['id']);
491
            $snapshot->set('display_name', $_POST['displayname']);
492
            $snapshot->set('order_nr', getLastSnapshotOrder($organization['id']) + 1000);
493
            $ok = $snapshot->save();
494
        }
495
        else {
496
            // recuperar snapshot
497
            $snapshot = ORM::for_table('snapshot')->
498
            where('organization_id',  $organization['id'])->
499
            where('id', $_POST['snapshot'])->
500
            find_one();
501
502
            if (!$snapshot) {
503
                $app->redirect($app->urlFor('login'));
504
            }
505
506
            $ok = true;
507
        }
508
509
        // archivar carpetas
510
        $ok = $ok && archiveDeliveriesFromFolder($organization['id'], $snapshot['id'], $id, $_POST['item']);
511
512
        // borrar eventos completados
513
        $ok = $ok && deleteCompletedEventsForFolder($organization['id'], $id);
514
515
        if ($ok) {
516
            $app->flash('save_ok', 'ok');
517
            ORM::get_db()->commit();
518
519
            $app->redirect($lastUrl);
520
        }
521
        else {
522
            $app->flash('save_error', 'ok');
523
            ORM::get_db()->rollback();
524
        }
525
    }
526
527
    $items = getDeliveriesFromFolderNotInSnapshot($organization['id'], $id);
528
    $snapshots = getSnapshots($organization['id']);
529
    $folder = getFolderById($organization['id'], $id);
530
531
    // generar barra de navegación
532
    $breadcrumb = array(
533
        array('display_name' => 'Historial', 'target' => $app->urlFor('managesnapshots')),
534
        array('display_name' => 'Archivado de una carpeta en historial'),
535
        array('display_name' => $folder['display_name'])
536
    );
537
538
    // lanzar plantilla
539
    $app->render('create_folder_snapshot.html.twig', array(
540
        'select2' => true,
541
        'navigation' => $breadcrumb,
542
        'snapshots' => $snapshots,
543
        'items' => $items,
544
        'folder' => $folder,
545
        'last_url' => $lastUrl,
546
        'url' => $app->request()->getPathInfo()
547
    ));
548
549
})->name('addfoldersnapshot')->via('GET', 'POST');
550
551
$app->map('/historial/listar', function () use ($app, $user, $config, $organization, $preferences) {
552
    if ((!$user) || (!$user['is_admin'])) {
553
        $app->redirect($app->urlFor('login'));
554
    }
555
556 View Code Duplication
    if (isset($_POST['up']) || isset($_POST['down'])) {
557
        if (isset($_POST['up'])) {
558
            $snap1 = getSnapshotById($organization['id'], $_POST['up']);
559
            $snap2 = getNextSnapshot($organization['id'], $_POST['up']);
560
        }
561
        else {
562
            $snap1 = getSnapshotById($organization['id'], $_POST['down']);
563
            $snap2 = getPreviousSnapshot($organization['id'], $_POST['down']);
564
        }
565
        if (!$snap1 || !$snap2) {
566
            $app->redirect($app->urlFor('login'));
567
        }
568
        $order_nr = $snap1['order_nr'];
569
        $snap1->set('order_nr', $snap2['order_nr'])->save();
570
        $snap2->set('order_nr', $order_nr)->save();
571
    }
572
573
    if (isset($_POST['delete'])) {
574
575
        // realizar los cambios en una transacción
576
        ORM::get_db()->beginTransaction();
577
578
        $ok = deleteSnapshots($organization['id'], $_POST['snapshot']);
579
580
        if ($ok) {
581
            $app->flash('save_ok', 'delete');
582
            ORM::get_db()->commit();
583
        }
584
        else {
585
            $app->flash('save_error', 'delete');
586
            ORM::get_db()->rollback();
587
        }
588
    }
589
590
    $snapshots = getSnapshots($organization['id']);
591
592
    // generar barra de navegación
593
    $breadcrumb = array(
594
        array('display_name' => 'Historial', 'target' => $app->urlFor('managesnapshots')),
595
        array('display_name' => 'Listado de archivos', 'target' => $app->urlFor('managesnapshots'))
596
    );
597
598
    // lanzar plantilla
599
    $app->render('manage_snapshot_list.html.twig', array(
600
        'select2' => true,
601
        'navigation' => $breadcrumb,
602
        'snapshots' => $snapshots,
603
        'url' => $app->request()->getPathInfo()
604
    ));
605
})->name('managesnapshots')->via('GET', 'POST');
606
607
$app->map('/historial/archivo/:id', function ($id) use ($app, $user, $config, $organization, $preferences) {
608
    if ((!$user) || (!$user['is_admin'])) {
609
        $app->redirect($app->urlFor('login'));
610
    }
611
612
    $snapshot = getSnapshotById($organization['id'], $id);
613
614
    if (isset($_POST['save'])) {
615
616
        $snapshot->set('display_name', $_POST['displayname']);
617
618
        $ok = $snapshot->save();
619
620
        if ($ok) {
621
            $app->flash('save_ok', 'ok');
622
            $app->redirect($app->urlFor('managesnapshots'));
623
        }
624
        else {
625
            $app->flash('save_error', 'ok');
626
        }
627
    }
628
629
    // generar barra de navegación
630
    $breadcrumb = array(
631
        array('display_name' => 'Historial', 'target' => $app->urlFor('managesnapshots')),
632
        array('display_name' => 'Listado de archivos', 'target' => $app->urlFor('managesnapshots')),
633
        array('display_name' => $snapshot['display_name'])
634
    );
635
636
    // lanzar plantilla
637
    $app->render('manage_snapshot.html.twig', array(
638
        'select2' => true,
639
        'navigation' => $breadcrumb,
640
        'snapshot' => $snapshot,
641
        'url' => $app->request()->getPathInfo()
642
    ));
643
})->name('managesnapshot')->via('GET', 'POST');
644
645
function getDeliveryUploadersById($deliveryId) {
646
    return parseArray(ORM::for_table('person')->
647
        select('person.*')->
648
        distinct()->
649
        inner_join('revision', array('revision.uploader_person_id', '=', 'person.id'))->
650
        inner_join('delivery', array('delivery.id', '=', 'revision.delivery_id'))->
651
        where('delivery.id', $deliveryId)->
652
        find_array());
653
}
654
655
function getDeliveryById($deliveryId) {
656
    $data = ORM::for_table('delivery')->
657
            find_one($deliveryId);
658
659
    return $data;
660
}
661
662
function getRevisionById($orgId, $revisionId) {
663
    $data = ORM::for_table('revision')->
664
            select('revision.*')->
665
            inner_join('delivery', array('delivery.id', '=', 'revision.delivery_id'))->
666
            inner_join('folder_delivery', array('delivery.id', '=', 'folder_delivery.delivery_id'))->
667
            inner_join('folder', array('folder.id', '=', 'folder_delivery.folder_id'))->
668
            inner_join('category', array('category.id', '=', 'folder.category_id'))->
669
            where('category.organization_id', $orgId)->
670
            find_one($revisionId);
671
672
    return $data;
673
}
674
675
function getDocumentById($documentId) {
676
    $data = ORM::for_table('document')->
677
            find_one($documentId);
678
679
    return $data;
680
}
681
682
function getActivePersonsByOrganization($organizationId) {
683
    $data = ORM::for_table('person')->
684
            select('person.id')->
685
            select('person.user_name')->
686
            select('person.display_name')->
687
            inner_join('person_organization', array('person.id', '=', 'person_organization.person_id'))->
688
            where('person_organization.organization_id', $organizationId)->
689
            where('person_organization.is_active', 1)->
690
            order_by_asc('person.display_name')->
691
            find_many();
692
693
    return $data;
694
}
695
696
function getRevisionsObjectByDelivery($deliveryId) {
697
    return ORM::for_table('revision')->
698
            select('revision.*')->
699
            select('document.download_filename')->
700
            where('revision.delivery_id', $deliveryId)->
701
            inner_join('document', array('document.id', '=', 'revision.original_document_id'))->
702
            order_by_desc('upload_date')->
703
            find_many();
704
}
705
706
function deleteDocumentById($docId, $preferences) {
707
    // comprobar si existen otros documentos con la misma información
708
    $document = ORM::for_table('document')->find_one($docId);
709
    if (!$document) {
710
        return false;
711
    }
712
713
    if (ORM::for_table('document')->where('document_data_id', $document['document_data_id'])->count() == 1) {
714
        // solamente hay un documento con esta información... hay que borrarlo
715
        $document_data = ORM::for_table('document_data')->find_one($document['document_data_id']);
716
717
        // borrar físicamente del sistema de archivos si existe
718
        if (strlen($document_data['download_path'])>0) {
719
            unlink($preferences['upload.folder'] . $document_data['download_path']);
720
        }
721
        $ok = $document->delete();
722
        $ok = $ok && $document_data->delete();
723
        return $ok;
724
    }
725
    else {
726
        $ok = $document->delete();
727
        return $ok;
728
    }
729
}
730
731
function getMaxRevisionNrByDelivery($delId) {
732
    return ORM::for_table('revision')->
733
            where('delivery_id', $delId)->
734
            max('revision_nr');
735
}
736
737
function getRevisionNrArrayByDelivery($delId, $limit, $currentNr) {
738
    $data = range(0, getMaxRevisionNrByDelivery($delId)+$limit);
739
    $existing = ORM::for_table('revision')->
740
            select('revision.revision_nr')->
741
            where('delivery_id', $delId)->
742
            where_not_equal('revision_nr', $currentNr)->find_array();
743
    $nrs = array();
744
    foreach($existing as $nr) {
745
        $nrs[] = $nr['revision_nr'];
746
    }
747
    return array_diff($data, $nrs);
748
}
749
750
function getLastSnapshotOrder($orgId) {
751
    return ORM::for_table('snapshot')->
752
        where('organization_id', $orgId)->
753
        max('order_nr');
754
}
755
756 View Code Duplication
function getAutoCleaningFolders($orgId) {
757
    $data = ORM::for_table('folder_delivery')->
758
        select('folder.*')->
759
        select('category.display_name', 'category_display_name')->
760
        select_expr('COUNT(*)', 'total')->
761
        inner_join('folder', array('folder_delivery.folder_id', '=', 'folder.id'))->
762
        inner_join('category', array('folder.category_id', '=', 'category.id'))->
763
        where('category.organization_id', $orgId)->
764
        where('folder.auto_clean', 1)->
765
        where_null('folder_delivery.snapshot_id')->
766
        group_by('folder_delivery.folder_id')->
767
        order_by_asc('folder.category_id')->
768
        find_array();
769
770
    return $data;
771
}
772
773
function archiveFolders($orgId, $snapId, $folders) {
774
775
    $ok = ORM::for_table('folder')->
776
        select('folder.*')->
777
        inner_join('category', array('category.id', '=', 'category_id'))->
778
        where_in('folder.id', $folders)->
779
        where('category.organization_id', $orgId)->
780
        find_result_set()->
781
        set('has_snapshot', 1)->
782
        save();
783
784
    $ok = $ok && ORM::for_table('delivery')->
785
        inner_join('folder_delivery', array('delivery.id', '=', 'delivery_id'))->
786
        where_in('folder_id', $folders)->
787
        where_null('snapshot_id')->
788
        find_result_set()->
789
        set('item_id', null)->
790
        save();
791
792
    $ok = $ok && ORM::for_table('folder_delivery')->
793
        use_id_column(array('folder_id', 'delivery_id'))->
794
        where_in('folder_id', $folders)->
795
        where_null('snapshot_id')->
796
        find_result_set()->
797
        set('snapshot_id', $snapId)->
798
        save();
799
800
    return $ok;
801
}
802
803
function archiveDeliveriesFromFolder($orgId, $snapId, $folderId, $deliveries) {
804
805
    $ok = ORM::for_table('folder')->
806
        select('folder.*')->
807
        inner_join('category', array('category.id', '=', 'category_id'))->
808
        where('folder.id', $folderId)->
809
        where('category.organization_id', $orgId)->
810
        find_result_set()->
811
        set('has_snapshot', 1)->
812
        save();
813
814
    $ok = $ok && ORM::for_table('delivery')->
815
        inner_join('folder_delivery', array('delivery.id', '=', 'delivery_id'))->
816
        where('folder_delivery.folder_id', $folderId)->
817
        where_null('snapshot_id')->
818
        where_in('delivery.id', $deliveries)->
819
        find_result_set()->
820
        set('item_id', null)->
821
        save();
822
823
    $ok = $ok && ORM::for_table('folder_delivery')->
824
        use_id_column(array('folder_id', 'delivery_id'))->
825
        where('folder_id', $folderId)->
826
        where_in('delivery_id', $deliveries)->
827
        where_null('snapshot_id')->
828
        find_result_set()->
829
        set('snapshot_id', $snapId)->
830
        save();
831
832
    return $ok;
833
}
834
835
function deleteEventsIn($events) {
836
    $ok = true;
837
    if (count($events) > 0) {
838
        $ok = ORM::for_table('completed_event')->
839
        where_in('event_id', $events)->
840
        delete_many();
841
    }
842
843
    return $ok;
844
}
845
846 View Code Duplication
function deleteCompletedEventsForFolder($orgId, $folderId) {
847
    $events = ORM::for_table('event')->
848
        select('event.id')->
849
        where('event.organization_id', $orgId)->
850
        where('event.folder_id', $folderId)->
851
        where('event.is_automatic', 1)->
852
        find_array();
853
854
    $events = array_column($events, 'id');
855
856
    $ok = deleteEventsIn($events);
857
858
    return $ok;
859
}
860
861
function deleteAllCompletedEvents($orgId) {
862
    $events = ORM::for_table('event')->
863
        select('event.id')->
864
        where('event.organization_id', $orgId)->
865
        find_array();
866
867
    $events = array_column($events, 'id');
868
869
    $ok = deleteEventsIn($events);
870
871
    return $ok;
872
}
873
874
function getSnapshots($orgId) {
875
    return ORM::for_table('folder_delivery')->
876
        select('snapshot.*')->
877
        select_expr('COUNT(*)', 'total')->
878
        inner_join('snapshot', array('snapshot.id', '=', 'snapshot_id'))->
879
        where('snapshot.organization_id', $orgId)->
880
        having_not_null('snapshot_id')->
881
        order_by_desc('order_nr')->
882
        group_by('snapshot_id')->
883
        find_array();
884
}
885
886
function getDeliveriesFromFolderNotInSnapshot($orgId, $folderId) {
887
    return ORM::for_table('delivery')->
888
        select('delivery.*')->
889
        inner_join('folder_delivery', array('delivery.id', '=', 'delivery_id'))->
890
        inner_join('folder', array('folder.id', '=', 'folder_delivery.folder_id'))->
891
        inner_join('category', array('folder.category_id', '=', 'category.id'))->
892
        where('category.organization_id', $orgId)->
893
        where('folder_delivery.folder_id', $folderId)->
894
        where_null('snapshot_id')->
895
        find_array();
896
}
897
898
function getSnapshotById($orgId, $snapId) {
899
    return ORM::for_table('snapshot')->
900
        where('organization_id', $orgId)->
901
        where('id', $snapId)->
902
        find_one();
903
}
904
905
function getNextSnapshot($orgId, $snapId) {
906
    $snap = getSnapshotById($orgId, $snapId);
907
908
    return ORM::for_table('snapshot')->
909
        where('organization_id', $orgId)->
910
        where_gt('order_nr', $snap['order_nr'])->
911
        order_by_asc('order_nr')->
912
        find_one();
913
}
914
915
function getPreviousSnapshot($orgId, $snapId) {
916
    $snap = getSnapshotById($orgId, $snapId);
917
918
    return ORM::for_table('snapshot')->
919
        where('organization_id', $orgId)->
920
        where_lt('order_nr', $snap['order_nr'])->
921
        order_by_desc('order_nr')->
922
        find_one();
923
}
924
925
function deleteSnapshots($orgId, $snapshots) {
926
    return ORM::for_table('snapshot')->
927
        where('organization_id', $orgId)->
928
        where_id_in($snapshots)->
929
        delete_many();
930
}
931