From ab7406de8885d085e45609cc806e920d0d05aa83 Mon Sep 17 00:00:00 2001 From: Erik Amaru Ortiz Date: Fri, 11 Nov 2011 17:28:22 -0400 Subject: [PATCH] BUG 0000 Rverting class.wsBase.php file class --- workflow/engine/classes/class.wsBase.php | 3939 +++++++++++----------- 1 file changed, 2033 insertions(+), 1906 deletions(-) diff --git a/workflow/engine/classes/class.wsBase.php b/workflow/engine/classes/class.wsBase.php index 32f4de1dc..69bb9bffb 100755 --- a/workflow/engine/classes/class.wsBase.php +++ b/workflow/engine/classes/class.wsBase.php @@ -1,9 +1,10 @@ + * Last Modify comment(26.06.2008): the session expired verification was removed from here to soap class + * @package workflow.engine.classes */ -function getCurrentDate() { - return G::CurDate('Y-m-d'); -} -/** - * @method - * - * Returns the current time in the format "hh:mm:ss" with leading zeros when the hours, - * minutes or seconds are less than 10. - * - * @name getCurrentTime - * @label Get Current Time - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#getCurrentTime.28.29 - * - * @return time | $time | Current Time (H:i:s)| The function returns the current time as a string. - * - */ -function getCurrentTime() { - return G::CurDate('H:i:s'); -} -/** - * @method - * - * Retrieves information about a user with a given ID. - * - * @name userInfo - * @label User Info - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#userInfo.28.29 - * - * @param string(32) | $user_id | User ID | The user unique ID - * @return array | $userInfo | User Info | An associative array with Information - * - */ -function userInfo($user_uid) { - try { - require_once 'classes/model/Users.php'; - $oUser = new Users(); - return $oUser->getAllInformation($user_uid); - } - catch (Exception $oException) { - throw $oException; - } -} -/** - * @method - * - * Returns a string converted into all UPPERCASE letters. - * - * @name upperCase - * @label Upper Case - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#upperCase.28.29 - * - * @param string(32) | $sText | Text To Convert | A string to convert to UPPERCASE letters. - * @return string | $TextC | Text Converted | Returns a string with the text converted into upper case letters. - * - */ -function upperCase($sText) { - return G::toUpper($sText); -} -/** - * @method - * - * Returns a string with all the letters converted into lower case letters. - * - * @name lowerCase - * @label Lower Case - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#lowerCase.28.29 - * - * @param string(32) | $sText | Text To Convert | A string to convert to lower case letters. - * @return string | $TextC | Text Converted | Returns a string with the text converted into lower case letters. - * - */ -function lowerCase($sText) { - return G::toLower($sText); -} -/** - * @method - * - * Converts the first letter in each word into an uppercase letter. - * Subsequent letters in each word are changed into lowercase letters. - * - * @name capitalize - * @label Capitalize - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#capitalize.28.29 - * - * @param string(32) | $sText | Text To Convert | The string to capitalize. - * @return string | $TextC | Text Converted | It returns the introduced text with the first letter capitalized in each word and the subsequent letters into lowercase letters - * - */ -function capitalize($sText) { - return G::capitalizeWords($sText); -} -/** - * @method - * - * Returns a string formatted according to the given date format and given language - * - * @name formatDate - * @label Format Date - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#formatDate.28.29 - * - * @param string(32) | $date | Date | The input date to be reformatted. The input date must be a string in the format 'yyyy-mm-dd'. - * @param string(32) | $format="" | format | The format of the date which will be returned. It can have the following definitions: - * @param string(32) | $lang="en"| Language | The language in which to reformat the date. It can be 'en' (English), 'es' (Spanish) or 'fa' (Persian). - * @return string | $formatDate | Date whit format | It returns the passed date according to the given date format. - * - */ -function formatDate($date, $format='', $lang='en') { - if( !isset($date) or $date == '') { - throw new Exception('function:formatDate::Bad param'); - } - try { - return G::getformatedDate($date, $format, $lang); - } catch (Exception $oException) { - throw $oException; - } -} -/** - * @method - * - * Returns a specified date written out in a given language, with full month names. - * - * @name literalDate - * @label Literal Date - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#literalDate.28.29 - * - * @param string(32) | $date | date | The input date in standard format (yyyy-mm-dd) that is a string. - * @param string(32) | $lang="en" | Language | The language to display, which can be 'en' (English) or 'es' (Spanish). If not included, then it will be English by default. - * @return string | $literaDate | Literal date | It returns the literal date as a string value. - * - */ -function literalDate($date, $lang = 'en') { - if( !isset($date) or $date == '' ) { - throw new Exception('function:formatDate::Bad param'); - } - try { - switch($lang) { - case 'en': $ret = G::getformatedDate($date, 'M d,yyyy', $lang); - break; - case 'es': $ret = G::getformatedDate($date, 'd de M de yyyy', $lang); - break; - } - return $ret; - } catch (Exception $oException) { - throw $oException; - } -} -/** - * @method - * - * Pauses a specified case. - * - * @name pauseCase - * @label Pause Case - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#pauseCase.28.29 - * - * @param string(32) | $sApplicationUID= "" | ID of the case | The unique ID of the case. The UID of the current case can be found in the system variable @@APPLICATION. - * @param string(32) | $iDelegation = 0| Delegation index of the case | The delegation index of the current task in the case. - * @param string(32) | $sUserUID = ""| ID user | The unique ID of the user who will pause the case. - * @param string(32) | $sUnpauseDate = null | Date | Optional parameter. The date in the format 'yyyy-mm-dd' indicating when to unpause the case. - * @return None | $none | None | None - * - */ -function pauseCase($sApplicationUID = '', $iDelegation = 0, $sUserUID = '', $sUnpauseDate = null) {//var_dump($sApplicationUID, $iDelegation, $sUserUID, $sUnpauseDate);die(':|'); - try { - if ($sApplicationUID == '') { - throw new Exception('The application UID cannot be empty!'); - } - if ($iDelegation == 0) { - throw new Exception('The delegation index cannot be 0!'); - } - if ($sUserUID == '') { - throw new Exception('The user UID cannot be empty!'); - } - G::LoadClass('case'); - $oCase = new Cases(); - $oCase->pauseCase($sApplicationUID, $iDelegation, $sUserUID, $sUnpauseDate); - } - catch (Exception $oException) { - throw $oException; - } -} -/** - * @method - * - * Executes a SQL statement in a database connection or in one of ProcessMaker's - * internal databases. - * - * @name executeQuery - * @label execute Query - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#executeQuery.28.29 - * - * @param string(32) | $SqlStatement | Sql query | The SQL statement to be executed. Do NOT include the database name in the SQL statement. - * @param string(32) | $DBConnectionUID="workflow"| UID database | The UID of the database connection where the SQL statement will be executed. - * @return array or string | $Resultquery | Result | Result of the query | If executing a SELECT statement, it returns an array of associative arrays - * - */ -function executeQuery($SqlStatement, $DBConnectionUID = 'workflow') { - try { - $statement = trim($SqlStatement); - $statement = str_replace('(', '', $statement); - $con = Propel::getConnection($DBConnectionUID); - $con->begin(); - $result = false; - - switch(true) { - case preg_match("/^SELECT\s/i", $statement): - case preg_match("/^EXECUTE\s/i", $statement): - $rs = $con->executeQuery($SqlStatement); - $con->commit(); - - $result = Array(); - $i=1; - while ($rs->next()) { - $result[$i++] = $rs->getRow(); - } - break; - case preg_match("/^INSERT\s/i", $statement): - $rs = $con->executeUpdate($SqlStatement); - $con->commit(); - //$result = $lastId->getId(); - $result = 1; - break; - case preg_match("/^UPDATE\s/i", $statement): - $rs = $con->executeUpdate($SqlStatement); - $con->commit(); - $result = $con->getUpdateCount(); - break; - case preg_match("/^DELETE\s/i", $statement): - $rs = $con->executeUpdate($SqlStatement); - $con->commit(); - $result = $con->getUpdateCount(); - break; - } - - return $result; - } catch (SQLException $sqle) { - $con->rollback(); - throw $sqle; - } -} -/** - * @method - * - * Sorts a grid according to a specified field in ascending or descending order. - * - * @name orderGrid - * @label order Grid - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#orderGrid.28.29 - * - * @param array | $dataM | User ID | A grid, which is a numbered array containing associative arrays with field names and their values, it has to be set like this "@=". - * @param string(32) | $field | Name of field | The name of the field by which the grid will be sorted. - * @param string(32) | $ord = "ASC"| Optional parameter | Optional parameter. The order which can either be 'ASC' (ascending) or 'DESC' (descending). If not included, 'ASC' will be used by default. - * @return array | $dataM | Grid Sorted | Grid sorted - * - */ -function orderGrid($dataM, $field, $ord = 'ASC') { - if(!is_array($dataM) or !isset($field) or $field=='') { - throw new Exception('function:orderGrid Error!, bad parameters found!'); - } - for($i=1; $i <= count($dataM)-1; $i++) { - for($j=$i+1; $j <= count($dataM); $j++) { - if(strtoupper($ord) == 'ASC') { - if(strtolower($dataM[$j][$field]) < strtolower($dataM[$i][$field])) { - $swap = $dataM[$i]; - $dataM[$i] = $dataM[$j]; - $dataM[$j] = $swap; - } - } else { - if($dataM[$j][$field] > $dataM[$i][$field]) { - $swap = $dataM[$i]; - $dataM[$i] = $dataM[$j]; - $dataM[$j] = $swap; - } - } - } - } - return $dataM; -} -/** - * @method - * - * Executes operations among the grid fields, such as addition, substraction, etc - * - * @name evaluateFunction - * @label evaluate Function - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#evaluateFunction.28.29 - * - * @param array | $aGrid | Grid | The input grid. - * @param string(32) | $sExpresion | Expression for the operation | The input expression for the operation among grid fields. The expression must always be within double quotes, otherwise a fatal error will occur. - * @return array | $aGrid | Grid | Grid with executed operation - * - */ -function evaluateFunction($aGrid, $sExpresion) { - $sExpresion = str_replace('Array','$this->aFields', $sExpresion); - $sExpresion .= ';'; - G::LoadClass('pmScript'); - $pmScript = new PMScript(); - $pmScript->setScript($sExpresion); - - for($i=1; $i<=count($aGrid); $i++) { - $aFields = $aGrid[$i]; - - $pmScript->setFields($aFields); - - $pmScript->execute(); - - $aGrid[$i] = $pmScript->aFields; - } - return $aGrid; -} - -/** Web Services Functions **/ -/** - * @method - * - * Logs in a user to initiate a web services session in a ProcessMaker server. - * - * @name WSLogin - * @label WS Login - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSLogin.28.29 - * - * @param string(32) | $user | Username of the user | The username of the user who will login to ProcessMaker. All subsequent actions will be limited to the permissions of that user. - * @param string(32) | $pass | Password encrypted | The user's password encrypted as an MD5 hash with 'md5:' prepended. - * @param string(32) | $endpoint="" | URI of the WSDL | The URI (address) of the WSDL definition of the ProcessMaker web services. - * @return string | $unique ID | Unique Id |The unique ID for the initiated session. - * - */ -function WSLogin($user, $pass, $endpoint='') { - $client = wSOpen(true); - $params = array('userid'=>$user, 'password'=>$pass); - $result = $client->__SoapCall('login', array($params)); - - if($result->status_code == 0) { - if($endpoint != '') { - if(isset($_SESSION['WS_SESSION_ID'])) - $_SESSION['WS_END_POINT'] = $endpoint; - } - if(isset($_SESSION['WS_SESSION_ID'])) - return $_SESSION['WS_SESSION_ID'] = $result->message; - else - return $result->message; - } else { - if(isset($_SESSION['WS_SESSION_ID'])) - unset($_SESSION['WS_SESSION_ID']); - $wp = (trim($pass) != "")?'YES':'NO'; - throw new Exception("WSAccess denied! for user $user with password $wp"); - } -} -/** - * @method - * - * Opens a connection for web services and returns a SOAP client object which is - * used by all subsequent other WS function calls - * - * @name WSOpen - * @label WS Open - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSOpen.28.29 - * - * @param boolean | $force=false | Optional Parameter | Optional parameter. Set to true to force a new connection to be created even if a valid connection already exists. - * @return Object Client | $client | SoapClient object | A SoapClient object. If unable to establish a connection, returns NULL. - * - */ -function WSOpen($force=false) { - if(isset($_SESSION['WS_SESSION_ID']) || $force) { - if( !isset ($_SESSION['WS_END_POINT']) ) { - $defaultEndpoint = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/sys'.SYS_SYS.'/en/green/services/wsdl'; - } - $endpoint = isset( $_SESSION['WS_END_POINT'] ) ? $_SESSION['WS_END_POINT'] : $defaultEndpoint; - $client = new SoapClient( $endpoint ); - return $client; - } else { - throw new Exception('WS session is not open'); - } -} -/** - * @method - * - * Returns all the tasks which has open delegations for the indicated case. - * - * @name WSTaskCase - * @label WS Task Case - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSTaskCase.28.29 - * - * @param string(32) | $caseId | Case ID | The unique ID for the case. Case UIDs can be found with WSCaseList() and are stored in the field wf_.APPLICATION.APP_UID. - * @return array | $rows | Array of tasks open | An array of tasks in the indicated case which have open delegations. - * - */ -function WSTaskCase($caseId) { - $client = WSOpen(); - - $sessionId = $_SESSION['WS_SESSION_ID']; - - $params = array('sessionId'=>$sessionId, 'caseId'=>$caseId); - $result = $client->__soapCall('taskCase', array($params)); - - $i = 1; - if(isset ($result->taskCases)) { - foreach ( $result->taskCases as $key=> $item) { - if ( isset ($item->item) ) { - foreach ( $item->item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } else { - foreach ( $item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } - - $rows[$i++] = array ( 'guid' => $guid, 'name' => $name ); - } - } - return $rows; -} -/** - * @method - * - * Returns a list of tasks in which the logged-in user can initiate cases or is - * assigned to these cases. - * - * @name WSTaskList - * @label WS Task List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSTaskList.28.29 - * - * @return array | $rows |List of tasks | This function returns a list of tasks - * - */ -function WSTaskList() { - $client = WSOpen(); - - $sessionId = $_SESSION['WS_SESSION_ID']; - $params = array('sessionId'=>$sessionId ); - $result = $client->__SoapCall('TaskList', array($params)); - - $i = 1; - if(isset ($result->tasks)) { - foreach ( $result->tasks as $key=> $item) { - if ( isset ($item->item) ) { - foreach ( $item->item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } else { - foreach ( $item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } - - $rows[$i++] = array ( 'guid' => $guid, 'name' => $name ); - } - } - return $rows; -} -/** - * @method - * - * Returns a list of users whose status is "ACTIVE" in the current workspace. - * - * @name WSUserList - * @label WS User List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSUserList.28.29 - * - * @return array | $rows | List | List of Active users in the workspace - * - */ -function WSUserList() { - $client = WSOpen(); - - $sessionId = $_SESSION['WS_SESSION_ID']; - $params = array('sessionId'=>$sessionId ); - $result = $client->__SoapCall('UserList', array($params)); - - $i = 1; - if(isset ($result->users)) { - foreach ( $result->users as $key=> $item) { - if ( isset ($item->item) ) { - foreach ( $item->item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } else { - foreach ( $item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } - - $rows[$i++] = array ( 'guid' => $guid, 'name' => $name ); - } - } - return $rows; -} -/** - * @method - * - * Returns a list of active groups in a workspace. - * - * @name WSGroupList - * @label WS Group List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSGroupList.28.29 - * - * @return array | $rows | List | List of active groups in the workspace - * - */ -function WSGroupList() { - $client = WSOpen(); - - $sessionId = $_SESSION['WS_SESSION_ID']; - $params = array('sessionId'=>$sessionId ); - $result = $client->__SoapCall('GroupList', array($params)); - - $i = 1; - if(isset ($result->groups)) { - foreach ( $result->groups as $key=> $item) { - if ( isset ($item->item) ) { - foreach ( $item->item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } else { - foreach ( $item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } - - $rows[$i++] = array ( 'guid' => $guid, 'name' => $name ); - } - } - return $rows; -} - -/** - * @method - * - * Returns a list of roles in the current workspace. - * - * @name WSRoleList - * @label WS Role List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSRoleList.28.29 - * - * @return array | $rows | List | List of roles in the workspace - * - */ -function WSRoleList() { - $client = WSOpen(); - - $sessionId = $_SESSION['WS_SESSION_ID']; - $params = array('sessionId'=>$sessionId ); - $result = $client->__SoapCall('RoleList', array($params)); - $i = 1; - if(isset ($result->roles)) { - foreach ( $result->roles as $key=> $item) { - if ( isset ($item->item) ) { - foreach ( $item->item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } else { - foreach ( $item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } - - $rows[$i++] = array ( 'guid' => $guid, 'name' => $name ); - } - } - return $rows; -} -/** - * @method - * - * Returns a list of the cases which the current logged-in user has privileges to - * open. - * - * @name WSCaseList - * @label WS Case List - * @Link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSCaseList.28.29 - * - * @return array | $rows | List of the cases |It returns a list of cases - * - */ -function WSCaseList() { - $client = WSOpen(); - - $sessionId = $_SESSION['WS_SESSION_ID']; - $params = array('sessionId'=>$sessionId ); - $result = $client->__SoapCall('CaseList', array($params)); - - $i = 1; - if(isset ($result->cases)) { - foreach ( $result->cases as $key=> $item) { - if ( isset ($item->item) ) { - foreach ( $item->item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } else { - foreach ( $item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } - - $rows[$i++] = array ( 'guid' => $guid, 'name' => $name ); - } - } - - return $rows; -} -/** - * @method - * - * Returns a list of processes in the current workspace. - * - * @name WSProcessList - * @label WS Process List - * @Link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSProcessList.28.29 - * - * @return array | $rows | List of processes | A list of processes - * - */ -function WSProcessList() { - $client = WSOpen(); - - $sessionId = $_SESSION['WS_SESSION_ID']; - $params = array('sessionId'=>$sessionId ); - $result = $client->__SoapCall('ProcessList', array($params)); - - $i = 1; - if(isset ($result->processes)) { - foreach ( $result->processes as $key=> $item) { - if ( isset ($item->item) ) { - foreach ( $item->item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } else { - foreach ( $item as $index=> $val ) { - if ( $val->key == 'guid' ) $guid = $val->value; - if ( $val->key == 'name' ) $name = $val->value; - } - } - - $rows[$i++] = array ( 'guid' => $guid, 'name' => $name ); - } - } - return $rows; -} -/** - * @method - * - * Returns a list of processes in the current workspace. - * - * @name getEmailConfiguration - * @label WS Get Email Configuration - * - * - * @return array | $aFields | Array |Get current email configuration - * - */ -//private function to get current email configuration -function getEmailConfiguration () { - require_once 'classes/model/Configuration.php'; - $oConfiguration = new Configuration(); - $sDelimiter = DBAdapter::getStringDelimiter(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(ConfigurationPeer::CFG_UID, 'Emails'); - $oCriteria->add(ConfigurationPeer::OBJ_UID, ''); - $oCriteria->add(ConfigurationPeer::PRO_UID, ''); - $oCriteria->add(ConfigurationPeer::USR_UID, ''); - $oCriteria->add(ConfigurationPeer::APP_UID, ''); - - if (ConfigurationPeer::doCount($oCriteria) == 0) { - $oConfiguration->create(array('CFG_UID' => 'Emails', 'OBJ_UID' => '', 'CFG_VALUE' => '', 'PRO_UID' => '', 'USR_UID' => '', 'APP_UID' => '')); - $aFields = array(); - } - else { - $aFields = $oConfiguration->load('Emails', '', '', '', ''); - if ($aFields['CFG_VALUE'] != '') { - $aFields = unserialize($aFields['CFG_VALUE']); - } - else { - $aFields = array(); - } - } - - return $aFields; -} - -/** - * @method - * - * Sends an email using a template file. - * - * @name PMFSendMessage - * @label PMF Send Message - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFSendMessage.28.29 - * - * @param string(32) | $caseId | UID for case | The UID (unique identification) for a case, which is a string of 32 hexadecimal characters to identify the case. - * @param string(32) | $sFrom | Email addres | The email address of the person who sends out the email. - * @param string(32) | $sTo | Email receptor | The email address(es) to whom the email is sent. If multiple recipients, separate each email address with a semicolon. - * @param string(32) | $sCc | Email addres for copies | The email address(es) of people who will receive carbon copies of the email. - * @param string(32) | $sBcc | Email addres for copies hidden | The email address(es) of people who will receive blind carbon copies of the email. - * @param string(32) | $sSubject | Subject of the email | The subject (title) of the email. - * @param string(32) | $sTemplate | Name of the template | The name of the template file in plain text or HTML format which will produce the body of the email. - * @param array | $aFields | An optional associative array | Optional parameter. An associative array where the keys are the variable names and the values are the variables' values. - * @param array | $aAttachment | Attachment | An Optional arrray. An array of files (full paths) to be attached to the email. - * @return int | $result | result | Result of sending email - * - */ -//@param array | $aFields=array() | An associative array optional | Optional parameter. An associative array where the keys are the variable name and the values are the variable's value. -function PMFSendMessage($caseId, $sFrom, $sTo, $sCc, $sBcc, $sSubject, $sTemplate, $aFields = array(), $aAttachment = array()) { - - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->sendMessage($caseId, $sFrom, $sTo, $sCc, $sBcc, $sSubject, $sTemplate, $aFields, $aAttachment); - - if ( $result->status_code == 0) { - return 1; - } else { - return 0; - } -} -/** - * @method - * - * Sends two variables to the specified case. - * It will create new case variables if they don't already exist - * - * @name WSSendVariables - * @label WS Send Variables - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSSendVariables.28.29 - * - * @param string(32) | $caseId | UID for case | The unique ID of the case which will receive the variables. - * @param string(32) | $name1 | Name of the first variable | The name of the first variable to be sent to the created case. - * @param string(32) | $value1 | Value of the first variable | The value of the first variable to be sent to the created case. - * @param string(32) | $name2 | Name of the second variable | The name of the second variable to be sent to the created case. - * @param string(32) | $value2 | Value of the second variable | The value of the second variable to be sent to the created case. - * @return array | $fields | WS Response Associative Array: | The function returns a WS Response associative array. - * - */ -function WSSendVariables($caseId, $name1, $value1, $name2, $value2) { - $client = WSOpen(); - $sessionId = $_SESSION['WS_SESSION_ID']; - - $variables[1]->name = $name1; - $variables[1]->value = $value1; - $variables[2]->name = $name2; - $variables[2]->value = $value2; - $params = array('sessionId'=>$sessionId, 'caseId'=>$caseId, 'variables'=>$variables); - $result = $client->__SoapCall('SendVariables', array($params)); - - $fields['status_code'] = $result->status_code; - $fields['message'] = $result->message; - $fields['time_stamp'] = $result->timestamp; - return $fields; -} -/** - * @method - * - * Routes (derivates) a case, moving the case to the next task in the process - * according its routing rules. - * - * @name WSDerivateCase - * @label WS Derivate Case - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSDerivateCase.28.29 - * - * @param string(32) | $CaseId | Case ID |The unique ID for a case, which can be found with WSCaseList() or by examining the field wf_.APPLICATION.APP_UID. - * @param string(32) | $delIndex | Delegation index for the task | The delegation index for the task, which can be found by examining the field wf_.APP_DELEGATION.DEL_INDEX. - * @return array | $fields | WS Response Associative Array | A WS Response associative array. - * - */ -function WSDerivateCase($caseId, $delIndex) { - $client = WSOpen(); - $sessionId = $_SESSION['WS_SESSION_ID']; - - $params = array('sessionId'=>$sessionId, 'caseId'=>$caseId, 'delIndex'=>$delIndex ); - $result = $client->__SoapCall('DerivateCase', array($params)); - - $fields['status_code'] = $result->status_code; - $fields['message'] = $result->message; - $fields['time_stamp'] = $result->timestamp; - return $fields; -} -/** - * @method - * - * Creates a case with any user with two initial case variables. - * - * @name WSNewCaseImpersonate - * @label WS New Case Impersonate - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSNewCaseImpersonate.28.29 - * - * @param string(32) | $processId | Process ID | The unique ID for the process. - * @param string(32) | $userId | User ID | The unique ID for the user. - * @param string(32) | $name1 | Name of the first variable | The name of the first variable to be sent to the created case. - * @param string(32) | $value1 | Value of the first variable | The value of the first variable to be sent to the created case. - * @param string(32) | $name2 | Name of the second variable | The name of the second variable to be sent to the created case. - * @param string(32) | $value2 | Value of the second variable | The value of the second variable to be sent to the created case. - * @return array | $fields | WS Response Associative Array | A WS Response associative array. - * - */ -function WSNewCaseImpersonate($processId, $userId, $name1, $value1, $name2, $value2) { - $client = WSOpen(); - $sessionId = $_SESSION['WS_SESSION_ID']; - - $variables[1]->name = $name1; - $variables[1]->value = $value1; - $variables[2]->name = $name2; - $variables[2]->value = $value2; - - $params = array('sessionId'=>$sessionId, 'processId'=>$processId, 'userId'=>$userId, 'variables'=>$variables ); - $result = $client->__SoapCall('NewCaseImpersonate', array($params)); - - $fields['status_code'] = $result->status_code; - $fields['message'] = $result->message; - $fields['time_stamp'] = $result->timestamp; - return $fields; -} -/** - * @method - * - * Creates a new case starting with a specified task and using two initial case - * variables. - * - * @name WSNewCase - * @label WS New Case - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSNewCase.28.29 - * - * @param string(32) | $processId | Process ID | The unique ID for the process. To use the current process, use the system variable @@PROCESS. - * @param string(32) | $userId | User ID | The unique ID for the user. To use the currently logged-in user, use the system variable @@USER_LOGGED. - * @param string(32) | $name1 | Name of the first variable | The name of the first variable to be sent to the created case. - * @param string(32) | $value1 | Value of the first variable | The value of the first variable to be sent to the created case. - * @param string(32) | $name2 | Name of the second variable | The name of the second variable to be sent to the created case. - * @param string(32) | $value2 | Value of the second variable | The value of the second variable to be sent to the created case. - * @return array | $fields | WS array | A WS Response associative array. - * - */ -function WSNewCase($processId, $taskId, $name1, $value1, $name2, $value2) { - $client = WSOpen(); - $sessionId = $_SESSION['WS_SESSION_ID']; - - $variables[1]->name = $name1; - $variables[1]->value = $value1; - $variables[2]->name = $name2; - $variables[2]->value = $value2; - - $params = array('sessionId'=>$sessionId, 'processId'=>$processId, 'taskId'=>$taskId, 'variables'=>$variables ); - $result = $client->__SoapCall('NewCase', array($params)); - - $fields['status_code'] = $result->status_code; - $fields['message'] = $result->message; - $fields['time_stamp'] = $result->timestamp; - return $fields; -} -/** - * @method - * - * Assigns a user to a group (as long as the logged in user has the PM_USERS - * permission in their role). - * - * @name WSAssignUserToGroup - * @label WS Assign User To Group - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSAssignUserToGroup.28.29 - * - * @param string(32) | $userId | User ID | The unique ID for a user. - * @param string(32) | $groupId | Group ID | The unique ID for a group. - * @return array | $fields | WS array |A WS Response associative array. - * - */ -function WSAssignUserToGroup($userId, $groupId) { - $client = WSOpen(); - $sessionId = $_SESSION['WS_SESSION_ID']; - - $params = array('sessionId'=>$sessionId, 'userId'=>$userId, 'groupId'=>$groupId); - $result = $client->__SoapCall('AssignUserToGroup', array($params)); - - $fields['status_code'] = $result->status_code; - $fields['message'] = $result->message; - $fields['time_stamp'] = $result->timestamp; - return $fields; -} -/** - * @method - * - * Creates a new user in ProcessMaker. - * - * @name WSCreateUser - * @label WS Create User - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSCreateUser.28.29 - * - * @param string(32) | $userId | User ID | The username of the new user, which can be up to 32 characters long. - * @param string(32) | $password | Password of the new user | El password of the new user, which can be up to 32 characters long. - * @param string(32) | $firstname | Firstname of the new user | The first name(s) of the new user, which can be up to 50 characters long. - * @param string(32) | $lastname | Lastname of the new user | The last name(s) of the new user, which can be up to 50 characters long. - * @param string(32) | $email | Email the new user | The e-mail of the new user, which can be up to 100 characters long. - * @param string(32) | $role | Rol of the new user | The role of the new user, such as 'PROCESSMAKER_ADMIN' and 'PROCESSMAKER_OPERATOR'. - * @return array | $fields | WS array | A WS Response associative array. - * - */ -function WSCreateUser($userId, $password, $firstname, $lastname, $email, $role) { - $client = WSOpen(); - $sessionId = $_SESSION['WS_SESSION_ID']; - $params = array('sessionId'=>$sessionId, 'userId'=>$userId, 'firstname'=>$firstname, 'lastname'=>$lastname, 'email'=>$email, 'role'=>$role, 'password'=>$password); - $result = $client->__SoapCall('CreateUser', array($params)); - - $fields['status_code'] = $result->status_code; - $fields['message'] = $result->message; - $fields['time_stamp'] = $result->timestamp; - return $fields; -} -/** - * @method - * - * Returns the unique ID for the current active session. - * - * @name WSGetSession - * @label WS Get Session - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#WSGetSession.28.29 - * - * @return string | $userId | Sesion ID | The unique ID for the current active session. - * - */ -function WSGetSession() { - if(isset($_SESSION['WS_SESSION_ID'])) { - return $_SESSION['WS_SESSION_ID']; - } else { - throw new Exception("SW session is not open!"); - } -} - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Local Services Functions **/ - -/** - * @method - * - * Returns all the tasks for the specified case which have open delegations. - * - * @name PMFTaskCase - * @label PMF Task Case - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFTaskCase.28.29 - * - * @param string(32) | $caseId | Case ID | The unique ID for a case. - * @return array | $rows | List of tasks | A list of tasks - * - */ -function PMFTaskCase($caseId) #its test was successfull +class wsBase { - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->taskCase($caseId); - $rows = Array(); - $i = 1; - if(isset ($result)) { - foreach ( $result as $item) { - $rows[$i++] = $item; + + public $stored_system_variables; //boolean + public $wsSessionId; // web service session id, if the wsbase function is used from a WS request + + function __construct($params=NULL) { + $this->stored_system_variables = FALSE; + + if( $params != NULL ){ + $this->stored_system_variables = isset($params->stored_system_variables)? $params->stored_system_variables: FALSE; + $this->wsSessionId = isset($params->wsSessionId)? $params->wsSessionId: ''; } } - return $rows; -} -/** - * @method - * - * Returns a list of tasks which the specified user has initiated. - * - * @name PMFTaskList - * @label PMF Task List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFTaskList.28.29 - * - * @param string(32) | $userid | User ID | The unique ID of a user. - * @return array | $rows | List of tasks | An array of tasks - * - */ -function PMFTaskList($userId) #its test was successfull -{ - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->taskList($userId); - $rows = Array(); - $i = 1; - if(isset ($result)) { - foreach ( $result as $item) { - $rows[$i++] = $item; - } - } - return $rows; -} -/** - * @method - * - * Returns a list of users whose status is set to "ACTIVE" for the current workspace. - * - * @name PMFUserList - * @label PMF User List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFUserList.28.29 - * - * @return array | $rows | List of users | An array of users - * - */ -function PMFUserList() #its test was successfull -{ - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->userList(); - $rows = Array(); - $i = 1; - if(isset ($result)) { - foreach ( $result as $item) { - $rows[$i++] = $item; - } - } - return $rows; -} -/** - * @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) { - - - if(!$sApplication){ - $sApplication = $_SESSION['APPLICATION']; - } - if(!$index){ - $index = $_SESSION['INDEX']; - } - if(!$sUserLogged){ - $sUserLogged = $_SESSION['USER_LOGGED']; - } - - G::LoadClass('case'); - $oCase = new Cases(); - $oCase->thisIsTheCurrentUser($sApplication, $index, $sUserLogged, '', 'cases_List'); - - -// 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($sUID, $sApplication); - - $oCriteria = new Criteria('workflow'); - $oCriteria->add(AppDocumentPeer::APP_UID, $sApplication); - //$oCriteria->add(AppDocumentPeer::DEL_INDEX, $index); - $oCriteria->add(AppDocumentPeer::DOC_UID, $sUID); - $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 . $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'],); - $oOutputDocument->generate( $outputID, $Fields['APP_DATA'], $pathOutput, $sFilename, $aOD['OUT_DOC_TEMPLATE'], (boolean)$aOD['OUT_DOC_LANDSCAPE'], $aOD['OUT_DOC_GENERATE'] ); - - //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 . $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; - } - - } - -} -/** - * @method - * - * Returns a list of groups from the current workspace - * - * @name PMFGroupList - * @label PMF Group List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFGroupList.28.29 - * - * @return array | $rows | List of groups | An array of groups - * - */ -function PMFGroupList() #its test was successfull -{ - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->groupList(); - $rows = Array(); - $i = 1; - if(isset ($result)) { - foreach ( $result as $item) { - $rows[$i++] = $item; - } - } - return $rows; -} - -/** - * @method - * - * Returns a list of roles whose status is "ACTIVE" for the current workspace. - * - * @name PMFRoleList - * @label PMF Role List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFRoleList.28.29 - * - * @return array | $rows | List of roles | This function returns an array of roles - * - */ -function PMFRoleList() #its test was successfull -{ - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->roleList(); - $rows = Array(); - $i = 1; - if(isset ($result)) { - foreach ( $result as $item) { - $rows[$i++] = $item; - } - } - return $rows; -} -/** - * @method - * - * Returns a list of the pending cases for a specified user - * - * @name PMFCaseList - * @label PMF Case List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFCaseList.28.29 - * - * @param string(32) | $userId | User ID | The unique ID of a user who is assigned to work on the cases. - * @return array | $rows | List of cases | A list of cases - * - */ -function PMFCaseList($userId) #its test was successfull -{ - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->caseList($userId); - $rows = Array(); - $i = 1; - if(isset ($result)) { - foreach ( $result as $item) { - $rows[$i++] = $item; - } - } - return $rows; -} -/** - * @method - * - * Returns a list of processes for the current workspace - * - * @name PMFProcessList - * @label PMF Process List - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFProcessList.28.29 - * - * @return array | $rows | Lis ot Processes | An array of tasks in the indicated case which have open delegations - * - */ -function PMFProcessList() #its test was successfull -{ - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->processList(); - $rows = Array(); - $i = 1; - if(isset ($result)) { - foreach ( $result as $item) { - $rows[$i++] = $item; - } - } - return $rows; -} - -/** - * @method - * - * Sends an array of case variables to a specified case. - * - * @name PMFSendVariables - * @label PMF Send Variables - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFSendVariables.28.29 - * - * @param string(32) | $caseId | Case ID | The unique ID of the case to receive the variable. - * @param array | $variables | Array of variables | An associative array to hold the case variables to send to the case. - * @return int | $result | Result of send variables | Returns 1 if the variables were sent successfully to the case; otherwise, returns 0 if an error occurred. - * - */ -function PMFSendVariables($caseId, $variables) { - G::LoadClass('wsBase'); - $ws = new wsBase (); - - $result = $ws->sendVariables($caseId, $variables); - if($result->status_code == 0) { - return 1; - } else { - return 0; - } -} -/** - * @method - * - * Derivates (routes) a case to the next task in the process. - * - * @name PMFDerivateCase - * @label PMF Derivate Case - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFDerivateCase.28.29 - * - * @param string(32) | $caseId | Case ID | The unique ID for the case to be derivated (routed) - * @param int | $delIndex | delegation index for the case | The delegation index for the case to derivated (routed). - * @param boolean | $bExecuteTriggersBeforeAssignment = false | Trigger | Optional parameter. If set to true, any triggers which are assigned to pending steps in the current task will be executed before the case is assigned to the next user. - * @return int | $result | Result of Derivate case | Returns 1 if new case was derivated (routed) successfully; otherwise, returns 0 if an error occurred. - * - */ -function PMFDerivateCase($caseId, $delIndex, $bExecuteTriggersBeforeAssignment = false, $sUserLogged = null) { - if(!$sUserLogged) { - $sUserLogged = $_SESSION['USER_LOGGED']; - } - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->derivateCase($sUserLogged, $caseId, $delIndex, $bExecuteTriggersBeforeAssignment);//var_dump($result);die; - if (isset($result->status_code)) { - return $result->status_code; - } - else { - return 0; - } - if($result->status_code == 0) { - return 1; - } else { - return 0; - } -} -/** - * @method - * - * Creates a new case with a user who can impersonate a user with the proper - * privileges. - * - * @name PMFNewCaseImpersonate - * @label PMF New Case Impersonate - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFNewCaseImpersonate.28.29 - * - * @param string(32) | $processId | Process ID | The unique ID of the process. - * @param string(32) | $userId | User ID | The unique ID of the user. - * @param array | $variables | Array of variables | An associative array of the variables which will be sent to the case. - * @return int | $result | Result | Returns 1 if new case was created successfully; otherwise, returns 0 if an error occurred. - * - */ -function PMFNewCaseImpersonate($processId, $userId, $variables) { - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->newCaseImpersonate($processId, $userId, $variables); - - if($result->status_code == 0) { - return 1; - } else { - return 0; - } -} -/** - * @method - * - * Creates a new case starting with the specified task - * - * @name PMFNewCase - * @label PMF New Case - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFNewCase.28.29 - * - * @param string(32) | $processId | Process ID | The unique ID of the process. - * @param string(32) | $userId | User ID | The unique ID of the user. - * @param string(32) | $taskId | Task ID | The unique ID of the task. - * @param array | $variables | Array of variables | An associative array of the variables which will be sent to the case. - * @return string | $idNewCase | Case ID | If an error occured, it returns the integer zero. Otherwise, it returns a string with the case UID of the new case. - * - */ -function PMFNewCase($processId, $userId, $taskId, $variables) { - G::LoadClass('wsBase'); - $ws = new wsBase (); - - $result = $ws->newCase($processId, $userId,$taskId, $variables); - - if($result->status_code == 0) { - return $result->caseId; - } else { - return 0; - } -} -/** - * @method - * - * Assigns a user to a group. - * - * @name PMFAssignUserToGroup - * @label PMF Assign User To Group - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFNewCase.28.29 - * - * @param string(32) | $userId | User ID | The unique ID of the user. - * @param string(32) | $groupId | Group ID | The unique ID of the group. - * @return int | $result | Result of the assignment | Returns 1 if the user was successfully assigned to the group; otherwise, returns 0. - * - */ -function PMFAssignUserToGroup($userId, $groupId) { - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->assignUserToGroup($userId, $groupId); - - if($result->status_code == 0) { - return 1; - } else { - return 0; - } -} -/** - * @method - * - * Creates a new user with the given data. - * - * @name PMFCreateUser - * @label PMF Create User - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFCreateUser.28.29 - * - * @param string(32) | $userId | User ID | The username for the new user. - * @param string(32) | $password | Password of the new user | The password of the new user, which can be up to 32 characters long. - * @param string(32) | $firstname | Firstname of the new user | The first name of the user, which can be up to 50 characters long. - * @param string(32) | $lastname | Lastname of the new user | The last name of the user, which can be up to 50 characters long. - * @param string(32) | $email | Email the new user | The email of the new user, which can be up to 100 characters long. - * @param string(32) | $role | Rol of the new user | The role of the new user such as 'PROCESSMAKER_ADMIN' or 'PROCESSMAKER_OPERATOR'. - * @return int | $result | Result of the creation | Returns 1 if the new user was created successfully; otherwise, returns 0 if an error occurred. - * - */ -function PMFCreateUser($userId, $password, $firstname, $lastname, $email, $role) { - G::LoadClass('wsBase'); - $ws = new wsBase (); - $result = $ws->createUser($userId, $firstname, $lastname, $email, $role, $password); - - if($result->status_code == 0) { - return 1; - } else { - return 0; - } -} -/** - * @method - * - * Creates a random string of letters and/or numbers of a specified length,which - * can be used as the PINs (public identification numbers) and codes for cases. - * - * @name generateCode - * @label generate Code - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#generateCode.28.29 - * - * @param int | $iDigits = 4 | Number of characters | The number of characters to be generated. - * @param string(32) | $sType="NUMERIC" | Type of characters | The type of of characters to be generated - * @return string | $generateString | Generated string | The generated string of random characters. - * - */ -function generateCode ( $iDigits = 4, $sType = 'NUMERIC' ) { - return G::generateCode ($iDigits, $sType ); -} - -/** - * @method - * - * Sets the code and PIN for a case. - * - * @name setCaseTrackerCode - * @label set Case Tracker Code - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#setCaseTrackerCode.28.29 - * - * @param string(32) | $sApplicationUID | Case ID | The unique ID for a case (which can be found with WSCaseList() - * @param string(32) | $sCode | New Code for case | The new code for a case, which will be stored in the field wf_.APPLICATION.APP_CODE - * @param string(32) | $sPIN = "" | New Code PIN for case |The new code for a case. - * @return int | $result | Result | If successful, returns zero, otherwise a non-zero error number. - * - */ -function setCaseTrackerCode($sApplicationUID, $sCode, $sPIN = '') { - if ($sCode != '') { - G::LoadClass('case'); - $oCase = new Cases(); - $aFields = $oCase->loadCase($sApplicationUID); - $aFields['APP_PROC_CODE'] = $sCode; - if ($sPIN != '') { - $aFields['APP_DATA']['PIN'] = $sPIN; - $aFields['APP_PIN'] = md5($sPIN); - } - $oCase->updateCase($sApplicationUID, $aFields); - return 1; - } - else { - return 0; - } -} -/** - * @method - * - * Routes (derivates) a case and then displays the case list. - * - * @name jumping - * @label jumping - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#jumping.28.29 - * - * @param string(32) | $caseId | Case ID | The unique ID for the case to be routed (derivated). - * @param int | $delIndex | delegation Index of case | The delegation index of the task to be routed (derivated). Counting starts from 1. - * @return none | $none | None | None - * - */ -function jumping ( $caseId, $delIndex ) { - try { - $x = PMFDerivateCase($caseId, $delIndex); - if($x==0) - G::SendTemporalMessage('ID_NOT_DERIVATED', 'error', 'labels'); - } catch (Exception $oException) { - G::SendTemporalMessage('ID_NOT_DERIVATED', 'error', 'labels'); - } - G::header('Location: cases_List'); -} -/** - * @method - * - * Returns the label of a specified option from a dropdown box, listbox, - * checkgroup or radiogroup. - * - * @name PMFgetLabelOption - * @label PMF get Label Option - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFgetLabelOption.28.29 - * - * @param string(32) | $PROCESS | Process ID | The unique ID of the process which contains the field. - * @param string(32) | $DYNAFORM_UID | Dynaform ID | The unique ID of the DynaForm where the field is located. - * @param string(32) | $FIELD_NAME | Fiel Name | The field name of the dropdown box, listbox, checkgroup or radiogroup from the specified DynaForm. - * @param string(32) | $FIELD_SELECTED_ID | ID selected | The value (i.e., ID) of the option from the fieldName. - * @return string | $label | Label of the specified option | A string holding the label of the specified option or NULL if the specified option does not exist. - * - */ -function PMFgetLabelOption($PROCESS, $DYNAFORM_UID, $FIELD_NAME, $FIELD_SELECTED_ID) { - $G_FORM = new Form ("{$PROCESS}/{$DYNAFORM_UID}", PATH_DYNAFORM, SYS_LANG, false); - if( isset($G_FORM->fields[$FIELD_NAME]->option[$FIELD_SELECTED_ID]) ) { - return $G_FORM->fields[$FIELD_NAME]->option[$FIELD_SELECTED_ID]; - } else { - return null; - } -} -/** - * @method - * - * Redirects a case to any step in the current task. In order for the step to - * be executed, the specified step much exist and if it contains a condition, - * it must evaluate to true. - * - * @name PMFRedirectToStep - * @label PMF Redirect To Step - * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFRedirectToStep.28.29 - * - * @param string(32) | $sApplicationUID | Case ID | The unique ID for a case, - * @param int | $iDelegation | Delegation index | The delegation index of a case. - * @param string(32) | $sStepType | Type of Step | The type of step, which can be "DYNAFORM", "INPUT_DOCUMENT" or "OUTPUT_DOCUMENT". - * @param string(32) | $sStepUid | Step ID | The unique ID for the step. - * @return none | $none | None | None - * - */ -function PMFRedirectToStep($sApplicationUID, $iDelegation, $sStepType, $sStepUid) { - require_once 'classes/model/AppDelegation.php'; - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(AppDelegationPeer::TAS_UID); - $oCriteria->add(AppDelegationPeer::APP_UID, $sApplicationUID); - $oCriteria->add(AppDelegationPeer::DEL_INDEX, $iDelegation); - $oDataset = AppDelegationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - $aRow = $oDataset->getRow(); - if ($aRow) { - require_once 'classes/model/Step.php'; - $oStep = new Step(); - $oTheStep = $oStep->loadByType($aRow['TAS_UID'], $sStepType, $sStepUid); - $bContinue = true; - if ($oTheStep->getStepCondition() != '') { - G::LoadClass('case'); - $oCase = new Cases(); - $aFields = $oCase->loadCase($sApplicationUID); - G::LoadClass('pmScript'); - $oPMScript = new PMScript(); - $oPMScript->setFields($aFields['APP_DATA']); - $oPMScript->setScript($oTheStep->getStepCondition()); - $bContinue = $oPMScript->evaluate(); - } - if ($bContinue) { - switch ($oTheStep->getStepTypeObj()) { - case 'DYNAFORM': - $sAction = 'EDIT'; - break; - case 'OUTPUT_DOCUMENT': - $sAction = 'GENERATE'; - break; - case 'INPUT_DOCUMENT': - $sAction = 'ATTACH'; - break; - case 'EXTERNAL': - $sAction = 'EDIT'; - break; - case 'MESSAGE': - $sAction = ''; - break; - } - G::header('Location: ' . 'cases_Step?TYPE=' . $sStepType . '&UID=' . $sStepUid . '&POSITION=' . $oTheStep->getStepPosition() . '&ACTION=' . $sAction); - die; - } - } -} - -/** - * @method - * - * Returns a list of the next assigned users to a case. - * - * @name PMFGetNextAssignedUser - * @label PMFGet Next Assigned User - * - * @param string(32) | $application | Case ID | Id of the case - * @param string(32) | $task | Task ID | Id of the task - * @return array | $array | List of users | Return a list of users - * - */ -function PMFGetNextAssignedUser ($application, $task) { - - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Task.php'; - require_once 'classes/model/TaskUser.php'; - require_once 'classes/model/Users.php'; - - $oTask = new Task(); - $TaskFields = $oTask->load ($task); - $typeTask = $TaskFields ['TAS_ASSIGN_TYPE']; - - if($typeTask == 'BALANCED') - { - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); - $oCriteria->add(AppDelegationPeer::APP_UID, $application); - $oDataset = AppDelegationPeer::doSelectRS($oCriteria); - $oDataset->next(); - $aRow = $oDataset->getRow(); - $PRO_UID=$aRow[0]; - - $c = new Criteria('workflow'); - $c->addSelectColumn(TaskPeer::TAS_UID); - $c->add(TaskPeer::PRO_UID, $PRO_UID); - // $c->add(TaskPeer::TAS_LAST_ASSIGNED, 0); - $oDataset = TaskPeer::doSelectRS($c); - $oDataset->next(); - $aRow = $oDataset->getRow(); - $TAS_UID=$aRow[0]; - - - $k=new Criteria('workflow'); - $k->addSelectColumn(TaskUserPeer::USR_UID); - $k->add(TaskUserPeer::TAS_UID,$TAS_UID); - $k->add(TaskUserPeer::TU_TYPE,1); - $ods=TaskUserPeer::doSelectRS($k); - $ods->next(); - $row=$ods->getRow(); - $USR_UID=$row[0]; - - $kk=new Criteria('workflow'); - $kk->addSelectColumn(UsersPeer::USR_UID); - $kk->addSelectColumn(UsersPeer::USR_USERNAME); - $kk->addSelectColumn(UsersPeer::USR_FIRSTNAME); - $kk->addSelectColumn(UsersPeer::USR_LASTNAME); - $kk->addSelectColumn(UsersPeer::USR_EMAIL); - $kk->add(UsersPeer::USR_UID,$USR_UID); - $oDataset=UsersPeer::doSelectRS($kk); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - - $aRow1 = $oDataset->getRow(); - - $array=array( - 'USR_UID' => $aRow1['USR_UID'], - 'USR_USERNAME' => $aRow1['USR_USERNAME'], - 'USR_FIRSTNAME'=> $aRow1['USR_FIRSTNAME'], - 'USR_LASTNAME' => $aRow1['USR_LASTNAME'], - 'USR_EMAIL' => $aRow1['USR_EMAIL'] - ); - return $array; - } else - { - return false; - } -} - - -//new functions by Erik - -function PMFGetUserEmailAddress($id, $APP_UID=null, $prefix='usr') { - - require_once 'classes/model/UsersPeer.php'; - require_once 'classes/model/AppDelegation.php'; - G::LoadClass('case'); - - if( is_string($id) && trim($id) == "" ){ - return false; - } - if( is_array($id) && count($id) == 0 ){ - return false; - } - - - //recipient to store the email addresses - $aRecipient = Array(); - $aItems = Array(); /* - * First at all the $id user input can be by example erik@colosa.com - * 2. this $id param can be a array by example Array('000000000001', '000000000002') in this case $prefix is necessary - * 3. this same param can be a array by example Array('usr|000000000001', 'usr|-1', 'grp|2245141479413131441') + * function to start a web services session in ProcessMaker + * @param string $userid + * @param string $password + * @return $wsResponse will return an object */ + public function login( $userid, $password ) { + global $RBAC; - /* - * The second thing is that the return type will be configurated depend of the input type (using $retType) - */ - if( is_array($id) ){ - $aItems = $id; - $retType = 'array'; - } else { - $retType = 'string'; - if( strpos($id, ",") !== false ){ - $aItems = explode(',', $id); - } else { - array_push($aItems, $id); + try { + $uid = $RBAC->VerifyLogin( $userid , $password); + switch ($uid) { + case -1: //The user doesn't exist + $wsResponse = new wsResponse (3, G::loadTranslation ('ID_USER_NOT_REGISTERED')); + break; + + case -2://The password is incorrect + $wsResponse = new wsResponse (4, G::loadTranslation ('ID_WRONG_PASS')); + break; + + case -3: //The user is inactive + $wsResponse = new wsResponse (5, G::loadTranslation ('ID_USER_INACTIVE')); + + case -4: //The Due date is finished + $wsResponse = new wsResponse (5, G::loadTranslation ('ID_USER_INACTIVE')); + break; + } + if ($uid < 0 ) { + throw ( new Exception ( serialize ( $wsResponse ) )); + } + // check access to PM + $RBAC->loadUserRolePermission( $RBAC->sSystem, $uid ); + $res = $RBAC->userCanAccess("PM_LOGIN"); + + if ($res != 1 ) { + //if ($res == -2) + // $wsResponse = new wsResponse (1, G::loadTranslation ('ID_USER_HAVENT_RIGHTS_SYSTEM')); + //else + $wsResponse = new wsResponse (2, G::loadTranslation ('ID_USER_HAVENT_RIGHTS_SYSTEM')); + throw ( new Exception ( serialize ( $wsResponse ) )); + } + + $sessionId = G::generateUniqueID(); + $wsResponse = new wsResponse ('0', $sessionId ); + + $session = new Session (); + $session->setSesUid ( $sessionId ); + $session->setSesStatus ( 'ACTIVE'); + $session->setUsrUid ( $uid ); + $session->setSesRemoteIp ( $_SERVER['REMOTE_ADDR'] ); + $session->setSesInitDate ( date ('Y-m-d H:i:s') ); + $session->setSesDueDate ( date ('Y-m-d H:i:s', mktime(date('H'),date('i')+15, date('s'), date('m'),date('d'),date('Y') ) ) ); + $session->setSesEndDate ( '' ); + $session->Save(); + + //save the session in DataBase + return $wsResponse; + } + catch ( Exception $e ) { + $wsResponse = unserialize ( $e->getMessage() ); + return $wsResponse; } } - foreach ($aItems as $sItem) { - //cleaning for blank spaces into each array item - $sItem = trim($sItem); - if( strpos($sItem, "|") !== false ){ - //explode the parameter because always will be compose with pipe separator to indicate the type (user or group) and the target mai - list($sType, $sID) = explode('|', $sItem); - $sType = trim($sType); - $sID = trim($sID); - } else { - $sType = $prefix; - $sID = $sItem; - } + /* + * get all groups + * @param none + * @return $result will return an object + */ + public function processList() { + try { + $result = array(); + $oCriteria = new Criteria('workflow'); + //$oCriteria->add(ProcessPeer::PRO_STATUS , 'ACTIVE' ); + $oCriteria->add(ProcessPeer::PRO_STATUS, 'DISABLED', Criteria::NOT_EQUAL); + $oDataset = ProcessPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); - switch($sType) { - case 'ext': - if( G::emailAddress($sID) ) { - array_push($aRecipient, $sID); + while ($aRow = $oDataset->getRow()) { + $oProcess = new Process(); + $arrayProcess = $oProcess->Load( $aRow['PRO_UID'] ); + $result[] = array ( 'guid' => $aRow['PRO_UID'], 'name' => $arrayProcess['PRO_TITLE'] ); + $oDataset->next(); + } + + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + /* + * get all roles, to see all roles + * @param none + * @return $result will return an object + */ + public function roleList( ) { + try { + $result = array(); + + $RBAC =& RBAC::getSingleton(); + $RBAC->initRBAC(); + $oCriteria = $RBAC->listAllRoles (); + $oDataset = GulliverBasePeer::doSelectRs ( $oCriteria);; + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + + while ($aRow = $oDataset->getRow()) { + $result[] = array ( 'guid' => $aRow['ROL_UID'], 'name' => $aRow['ROL_CODE'] ); + $oDataset->next(); + } + + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + + /* + * get all groups + * @param none + * @return $result will return an object + */ + public function groupList() { + try { + $result = array(); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(GroupwfPeer::GRP_STATUS , 'ACTIVE' ); + $oDataset = GroupwfPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + + while ($aRow = $oDataset->getRow()) { + $oGroupwf = new Groupwf(); + $arrayGroupwf = $oGroupwf->Load( $aRow['GRP_UID'] ); + $result[] = array ( 'guid' => $aRow['GRP_UID'], 'name' => $arrayGroupwf['GRP_TITLE'] ); + $oDataset->next(); + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + /* + * get all department + * @param none + * @return $result will return an object + */ + public function departmentList() { + try { + $result = array(); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(DepartmentPeer::DEP_STATUS , 'ACTIVE' ); + $oDataset = DepartmentPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + + while ($aRow = $oDataset->getRow()) { + $oDepartment = new Department(); + $aDepartment = $oDepartment->Load( $aRow['DEP_UID'] ); + $node['guid'] = $aRow['DEP_UID']; + $node['name'] = $aDepartment['DEPO_TITLE']; + $node['parentUID'] = $aDepartment['DEP_PARENT']; + $node['dn'] = $aDepartment['DEP_LDAP_DN']; + + //get the users from this department + $c = new Criteria(); + $c->clearSelectColumns(); + $c->addSelectColumn('COUNT(*)'); + $c->add(UsersPeer::DEP_UID, $aRow['DEP_UID'] ); + $rs = UsersPeer::doSelectRS($c); + $rs->next(); + $row = $rs->getRow(); + $count = $row[0]; + + $node['users'] = $count; + $result[] = $node; + $oDataset->next(); + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + + /* + * Get case list + * @param string $userId + * @return $result will return an object + */ + public function caseList( $userId ) { + try { + $result = array(); + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn(ApplicationPeer::APP_UID); + $oCriteria->addSelectColumn(ApplicationPeer::APP_NUMBER); + $oCriteria->addSelectColumn(ApplicationPeer::APP_STATUS); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_INDEX); + $oCriteria->addAsColumn('CASE_TITLE', 'C1.CON_VALUE' ); + $oCriteria->addAlias("C1", 'CONTENT'); + $caseTitleConds = array(); + $caseTitleConds[] = array( ApplicationPeer::APP_UID , 'C1.CON_ID' ); + $caseTitleConds[] = array( 'C1.CON_CATEGORY' , $del . 'APP_TITLE' . $del ); + $caseTitleConds[] = array( 'C1.CON_LANG' , $del . SYS_LANG . $del ); + $oCriteria->addJoinMC($caseTitleConds , Criteria::LEFT_JOIN); + + $oCriteria->addJoin(ApplicationPeer::APP_UID, AppDelegationPeer::APP_UID, Criteria::LEFT_JOIN); + + $oCriteria->add(ApplicationPeer::APP_STATUS , array('TO_DO','DRAFT'), Criteria::IN); + $oCriteria->add(AppDelegationPeer::USR_UID, $userId ); + $oCriteria->add(AppDelegationPeer::DEL_FINISH_DATE, null, Criteria::ISNULL); + $oCriteria->addDescendingOrderByColumn(ApplicationPeer::APP_NUMBER); + $oDataset = ApplicationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + + while ($aRow = $oDataset->getRow()) { + //$result[] = array ( 'guid' => $aRow['APP_UID'], 'name' => $aRow['CASE_TITLE'], 'status' => $aRow['APP_STATUS'], 'delIndex' => $aRow['DEL_INDEX'] ); + $result[] = array ( 'guid' => $aRow['APP_UID'], 'name' => $aRow['APP_NUMBER'], 'status' => $aRow['APP_STATUS'], 'delIndex' => $aRow['DEL_INDEX'] ); + $oDataset->next(); + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage(), 'status' => $e->getMessage() , 'status' => $e->getMessage() ); + return $result; + } + } + + + /* + * get all groups + * @param none + * @return $result will return an object + */ + public function userList( ) { + try { + $result = array(); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(UsersPeer::USR_STATUS , 'ACTIVE' ); + $oDataset = UsersPeer::doSelectRS($oCriteria); + $oDataset ->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset ->next(); + + while ($aRow = $oDataset->getRow()) { + //$oProcess = new User(); + //$arrayProcess = $oUser->Load( $aRow['PRO_UID'] ); + $result[] = array ( 'guid' => $aRow['USR_UID'], 'name' => $aRow['USR_USERNAME'] ); + $oDataset->next(); + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + + + /* + * get list of all the available triggers in a workspace + * @param none + * @return $result will return an object + */ + public function triggerList( ) { + try { + $del = DBAdapter::getStringDelimiter(); + + $result = array(); + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(TriggersPeer::TRI_UID); + $oCriteria->addSelectColumn(TriggersPeer::PRO_UID); + $oCriteria->addAsColumn('TITLE', 'C1.CON_VALUE' ); + $oCriteria->addAlias("C1", 'CONTENT'); + + $caseTitleConds = array(); + $caseTitleConds[] = array( TriggersPeer::TRI_UID , 'C1.CON_ID' ); + $caseTitleConds[] = array( 'C1.CON_CATEGORY' , $del . 'TRI_TITLE' . $del ); + $caseTitleConds[] = array( 'C1.CON_LANG' , $del . SYS_LANG . $del ); + $oCriteria ->addJoinMC($caseTitleConds , Criteria::LEFT_JOIN); + //$oCriteria->add(TriggersPeer::USR_STATUS , 'ACTIVE' ); + $oDataset = TriggersPeer::doSelectRS($oCriteria); + $oDataset ->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset ->next(); + + while ($aRow = $oDataset->getRow()) { + $result[] = array ( 'guid' => $aRow['TRI_UID'], 'name' => $aRow['TITLE'], 'processId' => $aRow['PRO_UID'] ); + $oDataset->next(); + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + + /* + * get list of the uploaded documents for a given case + * @param string $sApplicationUID + * @param string $sUserUID + * @return $result + */ + public function inputDocumentList( $sApplicationUID, $sUserUID ) { + try { + $oCase = new Cases(); + $fields = $oCase->loadCase($sApplicationUID); + $sProcessUID = $fields['PRO_UID']; + $sTaskUID = ''; + $oCriteria = $oCase->getAllUploadedDocumentsCriteria($sProcessUID, $sApplicationUID, $sTaskUID, $sUserUID); + + $result = array(); + global $_DBArray; + foreach ( $_DBArray['inputDocuments'] as $key => $row ) { + if ( isset($row['DOC_VERSION']) ) { + $docrow = array(); + $docrow['guid'] = $row['APP_DOC_UID']; + $docrow['filename'] = $row['APP_DOC_FILENAME']; + $docrow['docId'] = $row['DOC_UID']; + $docrow['version'] = $row['DOC_VERSION']; + $docrow['createDate'] = $row['CREATE_DATE']; + $docrow['createBy'] = $row['CREATED_BY']; + $docrow['type'] = $row['TYPE']; + $docrow['index'] = $row['APP_DOC_INDEX']; + $docrow['link'] = 'cases/' . $row['DOWNLOAD_LINK']; + $result[] = $docrow; } - break; - case 'usr': - if ($sID == '-1') { // -1: Cuurent user, load from user record - if( isset($APP_UID) ){ - $oAppDelegation = new AppDelegation; - $aAppDel = $oAppDelegation->getLastDeleration($APP_UID); - if(isset($aAppDel)){ - $oUserRow = UsersPeer::retrieveByPK($aAppDel['USR_UID']); - if( isset($oUserRow) ){ - $sID = $oUserRow->getUsrEmail(); - } else { - throw new Exception('User with ID '.$oAppDelegation->getUsrUid(). 'doesn\'t exist'); - } - if( G::emailAddress($sID) ) { - array_push($aRecipient, $sID); + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage() ); + return $result; + } + } + + /* + * input document process list + * @param string $sProcessUID + * @return $result will return an object + */ + public function inputDocumentProcessList( $sProcessUID ) { + try { + global $_DBArray; + $_DBArray = (isset ( $_SESSION ['_DBArray'] ) ? $_SESSION ['_DBArray'] : ''); + + $oMap = new processMap(); + $oCriteria = $oMap->getInputDocumentsCriteria($sProcessUID); + $oDataset = InputDocumentPeer::doSelectRS ( $oCriteria ); + $oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next (); + + $result = array(); + //$result[] = array('guid'=>'char','name'=>'name','description'=>'description'); //not necesary for SOAP message + while ( $aRow = $oDataset->getRow() ) { + if ( $aRow['INP_DOC_TITLE'] == NULL){// There is no transaltion for this Document name, try to get/regenerate the label + $inputDocument = new InputDocument(); + $inputDocumentObj = $inputDocument->load($aRow['INP_DOC_UID']); + $aRow['INP_DOC_TITLE'] = $inputDocumentObj['INP_DOC_TITLE']; + $aRow['INP_DOC_DESCRIPTION'] = $inputDocumentObj['INP_DOC_DESCRIPTION']; + } + $docrow = array(); + $docrow['guid'] = $aRow['INP_DOC_UID']; + $docrow['name'] = $aRow['INP_DOC_TITLE']; + $docrow['description'] = $aRow['INP_DOC_DESCRIPTION']; + $result[] = $docrow; + $oDataset->next (); + } + + //$_DBArray['inputDocArray'] = $inputDocArray; + + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage() ); + return $result; + } + } + + + /* + * output document list + * @param string $sApplicationUID + * @param string $sUserUID + * @return $result will return an object + */ + public function outputDocumentList( $sApplicationUID, $sUserUID ) { + try { + $oCase = new Cases(); + $fields = $oCase->loadCase($sApplicationUID); + $sProcessUID = $fields['PRO_UID']; + $sTaskUID = ''; + $oCriteria = $oCase->getAllGeneratedDocumentsCriteria($sProcessUID, $sApplicationUID, $sTaskUID, $sUserUID); + + $result = array(); + global $_DBArray; + foreach ( $_DBArray['outputDocuments'] as $key => $row ) { + if ( isset($row['DOC_VERSION']) ) { + $docrow = array(); + $docrow['guid'] = $row['APP_DOC_UID']; + $docrow['filename'] = $row['DOWNLOAD_FILE']; + + $docrow['docId'] = $row['DOC_UID']; + $docrow['version'] = $row['DOC_VERSION']; + $docrow['createDate'] = $row['CREATE_DATE']; + $docrow['createBy'] = $row['CREATED_BY']; + $docrow['type'] = $row['TYPE']; + $docrow['index'] = $row['APP_DOC_INDEX']; + $docrow['link'] = 'cases/' . $row['DOWNLOAD_LINK']; + $result[] = $docrow; + } + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage() ); + return $result; + } + } + + /* + * remove document + * @param string $appDocUid + * @return $result will return an object + */ + public function removeDocument($appDocUid) { + try { + $oAppDocument = new AppDocument(); + $oAppDocument->remove( $appDocUid, 1 ); //always send version 1 + $result = new wsResponse (0, " $appDocUid"); + + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + + + /* + * get task list + * @param string $userId + * @return $result will return an object + */ + public function taskList( $userId ) { + try { + g::loadClass('groups'); + $oGroup = new Groups(); + $aGroups = $oGroup->getActiveGroupsForAnUser($userId); + + $result = array(); + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn(TaskPeer::TAS_UID); + $oCriteria->setDistinct(); + $oCriteria->addAsColumn('TAS_TITLE', 'C1.CON_VALUE' ); + $oCriteria->addAlias("C1", 'CONTENT'); + $tasTitleConds = array(); + $tasTitleConds[] = array( TaskPeer::TAS_UID , 'C1.CON_ID' ); + $tasTitleConds[] = array( 'C1.CON_CATEGORY' , $del . 'TAS_TITLE' . $del ); + $tasTitleConds[] = array( 'C1.CON_LANG' , $del . SYS_LANG . $del ); + $oCriteria->addJoinMC($tasTitleConds , Criteria::LEFT_JOIN); + + $oCriteria->addJoin ( TaskPeer::TAS_UID, TaskUserPeer::TAS_UID, Criteria::LEFT_JOIN ); + $oCriteria->addOr ( TaskUserPeer::USR_UID, $userId ); + $oCriteria->addOr ( TaskUserPeer::USR_UID, $aGroups, Criteria::IN ); + + $oDataset = TaskPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + + while ($aRow = $oDataset->getRow()) { + $result[] = array ( 'guid' => $aRow['TAS_UID'], 'name' => $aRow['TAS_TITLE'] ); + $oDataset->next(); + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + /* + * send message + * @param string $caseId + * @param string $sFrom + * @param string $sTo + * @param string $sCc + * @param string $sBcc + * @param string $sSubject + * @param string $sTemplate + * @param $appFields = null + * @return $result will return an object + */ + public function sendMessage($caseId, $sFrom, $sTo, $sCc, $sBcc, $sSubject, $sTemplate, $appFields = null, $aAttachment = null ) { + try { + $aSetup = getEmailConfiguration(); + + $oSpool = new spoolRun(); + $oSpool->setConfig(array( + 'MESS_ENGINE' => $aSetup['MESS_ENGINE'], + 'MESS_SERVER' => $aSetup['MESS_SERVER'], + 'MESS_PORT' => $aSetup['MESS_PORT'], + 'MESS_ACCOUNT' => $aSetup['MESS_ACCOUNT'], + 'MESS_PASSWORD' => $aSetup['MESS_PASSWORD'], + 'SMTPAuth' => $aSetup['MESS_RAUTH'] + )); + + + $oCase = new Cases(); + $oldFields = $oCase->loadCase( $caseId ); + + $pathEmail = PATH_DATA_SITE . 'mailTemplates' . PATH_SEP . $oldFields['PRO_UID'] . PATH_SEP; + $fileTemplate = $pathEmail . $sTemplate; + G::mk_dir( $pathEmail, 0777,true); + + if ( ! file_exists ( $fileTemplate ) ) { + $result = new wsResponse (28, "Template file '$fileTemplate' does not exist." ); + return $result; + } + + if ( $appFields == null ) { + $Fields = $oldFields['APP_DATA']; + } else { + $Fields = $appFields; + } + $templateContents = file_get_contents ( $fileTemplate ); + + //$sContent = G::unhtmlentities($sContent); + $iAux = 0; + $iOcurrences = preg_match_all('/\@(?:([\>])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*(?:[\\\\][\w\W])?)*)\))((?:\s*\[[\'"]?\w+[\'"]?\])+)?/', $templateContents, $aMatch, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); + + if ($iOcurrences) { + for($i = 0; $i < $iOcurrences; $i++) { + preg_match_all('/@>' . $aMatch[2][$i][0] . '([\w\W]*)' . '@<' . $aMatch[2][$i][0] . '/', $templateContents, $aMatch2, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); + $sGridName = $aMatch[2][$i][0]; + $sStringToRepeat = $aMatch2[1][0][0]; + if (isset($Fields[$sGridName])) { + if (is_array($Fields[$sGridName])) { + $sAux = ''; + foreach ($Fields[$sGridName] as $aRow) { + $sAux .= G::replaceDataField($sStringToRepeat, $aRow); } } } - } else { - $oUserRow = UsersPeer::retrieveByPK($sID); - $sID = $oUserRow->getUsrEmail(); - if( G::emailAddress($sID) ) { - array_push($aRecipient, $sID); - } + $templateContents = str_replace('@>' . $sGridName . $sStringToRepeat . '@<' . $sGridName, $sAux, $templateContents); } + } - break; + $sBody = G::replaceDataField( $templateContents, $Fields); - case 'grp': - G::LoadClass('groups'); - $oGroups = new Groups(); - $oCriteria = $oGroups->getUsersGroupCriteria($sID); - $oDataset = GroupwfPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - while ($oDataset->next()) { - $aGroup = $oDataset->getRow(); - //to validate email address - if( G::emailAddress($aGroup['USR_EMAIL']) ) { - array_push($aRecipient, $aGroup['USR_EMAIL']); - } - } + if ($sFrom != '') { + $sFrom = $sFrom . ' <' . $aSetup['MESS_ACCOUNT'] . '>'; + } + else { + $sFrom = $aSetup['MESS_ACCOUNT']; + } - break; + $messageArray = array( + 'msg_uid' => '', + 'app_uid' => $caseId, + 'del_index' => 0, + 'app_msg_type' => 'TRIGGER', + 'app_msg_subject' => $sSubject, + 'app_msg_from' => $sFrom, + 'app_msg_to' => $sTo, + 'app_msg_body' => $sBody, + 'app_msg_cc' => $sCc, + 'app_msg_bcc' => $sBcc, + 'app_msg_attach' => $aAttachment, + 'app_msg_template' => '', + 'app_msg_status' => 'pending' + ); + $oSpool->create( $messageArray ); + $oSpool->sendMail(); - case 'dyn': - $oCase = new Cases(); - $aFields = $oCase->loadCase($APP_UID); - $aFields['APP_DATA'] = array_merge($aFields['APP_DATA'], G::getSystemConstants()); - - //to validate email address - if( isset($aFields['APP_DATA'][$sID]) && G::emailAddress($aFields['APP_DATA'][$sID]) ) { - array_push($aRecipient, $aFields['APP_DATA'][$sID]); - } - break; + if ( $oSpool->status == 'sent' ) + $result = new wsResponse (0, "message sent : $sTo" ); + else + $result = new wsResponse (29, $oSpool->status . ' ' . $oSpool->error . print_r ($aSetup ,1 ) ); + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; } } - switch($retType){ - case 'array': - return $aRecipient; + /* + * get case information + * @param string $caseId + * @param string $iDelIndex + * @return $result will return an object + */ + public function getCaseInfo($caseId, $iDelIndex ) { + try { + $oCase = new Cases(); + $aRows = $oCase->loadCase( $caseId, $iDelIndex ); + if ( count($aRows) == 0 ) { + $result = new wsResponse (16, "Case $caseNumber does not exist" ); + return $result; + } - case 'string': - return implode(',', $aRecipient); + $oProcess = new Process(); + try { + $uFields = $oProcess->load($aRows['PRO_UID']); + $processName = $uFields['PRO_TITLE']; + } + catch ( Exception $e ) { + $processName = ''; + } + $result = new wsResponse (0, "Command executed successfully" ); + $result->caseId = $aRows['APP_UID']; + $result->caseNumber = $aRows['APP_NUMBER']; + $result->caseName = $aRows['TITLE']; + $result->caseStatus = $aRows['APP_STATUS']; + $result->caseParalell = $aRows['APP_PARALLEL']; + $result->caseCreatorUser = $aRows['APP_INIT_USER']; + $result->caseCreatorUserName = $aRows['CREATOR']; + $result->processId = $aRows['PRO_UID']; + $result->processName = $processName; + $result->createDate = $aRows['CREATE_DATE']; - default: - return $aRecipient; + //now fill the array of AppDelegationPeer + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_INDEX); + $oCriteria->addSelectColumn(AppDelegationPeer::USR_UID); + $oCriteria->addSelectColumn(AppDelegationPeer::TAS_UID); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_THREAD); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_THREAD_STATUS); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE); + $oCriteria->add(AppDelegationPeer::APP_UID, $caseId); + $oCriteria->add(AppDelegationPeer::DEL_FINISH_DATE, null, Criteria::ISNULL ); + + $oCriteria->addAscendingOrderByColumn(AppDelegationPeer::DEL_INDEX); + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + $aCurrentUsers = array(); + while($oDataset->next()) { + $aAppDel = $oDataset->getRow(); + + $oUser = new Users(); + try { + $oUser->load($aAppDel['USR_UID']); + $uFields = $oUser->toArray(BasePeer::TYPE_FIELDNAME); + $currentUserName = $oUser->getUsrFirstname() . ' ' . $oUser->getUsrLastname(); + } + catch ( Exception $e ) { + $currentUserName = ''; + } + + $oTask = new Task(); + try { + $uFields = $oTask->load($aAppDel['TAS_UID']); + $taskName = $uFields['TAS_TITLE']; + } + catch ( Exception $e ) { + $taskName = ''; + } + + $currentUser = new stdClass(); + $currentUser->userId = $aAppDel['USR_UID']; + $currentUser->userName = $currentUserName; + $currentUser->taskId = $aAppDel['TAS_UID']; + $currentUser->taskName = $taskName; + $currentUser->delIndex = $aAppDel['DEL_INDEX']; + $currentUser->delThread = $aAppDel['DEL_THREAD']; + $currentUser->delThreadStatus = $aAppDel['DEL_THREAD_STATUS']; + $aCurrentUsers[] = $currentUser; + } + + $result->currentUsers = $aCurrentUsers; + + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } } + + /* + * creates a new user + * @param string sessionId : The session ID + * @param string userId : The username for the new user. + * @param string firstname : The user's first name. + * @param string lastname : The user's last name. + * @param string email : The user's email address. + * @param string role : The user's role, such as 'PROCESSMAKER_ADMIN' or 'PROCESSMAKER_OPERATOR'. + * @param string password : The user's password such as 'Be@gle2'(It will be automatically encrypted with an MD5 hash). + * @return $result will return an object + */ + public function createUser( $userId, $firstname, $lastname, $email, $role, $password) { + try { + if($userId=='') + { $result = new wsCreateUserResponse (25, "Username is required"); + return $result; + } + + if($password=='') + { $result = new wsCreateUserResponse (26, "Password is required"); + return $result; + } + + if($firstname=='') + { $result = new wsCreateUserResponse (27, "First Name is required"); + return $result; + } + + if(strlen($password)>20) + { $result = new wsCreateUserResponse (28, "Password surprases the maximun length allowed", ''); + return $result; + } + + global $RBAC; + $RBAC->initRBAC(); + + $user = $RBAC->verifyUser($userId); + if ( $user == 1){ + $result = new wsCreateUserResponse (7, "Username '$userId' already exists", '' ) ; + return $result; + } + + $rol=$RBAC->loadById($role); + if ( is_array($rol) ){ + $strRole = $rol['ROL_CODE']; + } + else { + $very_rol = $RBAC->verifyByCode($role); + if ( $very_rol==0 ){ + $result = new wsResponse (6, "Invalid role '$role'"); + return $result; + } + $strRole = $role; + } + + $aData['USR_USERNAME'] = $userId; + $aData['USR_PASSWORD'] = md5($password); + $aData['USR_FIRSTNAME'] = $firstname; + $aData['USR_LASTNAME'] = $lastname; + $aData['USR_EMAIL'] = $email; + $aData['USR_DUE_DATE'] = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1); + $aData['USR_CREATE_DATE'] = date('Y-m-d H:i:s'); + $aData['USR_UPDATE_DATE'] = date('Y-m-d H:i:s'); + $aData['USR_STATUS'] = 1; + + $sUserUID = $RBAC->createUser($aData, $strRole ); + + $aData['USR_UID'] = $sUserUID; + $aData['USR_PASSWORD'] = md5($sUserUID); + $aData['USR_STATUS'] = 'ACTIVE'; + $aData['USR_COUNTRY'] = ''; + $aData['USR_CITY'] = ''; + $aData['USR_LOCATION'] = ''; + $aData['USR_ADDRESS'] = ''; + $aData['USR_PHONE'] = ''; + $aData['USR_ZIP_CODE'] = ''; + $aData['USR_POSITION'] = ''; + $aData['USR_RESUME'] = ''; + $aData['USR_BIRTHDAY'] = date('Y-m-d'); + $aData['USR_ROLE'] = $strRole ; + + $oUser = new Users(); + $oUser->create($aData); + + $res = new wsResponse (0, "User $firstname $lastname [$userId] created successfully"); + $result = array('status_code' => $res->status_code , + 'message' => $res->message, + 'userUID' => $sUserUID, + 'timestamp' => $res->timestamp ); + + return $result; + } + catch ( Exception $e ) { + $result = wsCreateUserResponse (100 , $e->getMessage(), '' ); + return $result; + } + } + + + /* + * create Group + * @param string $groupName + * @return $result will return an object + */ + public function createGroup( $groupName) { + try { + if( trim($groupName) == '' ) { + $result = new wsCreateGroupResponse (25, "Group name is required", ''); + return $result; + } + + $group = new Groupwf(); + $grpRow['GRP_TITLE'] = $groupName; + $groupId = $group->create( $grpRow ); + + $result = new wsCreateGroupResponse (0, "Group $groupName created successfully", $groupId); + + return $result; + } + catch ( Exception $e ) { + $result = wsCreateGroupResponse (100 , $e->getMessage(), '' ); + return $result; + } + } + + /* + * Create New Department link on the top section of the left pane allows you to create a root-level department. + * @param string $departmentName + * @param string $parentUID + * @return $result will return an object + */ + public function createDepartment( $departmentName, $parentUID ) { + try { + if( trim($departmentName) == '' ) { + $result = new wsCreateDepartmentResponse (25, "Department name is required", ''); + return $result; + } + + $department = new department(); + $row['DEP_TITLE'] = $departmentName; + $row['DEP_PARENT'] = $parentUID; + + $departmentId = $department->create( $row ); + + $result = new wsCreateDepartmentResponse (0, "$departmentName, $parentUID Department $departmentName created successfully", $departmentId); + return $result; + } + catch ( Exception $e ) { + $result = wsCreateDepartmentResponse (100 , $e->getMessage(), '' ); + return $result; + } + } + + /* + * remove user from group + * @param string $appDocUid + * @return $result will return an object + */ + public function removeUserFromGroup($userId, $groupId) { + try { + G::LoadClass('groups'); + global $RBAC; + $RBAC->initRBAC(); + $user=$RBAC->verifyUserId($userId); + if($user==0){ + $result = new wsResponse (3, "User not registered in the system"); + return $result; + } + + $groups = new Groups; + $very_group = $groups->verifyGroup( $groupId ); + if ( $very_group==0 ) { + $result = new wsResponse (9, "Group not registered in the system"); + return $result; + } + + $very_user = $groups->verifyUsertoGroup( $groupId, $userId); + if($very_user==1){ + $oGroup = new Groups(); + $oGroup->removeUserOfGroup($groupId, $userId); + $result = new wsResponse (0, "command executed successfuly"); + return $result; + } + //$oGroup->removeUserOfGroup($_POST['GRP_UID'], $_POST['USR_UID']); + $result = new wsResponse (8, "User not registered in the group"); + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } +//G::LoadClass('groups'); +// $oGroup = new Groups(); +// $oGroup->removeUserOfGroup($_POST['GRP_UID'], $_POST['USR_UID']); + } + + /* + * assigns a user to a group + * @param string $userId + * @param string $groupId + * @return $result will return an object + */ + public function assignUserToGroup( $userId, $groupId) { + try { + global $RBAC; + $RBAC->initRBAC(); + $user=$RBAC->verifyUserId($userId); + if($user==0){ + $result = new wsResponse (3, "User not registered in the system"); + return $result; + } + + $groups = new Groups; + $very_group = $groups->verifyGroup( $groupId ); + if ( $very_group==0 ) { + $result = new wsResponse (9, "Group not registered in the system"); + return $result; + } + + $very_user = $groups->verifyUsertoGroup( $groupId, $userId); + if($very_user==1){ + $result = new wsResponse (8, "User already exists in the group"); + return $result; + } + $groups->addUserToGroup( $groupId, $userId); + $result = new wsResponse (0, "command executed successfuly"); + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + + + /* + * assigns user to department + * @param string $userId + * @param string $depId + * @param string $manager + * @return $result will return an object + */ + public function assignUserToDepartment( $userId, $depId, $manager) { + try { + global $RBAC; + $RBAC->initRBAC(); + $user=$RBAC->verifyUserId($userId); + if($user==0){ + $result = new wsResponse (3, "User not registered in the system"); + return $result; + } + + $deps = new Department; + if ( !$deps->existsDepartment( $depId ) ) { + $result = new wsResponse (100, "Department $depId is not registered in the system"); + return $result; + } + + if ( ! $deps->existsUserInDepartment( $depId, $userId ) ) { + $deps->addUserToDepartment( $depId, $userId, $manager, true ); + } + + $result = new wsResponse (0, "command executed successfuly"); + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + + /* + * sends variables to a case + * @param string $caseId + * @param string $variables + * @return $result will return an object + */ + public function sendVariables($caseId, $variables) { + //delegation where app uid (caseId) y usruid(session) ordenar delindes descendente y agaarr el primero + //delfinishdate != null error + try { + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE); + $oCriteria->add(AppDelegationPeer::APP_UID, $caseId); + $oCriteria->add(AppDelegationPeer::DEL_FINISH_DATE, null, Criteria::ISNULL ); + + $oCriteria->addDescendingOrderByColumn(AppDelegationPeer::DEL_INDEX); + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + $cnt = 0; + while($oDataset->next()) { + $aRow = $oDataset->getRow(); + $cnt++; + } + + if ($cnt == 0){ + $result = new wsResponse (18, 'This case delegation is already closed or does not exist'); + return $result; + } + if ( is_array($variables)) { + $cant = count ( $variables ); + + if($cant > 0) { + $oCase = new Cases(); + $oldFields = $oCase->loadCase( $caseId ); + $oldFields['APP_DATA'] = array_merge( $oldFields['APP_DATA'], $variables ); + ob_start(); + print_r($variables); + $cdata = ob_get_contents(); + ob_end_clean(); + $up_case = $oCase->updateCase($caseId, $oldFields); + $result = new wsResponse (0, "$cant variables received: \n".trim(str_replace('Array', '', $cdata)) ); + return $result; + } + else { + $result = new wsResponse (23, "The variables param length is zero"); + return $result; + } + } else { + $result = new wsResponse (24, "The variables param is not an array"); + return $result; + } + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + + /* + * get variables The variables can be system variables and/or case variables + * @param string $caseId + * @param string $variables + * @return $result will return an object + */ + public function getVariables($caseId, $variables) { + try { + if ( is_array($variables) ) { + $cant = count ( $variables ); + if($cant > 0) { + $oCase = new Cases(); + + $caseFields = $oCase->loadCase( $caseId ); + $oldFields = $caseFields['APP_DATA']; + $resFields = array(); + foreach ( $variables as $key => $val ) { + $a .= $val->name . ', '; + if ( isset ( $oldFields[ $val->name ] ) ) { + if ( !is_array ( $oldFields[ $val->name ] ) ) { + $node = new stdClass(); + $node->name = $val->name ; + $node->value = $oldFields[ $val->name ] ; + $resFields[ ] = $node; + }else{ + foreach($oldFields[ $val->name ] as $gridKey => $gridRow){//Sp?cial Variables like grids or checkgroups + if(is_array($gridRow)){//Grids + foreach($gridRow as $col => $colValue){ + $node = new stdClass(); + $node->name = $val->name."][".$gridKey."][".$col; + $node->value =$colValue; + $resFields[] = $node; + } + }else{//Checkgroups, Radiogroups + $node = new stdClass(); + $node->name = $key; + $node->value =implode("|",$val); + $resFields[] = $node; + } + } + } + } + } + $result = new wsGetVariableResponse (0, count($resFields) . " variables sent" , $resFields ); + return $result; + } + else { + $result = new wsGetVariableResponse (23, "The variables param length is zero", null); + return $result; + } + } + else { + $result = new wsGetVariableResponse (24, "The variables param is not a array", null); + return $result; + } + } + catch ( Exception $e ) { + $result = new wsGetVariableResponse (100, $e->getMessage(), NULL ); + return $result; + } + + } + + /* + * new Case begins a new case under the name of the logged-in user. + * @param string $processId + * @param string $userId + * @param string $taskId + * @param string $variables + * @return $result will return an object + */ + public function newCase($processId, $userId, $taskId, $variables) { + try { + $Fields = array(); + if ( is_array($variables) && count($variables)>0 ) { + $Fields = $variables; + } + $oProcesses = new Processes(); + $pro = $oProcesses->processExists($processId); + if( !$pro ) { + $result = new wsResponse (11, "Invalid process $processId"); + return $result; + } + + $oCase = new Cases(); + $oTask = new Tasks(); + $startingTasks = $oCase->getStartCases($userId); + array_shift ($startingTasks); //remove the first row, the header row + $founded = ''; + $tasksInThisProcess = 0; + $validTaskId = $taskId; + foreach ( $startingTasks as $key=> $val ) { + if ( $val['pro_uid'] == $processId ) { $tasksInThisProcess ++; $validTaskId = $val['uid']; } + if ( $val['uid'] == $taskId ) $founded = $val['value']; + } + + if ( $taskId == '' ) { + if ( $tasksInThisProcess == 1 ) { + $founded = $validTaskId; + $taskId = $validTaskId; + } + if ( $tasksInThisProcess > 1 ) { + $result = new wsResponse (13, "Multiple starting tasks in the process"); + return $result; + } + } + + if( $founded == '') { + $result = new wsResponse (14, "Task invalid or the user is not assigned to the task"); + return $result; + } + + $case = $oCase->startCase($taskId, $userId); + $caseId = $case['APPLICATION']; + $caseNr = $case['CASE_NUMBER']; + + $oldFields = $oCase->loadCase( $caseId ); + + $oldFields['APP_DATA'] = array_merge( $oldFields['APP_DATA'], $Fields); + + $up_case = $oCase->updateCase($caseId, $oldFields); + + $result = new wsResponse (0, "Command executed successfully"); + $result->caseId = $caseId; + $result->caseNumber = $caseNr; + + + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + + /* + * creates a new case impersonating a user who has the proper privileges to create new cases + * @param string $processId + * @param string $userId + * @param string $variables + * @return $result will return an object + */ + public function newCaseImpersonate($processId, $userId, $variables) { + try { + if(is_array($variables)) { + if(count($variables)>0) { + $c=count($variables); + $Fields = $variables; + if($c == 0) { //Si no tenenmos ninguna variables en el array variables. + $result = new wsResponse (10, "Array of variables is empty"); + return $result; + } + } + } else { + $result = new wsResponse (10, "The variables param is not an array"); + return $result; + } + + $oProcesses = new Processes(); + $pro = $oProcesses->processExists($processId); + + if(!$pro) { + $result = new wsResponse (11, "Invalid process $processId!!"); + return $result; + } + + $oCase = new Cases(); + + $tasks = $oProcesses->getStartingTaskForUser($processId, $userId); + $numTasks=count($tasks); + + if($numTasks==1) + { + $oTask = new Tasks(); + $very = $oTask->verifyUsertoTask($userId, $tasks[0]['TAS_UID']); + if(is_array($very)) + { + if($very['TU_RELATION']==2) + { + $group=$groups->getUsersOfGroup( $tasks[0]['TAS_UID'] ); + if(!is_array($group)) + { $result = new wsResponse (14, "The user is not assigned to the task"); + return $result; + } + } + } + else + { $result = new wsResponse (14, "The user is not assigned to the task"); + return $result; + } + + $case = $oCase->startCase($tasks[0]['TAS_UID'], $userId); + $caseId = $case['APPLICATION']; + + $oldFields = $oCase->loadCase( $caseId ); + + $oldFields['APP_DATA'] = array_merge( $oldFields['APP_DATA'], $Fields); + + $up_case = $oCase->updateCase($caseId, $oldFields); + $result = new wsResponse (0, "Command executed successfully"); + return $result; + } + else { + if($numTasks==0) { + $result = new wsResponse (12, "No starting task defined"); + return $result; + } + if($numTasks > 1){ + $result = new wsResponse (13, "Multiple starting tasks in the process"); + return $result; + } + } + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + + /* + * derivate Case moves the case to the next task in the process according to the routing rules + * @param string $userId + @param string $caseId + @param string $delIndex + * @return $result will return an object + */ + public function derivateCase($userId, $caseId, $delIndex, $bExecuteTriggersBeforeAssignment = false) { + try { + $sStatus = 'TO_DO'; + + $varResponse = ''; + $varTriggers = "\n"; + + if ($delIndex == '') { + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_INDEX); + $oCriteria->add(AppDelegationPeer::APP_UID, $caseId); + $oCriteria->add(AppDelegationPeer::DEL_FINISH_DATE, null, Criteria::ISNULL); + if (AppDelegationPeer::doCount($oCriteria) > 1) { + $result = new wsResponse (20, 'Please specify the delegation index'); + return $result; + } + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + $aRow = $oDataset->getRow(); + $delIndex = $aRow['DEL_INDEX']; + } + + $oAppDel = new AppDelegation(); + $appdel = $oAppDel->Load($caseId, $delIndex); + + if($userId!=$appdel['USR_UID']) + { + $result = new wsResponse (17, "This case is assigned to another user"); + return $result; + } + + if($appdel['DEL_FINISH_DATE']!=NULL) + { + $result = new wsResponse (18, 'This case delegation is already closed or does not exist'); + return $result; + } + + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(AppDelayPeer::APP_UID); + $oCriteria->addSelectColumn(AppDelayPeer::APP_DEL_INDEX); + $oCriteria->add(AppDelayPeer::APP_TYPE, ''); + $oCriteria->add($oCriteria->getNewCriterion(AppDelayPeer::APP_TYPE, 'PAUSE')->addOr($oCriteria->getNewCriterion(AppDelayPeer::APP_TYPE, 'CANCEL'))); + $oCriteria->addAscendingOrderByColumn(AppDelayPeer::APP_ENABLE_ACTION_DATE); + $oDataset = AppDelayPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + $aRow = $oDataset->getRow(); + + if(is_array($aRow)) + { + if ( isset($aRow['APP_DISABLE_ACTION_USER']) && $aRow['APP_DISABLE_ACTION_USER']!=0 && + isset($aRow['APP_DISABLE_ACTION_DATE']) && $aRow['APP_DISABLE_ACTION_DATE']!='' ) { + $result = new wsResponse (19, "This case is in status ". $aRow['APP_TYPE']); + return $result; + } + } + + $aData['APP_UID'] = $caseId; + $aData['DEL_INDEX'] = $delIndex; + + //load data + $oCase = new Cases (); + $appFields = $oCase->loadCase( $caseId ); + $appFields['APP_DATA']['APPLICATION'] = $caseId; + + if ($bExecuteTriggersBeforeAssignment) { + //Execute triggers before assignment + $aTriggers = $oCase->loadTriggers($appdel['TAS_UID'], 'ASSIGN_TASK', -1, 'BEFORE' ); + if (count($aTriggers) > 0) { + $oPMScript = new PMScript(); + foreach ($aTriggers as $aTrigger) { + //$appFields = $oCase->loadCase( $caseId ); + //$appFields['APP_DATA']['APPLICATION'] = $caseId; + + #@Neyek ############################################################################################# + if( !$this->stored_system_variables ) { + $appFields['APP_DATA'] = array_merge ( $appFields['APP_DATA'], G::getSystemConstants() ); + } else { + $oParams = new stdClass(); + $oParams->option = 'STORED SESSION'; + $oParams->SID = $this->wsSessionId; + + $appFields['APP_DATA'] = array_merge ( $appFields['APP_DATA'], G::getSystemConstants($oParams)); + } + ##################################################################################################### + + $oPMScript->setFields( $appFields['APP_DATA'] ); + $bExecute = true; + if ($aTrigger['ST_CONDITION'] !== '') { + $oPMScript->setScript($aTrigger['ST_CONDITION']); + $bExecute = $oPMScript->evaluate(); + } + if ($bExecute) { + $oPMScript->setScript($aTrigger['TRI_WEBBOT']); + $oPMScript->execute(); + $varTriggers .= "
-= Before Assignment =-
" . nl2br(htmlentities($aTrigger['TRI_WEBBOT'], ENT_QUOTES)) . "
"; + + + //$appFields = $oCase->loadCase( $caseId ); + $appFields['APP_DATA'] = $oPMScript->aFields; + $oCase->updateCase ( $caseId, $appFields ); + } + } + } + } + + //Execute triggers before derivation + $aTriggers = $oCase->loadTriggers($appdel['TAS_UID'], 'ASSIGN_TASK', -2, 'BEFORE' ); + if (count($aTriggers) > 0) { + $oPMScript = new PMScript(); + $varTriggers .= "-= Before Derivation =-
"; + foreach ($aTriggers as $aTrigger) { + //$appFields = $oCase->loadCase( $caseId ); + //$appFields['APP_DATA']['APPLICATION'] = $caseId; + + #@Neyek ############################################################################################# + if( !$this->stored_system_variables ) { + $appFields['APP_DATA'] = array_merge ( $appFields['APP_DATA'], G::getSystemConstants() ); + } else { + $oParams = new stdClass(); + $oParams->option = 'STORED SESSION'; + $oParams->SID = $this->wsSessionId; + + $appFields['APP_DATA'] = array_merge ( $appFields['APP_DATA'], G::getSystemConstants($oParams)); + } + ##################################################################################################### + + $oPMScript->setFields( $appFields['APP_DATA'] ); + $bExecute = true; + if ($aTrigger['ST_CONDITION'] !== '') { + $oPMScript->setScript($aTrigger['ST_CONDITION']); + $bExecute = $oPMScript->evaluate(); + + } + if ($bExecute) { + $oPMScript->setScript($aTrigger['TRI_WEBBOT']); + $oPMScript->execute(); + $oTrigger = TriggersPeer::retrieveByPk($aTrigger['TRI_UID']); + $varTriggers .= " - ".nl2br(htmlentities($oTrigger->getTriTitle(), ENT_QUOTES)) . "
"; + //$appFields = $oCase->loadCase( $caseId ); + $appFields['APP_DATA'] = $oPMScript->aFields; + //$appFields['APP_DATA']['APPLICATION'] = $caseId; + $oCase->updateCase ( $caseId, $appFields ); + } + } + } + + $oDerivation = new Derivation(); + $derive = $oDerivation->prepareInformation($aData); + if (isset($derive[1])) { + if ($derive[1]['ROU_TYPE'] == 'SELECT') { + $result = new wsResponse (21, 'Can not route a case with Manual Assignment using webservices'); + return $result; + } + } + else { + $result = new wsResponse (22, 'Task does not have a routing rule; check process definition'); + return $result; + } + foreach ( $derive as $key=>$val ) { + if($val['NEXT_TASK']['TAS_ASSIGN_TYPE']=='MANUAL') + { + $result = new wsResponse (15, "The task is defined for Manual assignment"); + return $result; + } + $nextDelegations[] = array( + 'TAS_UID' => $val['NEXT_TASK']['TAS_UID'], + 'USR_UID' => $val['NEXT_TASK']['USER_ASSIGNED']['USR_UID'], + 'TAS_ASSIGN_TYPE' => $val['NEXT_TASK']['TAS_ASSIGN_TYPE'], + 'TAS_DEF_PROC_CODE' => $val['NEXT_TASK']['TAS_DEF_PROC_CODE'], + 'DEL_PRIORITY' => $appdel['DEL_PRIORITY'], + 'TAS_PARENT' => $val['NEXT_TASK']['TAS_PARENT'] + ); + $varResponse = $varResponse . ($varResponse!=''?',':'') . $val['NEXT_TASK']['TAS_TITLE'].'('.$val['NEXT_TASK']['USER_ASSIGNED']['USR_USERNAME'].')'; + } + + $appFields['DEL_INDEX'] = $delIndex; + if ( isset($derive['TAS_UID']) ) + $appFields['TAS_UID'] = $derive['TAS_UID']; + + //Save data - Start + //$appFields = $oCase->loadCase( $caseId ); + //$oCase->updateCase ( $caseId, $appFields ); + //Save data - End + + $row = array(); + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn(RoutePeer::ROU_TYPE); + $oCriteria->addSelectColumn(RoutePeer::ROU_NEXT_TASK); + $oCriteria->add(RoutePeer::TAS_UID, $appdel['TAS_UID']); + $oDataset = TaskPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $row[] = array ( 'ROU_TYPE' => $aRow['ROU_TYPE'], 'ROU_NEXT_TASK' => $aRow['ROU_NEXT_TASK'] ); + $oDataset->next(); + } + + //derivate case + $aCurrentDerivation = array( + 'APP_UID' => $caseId, + 'DEL_INDEX' => $delIndex, + 'APP_STATUS' => $sStatus, + 'TAS_UID' => $appdel['TAS_UID'], + 'ROU_TYPE' => $row[0]['ROU_TYPE'] + ); + + $oDerivation->derivate( $aCurrentDerivation, $nextDelegations ); + $appFields = $oCase->loadCase($caseId); + + $aTriggers = $oCase->loadTriggers($appdel['TAS_UID'], 'ASSIGN_TASK', -2, 'AFTER' ); + if (count($aTriggers) > 0) { + $oPMScript = new PMScript(); + //$appFields['APP_DATA']['APPLICATION'] = $caseId; + + #@Neyek ############################################################################################# + if( !$this->stored_system_variables ) { + $appFields['APP_DATA'] = array_merge ( $appFields['APP_DATA'], G::getSystemConstants() ); + } else { + $oParams = new stdClass(); + $oParams->option = 'STORED SESSION'; + $oParams->SID = $this->wsSessionId; + + $appFields['APP_DATA'] = array_merge ( $appFields['APP_DATA'], G::getSystemConstants($oParams)); + } + ##################################################################################################### + + $oPMScript->setFields( $appFields['APP_DATA'] ); + $varTriggers .= "-= After Derivation =-
"; + foreach ($aTriggers as $aTrigger) { + $bExecute = true; + if ($aTrigger['ST_CONDITION'] !== '') { + $oPMScript->setScript($aTrigger['ST_CONDITION']); + $bExecute = $oPMScript->evaluate(); + } + if ($bExecute) { + $oPMScript->setScript($aTrigger['TRI_WEBBOT']); + $oPMScript->execute(); + $oTrigger = TriggersPeer::retrieveByPk($aTrigger['TRI_UID']); + $varTriggers .= " - ".nl2br(htmlentities($oTrigger->getTriTitle(), ENT_QUOTES)) . "
"; + //$appFields = $oCase->loadCase( $caseId ); + $appFields['APP_DATA'] = $oPMScript->aFields; + //$appFields['APP_DATA']['APPLICATION'] = $caseId; + //$appFields = $oCase->loadCase( $caseId ); + $oCase->updateCase ( $caseId, $appFields ); + } + } + } + + $oUser = new Users(); + $aUser = $oUser->load($userId); + $sFromName = '"' . $aUser['USR_FIRSTNAME'] . ' ' . $aUser['USR_LASTNAME'] . '"'; + $oCase->sendNotifications($appdel['TAS_UID'], $nextDelegations, $appFields['APP_DATA'], $caseId, $delIndex, $sFromName); + + //Save data - Start + //$appFields = $oCase->loadCase( $caseId ); + //$oCase->updateCase ( $caseId, $appFields ); + //Save data - End + + + $oProcess = new Process(); + $oProcessFieds = $oProcess->Load($appFields['PRO_UID']); + //here dubug mode in web entry + if(isset($oProcessFieds['PRO_DEBUG']) && $oProcessFieds['PRO_DEBUG']){ + $result = new wsResponse (0, $varResponse."

".G::LoadTranslation('ID_DEBUG_MESSAGE')."
".$varTriggers); + }else{ + $result = new wsResponse (0, $varResponse." --- ".$oProcessFieds['PRO_DUBUG']); + } + + $res = $result->getPayloadArray (); + + //now fill the array of AppDelegationPeer + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_INDEX); + $oCriteria->addSelectColumn(AppDelegationPeer::USR_UID); + $oCriteria->addSelectColumn(AppDelegationPeer::TAS_UID); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_THREAD); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_THREAD_STATUS); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE); + $oCriteria->add(AppDelegationPeer::APP_UID, $caseId); + $oCriteria->add(AppDelegationPeer::DEL_PREVIOUS, $delIndex ); + $oCriteria->addAscendingOrderByColumn(AppDelegationPeer::DEL_INDEX); + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset ->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + $aCurrentUsers = array(); + while($oDataset->next()) { + $aAppDel = $oDataset->getRow(); + + $oUser = new Users(); + try { + $oUser->load($aAppDel['USR_UID']); + $uFields = $oUser->toArray(BasePeer::TYPE_FIELDNAME); + $currentUserName = $oUser->getUsrFirstname() . ' ' . $oUser->getUsrLastname(); + } + catch ( Exception $e ) { + $currentUserName = ''; + } + + $oTask = new Task(); + try { + $uFields = $oTask->load($aAppDel['TAS_UID']); + $taskName = $uFields['TAS_TITLE']; + } + catch ( Exception $e ) { + $taskName = ''; + } + + $currentUser = new stdClass(); + $currentUser->userId = $aAppDel['USR_UID']; + $currentUser->userName = $currentUserName; + $currentUser->taskId = $aAppDel['TAS_UID']; + $currentUser->taskName = $taskName; + $currentUser->delIndex = $aAppDel['DEL_INDEX']; + $currentUser->delThread = $aAppDel['DEL_THREAD']; + $currentUser->delThreadStatus = $aAppDel['DEL_THREAD_STATUS']; + $aCurrentUsers[] = $currentUser; + } + + $res['routing'] = $aCurrentUsers; + return $res; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + + /* + * execute Trigger, executes a ProcessMaker trigger. Note that triggers which are tied to case derivation will executing automatically. + * @param string $userId + * @param string $caseId + * @param string $delIndex + * @return $result will return an object + */ + public function executeTrigger($userId, $caseId, $triggerIndex, $delIndex) { + try { + $oAppDel = new AppDelegation(); + $appdel = $oAppDel->Load($caseId, $delIndex); + + if($userId!=$appdel['USR_UID']) + { + $result = new wsResponse (17, "This case is assigned to another user"); + return $result; + } + + if($appdel['DEL_FINISH_DATE']!=NULL) + { + $result = new wsResponse (18, 'This case delegation is already closed or does not exist'); + return $result; + } + + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(AppDelayPeer::APP_UID); + $oCriteria->addSelectColumn(AppDelayPeer::APP_DEL_INDEX); + $oCriteria->add(AppDelayPeer::APP_TYPE, ''); + $oCriteria->add($oCriteria->getNewCriterion(AppDelayPeer::APP_TYPE, 'PAUSE')->addOr($oCriteria->getNewCriterion(AppDelayPeer::APP_TYPE, 'CANCEL'))); + $oCriteria->addAscendingOrderByColumn(AppDelayPeer::APP_ENABLE_ACTION_DATE); + $oDataset = AppDelayPeer::doSelectRS($oCriteria); + $oDataset ->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset ->next(); + $aRow = $oDataset->getRow(); + + if(is_array($aRow)) + { + if($aRow['APP_DISABLE_ACTION_USER']!=0 && $aRow['APP_DISABLE_ACTION_DATE']!='') + { + $result = new wsResponse (19, "This case is in status ". $aRow['APP_TYPE']); + return $result; + } + } + + //load data + $oCase = new Cases (); + $appFields = $oCase->loadCase( $caseId ); + $appFields['APP_DATA']['APPLICATION'] = $caseId; + + //executeTrigger + $aTriggers = array(); + $c = new Criteria(); + $c ->add(TriggersPeer::TRI_UID, $triggerIndex ); + $rs = TriggersPeer::doSelectRS($c); + $rs ->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $rs ->next(); + $row = $rs->getRow(); + if (is_array($row) && $row['TRI_TYPE'] == 'SCRIPT' ) { + $aTriggers[] = $row; + $oPMScript = new PMScript(); + $oPMScript ->setFields($appFields['APP_DATA']); + $oPMScript ->setScript($row['TRI_WEBBOT']); + $oPMScript ->execute(); + + //Save data - Start + $appFields['APP_DATA'] = $oPMScript->aFields; + //$appFields = $oCase->loadCase( $caseId ); + $oCase->updateCase ( $caseId, $appFields); + //Save data - End + } + else { + $result = new wsResponse (100, "Invalid trigger '$triggerIndex'" ); + return $result; + } + + + $result = new wsResponse (0, 'executed: '. trim( $row['TRI_WEBBOT']) ); + //$result = new wsResponse (0, 'executed: '. print_r( $oPMScript ,1 ) ); + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + + /* + * task Case + * @param string sessionId : The session ID which is obtained when logging in + * @param string caseId : The case ID. The caseList() function can be used to find the ID number for cases + * @return $result returns the current task for a given case. Note that the logged-in user must have privileges to access the task + */ + public function taskCase( $caseId ) { + try { + $result = array(); + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria ->addSelectColumn(AppDelegationPeer::DEL_INDEX); + + $oCriteria ->addAsColumn('TAS_TITLE', 'C1.CON_VALUE' ); + $oCriteria ->addAlias("C1", 'CONTENT'); + $tasTitleConds = array(); + $tasTitleConds[] = array( AppDelegationPeer::TAS_UID , 'C1.CON_ID' ); + $tasTitleConds[] = array( 'C1.CON_CATEGORY' , $del . 'TAS_TITLE' . $del ); + $tasTitleConds[] = array( 'C1.CON_LANG' , $del . SYS_LANG . $del ); + $oCriteria ->addJoinMC($tasTitleConds , Criteria::LEFT_JOIN); + + $oCriteria ->add(AppDelegationPeer::APP_UID, $caseId ); + $oCriteria ->add(AppDelegationPeer::DEL_THREAD_STATUS, 'OPEN'); + $oCriteria ->add(AppDelegationPeer::DEL_FINISH_DATE, null, Criteria::ISNULL ); + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset ->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset ->next(); + + while ($aRow = $oDataset->getRow()) { + $result[] = array ( 'guid' => $aRow['DEL_INDEX'], 'name' => $aRow['TAS_TITLE'] ); + $oDataset->next(); + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + + /* + * process list verified + * @param string sessionId : The session ID which is obtained when logging in + * @param string userId : + * @return $result will return an object + */ + public function processListVerified( $userId ){ + try { + $oCase = new Cases(); + $rows = $oCase->getStartCases($userId); + $result = array(); + + foreach ( $rows as $key=>$val ) { + if ( $key != 0 ) + $result[] = array ( 'guid' => $val['pro_uid'], 'name' => $val['value'] ); + } + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + + /* + * reassign Case + * @param string sessionId : The session ID (which was obtained during login) + * @param string caseId : The case ID (which can be obtained with the caseList() function) + * @param string delIndex : The delegation index number of the case (which can be obtained with the caseList() function). + * @param string userIdSource : The user who is currently assigned the case. + * @param string userIdTarget : The target user who will be newly assigned to the case. + * @return $result will return an object + */ + public function reassignCase( $sessionId, $caseId, $delIndex, $userIdSource, $userIdTarget ){ + try { + if ( $userIdTarget == $userIdSource ) { + $result = new wsResponse (30, "Target and Origin user are the same" ); + return $result; + } + + /******************( 1 )******************/ + $oCriteria = new Criteria('workflow'); + $oCriteria ->add(UsersPeer::USR_STATUS, 'ACTIVE' ); + $oCriteria ->add(UsersPeer::USR_UID, $userIdSource); + $oDataset = UsersPeer::doSelectRS($oCriteria); + $oDataset ->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset ->next(); + $aRow = $oDataset->getRow(); + if(!is_array($aRow)) + { + $result = new wsResponse (31, "Invalid origin user" ); + return $result; + } + + /******************( 2 )******************/ + $oCase = new Cases(); + $rows = $oCase->loadCase($caseId); + if(!is_array($aRow)) + { + $result = new wsResponse (32, "This case is not open" ); + return $result; + } + + /******************( 3 )******************/ + $oCriteria = new Criteria('workflow'); + $aConditions = array(); + // $aConditions[] = array(AppDelegationPeer::USR_UID, TaskUserPeer::USR_UID); + // $aConditions[] = array(AppDelegationPeer::TAS_UID, TaskUserPeer::TAS_UID); + // $oCriteria->addJoinMC($aConditions, Criteria::LEFT_JOIN); + //$oCriteria->addJoin(AppDelegationPeer::USR_UID, TaskUserPeer::USR_UID, Criteria::LEFT_JOIN); + $oCriteria ->add(AppDelegationPeer::APP_UID, $caseId ); + $oCriteria ->add(AppDelegationPeer::USR_UID, $userIdSource ); + $oCriteria ->add(AppDelegationPeer::DEL_INDEX, $delIndex); + $oCriteria ->add(AppDelegationPeer::DEL_FINISH_DATE, null, Criteria::ISNULL); + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset ->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset ->next(); + $aRow = $oDataset->getRow(); + if(!is_array($aRow)) + { + $result = new wsResponse (33, "Invalid Case Delegation index for this user" ); + return $result; + } + $tasUid = $aRow['TAS_UID']; + $derivation = new Derivation (); + $userList = $derivation->getAllUsersFromAnyTask( $tasUid ); + if ( in_array ( $userIdTarget, $userList ) ) { + $result = new wsResponse (34, "The target user does not have rights to execute the task " ); + return $result; + } + + + /******************( 4 )******************/ + $oCriteria = new Criteria('workflow'); + $oCriteria ->add(UsersPeer::USR_STATUS, 'ACTIVE' ); + $oCriteria ->add(UsersPeer::USR_UID, $userIdTarget); + $oDataset = UsersPeer::doSelectRS($oCriteria); + $oDataset ->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset ->next(); + $aRow = $oDataset->getRow(); + if(!is_array($aRow)) + { + $result = new wsResponse (35, "The target user destination is invalid" ); + return $result; + } + + + /******************( 5 )******************/ + $var=$oCase->reassignCase($caseId, $delIndex, $userIdSource, $userIdTarget); + + if(!$var) + { + $result = new wsResponse (36, "The case could not be reassigned." ); + return $result; + } + + $result = new wsResponse (0, 'Command executed successfully'); + + return $result; + } + catch ( Exception $e ) { + $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); + return $result; + } + } + + /* + * get system information + * @param string sessionId : The session ID (which was obtained at login) + * @return $eturns information about the WAMP/LAMP stack, the workspace database, the IP number and version of ProcessMaker, and the IP number and version of web browser of the user + */ + public function systemInformation() { + try { + define ( 'SKIP_RENDER_SYSTEM_INFORMATION', true ); + require_once ( PATH_METHODS . 'login' . PATH_SEP . 'dbInfo.php' ); + $result->status_code = 0; + $result->message = 'Sucessful'; + $result->timestamp = date ( 'Y-m-d H:i:s'); + G::LoadClass("system"); + $result->version = System::getVersion(); + $result->operatingSystem = $redhat; + $result->webServer = getenv('SERVER_SOFTWARE'); + $result->serverName = getenv('SERVER_NAME'); + $result->serverIp = $Fields['IP']; //lookup ($ip); + $result->phpVersion = phpversion(); + $result->databaseVersion = $Fields['DATABASE']; + $result->databaseServerIp = $Fields['DATABASE_SERVER']; + $result->databaseName = $Fields['DATABASE_NAME']; + $result->availableDatabases = $Fields['AVAILABLE_DB']; + $result->userBrowser = $Fields['HTTP_USER_AGENT']; + $result->userIp = $Fields['IP']; + + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + + /* + * import process fromLibrary: downloads and imports a process from the ProcessMaker library + * @param string sessionId : The session ID (which was obtained at login). + * @param string processId : + * @param string version : + * @param string importOption : + * @param string usernameLibrary : The username to obtain access to the ProcessMaker library. + * @param string passwordLibrary : The password to obtain access to the ProcessMaker library. + * @return $eturns will return an object + */ + public function importProcessFromLibrary ( $processId, $version = '', $importOption = '', $usernameLibrary = '', $passwordLibrary = '' ) { + try { + G::LoadClass('processes'); + //$versionReq = $_GET['v']; + //. (isset($_GET['s']) ? '&s=' . $_GET['s'] : '') + $ipaddress = $_SERVER['REMOTE_ADDR']; + $oProcesses = new Processes(); + $oProcesses ->ws_open_public(); + $oProcess = $oProcesses->ws_processGetData($processId); + if ( $oProcess->status_code != 0 ) { + throw ( new Exception ( $oProcess->message ) ); + } + + $privacy = $oProcess->privacy; + + $strSession = ''; + if ( $privacy != 'FREE' ) { + global $sessionId; + $antSession = $sessionId; + $oProcesses->ws_open ($usernameLibrary, $passwordLibrary ); + $strSession = "&s=" . $sessionId; + $sessionId = $antSession; + } + + //downloading the file + $localPath = PATH_DOCUMENT . 'input' . PATH_SEP ; + G::mk_dir($localPath); + $newfilename = G::GenerateUniqueId() . '.pm'; + + $downloadUrl = PML_DOWNLOAD_URL . '?id=' . $processId . $strSession; + + $oProcess = new Processes(); + $oProcess->downloadFile( $downloadUrl, $localPath, $newfilename); + + //getting the ProUid from the file recently downloaded + $oData = $oProcess->getProcessData ( $localPath . $newfilename ); + if ( is_null($oData)) { + throw new Exception('Error the url ' . $downloadUrl . ' is invalid or the process in '. $localPath . $newfilename. ' is invalid'); + } + + $sProUid = $oData->process['PRO_UID']; + $oData->process['PRO_UID_OLD'] = $sProUid; + + //if the process exists, we need to check the $importOption to and re-import if the user wants, + if ( $oProcess->processExists ( $sProUid ) ) { + + //Update the current Process, overwriting all tasks and steps + if ( $importOption == 1 ) { + $oProcess->updateProcessFromData ($oData, $localPath . $newfilename ); + //delete the xmlform cache + if (file_exists(PATH_OUTTRUNK . 'compiled' . PATH_SEP . 'xmlform' . PATH_SEP . $sProUid)) { + $oDirectory = dir(PATH_OUTTRUNK . 'compiled' . PATH_SEP . 'xmlform' . PATH_SEP . $sProUid); + while($sObjectName = $oDirectory->read()) { + if (($sObjectName != '.') && ($sObjectName != '..')) { + unlink(PATH_OUTTRUNK . 'compiled' . PATH_SEP . 'xmlform' . PATH_SEP . $sProUid . PATH_SEP . $sObjectName); + } + } + $oDirectory->close(); + } + $sNewProUid = $sProUid; + } + + //Disable current Process and create a new version of the Process + if ( $importOption == 2 ) { + $oProcess ->disablePreviousProcesses( $sProUid ); + $sNewProUid = $oProcess->getUnusedProcessGUID() ; + $oProcess ->setProcessGuid ( $oData, $sNewProUid ); + $oProcess ->setProcessParent( $oData, $sProUid ); + $oData ->process['PRO_TITLE'] = "New - " . $oData->process['PRO_TITLE'] . ' - ' . date ( 'M d, H:i' ); + $oProcess ->renewAll ( $oData ); + $oProcess ->createProcessFromData ($oData, $localPath . $newfilename ); + } + + //Create a completely new Process without change the current Process + if ( $importOption == 3 ) { + //krumo ($oData); die; + $sNewProUid = $oProcess->getUnusedProcessGUID() ; + $oProcess ->setProcessGuid ( $oData, $sNewProUid ); + $oData ->process['PRO_TITLE'] = "Copy of - " . $oData->process['PRO_TITLE'] . ' - ' . date ( 'M d, H:i' ); + $oProcess ->renewAll ( $oData ); + $oProcess ->createProcessFromData ($oData, $localPath . $newfilename ); + } + + if ( $importOption != 1 && $importOption != 2 && $importOption != 3 ) { + throw new Exception('The process is already in the System and the value for importOption is not specified.'); + } + } + + //finally, creating the process if the process doesn't exist + if ( ! $oProcess->processExists ( $processId ) ) { + $oProcess->createProcessFromData ($oData, $localPath . $newfilename ); + } + + //show the info after the imported process + $oProcess = new Processes(); + $oProcess ->ws_open_public (); + $processData = $oProcess->ws_processGetData ( $processId ); + + $result ->status_code = 0; + $result ->message = 'Command executed successfully'; + $result ->timestamp = date ( 'Y-m-d H:i:s'); + $result ->processId = $processId; + $result ->processTitle = $processData->title; + $result ->category = (isset($processData->category) ? $processData->category : ''); + $result ->version = $processData->version; + + return $result; + } + catch ( Exception $e ) { + $result = new wsResponse (100, $e->getMessage()); + return $result; + } + } + }