示例#1
0
    function derivate($currentDelegation = array(), $nextDelegations = array(), $removeList = true)

    {

        //define this...

        if (! defined( 'TASK_FINISH_PROCESS' )) {

            define( 'TASK_FINISH_PROCESS', - 1 );

        }

        if (! defined( 'TASK_FINISH_TASK' )) {

            define( 'TASK_FINISH_TASK', - 2 );

        }



        $this->case = new cases();



        //Get data for this DEL_INDEX current

        $appFields = $this->case->loadCase( $currentDelegation['APP_UID'], $currentDelegation['DEL_INDEX'] );



        //We close the current derivation, then we'll try to derivate to each defined route

        $this->case->CloseCurrentDelegation( $currentDelegation['APP_UID'], $currentDelegation['DEL_INDEX'] );



        //Get data for current delegation (current Task)

        $task = TaskPeer::retrieveByPK($currentDelegation["TAS_UID"]);



        $currentDelegation["TAS_ASSIGN_TYPE"] = $task->getTasAssignType();

        $currentDelegation["TAS_MI_COMPLETE_VARIABLE"] = $task->getTasMiCompleteVariable();

        $currentDelegation["TAS_MI_INSTANCE_VARIABLE"] = $task->getTasMiInstanceVariable();



        //Count how many tasks should be derivated.

        //$countNextTask = count($nextDelegations);

        //$removeList = true;



        foreach ($nextDelegations as $nextDel) {

            //BpmnEvent - END-MESSAGE-EVENT, END-EMAIL-EVENT

            //Check and get unique id

            if (preg_match("/^(.{32})\/(\-1)$/", $nextDel["TAS_UID"], $arrayMatch)) {

                $nextDel["TAS_UID"] = $arrayMatch[2];

                $nextDel["TAS_UID_DUMMY"] = $arrayMatch[1];

            }



            //subprocesses??

            if ($nextDel['TAS_PARENT'] != '') {

                $oCriteria = new Criteria( 'workflow' );

                $oCriteria->add( SubProcessPeer::PRO_PARENT, $appFields['PRO_UID'] );

                $oCriteria->add( SubProcessPeer::TAS_PARENT, $nextDel['TAS_PARENT'] );

                if (SubProcessPeer::doCount( $oCriteria ) > 0) {

                    $oDataset = SubProcessPeer::doSelectRS( $oCriteria );

                    $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC );

                    $oDataset->next();

                    $aSP = $oDataset->getRow();

                    $aSP['USR_UID'] = $nextDel['USR_UID'];

                    $oTask = new Task();

                    $aTask = $oTask->load( $nextDel['TAS_PARENT'] );

                    $nextDel = array ('TAS_UID' => $aTask['TAS_UID'],'USR_UID' => $aSP['USR_UID'],'TAS_ASSIGN_TYPE' => $aTask['TAS_ASSIGN_TYPE'],'TAS_DEF_PROC_CODE' => $aTask['TAS_DEF_PROC_CODE'],'DEL_PRIORITY' => 3,'TAS_PARENT' => ''

                    );

                } else {

                    continue;

                }

            }



            //get open threads

            $openThreads = $this->case->GetOpenThreads( $currentDelegation['APP_UID'] );

            //if we are derivating to finish process but there are no more open thread then we are finishing only the task, we are not finishing the whole process

            if (($nextDel['TAS_UID'] == TASK_FINISH_PROCESS) && (($openThreads + 1) > 1)) {

                $nextDel['TAS_UID'] = TASK_FINISH_TASK;

            }



            $taskNextDel = TaskPeer::retrieveByPK($nextDel["TAS_UID"]); //Get data for next delegation (next Task)



            switch ($nextDel['TAS_UID']) {

                case TASK_FINISH_PROCESS:

                    /*Close all delegations of $currentDelegation['APP_UID'] */

                    $this->case->closeAllDelegations( $currentDelegation['APP_UID'] );

                    $this->case->closeAllThreads( $currentDelegation['APP_UID'] );

                    //I think we need to change the APP_STATUS to completed,



                    //BpmnEvent - END-MESSAGE-EVENT, END-EMAIL-EVENT

                    if (isset($nextDel["TAS_UID_DUMMY"])) {

                        $taskDummy = TaskPeer::retrieveByPK($nextDel["TAS_UID_DUMMY"]);



                        switch ($taskDummy->getTasType()) {

                            case "END-MESSAGE-EVENT":

                                //Throw Message-Events - BpmnEvent - END-MESSAGE-EVENT

                                $case = new \ProcessMaker\BusinessModel\Cases();



                                $case->throwMessageEventBetweenElementOriginAndElementDest($currentDelegation["TAS_UID"], $nextDel["TAS_UID_DUMMY"], $appFields);

                                break;

                            case "END-EMAIL-EVENT":

                                //Email Event

                                $emailEvent = new \ProcessMaker\BusinessModel\EmailEvent();



                                $emailEvent->emailEventBetweenElementOriginAndElementDest($currentDelegation["TAS_UID"], $nextDel["TAS_UID_DUMMY"], $appFields);

                                break;

                        }

                    }

                    break;

                case TASK_FINISH_TASK:

                    $iAppThreadIndex = $appFields['DEL_THREAD'];

                    $this->case->closeAppThread( $currentDelegation['APP_UID'], $iAppThreadIndex );

                    break;

                default:

                    // get all siblingThreads

                    //if($currentDelegation['TAS_ASSIGN_TYPE'] == 'STATIC_MI')

                    switch ($currentDelegation['TAS_ASSIGN_TYPE']) {

                        case 'CANCEL_MI':

                        case 'STATIC_MI':

                            $siblingThreads = $this->case->GetAllOpenDelegation( $currentDelegation );

                            $aData = $this->case->loadCase( $currentDelegation['APP_UID'] );



                            if (isset( $aData['APP_DATA'][str_replace( '@@', '', $currentDelegation['TAS_MI_INSTANCE_VARIABLE'] )] )) {

                                $sMIinstanceVar = $aData['APP_DATA'][str_replace( '@@', '', $currentDelegation['TAS_MI_INSTANCE_VARIABLE'] )];

                            } else {

                                $sMIinstanceVar = $aData['APP_DATA']['TAS_MI_INSTANCE_VARIABLE'];

                            }



                            if (isset( $aData['APP_DATA'][str_replace( '@@', '', $currentDelegation['TAS_MI_COMPLETE_VARIABLE'] )] )) {

                                $sMIcompleteVar = $aData['APP_DATA'][str_replace( '@@', '', $currentDelegation['TAS_MI_COMPLETE_VARIABLE'] )];

                            } else {

                                $sMIcompleteVar = $aData['APP_DATA']['TAS_MI_COMPLETE_VARIABLE'];

                            }



                            $discriminateThread = $sMIinstanceVar - $sMIcompleteVar;



                            // -1 because One App Delegation is closed by above Code

                            if ($discriminateThread == count( $siblingThreads )) {

                                $canDerivate = true;

                            } else {

                                $canDerivate = false;

                            }

                            break;

                        default:

                            if ($currentDelegation["ROU_TYPE"] == "SEC-JOIN") {

                                $siblingThreads = $this->case->getOpenSiblingThreads($nextDel["TAS_UID"], $currentDelegation["APP_UID"], $currentDelegation["DEL_INDEX"], $currentDelegation["TAS_UID"]);



                                $canDerivate = empty($siblingThreads);

                            } else {

                                $canDerivate = true;

                            }

                    } //end switch



                    if ($canDerivate) {

                        //Throw Message-Events

                        $case = new \ProcessMaker\BusinessModel\Cases();



                        $case->throwMessageEventBetweenElementOriginAndElementDest($currentDelegation["TAS_UID"], $nextDel["TAS_UID"], $appFields);



                        //Throw Email-Events

                        $emailEvent = new \ProcessMaker\BusinessModel\EmailEvent();



                        $emailEvent->emailEventBetweenElementOriginAndElementDest($currentDelegation["TAS_UID"], $nextDel["TAS_UID"], $appFields);



                        //Derivate

                        $aSP = isset( $aSP ) ? $aSP : null;



                        $iNewDelIndex = $this->doDerivation( $currentDelegation, $nextDel, $appFields, $aSP );



                        //Execute Script-Task

                        $scriptTask = new \ProcessMaker\BusinessModel\ScriptTask();



                        $appFields["APP_DATA"] = $scriptTask->execScriptByActivityUid($nextDel["TAS_UID"], $appFields);



                        //Create record in table APP_ASSIGN_SELF_SERVICE_VALUE

                        $arrayTaskTypeToExclude = array("SCRIPT-TASK");



                        if (!in_array($taskNextDel->getTasType(), $arrayTaskTypeToExclude)) {

                            if ($taskNextDel->getTasAssignType() == "SELF_SERVICE" && trim($taskNextDel->getTasGroupVariable()) != "") {

                                $nextTaskGroupVariable = trim($taskNextDel->getTasGroupVariable(), " @#");



                                if (isset($appFields["APP_DATA"][$nextTaskGroupVariable]) && trim($appFields["APP_DATA"][$nextTaskGroupVariable]) != "") {

                                    $appAssignSelfServiceValue = new AppAssignSelfServiceValue();



                                    $appAssignSelfServiceValue->create($appFields["APP_UID"], $iNewDelIndex, array("PRO_UID" => $appFields["PRO_UID"], "TAS_UID" => $nextDel["TAS_UID"], "GRP_UID" => trim($appFields["APP_DATA"][$nextTaskGroupVariable])));

                                }

                            }

                        }



                        //Check if $taskNextDel is Script-Task

                        if ($taskNextDel->getTasType() == "SCRIPT-TASK") {

                            $this->case->CloseCurrentDelegation($currentDelegation["APP_UID"], $iNewDelIndex);



                            //Get for $nextDel["TAS_UID"] your next Task

                            $taskNextDelNextDelegations = $this->prepareInformation(array(

                                "USER_UID"  => $_SESSION["USER_LOGGED"],

                                "APP_UID"   => $_SESSION["APPLICATION"],

                                "DEL_INDEX" => $iNewDelIndex

                            ));



                            //New next delegation

                            $newNextDelegation = array();



                            $newNextDelegation[1] = array(

                                "TAS_UID"           => $taskNextDelNextDelegations[1]["NEXT_TASK"]["TAS_UID"],

                                "USR_UID"           => $taskNextDelNextDelegations[1]["NEXT_TASK"]["USER_ASSIGNED"]["USR_UID"],

                                "TAS_ASSIGN_TYPE"   => $taskNextDelNextDelegations[1]["NEXT_TASK"]["TAS_ASSIGN_TYPE"],

                                "TAS_DEF_PROC_CODE" => "",

                                "DEL_PRIORITY"      => "",

                                "TAS_PARENT"        => ""

                            );



                            $this->derivate($currentDelegation, $newNextDelegation, $removeList);

                        }

                    } else {

                        //when the task doesnt generate a new AppDelegation

                        $iAppThreadIndex = $appFields['DEL_THREAD'];

                        switch ($currentDelegation['ROU_TYPE']) {

                            case 'SEC-JOIN':

                                $this->case->closeAppThread( $currentDelegation['APP_UID'], $iAppThreadIndex );

                                break;

                            default:

                                if ($currentDelegation['TAS_ASSIGN_TYPE'] == 'STATIC_MI' || $currentDelegation['TAS_ASSIGN_TYPE'] == 'CANCEL_MI') {

                                    $this->case->closeAppThread( $currentDelegation['APP_UID'], $iAppThreadIndex );

                                }

                                break;

                        } //switch

                    }

            }



            //SETS THE APP_PROC_CODE

            //if (isset($nextDel['TAS_DEF_PROC_CODE']))

            //$appFields['APP_PROC_CODE'] = $nextDel['TAS_DEF_PROC_CODE'];

            /*----------------------------------********---------------------------------*/



            unset( $aSP );



            $removeList = false;

        } //end foreach



        /* Start Block : UPDATES APPLICATION */



        //Set THE APP_STATUS

        $appFields['APP_STATUS'] = $currentDelegation['APP_STATUS'];

        /* Start Block : Count the open threads of $currentDelegation['APP_UID'] */

        $openThreads = $this->case->GetOpenThreads( $currentDelegation['APP_UID'] );



        ///////

        $sw = 0;



        if ($openThreads == 0) {

            //Close case

            $appFields["APP_STATUS"] = "COMPLETED";

            $appFields["APP_FINISH_DATE"] = "now";

            $this->verifyIsCaseChild($currentDelegation["APP_UID"], $currentDelegation["DEL_INDEX"]);



            $sw = 1;

        }



        if (isset( $iNewDelIndex )) {

            $appFields["DEL_INDEX"] = $iNewDelIndex;

            $appFields["TAS_UID"] = $nextDel["TAS_UID"];



            $sw = 1;

        }



        if ($sw == 1) {

            //Start Block : UPDATES APPLICATION

            $this->case->updateCase( $currentDelegation["APP_UID"], $appFields );

            //End Block : UPDATES APPLICATION

        }

    }
示例#2
0
    /**

     * Create Script-Task records

     *

     * @param string $processUid Unique id of Process

     * @param array  $arrayData  Data

     *

     * return void

     */

    public function createScriptTask($processUid, array $arrayData)

    {

        try {

            $scriptTask = new \ProcessMaker\BusinessModel\ScriptTask();



            foreach ($arrayData as $value) {

                $record = $value;



                $result = $scriptTask->create($processUid, $record);

            }

        } catch (Exception $e) {

            throw $e;

        }

    }
示例#3
0
    public function removeActivity($actUid)
    {
        $activity = \BpmnActivityPeer::retrieveByPK($actUid);

        parent::removeActivity($actUid);
        $this->wp->removeTask($actUid);

        //Delete Script-Task
        $scriptTask = new \ProcessMaker\BusinessModel\ScriptTask();

        $scriptTask->deleteWhere(array(
            \ScriptTaskPeer::PRJ_UID => $activity->getPrjUid(),
            \ScriptTaskPeer::ACT_UID => $activity->getActUid()
        ));
    }
示例#4
0
 public function deleteProcess($sProcessUID, $flagRemoveCases = true)
 {
     try {
         //G::LoadClass('case');
         //G::LoadClass('reportTables');
         //Instance all classes necesaries
         $oProcess = new \Process();
         $oDynaform = new \Dynaform();
         $oInputDocument = new \InputDocument();
         $oOutputDocument = new \OutputDocument();
         $oTrigger = new \Triggers();
         $oRoute = new \Route();
         $oGateway = new \Gateway();
         $oEvent = new \Event();
         $oSwimlaneElement = new \SwimlanesElements();
         $oConfiguration = new \Configuration();
         $oDbSource = new \DbSource();
         $oReportTable = new \ReportTables();
         $oCaseTracker = new \CaseTracker();
         $oCaseTrackerObject = new \CaseTrackerObject();
         //Update PROCESS_FILES_CHECKED
         $configuration = \ConfigurationPeer::retrieveByPK("PROCESS_FILES_CHECKED", "", "", "", "");
         if (!is_null($configuration)) {
             $arrayProjectUid = unserialize($configuration->getCfgValue());
             unset($arrayProjectUid[$sProcessUID]);
             $conf = new \Configuration();
             $result = $conf->update(array("CFG_UID" => "PROCESS_FILES_CHECKED", "OBJ_UID" => "", "CFG_VALUE" => serialize($arrayProjectUid), "PRO_UID" => "", "USR_UID" => "", "APP_UID" => ""));
         }
         //Delete the applications of process
         if ($flagRemoveCases) {
             $case = new \Cases();
             $criteria = new \Criteria("workflow");
             $criteria->addSelectColumn(\ApplicationPeer::APP_UID);
             $criteria->add(\ApplicationPeer::PRO_UID, $sProcessUID, \Criteria::EQUAL);
             $rsCriteria = \ApplicationPeer::doSelectRS($criteria);
             $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
             while ($rsCriteria->next()) {
                 $row = $rsCriteria->getRow();
                 $result = $case->removeCase($row["APP_UID"]);
             }
         }
         //Delete the tasks of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\TaskPeer::PRO_UID, $sProcessUID);
         $oDataset = \TaskPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             //$this->deleteTask($aRow['TAS_UID']);
             $oTasks = new \Tasks();
             $oTasks->deleteTask($aRow['TAS_UID']);
             $oDataset->next();
         }
         //Delete the dynaforms of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\DynaformPeer::PRO_UID, $sProcessUID);
         $oDataset = \DynaformPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oDynaform->remove($aRow['DYN_UID']);
             $oDataset->next();
         }
         //Delete the input documents of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\InputDocumentPeer::PRO_UID, $sProcessUID);
         $oDataset = \InputDocumentPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oInputDocument->remove($aRow['INP_DOC_UID']);
             $oDataset->next();
         }
         //Delete the output documents of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\OutputDocumentPeer::PRO_UID, $sProcessUID);
         $oDataset = \OutputDocumentPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oOutputDocument->remove($aRow['OUT_DOC_UID']);
             $oDataset->next();
         }
         //Delete the triggers of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\TriggersPeer::PRO_UID, $sProcessUID);
         $oDataset = \TriggersPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oTrigger->remove($aRow['TRI_UID']);
             $oDataset->next();
         }
         //Delete the routes of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\RoutePeer::PRO_UID, $sProcessUID);
         $oDataset = \RoutePeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oRoute->remove($aRow['ROU_UID']);
             $oDataset->next();
         }
         //Delete the gateways of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\GatewayPeer::PRO_UID, $sProcessUID);
         $oDataset = \GatewayPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oGateway->remove($aRow['GAT_UID']);
             $oDataset->next();
         }
         //Delete the Event of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\EventPeer::PRO_UID, $sProcessUID);
         $oDataset = \EventPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oEvent->remove($aRow['EVN_UID']);
             $oDataset->next();
         }
         //Delete the swimlanes elements of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\SwimlanesElementsPeer::PRO_UID, $sProcessUID);
         $oDataset = \SwimlanesElementsPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oSwimlaneElement->remove($aRow['SWI_UID']);
             $oDataset->next();
         }
         //Delete the configurations of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\ConfigurationPeer::PRO_UID, $sProcessUID);
         $oDataset = \ConfigurationPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oConfiguration->remove($aRow['CFG_UID'], $aRow['OBJ_UID'], $aRow['PRO_UID'], $aRow['USR_UID'], $aRow['APP_UID']);
             $oDataset->next();
         }
         //Delete the DB sources of process
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\DbSourcePeer::PRO_UID, $sProcessUID);
         $oDataset = \DbSourcePeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             /**
              * note added by gustavo cruz gustavo-at-colosa-dot-com 27-01-2010
              * in order to solve the bug 0004389, we use the validation function Exists
              * inside the remove function in order to verify if the DbSource record
              * exists in the Database, however there is a strange behavior within the
              * propel engine, when the first record is erased somehow the "_deleted"
              * attribute of the next row is set to true, so when propel tries to erase
              * it, obviously it can't and trows an error. With the "Exist" function
              * we ensure that if there is the record in the database, the _delete attribute must be false.
              *
              * note added by gustavo cruz gustavo-at-colosa-dot-com 28-01-2010
              * I have just identified the source of the issue, when is created a $oDbSource DbSource object
              * it's used whenever a record is erased or removed in the db, however the problem
              * it's that the same object is used every time, and the delete method invoked
              * sets the _deleted attribute to true when its called, of course as we use
              * the same object, the first time works fine but trowns an error with the
              * next record, cos it's the same object and the delete method checks if the _deleted
              * attribute it's true or false, the attrib _deleted is setted to true the
              * first time and later is never changed, the issue seems to be part of
              * every remove function in the model classes, not only DbSource
              * i recommend that a more general solution must be achieved to resolve
              * this issue in every model class, to prevent future problems.
              */
             $oDbSource->remove($aRow['DBS_UID'], $sProcessUID);
             $oDataset->next();
         }
         //Delete the supervisors
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\ProcessUserPeer::PRO_UID, $sProcessUID);
         \ProcessUserPeer::doDelete($oCriteria);
         //Delete the object permissions
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\ObjectPermissionPeer::PRO_UID, $sProcessUID);
         \ObjectPermissionPeer::doDelete($oCriteria);
         //Delete the step supervisors
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\StepSupervisorPeer::PRO_UID, $sProcessUID);
         \StepSupervisorPeer::doDelete($oCriteria);
         //Delete the report tables
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\ReportTablePeer::PRO_UID, $sProcessUID);
         $oDataset = \ReportTablePeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $oReportTable->deleteReportTable($aRow['REP_TAB_UID']);
             $oDataset->next();
         }
         //Delete case tracker configuration
         $oCaseTracker->remove($sProcessUID);
         //Delete case tracker objects
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\CaseTrackerObjectPeer::PRO_UID, $sProcessUID);
         \ProcessUserPeer::doDelete($oCriteria);
         //Delete SubProcess
         $criteria = new \Criteria("workflow");
         $criteria->add(\SubProcessPeer::PRO_PARENT, $sProcessUID, \Criteria::EQUAL);
         $result = \SubProcessPeer::doDelete($criteria);
         //Delete WebEntries
         $webEntry = new \ProcessMaker\BusinessModel\WebEntry();
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\WebEntryPeer::WE_UID);
         $criteria->add(\WebEntryPeer::PRO_UID, $sProcessUID, \Criteria::EQUAL);
         $rsCriteria = \WebEntryPeer::doSelectRS($criteria);
         $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
         while ($rsCriteria->next()) {
             $row = $rsCriteria->getRow();
             $webEntry->delete($row["WE_UID"]);
         }
         //Delete WebEntry-Events
         $webEntryEvent = new \ProcessMaker\BusinessModel\WebEntryEvent();
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\WebEntryEventPeer::WEE_UID);
         $criteria->add(\WebEntryEventPeer::PRJ_UID, $sProcessUID, \Criteria::EQUAL);
         $rsCriteria = \WebEntryEventPeer::doSelectRS($criteria);
         $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
         while ($rsCriteria->next()) {
             $row = $rsCriteria->getRow();
             $webEntryEvent->delete($row["WEE_UID"]);
         }
         //Delete MessageTypes
         $messageType = new \ProcessMaker\BusinessModel\MessageType();
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\MessageTypePeer::MSGT_UID);
         $criteria->add(\MessageTypePeer::PRJ_UID, $sProcessUID, \Criteria::EQUAL);
         $rsCriteria = \MessageTypePeer::doSelectRS($criteria);
         $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
         while ($rsCriteria->next()) {
             $row = $rsCriteria->getRow();
             $messageType->delete($row["MSGT_UID"]);
         }
         //Delete Message-Event-Relation
         $messageEventRelation = new \ProcessMaker\BusinessModel\MessageEventRelation();
         $messageEventRelation->deleteWhere(array(\MessageEventRelationPeer::PRJ_UID => $sProcessUID));
         //Delete Message-Event-Task-Relation
         $elementTaskRelation = new \ProcessMaker\BusinessModel\ElementTaskRelation();
         $elementTaskRelation->deleteWhere(array(\ElementTaskRelationPeer::PRJ_UID => $sProcessUID));
         //Delete Message-Event-Definition
         $messageEventDefinition = new \ProcessMaker\BusinessModel\MessageEventDefinition();
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\MessageEventDefinitionPeer::MSGED_UID);
         $criteria->add(\MessageEventDefinitionPeer::PRJ_UID, $sProcessUID, \Criteria::EQUAL);
         $rsCriteria = \MessageEventDefinitionPeer::doSelectRS($criteria);
         $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
         while ($rsCriteria->next()) {
             $row = $rsCriteria->getRow();
             $messageEventDefinition->delete($row["MSGED_UID"]);
         }
         //Delete Script-Task
         $scriptTask = new \ProcessMaker\BusinessModel\ScriptTask();
         $scriptTask->deleteWhere(array(\ScriptTaskPeer::PRJ_UID => array($sProcessUID, \Criteria::EQUAL)));
         //Delete Timer-Event
         $timerEvent = new \ProcessMaker\BusinessModel\TimerEvent();
         $timerEvent->deleteWhere(array(\TimerEventPeer::PRJ_UID => array($sProcessUID, \Criteria::EQUAL)));
         //Delete Email-Event
         $emailEvent = new \ProcessMaker\BusinessModel\EmailEvent();
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\EmailEventPeer::EMAIL_EVENT_UID);
         $criteria->add(\EmailEventPeer::PRJ_UID, $sProcessUID, \Criteria::EQUAL);
         $rsCriteria = \EmailEventPeer::doSelectRS($criteria);
         $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
         while ($rsCriteria->next()) {
             $row = $rsCriteria->getRow();
             $emailEvent->delete($sProcessUID, $row["EMAIL_EVENT_UID"], false);
         }
         //Delete files Manager
         $filesManager = new \ProcessMaker\BusinessModel\FilesManager();
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\ProcessFilesPeer::PRF_UID);
         $criteria->add(\ProcessFilesPeer::PRO_UID, $sProcessUID, \Criteria::EQUAL);
         $rsCriteria = \ProcessFilesPeer::doSelectRS($criteria);
         $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
         while ($rsCriteria->next()) {
             $row = $rsCriteria->getRow();
             $filesManager->deleteProcessFilesManager($sProcessUID, $row["PRF_UID"]);
         }
         //Delete the actions by email
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(\AbeConfigurationPeer::PRO_UID, $sProcessUID);
         \AbeConfigurationPeer::doDelete($oCriteria);
         //Delete the process
         try {
             $oProcess->remove($sProcessUID);
         } catch (\Exception $oError) {
             throw $oError;
         }
         return true;
     } catch (\Exception $oError) {
         throw $oError;
     }
 }
    function derivate($currentDelegation = array(), $nextDelegations = array(), $removeList = true)

    {

        //define this...

        if (! defined( 'TASK_FINISH_PROCESS' )) {

            define( 'TASK_FINISH_PROCESS', - 1 );

        }

        if (! defined( 'TASK_FINISH_TASK' )) {

            define( 'TASK_FINISH_TASK', - 2 );

        }



        $this->case = new cases();



        //Get data for this DEL_INDEX current

        $appFields = $this->case->loadCase( $currentDelegation['APP_UID'], $currentDelegation['DEL_INDEX'] );



        //We close the current derivation, then we'll try to derivate to each defined route

        $this->case->CloseCurrentDelegation( $currentDelegation['APP_UID'], $currentDelegation['DEL_INDEX'] );



        //Get data for current delegation (current Task)

        $task = TaskPeer::retrieveByPK($currentDelegation["TAS_UID"]);

        $bpmnActivity = BpmnActivityPeer::retrieveByPK($currentDelegation["TAS_UID"]);



        $flagTaskIsMultipleInstance = false;

        $flagTaskAssignTypeIsMultipleInstance = false;



        if (!is_null($task) && !is_null($bpmnActivity)) {

            $flagTaskIsMultipleInstance = $bpmnActivity->getActType() == "TASK" && preg_match("/^(?:EMPTY|USERTASK|MANUALTASK)$/", $bpmnActivity->getActTaskType()) && $bpmnActivity->getActLoopType() == "PARALLEL";

            $flagTaskAssignTypeIsMultipleInstance = preg_match("/^(?:MULTIPLE_INSTANCE|MULTIPLE_INSTANCE_VALUE_BASED)$/", $task->getTasAssignType());

        }



        $currentDelegation["TAS_ASSIGN_TYPE"] = $task->getTasAssignType();

        $currentDelegation["TAS_MI_COMPLETE_VARIABLE"] = $task->getTasMiCompleteVariable();

        $currentDelegation["TAS_MI_INSTANCE_VARIABLE"] = $task->getTasMiInstanceVariable();



        //Count how many tasks should be derivated.

        //$countNextTask = count($nextDelegations);

        //$removeList = true;



        foreach ($nextDelegations as $nextDel) {

            //BpmnEvent - END-MESSAGE-EVENT, END-EMAIL-EVENT

            //Check and get unique id

            if (preg_match("/^(.{32})\/(\-1)$/", $nextDel["TAS_UID"], $arrayMatch)) {

                $nextDel["TAS_UID"] = $arrayMatch[2];

                $nextDel["TAS_UID_DUMMY"] = $arrayMatch[1];

            }



            //subprocesses??

            if ($nextDel['TAS_PARENT'] != '') {

                $oCriteria = new Criteria( 'workflow' );

                $oCriteria->add( SubProcessPeer::PRO_PARENT, $appFields['PRO_UID'] );

                $oCriteria->add( SubProcessPeer::TAS_PARENT, $nextDel['TAS_PARENT'] );

                if (SubProcessPeer::doCount( $oCriteria ) > 0) {

                    $oDataset = SubProcessPeer::doSelectRS( $oCriteria );

                    $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC );

                    $oDataset->next();

                    $aSP = $oDataset->getRow();

                    $aSP['USR_UID'] = $nextDel['USR_UID'];

                    $oTask = new Task();

                    $aTask = $oTask->load( $nextDel['TAS_PARENT'] );

                    $nextDel = array ('TAS_UID' => $aTask['TAS_UID'],'USR_UID' => $aSP['USR_UID'],'TAS_ASSIGN_TYPE' => $aTask['TAS_ASSIGN_TYPE'],'TAS_DEF_PROC_CODE' => $aTask['TAS_DEF_PROC_CODE'],'DEL_PRIORITY' => 3,'TAS_PARENT' => ''

                    );

                } else {

                    continue;

                }

            }



            //get open threads

            $openThreads = $this->case->GetOpenThreads( $currentDelegation['APP_UID'] );

            //if we are derivating to finish process but there are no more open thread then we are finishing only the task, we are not finishing the whole process

            if (($nextDel['TAS_UID'] == TASK_FINISH_PROCESS) && (($openThreads + 1) > 1)) {

                $nextDel['TAS_UID'] = TASK_FINISH_TASK;

            }



            $taskNextDel = TaskPeer::retrieveByPK($nextDel["TAS_UID"]); //Get data for next delegation (next Task)

            $bpmnActivityNextDel = BpmnActivityPeer::retrieveByPK($nextDel["TAS_UID"]);



            $flagTaskNextDelIsMultipleInstance = false;

            $flagTaskNextDelAssignTypeIsMultipleInstance = false;



            if (!is_null($taskNextDel) && !is_null($bpmnActivityNextDel)) {

                $flagTaskNextDelIsMultipleInstance = $bpmnActivityNextDel->getActType() == "TASK" && preg_match("/^(?:EMPTY|USERTASK|MANUALTASK)$/", $bpmnActivityNextDel->getActTaskType()) && $bpmnActivityNextDel->getActLoopType() == "PARALLEL";

                $flagTaskNextDelAssignTypeIsMultipleInstance = preg_match("/^(?:MULTIPLE_INSTANCE|MULTIPLE_INSTANCE_VALUE_BASED)$/", $taskNextDel->getTasAssignType());

            }



            $flagUpdateCounters = true;



            switch ($nextDel['TAS_UID']) {

                case TASK_FINISH_PROCESS:

                    /*Close all delegations of $currentDelegation['APP_UID'] */

                    $this->case->closeAllDelegations( $currentDelegation['APP_UID'] );

                    $this->case->closeAllThreads( $currentDelegation['APP_UID'] );

                    //I think we need to change the APP_STATUS to completed,



                    //BpmnEvent - END-MESSAGE-EVENT, END-EMAIL-EVENT

                    if (isset($nextDel["TAS_UID_DUMMY"])) {

                        $taskDummy = TaskPeer::retrieveByPK($nextDel["TAS_UID_DUMMY"]);



                        switch ($taskDummy->getTasType()) {

                            case "END-MESSAGE-EVENT":

                                //Throw Message-Events - BpmnEvent - END-MESSAGE-EVENT

                                $case = new \ProcessMaker\BusinessModel\Cases();



                                $case->throwMessageEventBetweenElementOriginAndElementDest($currentDelegation["TAS_UID"], $nextDel["TAS_UID_DUMMY"], $appFields);

                                break;

                            case "END-EMAIL-EVENT":

                                //Email Event

                                $emailEvent = new \ProcessMaker\BusinessModel\EmailEvent();



                                $emailEvent->emailEventBetweenElementOriginAndElementDest($currentDelegation["TAS_UID"], $nextDel["TAS_UID_DUMMY"], $appFields);

                                break;

                        }

                    }

                    break;

                case TASK_FINISH_TASK:

                    $iAppThreadIndex = $appFields['DEL_THREAD'];

                    $this->case->closeAppThread( $currentDelegation['APP_UID'], $iAppThreadIndex );

                    break;

                default:

                    //Get all siblingThreads

                    $canDerivate = false;



                    switch ($currentDelegation['TAS_ASSIGN_TYPE']) {

                        case 'CANCEL_MI':

                        case 'STATIC_MI':

                            $arrayOpenThread = $this->case->GetAllOpenDelegation($currentDelegation);

                            $aData = $this->case->loadCase( $currentDelegation['APP_UID'] );



                            if (isset( $aData['APP_DATA'][str_replace( '@@', '', $currentDelegation['TAS_MI_INSTANCE_VARIABLE'] )] )) {

                                $sMIinstanceVar = $aData['APP_DATA'][str_replace( '@@', '', $currentDelegation['TAS_MI_INSTANCE_VARIABLE'] )];

                            } else {

                                $sMIinstanceVar = $aData['APP_DATA']['TAS_MI_INSTANCE_VARIABLE'];

                            }



                            if (isset( $aData['APP_DATA'][str_replace( '@@', '', $currentDelegation['TAS_MI_COMPLETE_VARIABLE'] )] )) {

                                $sMIcompleteVar = $aData['APP_DATA'][str_replace( '@@', '', $currentDelegation['TAS_MI_COMPLETE_VARIABLE'] )];

                            } else {

                                $sMIcompleteVar = $aData['APP_DATA']['TAS_MI_COMPLETE_VARIABLE'];

                            }



                            $discriminateThread = $sMIinstanceVar - $sMIcompleteVar;



                            // -1 because One App Delegation is closed by above Code

                            if ($discriminateThread == count($arrayOpenThread)) {

                                $canDerivate = true;

                            } else {

                                $canDerivate = false;

                            }

                            break;

                        default:

                            $routeType = $currentDelegation["ROU_TYPE"];

                            $routeType = ($flagTaskIsMultipleInstance && $flagTaskAssignTypeIsMultipleInstance)? "SEC-JOIN" : $routeType;



                            switch ($routeType) {

                                case "SEC-JOIN":

                                    $arrayOpenThread = ($flagTaskIsMultipleInstance && $flagTaskAssignTypeIsMultipleInstance)? $this->case->searchOpenPreviousTasks($currentDelegation["TAS_UID"], $currentDelegation["APP_UID"]) : array();

                                    $arrayOpenThread = array_merge($arrayOpenThread, $this->case->getOpenSiblingThreads($nextDel["TAS_UID"], $currentDelegation["APP_UID"], $currentDelegation["DEL_INDEX"], $currentDelegation["TAS_UID"]));



                                    $canDerivate = empty($arrayOpenThread);

                                    break;

                                default:

                                    $canDerivate = true;

                                    break;

                            }

                            break;

                    }



                    if ($canDerivate) {

                        //Throw Message-Events

                        $case = new \ProcessMaker\BusinessModel\Cases();



                        $case->throwMessageEventBetweenElementOriginAndElementDest($currentDelegation["TAS_UID"], $nextDel["TAS_UID"], $appFields);



                        //Throw Email-Events

                        $emailEvent = new \ProcessMaker\BusinessModel\EmailEvent();



                        $emailEvent->emailEventBetweenElementOriginAndElementDest($currentDelegation["TAS_UID"], $nextDel["TAS_UID"], $appFields);



                        //Derivate

                        $aSP = (isset($aSP))? $aSP : null;



                        $taskNextDelAssignType = ($flagTaskNextDelIsMultipleInstance && $flagTaskNextDelAssignTypeIsMultipleInstance)? $taskNextDel->getTasAssignType() : "";



                        switch ($taskNextDelAssignType) {

                            case "MULTIPLE_INSTANCE":

                            case "MULTIPLE_INSTANCE_VALUE_BASED":

                                $arrayUser = $this->getNextAssignedUser(array("APP_UID" => $currentDelegation["APP_UID"], "NEXT_TASK" => $taskNextDel->toArray(BasePeer::TYPE_FIELDNAME)));



                                if (empty($arrayUser)) {

                                    throw new Exception(G::LoadTranslation("ID_NO_USERS"));

                                }



                                foreach ($arrayUser as $value2) {

                                    $currentDelegationAux = array_merge($currentDelegation, array("ROU_TYPE" => "PARALLEL"));

                                    $nextDelAux = array_merge($nextDel, array("USR_UID" => $value2["USR_UID"]));



                                    $iNewDelIndex = $this->doDerivation($currentDelegationAux, $nextDelAux, $appFields, $aSP);



                                    $this->derivateUpdateCounters($currentDelegationAux, $nextDelAux, $taskNextDel, $appFields, $iNewDelIndex, $aSP, $removeList);



                                    $flagUpdateCounters = false;

                                    $removeList = false;

                                }

                                break;

                            default:

                                $iNewDelIndex = $this->doDerivation($currentDelegation, $nextDel, $appFields, $aSP);

                                break;

                        }



                        //Execute Script-Task

                        $scriptTask = new \ProcessMaker\BusinessModel\ScriptTask();



                        $appFields["APP_DATA"] = $scriptTask->execScriptByActivityUid($nextDel["TAS_UID"], $appFields);



                        //Create record in table APP_ASSIGN_SELF_SERVICE_VALUE

                        $regexpTaskTypeToExclude = "SCRIPT-TASK";



                        if (!is_null($taskNextDel) && !preg_match("/^(?:" . $regexpTaskTypeToExclude . ")$/", $taskNextDel->getTasType())) {

                            if ($taskNextDel->getTasAssignType() == "SELF_SERVICE" && trim($taskNextDel->getTasGroupVariable()) != "") {

                                $nextTaskGroupVariable = trim($taskNextDel->getTasGroupVariable(), " @#");



                                if (isset($appFields["APP_DATA"][$nextTaskGroupVariable])) {

                                    $dataVariable = $appFields["APP_DATA"][$nextTaskGroupVariable];

                                    $dataVariable = (is_array($dataVariable))? $dataVariable : trim($dataVariable);



                                    if (!empty($dataVariable)) {

                                        $appAssignSelfServiceValue = new AppAssignSelfServiceValue();



                                        $appAssignSelfServiceValue->create($appFields["APP_UID"], $iNewDelIndex, array("PRO_UID" => $appFields["PRO_UID"], "TAS_UID" => $nextDel["TAS_UID"], "GRP_UID" => serialize($dataVariable)));

                                    }

                                }

                            }

                        }



                        //Check if $taskNextDel is Script-Task

                        if (!is_null($taskNextDel) && $taskNextDel->getTasType() == "SCRIPT-TASK") {

                            $this->case->CloseCurrentDelegation($currentDelegation["APP_UID"], $iNewDelIndex);



                            //Get for $nextDel["TAS_UID"] your next Task

                            $taskNextDelNextDelegations = $this->prepareInformation(array(

                                "USER_UID"  => $_SESSION["USER_LOGGED"],

                                "APP_UID"   => $_SESSION["APPLICATION"],

                                "DEL_INDEX" => $iNewDelIndex

                            ));



                            //New next delegation

                            $newNextDelegation = array();



                            $newNextDelegation[1] = array(

                                "TAS_UID"           => $taskNextDelNextDelegations[1]["NEXT_TASK"]["TAS_UID"],

                                "USR_UID"           => $taskNextDelNextDelegations[1]["NEXT_TASK"]["USER_ASSIGNED"]["USR_UID"],

                                "TAS_ASSIGN_TYPE"   => $taskNextDelNextDelegations[1]["NEXT_TASK"]["TAS_ASSIGN_TYPE"],

                                "TAS_DEF_PROC_CODE" => "",

                                "DEL_PRIORITY"      => "",

                                "TAS_PARENT"        => ""

                            );



                            $this->derivate($currentDelegation, $newNextDelegation, $removeList);

                        }

                    } else {

                        //when the task doesnt generate a new AppDelegation

                        $iAppThreadIndex = $appFields['DEL_THREAD'];



                        $routeType = $currentDelegation["ROU_TYPE"];

                        $routeType = ($flagTaskIsMultipleInstance && $flagTaskAssignTypeIsMultipleInstance)? "SEC-JOIN" : $routeType;



                        switch ($routeType) {

                            case 'SEC-JOIN':

                                $this->case->closeAppThread( $currentDelegation['APP_UID'], $iAppThreadIndex );

                                break;

                            default:

                                if ($currentDelegation['TAS_ASSIGN_TYPE'] == 'STATIC_MI' || $currentDelegation['TAS_ASSIGN_TYPE'] == 'CANCEL_MI') {

                                    $this->case->closeAppThread( $currentDelegation['APP_UID'], $iAppThreadIndex );

                                }

                                break;

                        }

                    }

                    break;

            }



            if ($flagUpdateCounters) {

                $this->derivateUpdateCounters($currentDelegation, $nextDel, $taskNextDel, $appFields, (isset($iNewDelIndex))? $iNewDelIndex : 0, (isset($aSP))? $aSP : null, $removeList);

            }



            $removeList = false;



            unset($aSP);

        }



        /* Start Block : UPDATES APPLICATION */



        //Set THE APP_STATUS

        $appFields['APP_STATUS'] = $currentDelegation['APP_STATUS'];

        /* Start Block : Count the open threads of $currentDelegation['APP_UID'] */

        $openThreads = $this->case->GetOpenThreads( $currentDelegation['APP_UID'] );



        ///////

        $flag = false;



        if ($openThreads == 0) {

            //Close case

            $appFields["APP_STATUS"] = "COMPLETED";

            $appFields["APP_FINISH_DATE"] = "now";

            $this->verifyIsCaseChild($currentDelegation["APP_UID"], $currentDelegation["DEL_INDEX"]);



            $flag = true;

        }



        if (isset( $iNewDelIndex )) {

            $appFields["DEL_INDEX"] = $iNewDelIndex;

            $appFields["TAS_UID"] = $nextDel["TAS_UID"];



            $flag = true;

        }



        if ($flag) {

            //Start Block : UPDATES APPLICATION

            $this->case->updateCase( $currentDelegation["APP_UID"], $appFields );

            //End Block : UPDATES APPLICATION

        }

    }