From 152ab8be7be0a6ca8f138d01add0bf5dddc0bd76 Mon Sep 17 00:00:00 2001 From: Julio Cesar Laura Date: Tue, 8 Nov 2011 17:37:47 -0400 Subject: [PATCH] Now is possible upgrade the data in the tables, DASHLET is the first --- gulliver/system/class.database_mssql.php | 274 +- gulliver/system/class.database_mysql.php | 204 +- workflow/engine/bin/tasks/cliWorkspaces.php | 12 +- workflow/engine/classes/class.wsBase.php | 3925 +++++++++---------- workflow/engine/classes/class.wsTools.php | 70 +- workflow/engine/data/check.data | 1 + 6 files changed, 2280 insertions(+), 2206 deletions(-) create mode 100644 workflow/engine/data/check.data diff --git a/gulliver/system/class.database_mssql.php b/gulliver/system/class.database_mssql.php index 4e7793118..934a81e6d 100755 --- a/gulliver/system/class.database_mssql.php +++ b/gulliver/system/class.database_mssql.php @@ -1,7 +1,7 @@ sType = $sType; $this->sServer = $sServer; @@ -45,19 +45,19 @@ class database extends database_base { $this->sQuoteCharacterBegin = '['; $this->sQuoteCharacterEnd = ']'; } - - + + public function generateCreateTableSQL($sTable, $aColumns) { $sKeys = ''; $sSQL = 'CREATE TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . '('; - + foreach ($aColumns as $sColumnName => $aParameters) { if ($sColumnName != 'INDEXES') { - + if ( $sColumnName != '' && isset($aParameters['Type']) && $aParameters['Type'] != '' ){ $sSQL .= $this->sQuoteCharacter . $sColumnName . $this->sQuoteCharacter . ' ' . $aParameters['Type']; - + if ( isset($aParameters['Null']) && $aParameters['Null'] == 'YES') { $sSQL .= ' NULL'; } else { @@ -66,11 +66,11 @@ class database extends database_base { if ( isset($aParameters['Key']) && $aParameters['Key'] == 'PRI') { $sKeys .= $this->sQuoteCharacter . $sColumnName . $this->sQuoteCharacter . ','; } - + if ( isset($aParameters['Default']) && $aParameters['Default'] != '' ) { $sSQL .= " DEFAULT '" . $aParameters['Default'] . "'"; } - + $sSQL .= ','; } } @@ -80,22 +80,22 @@ class database extends database_base { $sSQL .= ',PRIMARY KEY(' . substr($sKeys, 0, -1) . ')'; } $sSQL .= ')' . $this->sEndLine; - + return $sSQL; } - + public function generateDropTableSQL($sTable) { return 'DROP TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . $this->sEndLine; } public function generateDropColumnSQL($sTable, $sColumn) { - // SQL Server first should remove the restriction before the Elimination of the field + // SQL Server first should remove the restriction before the Elimination of the field $oConstraint = $this->dropFieldConstraint($sTable, $sColumn); $sSQL = 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' DROP COLUMN ' . $this->sQuoteCharacter . $sColumn . $this->sQuoteCharacter . $this->sEndLine; return $sSQL; } - + public function generateAddColumnSQL($sTable, $sColumn, $aParameters) { if ( isset($aParameters['Type']) && isset($aParameters['Null']) ) { $sDefault = ""; @@ -105,15 +105,15 @@ class database extends database_base { $sType = substr($sType, 0, strpos($sType,'(')); } switch($sType) { - case 'VARCHAR' : - case 'TEXT' : $sDefault = " DEFAULT '' "; + case 'VARCHAR' : + case 'TEXT' : $sDefault = " DEFAULT '' "; break; case 'DATE' : $sDataType = " CHAR(19) "; $sDefault = " DEFAULT '0000-00-00' "; // The date data type to use char (19) break; - case 'INT' : + case 'INT' : case 'FLOAT' : $sDataType = $sType; - $sDefault = " DEFAULT 0 "; + $sDefault = " DEFAULT 0 "; break; } $sSQL = "ALTER TABLE " . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . @@ -124,7 +124,7 @@ class database extends database_base { } else { $sSQL .= " NOT NULL " . $sDefault; - + } } /*if ($aParameters['Key'] == 'PRI') { @@ -182,7 +182,7 @@ class database extends database_base { if ( trim($aParameters['Default'] == '') && $aParameters['Type'] == 'datetime' ) { //do nothing } - else + else $sSQL .= " DEFAULT '" . $aParameters['Default'] . "'"; //} } @@ -193,7 +193,7 @@ class database extends database_base { $sSQL .= $this->sEndLine; return $sSQL; } - + public function generateGetPrimaryKeysSQL($sTable) { try { if ($sTable == '') { @@ -206,7 +206,7 @@ class database extends database_base { } } - /** + /** * Get primary key * @parameter string $sTable * @return string $sPrimaryKey @@ -221,19 +221,19 @@ class database extends database_base { " AND CONSTRAINT_TYPE = 'PRIMARY KEY' " . " AND c.TABLE_NAME = pk.TABLE_NAME " . " AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME "; - $oPrimaryKey = $this->executeQuery($sSQL); + $oPrimaryKey = $this->executeQuery($sSQL); $aPrimaryKey = mssql_fetch_array($oPrimaryKey); mssql_free_result($oPrimaryKey); return $aPrimaryKey[0]; } catch (Exception $oException) { throw $oException; - } + } } - - /** + + /** * Get Field Constraint * @parameter string $sTable - * @parameter string $sField + * @parameter string $sField * @return string $sFieldConstraint */ public function getFieldConstraint($sTable, $sField) @@ -245,21 +245,21 @@ class database extends database_base { " where a.xtype = 'D' " . " and a.parent_obj = (select id from sysobjects where xtype = 'U' and name = '" . trim($sTable) . "') " . " and b.name = '" . trim($sField) . "' "; - - $oFieldConstraint = $this->executeQuery($sSQL); + + $oFieldConstraint = $this->executeQuery($sSQL); $aFieldConstraint = mssql_fetch_array($oFieldConstraint); mssql_free_result($oFieldConstraint); return $aFieldConstraint[0]; } catch (Exception $oException) { throw $oException; - } + } } - - /** + + /** * drop Field Constraint * @parameter string $sTable - * @parameter string $sField + * @parameter string $sField * @return object $oFieldConstraint */ public function dropFieldConstraint($sTable, $sField) @@ -267,11 +267,11 @@ class database extends database_base { try { $sConstraint = $this->getFieldConstraint($sTable, $sField); $sSQL = "ALTER TABLE " . $sTable . " DROP CONSTRAINT " . $sConstraint . $this->sEndLine ; - $oFieldConstraint = $this->executeQuery($sSQL); + $oFieldConstraint = $this->executeQuery($sSQL); return $oFieldConstraint; } catch (Exception $oException) { throw $oException; - } + } } @@ -288,7 +288,7 @@ class database extends database_base { throw $oException; } } - + public function generateAddPrimaryKeysSQL($sTable, $aPrimaryKeys) { try { if ($sTable == '') { @@ -306,7 +306,7 @@ class database extends database_base { throw $oException; } } - + public function generateDropKeySQL($sTable, $sIndexName) { try { if ($sTable == '') { @@ -341,15 +341,15 @@ class database extends database_base { throw $oException; } } - + public function generateShowTablesSQL() { return 'SHOW TABLES' . $this->sEndLine; } - + public function generateShowTablesLikeSQL($sTable) { return "SHOW TABLES LIKE '" . $sTable . "'" . $this->sEndLine; } - + public function generateDescTableSQL($sTable) { try { if ($sTable == '') { @@ -361,14 +361,14 @@ class database extends database_base { throw $oException; } } - + public function generateTableIndexSQL($sTable) { return 'SHOW INDEX FROM ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . " " . $this->sEndLine; //return 'SHOW INDEX FROM ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . " WHERE Key_name <> 'PRIMARY'" . $this->sEndLine; } - public function isConnected() { - if ( !$this->oConnection ) + public function isConnected() { + if ( !$this->oConnection ) return false; return $this->executeQuery( 'USE ' . $this->sDataBase ); } @@ -387,13 +387,13 @@ class database extends database_base { fclose ( $fp ); } } - catch (Exception $oException) { + catch (Exception $oException) { } - } - + } + public function executeQuery($sQuery) { $this->logQuery( $sQuery); - + try { if ($this->oConnection) { @mssql_select_db($this->sDataBase); @@ -404,25 +404,91 @@ class database extends database_base { throw new Exception('invalid connection to database ' . $this->sDataBase ); } } - catch (Exception $oException) { + catch (Exception $oException) { $this->logQuery( $oException->getMessage() ); throw $oException; } } - + public function countResults($oDataset) { return @mssql_num_rows($oDataset); } - + public function getRegistry($oDataset) { return @mssql_fetch_array($oDataset, $this->iFetchType); } - + public function close() { @mssql_close($this->oConnection); } - + public function generateInsertSQL($table, $data) { + $fields = array(); + $values = array(); + foreach ($data as $field) { + $fields[] = $field['field']; + switch ($field['type']) { + case 'text': + case 'date': + $values[] = "'" . addslashes($field['value']) . "'"; + break; + case 'int': + default: + $values[] = addslashes($field['value']); + break; + } + } + $fields = array_map(array($this, 'putQuotes'), $fields); + $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $this->putQuotes($table), implode(', ', $fields), implode(', ', $values)); + return $sql; + } + + public function generateUpdateSQL($table, $keys, $data) { + $fields = array(); + $where = array(); + foreach ($data as $field) { + switch ($field['type']) { + case 'text': + case 'date': + $fields[] = $this->putQuotes($field['field']) . " = '" . addslashes($field['value']) . "'"; + break; + case 'int': + default: + $fields[] = $this->putQuotes($field['field']) . " = " . addslashes($field['value']); + break; + } + if (in_array($field['field'], $keys)) { + $where[] = $fields[count($fields) - 1]; + } + } + $sql = sprintf("UPDATE %s SET %s WHERE %s", $this->putQuotes($table), implode(', ', $fields), implode(', ', $where)); + return $sql; + } + + public function generateDeleteSQL($table, $keys, $data) { + $fields = array(); + $where = array(); + foreach ($data as $field) { + if (in_array($field['field'], $keys)) { + switch ($field['type']) { + case 'text': + case 'date': + $where[] = $this->putQuotes($field['field']) . " = '" . addslashes($field['value']) . "'"; + break; + case 'int': + default: + $where[] = $this->putQuotes($field['field']) . " = " . addslashes($field['value']); + break; + } + } + } + $sql = sprintf("DELETE FROM %s WHERE %s", $this->putQuotes($table), implode(', ', $where)); + return $sql; + } + + private function putQuotes($element) { + return $this->sQuoteCharacterBegin . $element . $this->sQuoteCharacterEnd; + } /*=================================================================================================*/ /** @@ -433,7 +499,7 @@ class database extends database_base { * date 2010-08-04 * * @return string $sConcat - */ + */ function concatString() { $nums = func_num_args(); @@ -449,7 +515,7 @@ class database extends database_base { return $sConcat; } - /* + /* * query functions for class class.case.php * */ @@ -460,9 +526,9 @@ class database extends database_base { * @author Hector Cortez * date 2010-08-04 * - * @return string $sCompare - */ - function getCaseWhen($compareValue, $trueResult, $falseResult) + * @return string $sCompare + */ + function getCaseWhen($compareValue, $trueResult, $falseResult) { $sCompare = " CASE WHEN " . $compareValue . " THEN " . $trueResult . " ELSE " . $falseResult . " END "; return $sCompare; @@ -470,7 +536,7 @@ class database extends database_base { /** * Generates a string equivalent to create table ObjectPermission - * + * * class.case.php * function verifyTable() * @@ -479,28 +545,28 @@ class database extends database_base { function createTableObjectPermission() { $sql = "IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='OBJECT_PERMISSION' AND xtype='U') - CREATE TABLE OBJECT_PERMISSION ( - OP_UID varchar(32) NOT NULL, - PRO_UID varchar(32) NOT NULL, - TAS_UID varchar(32) NOT NULL, - USR_UID varchar(32) NOT NULL, - OP_USER_RELATION int NOT NULL default '1', - OP_TASK_SOURCE varchar(32) NOT NULL, - OP_PARTICIPATE int NOT NULL default '1', - OP_OBJ_TYPE varchar(15) NOT NULL default 'ANY', - OP_OBJ_UID varchar(32) NOT NULL, - OP_ACTION varchar(10) NOT NULL default 'VIEW', + CREATE TABLE OBJECT_PERMISSION ( + OP_UID varchar(32) NOT NULL, + PRO_UID varchar(32) NOT NULL, + TAS_UID varchar(32) NOT NULL, + USR_UID varchar(32) NOT NULL, + OP_USER_RELATION int NOT NULL default '1', + OP_TASK_SOURCE varchar(32) NOT NULL, + OP_PARTICIPATE int NOT NULL default '1', + OP_OBJ_TYPE varchar(15) NOT NULL default 'ANY', + OP_OBJ_UID varchar(32) NOT NULL, + OP_ACTION varchar(10) NOT NULL default 'VIEW', CONSTRAINT PK_PRO_UID PRIMARY KEY CLUSTERED (PRO_UID, TAS_UID,USR_UID, OP_TASK_SOURCE, OP_OBJ_UID) )"; return $sql; - } - - /* + } + + /* * query functions for class class.report.php * */ /** * Generates a string query - * + * * class.report.php * function generatedReport4() * @@ -508,10 +574,10 @@ class database extends database_base { */ function getSelectReport4() { - + $sqlConcat = " U.USR_LASTNAME + ' ' + USR_FIRSTNAME AS [USER] "; $sqlGroupBy = " U.USR_LASTNAME + ' ' + USR_FIRSTNAME "; - + $sql = "SELECT " . $sqlConcat . ", " . " COUNT(*) AS CANTCASES, MIN(AD.DEL_DURATION) AS MIN, @@ -523,20 +589,20 @@ class database extends database_base { LEFT JOIN USERS AS U ON(U.USR_UID = A.APP_INIT_USER) WHERE A.APP_UID<>'' GROUP BY " . $sqlGroupBy; - + return $sql; - + } /** * Generates a string query - * + * * class.report.php * function generatedReport4_filter() * * @return string $sql */ - function getSelectReport4Filter($var) + function getSelectReport4Filter($var) { $sqlConcat = " U.USR_LASTNAME + ' ' + USR_FIRSTNAME AS [USER] "; $sqlGroupBy = " U.USR_LASTNAME + ' ' + USR_FIRSTNAME "; @@ -554,12 +620,12 @@ class database extends database_base { GROUP BY " . $sqlGroupBy; return $sql; - + } - + /** * Generates a string query - * + * * class.report.php * function generatedReport5() * @@ -582,20 +648,20 @@ class database extends database_base { LEFT JOIN USERS AS U ON(U.USR_UID = AD.USR_UID) WHERE AD.APP_UID<>'' AND AD.DEL_FINISH_DATE IS NULL GROUP BY " . $sqlGroupBy; - + return $sql; - + } - + /** * Generates a string query - * + * * class.report.php * function generatedReport5_filter() * * @return string $sql */ - function getSelectReport5Filter($var) + function getSelectReport5Filter($var) { $sqlConcat = " U.USR_LASTNAME + ' ' + USR_FIRSTNAME AS [USER] "; @@ -615,19 +681,19 @@ class database extends database_base { return $sql; } - - /* + + /* * query functions for class class.net.php * */ function getServerVersion($driver, $dbIP, $dbPort, $dbUser, $dbPasswd, $dbSourcename) { - + if(strlen(trim($dbIP))<=0) $dbIP = DB_HOST; if($link = @mssql_connect($dbIP, $dbUser, $dbPasswd)){ @mssql_select_db( DB_NAME, $link ); - $oResult = @mssql_query("select substring(@@version, 21, 6) + ' (' + CAST(SERVERPROPERTY ('productlevel') as varchar(10)) + ') ' + CAST(SERVERPROPERTY('productversion') AS VARCHAR(15)) + ' ' + CAST(SERVERPROPERTY ('edition') AS VARCHAR(25)) as version; ", $link); + $oResult = @mssql_query("select substring(@@version, 21, 6) + ' (' + CAST(SERVERPROPERTY ('productlevel') as varchar(10)) + ') ' + CAST(SERVERPROPERTY('productversion') AS VARCHAR(15)) + ' ' + CAST(SERVERPROPERTY ('edition') AS VARCHAR(25)) as version; ", $link); $aResult = @mssql_fetch_array($oResult); @mssql_free_result($oResult); $v = $aResult[0]; @@ -635,11 +701,11 @@ class database extends database_base { throw new Exception(@mssql_error($link)); } return (isset($v))?$v:'none'; - + } - - - /* + + + /* * query functions for class class.net.php * */ @@ -648,9 +714,9 @@ class database extends database_base { $sql = "IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='" . $sTableName . "' AND xtype='U') " . "DROP TABLE ['" . $sTableName . "']"; return $sql; - } - - + } + + function getTableDescription($sTableName) { $sql = " select column_name as Field, @@ -673,7 +739,7 @@ class database extends database_base { " Order by Ordinal_Position asc "; return $sql; } - + function getFieldNull() { $fieldName = "AsNull"; @@ -696,10 +762,10 @@ class database extends database_base { $oConnection = mssql_connect(DB_HOST, DB_USER, DB_PASS); mssql_select_db(DB_NAME); $oDataset = mssql_query('SELECT COUNT(*) FROM REPORT_TABLE') || ($bExists = false); - + return $bExists; } - + /** * It is part of class.pagedTable.php */ @@ -708,11 +774,11 @@ class database extends database_base { $sql = ""; return $sql; } - + /** * Determining the existence of a table */ - function tableExists ($table, $db) { + function tableExists ($table, $db) { $sql = "SELECT * FROM sysobjects WHERE name='" . $table . "' AND type='u'"; $bExists = true; $oConnection = mssql_connect(DB_HOST, DB_USER, DB_PASS); @@ -720,5 +786,5 @@ class database extends database_base { $oDataset = mssql_query($sql) || ($bExists = false); return $bExists; } - + } \ No newline at end of file diff --git a/gulliver/system/class.database_mysql.php b/gulliver/system/class.database_mysql.php index 0176bb02c..6b3d149fa 100755 --- a/gulliver/system/class.database_mysql.php +++ b/gulliver/system/class.database_mysql.php @@ -1,7 +1,7 @@ sQuoteCharacter . $sTable . $this->sQuoteCharacter . '('; - + foreach ($aColumns as $sColumnName => $aParameters) { if ($sColumnName != 'INDEXES') { - + if ( $sColumnName != '' && isset($aParameters['Type']) && $aParameters['Type'] != '' ){ $sSQL .= $this->sQuoteCharacter . $sColumnName . $this->sQuoteCharacter . ' ' . $aParameters['Type']; - + if ( isset($aParameters['Null']) && $aParameters['Null'] == 'YES') { $sSQL .= ' NULL'; } else { @@ -76,11 +76,11 @@ class database extends database_base { if ( isset($aParameters['Key']) && $aParameters['Key'] == 'PRI') { $sKeys .= $this->sQuoteCharacter . $sColumnName . $this->sQuoteCharacter . ','; } - + if ( isset($aParameters['Default']) && $aParameters['Default'] != '' ) { $sSQL .= " DEFAULT '" . $aParameters['Default'] . "'"; } - + $sSQL .= ','; } } @@ -90,7 +90,7 @@ class database extends database_base { $sSQL .= ',PRIMARY KEY(' . substr($sKeys, 0, -1) . ')'; } $sSQL .= ')' . $this->sEndLine; - + return $sSQL; } @@ -197,7 +197,7 @@ class database extends database_base { if ( trim($aParameters['Default'] == '') && $aParameters['Type'] == 'datetime' ) { //do nothing } - else + else $sSQL .= " DEFAULT '" . $aParameters['Default'] . "'"; //} } @@ -208,7 +208,7 @@ class database extends database_base { $sSQL .= $this->sEndLine; return $sSQL; } - + /** * Generate and get the primary key in a sentence * @param $sTable table name @@ -295,7 +295,7 @@ class database extends database_base { * @param $aKeys array of keys * @return sql sentence */ - + public function generateAddKeysSQL($sTable, $indexName, $aKeys) { try { $indexType = 'INDEX'; @@ -363,8 +363,8 @@ class database extends database_base { * execute a sentence to check if there is connection * @return void */ - public function isConnected() { - if ( !$this->oConnection ) + public function isConnected() { + if ( !$this->oConnection ) return false; return $this->executeQuery( 'USE ' . $this->sDataBase ); } @@ -394,9 +394,9 @@ class database extends database_base { } } } - catch (Exception $oException) { + catch (Exception $oException) { } - } + } /** * execute a sql query @@ -405,7 +405,7 @@ class database extends database_base { */ public function executeQuery($sQuery) { $this->logQuery( $sQuery); - + try { if ($this->oConnection) { @mysql_select_db($this->sDataBase); @@ -416,7 +416,7 @@ class database extends database_base { throw new Exception('invalid connection to database ' . $this->sDataBase ); } } - catch (Exception $oException) { + catch (Exception $oException) { $this->logQuery( $oException->getMessage() ); throw $oException; } @@ -447,8 +447,96 @@ class database extends database_base { public function close() { @mysql_close($this->oConnection); } - - + + public function generateInsertSQL($table, $data) { + $fields = array(); + $values = array(); + foreach ($data as $field) { + $fields[] = $field['field']; + switch ($field['type']) { + case 'text': + case 'date': + $values[] = "'" . mysql_real_escape_string($field['value']) . "'"; + break; + case 'int': + default: + $values[] = mysql_real_escape_string($field['value']); + break; + } + } + $fields = array_map(array($this, 'putQuotes'), $fields); + $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $this->putQuotes($table), implode(', ', $fields), implode(', ', $values)); + return $sql; + } + + public function generateUpdateSQL($table, $keys, $data) { + $fields = array(); + $where = array(); + foreach ($data as $field) { + switch ($field['type']) { + case 'text': + case 'date': + $fields[] = $this->putQuotes($field['field']) . " = '" . mysql_real_escape_string($field['value']) . "'"; + break; + case 'int': + default: + $fields[] = $this->putQuotes($field['field']) . " = " . mysql_real_escape_string($field['value']); + break; + } + if (in_array($field['field'], $keys)) { + $where[] = $fields[count($fields) - 1]; + } + } + $sql = sprintf("UPDATE %s SET %s WHERE %s", $this->putQuotes($table), implode(', ', $fields), implode(', ', $where)); + return $sql; + } + + public function generateDeleteSQL($table, $keys, $data) { + $fields = array(); + $where = array(); + foreach ($data as $field) { + if (in_array($field['field'], $keys)) { + switch ($field['type']) { + case 'text': + case 'date': + $where[] = $this->putQuotes($field['field']) . " = '" . mysql_real_escape_string($field['value']) . "'"; + break; + case 'int': + default: + $where[] = $this->putQuotes($field['field']) . " = " . mysql_real_escape_string($field['value']); + break; + } + } + } + $sql = sprintf("DELETE FROM %s WHERE %s", $this->putQuotes($table), implode(', ', $where)); + return $sql; + } + + public function generateSelectSQL($table, $keys, $data) { + $fields = array(); + $where = array(); + foreach ($data as $field) { + if (in_array($field['field'], $keys)) { + switch ($field['type']) { + case 'text': + case 'date': + $where[] = $this->putQuotes($field['field']) . " = '" . mysql_real_escape_string($field['value']) . "'"; + break; + case 'int': + default: + $where[] = $this->putQuotes($field['field']) . " = " . mysql_real_escape_string($field['value']); + break; + } + } + } + $sql = sprintf("SELECT * FROM %s WHERE %s", $this->putQuotes($table), implode(', ', $where)); + return $sql; + } + + private function putQuotes($element) { + return $this->sQuoteCharacter . $element . $this->sQuoteCharacter; + } + /*=================================================================================================*/ /** * concatString @@ -458,7 +546,7 @@ class database extends database_base { * date 2010-08-04 * * @return string $sConcat - */ + */ function concatString() { $nums = func_num_args(); @@ -475,10 +563,10 @@ class database extends database_base { $sConcat .= ")"; return $sConcat; - + } - /* + /* * query functions for class class.case.php * */ @@ -489,18 +577,18 @@ class database extends database_base { * author Hector Cortez * date 2010-08-04 * - * @return string $sCompare - */ - function getCaseWhen($compareValue, $trueResult, $falseResult) + * @return string $sCompare + */ + function getCaseWhen($compareValue, $trueResult, $falseResult) { $sCompare = "IF(" . $compareValue . ", " . $trueResult . ", " . $falseResult . ") "; return $sCompare; - + } /** * Generates a string equivalent to create table ObjectPermission - * + * * class.case.php * function verifyTable() * @@ -522,15 +610,15 @@ class database extends database_base { KEY `PRO_UID` (`PRO_UID`,`TAS_UID`,`USR_UID`,`OP_TASK_SOURCE`,`OP_OBJ_UID`) )ENGINE=MyISAM DEFAULT CHARSET=latin1;"; return $sql; - } - - /* + } + + /* * query functions for class class.report.php * */ /** * Generates a string query - * + * * class.report.php * function generatedReport4() * @@ -538,10 +626,10 @@ class database extends database_base { */ function getSelectReport4() { - + $sqlConcat = " CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER "; $sqlGroupBy = " USER "; - + $sql = "SELECT " . $sqlConcat . ", " . " COUNT(*) AS CANTCASES, MIN(AD.DEL_DURATION) AS MIN, @@ -553,20 +641,20 @@ class database extends database_base { LEFT JOIN USERS AS U ON(U.USR_UID = A.APP_INIT_USER) WHERE A.APP_UID<>'' GROUP BY " . $sqlGroupBy; - + return $sql; - + } /** * Generates a string query - * + * * class.report.php * function generatedReport4_filter() * * @return string $sql */ - function getSelectReport4Filter($var) + function getSelectReport4Filter($var) { $sqlConcat = " CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER "; $sqlGroupBy = " USER "; @@ -584,12 +672,12 @@ class database extends database_base { GROUP BY " . $sqlGroupBy; return $sql; - + } - + /** * Generates a string query - * + * * class.report.php * function generatedReport5() * @@ -611,20 +699,20 @@ class database extends database_base { LEFT JOIN USERS AS U ON(U.USR_UID = AD.USR_UID) WHERE AD.APP_UID<>'' AND AD.DEL_FINISH_DATE IS NULL GROUP BY " . $sqlGroupBy; - + return $sql; - + } - + /** * Generates a string query - * + * * class.report.php * function generatedReport5_filter() * * @return string $sql */ - function getSelectReport5Filter($var) + function getSelectReport5Filter($var) { $sqlConcat = " CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER "; @@ -644,25 +732,25 @@ class database extends database_base { return $sql; } - - /* + + /* * query functions for class class.net.php * */ function getServerVersion($driver, $dbIP, $dbPort, $dbUser, $dbPasswd, $dbSourcename) { - + if($link = @mysql_connect($dbIP, $dbUser, $dbPasswd)){ $v = @mysql_get_server_info(); } else { throw new Exception(@mysql_error($link)); } return (isset($v))?$v:'none'; - + } - - - /* + + + /* * query functions for class class.net.php, class.reportTables.php * */ @@ -670,15 +758,15 @@ class database extends database_base { { $sql = 'DROP TABLE IF EXISTS `' . $sTableName . '`'; return $sql; - } - - + } + + function getTableDescription($sTableName) { $sql = "DESC ".$sTableName; return $sql; } - + function getFieldNull() { $fieldName = "Null"; @@ -701,7 +789,7 @@ class database extends database_base { $oConnection = mysql_connect(DB_HOST, DB_USER, DB_PASS); mysql_select_db(DB_NAME); $oDataset = mysql_query('SELECT COUNT(*) FROM REPORT_TABLE') || ($bExists = false); - + return $bExists; } @@ -713,7 +801,7 @@ class database extends database_base { $sql = ' LIMIT '.(($nCurrentPage-1)*$nRowsPerPage).', '.$nRowsPerPage; return $sql; } - + /** * Determining the existence of a table */ diff --git a/workflow/engine/bin/tasks/cliWorkspaces.php b/workflow/engine/bin/tasks/cliWorkspaces.php index 0fefcdc7e..360ced258 100755 --- a/workflow/engine/bin/tasks/cliWorkspaces.php +++ b/workflow/engine/bin/tasks/cliWorkspaces.php @@ -129,7 +129,7 @@ CLI::taskDescription(<< Schema fixed\n"; + echo "-> Schema fixed\n"; } } else { echo "> OK\n"; @@ -276,11 +276,11 @@ function delete_app_from_table($con, $tableName, $appUid, $col="APP_UID") { function run_drafts_clean($args, $opts) { echo "Cleaning drafts\n"; - + if (count($args) < 1) throw new Exception ("Please specify a workspace name"); $workspace = $args[0]; - + if (!file_exists(PATH_DB . $workspace . '/db.php')) { throw new Exception('Could not find workspace ' . $workspace); } @@ -388,7 +388,7 @@ function run_workspace_backup($args, $opts) { CLI::logging("\n"); $workspace->printMetadata(false); } - + } function run_workspace_restore($args, $opts) { diff --git a/workflow/engine/classes/class.wsBase.php b/workflow/engine/classes/class.wsBase.php index 69bb9bffb..32f4de1dc 100755 --- a/workflow/engine/classes/class.wsBase.php +++ b/workflow/engine/classes/class.wsBase.php @@ -1,10 +1,9 @@ - * Last Modify comment(26.06.2008): the session expired verification was removed from here to soap class - * @package workflow.engine.classes +/** + * @method + * + * Returns the current date formated in the format "yyyy-mm-dd", with leading zeros in the + * month and day if less than 10. This function is equivalent to PHP's date("Y-m-d"). + * + * @name getCurrentDate + * @label Get Current Date + * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#getCurrentDate.28.29 + * + * @return date | $date | Current Date (Y-m-d) | It returns the current date as a string value. + * */ +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(); -class wsBase + $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 { - - 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: ''; + G::LoadClass('wsBase'); + $ws = new wsBase (); + $result = $ws->taskCase($caseId); + $rows = Array(); + $i = 1; + if(isset ($result)) { + foreach ( $result as $item) { + $rows[$i++] = $item; } } - - /* - * 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; - - 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; + 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; } } - - /* - * 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(); - - 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; + 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; } } - - /* - * get all roles, to see all roles - * @param none - * @return $result will return an object - */ - public function roleList( ) { - try { - $result = array(); + 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) { - $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; - } + 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'); - /* - * 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; +// 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']; } - catch ( Exception $e ) { - $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); - return $result; + }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; - /* - * 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(); + $pathOutput = PATH_DOCUMENT . $sApplication . PATH_SEP . 'outdocs'. PATH_SEP ;//G::pr($sFilename);die; + G::mk_dir ( $pathOutput ); - 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']; + $aProperties = array(); - //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]; + 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'; - $node['users'] = $count; - $result[] = $node; - $oDataset->next(); - } - return $result; - } - catch ( Exception $e ) { - $result[] = array ( 'guid' => $e->getMessage(), 'name' => $e->getMessage() ); - return $result; - } - } + $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' ); + } - /* - * 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); + $documentData = new uploadDocumentData ( + $sApplication, + $sUserLogged, + $pathOutput . $sFilename . '.doc', + $sFilename. '.doc', + $sDocUID, + $oAppDocument->getDocVersion() + ); - $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; - } - } - 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; + $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' ); } - if ( $appFields == null ) { - $Fields = $oldFields['APP_DATA']; - } else { - $Fields = $appFields; + 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' ); } - $templateContents = file_get_contents ( $fileTemplate ); + break; + case "DOC": + $documentData = new uploadDocumentData ( + $sApplication, + $sUserLogged, + $pathOutput . $sFilename . '.doc', + $sFilename. '.doc', + $sDocUID, + $oAppDocument->getDocVersion() + ); - //$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); - } - } - } - $templateContents = str_replace('@>' . $sGridName . $sStringToRepeat . '@<' . $sGridName, $sAux, $templateContents); - } + $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' ); } - - $sBody = G::replaceDataField( $templateContents, $Fields); - - if ($sFrom != '') { - $sFrom = $sFrom . ' <' . $aSetup['MESS_ACCOUNT'] . '>'; - } - else { - $sFrom = $aSetup['MESS_ACCOUNT']; - } - - $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(); - - 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; - } - } - - /* - * 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; - } - - $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']; - - //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; + break; } } - /* - * 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; - } - } - +} +/** + * @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') + */ + + /* + * 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); + } + } + + 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; + } + + switch($sType) { + case 'ext': + if( G::emailAddress($sID) ) { + array_push($aRecipient, $sID); + } + 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); + } + } + } + } else { + $oUserRow = UsersPeer::retrieveByPK($sID); + $sID = $oUserRow->getUsrEmail(); + if( G::emailAddress($sID) ) { + array_push($aRecipient, $sID); + } + } + + break; + + 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']); + } + } + + break; + + 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; + } + } + + switch($retType){ + case 'array': + return $aRecipient; + + case 'string': + return implode(',', $aRecipient); + + default: + return $aRecipient; + } } diff --git a/workflow/engine/classes/class.wsTools.php b/workflow/engine/classes/class.wsTools.php index bfad34e0f..cde4b6249 100755 --- a/workflow/engine/classes/class.wsTools.php +++ b/workflow/engine/classes/class.wsTools.php @@ -2,13 +2,13 @@ /** * Utility functions to manage a workspace. * - * @author Alexandre Rosenfeld + * @author Alexandre Rosenfeld */ G::LoadSystem('dbMaintenance'); G::LoadClass("cli"); -/** +/** * class workspaceTools * @package workflow.engine.classes */ @@ -129,7 +129,7 @@ class workspaceTools { * Reset the database information to that of a newly created workspace. * * This assumes this workspace already has a db.php file, which will be changed - * to contain the new information. + * to contain the new information. * This function will reset the database hostname to the system database. * If reseting database names, it will also use the the prefixes rp_, * rb_ and wf_, with the workspace name as database names. @@ -445,7 +445,7 @@ class workspaceTools { $oCriteria = new Criteria(); $oCriteria->add(ConfigurationPeer::CFG_UID,'casesList'); ConfigurationPeer::doDelete($oCriteria); - // end of reset + // end of reset } /** @@ -470,6 +470,7 @@ class workspaceTools { public function upgradeDatabase($checkOnly = false) { $systemSchema = System::getSystemSchema(); $this->upgradeSchema($systemSchema); + $this->upgradeData(); return true; } @@ -499,7 +500,7 @@ class workspaceTools { if ($changed) { return $changes; } else { - CLI::logging("-> Nothing to change\n"); + CLI::logging("-> Nothing to change in the data base structure\n"); return $changed; } } @@ -560,6 +561,51 @@ class workspaceTools { return true; } + public function upgradeData() { + if (file_exists(PATH_CORE . 'data' . PATH_SEP . 'check.data')) { + $checkData = @unserialize(file_get_contents(PATH_CORE . 'data' . PATH_SEP . 'check.data')); + if (is_array($checkData)) { + foreach ($checkData as $checkThis) { + $this->updateThisRegistry($checkThis); + } + } + } + } + + public function updateThisRegistry($data) { + $dataBase = $this->getDatabase(); + $sql = ''; + switch ($data['action']) { + case 1: + $sql = $dataBase->generateInsertSQL($data['table'], $data['data']); + $message = "-> Row added in {$data['table']}\n"; + break; + case 2: + $sql = $dataBase->generateUpdateSQL($data['table'], $data['keys'], $data['data']); + $message = "-> Row updated in {$data['table']}\n"; + break; + case 3: + $sql = $dataBase->generateDeleteSQL($data['table'], $data['keys'], $data['data']); + $message = "-> Row deleted in {$data['table']}\n"; + break; + case 4: + $sql = $dataBase->generateSelectSQL($data['table'], $data['keys'], $data['data']); + $result = $dataBase->executeQuery($sql); + if (!$result) { + $sql = $dataBase->generateInsertSQL($data['table'], $data['data']); + $message = "-> Row updated in {$data['table']}\n"; + } + else { + $sql = ''; + } + break; + } + if ($sql != '') { + $dataBase->executeQuery($sql); + CLI::logging($message); + } + } + /** * Get metadata from this workspace * @@ -607,9 +653,9 @@ class workspaceTools { return $Fields; } - /** + /** * Print the system information gathered from getSysInfo - */ + */ public static function printSysInfo() { $fields = System::getSysInfo(); @@ -776,7 +822,7 @@ class workspaceTools { CLI::logging("Copying database to backup...\n"); $this->addToBackup($backup, $tempDirectory, $tempDirectory); CLI::logging("Copying files to backup...\n"); - + $this->addToBackup($backup, $this->path, $this->path, "{$this->name}.files"); //Remove leftovers. G::rm_dir($tempDirectory); @@ -821,7 +867,7 @@ class workspaceTools { //TODO: Move to class.dbMaintenance.php /** * executes a mysql script - * + * * This function supports scripts with -- comments in the beginning of a line * and multi-line statements. * It does not support other forms of comments (such as /*... or {{...}}). @@ -879,7 +925,7 @@ class workspaceTools { $metafiles[] = "$tempDirectory/$filename"; } } - + CLI::logging("Found " . count($metafiles) . " workspace(s) in backup\n"); foreach ($metafiles as $metafile) { @@ -995,7 +1041,7 @@ class workspaceTools { throw new Exception('Could not connect to system database: ' . mysql_error()); $newDBNames = $workspace->resetDBInfo($dbHost, $createWorkspace); - + foreach ($metadata->databases as $db) { $dbName = $newDBNames[$db->name]; CLI::logging("+> Restoring database {$db->name} to $dbName\n"); @@ -1003,7 +1049,7 @@ class workspaceTools { $workspace->createDBUser($dbName, $db->pass, "localhost", $dbName); $workspace->createDBUser($dbName, $db->pass, "%", $dbName); } - + $workspace->upgradeCacheView(false); mysql_close($link); diff --git a/workflow/engine/data/check.data b/workflow/engine/data/check.data new file mode 100644 index 000000000..83697e4e1 --- /dev/null +++ b/workflow/engine/data/check.data @@ -0,0 +1 @@ +a:1:{i:0;a:5:{s:2:"db";s:2:"wf";s:5:"table";s:7:"DASHLET";s:4:"keys";a:1:{i:0;s:7:"DAS_UID";}s:4:"data";a:8:{i:0;a:3:{s:5:"field";s:7:"DAS_UID";s:4:"type";s:4:"text";s:5:"value";s:32:"00000000000000000000000000000001";}i:1;a:3:{s:5:"field";s:9:"DAS_CLASS";s:4:"type";s:4:"text";s:5:"value";s:22:"dashletOpenVSCompleted";}i:2;a:3:{s:5:"field";s:9:"DAS_TITLE";s:4:"type";s:4:"text";s:5:"value";s:29:"Open Cases VS Completed Cases";}i:3;a:3:{s:5:"field";s:15:"DAS_DESCRIPTION";s:4:"type";s:4:"text";s:5:"value";s:29:"Open Cases VS Completed Cases";}i:4;a:3:{s:5:"field";s:11:"DAS_VERSION";s:4:"type";s:4:"text";s:5:"value";s:3:"1.0";}i:5;a:3:{s:5:"field";s:15:"DAS_CREATE_DATE";s:4:"type";s:4:"date";s:5:"value";s:20:" 2011-10-28 00:00:00";}i:6;a:3:{s:5:"field";s:15:"DAS_UPDATE_DATE";s:4:"type";s:4:"date";s:5:"value";s:20:" 2011-10-28 00:00:00";}i:7;a:3:{s:5:"field";s:10:"DAS_STATUS";s:4:"type";s:3:"int";s:5:"value";i:1;}}s:6:"action";i:4;}} \ No newline at end of file