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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
<?php
namespace ProcessMaker\Project;

use BasePeer;
use BpmnActivity as Activity;
use BpmnArtifact as Artifact;
use BpmnActivityPeer as ActivityPeer;
use BpmnArtifactPeer as ArtifactPeer;
use BpmnBound as Bound;
use BpmnBoundPeer as BoundPeer;
use BpmnDiagram as Diagram;
use BpmnDiagramPeer as DiagramPeer;
use BpmnEvent as Event;
use BpmnEventPeer as EventPeer;
use BpmnFlow as Flow;
use BpmnFlowPeer as FlowPeer;
use BpmnGateway as Gateway;
use BpmnGatewayPeer as GatewayPeer;
use BpmnLaneset as Laneset;
use BpmnLanesetPeer as LanesetPeer;
use BpmnLane as Lane;
use BpmnLanePeer as LanePeer;
use BpmnParticipant as Participant;
use BpmnParticipantPeer as ParticipantPeer;
use BpmnProject as Project;
use BpmnProcess as Process;
use BpmnProjectPeer as ProjectPeer;
use BpmnProcessPeer as ProcessPeer;
use Criteria as Criteria;
use Exception;
use G;
use ResultSet as ResultSet;
use ProcessMaker\Util\Common;
use ProcessMaker\Exception\ProjectNotFound;
use ProcessMaker\Project\Adapter\BpmnWorkflow;
use Bootstrap;

/**
 * Class Bpmn
 *
 * @package ProcessMaker\Project
 * @author Erik Amaru Ortiz <aortiz.erik@gmail.com, erik@colosa.com>
 */
class Bpmn extends Handler
{
    /**
     * @var \BpmnProject
     */
    protected $project;

    protected $prjUid;

    /**
     * @var \BpmnProcess
     */
    protected $process;

    /**
     * @var \BpmnDiagram
     */
    protected $diagram;

    protected static $excludeFields = array(
        "activity" => array(
            "PRJ_UID",
            "PRO_UID",
            "BOU_ELEMENT_TYPE",
            "BOU_REL_POSITION",
            "BOU_SIZE_IDENTICAL",
            "DIA_UID",
            "BOU_UID",
            "ELEMENT_UID"
        ),
        "event" => array(
            "PRJ_UID",
            "PRO_UID",
            "BOU_ELEMENT_TYPE",
            "BOU_REL_POSITION",
            "BOU_SIZE_IDENTICAL",
            "DIA_UID",
            "BOU_UID",
            "ELEMENT_UID",
            "EVN_ATTACHED_TO",
            "EVN_CONDITION"
        ),
        "gateway" => array(
            "BOU_ELEMENT_TYPE",
            "BOU_REL_POSITION",
            "BOU_SIZE_IDENTICAL",
            "BOU_UID",
            "DIA_UID",
            "ELEMENT_UID",
            "PRJ_UID",
            "PRO_UID"
        ),
        "artifact" => array(
            "PRJ_UID",
            "PRO_UID",
            "BOU_ELEMENT_TYPE",
            "BOU_REL_POSITION",
            "BOU_SIZE_IDENTICAL",
            "DIA_UID",
            "BOU_UID",
            "ELEMENT_UID"
        ),
        "flow" => array(
            "PRJ_UID",
            "DIA_UID",
            "FLO_ELEMENT_DEST_PORT",
            "FLO_ELEMENT_ORIGIN_PORT"
        ),
        "data" => array(
            "PRJ_UID"
        ),
        "participant" => array(
            "PRJ_UID"
        ),
        "laneset" => array(
            "BOU_ELEMENT_TYPE",
            "BOU_SIZE_IDENTICAL",
            "BOU_UID"
        ),
        "lane" => array(
            "BOU_ELEMENT_TYPE",
            "BOU_SIZE_IDENTICAL",
            "BOU_UID"
        )
    );

    private $arrayElementOriginChecked = array();
    protected $contextLog = array();

    public function __construct($data = null)
    {
        if (! is_null($data)) {
            $this->create($data);
        }
        //Define the variables for the logging
        $info = array(
            'ip' => G::getIpAddress(),
            'workspace' => (!empty(config("system.workspace")))? config("system.workspace") : "Undefined Workspace"
        );
        $this->setContextLog($info);
    }

    /**
     * Get the $contextLog value.
     *
     * @return string
     */
    public function getContextLog()
    {
        return $this->contextLog;
    }

    /**
     * Set the value of $contextLog.
     *
     * @param array $k
     * @return void
     */
    public function setContextLog($k)
    {
        $this->contextLog = array_merge($this->contextLog, $k);
    }

    /**
     * Bulk actions
     * We will have actions in many projects
     *
     * @param array $data
     * @return array $result, related to actions send
     */
    public static function doBulk($data)
    {
        //We will review the data format
        if (!is_array($data)) {
            $isJson = is_string($data) && is_array(G::json_decode($data, true));
            if ($isJson) {
                $data = G::json_decode($data, true);
            } else {
                return;
            }
        }
        //We get the action and execute
        $response = array();
        if (isset($data['data'])) {
            foreach ($data['data'] as $key => $val) {
                if (isset($val['action'])) {
                    switch ($val['action']) {
                        case 'delete':
                            $response[] = array(
                                'action' => $val['action'],
                                'data'=> self::doBulkDelete($val['data'])
                            );
                            break;
                        default:
                            $response[] = array(
                                'action' => $val['action'],
                                'title' => 'Unknown action',
                                'status' => '400',
                                'detail' => "Unknown action.",
                                'result' => false
                            );
                        //todo, we can add more bulk actions
                    }
                }
            }
        }
        $result['data'] = $response;

        return $result;
    }

    /**
     * Bulk delete
     * We will delete many projects in bulk
     *
     * @param array $data, array of projectUid
     * @return array $response, information about the action with the projectUid
    */
    public static function doBulkDelete($data)
    {
        //We reviewed the action in all projectUid
        $response = array();
        foreach ($data as $key => $val) {
            //Review if the type is "prj_uid"
            if (isset($val['prj_uid']) && !empty($val['prj_uid']) ) {
                //The project exist?
                if (!Bpmn::exists($val['prj_uid'])) {
                    $response[] = array(
                        'type' => $val['type'],
                        'prj_uid' => $val['prj_uid'],
                        'title' => 'Not found',
                        'token' => strtotime("now"),
                        'status' => '404',
                        'detail' => "The row {$val['prj_uid']} in table Process doesn't exist!.",
                        'result' => false
                    );
                    continue;
                }
                //The project has cases?
                $oBpmnWf = BpmnWorkflow::load($val['prj_uid']);
                if (!$oBpmnWf->canRemove()) {
                    $response[] = array(
                        'type' => $val['type'],
                        'prj_uid' => $val['prj_uid'],
                        'title' => 'Unable to delete project',
                        'token' => strtotime("now"),
                        'status' => '403',
                        'detail' => "Project with prj_uid: {$val['prj_uid']} can not be deleted, it has started cases.",
                        'result' => false

                    );
                    continue;
                }
                //We will to remove
                $oBpmnWf = BpmnWorkflow::load($val['prj_uid']);
                $oBpmnWf->remove();
                $response[] = array(
                    'type' => $val['type'],
                    'prj_uid' => $val['prj_uid'],
                    'status' => '200',
                    'result' => true
                );
            } else {
                //Is not defined the "prj_uid"
                $response[] = array(
                    'type' => $val['type'],
                    'title' => 'Unknown field',
                    'token' => strtotime("now"),
                    'status' => '400',
                    'detail' => "Unknown field.",
                    'result' => false

                );
            }
        }
        $me = new self();
        $me->setContextLog($response);
        $me->syslog(
            'DoBulkDelete',
            200,
            'Do bulk delete',
            $me->getContextLog()
        );

        return $response;
    }

    public function exists($projectUid)
    {
        try {
            $obj = ProjectPeer::retrieveByPK($projectUid);

            return (!is_null($obj))? true : false;
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());

            throw $e;
        }
    }

    public static function load($prjUid)
    {
        $me = new self();
        $project = ProjectPeer::retrieveByPK($prjUid);

        if (!is_object($project)) {
            throw new ProjectNotFound($me, $prjUid);
        }

        $me->project = $project;
        $me->prjUid = $me->project->getPrjUid();

        return $me;
    }

    /**
     * @param array| $data array attributes to create and initialize a BpmnProject
     */
    public function create($data)
    {
        // setting defaults
        $data['PRJ_UID'] = array_key_exists('PRJ_UID', $data) ? $data['PRJ_UID'] : Common::generateUID();

        self::log("Create Project with data: ", $data);
        $this->project = new Project();
        $this->project->fromArray($data, BasePeer::TYPE_FIELDNAME);
        $this->project->setPrjCreateDate(date("Y-m-d H:i:s"));
        $this->project->save();

        $this->prjUid = $this->project->getPrjUid();
        self::log("Create Project Success!");
    }

    public function update($data)
    {
        if (isset($data["PRJ_NAME"])) {
            $process = new \ProcessMaker\BusinessModel\Process();

            $process->throwExceptionIfExistsTitle($data["PRJ_NAME"], strtolower("PRJ_NAME"), $this->prjUid);
        }

        if (array_key_exists("PRJ_CREATE_DATE", $data) && empty($data["PRJ_CREATE_DATE"])) {
            unset($data["PRJ_UPDATE_DATE"]);
        }

        if (array_key_exists("PRJ_UPDATE_DATE", $data)) {
            unset($data["PRJ_UPDATE_DATE"]);
        }

        $this->project->fromArray($data, BasePeer::TYPE_FIELDNAME);
        $this->project->setPrjUpdateDate(date("Y-m-d H:i:s"));
        $this->project->save();

        if (isset($data["PRJ_NAME"])) {
            $this->updateDiagram(array("DIA_NAME" => $data["PRJ_NAME"]));
        }
    }

    public function remove($force = false)
    {
        /*
         * 1. Remove Diagram related objects
         * 2. Remove Project related objects
         */

        if (! $force && ! $this->canRemove()) {
            throw new \Exception("Project with prj_uid: {$this->getUid()} can not be deleted, it has started cases.");
        }

        self::log("Remove Project With Uid: {$this->prjUid}");
        foreach ($this->getEvents() as $event) {
            $this->removeEvent($event["EVN_UID"]);
        }
        foreach ($this->getActivities() as $activity) {
            $this->removeActivity($activity["ACT_UID"]);
        }
        foreach ($this->getGateways() as $gateway) {
            $this->removeGateway($gateway["GAT_UID"]);
        }
        foreach ($this->getFlows() as $flow) {
            $this->removeFlow($flow["FLO_UID"]);
        }
        foreach ($this->getArtifacts() as $artifacts) {
            $this->removeArtifact($artifacts["ART_UID"]);
        }
        foreach ($this->getDataCollection() as $bpmnData) {
            $this->removeData($bpmnData["DAT_UID"]);
        }
        foreach ($this->getParticipants() as $participant) {
            $this->removeParticipant($participant["PAR_UID"]);
        }
        foreach ($this->getLanes() as $lane) {
            $this->removeLane($lane["LAN_UID"]);
        }
        foreach ($this->getLanesets() as $laneset) {
            $this->removeLaneset($laneset["LNS_UID"]);
        }
        if ($process = $this->getProcess("object")) {
            $process->delete();
        }
        if ($diagram = $this->getDiagram("object")) {
            $diagram->delete();
        }
        if ($project = $this->getProject("object")) {
            $project->delete();
        }
        self::log("Remove Project Success!");
    }

    public static function removeIfExists($prjUid)
    {
        $project = ProjectPeer::retrieveByPK($prjUid);

        if ($project) {
            $me = new self();
            $me->prjUid = $project->getPrjUid();
            $me->project = $project;
            $me->remove();
        }
    }

    public static function getList($start = null, $limit = null, $filter = "", $changeCaseTo = CASE_UPPER)
    {
        return Project::getAll($start, $limit, $filter, $changeCaseTo);
    }

    public function getUid()
    {
        if (empty($this->project)) {
            throw new \RuntimeException("Error: There is not an initialized project.");
        }

        return $this->prjUid;
    }

    /**
     * @param string $retType
     * @return array|Project
     * @throws \RuntimeException
     */
    public function getProject($retType = "array")
    {
        if (empty($this->project)) {
            throw new \RuntimeException("Error: There is not an initialized project.");
        }

        return $retType == "array" ? $this->project->toArray() : $this->project;
    }

    public function canRemove()
    {
        $totalCases = \Process::getCasesCountForProcess($this->prjUid);
        if ($totalCases == 0) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * Projects elements handlers
     */

    public function addDiagram($data = array())
    {
        if (empty($this->project)) {
            throw new \Exception("Error: There is not an initialized project.");
        }

        // setting defaults
        $data['DIA_UID'] = array_key_exists('DIA_UID', $data) ? $data['DIA_UID'] : Common::generateUID();
        $data['DIA_NAME'] = array_key_exists('DIA_NAME', $data) ? $data['DIA_NAME'] : $this->project->getPrjName();

        $this->diagram = new Diagram();
        $this->diagram->fromArray($data, BasePeer::TYPE_FIELDNAME);
        $this->diagram->setPrjUid($this->project->getPrjUid());
        $this->diagram->save();
    }

    public function updateDiagram($data)
    {
        if (empty($this->project)) {
            throw new \Exception("Error: There is not an initialized project.");
        }
        if (! is_object($this->diagram)) {
            $this->getDiagram();
        }

        $this->diagram->fromArray($data, BasePeer::TYPE_FIELDNAME);
        $this->diagram->save();
    }

    public function getDiagram($retType = "array")
    {
        if (empty($this->diagram)) {
            $diagrams = Diagram::findAllByProUid($this->getUid());

            if (! empty($diagrams)) {
                //NOTICE for ProcessMaker we're just handling a "one to one" relationship between project and process
                $this->diagram = $diagrams[0];
            }
        }

        return ($retType == "array" && is_object($this->diagram)) ? $this->diagram->toArray() : $this->diagram;
    }

    public function addProcess($data = array())
    {
        if (empty($this->diagram)) {
            throw new \Exception("Error: There is not an initialized diagram.");
        }

        // setting defaults
        $data['PRO_UID'] = array_key_exists('PRO_UID', $data) ? $data['PRO_UID'] : Common::generateUID();;
        $data['PRO_NAME'] = array_key_exists('PRO_NAME', $data) ? $data['PRO_NAME'] : $this->diagram->getDiaName();

        $this->process = new Process();
        $this->process->fromArray($data, BasePeer::TYPE_FIELDNAME);
        $this->process->setPrjUid($this->project->getPrjUid());
        $this->process->setDiaUid($this->getDiagram("object")->getDiaUid());
        $this->process->save();
    }

    public function getProcess($retType = "array")
    {
        if (empty($this->process)) {
            $processes = Process::findAllByProUid($this->getUid());

            if (! empty($processes)) {
                //NOTICE for ProcessMaker we're just handling a "one to one" relationship between project and process
                $this->process = $processes[0];
            }
        }

        return $retType == "array" ? $this->process->toArray() : $this->process;
    }

    public function addActivity($data)
    {
        if (! ($process = $this->getProcess("object"))) {
            throw new \Exception(sprintf("Error: There is not an initialized diagram for Project with prj_uid: %s.", $this->getUid()));
        }

        // setting defaults
        $processUid = $process->getProUid();

        $data["ACT_UID"] = (array_key_exists("ACT_UID", $data))? $data["ACT_UID"] : Common::generateUID();
        $data["PRO_UID"] = $processUid;

        if (isset($data["ACT_LOOP_TYPE"]) && $data["ACT_LOOP_TYPE"] == "NONE") {
            $data["ACT_LOOP_TYPE"] = "EMPTY";
        }

        try {
            self::log("Add Activity with data: ", $data);

            $activity = new Activity();
            $activity->fromArray($data);
            $activity->setPrjUid($this->getUid());
            $activity->setProUid($processUid);
            $activity->save();

            self::log("Add Activity Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }

        return $activity->getActUid();
    }

    public function getActivity($actUid, $retType = 'array')
    {
        $activity = ActivityPeer::retrieveByPK($actUid);

        if ($retType != "object" && ! empty($activity)) {
            $activity = $activity->toArray();
            $activity = self::filterArrayKeys($activity, self::$excludeFields["activity"]);
        }

        return $activity;
    }

    public function getActivities($start = null, $limit = null, $filter = '', $changeCaseTo = CASE_UPPER)
    {
        if (is_array($start)) {
            extract($start);
        }

        $filter = $changeCaseTo != CASE_UPPER ? array_map("strtolower", self::$excludeFields["activity"]) : self::$excludeFields["activity"];

        return self::filterCollectionArrayKeys(
            Activity::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo),
            $filter
        );
    }

    public function updateActivity($actUid, $data)
    {
        try {
            if (isset($data["ACT_LOOP_TYPE"]) && $data["ACT_LOOP_TYPE"] == "NONE") {
                $data["ACT_LOOP_TYPE"] = "EMPTY";
            }

            self::log("Update Activity: $actUid, with data: ", $data);

            $activity = ActivityPeer::retrieveByPk($actUid);
            $activity->fromArray($data);
            $activity->save();

            self::log("Update Activity Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function removeActivity($actUid)
    {
        try {
            self::log("Remove Activity: $actUid");

            $activity = ActivityPeer::retrieveByPK($actUid);
            if (isset($activity)) {
                $activity->delete();
                Flow::removeAllRelated($actUid);
            } else {
                throw new Exception(G::LoadTranslation("ID_ACTIVITY_DOES_NOT_EXIST", array("act_uid", $actUid)));
            }
            self::log("Remove Activity Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function activityExists($actUid)
    {
        return \BpmnActivity::exists($actUid);
    }

    public function addEvent($data)
    {
        // setting defaults
        $processUid = $this->getProcess("object")->getProUid();

        $data['EVN_UID'] = array_key_exists('EVN_UID', $data) ? $data['EVN_UID'] : Common::generateUID();
        $data["PRO_UID"] = $processUid;

        try {
            self::log("Add Event with data: ", $data);

            $event = new Event();
            $event->fromArray($data);
            $event->setPrjUid($this->project->getPrjUid());
            $event->setProUid($processUid);
            $event->save();

            self::log("Add Event Success!");

            return $event->getEvnUid();
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function getEvent($evnUid, $retType = 'array')
    {
        $event = EventPeer::retrieveByPK($evnUid);

        if ($retType != "object" && ! empty($event)) {
            $event = $event->toArray();
            $event = self::filterArrayKeys($event, self::$excludeFields["event"]);
        }

        return $event;
    }

    public function getEvents($start = null, $limit = null, $filter = '', $changeCaseTo = CASE_UPPER)
    {
        if (is_array($start)) {
            extract($start);
        }

        //return Event::getAll($this->project->getPrjUid(), null, null, '', $changeCaseTo);

        $filter = $changeCaseTo != CASE_UPPER ? array_map("strtolower", self::$excludeFields["event"]) : self::$excludeFields["event"];

        return self::filterCollectionArrayKeys(
            Event::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo),
            $filter
        );
    }

    public function updateEvent($evnUid, $data)
    {
        /*if (array_key_exists("EVN_CANCEL_ACTIVITY", $data)) {
            $data["EVN_CANCEL_ACTIVITY"] = $data["EVN_CANCEL_ACTIVITY"] ? 1 : 0;
        }

        if (array_key_exists("EVN_WAIT_FOR_COMPLETION", $data)) {
            $data["EVN_WAIT_FOR_COMPLETION"] = $data["EVN_WAIT_FOR_COMPLETION"] ? 1 : 0;
        }*/

        try {
            self::log("Update Event: $evnUid", "With data: ", $data);

            $event = EventPeer::retrieveByPk($evnUid);
            $event->fromArray($data);
            $event->save();

            self::log("Update Event Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function removeEvent($evnUid)
    {
        try {
            self::log("Remove Event: $evnUid");
            $event = EventPeer::retrieveByPK($evnUid);

            $event->delete();

            self::log("Remove Event Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function addGateway($data)
    {
        // setting defaults
        $processUid = $this->getProcess("object")->getProUid();

        $data['GAT_UID'] = array_key_exists('GAT_UID', $data) ? $data['GAT_UID'] : Common::generateUID();
        $data["PRO_UID"] = $processUid;

        try {
            self::log("Add Gateway with data: ", $data);
            $gateway = new Gateway();
            $gateway->fromArray($data);
            $gateway->setPrjUid($this->getUid());
            $gateway->setProUid($processUid);
            $gateway->save();
            self::log("Add Gateway Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }

        return $gateway->getGatUid();
    }

    public function updateGateway($gatUid, $data)
    {
        try {
            self::log("Update Gateway: $gatUid", "With data: ", $data);

            $gateway = GatewayPeer::retrieveByPk($gatUid);

            $gateway->fromArray($data);
            $gateway->save();

            self::log("Update Gateway Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function getGateway($gatUid, $retType = 'array')
    {
        $gateway = GatewayPeer::retrieveByPK($gatUid);

        if ($retType != "object" && ! empty($gateway)) {
            $gateway = $gateway->toArray();
            $gateway = self::filterArrayKeys($gateway, self::$excludeFields["gateway"]);
        }

        return $gateway;
    }

    public function getGateway2($gatewayUid)
    {
        try {
            $criteria = new Criteria("workflow");

            $criteria->addSelectColumn(GatewayPeer::TABLE_NAME . ".*");
            $criteria->addSelectColumn(BoundPeer::TABLE_NAME . ".*");
            $criteria->addJoin(GatewayPeer::GAT_UID, BoundPeer::ELEMENT_UID, Criteria::LEFT_JOIN);
            $criteria->add(GatewayPeer::GAT_UID, $gatewayUid, Criteria::EQUAL);

            $rsCriteria = GatewayPeer::doSelectRS($criteria);
            $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);

            if ($rsCriteria->next()) {
                //Return
                return $rsCriteria->getRow();
            }

            //Return
            return false;
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());

            throw $e;
        }
    }

    public function getGateways($start = null, $limit = null, $filter = '', $changeCaseTo = CASE_UPPER)
    {
        if (is_array($start)) {
            extract($start);
        }

        //return  Gateway::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo);
        $filter = $changeCaseTo != CASE_UPPER ? array_map("strtolower", self::$excludeFields["gateway"]) : self::$excludeFields["gateway"];

        return self::filterCollectionArrayKeys(
            Gateway::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo),
            $filter
        );
    }

    public function removeGateway($gatUid)
    {
        try {
            self::log("Remove Gateway: $gatUid");

            $gateway = GatewayPeer::retrieveByPK($gatUid);
            $gateway->delete();

            // remove related object (flows)
            Flow::removeAllRelated($gatUid);

            self::log("Remove Gateway Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function throwExceptionFlowIfIsAnInvalidMessageFlow(array $bpmnFlow)
    {
        try {
            if ($bpmnFlow["FLO_TYPE"] == "MESSAGE" &&
                $bpmnFlow["FLO_ELEMENT_ORIGIN_TYPE"] == "bpmnEvent" && $bpmnFlow["FLO_ELEMENT_DEST_TYPE"] == "bpmnEvent"
            ) {
                $flagValid = true;

                $arrayEventType = array("START", "END", "INTERMEDIATE");

                $arrayAux = array(
                    array("eventUid" => $bpmnFlow["FLO_ELEMENT_ORIGIN"], "eventMarker" => array("MESSAGETHROW",
                        "EMAIL")),
                    array("eventUid" => $bpmnFlow["FLO_ELEMENT_DEST"],   "eventMarker" => array("MESSAGECATCH"))
                );

                foreach ($arrayAux as $value) {
                    $criteria = new \Criteria("workflow");

                    $criteria->addSelectColumn(\BpmnEventPeer::EVN_UID);
                    $criteria->add(\BpmnEventPeer::EVN_UID, $value["eventUid"], \Criteria::EQUAL);
                    $criteria->add(\BpmnEventPeer::EVN_TYPE, $arrayEventType, \Criteria::IN);
                    $criteria->add(\BpmnEventPeer::EVN_MARKER, $value["eventMarker"], \Criteria::IN);

                    $rsCriteria = \BpmnEventPeer::doSelectRS($criteria);

                    if (!$rsCriteria->next()) {
                        $flagValid = false;
                        break;
                    }
                }

                if (!$flagValid) {
                    throw new \RuntimeException("Invalid Message Flow.");
                }
            }
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());

            throw $e;
        }
    }

    public function addFlow($data)
    {
        self::log("Add Flow with data: ", $data);

        // setting defaults
        $data['FLO_UID'] = array_key_exists('FLO_UID', $data) ? $data['FLO_UID'] : Common::generateUID();

        if (array_key_exists('FLO_STATE', $data)) {
            $data['FLO_STATE'] = is_array($data['FLO_STATE']) ? json_encode($data['FLO_STATE']) : $data['FLO_STATE'];
        }

        try {
            switch ($data["FLO_ELEMENT_ORIGIN_TYPE"]) {
                case "bpmnActivity": $class = "BpmnActivity"; break;
                case "bpmnGateway": $class = "BpmnGateway"; break;
                case "bpmnEvent": $class = "BpmnEvent"; break;
                case "bpmnArtifact": $class = "BpmnArtifact"; break;
                case "bpmnData": $class = "BpmnData"; break;
                case "bpmnParticipant": $class = "BpmnParticipant"; break;
                case "bpmnLaneset": $class = "BpmnLaneset"; break;
                case "bpmnLane": $class = "BpmnLane"; break;
                default:
                    throw new \RuntimeException(sprintf("Invalid Object type, accepted types: [%s|%s|%s|%s], given %s.",
                        "BpmnActivity", "BpmnBpmnGateway", "BpmnEvent", "bpmnArtifact", $data["FLO_ELEMENT_ORIGIN_TYPE"]
                    ));
            }

            // Validate origin object exists
            if (! $class::exists($data["FLO_ELEMENT_ORIGIN"])) {
                throw new \RuntimeException(sprintf("Reference not found, the %s with UID: %s, does not exist!",
                    ucfirst($data["FLO_ELEMENT_ORIGIN_TYPE"]), $data["FLO_ELEMENT_ORIGIN"]
                ));
            }

            switch ($data["FLO_ELEMENT_DEST_TYPE"]) {
                case "bpmnActivity": $class = "BpmnActivity"; break;
                case "bpmnGateway": $class = "BpmnGateway"; break;
                case "bpmnEvent": $class = "BpmnEvent"; break;
                case "bpmnArtifact": $class = "BpmnArtifact"; break;
                case "bpmnData": $class = "BpmnData"; break;
                case "bpmnParticipant": $class = "BpmnParticipant"; break;
                case "bpmnLaneset": $class = "BpmnLaneset"; break;
                case "bpmnLane": $class = "BpmnLane"; break;
                default:
                    throw new \RuntimeException(sprintf("Invalid Object type, accepted types: [%s|%s|%s|%s], given %s.",
                        "BpmnActivity", "BpmnBpmnGateway", "BpmnEvent", "bpmnArtifact", $data["FLO_ELEMENT_DEST_TYPE"]
                    ));
            }

            // Validate origin object exists
            if (! $class::exists($data["FLO_ELEMENT_DEST"])) {
                throw new \RuntimeException(sprintf("Reference not found, the %s with UID: %s, does not exist!",
                    ucfirst($data["FLO_ELEMENT_DEST_TYPE"]), $data["FLO_ELEMENT_DEST"]
                ));
            }

            //Check and validate Message Flow
            $this->throwExceptionFlowIfIsAnInvalidMessageFlow($data);

            //Validating FLO_CONDITION value
            if (array_key_exists('FLO_CONDITION', $data) && is_null($data['FLO_CONDITION'])) {
                $data['FLO_CONDITION'] = '';
            }

            //Create
            $flow = new Flow();
            $flow->fromArray($data, BasePeer::TYPE_FIELDNAME);
            $flow->setPrjUid($this->getUid());
            $flow->setDiaUid($this->getDiagram("object")->getDiaUid());
            $flow->setFloPosition($this->getFlowNextPosition($data["FLO_UID"], $data["FLO_TYPE"], $data["FLO_ELEMENT_ORIGIN"]));
            $flow->save();

            self::log("Add Flow Success!");

            return $flow->getFloUid();
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());

            throw $e;
        }
    }

    public function updateFlow($floUid, $data)
    {
        self::log("Update Flow: $floUid", "With data: ", $data);

        // setting defaults
        if (array_key_exists('FLO_STATE', $data)) {
            $data['FLO_STATE'] = is_array($data['FLO_STATE']) ? json_encode($data['FLO_STATE']) : $data['FLO_STATE'];
        }

        try {
            //Check and validate Message Flow
            $this->throwExceptionFlowIfIsAnInvalidMessageFlow($data);

            //Validating FLO_CONDITION value
            if (array_key_exists('FLO_CONDITION', $data) && is_null($data['FLO_CONDITION'])) {
                $data['FLO_CONDITION'] = '';
            }

            //Update
            $flow = FlowPeer::retrieveByPk($floUid);
            $flow->fromArray($data);
            $flow->save();

            self::log("Update Flow Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function getFlow($floUid, $retType = 'array')
    {
        $flow = FlowPeer::retrieveByPK($floUid);

        if ($retType != "object" && ! empty($flow)) {
            $flow = $flow->toArray();
            $flow = self::filterArrayKeys($flow, self::$excludeFields["flow"]);
        }

        return $flow;
    }

    public function getFlows($start = null, $limit = null, $filter = '', $changeCaseTo = CASE_UPPER)
    {
        if (is_array($start)) {
            extract($start);
        }

        $filter = $changeCaseTo != CASE_UPPER ? array_map("strtolower", self::$excludeFields["flow"]) : self::$excludeFields["flow"];

        return self::filterCollectionArrayKeys(
            Flow::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo),
            $filter
        );
    }

    public function removeFlow($floUid)
    {
        try {
            self::log("Remove Flow: $floUid");

            $flow = FlowPeer::retrieveByPK($floUid);
            $this->reOrderFlowPosition($flow->getFloElementOrigin(), $flow->getFloPosition());

            $flow->delete();

            self::log("Remove Flow Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function flowExists($floUid)
    {
        return \BpmnFlow::exists($floUid);
    }

    public function addArtifact($data)
    {
        // setting defaults
        $processUid = $this->getProcess("object")->getProUid();

        $data['ART_UID'] = array_key_exists('ART_UID', $data) ? $data['ART_UID'] : Common::generateUID();
        $data["PRO_UID"] = $processUid;

        try {
            self::log("Add Artifact with data: ", $data);
            $artifact = new Artifact();
            $artifact->fromArray($data, BasePeer::TYPE_FIELDNAME);
            $artifact->setPrjUid($this->getUid());
            $artifact->setProUid($this->getProcess("object")->getProUid());
            $artifact->save();
            self::log("Add Artifact Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }

        return $artifact->getArtUid();
    }

    public function updateArtifact($artUid, $data)
    {
        try {
            self::log("Update Artifact: $artUid", "With data: ", $data);

            $artifact = ArtifactPeer::retrieveByPk($artUid);

            $artifact->fromArray($data);
            $artifact->save();

            self::log("Update Artifact Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function getArtifact($artUid, $retType = 'array')
    {
        $artifact = ArtifactPeer::retrieveByPK($artUid);

        if ($retType != "object" && ! empty($artifact)) {
            $artifact = $artifact->toArray();
            $artifact = self::filterArrayKeys($artifact, self::$excludeFields["artifact"]);
        }

        return $artifact;
    }

    public function getArtifacts($start = null, $limit = null, $filter = '', $changeCaseTo = CASE_UPPER)
    {
        if (is_array($start)) {
            extract($start);
        }

        $filter = $changeCaseTo != CASE_UPPER ? array_map("strtolower", self::$excludeFields["artifact"]) : self::$excludeFields["artifact"];

        return self::filterCollectionArrayKeys(
            Artifact::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo),
            $filter
        );
    }

    public function removeArtifact($artUid)
    {
        try {
            self::log("Remove Artifact: $artUid");

            $artifact = ArtifactPeer::retrieveByPK($artUid);
            $artifact->delete();

            // remove related object (flows)
            Flow::removeAllRelated($artUid);

            self::log("Remove Artifact Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function addData($data)
    {
        // setting defaults
        $processUid = $this->getProcess("object")->getProUid();

        $data['DATA_UID'] = array_key_exists('DAT_UID', $data) ? $data['DAT_UID'] : Common::generateUID();
        $data["PRO_UID"] = $processUid;

        try {
            self::log("Add BpmnData with data: ", $data);
            $bpmnData = new \BpmnData();
            $bpmnData->fromArray($data, BasePeer::TYPE_FIELDNAME);
            $bpmnData->setPrjUid($this->getUid());
            $bpmnData->setProUid($this->getProcess("object")->getProUid());
            $bpmnData->save();
            self::log("Add BpmnData Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }

        return $bpmnData->getDatUid();
    }

    public function updateData($datUid, $data)
    {
        try {
            self::log("Update BpmnData: $datUid", "With data: ", $data);

            $bpmnData = \BpmnDataPeer::retrieveByPk($datUid);

            $bpmnData->fromArray($data);
            $bpmnData->save();

            self::log("Update BpmnData Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function getData($datUid, $retType = 'array')
    {
        $bpmnData = \BpmnDataPeer::retrieveByPK($datUid);

        if ($retType != "object" && ! empty($bpmnData)) {
            $bpmnData = $bpmnData->toArray();
            $bpmnData = self::filterArrayKeys($bpmnData, self::$excludeFields["data"]);
        }

        return $bpmnData;
    }

    public function getDataCollection($start = null, $limit = null, $filter = '', $changeCaseTo = CASE_UPPER)
    {
        if (is_array($start)) {
            extract($start);
        }

        $filter = $changeCaseTo != CASE_UPPER ? array_map("strtolower", self::$excludeFields["data"]) : self::$excludeFields["data"];

        return self::filterCollectionArrayKeys(
            \BpmnData::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo),
            $filter
        );
    }

    public function removeData($datUid)
    {
        try {
            self::log("Remove BpmnData: $datUid");

            $bpmnData = \BpmnDataPeer::retrieveByPK($datUid);
            $bpmnData->delete();

            // remove related object (flows)
            Flow::removeAllRelated($datUid);

            self::log("Remove BpmnData Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function addParticipant($data)
    {
        // setting defaults
        $processUid = $this->getProcess("object")->getProUid();

        $data['PAR_UID'] = array_key_exists('PAR_UID', $data) ? $data['PAR_UID'] : Common::generateUID();
        $data["PRO_UID"] = $processUid;

        try {
            self::log("Add Participant with data: ", $data);
            $participant = new Participant();
            $participant->fromArray($data, BasePeer::TYPE_FIELDNAME);
            $participant->setPrjUid($this->getUid());
            $participant->setProUid($this->getProcess("object")->getProUid());
            $participant->save();
            self::log("Add Participant Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }

        return $participant->getParUid();
    }

    public function updateParticipant($parUid, $data)
    {
        try {
            self::log("Update Participant: $parUid", "With data: ", $data);

            $participant = ParticipantPeer::retrieveByPk($parUid);

            $participant->fromArray($data);
            $participant->save();

            self::log("Update Participant Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function getParticipant($parUid, $retType = 'array')
    {
        $participant = ParticipantPeer::retrieveByPK($parUid);

        if ($retType != "object" && ! empty($participant)) {
            $participant = $participant->toArray();
            $participant = self::filterArrayKeys($participant, self::$excludeFields["participant"]);
        }

        return $participant;
    }

    public function getParticipants($start = null, $limit = null, $filter = '', $changeCaseTo = CASE_UPPER)
    {
        if (is_array($start)) {
            extract($start);
        }

        $filter = $changeCaseTo != CASE_UPPER ? array_map("strtolower", self::$excludeFields["participant"]) : self::$excludeFields["participant"];

        return self::filterCollectionArrayKeys(
            Participant::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo),
            $filter
        );
    }

    public function removeParticipant($parUid)
    {
        try {
            self::log("Remove Participant: $parUid");

            $participant = ParticipantPeer::retrieveByPK($parUid);
            $participant->delete();

            // remove related object (flows)
            Flow::removeAllRelated($parUid);

            self::log("Remove Participant Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function addLane($data)
    {
        // setting defaults
        $processUid = $this->getProcess("object")->getProUid();

        $data['LAN_UID'] = array_key_exists('LAN_UID', $data) ? $data['LAN_UID'] : Common::generateUID();
        $data["PRO_UID"] = $processUid;

        try {
            self::log("Add Lane with data: ", $data);
            $lane = new Lane();
            $lane->fromArray($data, BasePeer::TYPE_FIELDNAME);
            $lane->setPrjUid($this->getUid());
            //$lane->setProUid($this->getProcess("object")->getProUid());
            $lane->save();
            self::log("Add Lane Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }

        return $lane->getLanUid();
    }

    public function getLane($lanUid, $retType = 'array')
    {
        $lane = LanePeer::retrieveByPK($lanUid);

        if ($retType != "object" && ! empty($lane)) {
            $lane = $lane->toArray();
            $lane = self::filterArrayKeys($lane, self::$excludeFields["lane"]);
        }

        return $lane;
    }

    public function getLanes($start = null, $limit = null, $filter = '', $changeCaseTo = CASE_UPPER)
    {
        if (is_array($start)) {
            extract($start);
        }

        $filter = $changeCaseTo != CASE_UPPER ? array_map("strtolower", self::$excludeFields["lane"]) : self::$excludeFields["lane"];

        return self::filterCollectionArrayKeys(
            Lane::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo),
            $filter
        );
    }

    public function removeLane($lanUid)
    {
        try {
            self::log("Remove Lane: $lanUid");

            $lane = LanePeer::retrieveByPK($lanUid);
            $lane->delete();

            // remove related object (flows)
            Flow::removeAllRelated($lanUid);

            self::log("Remove Lane Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function updateLane($lanUid, $data)
    {
        try {
            self::log("Update Lane: $lanUid", "With data: ", $data);
            $lane = LanePeer::retrieveByPk($lanUid);

            $lane->fromArray($data);
            $lane->save();

            self::log("Update Lane Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function addLaneset($data)
    {
        // setting defaults
        $processUid = $this->getProcess("object")->getProUid();
        $data['LNS_UID'] = array_key_exists('LNS_UID', $data) ? $data['LNS_UID'] : Common::generateUID();
        $data["PRO_UID"] = $processUid;

        try {
            self::log("Add Laneset with data: ", $data);
            $laneset = new Laneset();
            $laneset->fromArray($data, BasePeer::TYPE_FIELDNAME);
            $laneset->setPrjUid($this->getUid());
            $laneset->setProUid($this->getProcess("object")->getProUid());
            $laneset->save();
            self::log("Add Laneset Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }

        return $laneset->getLnsUid();
    }

    public function getLaneset($lnsUid, $retType = 'array')
    {
        $laneset = LanesetPeer::retrieveByPK($lnsUid);

        if ($retType != "object" && ! empty($laneset)) {
            $laneset = $laneset->toArray();
            $laneset = self::filterArrayKeys($laneset, self::$excludeFields["laneset"]);
        }

        return $laneset;
    }

    public function getLanesets($start = null, $limit = null, $filter = '', $changeCaseTo = CASE_UPPER)
    {
        if (is_array($start)) {
            extract($start);
        }
        $filter = $changeCaseTo != CASE_UPPER ? array_map("strtolower", self::$excludeFields["laneset"]) : self::$excludeFields["laneset"];
        return self::filterCollectionArrayKeys(
            Laneset::getAll($this->getUid(), $start, $limit, $filter, $changeCaseTo),
            $filter
        );
    }

    public function removeLaneset($lnsUid)
    {
        try {
            self::log("Remove Laneset: $lnsUid");

            $laneset = LanesetPeer::retrieveByPK($lnsUid);
            $laneset->delete();

            // remove related object (flows)
            Flow::removeAllRelated($lnsUid);

            self::log("Remove Laneset Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function updateLaneset($lnsUid, $data)
    {
        try {
            self::log("Update Laneset: $lnsUid", "With data: ", $data);

            $laneset = LanesetPeer::retrieveByPk($lnsUid);

            $laneset->fromArray($data);
            $laneset->save();

            self::log("Update Laneset Success!");
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
            throw $e;
        }
    }

    public function isModified($element, $uid, $newData)
    {
        $data = array();

        switch ($element) {
            case "activity": $data = $this->getActivity($uid); break;
            case "gateway":  $data = $this->getGateway($uid); break;
            case "event":    $data = $this->getEvent($uid); break;
            case "flow":     $data = $this->getFlow($uid); break;
        }
        //self::log("saved data: ", $data, "new data: ", $newData);
        //self::log("checksum saved data: ", self::getChecksum($data), "checksum new data: ", self::getChecksum($newData));
        return (self::getChecksum($data) !== self::getChecksum($newData));
    }

    public function setDisabled($value = true)
    {
        $status = $value ? "DISABLED" : "ACTIVE";
        $this->update(array("PRJ_STATUS" => $status));
    }

    public function getGatewayByDirectionActivityAndFlow($gatewayDirection, $activityUid)
    {
        try {
            $criteria = new Criteria("workflow");

            if ($gatewayDirection == "DIVERGING") {
                $criteria->addSelectColumn(FlowPeer::FLO_ELEMENT_DEST . " AS GAT_UID");

                $criteria->add(FlowPeer::FLO_ELEMENT_ORIGIN, $activityUid, Criteria::EQUAL);
                $criteria->add(FlowPeer::FLO_ELEMENT_ORIGIN_TYPE, "bpmnActivity", Criteria::EQUAL);
                $criteria->add(FlowPeer::FLO_ELEMENT_DEST_TYPE, "bpmnGateway", Criteria::EQUAL);
            } else {
                //CONVERGING
                $criteria->addSelectColumn(FlowPeer::FLO_ELEMENT_ORIGIN . " AS GAT_UID");

                $criteria->add(FlowPeer::FLO_ELEMENT_ORIGIN_TYPE, "bpmnGateway", Criteria::EQUAL);
                $criteria->add(FlowPeer::FLO_ELEMENT_DEST, $activityUid, Criteria::EQUAL);
                $criteria->add(FlowPeer::FLO_ELEMENT_DEST_TYPE, "bpmnActivity", Criteria::EQUAL);
            }

            $criteria->add(FlowPeer::PRJ_UID, $this->prjUid, Criteria::EQUAL);
            $criteria->add(FlowPeer::FLO_TYPE, "SEQUENCE", Criteria::EQUAL);

            $rsCriteria = FlowPeer::doSelectRS($criteria);
            $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);

            $gatewayUid = "";

            if ($rsCriteria->next()) {
                $row = $rsCriteria->getRow();

                $gatewayUid = $row["GAT_UID"];
            }

            //Return
            return $this->getGateway2($gatewayUid);
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());

            throw $e;
        }
    }

    public function getFlowNextPosition ($sFloUid, $sFloType, $sFloElementOrigin)
    {
        try {

            $oCriteria = new Criteria('workflow');
            $oCriteria->addSelectColumn( '(COUNT(*) + 1) AS FLOW_POS' );
            $oCriteria->add(\BpmnFlowPeer::PRJ_UID, $this->getUid());
            $oCriteria->add(\BpmnFlowPeer::DIA_UID, $this->getDiagram("object")->getDiaUid());
            $oCriteria->add(\BpmnFlowPeer::FLO_UID, $sFloUid, \Criteria::NOT_EQUAL);
            $oCriteria->add(\BpmnFlowPeer::FLO_TYPE, $sFloType);
            $oCriteria->add(\BpmnFlowPeer::FLO_ELEMENT_ORIGIN, $sFloElementOrigin);
            $oDataset = \BpmnFlowPeer::doSelectRS($oCriteria);
            $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
            $oDataset->next();
            $aRow = $oDataset->getRow();
            return (int)($aRow["FLOW_POS"]);

        } catch (Exception $oException) {
            throw $oException;
        }
    }

    public function reOrderFlowPosition ($sFloOrigin, $iPosition)
    {
        try {
            $con = \Propel::getConnection('workflow');
            $oCriteria = new Criteria( 'workflow' );
            $oCriteria->add( \BpmnFlowPeer::FLO_ELEMENT_ORIGIN, $sFloOrigin );
            $oCriteria->add( \BpmnFlowPeer::FLO_POSITION, $iPosition, '>' );
            $oDataset = \BpmnFlowPeer::doSelectRS( $oCriteria );
            $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC );
            while ($oDataset->next()) {
                $aRow = $oDataset->getRow();
                $newPosition = ((int)$aRow['FLO_POSITION'])-1;
                $oCriteriaTemp = new Criteria( 'workflow' );
                $oCriteriaTemp->add( \BpmnFlowPeer::FLO_UID, $aRow['FLO_UID'] );
                $oCriteria2 = new Criteria('workflow');
                $oCriteria2->add(\BpmnFlowPeer::FLO_POSITION, $newPosition);
                BasePeer::doUpdate($oCriteriaTemp, $oCriteria2, $con);
            }
        } catch (Exception $oException) {
            throw $oException;
        }
    }

    private function __getElementsBetweenElementOriginAndElementDest(
        $elementOriginUid,
        $elementOriginType,
        $elementDestUid,
        $elementDestType,
        $index
    ) {
        try {
            if (isset($this->arrayElementOriginChecked[$elementOriginUid]) && $this->arrayElementOriginChecked[$elementOriginUid] == $elementOriginType) {
                //Return
                return [];
            }

            $this->arrayElementOriginChecked[$elementOriginUid] = $elementOriginType;

            if ($index > 0 && $elementOriginType == $elementDestType) {
                if ($elementOriginUid == $elementDestUid) {
                    $arrayEvent = [];

                    array_unshift($arrayEvent, [$elementDestUid, $elementDestType]);

                    //Return
                    return $arrayEvent;
                }

                //Return
                return [];
            } else {
                //Flows
                $arrayFlow = \BpmnFlow::findAllBy([
                    \BpmnFlowPeer::FLO_TYPE                => ["MESSAGE", \Criteria::NOT_EQUAL],
                    \BpmnFlowPeer::FLO_ELEMENT_ORIGIN      => $elementOriginUid,
                    \BpmnFlowPeer::FLO_ELEMENT_ORIGIN_TYPE => $elementOriginType
                ]);

                foreach ($arrayFlow as $value) {
                    $arrayFlowData = $value->toArray();

                    $arrayEvent = $this->__getElementsBetweenElementOriginAndElementDest(
                        $arrayFlowData["FLO_ELEMENT_DEST"],
                        $arrayFlowData["FLO_ELEMENT_DEST_TYPE"],
                        $elementDestUid,
                        $elementDestType,
                        $index + 1
                    );

                    if (!empty($arrayEvent)) {
                        array_unshift($arrayEvent, [$elementOriginUid, $elementOriginType]);

                        //Return
                        return $arrayEvent;
                    }
                }

                //Return
                return [];
            }
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());

            throw $e;
        }
    }

    public function getElementsBetweenElementOriginAndElementDest(
        $elementOriginUid,
        $elementOriginType,
        $elementDestUid,
        $elementDestType
    ) {
        try {
            $this->arrayElementOriginChecked = [];

            //Return
            return call_user_func_array([$this, "__getElementsBetweenElementOriginAndElementDest"], array_merge(func_get_args(), [0]));
        } catch (\Exception $e) {
            self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());

            throw $e;
        }
    }

    /**
     * Logging information related to project
     * When the user doDeleteBulk
     *
     * @param string $channel
     * @param string $level
     * @param string $message
     * @param array $context
     *
     * @return void
     * @throws Exception
     */
    private function syslog(
        $channel,
        $level,
        $message,
        $context = array()
    )
    {
        try {
            Bootstrap::registerMonolog($channel, $level, $message, $context, $context['workspace'], 'processmaker.log');
        } catch (Exception $e) {
            throw $e;
        }
    }
}