function pluginCaseSchedulerForm()
{
    if (!isset($_REQUEST['selectedOption'])) {
        die;
    }
    $G_PUBLISH = new Publisher();
    $params = explode("--", $_REQUEST['selectedOption']);
    $oPluginRegistry =& PMPluginRegistry::getSingleton();
    $activePluginsForCaseScheduler = $oPluginRegistry->getCaseSchedulerPlugins();
    foreach ($activePluginsForCaseScheduler as $key => $caseSchedulerPluginDetail) {
        if ($caseSchedulerPluginDetail->sNamespace == $params[0] && $caseSchedulerPluginDetail->sActionId == $params[1]) {
            $caseSchedulerSelected = $caseSchedulerPluginDetail;
        }
    }
    if (isset($caseSchedulerSelected) && is_object($caseSchedulerSelected)) {
        //Render the form
        if (isset($_REQUEST['sch_uid']) && $_REQUEST['sch_uid'] != "") {
            //$oData=$oPluginRegistry->executeMethod( $caseSchedulerPluginDetail->sNamespace, $caseSchedulerPluginDetail->sActionGetFields, array("SCH_UID"=>$_REQUEST['sch_uid']) );
            $oData = array("SCH_UID" => $_REQUEST['sch_uid'], "PRO_UID" => $_REQUEST['pro_uid']);
        } else {
            $oData = array("PRO_UID" => $_REQUEST['pro_uid']);
        }
        $oPluginRegistry->executeMethod($caseSchedulerPluginDetail->sNamespace, $caseSchedulerPluginDetail->sActionForm, $oData);
    }
}
예제 #2
0
 /**
  * __construct
  *
  * @return void     
  */
 function __construct()
 {
     //Initialize the Library and register the Default
     $this->registerFunctionsFileToLibrary(PATH_CORE . "classes" . PATH_SEP . "class.pmFunctions.php", "ProcessMaker Functions");
     //Register all registered PLugin Functions
     if (class_exists('folderData')) {
         //$folderData = new folderData($sProUid, $proFields['PRO_TITLE'], $sAppUid, $Fields['APP_TITLE'], $sUsrUid);
         $oPluginRegistry =& PMPluginRegistry::getSingleton();
         $aAvailablePmFunctions = $oPluginRegistry->getPmFunctions();
         foreach ($aAvailablePmFunctions as $key => $class) {
             $filePlugin = PATH_PLUGINS . $class . PATH_SEP . 'classes' . PATH_SEP . 'class.pmFunctions.php';
             if (file_exists($filePlugin) && !is_dir($filePlugin)) {
                 $this->registerFunctionsFileToLibrary($filePlugin, "ProcessMaker Functions");
             }
         }
     }
     //Add External Triggers
     $dir = G::ExpandPath("classes") . 'triggers';
     $filesArray = array();
     if (file_exists($dir)) {
         if ($handle = opendir($dir)) {
             while (false !== ($file = readdir($handle))) {
                 if ($file != "." && $file != ".." && !is_dir($dir . PATH_SEP . $file)) {
                     $this->registerFunctionsFileToLibrary($dir . PATH_SEP . $file, "ProcessMaker External Functions");
                 }
             }
             closedir($handle);
         }
     }
 }
예제 #3
0
 public function create($data)
 {
     // setting defaults
     $data['PRO_UID'] = array_key_exists('PRO_UID', $data) ? $data['PRO_UID'] : Common::generateUID();
     $data['USR_UID'] = array_key_exists('PRO_CREATE_USER', $data) ? $data['PRO_CREATE_USER'] : null;
     $data['PRO_TITLE'] = array_key_exists('PRO_TITLE', $data) ? trim($data['PRO_TITLE']) : "";
     $data['PRO_CATEGORY'] = array_key_exists('PRO_CATEGORY', $data) ? $data['PRO_CATEGORY'] : "";
     try {
         self::log("Create Process with data:", $data);
         //validate if process with specified name already exists
         if (Process::existsByProTitle($data["PRO_TITLE"])) {
             throw new Exception\ProjectAlreadyExists($this, $data["PRO_TITLE"]);
         }
         // Create project
         $process = new Process();
         $this->proUid = $process->create($data, false);
         // Call Plugins
         $pluginData['PRO_UID'] = $this->proUid;
         $pluginData['PRO_TEMPLATE'] = empty($data["PRO_TEMPLATE"]) ? "" : $data["PRO_TEMPLATE"];
         $pluginData['PROCESSMAP'] = null;
         $pluginRegistry = \PMPluginRegistry::getSingleton();
         $pluginRegistry->executeTriggers(PM_NEW_PROCESS_SAVE, $pluginData);
         // Save Calendar ID for this process
         if (!empty($data["PRO_CALENDAR"])) {
             //G::LoadClass( "calendar" );
             $calendar = new \Calendar();
             $calendar->assignCalendarTo($this->proUid, $data["PRO_CALENDAR"], 'PROCESS');
         }
         self::log("Create Process Success!");
     } catch (\Exception $e) {
         self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
         throw $e;
     }
 }
예제 #4
0
 public function saveProcess()
 {
     try {
         require_once 'classes/model/Task.php';
         G::LoadClass('processMap');
         $oProcessMap = new ProcessMap();
         if (!isset($_POST['PRO_UID'])) {
             if (Process::existsByProTitle($_POST['PRO_TITLE'])) {
                 $result = array('success' => false, 'msg' => 'Process Save Error', 'errors' => array('PRO_TITLE' => G::LoadTranslation('ID_PROCESSTITLE_ALREADY_EXISTS', SYS_LANG, $_POST)));
                 print G::json_encode($result);
                 exit(0);
             }
             $processData['USR_UID'] = $_SESSION['USER_LOGGED'];
             $processData['PRO_TITLE'] = $_POST['PRO_TITLE'];
             $processData['PRO_DESCRIPTION'] = $_POST['PRO_DESCRIPTION'];
             $processData['PRO_CATEGORY'] = $_POST['PRO_CATEGORY'];
             $sProUid = $oProcessMap->createProcess($processData);
             //call plugins
             $oData['PRO_UID'] = $sProUid;
             $oData['PRO_TEMPLATE'] = isset($_POST['PRO_TEMPLATE']) && $_POST['PRO_TEMPLATE'] != '' ? $_POST['form']['PRO_TEMPLATE'] : '';
             $oData['PROCESSMAP'] = $oProcessMap;
             $oPluginRegistry =& PMPluginRegistry::getSingleton();
             $oPluginRegistry->executeTriggers(PM_NEW_PROCESS_SAVE, $oData);
         } else {
             //$oProcessMap->updateProcess($_POST['form']);
             $sProUid = $_POST['PRO_UID'];
         }
         //Save Calendar ID for this process
         if (isset($_POST['PRO_CALENDAR'])) {
             G::LoadClass("calendar");
             $calendarObj = new Calendar();
             $calendarObj->assignCalendarTo($sProUid, $_POST['PRO_CALENDAR'], 'PROCESS');
         }
         $result->success = true;
         $result->PRO_UID = $sProUid;
         $result->msg = G::LoadTranslation('ID_CREATE_PROCESS_SUCCESS');
     } catch (Exception $e) {
         $result->success = false;
         $result->msg = $e->getMessage();
     }
     print G::json_encode($result);
 }
function getRegisteredDashboards()
{
    $oPluginRegistry =& PMPluginRegistry::getSingleton();
    $dashBoardPages = $oPluginRegistry->getDashboardPages();
    print_r(G::json_encode($dashBoardPages));
}
예제 #6
0
 /**
  * Get available Steps of a Task
  *
  * @param string $taskUid Unique id of Task
  *
  * return array Return an array with the Steps available of a Task
  */
 public function getAvailableSteps($taskUid)
 {
     try {
         $arrayAvailableStep = array();
         //Verify data
         $this->throwExceptionIfNotExistsTask("", $taskUid, $this->arrayParamException["taskUid"]);
         //Load Task
         $task = new \Task();
         $arrayTaskData = $task->load($taskUid);
         $processUid = $arrayTaskData["PRO_UID"];
         //Get data
         //Get Uids
         $arrayUid = array();
         $task = new \Tasks();
         $arrayStep = $task->getStepsOfTask($taskUid);
         foreach ($arrayStep as $step) {
             $arrayUid[] = $step["STEP_UID_OBJ"];
         }
         //Array DB
         $arraydbStep = array();
         $delimiter = \DBAdapter::getStringDelimiter();
         //DynaForms
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\DynaformPeer::DYN_UID);
         $criteria->addAsColumn("DYN_TITLE", "CT.CON_VALUE");
         $criteria->addAsColumn("DYN_DESCRIPTION", "CD.CON_VALUE");
         $criteria->addAlias("CT", \ContentPeer::TABLE_NAME);
         $criteria->addAlias("CD", \ContentPeer::TABLE_NAME);
         $arrayCondition = array();
         $arrayCondition[] = array(\DynaformPeer::DYN_UID, "CT.CON_ID", \Criteria::EQUAL);
         $arrayCondition[] = array("CT.CON_CATEGORY", $delimiter . "DYN_TITLE" . $delimiter, \Criteria::EQUAL);
         $arrayCondition[] = array("CT.CON_LANG", $delimiter . SYS_LANG . $delimiter, \Criteria::EQUAL);
         $criteria->addJoinMC($arrayCondition, \Criteria::LEFT_JOIN);
         $arrayCondition = array();
         $arrayCondition[] = array(\DynaformPeer::DYN_UID, "CD.CON_ID", \Criteria::EQUAL);
         $arrayCondition[] = array("CD.CON_CATEGORY", $delimiter . "DYN_DESCRIPTION" . $delimiter, \Criteria::EQUAL);
         $arrayCondition[] = array("CD.CON_LANG", $delimiter . SYS_LANG . $delimiter, \Criteria::EQUAL);
         $criteria->addJoinMC($arrayCondition, \Criteria::LEFT_JOIN);
         $criteria->add(\DynaformPeer::PRO_UID, $processUid, \Criteria::EQUAL);
         $criteria->add(\DynaformPeer::DYN_UID, $arrayUid, \Criteria::NOT_IN);
         $criteria->add(\DynaformPeer::DYN_TYPE, "xmlform", \Criteria::EQUAL);
         $rsCriteria = \DynaformPeer::doSelectRS($criteria);
         $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
         while ($rsCriteria->next()) {
             $row = $rsCriteria->getRow();
             if ($row["DYN_TITLE"] . "" == "") {
                 //There is no transaltion for this Document name, try to get/regenerate the label
                 $row["DYN_TITLE"] = \Content::Load("DYN_TITLE", "", $row["DYN_UID"], SYS_LANG);
             }
             $arraydbStep[] = array($this->getFieldNameByFormatFieldName("OBJ_UID") => $row["DYN_UID"], $this->getFieldNameByFormatFieldName("OBJ_TITLE") => $row["DYN_TITLE"], $this->getFieldNameByFormatFieldName("OBJ_DESCRIPTION") => $row["DYN_DESCRIPTION"], $this->getFieldNameByFormatFieldName("OBJ_TYPE") => "DYNAFORM");
         }
         //InputDocuments
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\InputDocumentPeer::INP_DOC_UID);
         $criteria->addAsColumn("INP_DOC_TITLE", "CT.CON_VALUE");
         $criteria->addAsColumn("INP_DOC_DESCRIPTION", "CD.CON_VALUE");
         $criteria->addAlias("CT", \ContentPeer::TABLE_NAME);
         $criteria->addAlias("CD", \ContentPeer::TABLE_NAME);
         $arrayCondition = array();
         $arrayCondition[] = array(\InputDocumentPeer::INP_DOC_UID, "CT.CON_ID", \Criteria::EQUAL);
         $arrayCondition[] = array("CT.CON_CATEGORY", $delimiter . "INP_DOC_TITLE" . $delimiter, \Criteria::EQUAL);
         $arrayCondition[] = array("CT.CON_LANG", $delimiter . SYS_LANG . $delimiter, \Criteria::EQUAL);
         $criteria->addJoinMC($arrayCondition, \Criteria::LEFT_JOIN);
         $arrayCondition = array();
         $arrayCondition[] = array(\InputDocumentPeer::INP_DOC_UID, "CD.CON_ID", \Criteria::EQUAL);
         $arrayCondition[] = array("CD.CON_CATEGORY", $delimiter . "INP_DOC_DESCRIPTION" . $delimiter, \Criteria::EQUAL);
         $arrayCondition[] = array("CD.CON_LANG", $delimiter . SYS_LANG . $delimiter, \Criteria::EQUAL);
         $criteria->addJoinMC($arrayCondition, \Criteria::LEFT_JOIN);
         $criteria->add(\InputDocumentPeer::PRO_UID, $processUid, \Criteria::EQUAL);
         $criteria->add(\InputDocumentPeer::INP_DOC_UID, $arrayUid, \Criteria::NOT_IN);
         $rsCriteria = \InputDocumentPeer::doSelectRS($criteria);
         $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
         while ($rsCriteria->next()) {
             $row = $rsCriteria->getRow();
             if ($row["INP_DOC_TITLE"] . "" == "") {
                 //There is no transaltion for this Document name, try to get/regenerate the label
                 $row["INP_DOC_TITLE"] = \Content::Load("INP_DOC_TITLE", "", $row["INP_DOC_UID"], SYS_LANG);
             }
             $arraydbStep[] = array($this->getFieldNameByFormatFieldName("OBJ_UID") => $row["INP_DOC_UID"], $this->getFieldNameByFormatFieldName("OBJ_TITLE") => $row["INP_DOC_TITLE"], $this->getFieldNameByFormatFieldName("OBJ_DESCRIPTION") => $row["INP_DOC_DESCRIPTION"], $this->getFieldNameByFormatFieldName("OBJ_TYPE") => "INPUT_DOCUMENT");
         }
         //OutputDocuments
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\OutputDocumentPeer::OUT_DOC_UID);
         $criteria->addAsColumn("OUT_DOC_TITLE", "CT.CON_VALUE");
         $criteria->addAsColumn("OUT_DOC_DESCRIPTION", "CD.CON_VALUE");
         $criteria->addAlias("CT", \ContentPeer::TABLE_NAME);
         $criteria->addAlias("CD", \ContentPeer::TABLE_NAME);
         $arrayCondition = array();
         $arrayCondition[] = array(\OutputDocumentPeer::OUT_DOC_UID, "CT.CON_ID", \Criteria::EQUAL);
         $arrayCondition[] = array("CT.CON_CATEGORY", $delimiter . "OUT_DOC_TITLE" . $delimiter, \Criteria::EQUAL);
         $arrayCondition[] = array("CT.CON_LANG", $delimiter . SYS_LANG . $delimiter, \Criteria::EQUAL);
         $criteria->addJoinMC($arrayCondition, \Criteria::LEFT_JOIN);
         $arrayCondition = array();
         $arrayCondition[] = array(\OutputDocumentPeer::OUT_DOC_UID, "CD.CON_ID", \Criteria::EQUAL);
         $arrayCondition[] = array("CD.CON_CATEGORY", $delimiter . "OUT_DOC_DESCRIPTION" . $delimiter, \Criteria::EQUAL);
         $arrayCondition[] = array("CD.CON_LANG", $delimiter . SYS_LANG . $delimiter, \Criteria::EQUAL);
         $criteria->addJoinMC($arrayCondition, \Criteria::LEFT_JOIN);
         $criteria->add(\OutputDocumentPeer::PRO_UID, $processUid, \Criteria::EQUAL);
         $criteria->add(\OutputDocumentPeer::OUT_DOC_UID, $arrayUid, \Criteria::NOT_IN);
         $rsCriteria = \OutputDocumentPeer::doSelectRS($criteria);
         $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
         while ($rsCriteria->next()) {
             $row = $rsCriteria->getRow();
             if ($row["OUT_DOC_TITLE"] . "" == "") {
                 //There is no transaltion for this Document name, try to get/regenerate the label
                 $row["OUT_DOC_TITLE"] = \Content::Load("OUT_DOC_TITLE", "", $row["OUT_DOC_UID"], SYS_LANG);
             }
             $arraydbStep[] = array($this->getFieldNameByFormatFieldName("OBJ_UID") => $row["OUT_DOC_UID"], $this->getFieldNameByFormatFieldName("OBJ_TITLE") => $row["OUT_DOC_TITLE"], $this->getFieldNameByFormatFieldName("OBJ_DESCRIPTION") => $row["OUT_DOC_DESCRIPTION"], $this->getFieldNameByFormatFieldName("OBJ_TYPE") => "OUTPUT_DOCUMENT");
         }
         //Call plugin
         $pluginRegistry =& \PMPluginRegistry::getSingleton();
         $externalSteps = $pluginRegistry->getSteps();
         if (is_array($externalSteps) && count($externalSteps) > 0) {
             foreach ($externalSteps as $key => $value) {
                 $arraydbStep[] = array($this->getFieldNameByFormatFieldName("OBJ_UID") => $value->sStepId, $this->getFieldNameByFormatFieldName("OBJ_TITLE") => $value->sStepTitle, $this->getFieldNameByFormatFieldName("OBJ_DESCRIPTION") => "", $this->getFieldNameByFormatFieldName("OBJ_TYPE") => "EXTERNAL");
             }
         }
         if (!empty($arraydbStep)) {
             $arraydbStep = Util\ArrayUtil::sort($arraydbStep, array($this->getFieldNameByFormatFieldName("OBJ_TYPE"), $this->getFieldNameByFormatFieldName("OBJ_TITLE")), SORT_ASC);
         }
         return $arraydbStep;
     } catch (\Exception $e) {
         throw $e;
     }
 }
예제 #7
0
 /**
  * This method allow dispatch rest services using 'Restler' thirdparty library
  *
  * @author Erik Amaru Ortiz <*****@*****.**>
  */
 public function dispatchRestService($uri, $config, $apiClassesPath = '')
 {
     require_once 'restler/restler.php';
     $rest = new Restler();
     $rest->setSupportedFormats('JsonFormat', 'XmlFormat');
     // getting all services class
     $restClasses = array();
     $restClassesList = G::rglob('*', 0, PATH_CORE . 'services/');
     foreach ($restClassesList as $classFile) {
         if (substr($classFile, -4) === '.php') {
             $restClasses[str_replace('.php', '', basename($classFile))] = $classFile;
         }
     }
     if (!empty($apiClassesPath)) {
         $pluginRestClasses = array();
         $restClassesList = G::rglob('*', 0, $apiClassesPath . 'services/');
         foreach ($restClassesList as $classFile) {
             if (substr($classFile, -4) === '.php') {
                 $pluginRestClasses[str_replace('.php', '', basename($classFile))] = $classFile;
             }
         }
         $restClasses = array_merge($restClasses, $pluginRestClasses);
     }
     // hook to get rest api classes from plugins
     if (class_exists('PMPluginRegistry')) {
         $pluginRegistry =& PMPluginRegistry::getSingleton();
         $pluginClasses = $pluginRegistry->getRegisteredRestClassFiles();
         $restClasses = array_merge($restClasses, $pluginClasses);
     }
     foreach ($restClasses as $key => $classFile) {
         if (!file_exists($classFile)) {
             unset($restClasses[$key]);
             continue;
         }
         //load the file, and check if exist the class inside it.
         require_once $classFile;
         $namespace = 'Services_Rest_';
         $className = str_replace('.php', '', basename($classFile));
         // if the core class does not exists try resolve the for a plugin
         if (!class_exists($namespace . $className)) {
             $namespace = 'Plugin_Services_Rest_';
             // Couldn't resolve the class name, just skipp it
             if (!class_exists($namespace . $className)) {
                 unset($restClasses[$key]);
                 continue;
             }
         }
         // verify if there is an auth class implementing 'iAuthenticate'
         $classNameAuth = $namespace . $className;
         $reflClass = new ReflectionClass($classNameAuth);
         // that wasn't from plugin
         if ($reflClass->implementsInterface('iAuthenticate') && $namespace != 'Plugin_Services_Rest_') {
             // auth class found, set as restler authentication class handler
             $rest->addAuthenticationClass($classNameAuth);
         } else {
             // add api class
             $rest->addAPIClass($classNameAuth);
         }
     }
     //end foreach rest class
     // resolving the class for current request
     $uriPart = explode('/', $uri);
     $requestedClass = '';
     if (isset($uriPart[1])) {
         $requestedClass = ucfirst($uriPart[1]);
     }
     if (class_exists('Services_Rest_' . $requestedClass)) {
         $namespace = 'Services_Rest_';
     } elseif (class_exists('Plugin_Services_Rest_' . $requestedClass)) {
         $namespace = 'Plugin_Services_Rest_';
     } else {
         $namespace = '';
     }
     // end resolv.
     // Send additional headers (if exists) configured on rest-config.ini
     if (array_key_exists('HEADERS', $config)) {
         foreach ($config['HEADERS'] as $name => $value) {
             header("{$name}: {$value}");
         }
     }
     // to handle a request with "OPTIONS" method
     if (!empty($namespace) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
         $reflClass = new ReflectionClass($namespace . $requestedClass);
         // if the rest class has not a "options" method
         if (!$reflClass->hasMethod('options')) {
             header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEADERS');
             header('Access-Control-Allow-Headers: authorization, content-type');
             header("Access-Control-Allow-Credentials", "false");
             header('Access-Control-Max-Age: 60');
             exit;
         }
     }
     // override global REQUEST_URI to pass to Restler library
     $_SERVER['REQUEST_URI'] = '/' . strtolower($namespace) . ltrim($uri, '/');
     // handle the rest request
     $rest->handle();
 }
예제 #8
0
    public function caseSchedulerCron ($date, &$log = array(), $cron = 0)
    {
        try {
            require_once("classes" . PATH_SEP . "model" . PATH_SEP . "LogCasesScheduler.php");

            //Set variables
            $port = "";

            if (isset($_SERVER["SERVER_PORT"])) {
                $port = ($_SERVER["SERVER_PORT"] . "" != "80")? ":" . $_SERVER["SERVER_PORT"] : "";
            } else {
                if (defined("SERVER_PORT")) {
                    $port = (SERVER_PORT . "" != "80")? ":" . SERVER_PORT : "";
                }
            }

            $wsdl = "http://" . SERVER_NAME . $port . "/sys" . SYS_SYS . "/" . SYS_LANG . "/classic/services/wsdl2";

            $timeDate = strtotime($date);

            $dateHour    = date("H", $timeDate);
            $dateMinutes = date("i", $timeDate);

            $dateCurrentIni = date("Y-m-d", $timeDate) . " 00:00:00";
            $dateCurrentEnd = date("Y-m-d", $timeDate) . " 23:59:59";

            //Query
            $criteria = $this->getAllCriteria();

            $criteria->add(
                $criteria->getNewCriterion(CaseSchedulerPeer::SCH_STATE, "INACTIVE", Criteria::NOT_EQUAL)->addAnd(
                $criteria->getNewCriterion(CaseSchedulerPeer::SCH_STATE, "PROCESSED", Criteria::NOT_EQUAL))
            );
            $criteria->add(
                $criteria->getNewCriterion(CaseSchedulerPeer::SCH_TIME_NEXT_RUN, $dateCurrentIni, Criteria::GREATER_EQUAL)->addAnd(
                $criteria->getNewCriterion(CaseSchedulerPeer::SCH_TIME_NEXT_RUN, $dateCurrentEnd, Criteria::LESS_EQUAL))->addOr(
                //$criteria->getNewCriterion(CaseSchedulerPeer::SCH_OPTION, 5, Criteria::GREATER_EQUAL))->addOr(

                $criteria->getNewCriterion(CaseSchedulerPeer::SCH_TIME_NEXT_RUN, $dateCurrentIni, Criteria::LESS_THAN))
            );
            $criteria->add(
                $criteria->getNewCriterion(CaseSchedulerPeer::SCH_END_DATE, null, Criteria::EQUAL)->addOr(
                $criteria->getNewCriterion(CaseSchedulerPeer::SCH_END_DATE, $dateCurrentIni, Criteria::GREATER_EQUAL))
            );

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

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

                if ($cron == 1) {
                    $arrayCron = unserialize(trim(@file_get_contents(PATH_DATA . "cron")));
                    $arrayCron["processcTimeStart"] = time();
                    @file_put_contents(PATH_DATA . "cron", serialize($arrayCron));
                }

                $caseSchedulerUid    = $row["SCH_UID"];
                $caseSchedulerOption = (int)($row["SCH_OPTION"]);
                $caseSchedulerTimeNextRun = $row["SCH_TIME_NEXT_RUN"];

                //Create the new case
                $flagNewCase = false;
                $caseSchedulerTimeNextRunNew = "";

                if (strtotime($caseSchedulerTimeNextRun) < strtotime($dateCurrentIni)) {
                    //Generate new date for old SCH_TIME_NEXT_RUN
                    $flagNewCase = true; //Create the old case
                    $caseSchedulerTimeNextRunNew = $this->getTimeNextRunByDate($row, $date, false);
                } else {
                    $caseSchedulerTimeNextRunHour    = date("H", strtotime($row["SCH_TIME_NEXT_RUN"]));
                    $caseSchedulerTimeNextRunMinutes = date("i", strtotime($row["SCH_TIME_NEXT_RUN"]));

                    if ((int)($dateHour . $dateMinutes) <= (int)($caseSchedulerTimeNextRunHour . $caseSchedulerTimeNextRunMinutes)) {
                        $flagNewCase = $caseSchedulerTimeNextRunHour == $dateHour && $caseSchedulerTimeNextRunMinutes == $dateMinutes;
                    } else {
                        $flagNewCase = true; //Create the old case
                    }
                }

                if ($flagNewCase) {
                    println("  CASE SCHEDULER: " . $row["SCH_NAME"]);
                    println("  - Connecting webservice: $wsdl");

                    $user = $row["SCH_DEL_USER_NAME"];
                    $pass = $row["SCH_DEL_USER_PASS"];
                    $processId = $row["PRO_UID"];
                    $taskId = $row["TAS_UID"];

                    $client = new SoapClient($wsdl);
                    $result = $client->__SoapCall("login",
                        array(
                            array("userid" => $user, "password" => Bootstrap::getPasswordHashType() . ":" . $pass)
                        )
                    );

                    eprintln("  - Logging as user \"$user\"...");

                    $paramsLog = array(
                        "PRO_UID"   => $processId,
                        "TAS_UID"   => $taskId,
                        "SCH_UID"   => $caseSchedulerUid,
                        "USR_NAME"  => $user,
                        "RESULT"    => "",
                        "EXEC_DATE" => date("Y-m-d"),
                        "EXEC_HOUR" => date("H:i:s"),
                        "WS_CREATE_CASE_STATUS" => "",
                        "WS_ROUTE_CASE_STATUS"  => ""
                    );

                    $paramsLogResult = "FAILED";
                    $paramsRouteLogResult = "FAILED";

                    if ($result->status_code == 0) {
                        eprintln("    OK", "green");

                        $sessionId = $result->message;

                        $params = array("sessionId" => $sessionId, "processId" => $processId, "taskId" => $taskId, "variables" => array());

                        //If this Job was was registered to be performed by a plugin
                        if (isset($row["CASE_SH_PLUGIN_UID"]) && $row["CASE_SH_PLUGIN_UID"] != "") {
                            //Check if the plugin is active
                            $pluginParts = explode("--", $row["CASE_SH_PLUGIN_UID"]);

                            if (count($pluginParts) == 2) {
                                //Plugins
                                G::LoadClass("plugin");

                                //Here we are loading all plugins registered
                                //The singleton has a list of enabled plugins
                                $sSerializedFile = PATH_DATA_SITE . "plugin.singleton";
                                $oPluginRegistry = &PMPluginRegistry::getSingleton();

                                if (file_exists($sSerializedFile)) {
                                    $oPluginRegistry->unSerializeInstance(file_get_contents($sSerializedFile));
                                }

                                $oPluginRegistry = &PMPluginRegistry::getSingleton();
                                $activePluginsForCaseScheduler = $oPluginRegistry->getCaseSchedulerPlugins();

                                foreach ($activePluginsForCaseScheduler as $key => $caseSchedulerPlugin) {
                                    if (isset($caseSchedulerPlugin->sNamespace) && $caseSchedulerPlugin->sNamespace == $pluginParts[0] && isset($caseSchedulerPlugin->sActionId) && $caseSchedulerPlugin->sActionId == $pluginParts[1]) {
                                        $caseSchedulerSelected = $caseSchedulerPlugin;
                                    }
                                }
                            }
                        }

                        //If there is a trigger that is registered to do this then transfer control
                        if (isset($caseSchedulerSelected) && is_object($caseSchedulerSelected)) {
                            eprintln("  - Transfering control to a Plugin: " . $caseSchedulerSelected->sNamespace . "/" . $caseSchedulerSelected->sActionId, "green");

                            $oData = array();
                            $oData["OBJ_SOAP"] = $client;
                            $oData["SCH_UID"] = $row["SCH_UID"];
                            $oData["params"] = $params;
                            $oData["sessionId"] = $sessionId;
                            $oData["userId"] = $user;

                            $paramsLogResultFromPlugin = $oPluginRegistry->executeMethod($caseSchedulerSelected->sNamespace, $caseSchedulerSelected->sActionExecute, $oData);
                            $paramsLog["WS_CREATE_CASE_STATUS"] = $paramsLogResultFromPlugin["WS_CREATE_CASE_STATUS"];
                            $paramsLog["WS_ROUTE_CASE_STATUS"] = $paramsLogResultFromPlugin["WS_ROUTE_CASE_STATUS"];

                            $paramsLogResult = $paramsLogResultFromPlugin["paramsLogResult"];
                            $paramsRouteLogResult = $paramsLogResultFromPlugin["paramsRouteLogResult"];
                        } else {
                            eprintln("  - Creating the new case...");

                            $paramsAux = $params;
                            $paramsAux["executeTriggers"] = 1;

                            $oPluginRegistry = &PMPluginRegistry::getSingleton();

                            if ($oPluginRegistry->existsTrigger(PM_SCHEDULER_CREATE_CASE_BEFORE)) {
                                $oPluginRegistry->executeTriggers(PM_SCHEDULER_CREATE_CASE_BEFORE, $paramsAux);
                            }

                            $result = $client->__SoapCall("NewCase", array($paramsAux));

                            if ($oPluginRegistry->existsTrigger (PM_SCHEDULER_CREATE_CASE_AFTER)) {
                                $oPluginRegistry->executeTriggers(PM_SCHEDULER_CREATE_CASE_AFTER, $result);
                            }

                            if ($result->status_code == 0) {
                                eprintln("    OK case #" . $result->caseNumber . " was created!", "green");

                                $caseId = $result->caseId;
                                $caseNumber = $result->caseNumber;
                                $log[] = $caseNumber . " was created!, ProcessID: " . $row["PRO_UID"];
                                $paramsLog["WS_CREATE_CASE_STATUS"] = "Case " . $caseNumber . " " . strip_tags($result->message);
                                $paramsLogResult = "SUCCESS";
                                $params = array("sessionId" => $sessionId, "caseId" => $caseId, "delIndex" => "1");

                                try {
                                    eprintln("  - Routing the case #$caseNumber...");

                                    $result = $client->__SoapCall("RouteCase", array($params));

                                    if ($result->status_code == 0) {
                                        $paramsLog["WS_ROUTE_CASE_STATUS"] = strip_tags($result->message);
                                        $retMsg = explode("Debug", $paramsLog["WS_ROUTE_CASE_STATUS"]);
                                        $retMsg = $retMsg[0];
                                        $paramsRouteLogResult = "SUCCESS";

                                        eprintln("    OK $retMsg", "green");
                                    } else {
                                        $paramsLog["WS_ROUTE_CASE_STATUS"] = strip_tags($result->message);
                                        $paramsRouteLogResult = "FAILED";

                                        eprintln("    Failed: " . $paramsLog["WS_ROUTE_CASE_STATUS"], "red");
                                    }
                                } catch (Exception $e) {
                                    //setExecutionResultMessage("WITH ERRORS", "error");
                                    $paramsLog["WS_ROUTE_CASE_STATUS"] = strip_tags($e->getMessage());
                                    $paramsRouteLogResult = "FAILED";

                                    eprintln("    Failed: " . strip_tags($e->getMessage()), "red");
                                }
                            } else {
                                $paramsLog["WS_CREATE_CASE_STATUS"] = strip_tags($result->message);
                                $paramsLogResult = "FAILED";

                                eprintln("    Failed: " . $paramsLog["WS_CREATE_CASE_STATUS"], "red");
                            }
                        }
                    } else {
                        //Invalid user or bad password
                        eprintln("    " . $result->message, "red");
                    }

                    if ($paramsLogResult == "SUCCESS" && $paramsRouteLogResult == "SUCCESS") {
                        $paramsLog["RESULT"] = "SUCCESS";
                    } else {
                        $paramsLog["RESULT"] = "FAILED";
                    }

                    $newCaseLog = new LogCasesScheduler();
                    $newCaseLog->saveLogParameters($paramsLog);
                    $newCaseLog->save();

                    //Update the SCH_TIME_NEXT_RUN field
                    switch ($caseSchedulerOption) {
                        case 1:
                        case 2:
                        case 3:
                            //Daily
                            //Weekly
                            //Monthly
                            if ($caseSchedulerTimeNextRunNew == "") {
                                list($value, $daysPerformTask, $weeks, $startDay, $months) = $this->getVariablesFromRecord($row);

                                $caseSchedulerTimeNextRunNew = $this->updateNextRun($caseSchedulerOption, $value, $caseSchedulerTimeNextRun, $daysPerformTask, $weeks, $startDay, $months);
                            }

                            if ($row["SCH_END_DATE"] . "" != "" && strtotime($row["SCH_END_DATE"]) < strtotime($caseSchedulerTimeNextRunNew)) {
                                $result = $this->update(array(
                                    "SCH_UID"           => $caseSchedulerUid,
                                    "SCH_LAST_STATE"    => $row["SCH_STATE"],
                                    "SCH_LAST_RUN_TIME" => $caseSchedulerTimeNextRun,
                                    "SCH_STATE"         => "PROCESSED"
                                ));
                            } else {
                                $this->updateDate($caseSchedulerUid, $caseSchedulerTimeNextRunNew, $caseSchedulerTimeNextRun);
                            }
                            break;
                        case 4:
                            //One time only
                            $result = $this->update(array(
                                "SCH_UID"           => $caseSchedulerUid,
                                "SCH_LAST_STATE"    => $row["SCH_STATE"],
                                "SCH_LAST_RUN_TIME" => $caseSchedulerTimeNextRun,
                                "SCH_STATE"         => "PROCESSED"
                            ));
                            break;
                        case 5:
                            //Every
                            if ($caseSchedulerTimeNextRunNew == "") {
                                $caseSchedulerTimeNextRunNew = date("Y-m-d H:i:s", $timeDate + round(floatval($row["SCH_REPEAT_EVERY"]) * 60 * 60));
                            }

                            $this->updateDate($caseSchedulerUid, $caseSchedulerTimeNextRunNew, $caseSchedulerTimeNextRun);
                            break;
                    }
                }
            }
        } catch (Exception $e) {
            throw $e;
        }
    }
예제 #9
0
 /**
  * create an application delegation
  *
  * @param $sProUid process Uid
  * @param $sAppUid Application Uid
  * @param $sTasUid Task Uid
  * @param $sUsrUid User Uid
  * @param $iPriority delegation priority
  * @param $isSubprocess is a subprocess inside a process?
  * @return delegation index of the application delegation.
  */
 public function createAppDelegation($sProUid, $sAppUid, $sTasUid, $sUsrUid, $sAppThread, $iPriority = 3, $isSubprocess = false, $sPrevious = -1, $sNextTasParam = null)
 {
     if (!isset($sProUid) || strlen($sProUid) == 0) {
         throw new Exception('Column "PRO_UID" cannot be null.');
     }
     if (!isset($sAppUid) || strlen($sAppUid) == 0) {
         throw new Exception('Column "APP_UID" cannot be null.');
     }
     if (!isset($sTasUid) || strlen($sTasUid) == 0) {
         throw new Exception('Column "TAS_UID" cannot be null.');
     }
     if (!isset($sUsrUid)) {
         throw new Exception('Column "USR_UID" cannot be null.');
     }
     if (!isset($sAppThread) || strlen($sAppThread) == 0) {
         throw new Exception('Column "APP_THREAD" cannot be null.');
     }
     //Get max DEL_INDEX
     $criteria = new Criteria("workflow");
     $criteria->add(AppDelegationPeer::APP_UID, $sAppUid);
     $criteria->add(AppDelegationPeer::DEL_LAST_INDEX, 1);
     $criteriaIndex = clone $criteria;
     $rs = AppDelegationPeer::doSelectRS($criteriaIndex);
     $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
     $delIndex = 1;
     if ($rs->next()) {
         $row = $rs->getRow();
         $delIndex = isset($row["DEL_INDEX"]) ? $row["DEL_INDEX"] + 1 : 1;
     } else {
         $criteriaDelIndex = new Criteria("workflow");
         $criteriaDelIndex->addSelectColumn(AppDelegationPeer::DEL_INDEX);
         $criteriaDelIndex->addSelectColumn(AppDelegationPeer::DEL_DELEGATE_DATE);
         $criteriaDelIndex->add(AppDelegationPeer::APP_UID, $sAppUid);
         $criteriaDelIndex->addDescendingOrderByColumn(AppDelegationPeer::DEL_DELEGATE_DATE);
         $rsCriteriaDelIndex = AppDelegationPeer::doSelectRS($criteriaDelIndex);
         $rsCriteriaDelIndex->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         if ($rsCriteriaDelIndex->next()) {
             $row = $rsCriteriaDelIndex->getRow();
             $delIndex = isset($row["DEL_INDEX"]) ? $row["DEL_INDEX"] + 1 : 1;
         }
     }
     //Update set
     $criteriaUpdate = new Criteria('workflow');
     $criteriaUpdate->add(AppDelegationPeer::DEL_LAST_INDEX, 0);
     BasePeer::doUpdate($criteria, $criteriaUpdate, Propel::getConnection('workflow'));
     $this->setAppUid($sAppUid);
     $this->setProUid($sProUid);
     $this->setTasUid($sTasUid);
     $this->setDelIndex($delIndex);
     $this->setDelLastIndex(1);
     $this->setDelPrevious($sPrevious == -1 ? 0 : $sPrevious);
     $this->setUsrUid($sUsrUid);
     $this->setDelType('NORMAL');
     $this->setDelPriority($iPriority != '' ? $iPriority : '3');
     $this->setDelThread($sAppThread);
     $this->setDelThreadStatus('OPEN');
     $this->setDelDelegateDate('now');
     //The function return an array now.  By JHL
     $delTaskDueDate = $this->calculateDueDate($sNextTasParam);
     $this->setDelTaskDueDate($delTaskDueDate['DUE_DATE']);
     // Due date formatted
     if (defined("DEBUG_CALENDAR_LOG") && DEBUG_CALENDAR_LOG) {
         $this->setDelData($delTaskDueDate['DUE_DATE_LOG']);
         // Log of actions made by Calendar Engine
     } else {
         $this->setDelData('');
     }
     // this condition assures that an internal delegation like a subprocess dont have an initial date setted
     if ($delIndex == 1 && !$isSubprocess) {
         //the first delegation, init date this should be now for draft applications, in other cases, should be null.
         $this->setDelInitDate('now');
     }
     if ($this->validate()) {
         try {
             $res = $this->save();
         } catch (PropelException $e) {
             throw $e;
         }
     } else {
         // Something went wrong. We can now get the validationFailures and handle them.
         $msg = '';
         $validationFailuresArray = $this->getValidationFailures();
         foreach ($validationFailuresArray as $objValidationFailure) {
             $msg .= $objValidationFailure->getMessage() . "<br/>";
         }
         throw new Exception('Failed Data validation. ' . $msg);
     }
     $delIndex = $this->getDelIndex();
     // Hook for the trigger PM_CREATE_NEW_DELEGATION
     if (defined('PM_CREATE_NEW_DELEGATION')) {
         $data = new stdclass();
         $data->TAS_UID = $sTasUid;
         $data->APP_UID = $sAppUid;
         $data->DEL_INDEX = $delIndex;
         $data->USR_UID = $sUsrUid;
         $oPluginRegistry =& PMPluginRegistry::getSingleton();
         $oPluginRegistry->executeTriggers(PM_CREATE_NEW_DELEGATION, $data);
     }
     return $delIndex;
 }
예제 #10
0
 /**
  * Function renderExtJs
  * this function returns the content rendered using ExtJs
  * extJsContent have an array, and we iterate this array to draw the content
  *
  * @author Fernando Ontiveros <*****@*****.**>
  * @access public
  * @return string
  */
 public function renderExtJs()
 {
     $body = '';
     if (isset($this->extJsContent) && is_array($this->extJsContent)) {
         foreach ($this->extJsContent as $key => $file) {
             $sPath = PATH_TPL;
             //if the template  file doesn't exists, then try with the plugins folders
             if (!is_file($sPath . $file . ".html")) {
                 $aux = explode(PATH_SEP, $file);
                 //check if G_PLUGIN_CLASS is defined, because publisher can be called without an environment
                 if (count($aux) == 2 && defined('G_PLUGIN_CLASS')) {
                     $oPluginRegistry =& PMPluginRegistry::getSingleton();
                     if ($oPluginRegistry->isRegisteredFolder($aux[0])) {
                         $sPath = PATH_PLUGINS;
                     }
                 }
             }
             $template = new TemplatePower($sPath . $file . '.html');
             $template->prepare();
             foreach ($this->getVars() as $k => $v) {
                 $template->assign($k, $v);
             }
             $body .= $template->getOutputContent();
         }
     }
     return $body;
 }
예제 #11
0
 /**
  * Load menu options
  *
  * @author Fernando Ontiveros Lira <*****@*****.**>
  * @access public
  * @param $strMenuName name of menu
  * @return void
  */
 function Load($strMenuName)
 {
     global $G_TMP_MENU;
     $G_TMP_MENU = null;
     $G_TMP_MENU = new Menu();
     $fMenu = G::ExpandPath("menus") . $strMenuName . ".php";
     //if the menu file doesn't exists, then try with the plugins folders
     if (!is_file($fMenu)) {
         $aux = explode(PATH_SEP, $strMenuName);
         if (count($aux) == 2) {
             $oPluginRegistry =& PMPluginRegistry::getSingleton();
             if ($oPluginRegistry->isRegisteredFolder($aux[0])) {
                 $fMenu = PATH_PLUGINS . $aux[0] . PATH_SEP . $aux[1] . ".php";
             }
         }
     }
     if (!is_file($fMenu)) {
         return;
     }
     include $fMenu;
     //this line will add options to current menu.
     $oPluginRegistry =& PMPluginRegistry::getSingleton();
     $oPluginRegistry->getMenus($strMenuName);
     //?
     $c = 0;
     for ($i = 0; $i < count($G_TMP_MENU->Options); $i++) {
         if ($G_TMP_MENU->Enabled[$i] == 1) {
             $this->Options[$c] = $G_TMP_MENU->Options[$i];
             $this->Labels[$c] = $G_TMP_MENU->Labels[$i];
             $this->Icons[$c] = $G_TMP_MENU->Icons[$i];
             $this->JS[$c] = $G_TMP_MENU->JS[$i];
             $this->Types[$c] = $G_TMP_MENU->Types[$i];
             $this->Enabled[$c] = $G_TMP_MENU->Enabled[$i];
             $this->Id[$c] = $G_TMP_MENU->Id[$i];
             $this->Classes[$c] = $G_TMP_MENU->Classes[$i];
             $this->ElementClass[$c] = $G_TMP_MENU->ElementClass[$i];
             $c++;
         } else {
             if ($i == $this->optionOn) {
                 $this->optionOn = -1;
             } elseif ($i < $this->optionOn) {
                 $this->optionOn--;
             } elseif ($this->optionOn > 0) {
                 $this->optionOn--;
             }
             //added this line
         }
     }
     $G_TMP_MENU = null;
 }
예제 #12
0
파일: Step.php 프로젝트: rrsc/processmaker
    /**
     * Get data of a Step
     *
     * @param string $stepUid Unique id of Step
     *
     * return array Return an array with data of a Step
     */
    public function getStep($stepUid)
    {
        try {
            $arrayStep = array();

            //Verify data
            $this->throwExceptionIfNotExistsStep($stepUid);

            //Get data
            //Call plugin
            $pluginRegistry = &\PMPluginRegistry::getSingleton();
            $externalSteps = $pluginRegistry->getSteps();

            $criteria = new \Criteria("workflow");

            $criteria->add(\StepPeer::STEP_UID, $stepUid, \Criteria::EQUAL);

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

            $rsCriteria->next();

            $row = $rsCriteria->getRow();

            $titleObj = "";
            $descriptionObj = "";

            switch ($row["STEP_TYPE_OBJ"]) {
                case "DYNAFORM":
                    $dynaform = new \Dynaform();
                    $arrayData = $dynaform->load($row["STEP_UID_OBJ"]);

                    $titleObj = $arrayData["DYN_TITLE"];
                    $descriptionObj = $arrayData["DYN_DESCRIPTION"];
                    break;
                case "INPUT_DOCUMENT":
                    $inputDocument = new \InputDocument();
                    $arrayData = $inputDocument->getByUid($row["STEP_UID_OBJ"]);

                    if ($arrayData === false) {
                        return $arrayStep;
                    }

                    $titleObj = $arrayData["INP_DOC_TITLE"];
                    $descriptionObj = $arrayData["INP_DOC_DESCRIPTION"];
                    break;
                case "OUTPUT_DOCUMENT":
                    $outputDocument = new \OutputDocument();
                    $arrayData = $outputDocument->getByUid($row["STEP_UID_OBJ"]);

                    if ($arrayData === false) {
                        return $arrayStep;
                    }

                    $titleObj = $arrayData["OUT_DOC_TITLE"];
                    $descriptionObj = $arrayData["OUT_DOC_DESCRIPTION"];
                    break;
                case "EXTERNAL":
                    $titleObj = "unknown " . $row["STEP_UID"];

                    if (is_array($externalSteps) && count($externalSteps) > 0) {
                        foreach ($externalSteps as $key => $value) {
                            if ($value->sStepId == $row["STEP_UID_OBJ"]) {
                                $titleObj = $value->sStepTitle;
                            }
                        }
                    }
                    break;
            }

            //Return
            $arrayStep = array(
                $this->getFieldNameByFormatFieldName("STEP_UID")        => $stepUid,
                $this->getFieldNameByFormatFieldName("STEP_TYPE_OBJ")   => $row["STEP_TYPE_OBJ"],
                $this->getFieldNameByFormatFieldName("STEP_UID_OBJ")    => $row["STEP_UID_OBJ"],
                $this->getFieldNameByFormatFieldName("STEP_CONDITION")  => $row["STEP_CONDITION"],
                $this->getFieldNameByFormatFieldName("STEP_POSITION")   => (int)($row["STEP_POSITION"]),
                $this->getFieldNameByFormatFieldName("STEP_MODE")       => $row["STEP_MODE"],
                $this->getFieldNameByFormatFieldName("OBJ_TITLE")       => $titleObj,
                $this->getFieldNameByFormatFieldName("OBJ_DESCRIPTION") => $descriptionObj
            );

            return $arrayStep;
        } catch (\Exception $e) {
            throw $e;
        }
    }
예제 #13
0
function run_addon_core_install($args)
{
    try {
        if (!extension_loaded("mysql")) {
            if (strtoupper(substr(PHP_OS, 0, 3)) === "WIN") {
                dl("mysql.dll");
            } else {
                dl("mysql.so");
            }
        }
        ///////
        /*
        if (!CLI2) {
          $args = $opts;
        }
        */
        $workspace = $args[0];
        $storeId = $args[1];
        $addonName = $args[2];
        if (!defined("SYS_SYS")) {
            define("SYS_SYS", $workspace);
        }
        if (!defined("PATH_DATA_SITE")) {
            define("PATH_DATA_SITE", PATH_DATA . "sites/" . SYS_SYS . "/");
        }
        if (!defined("DB_ADAPTER")) {
            define("DB_ADAPTER", $args[3]);
        }
        ///////
        //***************** Plugins **************************
        G::LoadClass("plugin");
        //Here we are loading all plugins registered
        //the singleton has a list of enabled plugins
        $sSerializedFile = PATH_DATA_SITE . "plugin.singleton";
        $oPluginRegistry =& PMPluginRegistry::getSingleton();
        if (file_exists($sSerializedFile)) {
            $oPluginRegistry->unSerializeInstance(file_get_contents($sSerializedFile));
        }
        ///////
        //echo "** Installation starting... (workspace: $workspace, store: $storeId, id: $addonName)\n";
        $ws = new workspaceTools($workspace);
        $ws->initPropel(false);
        require_once PATH_CORE . 'methods' . PATH_SEP . 'enterprise' . PATH_SEP . 'enterprise.php';
        require_once PATH_CORE . 'classes' . PATH_SEP . 'model' . PATH_SEP . 'AddonsManagerPeer.php';
        $addon = AddonsManagerPeer::retrieveByPK($addonName, $storeId);
        if ($addon == null) {
            throw new Exception("Id {$addonName} not found in store {$storeId}");
        }
        //echo "Downloading...\n";
        $download = $addon->download();
        //echo "Installing...\n";
        $addon->install();
        if ($addon->isCore()) {
            $ws = new workspaceTools($workspace);
            $ws->initPropel(false);
            $addon->setState("install-finish");
        } else {
            $addon->setState();
        }
    } catch (Exception $e) {
        $addon->setState("error");
        //fwrite(STDERR, "\n[ERROR: {$e->getMessage()}]\n");
        //fwrite(STDOUT, "\n[ERROR: {$e->getMessage()}]\n");
    }
    //echo "** Installation finished\n";
}
 public function activateFeatures()
 {
     //Get a list of all Enterprise plugins and active/inactive them
     if (file_exists(PATH_PLUGINS . 'enterprise/data/default')) {
         if ($this->result == "OK") {
             //Disable
             if (file_exists(PATH_PLUGINS . 'enterprise/data/data')) {
                 $oPluginRegistry =& PMPluginRegistry::getSingleton();
                 $aPlugins = unserialize(trim(file_get_contents(PATH_PLUGINS . 'enterprise/data/data')));
                 foreach ($aPlugins as $aPlugin) {
                     $sClassName = substr($aPlugin['sFilename'], 0, strpos($aPlugin['sFilename'], '-'));
                     require_once PATH_PLUGINS . $sClassName . '.php';
                     $oDetails = $oPluginRegistry->getPluginDetails($sClassName . '.php');
                     $oPluginRegistry->disablePlugin($oDetails->sNamespace);
                     file_put_contents(PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance());
                 }
                 unlink(PATH_PLUGINS . 'enterprise/data/data');
             }
             //Enable
             $oPluginRegistry =& PMPluginRegistry::getSingleton();
             $aPlugins = unserialize(trim(file_get_contents(PATH_PLUGINS . "enterprise/data/default")));
             foreach ($aPlugins as $aPlugin) {
                 if ($aPlugin["bActive"]) {
                     $sClassName = substr($aPlugin["sFilename"], 0, strpos($aPlugin["sFilename"], "-"));
                     require_once PATH_PLUGINS . $sClassName . ".php";
                     $oDetails = $oPluginRegistry->getPluginDetails($sClassName . ".php");
                     $oPluginRegistry->enablePlugin($oDetails->sNamespace);
                     file_put_contents(PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance());
                 }
             }
             if (file_exists(PATH_DATA_SITE . "ee")) {
                 $aPlugins = unserialize(trim(file_get_contents(PATH_DATA_SITE . 'ee')));
                 $aDenied = array();
                 foreach ($aPlugins as $aPlugin) {
                     $sClassName = substr($aPlugin['sFilename'], 0, strpos($aPlugin['sFilename'], '-'));
                     if (!in_array($sClassName, $this->features)) {
                         if (file_exists(PATH_PLUGINS . $sClassName . '.php')) {
                             require_once PATH_PLUGINS . $sClassName . '.php';
                             $oDetails = $oPluginRegistry->getPluginDetails($sClassName . '.php');
                             $oPluginRegistry->disablePlugin($oDetails->sNamespace);
                             file_put_contents(PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance());
                             $aDenied[] = $oDetails->sNamespace;
                         }
                     }
                 }
                 if (!empty($aDenied)) {
                     if (SYS_COLLECTION == "enterprise" && SYS_TARGET == "pluginsList") {
                         G::SendMessageText("The following plugins were restricted due to your enterprise license: " . implode(", ", $aDenied), "INFO");
                     }
                 }
             }
         } else {
             //Disable
             $oPluginRegistry =& PMPluginRegistry::getSingleton();
             $aPlugins = unserialize(trim(file_get_contents(PATH_PLUGINS . 'enterprise/data/default')));
             foreach ($aPlugins as $aPlugin) {
                 $sClassName = substr($aPlugin['sFilename'], 0, strpos($aPlugin['sFilename'], '-'));
                 //To avoid self disable
                 if ($sClassName != "pmLicenseManager" && $sClassName != "pmTrial" && $sClassName != "enterprise") {
                     require_once PATH_PLUGINS . $sClassName . '.php';
                     $oDetails = $oPluginRegistry->getPluginDetails($sClassName . '.php');
                     $oPluginRegistry->disablePlugin($oDetails->sNamespace);
                 } else {
                     //Enable default and required plugins
                     require_once PATH_PLUGINS . $sClassName . '.php';
                     $oDetails = $oPluginRegistry->getPluginDetails($sClassName . '.php');
                     $oPluginRegistry->enablePlugin($oDetails->sNamespace);
                 }
             }
             if (file_exists(PATH_DATA_SITE . 'ee')) {
                 $aPlugins = unserialize(trim(file_get_contents(PATH_DATA_SITE . 'ee')));
                 foreach ($aPlugins as $aPlugin) {
                     $sClassName = substr($aPlugin['sFilename'], 0, strpos($aPlugin['sFilename'], '-'));
                     if (strlen($sClassName) > 0) {
                         if (!class_exists($sClassName)) {
                             require_once PATH_PLUGINS . $sClassName . '.php';
                         }
                         $oDetails = $oPluginRegistry->getPluginDetails($sClassName . '.php');
                         if ($oDetails) {
                             $oPluginRegistry->disablePlugin($oDetails->sNamespace);
                         }
                     }
                 }
             }
             file_put_contents(PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance());
         }
     }
 }
예제 #15
0
/**
 *
 * @method
 *
 * Generates an Output Document
 *
 * @name PMFGenerateOutputDocument
 * @label PMF Generate Output Document
 *
 * @param string(32) | $outputID | Output ID | Output Document ID
 * @return none | $none | None | None
 *
 */
function PMFGenerateOutputDocument($outputID, $sApplication = null, $index = null, $sUserLogged = null)
{
    $g = new G();
    $g->sessionVarSave();
    if ($sApplication) {
        $_SESSION["APPLICATION"] = $sApplication;
    } else {
        $sApplication = $_SESSION["APPLICATION"];
    }
    if ($index) {
        $_SESSION["INDEX"] = $index;
    } else {
        $index = $_SESSION["INDEX"];
    }
    if ($sUserLogged) {
        $_SESSION["USER_LOGGED"] = $sUserLogged;
    } else {
        $sUserLogged = $_SESSION["USER_LOGGED"];
    }
    G::LoadClass('case');
    $oCase = new Cases();
    $oCase->thisIsTheCurrentUser($sApplication, $index, $sUserLogged, '', 'casesListExtJs');
    //require_once 'classes/model/OutputDocument.php';
    $oOutputDocument = new OutputDocument();
    $aOD = $oOutputDocument->load($outputID);
    $Fields = $oCase->loadCase($sApplication);
    //The $_GET['UID'] variable is used when a process executes.
    //$_GET['UID']=($aOD['OUT_DOC_VERSIONING'])?$_GET['UID']:$aOD['OUT_DOC_UID'];
    //$sUID = ($aOD['OUT_DOC_VERSIONING'])?$_GET['UID']:$aOD['OUT_DOC_UID'];
    $sFilename = preg_replace('[^A-Za-z0-9_]', '_', G::replaceDataField($aOD['OUT_DOC_FILENAME'], $Fields['APP_DATA']));
    require_once 'classes/model/AppFolder.php';
    require_once 'classes/model/AppDocument.php';
    //Get the Custom Folder ID (create if necessary)
    $oFolder = new AppFolder();
    //$aOD['OUT_DOC_DESTINATION_PATH'] = ($aOD['OUT_DOC_DESTINATION_PATH']=='')?PATH_DOCUMENT
    //      . $_SESSION['APPLICATION'] . PATH_SEP . 'outdocs'. PATH_SEP:$aOD['OUT_DOC_DESTINATION_PATH'];
    $folderId = $oFolder->createFromPath($aOD['OUT_DOC_DESTINATION_PATH'], $sApplication);
    //Tags
    $fileTags = $oFolder->parseTags($aOD['OUT_DOC_TAGS'], $sApplication);
    //Get last Document Version and apply versioning if is enabled
    $oAppDocument = new AppDocument();
    $lastDocVersion = $oAppDocument->getLastDocVersion($outputID, $sApplication);
    $oCriteria = new Criteria('workflow');
    $oCriteria->add(AppDocumentPeer::APP_UID, $sApplication);
    //$oCriteria->add(AppDocumentPeer::DEL_INDEX,    $index);
    $oCriteria->add(AppDocumentPeer::DOC_UID, $outputID);
    $oCriteria->add(AppDocumentPeer::DOC_VERSION, $lastDocVersion);
    $oCriteria->add(AppDocumentPeer::APP_DOC_TYPE, 'OUTPUT');
    $oDataset = AppDocumentPeer::doSelectRS($oCriteria);
    $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
    $oDataset->next();
    if ($aOD['OUT_DOC_VERSIONING'] && $lastDocVersion != 0) {
        //Create new Version of current output
        $lastDocVersion++;
        if ($aRow = $oDataset->getRow()) {
            $aFields = array('APP_DOC_UID' => $aRow['APP_DOC_UID'], 'APP_UID' => $sApplication, 'DEL_INDEX' => $index, 'DOC_UID' => $outputID, 'DOC_VERSION' => $lastDocVersion + 1, 'USR_UID' => $sUserLogged, 'APP_DOC_TYPE' => 'OUTPUT', 'APP_DOC_CREATE_DATE' => date('Y-m-d H:i:s'), 'APP_DOC_FILENAME' => $sFilename, 'FOLDER_UID' => $folderId, 'APP_DOC_TAGS' => $fileTags);
            $oAppDocument = new AppDocument();
            $oAppDocument->create($aFields);
            $sDocUID = $aRow['APP_DOC_UID'];
        }
    } else {
        ////No versioning so Update a current Output or Create new if no exist
        if ($aRow = $oDataset->getRow()) {
            //Update
            $aFields = array('APP_DOC_UID' => $aRow['APP_DOC_UID'], 'APP_UID' => $sApplication, 'DEL_INDEX' => $index, 'DOC_UID' => $outputID, 'DOC_VERSION' => $lastDocVersion, 'USR_UID' => $sUserLogged, 'APP_DOC_TYPE' => 'OUTPUT', 'APP_DOC_CREATE_DATE' => date('Y-m-d H:i:s'), 'APP_DOC_FILENAME' => $sFilename, 'FOLDER_UID' => $folderId, 'APP_DOC_TAGS' => $fileTags);
            $oAppDocument = new AppDocument();
            $oAppDocument->update($aFields);
            $sDocUID = $aRow['APP_DOC_UID'];
        } else {
            //we are creating the appdocument row
            //create
            if ($lastDocVersion == 0) {
                $lastDocVersion++;
            }
            $aFields = array('APP_UID' => $sApplication, 'DEL_INDEX' => $index, 'DOC_UID' => $outputID, 'DOC_VERSION' => $lastDocVersion, 'USR_UID' => $sUserLogged, 'APP_DOC_TYPE' => 'OUTPUT', 'APP_DOC_CREATE_DATE' => date('Y-m-d H:i:s'), 'APP_DOC_FILENAME' => $sFilename, 'FOLDER_UID' => $folderId, 'APP_DOC_TAGS' => $fileTags);
            $oAppDocument = new AppDocument();
            $aFields['APP_DOC_UID'] = $sDocUID = $oAppDocument->create($aFields);
        }
    }
    $sFilename = $aFields['APP_DOC_UID'] . "_" . $lastDocVersion;
    $pathOutput = PATH_DOCUMENT . G::getPathFromUID($sApplication) . PATH_SEP . 'outdocs' . PATH_SEP;
    //G::pr($sFilename);die;
    G::mk_dir($pathOutput);
    $aProperties = array();
    if (!isset($aOD['OUT_DOC_MEDIA'])) {
        $aOD['OUT_DOC_MEDIA'] = 'Letter';
    }
    if (!isset($aOD['OUT_DOC_LEFT_MARGIN'])) {
        $aOD['OUT_DOC_LEFT_MARGIN'] = '15';
    }
    if (!isset($aOD['OUT_DOC_RIGHT_MARGIN'])) {
        $aOD['OUT_DOC_RIGHT_MARGIN'] = '15';
    }
    if (!isset($aOD['OUT_DOC_TOP_MARGIN'])) {
        $aOD['OUT_DOC_TOP_MARGIN'] = '15';
    }
    if (!isset($aOD['OUT_DOC_BOTTOM_MARGIN'])) {
        $aOD['OUT_DOC_BOTTOM_MARGIN'] = '15';
    }
    $aProperties['media'] = $aOD['OUT_DOC_MEDIA'];
    $aProperties['margins'] = array('left' => $aOD['OUT_DOC_LEFT_MARGIN'], 'right' => $aOD['OUT_DOC_RIGHT_MARGIN'], 'top' => $aOD['OUT_DOC_TOP_MARGIN'], 'bottom' => $aOD['OUT_DOC_BOTTOM_MARGIN']);
    if (isset($aOD['OUT_DOC_REPORT_GENERATOR'])) {
        $aProperties['report_generator'] = $aOD['OUT_DOC_REPORT_GENERATOR'];
    }
    $oOutputDocument->generate($outputID, $Fields['APP_DATA'], $pathOutput, $sFilename, $aOD['OUT_DOC_TEMPLATE'], (bool) $aOD['OUT_DOC_LANDSCAPE'], $aOD['OUT_DOC_GENERATE'], $aProperties);
    //Plugin Hook PM_UPLOAD_DOCUMENT for upload document
    //G::LoadClass('plugin');
    $oPluginRegistry =& PMPluginRegistry::getSingleton();
    if ($oPluginRegistry->existsTrigger(PM_UPLOAD_DOCUMENT) && class_exists('uploadDocumentData')) {
        $triggerDetail = $oPluginRegistry->getTriggerInfo(PM_UPLOAD_DOCUMENT);
        $aFields['APP_DOC_PLUGIN'] = $triggerDetail->sNamespace;
        $oAppDocument1 = new AppDocument();
        $oAppDocument1->update($aFields);
        $sPathName = PATH_DOCUMENT . G::getPathFromUID($sApplication) . PATH_SEP;
        $oData['APP_UID'] = $sApplication;
        $oData['ATTACHMENT_FOLDER'] = true;
        switch ($aOD['OUT_DOC_GENERATE']) {
            case "BOTH":
                $documentData = new uploadDocumentData($sApplication, $sUserLogged, $pathOutput . $sFilename . '.pdf', $sFilename . '.pdf', $sDocUID, $oAppDocument->getDocVersion());
                $documentData->sFileType = "PDF";
                $documentData->bUseOutputFolder = true;
                $uploadReturn = $oPluginRegistry->executeTriggers(PM_UPLOAD_DOCUMENT, $documentData);
                if ($uploadReturn) {
                    //Only delete if the file was saved correctly
                    unlink($pathOutput . $sFilename . '.pdf');
                }
                $documentData = new uploadDocumentData($sApplication, $sUserLogged, $pathOutput . $sFilename . '.doc', $sFilename . '.doc', $sDocUID, $oAppDocument->getDocVersion());
                $documentData->sFileType = "DOC";
                $documentData->bUseOutputFolder = true;
                $uploadReturn = $oPluginRegistry->executeTriggers(PM_UPLOAD_DOCUMENT, $documentData);
                if ($uploadReturn) {
                    //Only delete if the file was saved correctly
                    unlink($pathOutput . $sFilename . '.doc');
                }
                break;
            case "PDF":
                $documentData = new uploadDocumentData($sApplication, $sUserLogged, $pathOutput . $sFilename . '.pdf', $sFilename . '.pdf', $sDocUID, $oAppDocument->getDocVersion());
                $documentData->sFileType = "PDF";
                $documentData->bUseOutputFolder = true;
                $uploadReturn = $oPluginRegistry->executeTriggers(PM_UPLOAD_DOCUMENT, $documentData);
                if ($uploadReturn) {
                    //Only delete if the file was saved correctly
                    unlink($pathOutput . $sFilename . '.pdf');
                }
                break;
            case "DOC":
                $documentData = new uploadDocumentData($sApplication, $sUserLogged, $pathOutput . $sFilename . '.doc', $sFilename . '.doc', $sDocUID, $oAppDocument->getDocVersion());
                $documentData->sFileType = "DOC";
                $documentData->bUseOutputFolder = true;
                $uploadReturn = $oPluginRegistry->executeTriggers(PM_UPLOAD_DOCUMENT, $documentData);
                if ($uploadReturn) {
                    //Only delete if the file was saved correctly
                    unlink($pathOutput . $sFilename . '.doc');
                }
                break;
        }
    }
    $g->sessionVarRestore();
}
예제 #16
0
 /**
  * It Renders content according to Part['Type']
  *
  * @author Fernando Ontiveros Lira <*****@*****.**>
  *
  * @param intPos = 0
  * @return void
  *
  */
 public function RenderContent0($intPos = 0, $showXMLFormName = false)
 {
     global $G_FORM;
     global $G_TABLE;
     global $G_TMP_TARGET;
     global $G_OP_MENU;
     global $G_IMAGE_FILENAME;
     global $G_IMAGE_PARTS;
     global $_SESSION;
     //Changed from $HTTP_SESSION_VARS
     global $G_OBJGRAPH;
     //For graphLayout component
     $this->intPos = $intPos;
     $Part = $this->Parts[$intPos];
     $this->publishType = $Part['Type'];
     switch ($this->publishType) {
         case 'externalContent':
             $G_CONTENT = new Content();
             if ($Part['Content'] != "") {
                 $G_CONTENT = G::LoadContent($Part['Content']);
             }
             G::LoadTemplateExternal($Part['Template']);
             break;
         case 'image':
             $G_IMAGE_FILENAME = $Part['File'];
             $G_IMAGE_PARTS = $Part['Data'];
             break;
         case 'appform':
             global $APP_FORM;
             $G_FORM = $APP_FORM;
             break;
         case 'xmlform':
         case 'dynaform':
             global $G_FORM;
             if ($Part['AbsolutePath']) {
                 $sPath = $Part['AbsolutePath'];
             } else {
                 if ($this->publishType == 'xmlform') {
                     $sPath = PATH_XMLFORM;
                 } else {
                     $sPath = PATH_DYNAFORM;
                 }
             }
             //if the xmlform file doesn't exists, then try with the plugins folders
             if (!is_file($sPath . $Part['File'] . '.xml')) {
                 $aux = explode(PATH_SEP, $Part['File']);
                 //check if G_PLUGIN_CLASS is defined, because publisher can be called without an environment
                 if (count($aux) > 2) {
                     //Subfolders
                     $filename = array_pop($aux);
                     $aux0 = implode(PATH_SEP, $aux);
                     $aux = array();
                     $aux[0] = $aux0;
                     $aux[1] = $filename;
                 }
                 if (count($aux) == 2 && defined('G_PLUGIN_CLASS')) {
                     $oPluginRegistry =& PMPluginRegistry::getSingleton();
                     if ($response = $oPluginRegistry->isRegisteredFolder($aux[0])) {
                         if ($response !== true) {
                             $sPath = PATH_PLUGINS . $response . PATH_SEP;
                         } else {
                             $sPath = PATH_PLUGINS;
                         }
                     }
                 }
             }
             if (!class_exists($Part['Template']) || $Part['Template'] === 'xmlform') {
                 $G_FORM = new Form($Part['File'], $sPath, SYS_LANG, false);
             } else {
                 eval('$G_FORM = new ' . $Part['Template'] . ' ( $Part[\'File\'] , "' . $sPath . '");');
             }
             if ($this->publishType == 'dynaform' && ($Part['Template'] == 'xmlform' || $Part['Template'] == 'xmlform_preview')) {
                 $dynaformShow = isset($G_FORM->printdynaform) && $G_FORM->printdynaform ? 'gulliver/dynaforms_OptionsPrint' : 'gulliver/dynaforms_Options';
                 $G_FORM->fields = G::array_merges(array('__DYNAFORM_OPTIONS' => new XmlForm_Field_XmlMenu(new Xml_Node('__DYNAFORM_OPTIONS', 'complete', '', array('type' => 'xmlmenu', 'xmlfile' => $dynaformShow, 'parentFormId' => $G_FORM->id)), SYS_LANG, PATH_XMLFORM, $G_FORM)), $G_FORM->fields);
             }
             //Needed to make ajax calls
             //The action in the form tag.
             if (defined('ENABLE_ENCRYPT') && ENABLE_ENCRYPT == 'yes') {
                 $G_FORM->action = urlencode(G::encrypt($Part['Target'], URL_KEY));
             } else {
                 $G_FORM->action = $Part['Target'];
             }
             if (!(isset($Part['ajaxServer']) && $Part['ajaxServer'] !== '')) {
                 if ($this->publishType == 'dynaform') {
                     $Part['ajaxServer'] = '../gulliver/defaultAjaxDynaform';
                 } else {
                     $Part['ajaxServer'] = '../gulliver/defaultAjax';
                 }
             }
             if (defined('ENABLE_ENCRYPT') && ENABLE_ENCRYPT == 'yes') {
                 $G_FORM->ajaxServer = urlencode(G::encrypt($Part['ajaxServer'], URL_KEY));
             } else {
                 $G_FORM->ajaxServer = $Part['ajaxServer'];
             }
             $G_FORM->setValues($Part['Data']);
             $G_FORM->setValues(array('G_FORM_ID' => $G_FORM->id));
             //Asegurese de que no entre cuando $Part['Template']=="grid"
             //de hecho soo deberia usarse cuando $Part['Template']=="xmlform"
             if ($this->publishType == 'dynaform' && $Part['Template'] == "xmlform" || $Part['Template'] == "xmlform") {
                 $G_FORM->values = G::array_merges(array('__DYNAFORM_OPTIONS' => isset($Part['Data']['__DYNAFORM_OPTIONS']) ? $Part['Data']['__DYNAFORM_OPTIONS'] : ''), $G_FORM->values);
                 if (isset($G_FORM->nextstepsave)) {
                     switch ($G_FORM->nextstepsave) {
                         // this condition validates if the next step link is configured to Save and Go the next step or show a prompt
                         case 'save':
                             // Save and Next only if there are no required fields can submit the form.
                             $G_FORM->values['__DYNAFORM_OPTIONS']['NEXT_ACTION'] = 'if (document.getElementById("' . $G_FORM->id . '")&&validateForm(document.getElementById(\'DynaformRequiredFields\').value)) {document.getElementById("' . $G_FORM->id . '").submit();}return false;';
                             break;
                         case 'prompt':
                             // Show Prompt only if there are no required fields can submit the form.
                             $G_FORM->values['__DYNAFORM_OPTIONS']['NEXT_ACTION'] = 'if (document.getElementById("' . $G_FORM->id . '")&&validateForm(document.getElementById(\'DynaformRequiredFields\').value)) {if(dynaFormChanged(document.getElementsByTagName(\'form\').item(0))) {new leimnud.module.app.confirm().make({label:"@G::LoadTranslation(ID_DYNAFORM_SAVE_CHANGES)", action:function(){document.getElementById("' . $G_FORM->id . '").submit();}.extend(this), cancel:function(){window.location = getField("DYN_FORWARD").href;}.extend(this)});return false;} else {window.location = getField("DYN_FORWARD").href;return false;}}return false;';
                             break;
                     }
                 }
             }
             if (isset($_SESSION)) {
                 $_SESSION[$G_FORM->id] = $G_FORM->values;
             }
             // by default load the core template
             if ($Part['Template'] == 'xmlform_preview') {
                 $Part['Template'] = 'xmlform';
             }
             $template = PATH_CORE . 'templates/' . $Part['Template'] . '.html';
             //erik: new feature, now templates such as xmlform.html can be personalized via skins
             if (defined('SYS_SKIN') && strtolower(SYS_SKIN) != 'classic') {
                 // First, verify if the template exists on Custom skins path
                 if (is_file(PATH_CUSTOM_SKINS . SYS_SKIN . PATH_SEP . $Part['Template'] . '.html')) {
                     $template = PATH_CUSTOM_SKINS . SYS_SKIN . PATH_SEP . $Part['Template'] . '.html';
                     //Second, verify if the template exists on base skins path
                 } elseif (is_file(G::ExpandPath("skinEngine") . SYS_SKIN . PATH_SEP . $Part['Template'] . '.html')) {
                     $template = G::ExpandPath("skinEngine") . SYS_SKIN . PATH_SEP . $Part['Template'] . '.html';
                 }
             }
             //end new feature
             if ($Part['Template'] == 'grid') {
                 print '<form class="formDefault">';
             }
             $scriptCode = '';
             if ($this->localMode != '') {
                 // @# las modification by erik in 09/06/2008
                 $G_FORM->mode = $this->localMode;
             }
             print $G_FORM->render($template, $scriptCode);
             if ($Part['Template'] == 'grid') {
                 print '</form>';
             }
             $oHeadPublisher =& headPublisher::getSingleton();
             $oHeadPublisher->addScriptFile($G_FORM->scriptURL);
             $oHeadPublisher->addScriptCode($scriptCode);
             /**
              * We've implemented the conditional show hide fields..
              *
              * @author Erik A. Ortiz <*****@*****.**>
              * @date Fri Feb 19, 2009
              */
             if ($this->publishType == 'dynaform') {
                 if (isset($_SESSION['CURRENT_DYN_UID']) || isset($_SESSION['CONDITION_DYN_UID'])) {
                     require_once "classes/model/FieldCondition.php";
                     $oFieldCondition = new FieldCondition();
                     //This dynaform has show/hide field conditions
                     if (isset($_SESSION['CURRENT_DYN_UID']) && $_SESSION['CURRENT_DYN_UID'] != '') {
                         $ConditionalShowHideRoutines = $oFieldCondition->getConditionScript($_SESSION["CURRENT_DYN_UID"]);
                         //lsl
                     } else {
                         if (isset($_SESSION['CONDITION_DYN_UID']) && $_SESSION['CONDITION_DYN_UID'] != '') {
                             $ConditionalShowHideRoutines = $oFieldCondition->getConditionScript($_SESSION["CONDITION_DYN_UID"]);
                             //lsl
                         }
                     }
                 }
             }
             if (isset($ConditionalShowHideRoutines) && $ConditionalShowHideRoutines) {
                 G::evalJScript($ConditionalShowHideRoutines);
             }
             break;
         case 'pagedtable':
             global $G_FORM;
             //if the xmlform file doesn't exists, then try with the plugins folders
             $sPath = PATH_XMLFORM;
             if (!is_file($sPath . $Part['File'])) {
                 $aux = explode(PATH_SEP, $Part['File']);
                 if (count($aux) == 2) {
                     $oPluginRegistry =& PMPluginRegistry::getSingleton();
                     if ($oPluginRegistry->isRegisteredFolder($aux[0])) {
                         $sPath = PATH_PLUGINS;
                         // . $aux[0] . PATH_SEP ;
                     }
                 }
             }
             $G_FORM = new Form($Part['File'], $sPath, SYS_LANG, true);
             if (defined('ENABLE_ENCRYPT') && ENABLE_ENCRYPT == 'yes') {
                 $G_FORM->ajaxServer = urlencode(G::encrypt($Part['ajaxServer'], URL_KEY));
             } else {
                 $G_FORM->ajaxServer = $Part['ajaxServer'];
             }
             $G_FORM->setValues($Part['Data']);
             if (isset($_SESSION)) {
                 $_SESSION[$G_FORM->id] = $G_FORM->values;
             }
             G::LoadSystem('pagedTable');
             $oTable = new pagedTable();
             $oTable->template = 'templates/' . $Part['Template'] . '.html';
             $G_FORM->xmlform = '';
             $G_FORM->xmlform->fileXml = $G_FORM->fileName;
             $G_FORM->xmlform->home = $G_FORM->home;
             $G_FORM->xmlform->tree->attribute = $G_FORM->tree->attributes;
             $G_FORM->values = array_merge($G_FORM->values, $Part['Data']);
             $oTable->setupFromXmlform($G_FORM);
             if (isset($Part['ajaxServer']) && $Part['ajaxServer'] !== '') {
                 $oTable->ajaxServer = $Part['ajaxServer'];
             }
             /* Start Block: Load user configuration for the pagedTable */
             G::LoadClass('configuration');
             $objUID = $Part['File'];
             $conf = new Configurations();
             $conf->loadConfig($oTable, 'pagedTable', $objUID, '', isset($_SESSION['USER_LOGGED']) ? $_SESSION['USER_LOGGED'] : '', '');
             $oTable->__OBJ_UID = $objUID;
             /* End Block */
             /* Start Block: PagedTable Right Click */
             G::LoadClass('popupMenu');
             $pm = new popupMenu('gulliver/pagedTable_PopupMenu');
             $pm->name = $oTable->id;
             $fields = array_keys($oTable->fields);
             foreach ($fields as $f) {
                 switch (strtolower($oTable->fields[$f]['Type'])) {
                     case 'javascript':
                     case 'button':
                     case 'private':
                     case 'hidden':
                     case 'cellmark':
                         break;
                     default:
                         $label = $oTable->fields[$f]['Label'] != '' ? $oTable->fields[$f]['Label'] : $f;
                         $label = str_replace("\n", ' ', $label);
                         $pm->fields[$f] = new XmlForm_Field_popupOption(new Xml_Node($f, 'complete', '', array('label' => $label, 'type' => 'popupOption', 'launch' => $oTable->id . '.showHideField("' . $f . '")')));
                         $pm->values[$f] = '';
                 }
             }
             $sc = '';
             $pm->values['PAGED_TABLE_ID'] = $oTable->id;
             print $pm->render(PATH_CORE . 'templates/popupMenu.html', $sc);
             /* End Block */
             $oTable->renderTable();
             /* Start Block: Load PagedTable Right Click */
             print '<script type="text/javascript">';
             print $sc;
             print 'loadPopupMenu_' . $oTable->id . '();';
             print '</script>';
             /* End Block */
             break;
         case 'propeltable':
             global $G_FORM;
             //if the xmlform file doesn't exists, then try with the plugins folders
             if ($Part['AbsolutePath']) {
                 $sPath = '';
             } else {
                 $sPath = PATH_XMLFORM;
             }
             if (!is_file($sPath . $Part['File'])) {
                 $aux = explode(PATH_SEP, $Part['File']);
                 //search in PLUGINS folder, probably the file is in plugin
                 if (count($aux) == 2) {
                     $oPluginRegistry =& PMPluginRegistry::getSingleton();
                     if ($oPluginRegistry->isRegisteredFolder($aux[0])) {
                         $sPath = PATH_PLUGINS;
                         // . $aux[0] . PATH_SEP ;
                     }
                 }
                 //search in PATH_DYNAFORM folder
                 if (!is_file($sPath . PATH_SEP . $Part['File'] . '.xml')) {
                     $sPath = PATH_DYNAFORM;
                 }
             }
             //PATH_DATA_PUBLIC ???
             if (!file_exists($sPath . PATH_SEP . $Part['File'] . '.xml') && defined('PATH_DATA_PUBLIC')) {
                 $sPath = PATH_DATA_PUBLIC;
             }
             $G_FORM = new Form($Part['File'], $sPath, SYS_LANG, true);
             if (defined('ENABLE_ENCRYPT') && ENABLE_ENCRYPT == 'yes') {
                 $G_FORM->ajaxServer = urlencode(G::encrypt($Part['ajaxServer'], URL_KEY));
             } else {
                 $G_FORM->ajaxServer = $Part['ajaxServer'];
             }
             if (isset($_SESSION)) {
                 $_SESSION[$G_FORM->id] = $G_FORM->values;
             }
             G::LoadClass('propelTable');
             $oTable = new propelTable();
             $oTable->template = $Part['Template'];
             $oTable->criteria = $Part['Content'];
             if (isset($Part['ajaxServer']) && $Part['ajaxServer'] !== '') {
                 $oTable->ajaxServer = $Part['ajaxServer'];
             }
             if (!isset($G_FORM->xmlform)) {
                 $G_FORM->xmlform = new stdclass();
             }
             $G_FORM->xmlform->fileXml = $G_FORM->fileName;
             $G_FORM->xmlform->home = $G_FORM->home;
             if (!isset($G_FORM->xmlform->tree)) {
                 $G_FORM->xmlform->tree = new stdclass();
             }
             $G_FORM->xmlform->tree->attribute = $G_FORM->tree->attributes;
             if (is_array($Part['Data'])) {
                 $G_FORM->values = array_merge($G_FORM->values, $Part['Data']);
             }
             $oTable->setupFromXmlform($G_FORM);
             /* Start Block: Load user configuration for the pagedTable */
             G::LoadClass('configuration');
             $objUID = $Part['File'];
             $conf = new Configurations($oTable);
             $conf->loadConfig($oTable, 'pagedTable', $objUID, '', isset($_SESSION['USER_LOGGED']) ? $_SESSION['USER_LOGGED'] : '', '');
             $oTable->__OBJ_UID = $objUID;
             //$oTable->__OBJ_UID = '';
             /* End Block */
             /* Start Block: PagedTable Right Click */
             G::LoadClass('popupMenu');
             $pm = new popupMenu('gulliver/pagedTable_PopupMenu');
             $sc = $pm->renderPopup($oTable->id, $oTable->fields);
             /* End Block */
             //krumo ( $Part );
             if ($this->ROWS_PER_PAGE) {
                 $oTable->rowsPerPage = $this->ROWS_PER_PAGE;
             }
             try {
                 if (is_array($Part['Data'])) {
                     $oTable->renderTable('', $Part['Data']);
                 } else {
                     $oTable->renderTable();
                 }
                 print $sc;
             } catch (Exception $e) {
                 $aMessage['MESSAGE'] = $e->getMessage();
                 $this->AddContent('xmlform', 'xmlform', 'login/showMessage', '', $aMessage);
             }
             break;
         case 'panel-init':
             global $mainPanelScript;
             global $panelName;
             global $tabCount;
             //G::LoadThirdParty( 'pear/json', 'class.json' );
             //$json = new Services_JSON();
             $tabCount = 0;
             $panelName = $Part['Template'];
             $data = $Part['File'];
             if (!is_array($data)) {
                 $data = array();
             }
             $data = G::array_merges(array('title' => '', 'style' => array(), 'left' => 'getAbsoluteLeft(mycontent)', 'top' => 'getAbsoluteTop(mycontent)', 'width' => 700, 'height' => 600, 'drag' => true, 'close' => true, 'modal' => true, 'roll' => false, 'resize' => false, 'tabWidth' => 120, 'tabStep' => 3, 'blinkToFront' => true, 'tabSpace' => 10), $data);
             $mainPanelScript = 'var ' . $panelName . '={},' . $panelName . 'Tabs=[];' . 'leimnud.event.add(window,"load",function(){' . $panelName . ' = new leimnud.module.panel();' . 'var mycontent=document.getElementById("' . $this->publisherId . '[' . $intPos . ']");' . $panelName . '.options={' . 'size:{w:' . $data['width'] . ',h:' . $data['height'] . '},' . 'position:{x:' . $data['left'] . ',y:' . $data['top'] . '},' . 'title:"' . addcslashes($data['title'], '\\"') . '",' . 'theme:"processmaker",' . 'statusBar:true,' . 'headerBar:true,' . 'control:{' . ' close:' . ($data['close'] ? 'true' : 'false') . ',' . ' roll:' . ($data['roll'] ? 'true' : 'false') . ',' . ' drag:' . ($data['drag'] ? 'true' : 'false') . ',' . ' resize:' . ($data['resize'] ? 'true' : 'false') . '},' . 'fx:{' . ' drag:' . ($data['drag'] ? 'true' : 'false') . ',' . ' modal:' . ($data['modal'] ? 'true' : 'false') . ',' . ' blinkToFront:' . ($data['blinkToFront'] ? 'true' : 'false') . '}' . '};' . $panelName . '.setStyle=' . Bootstrap::json_encode($data['style']) . ';' . $panelName . '.tab={' . 'width:' . ($data['tabWidth'] + $data['tabSpace']) . ',' . 'optWidth:' . $data['tabWidth'] . ',' . 'step :' . $data['tabStep'] . ',' . 'options:[]' . '};';
             print ' ';
             break;
         case 'panel-tab':
             global $tabCount;
             global $mainPanelScript;
             global $panelName;
             $onChange = $Part['Content'];
             $beforeChange = $Part['Data'];
             if (SYS_LANG == 'es') {
                 $mainPanelScript = str_replace("120", "150", $mainPanelScript);
             } else {
                 $mainPanelScript = str_replace("150", "120", $mainPanelScript);
             }
             $mainPanelScript .= $panelName . 'Tabs[' . $tabCount . ']=' . 'document.getElementById("' . $Part['File'] . '");' . $panelName . '.tab.options[' . $panelName . '.tab.options.length]=' . '{' . 'title  :"' . addcslashes($Part['Template'], '\\"') . '",' . 'noClear  :true,' . 'content  :function(){' . ($beforeChange != '' ? 'if (typeof(' . $beforeChange . ')!=="undefined") {' . $beforeChange . '();}' : '') . $panelName . 'Clear();' . $panelName . 'Tabs[' . $tabCount . '].style.display="";' . ($onChange != '' ? 'if (typeof(' . $onChange . ')!=="undefined") {' . $onChange . '();}' : '') . '}.extend(' . $panelName . '),' . 'selected:' . ($tabCount == 0 ? 'true' : 'false') . '};';
             $tabCount++;
             break;
         case 'panel-close':
             global $mainPanelScript;
             global $panelName;
             global $tabCount;
             $mainPanelScript .= $panelName . '.make();';
             $mainPanelScript .= 'for(var r=0;r<' . $tabCount . ';r++)' . 'if (' . $panelName . 'Tabs[r])' . $panelName . '.addContent(' . $panelName . 'Tabs[r]);';
             $mainPanelScript .= '});';
             $mainPanelScript .= 'function ' . $panelName . 'Clear(){';
             $mainPanelScript .= 'for(var r=0;r<' . $tabCount . ';r++)' . 'if (' . $panelName . 'Tabs[r])' . $panelName . 'Tabs[r].style.display="none";}';
             $oHeadPublisher =& headPublisher::getSingleton();
             $oHeadPublisher->addScriptCode($mainPanelScript);
             break;
         case 'blank':
             print ' ';
             break;
         case 'varform':
             global $G_FORM;
             $G_FORM = new Form();
             G::LoadSystem("varform");
             $xml = new varForm();
             //$xml->parseFile (  );
             $xml->renderForm($G_FORM, $Part['File']);
             $G_FORM->Values = $Part['Data'];
             $G_FORM->SetUp($Part['Target']);
             $G_FORM->width = 500;
             break;
         case 'table':
             $G_TMP_TARGET = $Part['Target'];
             $G_TABLE = G::LoadRawTable($Part['File'], $this->dbc, $Part['Data']);
             break;
         case 'menu':
             $G_TMP_TARGET = $Part['Target'];
             $G_OP_MENU = new Menu();
             $G_OP_MENU->Load($Part['File']);
             break;
         case 'smarty':
             //To do: Please check it 26/06/07
             $template = new Smarty();
             $template->compile_dir = PATH_SMARTY_C;
             $template->cache_dir = PATH_SMARTY_CACHE;
             $template->config_dir = PATH_THIRDPARTY . 'smarty/configs';
             $template->caching = false;
             $dataArray = $Part['Data'];
             // verify if there are templates folders registered, template and method folders are the same
             $folderTemplate = explode('/', $Part['Template']);
             $oPluginRegistry =& PMPluginRegistry::getSingleton();
             if ($oPluginRegistry->isRegisteredFolder($folderTemplate[0])) {
                 $template->templateFile = PATH_PLUGINS . $Part['Template'] . '.html';
             } else {
                 $template->templateFile = PATH_TPL . $Part['Template'] . '.html';
             }
             // last change to load the template, maybe absolute path was given
             if (!is_file($template->templateFile)) {
                 $template->templateFile = strpos($Part['Template'], '.html') !== false ? $Part['Template'] : $Part['Template'] . '.html';
             }
             //assign the variables and use the template $template
             $template->assign($dataArray);
             print $template->fetch($template->templateFile);
             break;
         case 'template':
             //To do: Please check it 26/06/07
             if (gettype($Part['Data']) == 'array') {
                 G::LoadSystem('template');
                 //template phpBB
                 $template = new Template();
                 $template->set_filenames(array('body' => $Part['Template'] . '.html'));
                 $dataArray = $Part['Data'];
                 if (is_array($dataArray)) {
                     foreach ($dataArray as $key => $val) {
                         if (is_array($val)) {
                             foreach ($val as $key_val => $val_array) {
                                 $template->assign_block_vars($key, $val_array);
                             }
                         } else {
                             $template->assign_vars(array($key => $val));
                         }
                     }
                 }
                 $template->pparse('body');
             }
             if (gettype($Part['Data']) == 'object' && strtolower(get_class($Part['Data'])) == 'templatepower') {
                 $Part['Data']->printToScreen();
             }
             return;
             break;
         case 'view':
         case 'content':
             //check if G_PLUGIN_CLASS is defined, because publisher can be called without an environment
             $aux = explode(PATH_SEP, $Part['Template']);
             if (count($aux) == 2 && defined('G_PLUGIN_CLASS')) {
                 //if the template doesn't exists, then try it with the plugins folders, after the normal Template
                 $userTemplate = G::ExpandPath('templates') . $Part['Template'];
                 $globalTemplate = PATH_TEMPLATE . $Part['Template'];
                 if (!is_file($userTemplate) && !is_file($globalTemplate)) {
                     $oPluginRegistry =& PMPluginRegistry::getSingleton();
                     if ($oPluginRegistry->isRegisteredFolder($aux[0])) {
                         $pluginTemplate = PATH_PLUGINS . $Part['Template'] . '.php';
                         include $pluginTemplate;
                     }
                 }
             }
             break;
         case 'graphLayout':
             //Added by JHL to render GraphLayout component
             $G_OBJGRAPH = $Part['Data'];
             $G_TMP_TARGET = $Part['Target'];
             $G_TMP_FILE = $Part['File'];
             break;
     }
     //krumo( $Part['Template'] );
     //check if this LoadTemplate is used, byOnti 12th Aug 2008
     G::LoadTemplate($Part['Template']);
     $G_TABLE = null;
 }
예제 #17
0
    public function getAllGeneratedDocumentsCriteria($sProcessUID, $sApplicationUID, $sTasKUID, $sUserUID)

    {

        G::LoadClass("configuration");



        $conf = new Configurations();



        $confEnvSetting = $conf->getFormats();



        //verifica si la tabla OBJECT_PERMISSION

        $this->verifyTable();

        $listing = false;

        $oPluginRegistry = & PMPluginRegistry::getSingleton();

        if ($oPluginRegistry->existsTrigger(PM_CASE_DOCUMENT_LIST)) {

            $folderData = new folderData(null, null, $sApplicationUID, null, $sUserUID);

            $folderData->PMType = "OUTPUT";

            $folderData->returnList = true;

            //$oPluginRegistry = & PMPluginRegistry::getSingleton();

            $listing = $oPluginRegistry->executeTriggers(PM_CASE_DOCUMENT_LIST, $folderData);

        }



        $aObjectPermissions = $this->getAllObjects($sProcessUID, $sApplicationUID, $sTasKUID, $sUserUID);

        if (!is_array($aObjectPermissions)) {

            $aObjectPermissions = array(

                'DYNAFORMS' => array(-1),

                'INPUT_DOCUMENTS' => array(-1),

                'OUTPUT_DOCUMENTS' => array(-1)

            );

        }

        if (!isset($aObjectPermissions['DYNAFORMS'])) {

            $aObjectPermissions['DYNAFORMS'] = array(-1);

        } else {

            if (!is_array($aObjectPermissions['DYNAFORMS'])) {

                $aObjectPermissions['DYNAFORMS'] = array(-1);

            }

        }

        if (!isset($aObjectPermissions['INPUT_DOCUMENTS'])) {

            $aObjectPermissions['INPUT_DOCUMENTS'] = array(-1);

        } else {

            if (!is_array($aObjectPermissions['INPUT_DOCUMENTS'])) {

                $aObjectPermissions['INPUT_DOCUMENTS'] = array(-1);

            }

        }

        if (!isset($aObjectPermissions['OUTPUT_DOCUMENTS'])) {

            $aObjectPermissions['OUTPUT_DOCUMENTS'] = array(-1);

        } else {

            if (!is_array($aObjectPermissions['OUTPUT_DOCUMENTS'])) {

                $aObjectPermissions['OUTPUT_DOCUMENTS'] = array(-1);

            }

        }

        $aDelete = $this->getAllObjectsFrom($sProcessUID, $sApplicationUID, $sTasKUID, $sUserUID, 'DELETE');

        $oAppDocument = new AppDocument();

        $oCriteria = new Criteria('workflow');

        $oCriteria->add(AppDocumentPeer::APP_UID, $sApplicationUID);

        $oCriteria->add(AppDocumentPeer::APP_DOC_TYPE, 'OUTPUT');

        $oCriteria->add(AppDocumentPeer::APP_DOC_STATUS, array('ACTIVE'), Criteria::IN);

        //$oCriteria->add(AppDocumentPeer::APP_DOC_UID, $aObjectPermissions['OUTPUT_DOCUMENTS'], Criteria::IN);

        $oCriteria->add(

                $oCriteria->getNewCriterion(

                        AppDocumentPeer::APP_DOC_UID, $aObjectPermissions['OUTPUT_DOCUMENTS'], Criteria::IN)->addOr($oCriteria->getNewCriterion(AppDocumentPeer::USR_UID, $sUserUID, Criteria::EQUAL))

        );



        $aConditions = array();

        $aConditions[] = array(AppDocumentPeer::APP_UID, AppDelegationPeer::APP_UID);

        $aConditions[] = array(AppDocumentPeer::DEL_INDEX, AppDelegationPeer::DEL_INDEX);

        $oCriteria->addJoinMC($aConditions, Criteria::LEFT_JOIN);

        $oCriteria->add(AppDelegationPeer::PRO_UID, $sProcessUID);

        $oCriteria->addAscendingOrderByColumn(AppDocumentPeer::APP_DOC_INDEX);

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

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

        $oDataset->next();

        $aOutputDocuments = array();

        $aOutputDocuments[] = array(

            'APP_DOC_UID' => 'char',

            'DOC_UID' => 'char',

            'APP_DOC_COMMENT' => 'char',

            'APP_DOC_FILENAME' => 'char',

            'APP_DOC_INDEX' => 'integer'

        );

        $oUser = new Users();

        while ($aRow = $oDataset->getRow()) {

            $oCriteria2 = new Criteria('workflow');

            $oCriteria2->add(AppDelegationPeer::APP_UID, $sApplicationUID);

            $oCriteria2->add(AppDelegationPeer::DEL_INDEX, $aRow['DEL_INDEX']);

            $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2);

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

            $oDataset2->next();

            $aRow2 = $oDataset2->getRow();

            $oTask = new Task();

            if ($oTask->taskExists($aRow2['TAS_UID'])) {

                $aTask = $oTask->load($aRow2['TAS_UID']);

            } else {

                $aTask = array('TAS_TITLE' => '(TASK DELETED)');

            }

            $lastVersion = $oAppDocument->getLastDocVersion($aRow['DOC_UID'], $sApplicationUID);

            if ($lastVersion == $aRow['DOC_VERSION']) {

                //Only show last document Version

                $aAux = $oAppDocument->load($aRow['APP_DOC_UID'], $aRow['DOC_VERSION']);

                //Get output Document information

                $oOutputDocument = new OutputDocument();

                $aGields = $oOutputDocument->load($aRow['DOC_UID']);

                //OUTPUTDOCUMENT

                $outDocTitle = $aGields['OUT_DOC_TITLE'];

                switch ($aGields['OUT_DOC_GENERATE']) {

                    //G::LoadTranslation(ID_DOWNLOAD)

                    case "PDF":

                        $fileDoc = 'javascript:alert("NO DOC")';

                        $fileDocLabel = " ";

                        $filePdf = 'cases_ShowOutputDocument?a=' .

                                $aRow['APP_DOC_UID'] . '&v=' . $aRow['DOC_VERSION'] . '&ext=pdf&random=' . rand();

                        $filePdfLabel = ".pdf";

                        if (is_array($listing)) {

                            foreach ($listing as $folderitem) {

                                if (($folderitem->filename == $aRow['APP_DOC_UID']) && ($folderitem->type == "PDF")) {

                                    $filePdfLabel = G::LoadTranslation('ID_GET_EXTERNAL_FILE') . " .pdf";

                                    $filePdf = $folderitem->downloadScript;

                                    continue;

                                }

                            }

                        }

                        break;

                    case "DOC":

                        $fileDoc = 'cases_ShowOutputDocument?a=' .

                                $aRow['APP_DOC_UID'] . '&v=' . $aRow['DOC_VERSION'] . '&ext=doc&random=' . rand();

                        $fileDocLabel = ".doc";

                        $filePdf = 'javascript:alert("NO PDF")';

                        $filePdfLabel = " ";

                        if (is_array($listing)) {

                            foreach ($listing as $folderitem) {

                                if (($folderitem->filename == $aRow['APP_DOC_UID']) && ($folderitem->type == "DOC")) {

                                    $fileDocLabel = G::LoadTranslation('ID_GET_EXTERNAL_FILE') . " .doc";

                                    $fileDoc = $folderitem->downloadScript;

                                    continue;

                                }

                            }

                        }

                        break;

                    case "BOTH":

                        $fileDoc = 'cases_ShowOutputDocument?a=' .

                                $aRow['APP_DOC_UID'] . '&v=' . $aRow['DOC_VERSION'] . '&ext=doc&random=' . rand();

                        $fileDocLabel = ".doc";

                        if (is_array($listing)) {

                            foreach ($listing as $folderitem) {

                                if (($folderitem->filename == $aRow['APP_DOC_UID']) && ($folderitem->type == "DOC")) {

                                    $fileDocLabel = G::LoadTranslation('ID_GET_EXTERNAL_FILE') . " .doc";

                                    $fileDoc = $folderitem->downloadScript;

                                    continue;

                                }

                            }

                        }

                        $filePdf = 'cases_ShowOutputDocument?a=' .

                                $aRow['APP_DOC_UID'] . '&v=' . $aRow['DOC_VERSION'] . '&ext=pdf&random=' . rand();

                        $filePdfLabel = ".pdf";



                        if (is_array($listing)) {

                            foreach ($listing as $folderitem) {

                                if (($folderitem->filename == $aRow['APP_DOC_UID']) && ($folderitem->type == "PDF")) {

                                    $filePdfLabel = G::LoadTranslation('ID_GET_EXTERNAL_FILE') . " .pdf";

                                    $filePdf = $folderitem->downloadScript;

                                    continue;

                                }

                            }

                        }

                        break;

                }



                try {

                    $aAux1 = $oUser->load($aAux['USR_UID']);



                    $sUser = $conf->usersNameFormatBySetParameters($confEnvSetting["format"], $aAux1["USR_USERNAME"], $aAux1["USR_FIRSTNAME"], $aAux1["USR_LASTNAME"]);

                } catch (Exception $oException) {

                    $sUser = '******';

                }



                //if both documents were generated, we choose the pdf one, only if doc was

                //generate then choose the doc file.

                $firstDocLink = $filePdf;

                $firstDocLabel = $filePdfLabel;

                if ($aGields['OUT_DOC_GENERATE'] == 'DOC') {

                    $firstDocLink = $fileDoc;

                    $firstDocLabel = $fileDocLabel;

                }



                $aFields = array(

                    'APP_DOC_UID' => $aAux['APP_DOC_UID'],

                    'DOC_UID' => $aAux['DOC_UID'],

                    'APP_DOC_COMMENT' => $aAux['APP_DOC_COMMENT'],

                    'APP_DOC_FILENAME' => $aAux['APP_DOC_FILENAME'],

                    'APP_DOC_INDEX' => $aAux['APP_DOC_INDEX'],

                    'ORIGIN' => $aTask['TAS_TITLE'],

                    'CREATE_DATE' => $aAux['APP_DOC_CREATE_DATE'],

                    'CREATED_BY' => $sUser,

                    'FILEDOC' => $fileDoc,

                    'FILEPDF' => $filePdf,

                    'OUTDOCTITLE' => $outDocTitle,

                    'DOC_VERSION' => $aAux['DOC_VERSION'],

                    'TYPE' => $aAux['APP_DOC_TYPE'] . ' ' . $aGields['OUT_DOC_GENERATE'],

                    'DOWNLOAD_LINK' => $firstDocLink,

                    'DOWNLOAD_FILE' => $aAux['APP_DOC_FILENAME'] . $firstDocLabel

                );



                if (trim($fileDocLabel) != '') {

                    $aFields['FILEDOCLABEL'] = $fileDocLabel;

                }

                if (trim($filePdfLabel) != '') {

                    $aFields['FILEPDFLABEL'] = $filePdfLabel;

                }

                if ($aFields['APP_DOC_FILENAME'] != '') {

                    $aFields['TITLE'] = $aFields['APP_DOC_FILENAME'];

                } else {

                    $aFields['TITLE'] = $aFields['APP_DOC_COMMENT'];

                }

                $aFields['POSITION'] = $_SESSION['STEP_POSITION'];

                $aFields['CONFIRM'] = G::LoadTranslation('ID_CONFIRM_DELETE_ELEMENT');

                if (in_array($aRow['APP_DOC_UID'], $aObjectPermissions['OUTPUT_DOCUMENTS'])) {

                    if (in_array($aRow['APP_DOC_UID'], $aDelete['OUTPUT_DOCUMENTS'])) {

                        $aFields['ID_DELETE'] = G::LoadTranslation('ID_DELETE');

                    }

                }

                $aOutputDocuments[] = $aFields;

            }

            $oDataset->next();

        }

        global $_DBArray;

        $_DBArray['outputDocuments'] = $aOutputDocuments;

        $_SESSION['_DBArray'] = $_DBArray;

        G::LoadClass('ArrayPeer');

        $oCriteria = new Criteria('dbarray');

        $oCriteria->setDBArrayTable('outputDocuments');

        $oCriteria->addDescendingOrderByColumn('CREATE_DATE');

        return $oCriteria;

    }
예제 #18
0
    public function getCompleteDocumentInfo ($appUid, $appDocUid, $docVersion, $docUid, $usrId)
    {
        //require_once ("classes/model/AppDocument.php");
        //require_once ("classes/model/InputDocument.php");
        //require_once ("classes/model/OutputDocument.php");
        //require_once ("classes/model/Users.php");

        //**** start get Doc Info
        $oApp = new Application();
        $oAppDocument = new AppDocument();
        G::LoadClass( 'case' );
        $oCase = new Cases();
        G::LoadClass( 'process' );
        $oProcess = new Process();
        if (($oApp->exists( $appUid )) || ($appUid == "00000000000000000000000000000000")) {
            if ($appUid == "00000000000000000000000000000000") {
                //External Files
                $row1 = $oAppDocument->load( $appDocUid, $docVersion );
                $row2 = array ('PRO_TITLE' => G::LoadTranslation( 'ID_NOT_PROCESS_RELATED' ));
                $row3 = array ('APP_TITLE' => G::LoadTranslation( 'ID_NOT_PROCESS_RELATED' ));
            } else {
                $row1 = $oAppDocument->load( $appDocUid, $docVersion );
                $row2 = $oCase->loadCase( $appUid );
                $row3 = $oProcess->Load( $row2['PRO_UID'] );
            }
            $lastVersion = $oAppDocument->getLastAppDocVersion( $appDocUid, $appUid );

            switch ($row1['APP_DOC_TYPE']) {
                case "OUTPUT":
                    $oOutputDocument = new OutputDocument();

                    $row4 = array();
                    $swOutDocExists = 0;

                    if ($oOutputDocument->OutputExists($docUid)) {
                        $row4 = $oOutputDocument->load($docUid);
                        $swOutDocExists = 1;
                    }

                    if ($swOutDocExists == 0) {
                        $swpdf = 0;
                        $swdoc = 0;

                        $info = pathinfo($oAppDocument->getAppDocFilename());

                        $version = (!empty($docVersion))? "_" . $docVersion : "_1";
                        $outDocPath = PATH_DOCUMENT . G::getPathFromUID($row1["APP_UID"]) . PATH_SEP . "outdocs" . PATH_SEP;

                        if (file_exists($outDocPath . $appDocUid . $version . ".pdf") ||
                            file_exists($outDocPath . $info["basename"] . $version . ".pdf") ||
                            file_exists($outDocPath . $info["basename"] . ".pdf")
                        ) {
                            $swpdf = 1;
                        }

                        if (file_exists($outDocPath . $appDocUid . $version . ".doc") ||
                            file_exists($outDocPath . $info["basename"] . $version . ".doc") ||
                            file_exists($outDocPath . $info["basename"] . ".doc")
                        ) {
                            $swdoc = 1;
                        }

                        if ($swpdf == 1 && $swdoc == 1) {
                            $row4["OUT_DOC_GENERATE"] = "BOTH";
                        } else {
                            if ($swpdf == 1) {
                                $row4["OUT_DOC_GENERATE"] = "PDF";
                            } else {
                                if ($swdoc == 1) {
                                    $row4["OUT_DOC_GENERATE"] = "DOC";
                                } else {
                                    $row4["OUT_DOC_GENERATE"] = "NOFILE";
                                }
                            }
                        }
                    }

                    $versioningEnabled = false; //$row4['OUT_DOC_VERSIONING']; //Only enabled for Input or Attached documents. Need to study the best way for Output docs.

                    switch ($row4['OUT_DOC_GENERATE']) {
                        case "PDF":
                            $downloadLink = "../cases/cases_ShowOutputDocument?a=" . $appDocUid . "&v=" . $docVersion . "&ext=pdf" . "&random=" . rand();
                            $downloadLink1 = "";
                            $downloadLabel = ".pdf";
                            $downloadLabel1 = "";
                            break;
                        case "DOC":
                            $downloadLink = "../cases/cases_ShowOutputDocument?a=" . $appDocUid . "&v=" . $docVersion . "&ext=doc" . "&random=" . rand();
                            $downloadLink1 = "";
                            $downloadLabel = ".doc";
                            $downloadLabel1 = "";
                            break;
                        case "BOTH":
                            $downloadLink = "../cases/cases_ShowOutputDocument?a=" . $appDocUid . "&v=" . $docVersion . "&ext=pdf" . "&random=" . rand();
                            $downloadLink1 = "../cases/cases_ShowOutputDocument?a=" . $appDocUid . "&v=" . $docVersion . "&ext=doc" . "&random=" . rand();
                            $downloadLabel = ".pdf";
                            $downloadLabel1 = ".doc";
                            break;
                        case "NOFILE":
                            $downloadLink = "../cases/cases_ShowDocument?a=" . $appDocUid . "&v=" . $docVersion;
                            $downloadLink1 = "";
                            $downloadLabel = G::LoadTranslation("ID_DOWNLOAD");
                            $downloadLabel1 = "";
                            break;
                    }

                    if ($swOutDocExists == 0) {
                        $row4 = array();
                    }
                    break;
                case "INPUT":
                    $oInputDocument = new InputDocument();
                    if ($docUid != - 1) {
                        if ($oInputDocument->InputExists( $docUid )) {
                            $row4 = $oInputDocument->load( $docUid );
                            $versioningEnabled = $row4['INP_DOC_VERSIONING'];
                        } else {
                            $row4 = array ();
                            $versioningEnabled = false;
                        }
                        $downloadLink = "../cases/cases_ShowDocument?a=" . $appDocUid . "&v=" . $docVersion;
                        $downloadLink1 = "";
                        $downloadLabel = G::LoadTranslation( 'ID_DOWNLOAD' );
                        $downloadLabel1 = "";
                    } else {
                        $row4 = array ();
                        $versioningEnabled = false;
                        $downloadLink = "../cases/cases_ShowDocument?a=" . $appDocUid . "&v=" . $docVersion;
                        $downloadLink1 = "";
                        $downloadLabel = G::LoadTranslation( 'ID_DOWNLOAD' );
                        $downloadLabel1 = "";
                    }

                    if (! empty( $row1["APP_DOC_PLUGIN"] )) {
                        $pluginRegistry = &PMPluginRegistry::getSingleton();
                        $pluginName = $row1["APP_DOC_PLUGIN"];
                        $fieldValue = "";

                        if (file_exists( PATH_PLUGINS . $pluginName . ".php" )) {
                            $pluginDetail = $pluginRegistry->getPluginDetails( $pluginName . ".php" );

                            if ($pluginDetail) {
                                if ($pluginDetail->enabled) {
                                    require_once (PATH_PLUGINS . $pluginName . ".php");
                                    $pluginNameClass = $pluginName . "Plugin";
                                    $objPluginClass = new $pluginNameClass( $pluginName );

                                    if (isset( $objPluginClass->sMethodGetUrlDownload ) && ! empty( $objPluginClass->sMethodGetUrlDownload )) {
                                        if (file_exists( PATH_PLUGINS . $pluginName . PATH_SEP . "class." . $pluginName . ".php" )) {
                                            require_once (PATH_PLUGINS . $pluginName . PATH_SEP . "class." . $pluginName . ".php");
                                            $pluginNameClass = $pluginName . "Class";
                                            $objClass = new $pluginNameClass();

                                            if (method_exists( $objClass, $objPluginClass->sMethodGetUrlDownload )) {
                                                eval( "\$url = \$objClass->" . $objPluginClass->sMethodGetUrlDownload . "(\"" . $row1["APP_DOC_UID"] . "\");" );
                                                $downloadLink = $url;
                                                $fieldValue = $row1["APP_DOC_PLUGIN"];
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        $row1["APP_DOC_PLUGIN"] = $fieldValue;
                    }
                    break;
                default:
                    $row4 = array ();
                    $versioningEnabled = false;
                    $downloadLink = "../cases/cases_ShowDocument?a=" . $appDocUid . "&v=" . $docVersion;
                    $downloadLink1 = "";
                    $downloadLabel = G::LoadTranslation( 'ID_DOWNLOAD' );
                    $downloadLabel1 = "";
                    break;
            }
            $oUser = new Users();
            if (($usrId != "-1") && ($oUser->userExists( $usrId ))) {
                $row5 = $oUser->load( $usrId );
            } else {
                $row5['USR_USERNAME'] = "******";
            }

            //Labels/Links
            $row6 = array ();
            $row6['DELETE_LABEL'] = G::LoadTranslation( 'ID_DELETE' );
            $row6['DOWNLOAD_LABEL'] = $downloadLabel;
            $row6['DOWNLOAD_LINK'] = $downloadLink;
            $row6['DOWNLOAD_LABEL1'] = $downloadLabel1;
            $row6['DOWNLOAD_LINK1'] = $downloadLink1;
            //if(($docVersion>1)&&($row1['APP_DOC_TYPE']!="OUTPUT")){
            if (($docVersion > 1)) {
                $row6['VERSIONHISTORY_LABEL'] = G::LoadTranslation( 'ID_VERSION_HISTORY' );
            }
            if ($versioningEnabled) {
                $row6['NEWVERSION_LABEL'] = G::LoadTranslation( 'ID_NEW_VERSION' );
            }
            $row6['APP_DOC_UID_VERSION'] = $appDocUid . "_" . $docVersion;

            if ($appUid == "00000000000000000000000000000000") {
                //External Files
                $row1['APP_DOC_TYPE'] = G::LoadTranslation( 'ID_EXTERNAL_FILE' );
            }
            //**** End get docinfo
            $infoMerged = array_merge( $row1, $row2, $row3, $row4, $row5, $row6 );

            $sUserUID = $_SESSION['USER_LOGGED'];
            $aObjectPermissions = array ();
            if (isset( $infoMerged['PRO_UID'] )) {
                $aObjectPermissions = $oCase->getAllObjects( $infoMerged['PRO_UID'], $infoMerged['APP_UID'], '', $sUserUID );
            }

            if (! is_array( $aObjectPermissions )) {
                $aObjectPermissions = array ('DYNAFORMS' => array (- 1),
                'INPUT_DOCUMENTS' => array (- 1),
                'OUTPUT_DOCUMENTS' => array (- 1)
                );
            }
            if (! isset( $aObjectPermissions['DYNAFORMS'] )) {
                $aObjectPermissions['DYNAFORMS'] = array (- 1);
            } else {
                if (! is_array( $aObjectPermissions['DYNAFORMS'] )) {
                    $aObjectPermissions['DYNAFORMS'] = array (- 1);
                }
            }
            if (! isset( $aObjectPermissions['INPUT_DOCUMENTS'] )) {
                $aObjectPermissions['INPUT_DOCUMENTS'] = array (- 1);
            } else {
                if (! is_array( $aObjectPermissions['INPUT_DOCUMENTS'] )) {
                    $aObjectPermissions['INPUT_DOCUMENTS'] = array (- 1);
                }
            }
            if (! isset( $aObjectPermissions['OUTPUT_DOCUMENTS'] )) {
                $aObjectPermissions['OUTPUT_DOCUMENTS'] = array (- 1);
            } else {
                if (! is_array( $aObjectPermissions['OUTPUT_DOCUMENTS'] )) {
                    $aObjectPermissions['OUTPUT_DOCUMENTS'] = array (- 1);
                }
            }
            return array_merge( $infoMerged, $aObjectPermissions );
        }
    }
예제 #19
0
 /**
  * get the plugins, and check if there is redirectLogins
  * if yes, then redirect goes according his Role
  */
 public function _getPluginLocation()
 {
     global $RBAC;
     $url = '';
     if (class_exists('redirectDetail')) {
         //to do: complete the validation
         if (isset($RBAC->aUserInfo['PROCESSMAKER']['ROLE']['ROL_CODE'])) {
             $userRole = $RBAC->aUserInfo['PROCESSMAKER']['ROLE']['ROL_CODE'];
         }
         $oPluginRegistry =& PMPluginRegistry::getSingleton();
         $aRedirectLogin = $oPluginRegistry->getRedirectLogins();
         if (isset($aRedirectLogin) && is_array($aRedirectLogin)) {
             foreach ($aRedirectLogin as $key => $detail) {
                 if (isset($detail->sPathMethod) && $detail->sRoleCode == $userRole) {
                     if (isset($_COOKIE['workspaceSkin'])) {
                         $url = '/sys' . SYS_SYS . '/' . $this->lang . '/' . $_COOKIE['workspaceSkin'] . '/' . $detail->sPathMethod;
                     } else {
                         $url = '/sys' . SYS_SYS . '/' . $this->lang . '/' . SYS_SKIN . '/' . $detail->sPathMethod;
                     }
                 }
             }
         }
     }
     return $url;
 }
예제 #20
0
 /**
  * Update this store information from the store location.
  *
  * @return bool true if updated, false otherwise
  */
 public function update($force = false, $type = 'plugin')
 {
     require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php';
     if (!class_exists('AddonsManagerPeer')) {
         require_once 'classes/model/AddonsManager.php';
     }
     //If we have any addon that is installing or updating, don't update store
     $criteria = new Criteria(AddonsManagerPeer::DATABASE_NAME);
     $criteria->add(AddonsManagerPeer::ADDON_STATE, '', Criteria::NOT_EQUAL);
     $criteria->add(AddonsManagerPeer::ADDON_TYPE, $type);
     if (AddonsManagerPeer::doCount($criteria) > 0) {
         return false;
     }
     $this->clear($type);
     //Fill with local information
     //List all plugins installed
     $oPluginRegistry =& PMPluginRegistry::getSingleton();
     $aPluginsPP = array();
     if (file_exists(PATH_DATA_SITE . 'ee')) {
         $aPluginsPP = unserialize(trim(file_get_contents(PATH_DATA_SITE . 'ee')));
     }
     $pmLicenseManagerO =& pmLicenseManager::getSingleton();
     $localPlugins = array();
     if ($type == 'plugin') {
         foreach ($aPluginsPP as $aPlugin) {
             $sClassName = substr($aPlugin['sFilename'], 0, strpos($aPlugin['sFilename'], '-'));
             if (file_exists(PATH_PLUGINS . $sClassName . '.php')) {
                 require_once PATH_PLUGINS . $sClassName . '.php';
                 $oDetails = $oPluginRegistry->getPluginDetails($sClassName . '.php');
                 if ($oDetails) {
                     $sStatus = $oDetails->enabled ? G::LoadTranslation('ID_ENABLED') : G::LoadTranslation('ID_DISABLED');
                     if (isset($oDetails->aWorkspaces)) {
                         if (!in_array(SYS_SYS, $oDetails->aWorkspaces)) {
                             continue;
                         }
                     }
                     if ($sClassName == "pmLicenseManager" || $sClassName == "pmTrial") {
                         continue;
                     }
                     $sEdit = $oDetails->sSetupPage != '' && $oDetails->enabled ? G::LoadTranslation('ID_SETUP') : ' ';
                     $aPlugin = array();
                     $aPluginId = $sClassName;
                     $aPluginTitle = $oDetails->sFriendlyName;
                     $aPluginDescription = $oDetails->sDescription;
                     $aPluginVersion = $oDetails->iVersion;
                     if (@in_array($sClassName, $pmLicenseManagerO->features)) {
                         $aPluginStatus = $sStatus;
                         $aPluginLinkStatus = 'pluginsChange?id=' . $sClassName . '.php&status=' . $oDetails->enabled;
                         $aPluginEdit = $sEdit;
                         $aPluginLinkEdit = 'pluginsSetup?id=' . $sClassName . '.php';
                         $aPluginStatusA = $sStatus == "Enabled" ? "installed" : 'disabled';
                         $enabledStatus = true;
                     } else {
                         $aPluginStatus = "";
                         $aPluginLinkStatus = '';
                         $aPluginEdit = '';
                         $aPluginLinkEdit = '';
                         $aPluginStatusA = 'minus-circle';
                         $enabledStatus = false;
                     }
                     $addon = new AddonsManager();
                     //G::pr($addon);
                     $addon->setAddonId($aPluginId);
                     $addon->setStoreId($this->getStoreId());
                     //Don't trust external data
                     $addon->setAddonName($aPluginId);
                     $addon->setAddonDescription($aPluginDescription);
                     $addon->setAddonNick($aPluginTitle);
                     $addon->setAddonVersion("");
                     $addon->setAddonStatus($aPluginStatusA);
                     $addon->setAddonType("plugin");
                     $addon->setAddonPublisher("Colosa");
                     $addon->setAddonDownloadUrl("");
                     $addon->setAddonDownloadMd5("");
                     $addon->setAddonReleaseDate(null);
                     $addon->setAddonReleaseType('localRegistry');
                     $addon->setAddonReleaseNotes("");
                     $addon->setAddonState("");
                     $addon->save();
                     $localPlugins[$aPluginId] = $addon;
                 }
             }
         }
     } else {
         $list = unserialize($pmLicenseManagerO->licensedfeaturesList);
         if (is_array($list)) {
             foreach ($list['addons'] as $key => $feature) {
                 $addon = new AddonsManager();
                 $addon->setAddonId($feature['name']);
                 $addon->setStoreId($feature['guid']);
                 $addon->setAddonName($feature['name']);
                 $addon->setAddonDescription($feature['description']);
                 $addon->setAddonNick($feature['nick']);
                 $addon->setAddonVersion("");
                 $addon->setAddonStatus($feature['status']);
                 $addon->setAddonType("features");
                 $addon->setAddonPublisher("Colosa");
                 $addon->setAddonDownloadUrl("");
                 $addon->setAddonDownloadMd5("");
                 $addon->setAddonReleaseDate(null);
                 $addon->setAddonReleaseType('localRegistry');
                 $addon->setAddonReleaseNotes("");
                 $addon->setAddonState("");
                 $addon->save();
             }
         }
     }
     $this->setStoreLastUpdated(time());
     $this->save();
     $url = $this->getStoreLocation();
     //Validate url
     $licenseInfo = $pmLicenseManagerO->getActiveLicense();
     $licenseId = str_replace('.dat', '', str_replace('license_', '', basename($licenseInfo['LICENSE_PATH'])));
     $url = explode('&', $url);
     $url[count($url) - 1] = 'licId=' . urlencode($licenseId);
     $url = implode('&', $url);
     if (EnterpriseUtils::getInternetConnection() == 1 && EnterpriseUtils::checkConnectivity($url) == true) {
         $option = array("http" => array("method" => "POST", "header" => "Content-type: application/x-www-form-urlencoded\r\n", "content" => http_build_query(array("pmVersion" => System::getVersion(), "version" => STORE_VERSION))));
         // Proxy settings
         $sysConf = System::getSystemConfiguration();
         if (isset($sysConf['proxy_host'])) {
             if ($sysConf['proxy_host'] != '') {
                 if (!is_array($option['http'])) {
                     $option['http'] = array();
                 }
                 $option['http']['request_fulluri'] = true;
                 $option['http']['proxy'] = 'tcp://' . $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '');
                 if ($sysConf['proxy_user'] != '') {
                     if (!isset($option['http']['header'])) {
                         $option['http']['header'] = '';
                     }
                     $option['http']['header'] .= 'Proxy-Authorization: Basic ' . base64_encode($sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
                 }
             }
         }
         $context = stream_context_create($option);
         //This may block for a while, always use AJAX to call this method
         $url = $url . '&type=' . strtoupper($type);
         $data = file_get_contents($url, false, $context);
         if ($data === false) {
             throw new Exception("Could not contact store");
         }
         $serverData = G::json_decode($data);
         //Don't trust external data
         if (empty($serverData)) {
             throw new Exception("Store data invalid ('{$data}')");
         }
         if (isset($serverData->error)) {
             throw new Exception("Store sent us an error: {$serverData->error}");
         }
         if (!isset($serverData->version)) {
             throw new Exception("Store version not found");
         }
         if ($serverData->version != STORE_VERSION) {
             throw new Exception("Store version '{$serverData->version}' unsupported");
         }
         if (!isset($serverData->addons)) {
             throw new Exception("Addons not found on store data");
         }
         $this->clear($type);
         try {
             //Add each item to this stores addons
             $addons = @get_object_vars($serverData->addons);
             if (!empty($addons)) {
                 foreach (get_object_vars($serverData->addons) as $addonId => $addonInfo) {
                     $addon = new AddonsManager();
                     $addon->setAddonId($addonId);
                     $addon->setStoreId($this->getStoreId());
                     //Don't trust external data
                     $addon->setAddonName(isset($addonInfo->name) ? $addonInfo->name : $addonId);
                     $addon->setAddonDescription(isset($addonInfo->description) ? $addonInfo->description : "");
                     $addon->setAddonNick(isset($addonInfo->nick) ? $addonInfo->nick : "");
                     $addon->setAddonVersion(isset($addonInfo->version) ? $addonInfo->version : "");
                     $addon->setAddonStatus(isset($addonInfo->status) ? $addonInfo->status : "");
                     $addon->setAddonType(isset($addonInfo->type) ? $addonInfo->type : "");
                     $addon->setAddonPublisher(isset($addonInfo->publisher) ? $addonInfo->publisher : "");
                     $workspace = isset($pmLicenseManagerO->workspace) ? $pmLicenseManagerO->workspace : 'pmLicenseSrv';
                     $addon->setAddonDownloadUrl(isset($addonInfo->download_url) ? $addonInfo->download_url : "http://" . $pmLicenseManagerO->server . "/sys" . $workspace . "/en/green/services/rest?action=getPlugin&OBJ_UID=" . $addonInfo->guid);
                     $addon->setAddonDownloadMd5(isset($addonInfo->download_md5) ? $addonInfo->download_md5 : "");
                     $addon->setAddonReleaseDate(isset($addonInfo->release_date) ? $addonInfo->release_date : "");
                     $addon->setAddonReleaseType(isset($addonInfo->release_type) ? $addonInfo->release_type : '');
                     $addon->setAddonReleaseNotes(isset($addonInfo->release_notes) ? $addonInfo->release_notes : "");
                     $addon->setAddonState("");
                     $addon->save();
                     if (isset($localPlugins[$addonId])) {
                         unset($localPlugins[$addonId]);
                     }
                 }
                 foreach ($localPlugins as $keyPlugin => $addonA) {
                     //G::pr($addonA );
                     //$addonA->save();
                     $addon = new AddonsManager();
                     //G::pr($addon);
                     $addon->setAddonId($addonA->getAddonId());
                     $addon->setStoreId($addonA->getStoreId());
                     //Don't trust external data
                     $addon->setAddonName($addonA->getAddonName());
                     $addon->setAddonDescription($addonA->getAddonDescription());
                     $addon->setAddonNick($addonA->getAddonNick());
                     $addon->setAddonVersion("");
                     $addon->setAddonStatus($addonA->getAddonStatus());
                     $addon->setAddonType($addonA->getAddonType());
                     $addon->setAddonPublisher($addonA->getAddonPublisher());
                     $addon->setAddonDownloadUrl($addonA->getAddonDownloadUrl());
                     $addon->setAddonDownloadMd5($addonA->getAddonDownloadMd5());
                     $addon->setAddonReleaseDate(null);
                     $addon->setAddonReleaseType('localRegistry');
                     $addon->setAddonReleaseNotes("");
                     $addon->setAddonState("");
                     $addon->save();
                 }
             }
             $this->setStoreLastUpdated(time());
             $this->save();
         } catch (Exception $e) {
             //If we had issues, don't keep only a part of the items
             $this->clear($type);
             throw $e;
         }
     }
     return true;
 }
    /**
     * Update the plugin attributes in all workspaces
     *
     * @param string $pluginName Plugin name
     *
     * return void
     */
    public function updatePluginAttributesInAllWorkspaces($pluginName)
    {
        try {
            G::LoadClass("system");
            G::LoadClass("wsTools");

            //Set variables
            $pluginFileName = $pluginName . ".php";

            //Verify data
            if (!file_exists(PATH_PLUGINS . $pluginFileName)) {
                throw new Exception("Error: The plugin not exists");
            }

            //Update plugin attributes
            require_once(PATH_PLUGINS . $pluginFileName);

            $pmPluginRegistry = &PMPluginRegistry::getSingleton();

            $pluginDetails = $pmPluginRegistry->getPluginDetails($pluginFileName);

            if (isset($pluginDetails->aWorkspaces) && is_array($pluginDetails->aWorkspaces) && count($pluginDetails->aWorkspaces) > 0) {
                $arrayWorkspace = array();

                foreach (System::listWorkspaces() as $value) {
                    $workspaceTools = $value;

                    $arrayWorkspace[] = $workspaceTools->name;
                }

                $arrayWorkspaceAux = array_diff($arrayWorkspace, $pluginDetails->aWorkspaces); //Workspaces to update
                $strWorkspaceNoWritable = "";

                $arrayWorkspace = array();

                foreach ($arrayWorkspaceAux as $value) {
                    $workspace = $value;

                    $workspacePathDataSite = PATH_DATA . "sites" . PATH_SEP . $workspace . PATH_SEP;

                    if (file_exists($workspacePathDataSite . "plugin.singleton")) {
                        $pmPluginRegistry = PMPluginRegistry::loadSingleton($workspacePathDataSite . "plugin.singleton");

                        if (isset($pmPluginRegistry->_aPluginDetails[$pluginName])) {
                            if (!is_writable($workspacePathDataSite . "plugin.singleton")) {
                                $strWorkspaceNoWritable .= (($strWorkspaceNoWritable != "")? ", " : "") . $workspace;
                            }

                            $arrayWorkspace[] = $workspace;
                        }
                    }
                }

                //Verify data
                if ($strWorkspaceNoWritable != "") {
                    throw new Exception("Error: The workspaces \"$strWorkspaceNoWritable\" has problems of permissions of write in file \"plugin.singleton\", solve this problem");
                }

                //Update plugin attributes
                foreach ($arrayWorkspace as $value) {
                    $workspace = $value;

                    $workspacePathDataSite = PATH_DATA . "sites" . PATH_SEP . $workspace . PATH_SEP;

                    $pmPluginRegistry = PMPluginRegistry::loadSingleton($workspacePathDataSite . "plugin.singleton");

                    $pmPluginRegistry->disablePlugin($pluginName);

                    file_put_contents($workspacePathDataSite . "plugin.singleton", $pmPluginRegistry->serializeInstance());
                }
            }
        } catch (Exception $e) {
            throw $e;
        }
    }
예제 #22
0
 /**
  * Get data of Cases OutputDocument
  *
  * @param string $applicationUid
  * @param string $outputDocumentUid
  * @param string $userUid
  *
  * return object Return an object with data of an OutputDocument
  */
 public function addCasesOutputDocument($applicationUid, $outputDocumentUid, $userUid)
 {
     try {
         $sApplication = $applicationUid;
         $index = \AppDelegation::getCurrentIndex($applicationUid);
         $sUserLogged = $userUid;
         $outputID = $outputDocumentUid;
         $g = new \G();
         $g->sessionVarSave();
         \G::LoadClass( 'case' );
         $oCase = new \Cases();
         $oCase->thisIsTheCurrentUser( $sApplication, $index, $sUserLogged, '', 'casesListExtJs' );
         //require_once 'classes/model/OutputDocument.php';
         $oOutputDocument = new \OutputDocument();
         $aOD = $oOutputDocument->load( $outputID );
         $Fields = $oCase->loadCase( $sApplication );
         $sFilename = preg_replace( '[^A-Za-z0-9_]', '_', \G::replaceDataField( $aOD['OUT_DOC_FILENAME'], $Fields['APP_DATA'] ) );
         require_once (PATH_TRUNK . "workflow" . PATH_SEP . "engine" . PATH_SEP . "classes" . PATH_SEP . "model" . PATH_SEP . "AppFolder.php");
         require_once (PATH_TRUNK . "workflow" . PATH_SEP . "engine" . PATH_SEP . "classes" . PATH_SEP . "model" . PATH_SEP . "AppDocument.php");
         //Get the Custom Folder ID (create if necessary)
         $oFolder = new \AppFolder();
         $folderId = $oFolder->createFromPath( $aOD['OUT_DOC_DESTINATION_PATH'], $sApplication );
         //Tags
         $fileTags = $oFolder->parseTags( $aOD['OUT_DOC_TAGS'], $sApplication );
         //Get last Document Version and apply versioning if is enabled
         $oAppDocument = new \AppDocument();
         $lastDocVersion = $oAppDocument->getLastDocVersion( $outputID, $sApplication );
         $oCriteria = new \Criteria( 'workflow' );
         $oCriteria->add( \AppDocumentPeer::APP_UID, $sApplication );
         $oCriteria->add( \AppDocumentPeer::DOC_UID, $outputID );
         $oCriteria->add( \AppDocumentPeer::DOC_VERSION, $lastDocVersion );
         $oCriteria->add( \AppDocumentPeer::APP_DOC_TYPE, 'OUTPUT' );
         $oDataset = \AppDocumentPeer::doSelectRS( $oCriteria );
         $oDataset->setFetchmode( \ResultSet::FETCHMODE_ASSOC );
         $oDataset->next();
         if (($aOD['OUT_DOC_VERSIONING']) && ($lastDocVersion != 0)) {
             //Create new Version of current output
             $lastDocVersion ++;
             if ($aRow = $oDataset->getRow()) {
                 $aFields = array ('APP_DOC_UID' => $aRow['APP_DOC_UID'],'APP_UID' => $sApplication,'DEL_INDEX' => $index,'DOC_UID' => $outputID,'DOC_VERSION' => $lastDocVersion + 1,'USR_UID' => $sUserLogged,'APP_DOC_TYPE' => 'OUTPUT','APP_DOC_CREATE_DATE' => date( 'Y-m-d H:i:s' ),'APP_DOC_FILENAME' => $sFilename,'FOLDER_UID' => $folderId,'APP_DOC_TAGS' => $fileTags);
                 $oAppDocument = new \AppDocument();
                 $oAppDocument->create( $aFields );
                 $sDocUID = $aRow['APP_DOC_UID'];
             }
         } else {
             ////No versioning so Update a current Output or Create new if no exist
             if ($aRow = $oDataset->getRow()) {
                 //Update
                 $aFields = array ('APP_DOC_UID' => $aRow['APP_DOC_UID'],'APP_UID' => $sApplication,'DEL_INDEX' => $index,'DOC_UID' => $outputID,'DOC_VERSION' => $lastDocVersion,'USR_UID' => $sUserLogged,'APP_DOC_TYPE' => 'OUTPUT','APP_DOC_CREATE_DATE' => date( 'Y-m-d H:i:s' ),'APP_DOC_FILENAME' => $sFilename,'FOLDER_UID' => $folderId,'APP_DOC_TAGS' => $fileTags
                 );
                 $oAppDocument = new \AppDocument();
                 $oAppDocument->update( $aFields );
                 $sDocUID = $aRow['APP_DOC_UID'];
             } else {
                 //we are creating the appdocument row
                 //create
                 if ($lastDocVersion == 0) {
                     $lastDocVersion ++;
                 }
                 $aFields = array ('APP_UID' => $sApplication,'DEL_INDEX' => $index,'DOC_UID' => $outputID,'DOC_VERSION' => $lastDocVersion,'USR_UID' => $sUserLogged,'APP_DOC_TYPE' => 'OUTPUT','APP_DOC_CREATE_DATE' => date( 'Y-m-d H:i:s' ),'APP_DOC_FILENAME' => $sFilename,'FOLDER_UID' => $folderId,'APP_DOC_TAGS' => $fileTags
                 );
                 $oAppDocument = new \AppDocument();
                 $aFields['APP_DOC_UID'] = $sDocUID = $oAppDocument->create( $aFields );
             }
         }
         $sFilename = $aFields['APP_DOC_UID'] . "_" . $lastDocVersion;
         $pathOutput = PATH_DOCUMENT . \G::getPathFromUID($sApplication) . PATH_SEP . 'outdocs' . PATH_SEP; //G::pr($sFilename);die;
         \G::mk_dir( $pathOutput );
         $aProperties = array ();
         if (! isset( $aOD['OUT_DOC_MEDIA'] )) {
             $aOD['OUT_DOC_MEDIA'] = 'Letter';
         }
         if (! isset( $aOD['OUT_DOC_LEFT_MARGIN'] )) {
             $aOD['OUT_DOC_LEFT_MARGIN'] = '15';
         }
         if (! isset( $aOD['OUT_DOC_RIGHT_MARGIN'] )) {
             $aOD['OUT_DOC_RIGHT_MARGIN'] = '15';
         }
         if (! isset( $aOD['OUT_DOC_TOP_MARGIN'] )) {
             $aOD['OUT_DOC_TOP_MARGIN'] = '15';
         }
         if (! isset( $aOD['OUT_DOC_BOTTOM_MARGIN'] )) {
             $aOD['OUT_DOC_BOTTOM_MARGIN'] = '15';
         }
         $aProperties['media'] = $aOD['OUT_DOC_MEDIA'];
         $aProperties['margins'] = array ('left' => $aOD['OUT_DOC_LEFT_MARGIN'],'right' => $aOD['OUT_DOC_RIGHT_MARGIN'],'top' => $aOD['OUT_DOC_TOP_MARGIN'],'bottom' => $aOD['OUT_DOC_BOTTOM_MARGIN']
         );
         if (isset($aOD['OUT_DOC_REPORT_GENERATOR'])) {
             $aProperties['report_generator'] = $aOD['OUT_DOC_REPORT_GENERATOR'];
         }
         $this->generate( $outputID, $Fields['APP_DATA'], $pathOutput, $sFilename, $aOD['OUT_DOC_TEMPLATE'], (boolean) $aOD['OUT_DOC_LANDSCAPE'], $aOD['OUT_DOC_GENERATE'], $aProperties , $applicationUid);
         //Plugin Hook PM_UPLOAD_DOCUMENT for upload document
         //G::LoadClass('plugin');
         $oPluginRegistry = & \PMPluginRegistry::getSingleton();
         if ($oPluginRegistry->existsTrigger( PM_UPLOAD_DOCUMENT ) && class_exists( 'uploadDocumentData' )) {
             $triggerDetail = $oPluginRegistry->getTriggerInfo( PM_UPLOAD_DOCUMENT );
             $aFields['APP_DOC_PLUGIN'] = $triggerDetail->sNamespace;
             $oAppDocument1 = new \AppDocument();
             $oAppDocument1->update( $aFields );
             $sPathName = PATH_DOCUMENT . \G::getPathFromUID($sApplication) . PATH_SEP;
             $oData['APP_UID'] = $sApplication;
             $oData['ATTACHMENT_FOLDER'] = true;
             switch ($aOD['OUT_DOC_GENERATE']) {
                 case "BOTH":
                     $documentData = new \uploadDocumentData( $sApplication, $sUserLogged, $pathOutput . $sFilename . '.pdf', $sFilename . '.pdf', $sDocUID, $oAppDocument->getDocVersion() );
                     $documentData->sFileType = "PDF";
                     $documentData->bUseOutputFolder = true;
                     $uploadReturn = $oPluginRegistry->executeTriggers( PM_UPLOAD_DOCUMENT, $documentData );
                     if ($uploadReturn) {
                         //Only delete if the file was saved correctly
                         unlink( $pathOutput . $sFilename . '.pdf' );
                     }
                     $documentData = new \uploadDocumentData( $sApplication, $sUserLogged, $pathOutput . $sFilename . '.doc', $sFilename . '.doc', $sDocUID, $oAppDocument->getDocVersion() );
                     $documentData->sFileType = "DOC";
                     $documentData->bUseOutputFolder = true;
                     $uploadReturn = $oPluginRegistry->executeTriggers( PM_UPLOAD_DOCUMENT, $documentData );
                     if ($uploadReturn) {
                         //Only delete if the file was saved correctly
                         unlink( $pathOutput . $sFilename . '.doc' );
                     }
                     break;
                 case "PDF":
                     $documentData = new \uploadDocumentData( $sApplication, $sUserLogged, $pathOutput . $sFilename . '.pdf', $sFilename . '.pdf', $sDocUID, $oAppDocument->getDocVersion() );
                     $documentData->sFileType = "PDF";
                     $documentData->bUseOutputFolder = true;
                     $uploadReturn = $oPluginRegistry->executeTriggers( PM_UPLOAD_DOCUMENT, $documentData );
                     if ($uploadReturn) {
                         //Only delete if the file was saved correctly
                         unlink( $pathOutput . $sFilename . '.pdf' );
                     }
                     break;
                 case "DOC":
                     $documentData = new \uploadDocumentData( $sApplication, $sUserLogged, $pathOutput . $sFilename . '.doc', $sFilename . '.doc', $sDocUID, $oAppDocument->getDocVersion() );
                     $documentData->sFileType = "DOC";
                     $documentData->bUseOutputFolder = true;
                     $uploadReturn = $oPluginRegistry->executeTriggers( PM_UPLOAD_DOCUMENT, $documentData );
                     if ($uploadReturn) {
                         //Only delete if the file was saved correctly
                         unlink( $pathOutput . $sFilename . '.doc' );
                     }
                     break;
             }
         }
         $g->sessionVarRestore();
         $oAppDocument = \AppDocumentPeer::retrieveByPK( $aFields['APP_DOC_UID'], $lastDocVersion);
         if ($oAppDocument->getAppDocStatus() == 'DELETED') {
             $oAppDocument->setAppDocStatus('ACTIVE');
             $oAppDocument->save();
         }
         $response = $this->getCasesOutputDocument($applicationUid, $userUid, $aFields['APP_DOC_UID']);
         return $response;
     } catch (\Exception $e) {
         throw $e;
     }
 }
예제 #23
0
 /**
  * With this function we can register a cron file
  * param string $cronFile
  * @return void
  */
 public function registerCronFile($cronFile)
 {
     $oPluginRegistry =& PMPluginRegistry::getSingleton();
     $oPluginRegistry->registerCronFile($this->sNamespace, $cronFile);
 }
예제 #24
0
 /**
  * Return the steps list criteria object
  * @param string $sTaskUID
  * @return array
  */
 public function getExtStepsCriteria($start, $limit, $sTaskUID = '')
 {
     try {
         //call plugin
         $oPluginRegistry =& PMPluginRegistry::getSingleton();
         $externalSteps = $oPluginRegistry->getSteps();
         $aSteps = array();
         $aSteps[] = array('STEP_TITLE' => 'char', 'STEP_UID' => 'char', 'STEP_TYPE_OBJ' => 'char', 'STEP_CONDITION' => 'char', 'STEP_POSITION' => 'integer', 'STEP_MODE' => 'char', 'STEP_UID_OBJ' => 'char');
         $oCriteria = new Criteria('workflow');
         $oCriteria->add(StepPeer::TAS_UID, $sTaskUID);
         $oCriteria->addAscendingOrderByColumn(StepPeer::STEP_POSITION);
         $this->tmpCriteria = clone $oCriteria;
         if ($start != '') {
             $oCriteria->setOffset($start);
         }
         if ($limit != '') {
             $oCriteria->setLimit($limit);
         }
         $oDataset = StepPeer::doSelectRS($oCriteria);
         $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
         $oDataset->next();
         while ($aRow = $oDataset->getRow()) {
             $urlEdit = '';
             $linkEditValue = '';
             switch ($aRow['STEP_TYPE_OBJ']) {
                 case 'DYNAFORM':
                     $oDynaform = new Dynaform();
                     $aFields = $oDynaform->load($aRow['STEP_UID_OBJ']);
                     $sTitle = $aFields['DYN_TITLE'];
                     /**
                      * @@@init2 PROCCESS FOR DIRECT EDIT LINK @by erik@colosa.com ON DATE 02/06/2008 18:48:13
                      */
                     $DYN_UID = $aFields['DYN_UID'];
                     $urlEdit = "dynaformEdit('" . $DYN_UID . "', '" . $aRow['PRO_UID'] . "');";
                     $linkEditValue = 'Edit';
                     /**
                      * @@@end2
                      */
                     break;
                 case 'INPUT_DOCUMENT':
                     $oInputDocument = new InputDocument();
                     $aFields = $oInputDocument->load($aRow['STEP_UID_OBJ']);
                     $sTitle = $aFields['INP_DOC_TITLE'];
                     break;
                 case 'OUTPUT_DOCUMENT':
                     $oOutputDocument = new OutputDocument();
                     $aFields = $oOutputDocument->load($aRow['STEP_UID_OBJ']);
                     $sTitle = $aFields['OUT_DOC_TITLE'];
                     break;
                 case 'EXTERNAL':
                     $sTitle = 'unknown ' . $aRow['STEP_UID'];
                     foreach ($externalSteps as $key => $val) {
                         if ($val->sStepId == $aRow['STEP_UID_OBJ']) {
                             $sTitle = $val->sStepTitle;
                             if (trim($val->sSetupStepPage) != '') {
                                 $urlEdit = "externalStepEdit('" . $aRow['STEP_UID'] . "', '" . $val->sSetupStepPage . "');";
                                 $linkEditValue = 'Edit';
                             } else {
                                 $urlEdit = "";
                                 $linkEditValue = '';
                             }
                         }
                     }
                     break;
             }
             $aSteps[] = array('STEP_TITLE' => $sTitle, 'STEP_UID' => $aRow['STEP_UID'], 'STEP_TYPE_OBJ' => $aRow['STEP_TYPE_OBJ'], 'STEP_CONDITION' => $aRow['STEP_CONDITION'], 'STEP_POSITION' => $aRow['STEP_POSITION'], 'urlEdit' => $urlEdit, 'linkEditValue' => $linkEditValue, 'PRO_UID' => $aRow['PRO_UID'], 'STEP_MODE' => $aRow['STEP_MODE'], 'STEP_UID_OBJ' => $aRow['STEP_UID_OBJ']);
             $oDataset->next();
         }
         global $_DBArray;
         $_DBArray = isset($_SESSION['_DBArray']) ? $_SESSION['_DBArray'] : '';
         $_DBArray['steps'] = $aSteps;
         $_SESSION['_DBArray'] = $_DBArray;
         G::LoadClass('ArrayPeer');
         $oCriteria = new Criteria('dbarray');
         $oCriteria->setDBArrayTable('steps');
         $oCriteria->addAscendingOrderByColumn('STEP_POSITION');
         //return $oCriteria;
         return $_SESSION['_DBArray']['steps'];
     } catch (Exception $oError) {
         throw $oError;
     }
 }
예제 #25
0
 function uninstallPluginWorkspaces($arrayPlugin)
 {
     G::LoadClass("system");
     G::LoadClass("wsTools");
     $workspace = System::listWorkspaces();
     foreach ($workspace as $indexWS => $ws) {
         $wsPathDataSite = PATH_DATA . "sites" . PATH_SEP . $ws->name . PATH_SEP;
         if (file_exists($wsPathDataSite . "plugin.singleton")) {
             //G::LoadClass("plugin");
             //Here we are loading all plug-ins registered
             //The singleton has a list of enabled plug-ins
             $pluginRegistry =& PMPluginRegistry::getSingleton();
             $pluginRegistry->unSerializeInstance(file_get_contents($wsPathDataSite . "plugin.singleton"));
             ///////
             $attributes = $pluginRegistry->getAttributes();
             foreach ($arrayPlugin as $index => $value) {
                 if (isset($attributes["_aPluginDetails"][$value])) {
                     $pluginRegistry->disablePlugin($value, 0);
                 }
             }
             ///////
             file_put_contents($wsPathDataSite . "plugin.singleton", $pluginRegistry->serializeInstance());
         }
     }
 }
예제 #26
0
 public function caseSchedulerCron($date, &$log = array(), $cron = 0)
 {
     G::LoadClass('dates');
     require_once 'classes/model/LogCasesScheduler.php';
     $oDates = new dates();
     $nTime = strtotime($date);
     $dCurrentDate = date('Y-m-d', $nTime) . ' 00:00:00';
     $dNextDay = date('Y-m-d', strtotime("{$dCurrentDate}")) . ' 23:59:59';
     $oCriteria = $this->getAllCriteria();
     $oCriteria->addAnd(CaseSchedulerPeer::SCH_STATE, 'INACTIVE', Criteria::NOT_EQUAL);
     $oCriteria->addAnd(CaseSchedulerPeer::SCH_STATE, 'PROCESSED', Criteria::NOT_EQUAL);
     $oCriteria->add($oCriteria->getNewCriterion(CaseSchedulerPeer::SCH_TIME_NEXT_RUN, $dCurrentDate, Criteria::GREATER_EQUAL)->addAnd($oCriteria->getNewCriterion(CaseSchedulerPeer::SCH_TIME_NEXT_RUN, $dNextDay, Criteria::LESS_EQUAL))->addOr($oCriteria->getNewCriterion(CaseSchedulerPeer::SCH_OPTION, '5', Criteria::GREATER_EQUAL)));
     $oCriteria->add(CaseSchedulerPeer::SCH_END_DATE, null, Criteria::EQUAL);
     $oCriteria->addOr(CaseSchedulerPeer::SCH_END_DATE, $dCurrentDate, Criteria::GREATER_EQUAL);
     $oDataset = CaseSchedulerPeer::doSelectRS($oCriteria);
     $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
     $oDataset->next();
     $sValue = '';
     $sActualTime = '';
     $sDaysPerformTask = '';
     $sWeeks = '';
     $sStartDay = '';
     $sMonths = '';
     while ($aRow = $oDataset->getRow()) {
         if ($cron == 1) {
             $arrayCron = unserialize(trim(@file_get_contents(PATH_DATA . "cron")));
             $arrayCron["processcTimeStart"] = time();
             @file_put_contents(PATH_DATA . "cron", serialize($arrayCron));
         }
         $sSchedulerUid = $aRow['SCH_UID'];
         $sOption = $aRow['SCH_OPTION'];
         switch ($sOption) {
             case '1':
                 $sDaysPerformTask = $aRow['SCH_DAYS_PERFORM_TASK'];
                 $aDaysPerformTask = explode('|', $sDaysPerformTask);
                 $sValue = $aDaysPerformTask[0];
                 if ($sValue != 1) {
                     $sDaysPerformTask = $aDaysPerformTask[1];
                 }
                 break;
             case '2':
                 $sDaysPerformTask = $aRow['SCH_EVERY_DAYS'];
                 $sWeeks = $aRow['SCH_WEEK_DAYS'];
                 break;
             case '3':
                 $sStartDay = $aRow['SCH_START_DAY'];
                 $sMonths = $aRow['SCH_MONTHS'];
                 $aStartDay = explode('|', $sStartDay);
                 $sValue = $aStartDay[0];
                 break;
             case '4':
                 $aRow['SCH_STATE'] = 'PROCESSED';
                 break;
             case '5':
                 break;
         }
         $sActualTime = $aRow['SCH_TIME_NEXT_RUN'];
         $sActualDataHour = date('H', strtotime($aRow['SCH_TIME_NEXT_RUN']));
         $sActualDataMinutes = date('i', strtotime($aRow['SCH_TIME_NEXT_RUN']));
         $dActualSysHour = date('H', $nTime);
         $dActualSysHour = $dActualSysHour == '00' ? '24' : $dActualSysHour;
         $dActualSysMinutes = date('i', $nTime);
         $sActualDataTime = strtotime($aRow['SCH_TIME_NEXT_RUN']);
         $sActualSysTime = strtotime($nTime);
         // note added consider the posibility to encapsulate some in functionality in a class method or some funtions
         if ($sActualDataHour < $dActualSysHour) {
             $_PORT = SERVER_PORT != '80' ? ':' . SERVER_PORT : '';
             $defaultEndpoint = 'http://' . SERVER_NAME . $_PORT . '/sys' . SYS_SYS . '/' . SYS_LANG . '/classic/services/wsdl2';
             println(" - Connecting webservice: {$defaultEndpoint}");
             $user = $aRow["SCH_DEL_USER_NAME"];
             $pass = $aRow["SCH_DEL_USER_PASS"];
             $processId = $aRow["PRO_UID"];
             $taskId = $aRow["TAS_UID"];
             $client = new SoapClient($defaultEndpoint);
             $params = array('userid' => $user, 'password' => 'md5:' . $pass);
             $result = $client->__SoapCall('login', array($params));
             eprint(" - Logging as user {$user}.............");
             if ($result->status_code == 0) {
                 eprintln("OK+", 'green');
                 $sessionId = $result->message;
                 $newCaseLog = new LogCasesScheduler();
                 $newRouteLog = new LogCasesScheduler();
                 $variables = array();
                 $params = array('sessionId' => $sessionId, 'processId' => $processId, 'taskId' => $taskId, 'variables' => $variables);
                 $paramsLog = array('PRO_UID' => $processId, 'TAS_UID' => $taskId, 'SCH_UID' => $sSchedulerUid, 'USR_NAME' => $user, 'RESULT' => '', 'EXEC_DATE' => date('Y-m-d'), 'EXEC_HOUR' => date('H:i:s'), 'WS_CREATE_CASE_STATUS' => '', 'WS_ROUTE_CASE_STATUS' => '');
                 $sw_transfer_control_plugin = false;
                 //This SW will be true only if a plugin is allowed to continue the action
                 //If this Job was was registered to be performed by a plugin
                 if (isset($aRow['CASE_SH_PLUGIN_UID']) && $aRow['CASE_SH_PLUGIN_UID'] != "") {
                     //Check if the plugin is active
                     $pluginParts = explode("--", $aRow['CASE_SH_PLUGIN_UID']);
                     if (count($pluginParts) == 2) {
                         //***************** Plugins **************************
                         G::LoadClass('plugin');
                         //here we are loading all plugins registered
                         //the singleton has a list of enabled plugins
                         $sSerializedFile = PATH_DATA_SITE . 'plugin.singleton';
                         $oPluginRegistry =& PMPluginRegistry::getSingleton();
                         if (file_exists($sSerializedFile)) {
                             $oPluginRegistry->unSerializeInstance(file_get_contents($sSerializedFile));
                         }
                         $oPluginRegistry =& PMPluginRegistry::getSingleton();
                         $activePluginsForCaseScheduler = $oPluginRegistry->getCaseSchedulerPlugins();
                         foreach ($activePluginsForCaseScheduler as $key => $caseSchedulerPlugin) {
                             if (isset($caseSchedulerPlugin->sNamespace) && $caseSchedulerPlugin->sNamespace == $pluginParts[0] && isset($caseSchedulerPlugin->sActionId) && $caseSchedulerPlugin->sActionId == $pluginParts[1]) {
                                 $sw_transfer_control_plugin = true;
                                 $caseSchedulerSelected = $caseSchedulerPlugin;
                             }
                         }
                     }
                 }
                 //If there is a trigger that is registered to do this then transfer control
                 if (isset($caseSchedulerSelected) && is_object($caseSchedulerSelected)) {
                     eprintln(" - Transfering control to a Plugin: " . $caseSchedulerSelected->sNamespace . "/" . $caseSchedulerSelected->sActionId, 'green');
                     $oData['OBJ_SOAP'] = $client;
                     $oData['SCH_UID'] = $aRow['SCH_UID'];
                     $oData['params'] = $params;
                     $oData['sessionId'] = $sessionId;
                     $oData['userId'] = $user;
                     $paramsLogResultFromPlugin = $oPluginRegistry->executeMethod($caseSchedulerSelected->sNamespace, $caseSchedulerSelected->sActionExecute, $oData);
                     $paramsLog['WS_CREATE_CASE_STATUS'] = $paramsLogResultFromPlugin['WS_CREATE_CASE_STATUS'];
                     $paramsLog['WS_ROUTE_CASE_STATUS'] = $paramsLogResultFromPlugin['WS_ROUTE_CASE_STATUS'];
                     $paramsLogResult = $paramsLogResultFromPlugin['paramsLogResult'];
                     $paramsRouteLogResult = $paramsLogResultFromPlugin['paramsRouteLogResult'];
                 } else {
                     eprint(" - Creating the new case.............");
                     $paramsAux = $params;
                     $paramsAux["executeTriggers"] = 1;
                     $result = $client->__SoapCall("NewCase", array($paramsAux));
                     if ($result->status_code == 0) {
                         eprintln("OK+ CASE #{$result->caseNumber} was created!", 'green');
                         $caseId = $result->caseId;
                         $caseNumber = $result->caseNumber;
                         $log[] = $caseNumber . ' was created!, ProcessID: ' . $aRow['PRO_UID'];
                         $paramsLog['WS_CREATE_CASE_STATUS'] = "Case " . $caseNumber . " " . strip_tags($result->message);
                         $paramsLogResult = 'SUCCESS';
                         $params = array('sessionId' => $sessionId, 'caseId' => $caseId, 'delIndex' => "1");
                         eprint(" - Routing the case #{$caseNumber}..............");
                         try {
                             $result = $client->__SoapCall('RouteCase', array($params));
                             if ($result->status_code == 0) {
                                 $paramsLog['WS_ROUTE_CASE_STATUS'] = strip_tags($result->message);
                                 $retMsg = explode("Debug", $paramsLog['WS_ROUTE_CASE_STATUS']);
                                 $retMsg = $retMsg[0];
                                 eprintln("OK+ {$retMsg}", 'green');
                                 $paramsRouteLogResult = 'SUCCESS';
                             } else {
                                 $paramsLog['WS_ROUTE_CASE_STATUS'] = strip_tags($result->message);
                                 eprintln("FAILED-> {$paramsLog['WS_ROUTE_CASE_STATUS']}", 'red');
                                 $paramsRouteLogResult = 'FAILED';
                             }
                         } catch (Exception $oError) {
                             setExecutionResultMessage('    WITH ERRORS', 'error');
                             $paramsLog['WS_ROUTE_CASE_STATUS'] = strip_tags($oError->getMessage());
                             eprintln("  '-" . strip_tags($oError->getMessage()), 'red');
                             $paramsRouteLogResult = 'FAILED';
                         }
                     } else {
                         $paramsLog['WS_CREATE_CASE_STATUS'] = strip_tags($result->message);
                         $paramsLogResult = 'FAILED';
                     }
                 }
             } else {
                 eprintln($result->message, 'red');
                 // invalid user or  bad password
             }
             if ($paramsLogResult == 'SUCCESS' && $paramsRouteLogResult == 'SUCCESS') {
                 $paramsLog['RESULT'] = 'SUCCESS';
             } else {
                 $paramsLog['RESULT'] = 'FAILED';
             }
             $newCaseLog->saveLogParameters($paramsLog);
             $newCaseLog->save();
             if ($sOption != '4' && $sOption != '5') {
                 $nSchLastRunTime = $sActualTime;
                 $dEstimatedDate = $this->updateNextRun($sOption, $sValue, $sActualTime, $sDaysPerformTask, $sWeeks, $sStartDay, $sMonths);
                 if ($aRow['SCH_END_DATE'] != '') {
                     if (date("Y-m-d", strtotime($dEstimatedDate)) > date("Y-m-d", strtotime($aRow['SCH_END_DATE']))) {
                         $Fields = $this->Load($sSchedulerUid);
                         $Fields['SCH_LAST_STATE'] = $aRow['SCH_STATE'];
                         $Fields['SCH_STATE'] = 'PROCESSED';
                         $this->Update($Fields);
                     }
                 }
                 $nSchTimeNextRun = $dEstimatedDate;
                 $this->updateDate($sSchedulerUid, $nSchTimeNextRun, $nSchLastRunTime);
             } elseif ($sOption != '5') {
                 $Fields = $this->Load($sSchedulerUid);
                 $Fields['SCH_LAST_STATE'] = $aRow['SCH_STATE'];
                 $Fields['SCH_LAST_RUN_TIME'] = $Fields['SCH_TIME_NEXT_RUN'];
                 $Fields['SCH_STATE'] = 'PROCESSED';
                 $this->Update($Fields);
             } else {
                 $nSchLastRunTime = $sActualTime;
                 $Fields = $this->Load($sSchedulerUid);
                 $Fields['SCH_LAST_RUN_TIME'] = $Fields['SCH_TIME_NEXT_RUN'];
                 //$nSchTimeNextRun = strtotime( $Fields['SCH_TIME_NEXT_RUN'] );
                 $nSchTimeNextRun = $nTime;
                 $nextRun = $Fields['SCH_REPEAT_EVERY'] * 60 * 60;
                 $nSchTimeNextRun += $nextRun;
                 $nSchTimeNextRun = date("Y-m-d H:i", $nSchTimeNextRun);
                 $this->updateDate($sSchedulerUid, $nSchTimeNextRun, $nSchLastRunTime);
             }
         } elseif ($sActualDataHour == $dActualSysHour && $sActualDataMinutes <= $dActualSysMinutes) {
             $_PORT = '';
             if (isset($_SERVER['SERVER_PORT'])) {
                 $_PORT = $_SERVER['SERVER_PORT'] != '80' ? ':' . $_SERVER['SERVER_PORT'] : '';
             } elseif (defined('SERVER_PORT')) {
                 $_PORT = SERVER_PORT != '80' ? ':' . SERVER_PORT : '';
             }
             //$defaultEndpoint = 'http://' . $_SERVER ['SERVER_NAME'] . ':' . $_PORT . '/sys' . SYS_SYS .'/'.SYS_LANG.'/classic/green/services/wsdl2';
             $defaultEndpoint = 'http://' . SERVER_NAME . $_PORT . '/sys' . SYS_SYS . '/' . SYS_LANG . '/classic/services/wsdl2';
             println(" - Connecting webservice: {$defaultEndpoint}");
             $user = $aRow["SCH_DEL_USER_NAME"];
             $pass = $aRow["SCH_DEL_USER_PASS"];
             $processId = $aRow["PRO_UID"];
             $taskId = $aRow["TAS_UID"];
             $client = new SoapClient($defaultEndpoint);
             $params = array('userid' => $user, 'password' => 'md5:' . $pass);
             $result = $client->__SoapCall('login', array($params));
             eprint(" - Logging as user {$user}.............");
             if ($result->status_code == 0) {
                 eprintln("OK+", 'green');
                 $sessionId = $result->message;
                 $newCaseLog = new LogCasesScheduler();
                 $newRouteLog = new LogCasesScheduler();
                 $variables = array();
                 $params = array('sessionId' => $sessionId, 'processId' => $processId, 'taskId' => $taskId, 'variables' => $variables);
                 $paramsLog = array('PRO_UID' => $processId, 'TAS_UID' => $taskId, 'SCH_UID' => $sSchedulerUid, 'USR_NAME' => $user, 'RESULT' => '', 'EXEC_DATE' => date('Y-m-d'), 'EXEC_HOUR' => date('H:i:s'), 'WS_CREATE_CASE_STATUS' => '', 'WS_ROUTE_CASE_STATUS' => '');
                 $paramsAux = $params;
                 $paramsAux["executeTriggers"] = 1;
                 $result = $client->__SoapCall("NewCase", array($paramsAux));
                 eprint(" - Creating the new case.............");
                 if ($result->status_code == 0) {
                     eprintln("OK+ CASE #{$result->caseNumber} was created!", 'green');
                     $caseId = $result->caseId;
                     $caseNumber = $result->caseNumber;
                     $log[] = $caseNumber . ' was created!, ProcessID: ' . $aRow['PRO_UID'];
                     $paramsLog['WS_CREATE_CASE_STATUS'] = "Case " . $caseNumber . " " . strip_tags($result->message);
                     $paramsLogResult = 'SUCCESS';
                     $params = array('sessionId' => $sessionId, 'caseId' => $caseId, 'delIndex' => "1");
                     try {
                         $result = $client->__SoapCall('RouteCase', array($params));
                         eprint(" - Routing the case #{$caseNumber}..............");
                         if ($result->status_code == 0) {
                             $paramsLog['WS_ROUTE_CASE_STATUS'] = strip_tags($result->message);
                             $retMsg = explode("Debug", $paramsLog['WS_ROUTE_CASE_STATUS']);
                             $retMsg = $retMsg[0];
                             eprintln("OK+ {$retMsg}", 'green');
                             $paramsRouteLogResult = 'SUCCESS';
                         } else {
                             eprintln("FAILED-> {$paramsLog['WS_ROUTE_CASE_STATUS']}", 'red');
                             $paramsLog['WS_ROUTE_CASE_STATUS'] = strip_tags($result->message);
                             $paramsRouteLogResult = 'FAILED';
                         }
                     } catch (Exception $oError) {
                         setExecutionResultMessage('    WITH ERRORS', 'error');
                         $paramsLog['WS_ROUTE_CASE_STATUS'] = strip_tags($oError->getMessage());
                         eprintln("  '-" . strip_tags($oError->getMessage()), 'red');
                         $paramsRouteLogResult = 'FAILED';
                     }
                 } else {
                     $paramsLog['WS_CREATE_CASE_STATUS'] = strip_tags($result->message);
                     eprintln("FAILED->{$paramsLog['WS_CREATE_CASE_STATUS']}", 'red');
                     $paramsLogResult = 'FAILED';
                 }
             } else {
                 // invalid user or  bad password
                 eprintln($result->message, 'red');
             }
             if ($paramsLogResult == 'SUCCESS' && $paramsRouteLogResult == 'SUCCESS') {
                 $paramsLog['RESULT'] = 'SUCCESS';
             } else {
                 $paramsLog['RESULT'] = 'FAILED';
             }
             $newCaseLog->saveLogParameters($paramsLog);
             $newCaseLog->save();
             if ($sOption != '4' && $sOption != '5') {
                 $nSchLastRunTime = $sActualTime;
                 $dEstimatedDate = $this->updateNextRun($sOption, $sValue, $sActualTime, $sDaysPerformTask, $sWeeks, $sStartDay, $sMonths);
                 if ($aRow['SCH_END_DATE'] != '') {
                     if (date("Y-m-d", strtotime($dEstimatedDate)) > date("Y-m-d", strtotime($aRow['SCH_END_DATE']))) {
                         $Fields = $this->Load($sSchedulerUid);
                         $Fields['SCH_LAST_STATE'] = $aRow['SCH_STATE'];
                         $Fields['SCH_STATE'] = 'PROCESSED';
                         $this->Update($Fields);
                     }
                 }
                 $nSchTimeNextRun = $dEstimatedDate;
                 $this->updateDate($sSchedulerUid, $nSchTimeNextRun, $nSchLastRunTime);
             } elseif ($sOption != '5') {
                 $Fields = $this->Load($sSchedulerUid);
                 $Fields['SCH_LAST_STATE'] = $aRow['SCH_STATE'];
                 $Fields['SCH_LAST_RUN_TIME'] = $Fields['SCH_TIME_NEXT_RUN'];
                 $Fields['SCH_STATE'] = 'PROCESSED';
                 $this->Update($Fields);
             } else {
                 $nSchLastRunTime = $sActualTime;
                 $Fields = $this->Load($sSchedulerUid);
                 $Fields['SCH_LAST_RUN_TIME'] = $Fields['SCH_TIME_NEXT_RUN'];
                 //$nSchTimeNextRun = strtotime( $Fields['SCH_TIME_NEXT_RUN'] );
                 $nSchTimeNextRun = $nTime;
                 $nextRun = $Fields['SCH_REPEAT_EVERY'] * 60 * 60;
                 $nSchTimeNextRun += $nextRun;
                 $nSchTimeNextRun = date("Y-m-d H:i", $nSchTimeNextRun);
                 $this->updateDate($sSchedulerUid, $nSchTimeNextRun, $nSchLastRunTime);
             }
         }
         $oDataset->next();
     }
 }
예제 #27
0
 private function _default()
 {
     require_once PATH_THIRDPARTY . 'smarty/libs/Smarty.class.php';
     // put full path to Smarty.class.php
     global $G_ENABLE_BLANK_SKIN;
     //menu
     global $G_PUBLISH;
     global $G_MAIN_MENU;
     global $G_SUB_MENU;
     global $G_MENU_SELECTED;
     global $G_SUB_MENU_SELECTED;
     global $G_ID_MENU_SELECTED;
     global $G_ID_SUB_MENU_SELECTED;
     G::verifyPath(PATH_SMARTY_C, true);
     G::verifyPath(PATH_SMARTY_CACHE, true);
     $smarty = new Smarty();
     $oHeadPublisher =& headPublisher::getSingleton();
     $smarty->compile_dir = PATH_SMARTY_C;
     $smarty->cache_dir = PATH_SMARTY_CACHE;
     $smarty->config_dir = PATH_THIRDPARTY . 'smarty/configs';
     //To setup en extJS Theme for this Skin
     G::LoadClass('serverConfiguration');
     $oServerConf =& serverConf::getSingleton();
     $extSkin = $oServerConf->getProperty("extSkin");
     if (!$extSkin) {
         $extSkin = array();
     }
     $extSkin[SYS_SKIN] = "xtheme-gray";
     $oServerConf->setProperty("extSkin", $extSkin);
     //End of extJS Theme setup
     if (isset($G_ENABLE_BLANK_SKIN) && $G_ENABLE_BLANK_SKIN) {
         $smarty->template_dir = $this->layoutFileBlank['dirname'];
         $smarty->force_compile = $this->forceTemplateCompile;
         $smarty->display($layoutFileBlank['basename']);
     } else {
         $smarty->template_dir = $this->layoutFile['dirname'];
         $meta = null;
         $header = null;
         if (preg_match("/^.*\\(.*MSIE (\\d+)\\..+\\).*\$/", $_SERVER["HTTP_USER_AGENT"], $arrayMatch)) {
             $ie = intval($arrayMatch[1]);
             if ($ie == 10) {
                 $ie = 8;
                 $meta = "<meta http-equiv=\"X-UA-Compatible\" content=\"IE={$ie}\" />";
             }
         }
         if (isset($oHeadPublisher)) {
             if (defined('SYS_SYS')) {
                 $oHeadPublisher->title = isset($_SESSION['USR_USERNAME']) ? '(' . $_SESSION['USR_USERNAME'] . ' ' . G::LoadTranslation('ID_IN') . ' ' . SYS_SYS . ')' : '';
             }
             $header = $oHeadPublisher->printHeader();
             $header .= $oHeadPublisher->getExtJsStylesheets($this->cssFileName);
         }
         $smarty->assign("meta", $meta);
         $smarty->assign("header", $header);
         $footer = '';
         if (strpos($_SERVER['REQUEST_URI'], '/login/login') !== false) {
             $freeOfChargeText = "";
             if (!defined('SKIP_FREE_OF_CHARGE_TEXT')) {
                 $freeOfChargeText = "Supplied free of charge with no support, certification, warranty, <br>maintenance nor indemnity by Colosa and its Certified Partners.";
             }
             if (class_exists('pmLicenseManager')) {
                 $freeOfChargeText = "";
             }
             $fileFooter = PATH_SKINS . SYS_SKIN . PATH_SEP . 'footer.html';
             if (file_exists($fileFooter)) {
                 $footer .= file_get_contents($fileFooter);
             } else {
                 $fileFooter = PATH_SKIN_ENGINE . SYS_SKIN . PATH_SEP . 'footer.html';
                 if (file_exists($fileFooter)) {
                     $footer .= file_get_contents($fileFooter);
                 } else {
                     $fileFooter = PATH_CUSTOM_SKINS . SYS_SKIN . PATH_SEP . 'footer.html';
                     if (file_exists($fileFooter)) {
                         $footer .= file_get_contents($fileFooter);
                     } else {
                         $footer .= "<br />Copyright &copy; 2003-" . date('Y') . " <a href=\"http://www.colosa.com\" alt=\"Colosa, Inc.\" target=\"_blank\">Colosa, Inc.</a> All rights reserved.<br /> {$freeOfChargeText} " . "<br><br/><a href=\"http://www.processmaker.com\" alt=\"Powered by ProcessMaker - Open Source Workflow & Business Process Management (BPM) Management Software\" title=\"Powered by ProcessMaker\" target=\"_blank\"></a>";
                     }
                 }
             }
         }
         $oMenu = new Menu();
         $menus = $oMenu->generateArrayForTemplate($G_MAIN_MENU, 'SelectedMenu', 'mainMenu', $G_MENU_SELECTED, $G_ID_MENU_SELECTED);
         $smarty->assign('menus', $menus);
         $oSubMenu = new Menu();
         $subMenus = $oSubMenu->generateArrayForTemplate($G_SUB_MENU, 'selectedSubMenu', 'subMenu', $G_SUB_MENU_SELECTED, $G_ID_SUB_MENU_SELECTED);
         $smarty->assign('subMenus', $subMenus);
         if (!defined('NO_DISPLAY_USERNAME')) {
             define('NO_DISPLAY_USERNAME', 0);
         }
         if (NO_DISPLAY_USERNAME == 0) {
             $switch_interface = isset($_SESSION['user_experience']) && $_SESSION['user_experience'] == 'SWITCHABLE';
             $smarty->assign('user_logged', isset($_SESSION['USER_LOGGED']) ? $_SESSION['USER_LOGGED'] : '');
             $smarty->assign('tracker', SYS_COLLECTION == 'tracker' ? $G_PUBLISH->Parts[0]['File'] != 'tracker/login' ? true : '' : '');
             $smarty->assign('switch_interface', $switch_interface);
             $smarty->assign('switch_interface_label', G::LoadTranslation('ID_SWITCH_INTERFACE'));
             $smarty->assign('rolename', isset($_SESSION['USR_ROLENAME']) ? $_SESSION['USR_ROLENAME'] . '' : '');
             $smarty->assign('pipe', isset($_SESSION['USR_USERNAME']) ? ' | ' : '');
             $smarty->assign('logout', G::LoadTranslation('ID_LOGOUT'));
             $smarty->assign('workspace', defined('SYS_SYS') ? SYS_SYS : '');
             $uws = isset($_SESSION['USR_ROLENAME']) && $_SESSION['USR_ROLENAME'] != '' ? strtolower(G::LoadTranslation('ID_WORKSPACE_USING')) : G::LoadTranslation('ID_WORKSPACE_USING');
             $smarty->assign('workspace_label', $uws);
             G::LoadClass("configuration");
             $conf = new Configurations();
             $conf->getFormats();
             if (defined('SYS_SYS')) {
                 $smarty->assign('udate', $conf->getSystemDate(date('Y-m-d H:i:s')));
             } else {
                 $smarty->assign('udate', G::getformatedDate(date('Y-m-d H:i:s'), 'M d, yyyy', SYS_LANG));
             }
             $name = $conf->userNameFormat(isset($_SESSION['USR_USERNAME']) ? $_SESSION['USR_USERNAME'] : '', isset($_SESSION['USR_FULLNAME']) ? htmlentities($_SESSION['USR_FULLNAME'], ENT_QUOTES, 'UTF-8') : '', isset($_SESSION['USER_LOGGED']) ? $_SESSION['USER_LOGGED'] : '');
             $smarty->assign('user', $name);
         }
         if (class_exists('pmLicenseManager')) {
             $pmLicenseManagerO =& pmLicenseManager::getSingleton();
             $expireIn = $pmLicenseManagerO->getExpireIn();
             $expireInLabel = $pmLicenseManagerO->getExpireInLabel();
             //if($expireIn<=30){
             if ($expireInLabel != "") {
                 $smarty->assign('msgVer', '<label class="textBlack">' . $expireInLabel . '</label>&nbsp;&nbsp;');
             }
             //}
         }
         if (defined('SYS_SYS')) {
             $logout = '/sys' . SYS_SYS . '/' . SYS_LANG . '/' . SYS_SKIN . '/login/login';
         } else {
             $logout = '/sys/' . SYS_LANG . '/' . SYS_SKIN . '/login/login';
         }
         $smarty->assign('linklogout', $logout);
         $smarty->assign('footer', $footer);
         $smarty->assign('tpl_menu', PATH_TEMPLATE . 'menu.html');
         $smarty->assign('tpl_submenu', PATH_TEMPLATE . 'submenu.html');
         G::LoadClass('replacementLogo');
         $oLogoR = new replacementLogo();
         if (defined("SYS_SYS")) {
             $aFotoSelect = $oLogoR->getNameLogo(isset($_SESSION['USER_LOGGED']) ? $_SESSION['USER_LOGGED'] : '');
             if (is_array($aFotoSelect)) {
                 $sFotoSelect = trim($aFotoSelect['DEFAULT_LOGO_NAME']);
                 $sWspaceSelect = trim($aFotoSelect['WORKSPACE_LOGO_NAME']);
             }
         }
         if (class_exists('PMPluginRegistry')) {
             $oPluginRegistry =& PMPluginRegistry::getSingleton();
             if (isset($sFotoSelect) && $sFotoSelect != '' && !strcmp($sWspaceSelect, SYS_SYS)) {
                 $sCompanyLogo = $oPluginRegistry->getCompanyLogo($sFotoSelect);
                 $sCompanyLogo = "/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN . "/setup/showLogoFile.php?id=" . base64_encode($sCompanyLogo);
             } else {
                 $sCompanyLogo = $oPluginRegistry->getCompanyLogo('/images/processmaker.logo.jpg');
             }
         } else {
             $sCompanyLogo = '/images/processmaker.logo.jpg';
         }
         $smarty->assign('logo_company', $sCompanyLogo);
         $smarty->force_compile = $this->forceTemplateCompile;
         $smarty->display($this->layoutFile['basename']);
     }
 }
예제 #28
0
 /**
  * Function xmlformTemplate
  *
  * @author David S. Callizaya S. <*****@*****.**>
  * @access public
  * @param string form
  * @param string templateFile
  * @return string
  */
 public function parseFile($filename, $language, $forceParse)
 {
     $this->language = $language;
     $filenameInitial = $filename;
     $filename = $this->home . $filename;
     //if the xmlform file doesn't exists, then try with the plugins folders
     if (!is_file($filename)) {
         $aux = explode(PATH_SEP, $filenameInitial);
         //check if G_PLUGIN_CLASS is defined, because publisher can be called without an environment
         if (count($aux) > 2) {
             //Subfolders
             $filename = array_pop($aux);
             $aux0 = implode(PATH_SEP, $aux);
             $aux = array();
             $aux[0] = $aux0;
             $aux[1] = $filename;
         }
         if (count($aux) == 2 && defined('G_PLUGIN_CLASS')) {
             $oPluginRegistry =& PMPluginRegistry::getSingleton();
             if ($response = $oPluginRegistry->isRegisteredFolder($aux[0])) {
                 if ($response !== true) {
                     $sPath = PATH_PLUGINS . $response . PATH_SEP;
                 } else {
                     $sPath = PATH_PLUGINS;
                 }
                 $filename = $sPath . $aux[0] . PATH_SEP . $aux[1];
             }
         }
     }
     $this->fileName = $filename;
     $parsedFile = dirname($filename) . PATH_SEP . basename($filename, 'xml') . $language;
     $parsedFilePath = defined('PATH_C') ? defined('SYS_SYS') ? PATH_C . 'ws' . PATH_SEP . SYS_SYS . PATH_SEP : PATH_C : PATH_DATA;
     $parsedFilePath .= 'xmlform/' . substr($parsedFile, strlen($this->home));
     // Improvement for the js cache - Start
     $realPath = substr(realpath($this->fileName), strlen(realpath($this->home)), -4);
     if (substr($realPath, 0, 1) != PATH_SEP) {
         $realPath = PATH_SEP . $realPath;
     }
     $filesToDelete = substr((defined('PATH_C') ? PATH_C : PATH_DATA) . 'xmlform/', 0, -1) . $realPath . '.*.js';
     $auxPath = explode(PATH_SEP, $realPath);
     $auxPath[count($auxPath) - 1] = $auxPath[count($auxPath) - 1] . '.' . md5(filemtime($this->fileName));
     $realPath = implode(PATH_SEP, $auxPath);
     // Improvement for the js cache - End
     $this->parsedFile = $parsedFilePath;
     $this->scriptURL = '/jsform' . $realPath . '.js';
     $this->scriptFile = substr((defined('PATH_C') ? PATH_C : PATH_DATA) . 'xmlform/', 0, -1) . substr($this->scriptURL, 7);
     $this->id = G::createUID('', substr($this->fileName, strlen($this->home)));
     $this->scriptURL = str_replace('\\', '/', $this->scriptURL);
     $newVersion = false;
     if ($forceParse || (!file_exists($this->parsedFile) || filemtime($filename) > filemtime($this->parsedFile) || filemtime(__FILE__) > filemtime($this->parsedFile)) || !file_exists($this->scriptFile) || filemtime($filename) > filemtime($this->scriptFile)) {
         if (glob($filesToDelete)) {
             foreach (glob($filesToDelete) as $fileToDelete) {
                 @unlink($fileToDelete);
             }
         }
         $this->tree = new Xml_Document();
         $this->tree->parseXmlFile($filename);
         //$this->tree->unsetParent();
         if (!is_object($this->tree->children[0])) {
             throw new Exception('Failure loading root node.');
         }
         $this->tree =& $this->tree->children[0]->toTree();
         //ERROR CODE [1] : Failed to read the xml document
         if (!isset($this->tree)) {
             return 1;
         }
         $xmlNode =& $this->tree->children;
         //Set the form's attributes
         $myAttributes = get_class_vars(get_class($this));
         foreach ($myAttributes as $k => $v) {
             $myAttributes[$k] = strtolower($k);
         }
         foreach ($this->tree->attributes as $k => $v) {
             $key = array_search(strtolower($k), $myAttributes);
             if ($key !== false && strtolower($k) !== 'fields' && strtolower($k) !== 'values') {
                 $this->{$key} = $v;
             }
         }
         //Reeplace non valid characters in xmlform name with "_"
         $this->name = preg_replace('/\\W/', '_', $this->name);
         //Create fields
         foreach ($xmlNode as $k => $v) {
             if ($xmlNode[$k]->type !== 'cdata' && isset($xmlNode[$k]->attributes['type'])) {
                 if (class_exists('XmlForm_Field_' . $xmlNode[$k]->attributes['type'])) {
                     $x = '$field = new XmlForm_Field_' . $xmlNode[$k]->attributes['type'] . '( $xmlNode[$k], $language, $this->home, $this);';
                     eval($x);
                 } else {
                     $field = new XmlForm_Field($xmlNode[$k], $language, $this->home, $this);
                 }
                 $field->language = $this->language;
                 $this->fields[$field->name] = $field;
             }
             if (isset($xmlNode[$k]->attributes['required']) || isset($xmlNode[$k]->attributes['validate'])) {
                 // the fields or xml nodes with a required attribute are put in an array that is passed to the view file
                 $isEditMode = isset($xmlNode[$k]->attributes['mode']) && $xmlNode[$k]->attributes['mode'] == 'view' ? false : true;
                 if ($isEditMode && $this->mode != 'view') {
                     $validateValue = "";
                     if (isset($xmlNode[$k]->attributes['validate'])) {
                         $validateValue = $xmlNode[$k]->attributes['validate'];
                     }
                     $requiredValue = "0";
                     if (isset($xmlNode[$k]->attributes['required'])) {
                         $requiredValue = $xmlNode[$k]->attributes['required'] == 1 ? '1' : '0';
                     }
                     $this->requiredFields[] = array('name' => $field->name, 'type' => $xmlNode[$k]->attributes['type'], 'label' => addslashes(trim($field->label)), 'validate' => $validateValue, 'required' => $requiredValue);
                 }
             }
         }
         //$oJSON = new Services_JSON();
         $jsonRequired = G::json_encode($this->requiredFields);
         $this->objectRequiredFields = str_replace('"', "%27", str_replace("'", "%39", $jsonRequired));
         //Load the default values
         //$this->setDefaultValues();
         //Save the cache file
         if (!is_dir(dirname($this->parsedFile))) {
             G::mk_dir(dirname($this->parsedFile));
         }
         $f = fopen($this->parsedFile, 'w+');
         //ERROR CODE [2] : Failed to open cache file
         if ($f === false) {
             return 2;
         }
         fwrite($f, "<?php\n");
         /*  fwrite ($f, '$this = unserialize( \'' .
             addcslashes( serialize ( $this ), '\\\'' ) . '\' );' . "\n" );*/
         foreach ($this as $key => $value) {
             //cho $key .'<br/>';
             switch ($key) {
                 case 'home':
                 case 'fileName':
                 case 'parsedFile':
                 case 'scriptFile':
                 case 'scriptURL':
                     break;
                 default:
                     switch (true) {
                         case is_string($this->{$key}):
                             fwrite($f, '$this->' . $key . '=\'' . addcslashes($this->{$key}, '\\\'') . '\'' . ";\n");
                             break;
                         case is_bool($this->{$key}):
                             fwrite($f, '$this->' . $key . '=' . ($this->{$key} ? 'true;' : 'false') . ";\n");
                             break;
                         case is_null($this->{$key}):
                             fwrite($f, '$this->' . $key . '=null' . ";\n");
                             break;
                         case is_float($this->{$key}):
                         case is_int($this->{$key}):
                             fwrite($f, '$this->' . $key . '=' . $this->{$key} . ";\n");
                             break;
                         default:
                             fwrite($f, '$this->' . $key . ' = unserialize( \'' . addcslashes(serialize($this->{$key}), '\\\'') . '\' );' . "\n");
                     }
             }
         }
         fwrite($f, "?>");
         fclose($f);
         $newVersion = true;
     }
     //if $forceParse
     //Loads the parsedFile.
     require $this->parsedFile;
     $this->fileName = $filename;
     $this->parsedFile = $parsedFile;
     //RECREATE LA JS file
     //Note: Template defined with publisher doesn't affect the .js file
     //created at this point.
     if ($newVersion) {
         $template = PATH_CORE . 'templates/' . $this->type . '.html';
         //If the type is not the correct template name, use xmlform.html
         //if (!file_exists($template)) $template = PATH_CORE . 'templates/xmlform.html';
         if ($template !== '' && file_exists($template)) {
             if (!is_dir(dirname($this->scriptFile))) {
                 G::mk_dir(dirname($this->scriptFile));
             }
             $f = fopen($this->scriptFile, 'w');
             $o = new xmlformTemplate($this, $template);
             $scriptContent = $o->printJSFile($this);
             unset($o);
             fwrite($f, $scriptContent);
             fclose($f);
         }
     }
     return 0;
 }
예제 #29
0
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
 * Coral Gables, FL, 33134, USA, or email info@colosa.com.
 */
// lets display the items
$pluginFile = $_GET['id'];
$pluginStatus = $_GET['status'];
$items = array();
G::LoadClass('plugin');
//here we are enabling or disabling the plugin and all related options registered.
$oPluginRegistry =& PMPluginRegistry::getSingleton();
if ($handle = opendir(PATH_PLUGINS)) {
    while (false !== ($file = readdir($handle))) {
        if (strpos($file, '.php', 1) && $file == $pluginFile) {
            if ($pluginStatus == '1') {
                //print "change to disable";
                $details = $oPluginRegistry->getPluginDetails($pluginFile);
                $oPluginRegistry->disablePlugin($details->sNamespace);
                $size = file_put_contents(PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance());
                print "size saved : {$size}  <br>";
            } else {
                //print "change to ENABLED";
                require_once PATH_PLUGINS . $pluginFile;
                $details = $oPluginRegistry->getPluginDetails($pluginFile);
                $oPluginRegistry->enablePlugin($details->sNamespace);
                $oPluginRegistry->setupPlugins();
예제 #30
0
 private static function setIncludePath()
 {
     $oPluginRegistry =& PMPluginRegistry::getSingleton();
     $pluginsDashlets = $oPluginRegistry->getDashlets();
     foreach ($pluginsDashlets as $pluginDashlet) {
         set_include_path(get_include_path() . PATH_SEPARATOR . PATH_PLUGINS . $pluginDashlet . PATH_SEP);
     }
 }