From ed3223eab9da0b2a57b8bb0ff66487ee8202cee1 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:18:09 -0400 Subject: [PATCH 01/18] CODE STYLE class.replacementLogo.php --- .../engine/classes/class.replacementLogo.php | 157 +++++++++--------- 1 file changed, 82 insertions(+), 75 deletions(-) diff --git a/workflow/engine/classes/class.replacementLogo.php b/workflow/engine/classes/class.replacementLogo.php index ffd1ec036..fae2c5bf0 100755 --- a/workflow/engine/classes/class.replacementLogo.php +++ b/workflow/engine/classes/class.replacementLogo.php @@ -1,6 +1,8 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ /** + * * @package workflow.engine.classes */ -class replacementLogo { - - //var $dir=''; - /** - * This function is the constructor of the replacementLogo class - * param - * @return void - */ - function replacementLogo() { - - } - - /** - * This function upload a file - * - * - * @name upLoadFile - * - * @param string $dirUpload - * @param string $namefile - * @param string $typefile - * @param string $errorfile - * @param string $tpnfile - * @param string $formf - * @return string - */ - function upLoadFile($dirUpload, $namefile, $typefile, $errorfile, $tpnfile, $formf) { - - //we are cheking the extension for file - $aExt = explode ( ".", $namefile ); - $infoupload = ''; //|| ($formf["type"]['uploadfile'] == "application/octet-stream")image/png - if (($typefile == "image/jpeg") || ($typefile == "image/png")) { - if ($errorfile > 0) { - $infoupload = "Return Code: " . $errorfile . "
"; - } else { - if (file_exists ( $dirUpload . $namefile )) { - $infoupload = $namefile . " already exist. "; - } else { - move_uploaded_file ( $tpnfile, $dirUpload . $namefile ); - $infoupload = "Stored in: " . $dirUpload . $namefile; - } - } - } else { - $infoupload = "- " . $typefile . " Invalid file your file should be jpeg"; +class replacementLogo +{ + + //var $dir=''; + /** + * This function is the constructor of the replacementLogo class + * param + * + * @return void + */ + public function replacementLogo () + { + } - return $infoupload; - } - - /** - * This function gets the logos' names - * - * - * @name getNameLogo - * - * param - * @return array - */ - function getNameLogo($usrUid) { - - require_once 'classes/model/Configuration.php'; - $oCriteria = new Criteria ( 'workflow' ); - $oCriteria->addSelectColumn ( ConfigurationPeer::CFG_VALUE ); - $oCriteria->add ( ConfigurationPeer::CFG_UID, 'USER_LOGO_REPLACEMENT' ); - $oDataset = ConfigurationPeer::doSelectRS ( $oCriteria ); - $oDataset->next (); - $aRow = $oDataset->getRow (); - if (isset ( $aRow [0] )) - $ainfoLogo = @unserialize ( $aRow [0] ); - else - $ainfoLogo = NULL; - - return ($ainfoLogo); - } -} // end class + /** + * This function upload a file + * + * + * @name upLoadFile + * + * @param string $dirUpload + * @param string $namefile + * @param string $typefile + * @param string $errorfile + * @param string $tpnfile + * @param string $formf + * @return string + */ + public function upLoadFile ($dirUpload, $namefile, $typefile, $errorfile, $tpnfile, $formf) + { + + //we are cheking the extension for file + $aExt = explode( ".", $namefile ); + $infoupload = ''; //|| ($formf["type"]['uploadfile'] == "application/octet-stream")image/png + if (($typefile == "image/jpeg") || ($typefile == "image/png")) { + if ($errorfile > 0) { + $infoupload = "Return Code: " . $errorfile . "
"; + } else { + if (file_exists( $dirUpload . $namefile )) { + $infoupload = $namefile . " already exist. "; + } else { + move_uploaded_file( $tpnfile, $dirUpload . $namefile ); + $infoupload = "Stored in: " . $dirUpload . $namefile; + } + } + } else { + $infoupload = "- " . $typefile . " Invalid file your file should be jpeg"; + } + return $infoupload; + } + + /** + * This function gets the logos' names + * + * + * @name getNameLogo + * + * param + * @return array + */ + public function getNameLogo ($usrUid) + { + + require_once 'classes/model/Configuration.php'; + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( ConfigurationPeer::CFG_VALUE ); + $oCriteria->add( ConfigurationPeer::CFG_UID, 'USER_LOGO_REPLACEMENT' ); + $oDataset = ConfigurationPeer::doSelectRS( $oCriteria ); + $oDataset->next(); + $aRow = $oDataset->getRow(); + if (isset( $aRow[0] )) { + $ainfoLogo = @unserialize( $aRow[0] ); + } else { + $ainfoLogo = null; + } + return ($ainfoLogo); + } +} From 407627ad781f30cabb26277524f7a917fd5c1759 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:19:43 -0400 Subject: [PATCH 02/18] CODE STYLE class.report.php --- workflow/engine/classes/class.report.php | 1568 ++++++++++------------ 1 file changed, 733 insertions(+), 835 deletions(-) diff --git a/workflow/engine/classes/class.report.php b/workflow/engine/classes/class.report.php index 39ce53d59..e17fc0063 100755 --- a/workflow/engine/classes/class.report.php +++ b/workflow/engine/classes/class.report.php @@ -1,6 +1,8 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. * */ - /** * Report - Report class + * * @package workflow.engine.ProcessMaker * @author Everth S. Berrios Morales * @copyright 2008 COLOSA */ -class Report { - - /** - * This function does a sql statment to a report - * - * - * @name generatedReport1 - * - * param - * @return object - */ - function generatedReport1() - { - $this->reportsPatch(); +class Report +{ - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addAsColumn("MIN", "MIN(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("MAX", "MAX(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("TOTALDUR", "SUM(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("PROMEDIO", "AVG(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn('PRO_TITLE', 'C1.CON_VALUE' ); - $oCriteria->addAlias("C1", 'CONTENT'); - $proTitleConds = array(); - $proTitleConds[] = array( AppDelegationPeer::PRO_UID , 'C1.CON_ID' ); - $proTitleConds[] = array( 'C1.CON_CATEGORY' , $del . 'PRO_TITLE' . $del ); - $proTitleConds[] = array( 'C1.CON_LANG' , $del . SYS_LANG . $del ); - $oCriteria->addJoinMC($proTitleConds , Criteria::LEFT_JOIN); - $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addGroupByColumn('C1.CON_VALUE'); - - $oDataset = AppDelegationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - $aProcess[] = array('PRO_UID' => 'char', - 'PRO_TITLE' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'TOTALDUR' => 'float', - 'PROMEDIO' => 'float'); - while ($aRow = $oDataset->getRow()) + /** + * This function does a sql statment to a report + * + * + * @name generatedReport1 + * + * param + * @return object + */ + public function generatedReport1 () { - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(ApplicationPeer::PRO_UID); - $oCriteria->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); + $this->reportsPatch(); - $aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], - 'PRO_TITLE' => $aRow['PRO_TITLE'], - 'CANTCASES' => ApplicationPeer::doCount($oCriteria), - 'MIN' => number_format($aRow['MIN'], 2), - 'MAX' => number_format($aRow['MAX'], 2), - 'TOTALDUR' => number_format($aRow['TOTALDUR'], 2), - 'PROMEDIO' => number_format($aRow['PROMEDIO'], 2)); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( 'PRO_TITLE', 'C1.CON_VALUE' ); + $oCriteria->addAlias( "C1", 'CONTENT' ); + $proTitleConds = array (); + $proTitleConds[] = array (AppDelegationPeer::PRO_UID,'C1.CON_ID' + ); + $proTitleConds[] = array ('C1.CON_CATEGORY',$del . 'PRO_TITLE' . $del + ); + $proTitleConds[] = array ('C1.CON_LANG',$del . SYS_LANG . $del + ); + $oCriteria->addJoinMC( $proTitleConds, Criteria::LEFT_JOIN ); + $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addGroupByColumn( 'C1.CON_VALUE' ); + + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); - } + $aProcess[] = array ('PRO_UID' => 'char','PRO_TITLE' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' + ); + while ($aRow = $oDataset->getRow()) { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( ApplicationPeer::PRO_UID ); + $oCriteria->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); + $aProcess[] = array ('PRO_UID' => $aRow['PRO_UID'],'PRO_TITLE' => $aRow['PRO_TITLE'],'CANTCASES' => ApplicationPeer::doCount( $oCriteria ),'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'TOTALDUR' => number_format( $aRow['TOTALDUR'], 2 ),'PROMEDIO' => number_format( $aRow['PROMEDIO'], 2 ) + ); + $oDataset->next(); + } - return $oCriteria; - } + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); - /** - * This function does a sql statment to a report wiht a condition - * or maybe when you're looking for some specials cases - * - * @name generatedReport1_filter - * - * @param string $from - * @param string $to - * @param string $startedby - * @return object - */ - function generatedReport1_filter($from, $to, $startedby) - { - $this->reportsPatch(); + return $oCriteria; + } - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn(UsersPeer::USR_UID); - $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addAsColumn("MIN", "MIN(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("MAX", "MAX(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("TOTALDUR", "SUM(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("PROMEDIO", "AVG(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn('PRO_TITLE', 'C1.CON_VALUE' ); - $oCriteria->addAlias("C1", 'CONTENT'); - $proTitleConds = array(); - $proTitleConds[] = array( AppDelegationPeer::PRO_UID , 'C1.CON_ID' ); - $proTitleConds[] = array( 'C1.CON_CATEGORY' , $del . 'PRO_TITLE' . $del ); - $proTitleConds[] = array( 'C1.CON_LANG' , $del . SYS_LANG . $del ); - $oCriteria->addJoinMC($proTitleConds , Criteria::LEFT_JOIN); - $oCriteria->addJoin(AppDelegationPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN); - //$oCriteria->add(AppDelegationPeer::DEL_DURATION, $from, Criteria::GREATER_EQUAL); - //$oCriteria->add(AppDelegationPeer::DEL_DURATION, $to, Criteria::LESS_EQUAL); - //$aAux1 = explode('-', $from); date('Y-m-d H:i:s', mktime(0, 0, 0, $aAux1[1], $aAux1[2], $aAux1[0])) - $oCriteria->add($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $from.' 00:00:00', Criteria::GREATER_EQUAL)->addAnd($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $to.' 23:59:59', Criteria::LESS_EQUAL))); + /** + * This function does a sql statment to a report wiht a condition + * or maybe when you're looking for some specials cases + * + * @name generatedReport1_filter + * + * @param string $from + * @param string $to + * @param string $startedby + * @return object + */ + public function generatedReport1_filter ($from, $to, $startedby) + { + $this->reportsPatch(); - if($startedby!='') $oCriteria->add(ApplicationPeer::APP_INIT_USER, $startedby); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn( UsersPeer::USR_UID ); + $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( 'PRO_TITLE', 'C1.CON_VALUE' ); + $oCriteria->addAlias( "C1", 'CONTENT' ); + $proTitleConds = array (); + $proTitleConds[] = array (AppDelegationPeer::PRO_UID,'C1.CON_ID' + ); + $proTitleConds[] = array ('C1.CON_CATEGORY',$del . 'PRO_TITLE' . $del + ); + $proTitleConds[] = array ('C1.CON_LANG',$del . SYS_LANG . $del + ); + $oCriteria->addJoinMC( $proTitleConds, Criteria::LEFT_JOIN ); + $oCriteria->addJoin( AppDelegationPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN ); + //$oCriteria->add(AppDelegationPeer::DEL_DURATION, $from, Criteria::GREATER_EQUAL); + //$oCriteria->add(AppDelegationPeer::DEL_DURATION, $to, Criteria::LESS_EQUAL); + //$aAux1 = explode('-', $from); date('Y-m-d H:i:s', mktime(0, 0, 0, $aAux1[1], $aAux1[2], $aAux1[0])) + $oCriteria->add( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $from . ' 00:00:00', Criteria::GREATER_EQUAL )->addAnd( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $to . ' 23:59:59', Criteria::LESS_EQUAL ) ) ); - $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addGroupByColumn('C1.CON_VALUE'); + if ($startedby != '') + $oCriteria->add( ApplicationPeer::APP_INIT_USER, $startedby ); - $oDataset = AppDelegationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); + $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addGroupByColumn( 'C1.CON_VALUE' ); - $aProcess[] = array('PRO_UID' => 'char', - 'PRO_TITLE' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'TOTALDUR' => 'float', - 'PROMEDIO' => 'float'); - while ($aRow = $oDataset->getRow()) { - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(ApplicationPeer::PRO_UID); - $oCriteria->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); - if($startedby!='') $oCriteria->add(ApplicationPeer::APP_INIT_USER, $startedby); - - $aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], - 'PRO_TITLE' => $aRow['PRO_TITLE'], - 'CANTCASES' => ApplicationPeer::doCount($oCriteria), - 'MIN' => number_format($aRow['MIN'],2), - 'MAX' => number_format($aRow['MAX'],2), - 'TOTALDUR' => number_format($aRow['TOTALDUR'],2), - 'PROMEDIO' => number_format($aRow['PROMEDIO'],2)); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); - } - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); + $aProcess[] = array ('PRO_UID' => 'char','PRO_TITLE' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' + ); + while ($aRow = $oDataset->getRow()) { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( ApplicationPeer::PRO_UID ); + $oCriteria->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); + if ($startedby != '') + $oCriteria->add( ApplicationPeer::APP_INIT_USER, $startedby ); - return $oCriteria; - } + $aProcess[] = array ('PRO_UID' => $aRow['PRO_UID'],'PRO_TITLE' => $aRow['PRO_TITLE'],'CANTCASES' => ApplicationPeer::doCount( $oCriteria ),'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'TOTALDUR' => number_format( $aRow['TOTALDUR'], 2 ),'PROMEDIO' => number_format( $aRow['PROMEDIO'], 2 ) + ); + $oDataset->next(); + } - /** - * This function gets info about a report - * - * - * @name descriptionReport1 - * - * @param string $PRO_UID - * @return object - */ - function descriptionReport1($PRO_UID) - { $this->reportsPatch(); + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Task.php'; - require_once 'classes/model/Content.php'; + return $oCriteria; + } - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addAsColumn("MIN", "MIN(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("MAX", "MAX(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("TOTALDUR", "SUM(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("PROMEDIO", "AVG(".AppDelegationPeer::DEL_DURATION.")"); + /** + * This function gets info about a report + * + * + * @name descriptionReport1 + * + * @param string $PRO_UID + * @return object + */ + public function descriptionReport1 ($PRO_UID) + { + $this->reportsPatch(); - $oCriteria->addJoin(AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Task.php'; + require_once 'classes/model/Content.php'; - $oCriteria->addAsColumn('TAS_TITLE', 'C.CON_VALUE'); - $oCriteria->addAlias("C", 'CONTENT'); + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")" ); - $proContentConds = array(); - $proContentConds[] = array(AppDelegationPeer::TAS_UID, 'C.CON_ID'); - $proContentConds[] = array('C.CON_CATEGORY', $del . 'TAS_TITLE' . $del); - $proContentConds[] = array('C.CON_LANG', $del . SYS_LANG . $del); - $oCriteria->addJoinMC($proContentConds, Criteria::LEFT_JOIN); + $oCriteria->addJoin( AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN ); - $oCriteria->add(AppDelegationPeer::PRO_UID, $PRO_UID); + $oCriteria->addAsColumn( 'TAS_TITLE', 'C.CON_VALUE' ); + $oCriteria->addAlias( "C", 'CONTENT' ); - $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addGroupByColumn('C.CON_VALUE'); + $proContentConds = array (); + $proContentConds[] = array (AppDelegationPeer::TAS_UID,'C.CON_ID' + ); + $proContentConds[] = array ('C.CON_CATEGORY',$del . 'TAS_TITLE' . $del + ); + $proContentConds[] = array ('C.CON_LANG',$del . SYS_LANG . $del + ); + $oCriteria->addJoinMC( $proContentConds, Criteria::LEFT_JOIN ); + $oCriteria->add( AppDelegationPeer::PRO_UID, $PRO_UID ); - $oDataset = AppDelegationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); + $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addGroupByColumn( 'C.CON_VALUE' ); - $aProcess[] = array('TAS_TITLE' => 'char', - 'MIN' => 'float', - 'MAX' => 'float', - 'TOTALDUR' => 'float', - 'PROMEDIO' => 'float'); - while ($aRow = $oDataset->getRow()) { - $aProcess[] = array('TAS_TITLE' => $aRow['TAS_TITLE'], - 'MIN' => number_format($aRow['MIN'],2), - 'MAX' => number_format($aRow['MAX'],2), - 'TOTALDUR' => number_format($aRow['TOTALDUR'],2), - 'PROMEDIO' => number_format($aRow['PROMEDIO'],2)); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); - } - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); + $aProcess[] = array ('TAS_TITLE' => 'char','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' + ); + while ($aRow = $oDataset->getRow()) { + $aProcess[] = array ('TAS_TITLE' => $aRow['TAS_TITLE'],'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'TOTALDUR' => number_format( $aRow['TOTALDUR'], 2 ),'PROMEDIO' => number_format( $aRow['PROMEDIO'], 2 ) + ); + $oDataset->next(); + } - return $oCriteria; - } + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); - /** - * This function generates a other kind of report - * - * - * @name generatedReport2 - * - * param - * @return object - */ - function generatedReport2() - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addAsColumn("MIN", "MIN(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("MAX", "MAX(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn('PRO_TITLE', 'C1.CON_VALUE' ); - $oCriteria->addAlias("C1", 'CONTENT'); - $proTitleConds = array(); - $proTitleConds[] = array( AppDelegationPeer::PRO_UID , 'C1.CON_ID' ); - $proTitleConds[] = array( 'C1.CON_CATEGORY' , $del . 'PRO_TITLE' . $del ); - $proTitleConds[] = array( 'C1.CON_LANG' , $del . SYS_LANG . $del ); - $oCriteria->addJoinMC($proTitleConds , Criteria::LEFT_JOIN); - $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); + return $oCriteria; + } - $oDataset = AppDelegationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); + /** + * This function generates a other kind of report + * + * + * @name generatedReport2 + * + * param + * @return object + */ + public function generatedReport2 () + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( 'PRO_TITLE', 'C1.CON_VALUE' ); + $oCriteria->addAlias( "C1", 'CONTENT' ); + $proTitleConds = array (); + $proTitleConds[] = array (AppDelegationPeer::PRO_UID,'C1.CON_ID' + ); + $proTitleConds[] = array ('C1.CON_CATEGORY',$del . 'PRO_TITLE' . $del + ); + $proTitleConds[] = array ('C1.CON_LANG',$del . SYS_LANG . $del + ); + $oCriteria->addJoinMC( $proTitleConds, Criteria::LEFT_JOIN ); + $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); - $month = date( 'Y-m-d' , mktime(0, 0, 0, date("m")-1 , date("d"), date("Y")) ); - $lastmonth = date( 'Y-m-d' , mktime(0, 0, 0, date("m")-2 , date("d"), date("Y")) ); - - $day = mktime(0, 0, 0, date("m") , date("d")-1, date("Y")); - $lastday = mktime(0, 0, 0, date("m") , date("d")-2, date("Y")); - - $aProcess[] = array('PRO_UID' => 'char', - 'PRO_TITLE' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'CASELASTMONTH' => 'integer', - 'CASELASTDAY' => 'integer' - ); - - while ($aRow = $oDataset->getRow()) { - $oCriteria2 = new Criteria('workflow'); - $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); - $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); - $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); - $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); - $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant = $aRow2['CANTCASES']; - - $oCriteria2 = new Criteria('workflow'); - $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); - $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); - $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); - $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $lastmonth, Criteria::GREATER_EQUAL); - $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $month, Criteria::LESS_EQUAL); - $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); - $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant1 = $aRow2['CANTCASES']; - - $oCriteria2 = new Criteria('workflow'); - $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); - $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); - $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); - $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $lastday, Criteria::GREATER_EQUAL); - $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $day, Criteria::LESS_EQUAL); - $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); - $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant2 = $aRow2['CANTCASES']; - - $aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], - 'PRO_TITLE' => $aRow['PRO_TITLE'], - 'CANTCASES' => $cant, - 'MIN' => number_format($aRow['MIN'],2), - 'MAX' => number_format($aRow['MAX'],2), - 'CASELASTMONTH' => number_format($cant1,2), - 'CASELASTDAY' => number_format($cant2,2) - ); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); - } - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); - return $oCriteria; - } + $month = date( 'Y-m-d', mktime( 0, 0, 0, date( "m" ) - 1, date( "d" ), date( "Y" ) ) ); + $lastmonth = date( 'Y-m-d', mktime( 0, 0, 0, date( "m" ) - 2, date( "d" ), date( "Y" ) ) ); - /** - * This function generates the description about a report - * - * - * @name reports_Description_filter - * - * @param string $from - * @param string $to - * @param string $startedby - * @param string $PRO_UID - * @return object - */ - function reports_Description_filter($from, $to, $startedby, $PRO_UID) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Task.php'; - require_once 'classes/model/Content.php'; - require_once 'classes/model/Users.php'; + $day = mktime( 0, 0, 0, date( "m" ), date( "d" ) - 1, date( "Y" ) ); + $lastday = mktime( 0, 0, 0, date( "m" ), date( "d" ) - 2, date( "Y" ) ); - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addAsColumn("MIN", "MIN(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("MAX", "MAX(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("TOTALDUR", "SUM(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("PROMEDIO", "AVG(".AppDelegationPeer::DEL_DURATION.")"); + $aProcess[] = array ('PRO_UID' => 'char','PRO_TITLE' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','CASELASTMONTH' => 'integer','CASELASTDAY' => 'integer' + ); - $oCriteria->addJoin(AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN); + while ($aRow = $oDataset->getRow()) { + $oCriteria2 = new Criteria( 'workflow' ); + $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); + $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); + $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); + $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); + $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); + $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant = $aRow2['CANTCASES']; - $oCriteria->addAsColumn('TAS_TITLE', 'C.CON_VALUE'); - $oCriteria->addAlias("C", 'CONTENT'); + $oCriteria2 = new Criteria( 'workflow' ); + $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); + $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); + $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); + $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $lastmonth, Criteria::GREATER_EQUAL ); + $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $month, Criteria::LESS_EQUAL ); + $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); + $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); + $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant1 = $aRow2['CANTCASES']; - $proContentConds = array(); - $proContentConds[] = array(AppDelegationPeer::TAS_UID, 'C.CON_ID'); - $proContentConds[] = array('C.CON_CATEGORY', $del . 'TAS_TITLE' . $del); - $proContentConds[] = array('C.CON_LANG', $del . SYS_LANG . $del); - $oCriteria->addJoinMC($proContentConds, Criteria::LEFT_JOIN); + $oCriteria2 = new Criteria( 'workflow' ); + $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); + $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); + $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); + $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $lastday, Criteria::GREATER_EQUAL ); + $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $day, Criteria::LESS_EQUAL ); + $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); + $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); + $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant2 = $aRow2['CANTCASES']; - $oCriteria->add($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $from.' 00:00:00', Criteria::GREATER_EQUAL)->addAnd($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $to.' 23:59:59', Criteria::LESS_EQUAL))); + $aProcess[] = array ('PRO_UID' => $aRow['PRO_UID'],'PRO_TITLE' => $aRow['PRO_TITLE'],'CANTCASES' => $cant,'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'CASELASTMONTH' => number_format( $cant1, 2 ),'CASELASTDAY' => number_format( $cant2, 2 ) + ); + $oDataset->next(); + } - if($startedby!='') $oCriteria->add(AppDelegationPeer::USR_UID, $startedby); + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); + return $oCriteria; + } - $oCriteria->add(AppDelegationPeer::PRO_UID, $PRO_UID); + /** + * This function generates the description about a report + * + * + * @name reports_Description_filter + * + * @param string $from + * @param string $to + * @param string $startedby + * @param string $PRO_UID + * @return object + */ + public function reports_Description_filter ($from, $to, $startedby, $PRO_UID) + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Task.php'; + require_once 'classes/model/Content.php'; + require_once 'classes/model/Users.php'; - $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addGroupByColumn('C.CON_VALUE'); + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")" ); - return $oCriteria; - } + $oCriteria->addJoin( AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN ); - /** - * This function looks for an special case it has a condition - * - * - * @name generatedReport2_filter - * - * @param string $from - * @param string $to - * @param string $startedby - * @return object - */ - function generatedReport2_filter($from, $to, $startedby) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Users.php'; + $oCriteria->addAsColumn( 'TAS_TITLE', 'C.CON_VALUE' ); + $oCriteria->addAlias( "C", 'CONTENT' ); - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addAsColumn("MIN", "MIN(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn("MAX", "MAX(".AppDelegationPeer::DEL_DURATION.")"); - $oCriteria->addAsColumn('PRO_TITLE', 'C1.CON_VALUE' ); - $oCriteria->addAlias("C1", 'CONTENT'); - $proTitleConds = array(); - $proTitleConds[] = array( AppDelegationPeer::PRO_UID , 'C1.CON_ID' ); - $proTitleConds[] = array( 'C1.CON_CATEGORY' , $del . 'PRO_TITLE' . $del ); - $proTitleConds[] = array( 'C1.CON_LANG' , $del . SYS_LANG . $del ); - $oCriteria->addJoinMC($proTitleConds , Criteria::LEFT_JOIN); - $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); - $oCriteria->addGroupByColumn('C1.CON_VALUE'); - - $oCriteria->add($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $from.' 00:00:00', Criteria::GREATER_EQUAL)->addAnd($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $to.' 23:59:59', Criteria::LESS_EQUAL))); + $proContentConds = array (); + $proContentConds[] = array (AppDelegationPeer::TAS_UID,'C.CON_ID' + ); + $proContentConds[] = array ('C.CON_CATEGORY',$del . 'TAS_TITLE' . $del + ); + $proContentConds[] = array ('C.CON_LANG',$del . SYS_LANG . $del + ); + $oCriteria->addJoinMC( $proContentConds, Criteria::LEFT_JOIN ); - if($startedby!='') $oCriteria->add(AppDelegationPeer::USR_UID, $startedby); + $oCriteria->add( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $from . ' 00:00:00', Criteria::GREATER_EQUAL )->addAnd( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $to . ' 23:59:59', Criteria::LESS_EQUAL ) ) ); - $oDataset = AppDelegationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); + if ($startedby != '') + $oCriteria->add( AppDelegationPeer::USR_UID, $startedby ); - $month = date( 'Y-m-d' , mktime(0, 0, 0, date("m")-1 , date("d"), date("Y")) ); - $lastmonth = date( 'Y-m-d' , mktime(0, 0, 0, date("m")-2 , date("d"), date("Y")) ); - $day = mktime(0, 0, 0, date("m") , date("d")-1, date("Y")); - $lastday = mktime(0, 0, 0, date("m") , date("d")-2, date("Y")); - $aProcess[] = array('PRO_UID' => 'char', - 'PRO_TITLE' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'CASELASTMONTH' => 'integer', - 'CASELASTDAY' => 'integer' - ); + $oCriteria->add( AppDelegationPeer::PRO_UID, $PRO_UID ); - while ($aRow = $oDataset->getRow()) { - $oCriteria2 = new Criteria('workflow'); - $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); - $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); - $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); - if($startedby!='') $oCriteria2->add(ApplicationPeer::APP_INIT_USER, $startedby); - $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); - $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant = $aRow2['CANTCASES']; + $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addGroupByColumn( 'C.CON_VALUE' ); - $oCriteria2 = new Criteria('workflow'); - $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); - $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); - $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); - $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $lastmonth, Criteria::GREATER_EQUAL); - $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $month, Criteria::LESS_EQUAL); - if($startedby!='') $oCriteria2->add(ApplicationPeer::APP_INIT_USER, $startedby); - $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); - $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant1 = $aRow2['CANTCASES']; + return $oCriteria; + } - $oCriteria2 = new Criteria('workflow'); - $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); - $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); - $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); - $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $lastday, Criteria::GREATER_EQUAL); - $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $day, Criteria::LESS_EQUAL); - if($startedby!='') $oCriteria2->add(ApplicationPeer::APP_INIT_USER, $startedby); - $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); - $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant2 = $aRow2['CANTCASES']; + /** + * This function looks for an special case it has a condition + * + * + * @name generatedReport2_filter + * + * @param string $from + * @param string $to + * @param string $startedby + * @return object + */ + public function generatedReport2_filter ($from, $to, $startedby) + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Users.php'; - /*$aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); + $oCriteria->addAsColumn( 'PRO_TITLE', 'C1.CON_VALUE' ); + $oCriteria->addAlias( "C1", 'CONTENT' ); + $proTitleConds = array (); + $proTitleConds[] = array (AppDelegationPeer::PRO_UID,'C1.CON_ID' + ); + $proTitleConds[] = array ('C1.CON_CATEGORY',$del . 'PRO_TITLE' . $del + ); + $proTitleConds[] = array ('C1.CON_LANG',$del . SYS_LANG . $del + ); + $oCriteria->addJoinMC( $proTitleConds, Criteria::LEFT_JOIN ); + $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); + $oCriteria->addGroupByColumn( 'C1.CON_VALUE' ); + + $oCriteria->add( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $from . ' 00:00:00', Criteria::GREATER_EQUAL )->addAnd( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $to . ' 23:59:59', Criteria::LESS_EQUAL ) ) ); + + if ($startedby != '') + $oCriteria->add( AppDelegationPeer::USR_UID, $startedby ); + + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + + $month = date( 'Y-m-d', mktime( 0, 0, 0, date( "m" ) - 1, date( "d" ), date( "Y" ) ) ); + $lastmonth = date( 'Y-m-d', mktime( 0, 0, 0, date( "m" ) - 2, date( "d" ), date( "Y" ) ) ); + $day = mktime( 0, 0, 0, date( "m" ), date( "d" ) - 1, date( "Y" ) ); + $lastday = mktime( 0, 0, 0, date( "m" ), date( "d" ) - 2, date( "Y" ) ); + $aProcess[] = array ('PRO_UID' => 'char','PRO_TITLE' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','CASELASTMONTH' => 'integer','CASELASTDAY' => 'integer' + ); + + while ($aRow = $oDataset->getRow()) { + $oCriteria2 = new Criteria( 'workflow' ); + $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); + $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); + $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); + if ($startedby != '') + $oCriteria2->add( ApplicationPeer::APP_INIT_USER, $startedby ); + $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); + $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); + $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant = $aRow2['CANTCASES']; + + $oCriteria2 = new Criteria( 'workflow' ); + $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); + $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); + $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); + $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $lastmonth, Criteria::GREATER_EQUAL ); + $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $month, Criteria::LESS_EQUAL ); + if ($startedby != '') + $oCriteria2->add( ApplicationPeer::APP_INIT_USER, $startedby ); + $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); + $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); + $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant1 = $aRow2['CANTCASES']; + + $oCriteria2 = new Criteria( 'workflow' ); + $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); + $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); + $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); + $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $lastday, Criteria::GREATER_EQUAL ); + $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $day, Criteria::LESS_EQUAL ); + if ($startedby != '') + $oCriteria2->add( ApplicationPeer::APP_INIT_USER, $startedby ); + $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); + $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); + $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant2 = $aRow2['CANTCASES']; + + /*$aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], 'PRO_TITLE' => $aRow['PRO_TITLE'], 'CANTCASES' => $cant, 'CASELASTMONTH' => $cant1, 'CASELASTDAY' => $cant2 );*/ - $aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], - 'PRO_TITLE' => $aRow['PRO_TITLE'], - 'CANTCASES' => $cant, - 'MIN' => number_format($aRow['MIN'],2), - 'MAX' => number_format($aRow['MAX'],2), - 'CASELASTMONTH' => number_format($cant1,2), - 'CASELASTDAY' => number_format($cant2,2) - ); - $oDataset->next(); - } + $aProcess[] = array ('PRO_UID' => $aRow['PRO_UID'],'PRO_TITLE' => $aRow['PRO_TITLE'],'CANTCASES' => $cant,'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'CASELASTMONTH' => number_format( $cant1, 2 ),'CASELASTDAY' => number_format( $cant2, 2 ) + ); + $oDataset->next(); + } - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); - return $oCriteria; - } + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); + return $oCriteria; + } - /** - * This function looks for an special case it has a condition - * - * - * @name generatedReport2_filter - * - * @param string $from - * @param string $to - * @param string $startedby - * @return object - */ - function generatedReport3() - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $sql = "SELECT CONCAT(SUBSTRING(AD.DEL_INIT_DATE,6,2),'-', SUBSTRING(AD.DEL_INIT_DATE,1,4)) AS FECHA, + /** + * This function looks for an special case it has a condition + * + * + * @name generatedReport2_filter + * + * @param string $from + * @param string $to + * @param string $startedby + * @return object + */ + public function generatedReport3 () + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $sql = "SELECT CONCAT(SUBSTRING(AD.DEL_INIT_DATE,6,2),'-', SUBSTRING(AD.DEL_INIT_DATE,1,4)) AS FECHA, COUNT(DISTINCT(AD.APP_UID)) AS CANTCASES, MIN(AD.DEL_DURATION) AS MIN, MAX(AD.DEL_DURATION) AS MAX, @@ -558,73 +535,58 @@ class Report { WHERE AD.APP_UID<>'' AND P.PRO_STATUS<>'DISABLED' GROUP BY FECHA"; - $con = Propel::getConnection("workflow"); - $stmt = $con->prepareStatement($sql); - $rs = $stmt->executeQuery(); + $con = Propel::getConnection( "workflow" ); + $stmt = $con->prepareStatement( $sql ); + $rs = $stmt->executeQuery(); - $ROW[] = array('FECHA' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'TOTALDUR' => 'float', - 'PROMEDIO' => 'float' - ); + $ROW[] = array ('FECHA' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' + ); - while($rs->next()) - { - $ROW[] = array('FECHA' => $rs->getString('FECHA'), - 'CANTCASES'=> $rs->getString('CANTCASES'), - 'MIN' => number_format($rs->getString('MIN'),2), - 'MAX' => number_format($rs->getString('MAX'),2), - 'TOTALDUR' => number_format($rs->getString('TOTALDUR'),2), - 'PROMEDIO' => number_format($rs->getString('PROMEDIO'),2) - ); - } + while ($rs->next()) { + $ROW[] = array ('FECHA' => $rs->getString( 'FECHA' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) + ); + } - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); - return $oCriteria; + return $oCriteria; - } - - /** - * This function looks for an special case it has a condition - * - * - * @name generatedReport3_filter - * - * @param string $process - * @param string $task - * @return object - */ - function generatedReport3_filter($process, $task) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - if($process=='') - { $var=" WHERE P.PRO_STATUS<>'DISABLED'"; } - else + + /** + * This function looks for an special case it has a condition + * + * + * @name generatedReport3_filter + * + * @param string $process + * @param string $task + * @return object + */ + public function generatedReport3_filter ($process, $task) { - if($task=='') - { - $var=" LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE P.PRO_STATUS<>'DISABLED' AND AD.PRO_UID='".$process."'"; - } - else - { $var=" LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE P.PRO_STATUS<>'DISABLED' AND AD.PRO_UID='".$process."' AND AD.TAS_UID='".$task."' "; - } - } - $sql = "SELECT CONCAT(SUBSTRING(AD.DEL_INIT_DATE,6,2),'-', SUBSTRING(AD.DEL_INIT_DATE,1,4)) AS FECHA, + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + if ($process == '') { + $var = " WHERE P.PRO_STATUS<>'DISABLED'"; + } else { + if ($task == '') { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE P.PRO_STATUS<>'DISABLED' AND AD.PRO_UID='" . $process . "'"; + } else { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE P.PRO_STATUS<>'DISABLED' AND AD.PRO_UID='" . $process . "' AND AD.TAS_UID='" . $task . "' "; + } + } + $sql = "SELECT CONCAT(SUBSTRING(AD.DEL_INIT_DATE,6,2),'-', SUBSTRING(AD.DEL_INIT_DATE,1,4)) AS FECHA, COUNT(DISTINCT(AD.APP_UID)) AS CANTCASES, MIN(AD.DEL_DURATION) AS MIN, MAX(AD.DEL_DURATION) AS MAX, @@ -632,60 +594,49 @@ class Report { AVG(AD.DEL_DURATION) AS PROMEDIO FROM APP_DELEGATION AS AD LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) - ".$var." + " . $var . " GROUP BY FECHA"; - $con = Propel::getConnection("workflow"); - $stmt = $con->prepareStatement($sql); - $rs = $stmt->executeQuery(); - $ROW[] = array('FECHA' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'TOTALDUR' => 'float', - 'PROMEDIO' => 'float' - ); + $con = Propel::getConnection( "workflow" ); + $stmt = $con->prepareStatement( $sql ); + $rs = $stmt->executeQuery(); + $ROW[] = array ('FECHA' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' + ); - while($rs->next()) - { - $ROW[] = array('FECHA' => $rs->getString('FECHA'), - 'CANTCASES' => $rs->getString('CANTCASES'), - 'MIN' => number_format($rs->getString('MIN'),2), - 'MAX' => number_format($rs->getString('MAX'),2), - 'TOTALDUR' => number_format($rs->getString('TOTALDUR'),2), - 'PROMEDIO' => number_format($rs->getString('PROMEDIO'),2) - ); - } + while ($rs->next()) { + $ROW[] = array ('FECHA' => $rs->getString( 'FECHA' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) + ); + } - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); - return $oCriteria; - } + return $oCriteria; + } - /** - * This function generates a report - * - * - * @name generatedReport4 - * - * param - * @return object - */ - function generatedReport4() - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Process.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, + /** + * This function generates a report + * + * + * @name generatedReport4 + * + * param + * @return object + */ + public function generatedReport4 () + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Process.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, COUNT(*) AS CANTCASES, MIN(AD.DEL_DURATION) AS MIN, MAX(AD.DEL_DURATION) AS MAX, @@ -696,78 +647,62 @@ class Report { LEFT JOIN USERS AS U ON(U.USR_UID = A.APP_INIT_USER) WHERE A.APP_UID<>'' GROUP BY USER"; - // AND P.PRO_STATUS<>'DISABLED' that hapens when it is created to new version it exists at the moment to import - $con = Propel::getConnection("workflow"); - $stmt = $con->prepareStatement($sql); - $rs = $stmt->executeQuery(); + // AND P.PRO_STATUS<>'DISABLED' that hapens when it is created to new version it exists at the moment to import + $con = Propel::getConnection( "workflow" ); + $stmt = $con->prepareStatement( $sql ); + $rs = $stmt->executeQuery(); - $ROW[] = array('USER' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'TOTALDUR' => 'float', - 'PROMEDIO' => 'float' - ); + $ROW[] = array ('USER' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' + ); - while($rs->next()) - { - $ROW[] = array('USER' => $rs->getString('USER'), - 'CANTCASES'=> $rs->getString('CANTCASES'), - 'MIN' => number_format($rs->getString('MIN'),2), - 'MAX' => number_format($rs->getString('MAX'),2), - 'TOTALDUR' => number_format($rs->getString('TOTALDUR'),2), - 'PROMEDIO' => number_format($rs->getString('PROMEDIO'),2) - ); - } + while ($rs->next()) { + $ROW[] = array ('USER' => $rs->getString( 'USER' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) + ); + } - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); - return $oCriteria; + return $oCriteria; - } - - /** - * This function generates a filter to report 4 - * - * - * @name generatedReport4_filter - * - * @param string process - * @param string task - * @return object - */ - function generatedReport4_filter($process, $task) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Process.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - if($process=='') - { - $var=" "; } - else + + /** + * This function generates a filter to report 4 + * + * + * @name generatedReport4_filter + * + * @param string process + * @param string task + * @return object + */ + public function generatedReport4_filter ($process, $task) { - if($task=='') - { - $var=" LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE AD.PRO_UID='".$process."'"; - } - else - { $var=" LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE AD.PRO_UID='".$process."' AND AD.TAS_UID='".$task."' "; - } - } + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Process.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + if ($process == '') { + $var = " "; + } else { + if ($task == '') { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE AD.PRO_UID='" . $process . "'"; + } else { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE AD.PRO_UID='" . $process . "' AND AD.TAS_UID='" . $task . "' "; + } + } - $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, + $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, COUNT(*) AS CANTCASES, MIN(AD.DEL_DURATION) AS MIN, MAX(AD.DEL_DURATION) AS MAX, @@ -776,62 +711,51 @@ class Report { FROM APPLICATION AS A LEFT JOIN APP_DELEGATION AS AD ON(A.APP_UID = AD.APP_UID AND AD.DEL_INDEX=1) LEFT JOIN USERS AS U ON(U.USR_UID = A.APP_INIT_USER) - ".$var." + " . $var . " GROUP BY USER"; - $con = Propel::getConnection("workflow"); - $stmt = $con->prepareStatement($sql); - $rs = $stmt->executeQuery(); + $con = Propel::getConnection( "workflow" ); + $stmt = $con->prepareStatement( $sql ); + $rs = $stmt->executeQuery(); - $ROW[] = array('USER' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'TOTALDUR' => 'float', - 'PROMEDIO' => 'float' - ); + $ROW[] = array ('USER' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' + ); - while($rs->next()) - { - $ROW[] = array('USER' => $rs->getString('USER'), - 'CANTCASES' => $rs->getString('CANTCASES'), - 'MIN' => number_format($rs->getString('MIN'),2), - 'MAX' => number_format($rs->getString('MAX'),2), - 'TOTALDUR' => number_format($rs->getString('TOTALDUR'),2), - 'PROMEDIO' => number_format($rs->getString('PROMEDIO'),2) - ); - } + while ($rs->next()) { + $ROW[] = array ('USER' => $rs->getString( 'USER' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) + ); + } - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); - return $oCriteria; - } + return $oCriteria; + } - /** - * This function generates a Report - * - * - * @name generatedReport4_filter - * - * @param string process - * @param string task - * @return object - */ - function generatedReport5() - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Process.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, + /** + * This function generates a Report + * + * + * @name generatedReport4_filter + * + * @param string process + * @param string task + * @return object + */ + public function generatedReport5 () + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Process.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, COUNT(*) AS CANTCASES, MIN(AD.DEL_DURATION) AS MIN, MAX(AD.DEL_DURATION) AS MAX, @@ -843,75 +767,60 @@ class Report { WHERE AD.APP_UID<>'' AND AD.DEL_FINISH_DATE IS NULL GROUP BY USER"; - $con = Propel::getConnection("workflow"); - $stmt = $con->prepareStatement($sql); - $rs = $stmt->executeQuery(); + $con = Propel::getConnection( "workflow" ); + $stmt = $con->prepareStatement( $sql ); + $rs = $stmt->executeQuery(); - $ROW[] = array('USER' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'TOTALDUR' => 'float', - 'PROMEDIO' => 'float' - ); + $ROW[] = array ('USER' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' + ); - while($rs->next()) - { - $ROW[] = array('USER' => $rs->getString('USER'), - 'CANTCASES'=> $rs->getString('CANTCASES'), - 'MIN' => number_format($rs->getString('MIN'),2), - 'MAX' => number_format($rs->getString('MAX'),2), - 'TOTALDUR' => number_format($rs->getString('TOTALDUR'),2), - 'PROMEDIO' => number_format($rs->getString('PROMEDIO'),2) - ); - } + while ($rs->next()) { + $ROW[] = array ('USER' => $rs->getString( 'USER' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) + ); + } - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); - return $oCriteria; + return $oCriteria; - } - - /** - * This function generates a filter to report 5 - * - * - * @name generatedReport5_filter - * - * @param string process - * @param string task - * @return object - */ - function generatedReport5_filter($process, $task) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Process.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - if($process=='') - { $var=" WHERE AD.DEL_FINISH_DATE IS NULL"; } - else + + /** + * This function generates a filter to report 5 + * + * + * @name generatedReport5_filter + * + * @param string process + * @param string task + * @return object + */ + public function generatedReport5_filter ($process, $task) { - if($task=='') - { - $var=" LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE AD.PRO_UID='".$process."' AND AD.DEL_FINISH_DATE IS NULL"; - } - else - { $var=" LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE AD.PRO_UID='".$process."' AND AD.TAS_UID='".$task."' "; - } - } - $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Process.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + if ($process == '') { + $var = " WHERE AD.DEL_FINISH_DATE IS NULL"; + } else { + if ($task == '') { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE AD.PRO_UID='" . $process . "' AND AD.DEL_FINISH_DATE IS NULL"; + } else { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE AD.PRO_UID='" . $process . "' AND AD.TAS_UID='" . $task . "' "; + } + } + $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, COUNT(*) AS CANTCASES, MIN(AD.DEL_DURATION) AS MIN, MAX(AD.DEL_DURATION) AS MAX, @@ -920,107 +829,96 @@ class Report { FROM APP_DELEGATION AS AD LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) LEFT JOIN USERS AS U ON(U.USR_UID = AD.USR_UID) - ".$var." + " . $var . " GROUP BY USER"; - $con = Propel::getConnection("workflow"); - $stmt = $con->prepareStatement($sql); - $rs = $stmt->executeQuery(); + $con = Propel::getConnection( "workflow" ); + $stmt = $con->prepareStatement( $sql ); + $rs = $stmt->executeQuery(); - $ROW[] = array('USER' => 'char', - 'CANTCASES' => 'integer', - 'MIN' => 'float', - 'MAX' => 'float', - 'TOTALDUR' => 'float', - 'PROMEDIO' => 'float' - ); + $ROW[] = array ('USER' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' + ); - while($rs->next()) - { - $ROW[] = array('USER' => $rs->getString('USER'), - 'CANTCASES' => $rs->getString('CANTCASES'), - 'MIN' => number_format($rs->getString('MIN'),2), - 'MAX' => number_format($rs->getString('MAX'),2), - 'TOTALDUR' => number_format($rs->getString('TOTALDUR'),2), - 'PROMEDIO' => number_format($rs->getString('PROMEDIO'),2) - ); - } + while ($rs->next()) { + $ROW[] = array ('USER' => $rs->getString( 'USER' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) + ); + } - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - G::LoadClass('ArrayPeer'); - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('reports'); + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reports' ); - return $oCriteria; - } - - /** - * This function returns an array, it has the reports' names - * - * - * @name getAvailableReports - * - * param - * @return array - */ - function getAvailableReports() - { - return array('ID_REPORT1', 'ID_REPORT2', 'ID_REPORT3', 'ID_REPORT4', 'ID_REPORT5'); - } - - /** - * Patch for reports by The Answer (17-10-2k8) - * - * - * @name reportsPatch - * - * param - * @return void - */ - - function reportsPatch() - { - require_once 'classes/model/AppDelegation.php'; - - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn(AppDelegationPeer::APP_UID); - $oCriteria->addSelectColumn(AppDelegationPeer::DEL_INDEX); - $oCriteria->addSelectColumn(AppDelegationPeer::TAS_UID); - $oCriteria->addSelectColumn(AppDelegationPeer::DEL_DELEGATE_DATE); - $oCriteria->addSelectColumn(AppDelegationPeer::DEL_INIT_DATE); - $oCriteria->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE); - $oCriteria->addSelectColumn(AppDelegationPeer::DEL_DURATION); - $oDataset = AppDelegationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $oAppDelegation = new AppDelegation(); - - $aData['APP_UID']=$aRow['APP_UID']; - $aData['DEL_INDEX']=$aRow['DEL_INDEX']; - $aData['DEL_DELEGATE_DATE']=$aRow['DEL_DELEGATE_DATE']; - - if($aRow['DEL_INIT_DATE']==NULL) - $aData['DEL_INIT_DATE']=$aRow['DEL_DELEGATE_DATE']; - else - $aData['DEL_INIT_DATE']=$aRow['DEL_INIT_DATE']; - - //$aData['DEL_FINISH_DATE']=$aRow['DEL_FINISH_DATE']; - if($aRow['DEL_DURATION']!=0) - { - G::LoadClass('dates'); - $oDates = new dates(); - $aData['DEL_DURATION']= $oDates->calculateDuration($aData['DEL_INIT_DATE'], $aRow['DEL_FINISH_DATE'], null, null, $aRow['TAS_UID']); + return $oCriteria; } - $oAppDelegation->update($aData); + /** + * This function returns an array, it has the reports' names + * + * + * @name getAvailableReports + * + * param + * @return array + */ + public function getAvailableReports () + { + return array ('ID_REPORT1','ID_REPORT2','ID_REPORT3','ID_REPORT4','ID_REPORT5' + ); + } - $oDataset->next(); - } - return; - } + /** + * Patch for reports by The Answer (17-10-2k8) + * + * + * @name reportsPatch + * + * param + * @return void + */ + + public function reportsPatch () + { + require_once 'classes/model/AppDelegation.php'; + + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn( AppDelegationPeer::APP_UID ); + $oCriteria->addSelectColumn( AppDelegationPeer::DEL_INDEX ); + $oCriteria->addSelectColumn( AppDelegationPeer::TAS_UID ); + $oCriteria->addSelectColumn( AppDelegationPeer::DEL_DELEGATE_DATE ); + $oCriteria->addSelectColumn( AppDelegationPeer::DEL_INIT_DATE ); + $oCriteria->addSelectColumn( AppDelegationPeer::DEL_FINISH_DATE ); + $oCriteria->addSelectColumn( AppDelegationPeer::DEL_DURATION ); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $oAppDelegation = new AppDelegation(); + + $aData['APP_UID'] = $aRow['APP_UID']; + $aData['DEL_INDEX'] = $aRow['DEL_INDEX']; + $aData['DEL_DELEGATE_DATE'] = $aRow['DEL_DELEGATE_DATE']; + + if ($aRow['DEL_INIT_DATE'] == NULL) + $aData['DEL_INIT_DATE'] = $aRow['DEL_DELEGATE_DATE']; + else + $aData['DEL_INIT_DATE'] = $aRow['DEL_INIT_DATE']; + + //$aData['DEL_FINISH_DATE']=$aRow['DEL_FINISH_DATE']; + if ($aRow['DEL_DURATION'] != 0) { + G::LoadClass( 'dates' ); + $oDates = new dates(); + $aData['DEL_DURATION'] = $oDates->calculateDuration( $aData['DEL_INIT_DATE'], $aRow['DEL_FINISH_DATE'], null, null, $aRow['TAS_UID'] ); + } + + $oAppDelegation->update( $aData ); + + $oDataset->next(); + } + return; + } }// end Report class \ No newline at end of file From 5919afd93090b8c0cd82522d319b70438b270d1a Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:21:00 -0400 Subject: [PATCH 03/18] CODE STYLE class.reportTables.php --- .../engine/classes/class.reportTables.php | 1539 ++++++++--------- 1 file changed, 766 insertions(+), 773 deletions(-) diff --git a/workflow/engine/classes/class.reportTables.php b/workflow/engine/classes/class.reportTables.php index a751f19c8..33721a55b 100755 --- a/workflow/engine/classes/class.reportTables.php +++ b/workflow/engine/classes/class.reportTables.php @@ -1,6 +1,7 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. * */ -G::LoadClass('case'); +G::LoadClass( 'case' ); /** * ReportTables - Report tables class + * * @package workflow.engine.ProcessMaker * @author Julio Cesar Laura Avenda�o * @copyright 2007 COLOSA @@ -35,798 +37,789 @@ G::LoadClass('case'); class ReportTables { - private $aDef = array('mysql' => array('number' => 'DOUBLE', - 'char' => 'VARCHAR(255)', - 'text' => 'TEXT', - 'date' => 'DATETIME'), - 'pgsql' => array('number' => 'DOUBLE', - 'char' => 'VARCHAR(255)', - 'text' => 'TEXT', - 'date' => 'DATETIME'), - 'mssql' => array('number' => 'FLOAT', - 'char' => 'NVARCHAR(255)', - 'text' => 'TEXT', - 'date' => 'CHAR(19)') /* Changed DATETIME CHAR(19) for compatibility issues. */ + private $aDef = array ('mysql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME' + ),'pgsql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME' + ),'mssql' => array ('number' => 'FLOAT','char' => 'NVARCHAR(255)','text' => 'TEXT','date' => 'CHAR(19)' + ) /* Changed DATETIME CHAR(19) for compatibility issues. */ ); - //private $sPrefix = 'REP_'; - private $sPrefix = ''; - - /** - * Function deleteAllReportVars - * This function delete all reports - * @access public - * @param string $$sRepTabUid - * @return void - */ - public function deleteAllReportVars($sRepTabUid = '') - { - try { - $oCriteria = new Criteria('workflow'); - $oCriteria->add(ReportVarPeer::REP_TAB_UID, $sRepTabUid); - ReportVarPeer::doDelete($oCriteria); - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Function prepareQuery - * This function removes the table - * @access public - * @param string $sTableName Table name - * @param string $sConnection Conexion - * @return void - */ - public function dropTable($sTableName, $sConnection = 'report') - { - $sTableName = $this->sPrefix . $sTableName; - //we have to do the propel connection - $PropelDatabase=$this->chooseDB($sConnection); - $con = Propel::getConnection($PropelDatabase); - $stmt = $con->createStatement(); - try { - switch (DB_ADAPTER) { - case 'mysql': - $rs = $stmt->executeQuery( 'DROP TABLE IF EXISTS `' . $sTableName . '`'); - break; - case 'mssql': - $rs = $stmt->executeQuery( "IF OBJECT_ID (N'" . $sTableName . "', N'U') IS NOT NULL - DROP TABLE [" . $sTableName . "]"); - break; - } - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Function createTable - * This Function creates the table - * @access public - * @param string $sTableName Table name - * @param string $sConnection Connection name - * @param string $sType - * @param array $aFields - * @param string $bDefaultFields - * @return void - */ - public function createTable($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $bDefaultFields = true) - { - $sTableName = $this->sPrefix . $sTableName; - //we have to do the propel connection - $PropelDatabase=$this->chooseDB($sConnection); - $con = Propel::getConnection($PropelDatabase); - $stmt = $con->createStatement(); - try { - switch (DB_ADAPTER) { - case 'mysql': - $sQuery = 'CREATE TABLE IF NOT EXISTS `' . $sTableName . '` ('; - if ($bDefaultFields) { - $sQuery .= "`APP_UID` VARCHAR(32) NOT NULL DEFAULT '',`APP_NUMBER` INT NOT NULL,"; - if ($sType == 'GRID') { - $sQuery .= "`ROW` INT NOT NULL,"; - } - } - foreach ($aFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '0',"; - break; - case 'char': - $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '',"; - break; - case 'text': - $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " ,"; - break; - case 'date': - $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NULL,"; - break; - } - } - if ($bDefaultFields) { - $sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) '; - } - $sQuery .= ' DEFAULT CHARSET=utf8;'; - $rs = $stmt->executeQuery( $sQuery ); - break; + //private $sPrefix = 'REP_'; + private $sPrefix = ''; - case 'mssql': - $sQuery = 'CREATE TABLE [' . $sTableName . '] ('; - if ($bDefaultFields) { - $sQuery .= "[APP_UID] VARCHAR(32) NOT NULL DEFAULT '', [APP_NUMBER] INT NOT NULL,"; - if ($sType == 'GRID') { - $sQuery .= "[ROW] INT NOT NULL,"; - } - } - foreach ($aFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '0',"; - break; - case 'char': - $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',"; - break; - case 'text': - $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',"; - break; - case 'date': - $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NULL,"; - break; - } - } - if ($bDefaultFields) { - $sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) '; - } - else { - $sQuery .= ' '; - } - - $rs = $stmt->executeQuery( $sQuery ); - break; - - } + /** + * Function deleteAllReportVars + * This function delete all reports + * + * @access public + * @param string $$sRepTabUid + * @return void + */ + public public function deleteAllReportVars ($sRepTabUid = '') + { + try { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); + ReportVarPeer::doDelete( $oCriteria ); + } catch (Exception $oError) { + throw ($oError); + } } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Function populateTable - * This Function fills the table - * @access public - * @param string $sTableName Table name - * @param string $sConnection Connection name - * @param string $sType - * @param array $aFields - * @param string $sProcessUid - * @param string $sGrid - * @return void - */ - public function populateTable($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $sProcessUid = '', $sGrid = '') - { - $sTableName = $this->sPrefix . $sTableName; - //we have to do the propel connection - $PropelDatabase=$this->chooseDB($sConnection); - $con = Propel::getConnection($PropelDatabase); - $stmt = $con->createStatement(); - if ($sType == 'GRID') { - $aAux = explode('-', $sGrid); - $sGrid = $aAux[0]; - } - try { - switch (DB_ADAPTER) { - case 'mysql': - //select cases for this Process, ordered by APP_NUMBER - $oCriteria = new Criteria('workflow'); - $oCriteria->add(ApplicationPeer::PRO_UID, $sProcessUid); - $oCriteria->addAscendingOrderByColumn(ApplicationPeer::APP_NUMBER); - $oDataset = ApplicationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aData = unserialize($aRow['APP_DATA']); - //delete previous record from this report table ( previous records in case this is a grid ) - $deleteSql = 'DELETE FROM `' . $sTableName . "` WHERE APP_UID = '" . $aRow['APP_UID'] . "'"; - $rsDel = $stmt->executeQuery( $deleteSql ); - if ($sType == 'NORMAL') { - $sQuery = 'INSERT INTO `' . $sTableName . '` ('; - $sQuery .= '`APP_UID`,`APP_NUMBER`'; - foreach ($aFields as $aField) { - $sQuery .= ',`' . $aField['sFieldName'] . '`'; - } - $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER']; - foreach ($aFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= ',' . (isset($aData[$aField['sFieldName']]) ? (float)str_replace(',', '', $aData[$aField['sFieldName']]) : '0'); + + /** + * Function prepareQuery + * This function removes the table + * + * @access public + * @param string $sTableName Table name + * @param string $sConnection Conexion + * @return void + */ + public function dropTable ($sTableName, $sConnection = 'report') + { + $sTableName = $this->sPrefix . $sTableName; + //we have to do the propel connection + $PropelDatabase = $this->chooseDB( $sConnection ); + $con = Propel::getConnection( $PropelDatabase ); + $stmt = $con->createStatement(); + try { + switch (DB_ADAPTER) { + case 'mysql': + $rs = $stmt->executeQuery( 'DROP TABLE IF EXISTS `' . $sTableName . '`' ); break; - case 'char': - case 'text': - if (!isset($aData[$aField['sFieldName']])) { - $aData[$aField['sFieldName']] = ''; - } - $sQuery .= ",'" . (isset($aData[$aField['sFieldName']]) ? mysql_real_escape_string($aData[$aField['sFieldName']]) : '') . "'"; + case 'mssql': + $rs = $stmt->executeQuery( "IF OBJECT_ID (N'" . $sTableName . "', N'U') IS NOT NULL + DROP TABLE [" . $sTableName . "]" ); break; - case 'date': - $value = (isset($aData[$aField['sFieldName']]) && trim($aData[$aField['sFieldName']])) != '' ? "'" . $aData[$aField['sFieldName']] . "'" : 'NULL'; - $sQuery .= "," . $value; - break; - } - } - $sQuery .= ')'; - $rs = $stmt->executeQuery( $sQuery ); } - else { - if (isset($aData[$sGrid])) { - foreach ($aData[$sGrid] as $iRow => $aGridRow) { - $sQuery = 'INSERT INTO `' . $sTableName . '` ('; - $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; - foreach ($aFields as $aField) { - $sQuery .= ',`' . $aField['sFieldName'] . '`'; - } - $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER'] . ',' . $iRow; - foreach ($aFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0'); - break; - case 'char': - case 'text': - if (!isset($aGridRow[$aField['sFieldName']])) { - $aGridRow[$aField['sFieldName']] = ''; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Function createTable + * This Function creates the table + * + * @access public + * @param string $sTableName Table name + * @param string $sConnection Connection name + * @param string $sType + * @param array $aFields + * @param string $bDefaultFields + * @return void + */ + public function createTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $bDefaultFields = true) + { + $sTableName = $this->sPrefix . $sTableName; + //we have to do the propel connection + $PropelDatabase = $this->chooseDB( $sConnection ); + $con = Propel::getConnection( $PropelDatabase ); + $stmt = $con->createStatement(); + try { + switch (DB_ADAPTER) { + case 'mysql': + $sQuery = 'CREATE TABLE IF NOT EXISTS `' . $sTableName . '` ('; + if ($bDefaultFields) { + $sQuery .= "`APP_UID` VARCHAR(32) NOT NULL DEFAULT '',`APP_NUMBER` INT NOT NULL,"; + if ($sType == 'GRID') { + $sQuery .= "`ROW` INT NOT NULL,"; } - $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'"; - break; - case 'date': - $value = (isset($aGridRow[$aField['sFieldName']]) && trim($aGridRow[$aField['sFieldName']])) != '' ? "'" . $aGridRow[$aField['sFieldName']] . "'" : 'NULL'; - $sQuery .= "," . $value; - break; } - } - $sQuery .= ')'; - $rs = $stmt->executeQuery( $sQuery ); - } - } - } - $oDataset->next(); - } - break; - - /** - * For SQLServer code - */ - case 'mssql': - $oCriteria = new Criteria('workflow'); - $oCriteria->add(ApplicationPeer::PRO_UID, $sProcessUid); - $oCriteria->addAscendingOrderByColumn(ApplicationPeer::APP_NUMBER); - $oDataset = ApplicationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aData = unserialize($aRow['APP_DATA']); - mysql_query('DELETE FROM [' . $sTableName . "] WHERE APP_UID = '" . $aRow['APP_UID'] . "'"); - if ($sType == 'NORMAL') { - $sQuery = 'INSERT INTO [' . $sTableName . '] ('; - $sQuery .= '[APP_UID],[APP_NUMBER]'; - foreach ($aFields as $aField) { - $sQuery .= ',[' . $aField['sFieldName'] . ']'; - } - $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER']; - foreach ($aFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= ',' . (isset($aData[$aField['sFieldName']]) ? (float)str_replace(',', '', $aData[$aField['sFieldName']]) : '0'); - break; - case 'char': - case 'text': - if (!isset($aData[$aField['sFieldName']])) { - $aData[$aField['sFieldName']] = ''; - } - $sQuery .= ",'" . (isset($aData[$aField['sFieldName']]) ? mysql_real_escape_string($aData[$aField['sFieldName']]) : '') . "'"; - break; - case 'date': - $sQuery .= ",'" . (isset($aData[$aField['sFieldName']]) ? $aData[$aField['sFieldName']] : '') . "'"; - break; - } - } - $sQuery .= ')'; - $rs = $stmt->executeQuery( $sQuery ); - } - else { - if (isset($aData[$sGrid])) { - foreach ($aData[$sGrid] as $iRow => $aGridRow) { - $sQuery = 'INSERT INTO [' . $sTableName . '] ('; - $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; foreach ($aFields as $aField) { - $sQuery .= ',[' . $aField['sFieldName'] . ']'; + switch ($aField['sType']) { + case 'number': + $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '0',"; + break; + case 'char': + $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '',"; + break; + case 'text': + $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " ,"; + break; + case 'date': + $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NULL,"; + break; + } } - $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER'] . ',' . $iRow; - foreach ($aFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0'); - break; - case 'char': - case 'text': - if (!isset($aGridRow[$aField['sFieldName']])) { - $aGridRow[$aField['sFieldName']] = ''; - } - $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'"; - break; - case 'date': - $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? $aGridRow[$aField['sFieldName']] : '') . "'"; - break; - } + if ($bDefaultFields) { + $sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) '; } - $sQuery .= ')'; + $sQuery .= ' DEFAULT CHARSET=utf8;'; $rs = $stmt->executeQuery( $sQuery ); - } - } - } - $oDataset->next(); - } - break; - - } - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Function getTableVars - * @access public - * @param string $sRepTabUid - * @param boolean $bWhitType - * @return void - */ - public function getTableVars($sRepTabUid, $bWhitType = false) - { - try { - $oCriteria = new Criteria('workflow'); - $oCriteria->add(ReportVarPeer::REP_TAB_UID, $sRepTabUid); - $oDataset = ReportVarPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - $aVars = array(); - $aImportedVars = array();//This array will help to control if the variable already exist - while ($aRow = $oDataset->getRow()) { - if ($bWhitType) { - if (!in_array($aRow['REP_VAR_NAME'], $aImportedVars)) { - $aImportedVars[]=$aRow['REP_VAR_NAME']; - $aVars[] = array('sFieldName' => $aRow['REP_VAR_NAME'], 'sType' => $aRow['REP_VAR_TYPE']); - } - }else { - $aVars[] = $aRow['REP_VAR_NAME']; - } - $oDataset->next(); - } - return $aVars; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Function deleteReportTable - * This Function deletes report table - * @access public - * @param string $sRepTabUid - * @return void - */ - public function deleteReportTable($sRepTabUid) - { - try { - $oReportTable = new ReportTable(); - $aFields = $oReportTable->load($sRepTabUid); - if(!(empty($aFields))){ - $this->dropTable($aFields['REP_TAB_NAME'], $aFields['REP_TAB_CONNECTION']); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(ReportVarPeer::REP_TAB_UID, $sRepTabUid); - $oDataset = ReportVarPeer::doDelete($oCriteria); - $oReportTable->remove($sRepTabUid); - } - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Function getSplitDate - * This function gets the split date - * @access public - * @param date $date - * @param string $mask - * @return array - */ - function getSplitDate($date, $mask) - { - $sw1 = false; - for($i=0; $i<3; $i++){ - $item = substr($mask, $i*2, 1); - switch($item){ - case 'Y': - switch($i){ - case 0: - $d1 = substr($date, 0, 4); - break; - case 1: - $d1 = substr($date, 3, 4); - break; - case 2: - $d1 = substr($date, 6, 4); - break; - } - $sw1 = true; - break; - case 'y': - switch($i){ - case 0: - $d1 = substr($date, 0, 2); - break; - case 1: - $d1 = substr($date, 3, 2); - break; - case 2: - $d1 = substr($date, 6, 2); - break; - } - break; - case 'm': - switch($i){ - case 0: - $d2 = substr($date, 0, 2); - break; - case 1: - $d2 = ($sw1)? substr($date, 5, 2): substr($date, 3, 2); - break; - case 2: - $d2 = ($sw1)? substr($date, 8, 2): substr($date, 5, 2); - break; - } - break; - case 'd': - switch($i){ - case 0: - $d3 = substr($date, 0, 2); - break; - case 1: - $d3 = ($sw1)? substr($date, 5, 2): substr($date, 3, 2); - break; - case 2: - $d3 = ($sw1)? substr($date, 8, 2): substr($date, 5, 2); - break; - } - break; - } - } - return Array(isset($d1)?$d1:'', isset($d2)?$d2:'', isset($d3)?$d3:''); - } - - /** - * Function getFormatDate - * This function returns the date formated - * @access public - * @param date $sDate - * @param date $sMask - * @return date - */ - function getFormatDate($sDate, $sMask) - { - //print $sDate." *** ". $sMask."
"; - $dateTime = explode(" ",$sDate); //To accept the Hour part - $aDate = explode ( '-', str_replace("/", "-", $dateTime[0]) ); - $bResult = true; - foreach($aDate as $sDate){ - if( !is_numeric($sDate) ){ - $bResult = false; - break; - } - } - if( $sMask != '' ){ - $aDate = $this->getSplitDate($dateTime[0], $sMask); - $aDate[0] = ($aDate[0] == '')? date('Y'): $aDate[0]; - $aDate[1] = ($aDate[1] == '')? date('m'): $aDate[1]; - $aDate[2] = ($aDate[2] == '')? date('d'): $aDate[2]; - if( checkdate($aDate[1], $aDate[2], $aDate[0]) ){ - } else { - return false; - } - } - $sDateC=''; - for($i=0;$i< count($aDate);$i++){ - $sDateC.= (($i==0)?"":"-") .$aDate[$i]; - } - return ($sDateC); - } - - /** - * Function updateTables - * This function updated the Report Tables - * @access public - * @param string $sProcessUid - * @param string $sApplicationUid - * @param string $iApplicationNumber - * @param string $aFields - * @return void - */ - public function updateTables($sProcessUid, $sApplicationUid, $iApplicationNumber, $aFields) - { - try { - //get all Active Report Tables - $oCriteria = new Criteria('workflow'); - $oCriteria->add(ReportTablePeer::PRO_UID, $sProcessUid); - $oCriteria->add(ReportTablePeer::REP_TAB_STATUS, 'ACTIVE'); - $oDataset = ReportTablePeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - $aVars = array(); - while ($aRow = $oDataset->getRow()) { - $aRow['REP_TAB_NAME'] = $this->sPrefix . $aRow['REP_TAB_NAME']; - $PropelDatabase=$this->chooseDB($aRow['REP_TAB_CONNECTION']); - $con = Propel::getConnection($PropelDatabase); - $stmt = $con->createStatement(); - switch (DB_ADAPTER) { + break; - case 'mysql': - $aTableFields = $this->getTableVars($aRow['REP_TAB_UID'], true); - if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { - $sqlExists = "SELECT * FROM `" . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; - $rsExists = $stmt->executeQuery( $sqlExists, ResultSet::FETCHMODE_ASSOC); - $rsExists->next(); - $aRow2 = $rsExists->getRow(); - - if ( is_array( $aRow2) ) { - $sQuery = 'UPDATE `' . $aRow['REP_TAB_NAME'] . '` SET '; - foreach ($aTableFields as $aField) { - $sQuery .= '`' . $aField['sFieldName'] . '` = '; - switch ($aField['sType']) { - case 'number': - $sQuery .= (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0') . ','; - break; - case 'char': - case 'text': - if (!isset($aFields[$aField['sFieldName']])) { - $aFields[$aField['sFieldName']] = ''; - } - $sQuery .= "'" . (isset($aFields[$aField['sFieldName']]) ? mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . "',"; - break; - case 'date': - $mysqlDate = (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : '') ; - if ($mysqlDate!='') { - $mysqlDate = str_replace('/', '-', $mysqlDate); - $mysqlDate = date( 'Y-m-d', strtotime($mysqlDate) ); - } - $value = trim($mysqlDate) != '' ? "'".$mysqlDate."'" : 'NULL'; - $sQuery .= $value . ","; - break; - } - } - $sQuery = substr($sQuery, 0, -1); - $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; - } - else { - $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; - $sQuery .= '`APP_UID`,`APP_NUMBER`'; - foreach ($aTableFields as $aField) { - $sQuery .= ',`' . $aField['sFieldName'] . '`'; - } - $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber; - foreach ($aTableFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= ',' . (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0'); - break; - case 'char': - case 'text': - if (!isset($aFields[$aField['sFieldName']])) { - $aFields[$aField['sFieldName']] = ''; - } - $sQuery .= ",'" . (isset($aFields[$aField['sFieldName']]) ? mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . "'"; - break; - case 'date': - $mysqlDate = ( isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : '' ); - if ($mysqlDate!='') { - $mysqlDate = str_replace( '/', '-', $mysqlDate ); - $mysqlDate = date( 'Y-m-d', strtotime($mysqlDate) ); - } - $value = trim($mysqlDate) != '' ? "'".$mysqlDate."'" : 'NULL'; - $sQuery .= "," . $value; - break; - } - } - $sQuery .= ')'; - } - $rs = $stmt->executeQuery( $sQuery ); - } - else { - //remove old rows from database - $sqlDelete = 'DELETE FROM `' . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; - $rsDelete = $stmt->executeQuery( $sqlDelete ); - - $aAux = explode('-', $aRow['REP_TAB_GRID']); - if (isset($aFields[$aAux[0]])) { - foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { - $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; - $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; - foreach ($aTableFields as $aField) { - $sQuery .= ',`' . $aField['sFieldName'] . '`'; - } - $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber . ',' . $iRow; - foreach ($aTableFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0'); - break; - case 'char': - case 'text': - if (!isset($aGridRow[$aField['sFieldName']])) { - $aGridRow[$aField['sFieldName']] = ''; - } - $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'"; - break; - case 'date': - $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? $aGridRow[$aField['sFieldName']] : '') . "'"; - break; - } - } - $sQuery .= ')'; - $rs =$stmt->executeQuery( $sQuery ); - } - } - } - break; - - /** - * For SQLServer code - */ - case 'mssql': - $aTableFields = $this->getTableVars($aRow['REP_TAB_UID'], true); - if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { - $oDataset2 = mssql_query("SELECT * FROM [" . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'"); - if ($aRow2 = mssql_fetch_row($oDataset2)) { - $sQuery = 'UPDATE [' . $aRow['REP_TAB_NAME'] . '] SET '; - foreach ($aTableFields as $aField) { - $sQuery .= '[' . $aField['sFieldName'] . '] = '; - switch ($aField['sType']) { - case 'number': - $sQuery .= (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0') . ','; - break; - case 'char': - case 'text': - if (!isset($aFields[$aField['sFieldName']])) { - $aFields[$aField['sFieldName']] = ''; - } - $sQuery .= "'" . (isset($aFields[$aField['sFieldName']]) ? mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . "',"; - break; - case 'date': - $sQuery .= "'" . (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : '') . "',"; - break; - } - } - $sQuery = substr($sQuery, 0, -1); - $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; - } - else { - $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; - $sQuery .= '[APP_UID],[APP_NUMBER]'; - foreach ($aTableFields as $aField) { - $sQuery .= ',[' . $aField['sFieldName'] . ']'; - } - $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber; - foreach ($aTableFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= ',' . (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0'); - break; - case 'char': - case 'text': - if (!isset($aFields[$aField['sFieldName']])) { - $aFields[$aField['sFieldName']] = ''; - } - $sQuery .= ",'" . (isset($aFields[$aField['sFieldName']]) ? mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . "'"; - break; - case 'date': - $sQuery .= ",'" . (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : '') . "'"; - break; - } - } - $sQuery .= ')'; - } - $rs = $stmt->executeQuery( $sQuery ); - } - else { - mysql_query('DELETE FROM [' . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'"); - $aAux = explode('-', $aRow['REP_TAB_GRID']); - if (isset($aFields[$aAux[0]])) { - foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { - $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; - $sQuery .= '[APP_UID],[APP_NUMBER],[ROW]'; - foreach ($aTableFields as $aField) { - $sQuery .= ',[' . $aField['sFieldName'] . ']'; - } - $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber . ',' . $iRow; - foreach ($aTableFields as $aField) { - switch ($aField['sType']) { - case 'number': - $sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0'); - break; - case 'char': - case 'text': - if (!isset($aGridRow[$aField['sFieldName']])) { - $aGridRow[$aField['sFieldName']] = ''; + case 'mssql': + $sQuery = 'CREATE TABLE [' . $sTableName . '] ('; + if ($bDefaultFields) { + $sQuery .= "[APP_UID] VARCHAR(32) NOT NULL DEFAULT '', [APP_NUMBER] INT NOT NULL,"; + if ($sType == 'GRID') { + $sQuery .= "[ROW] INT NOT NULL,"; } - $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'"; - break; - case 'date': - $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? $aGridRow[$aField['sFieldName']] : '') . "'"; - break; } - } - $sQuery .= ')'; - $rs =$stmt->executeQuery( $sQuery ); - } - } + foreach ($aFields as $aField) { + switch ($aField['sType']) { + case 'number': + $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '0',"; + break; + case 'char': + $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',"; + break; + case 'text': + $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',"; + break; + case 'date': + $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NULL,"; + break; + } + } + if ($bDefaultFields) { + $sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) '; + } else { + $sQuery .= ' '; + } + + $rs = $stmt->executeQuery( $sQuery ); + break; + } - break; - - } - $oDataset->next(); + } catch (Exception $oError) { + throw ($oError); + } } - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Function tableExist - * Check if table exists - * @access public - * @return boolean - */ - function tableExist() - { - /* + + /** + * Function populateTable + * This Function fills the table + * + * @access public + * @param string $sTableName Table name + * @param string $sConnection Connection name + * @param string $sType + * @param array $aFields + * @param string $sProcessUid + * @param string $sGrid + * @return void + */ + public function populateTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $sProcessUid = '', $sGrid = '') + { + $sTableName = $this->sPrefix . $sTableName; + //we have to do the propel connection + $PropelDatabase = $this->chooseDB( $sConnection ); + $con = Propel::getConnection( $PropelDatabase ); + $stmt = $con->createStatement(); + if ($sType == 'GRID') { + $aAux = explode( '-', $sGrid ); + $sGrid = $aAux[0]; + } + try { + switch (DB_ADAPTER) { + case 'mysql': + //select cases for this Process, ordered by APP_NUMBER + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid ); + $oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER ); + $oDataset = ApplicationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aData = unserialize( $aRow['APP_DATA'] ); + //delete previous record from this report table ( previous records in case this is a grid ) + $deleteSql = 'DELETE FROM `' . $sTableName . "` WHERE APP_UID = '" . $aRow['APP_UID'] . "'"; + $rsDel = $stmt->executeQuery( $deleteSql ); + if ($sType == 'NORMAL') { + $sQuery = 'INSERT INTO `' . $sTableName . '` ('; + $sQuery .= '`APP_UID`,`APP_NUMBER`'; + foreach ($aFields as $aField) { + $sQuery .= ',`' . $aField['sFieldName'] . '`'; + } + $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER']; + foreach ($aFields as $aField) { + switch ($aField['sType']) { + case 'number': + $sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0'); + break; + case 'char': + case 'text': + if (! isset( $aData[$aField['sFieldName']] )) { + $aData[$aField['sFieldName']] = ''; + } + $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'"; + break; + case 'date': + $value = (isset( $aData[$aField['sFieldName']] ) && trim( $aData[$aField['sFieldName']] )) != '' ? "'" . $aData[$aField['sFieldName']] . "'" : 'NULL'; + $sQuery .= "," . $value; + break; + } + } + $sQuery .= ')'; + $rs = $stmt->executeQuery( $sQuery ); + } else { + if (isset( $aData[$sGrid] )) { + foreach ($aData[$sGrid] as $iRow => $aGridRow) { + $sQuery = 'INSERT INTO `' . $sTableName . '` ('; + $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; + foreach ($aFields as $aField) { + $sQuery .= ',`' . $aField['sFieldName'] . '`'; + } + $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow; + foreach ($aFields as $aField) { + switch ($aField['sType']) { + case 'number': + $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); + break; + case 'char': + case 'text': + if (! isset( $aGridRow[$aField['sFieldName']] )) { + $aGridRow[$aField['sFieldName']] = ''; + } + $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; + break; + case 'date': + $value = (isset( $aGridRow[$aField['sFieldName']] ) && trim( $aGridRow[$aField['sFieldName']] )) != '' ? "'" . $aGridRow[$aField['sFieldName']] . "'" : 'NULL'; + $sQuery .= "," . $value; + break; + } + } + $sQuery .= ')'; + $rs = $stmt->executeQuery( $sQuery ); + } + } + } + $oDataset->next(); + } + break; + + /** + * For SQLServer code + */ + case 'mssql': + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid ); + $oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER ); + $oDataset = ApplicationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aData = unserialize( $aRow['APP_DATA'] ); + mysql_query( 'DELETE FROM [' . $sTableName . "] WHERE APP_UID = '" . $aRow['APP_UID'] . "'" ); + if ($sType == 'NORMAL') { + $sQuery = 'INSERT INTO [' . $sTableName . '] ('; + $sQuery .= '[APP_UID],[APP_NUMBER]'; + foreach ($aFields as $aField) { + $sQuery .= ',[' . $aField['sFieldName'] . ']'; + } + $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER']; + foreach ($aFields as $aField) { + switch ($aField['sType']) { + case 'number': + $sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0'); + break; + case 'char': + case 'text': + if (! isset( $aData[$aField['sFieldName']] )) { + $aData[$aField['sFieldName']] = ''; + } + $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'"; + break; + case 'date': + $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? $aData[$aField['sFieldName']] : '') . "'"; + break; + } + } + $sQuery .= ')'; + $rs = $stmt->executeQuery( $sQuery ); + } else { + if (isset( $aData[$sGrid] )) { + foreach ($aData[$sGrid] as $iRow => $aGridRow) { + $sQuery = 'INSERT INTO [' . $sTableName . '] ('; + $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; + foreach ($aFields as $aField) { + $sQuery .= ',[' . $aField['sFieldName'] . ']'; + } + $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow; + foreach ($aFields as $aField) { + switch ($aField['sType']) { + case 'number': + $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); + break; + case 'char': + case 'text': + if (! isset( $aGridRow[$aField['sFieldName']] )) { + $aGridRow[$aField['sFieldName']] = ''; + } + $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; + break; + case 'date': + $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; + break; + } + } + $sQuery .= ')'; + $rs = $stmt->executeQuery( $sQuery ); + } + } + } + $oDataset->next(); + } + break; + + } + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Function getTableVars + * + * @access public + * @param string $sRepTabUid + * @param boolean $bWhitType + * @return void + */ + public function getTableVars ($sRepTabUid, $bWhitType = false) + { + try { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); + $oDataset = ReportVarPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aVars = array (); + $aImportedVars = array (); //This array will help to control if the variable already exist + while ($aRow = $oDataset->getRow()) { + if ($bWhitType) { + if (! in_array( $aRow['REP_VAR_NAME'], $aImportedVars )) { + $aImportedVars[] = $aRow['REP_VAR_NAME']; + $aVars[] = array ('sFieldName' => $aRow['REP_VAR_NAME'],'sType' => $aRow['REP_VAR_TYPE'] + ); + } + } else { + $aVars[] = $aRow['REP_VAR_NAME']; + } + $oDataset->next(); + } + return $aVars; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Function deleteReportTable + * This Function deletes report table + * + * @access public + * @param string $sRepTabUid + * @return void + */ + public function deleteReportTable ($sRepTabUid) + { + try { + $oReportTable = new ReportTable(); + $aFields = $oReportTable->load( $sRepTabUid ); + if (! (empty( $aFields ))) { + $this->dropTable( $aFields['REP_TAB_NAME'], $aFields['REP_TAB_CONNECTION'] ); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); + $oDataset = ReportVarPeer::doDelete( $oCriteria ); + $oReportTable->remove( $sRepTabUid ); + } + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Function getSplitDate + * This function gets the split date + * + * @access public + * @param date $date + * @param string $mask + * @return array + */ + public function getSplitDate ($date, $mask) + { + $sw1 = false; + for ($i = 0; $i < 3; $i ++) { + $item = substr( $mask, $i * 2, 1 ); + switch ($item) { + case 'Y': + switch ($i) { + case 0: + $d1 = substr( $date, 0, 4 ); + break; + case 1: + $d1 = substr( $date, 3, 4 ); + break; + case 2: + $d1 = substr( $date, 6, 4 ); + break; + } + $sw1 = true; + break; + case 'y': + switch ($i) { + case 0: + $d1 = substr( $date, 0, 2 ); + break; + case 1: + $d1 = substr( $date, 3, 2 ); + break; + case 2: + $d1 = substr( $date, 6, 2 ); + break; + } + break; + case 'm': + switch ($i) { + case 0: + $d2 = substr( $date, 0, 2 ); + break; + case 1: + $d2 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 ); + break; + case 2: + $d2 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 ); + break; + } + break; + case 'd': + switch ($i) { + case 0: + $d3 = substr( $date, 0, 2 ); + break; + case 1: + $d3 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 ); + break; + case 2: + $d3 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 ); + break; + } + break; + } + } + return Array (isset( $d1 ) ? $d1 : '',isset( $d2 ) ? $d2 : '',isset( $d3 ) ? $d3 : '' + ); + } + + /** + * Function getFormatDate + * This function returns the date formated + * + * @access public + * @param date $sDate + * @param date $sMask + * @return date + */ + public function getFormatDate ($sDate, $sMask) + { + //print $sDate." *** ". $sMask."
"; + $dateTime = explode( " ", $sDate ); //To accept the Hour part + $aDate = explode( '-', str_replace( "/", "-", $dateTime[0] ) ); + $bResult = true; + foreach ($aDate as $sDate) { + if (! is_numeric( $sDate )) { + $bResult = false; + break; + } + } + if ($sMask != '') { + $aDate = $this->getSplitDate( $dateTime[0], $sMask ); + $aDate[0] = ($aDate[0] == '') ? date( 'Y' ) : $aDate[0]; + $aDate[1] = ($aDate[1] == '') ? date( 'm' ) : $aDate[1]; + $aDate[2] = ($aDate[2] == '') ? date( 'd' ) : $aDate[2]; + if (checkdate( $aDate[1], $aDate[2], $aDate[0] )) { + } else { + return false; + } + } + $sDateC = ''; + for ($i = 0; $i < count( $aDate ); $i ++) { + $sDateC .= (($i == 0) ? "" : "-") . $aDate[$i]; + } + return ($sDateC); + } + + /** + * Function updateTables + * This function updated the Report Tables + * + * @access public + * @param string $sProcessUid + * @param string $sApplicationUid + * @param string $iApplicationNumber + * @param string $aFields + * @return void + */ + public function updateTables ($sProcessUid, $sApplicationUid, $iApplicationNumber, $aFields) + { + try { + //get all Active Report Tables + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( ReportTablePeer::PRO_UID, $sProcessUid ); + $oCriteria->add( ReportTablePeer::REP_TAB_STATUS, 'ACTIVE' ); + $oDataset = ReportTablePeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aVars = array (); + while ($aRow = $oDataset->getRow()) { + $aRow['REP_TAB_NAME'] = $this->sPrefix . $aRow['REP_TAB_NAME']; + $PropelDatabase = $this->chooseDB( $aRow['REP_TAB_CONNECTION'] ); + $con = Propel::getConnection( $PropelDatabase ); + $stmt = $con->createStatement(); + switch (DB_ADAPTER) { + + case 'mysql': + $aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true ); + if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { + $sqlExists = "SELECT * FROM `" . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; + $rsExists = $stmt->executeQuery( $sqlExists, ResultSet::FETCHMODE_ASSOC ); + $rsExists->next(); + $aRow2 = $rsExists->getRow(); + + if (is_array( $aRow2 )) { + $sQuery = 'UPDATE `' . $aRow['REP_TAB_NAME'] . '` SET '; + foreach ($aTableFields as $aField) { + $sQuery .= '`' . $aField['sFieldName'] . '` = '; + switch ($aField['sType']) { + case 'number': + $sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ','; + break; + case 'char': + case 'text': + if (! isset( $aFields[$aField['sFieldName']] )) { + $aFields[$aField['sFieldName']] = ''; + } + $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "',"; + break; + case 'date': + $mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : ''); + if ($mysqlDate != '') { + $mysqlDate = str_replace( '/', '-', $mysqlDate ); + $mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) ); + } + $value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL'; + $sQuery .= $value . ","; + break; + } + } + $sQuery = substr( $sQuery, 0, - 1 ); + $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; + } else { + $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; + $sQuery .= '`APP_UID`,`APP_NUMBER`'; + foreach ($aTableFields as $aField) { + $sQuery .= ',`' . $aField['sFieldName'] . '`'; + } + $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber; + foreach ($aTableFields as $aField) { + switch ($aField['sType']) { + case 'number': + $sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0'); + break; + case 'char': + case 'text': + if (! isset( $aFields[$aField['sFieldName']] )) { + $aFields[$aField['sFieldName']] = ''; + } + $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'"; + break; + case 'date': + $mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : ''); + if ($mysqlDate != '') { + $mysqlDate = str_replace( '/', '-', $mysqlDate ); + $mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) ); + } + $value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL'; + $sQuery .= "," . $value; + break; + } + } + $sQuery .= ')'; + } + $rs = $stmt->executeQuery( $sQuery ); + } else { + //remove old rows from database + $sqlDelete = 'DELETE FROM `' . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; + $rsDelete = $stmt->executeQuery( $sqlDelete ); + + $aAux = explode( '-', $aRow['REP_TAB_GRID'] ); + if (isset( $aFields[$aAux[0]] )) { + foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { + $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; + $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; + foreach ($aTableFields as $aField) { + $sQuery .= ',`' . $aField['sFieldName'] . '`'; + } + $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow; + foreach ($aTableFields as $aField) { + switch ($aField['sType']) { + case 'number': + $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); + break; + case 'char': + case 'text': + if (! isset( $aGridRow[$aField['sFieldName']] )) { + $aGridRow[$aField['sFieldName']] = ''; + } + $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; + break; + case 'date': + $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; + break; + } + } + $sQuery .= ')'; + $rs = $stmt->executeQuery( $sQuery ); + } + } + } + break; + + /** + * For SQLServer code + */ + case 'mssql': + $aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true ); + if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { + $oDataset2 = mssql_query( "SELECT * FROM [" . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" ); + if ($aRow2 = mssql_fetch_row( $oDataset2 )) { + $sQuery = 'UPDATE [' . $aRow['REP_TAB_NAME'] . '] SET '; + foreach ($aTableFields as $aField) { + $sQuery .= '[' . $aField['sFieldName'] . '] = '; + switch ($aField['sType']) { + case 'number': + $sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ','; + break; + case 'char': + case 'text': + if (! isset( $aFields[$aField['sFieldName']] )) { + $aFields[$aField['sFieldName']] = ''; + } + $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "',"; + break; + case 'date': + $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "',"; + break; + } + } + $sQuery = substr( $sQuery, 0, - 1 ); + $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; + } else { + $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; + $sQuery .= '[APP_UID],[APP_NUMBER]'; + foreach ($aTableFields as $aField) { + $sQuery .= ',[' . $aField['sFieldName'] . ']'; + } + $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber; + foreach ($aTableFields as $aField) { + switch ($aField['sType']) { + case 'number': + $sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0'); + break; + case 'char': + case 'text': + if (! isset( $aFields[$aField['sFieldName']] )) { + $aFields[$aField['sFieldName']] = ''; + } + $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'"; + break; + case 'date': + $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "'"; + break; + } + } + $sQuery .= ')'; + } + $rs = $stmt->executeQuery( $sQuery ); + } else { + mysql_query( 'DELETE FROM [' . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" ); + $aAux = explode( '-', $aRow['REP_TAB_GRID'] ); + if (isset( $aFields[$aAux[0]] )) { + foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { + $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; + $sQuery .= '[APP_UID],[APP_NUMBER],[ROW]'; + foreach ($aTableFields as $aField) { + $sQuery .= ',[' . $aField['sFieldName'] . ']'; + } + $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow; + foreach ($aTableFields as $aField) { + switch ($aField['sType']) { + case 'number': + $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); + break; + case 'char': + case 'text': + if (! isset( $aGridRow[$aField['sFieldName']] )) { + $aGridRow[$aField['sFieldName']] = ''; + } + $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; + break; + case 'date': + $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; + break; + } + } + $sQuery .= ')'; + $rs = $stmt->executeQuery( $sQuery ); + } + } + } + break; + + } + $oDataset->next(); + } + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Function tableExist + * Check if table exists + * + * @access public + * @return boolean + */ + public function tableExist () + { + /* $bExists = true; $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; */ - $bExists = true; - $sDataBase = 'database_' . strtolower(DB_ADAPTER); - if(G::LoadSystemExist($sDataBase)){ - G::LoadSystem($sDataBase); - $oDataBase = new database(); - $bExists = $oDataBase->reportTableExist(); + $bExists = true; + $sDataBase = 'database_' . strtolower( DB_ADAPTER ); + if (G::LoadSystemExist( $sDataBase )) { + G::LoadSystem( $sDataBase ); + $oDataBase = new database(); + $bExists = $oDataBase->reportTableExist(); + } + return $bExists; + } + + /** + * Function chooseDB + * Choose the database to connect + * + * @access public + * @param string $TabConnectionk + * @return string + */ + public function chooseDB ($TabConnectionk) + { + $repTabConnection = trim( strtoupper( $TabConnectionk ) ); + $PropelDatabase = 'rp'; + if ($repTabConnection == '' || $repTabConnection == 'REPORT') + $PropelDatabase = 'rp'; + if ($repTabConnection == 'RBAC') + $PropelDatabase = 'rbac'; + if ($repTabConnection == 'WF') + $PropelDatabase = 'workflow'; + return ($PropelDatabase); } - return $bExists; - } - - /** - * Function chooseDB - * Choose the database to connect - * @access public - * @param string $TabConnectionk - * @return string - */ - function chooseDB($TabConnectionk) - { - $repTabConnection = trim( strtoupper( $TabConnectionk ) ); - $PropelDatabase = 'rp'; - if ( $repTabConnection == '' || $repTabConnection == 'REPORT' ) - $PropelDatabase = 'rp'; - if ( $repTabConnection == 'RBAC' ) - $PropelDatabase = 'rbac'; - if ( $repTabConnection == 'WF' ) - $PropelDatabase = 'workflow'; - return ($PropelDatabase); - } } From d73f690e1da12152e172c0de878b2012f934b744 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:21:57 -0400 Subject: [PATCH 04/18] CODE STYLE class.searchIndex.php --- workflow/engine/classes/class.searchIndex.php | 842 +++++++++--------- 1 file changed, 416 insertions(+), 426 deletions(-) diff --git a/workflow/engine/classes/class.searchIndex.php b/workflow/engine/classes/class.searchIndex.php index 26888f28c..16815c66d 100644 --- a/workflow/engine/classes/class.searchIndex.php +++ b/workflow/engine/classes/class.searchIndex.php @@ -1,6 +1,6 @@ solrIsEnabled = $registry->isRegistered('solrEnabled') && - // $registry->get('solrEnabled') == 1; - // $this->solrHost = - // $registry->isRegistered('solrHost')?$registry->get('solrHost'):""; - // } - // else{ - // //use the parameters to initialize class - $this->_solrIsEnabled = $solrIsEnabled; - $this->_solrHost = $solrHost; - // } - } - /** - * Verify if the Solr service is available - * @gearman = false - * @rest = false - * @background = false - * - * no input parameters @param[in] - * - * @param - * [out] bool true if index service is enabled false in other case - */ - public function isEnabled() - { - // require_once (ROOT_PATH . - // '/businessLogic/modules/SearchIndexAccess/Solr.php'); - require_once ('class.solr.php'); - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - return $solr->isEnabled (); - } - - /** - * Get the list of facets in base to the specified query and filter - * @gearman = true - * @rest = false - * @background = false - * - * @param - * [in] Entity_FacetRequest facetRequestEntity Facet request entity - * @param - * [out] array FacetGroup - */ - public function getFacetsList($facetRequestEntity) - { - require_once ('class.solr.php'); - // require_once (ROOT_PATH . - // '/businessLogic/modules/SearchIndexAccess/Solr.php'); - require_once ('entities/FacetGroup.php'); - require_once ('entities/FacetItem.php'); - require_once ('entities/SelectedFacetGroupItem.php'); - require_once ('entities/FacetResult.php'); - - /** - * *************************************************************** - */ - // get array of selected facet groups - $facetRequestEntity->selectedFacetsString = str_replace (',,', ',', $facetRequestEntity->selectedFacetsString); - // remove descriptions of selected facet groups - - $aGroups = explode (',', $facetRequestEntity->selectedFacetsString); - - $aGroups = array_filter ($aGroups); // remove empty items - - $aSelectedFacetGroups = array (); - foreach ($aGroups as $i => $value) { - $gi = explode (':::', $value); - $gr = explode ('::', $gi [0]); - $it = explode ('::', $gi [1]); - - // create string for remove condition - $count = 0; - $removeCondition = str_replace ($value . ',', '', $facetRequestEntity->selectedFacetsString, $count); - if ($count == 0) { - $removeCondition = str_replace ($value, '', $facetRequestEntity->selectedFacetsString, $count); - } - $selectedFacetGroupData = array ( - 'selectedFacetGroupName' => $gr [0], - 'selectedFacetGroupPrintName' => $gr [1], - 'selectedFacetItemName' => $it [0], - 'selectedFacetItemPrintName' => $it [1], - 'selectedFacetRemoveCondition' => $removeCondition - ); - - $aSelectedFacetGroups [] = Entity_SelectedFacetGroupItem::createForRequest ($selectedFacetGroupData); - } - - /** - * *************************************************************** - */ - // convert request to index request - // create filters - $filters = array (); - if (! empty ($aSelectedFacetGroups)) { - // exclude facetFields and facetDates included in filter from the next - // list of facets - foreach ($aSelectedFacetGroups as $value) { - $facetRequestEntity->facetFields = array_diff ($facetRequestEntity->facetFields, array ( - $value->selectedFacetGroupName - )); - $facetRequestEntity->facetDates = array_diff ($facetRequestEntity->facetDates, array ( - $value->selectedFacetGroupName - )); - } - - // $facetFields = array_diff($facetFields, - // $facetInterfaceRequestEntity->selectedFacetGroups); - // $facetDates = array_diff($facetDates, - // $facetInterfaceRequestEntity->selectedFacetGroups); - foreach ($aSelectedFacetGroups as $group) { - $filters [] = $group->selectedFacetGroupName . ':' . urlencode ($group->selectedFacetItemName); - } - } - $facetRequestEntity->filters = $filters; - - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // create list of facets - $facetsList = $solr->getFacetsList ($facetRequestEntity); - - $numFound = $facetsList->response->numFound; - - $facetCounts = $facetsList->facet_counts; - - $facetGroups = array (); - // convert facet fields result to objects - /** - * ********************************************************************* - */ - // include facet field results - $facetFieldsResult = $facetsList->facet_counts->facet_fields; - if (! empty ($facetFieldsResult)) { - foreach ($facetFieldsResult as $facetGroup => $facetvalues) { - if (count ($facetvalues) > 0) // if the group have facets included - { - $data = array ( - 'facetGroupName' => $facetGroup - ); - $data ['facetGroupPrintName'] = $facetGroup; - $data ['facetGroupType'] = 'field'; - $facetItems = array (); - for ($i = 0; $i < count ($facetvalues); $i += 2) { - $dataItem = array (); - $dataItem ['facetName'] = $facetvalues [$i]; - $dataItem ['facetPrintName'] = $facetvalues [$i]; - $dataItem ['facetCount'] = $facetvalues [$i + 1]; - $dataItem ['facetSelectCondition'] = $facetRequestEntity->selectedFacetsString . (empty ($facetRequestEntity->selectedFacetsString) ? '' : ',') . $data ['facetGroupName'] . '::' . $data ['facetGroupPrintName'] . ':::' . $dataItem ['facetName'] . '::' . $dataItem ['facetPrintName']; - $newFacetItem = Entity_FacetItem::createForInsert ($dataItem); - $facetItems [] = $newFacetItem; - } - $data ['facetItems'] = $facetItems; - $newFacetGroup = Entity_FacetGroup::createForInsert ($data); - - $facetGroups [] = $newFacetGroup; - } - } - } - /** - * ********************************************************************* - */ - // include facet date ranges results - $facetDatesResult = $facetsList->facet_counts->facet_dates; - if (! empty ($facetDatesResult)) { - foreach ($facetDatesResult as $facetGroup => $facetvalues) { - if (count ((array)$facetvalues) > 3) // if the group have any facets included - // besides start, end and gap - { - $data = array ( - 'facetGroupName' => $facetGroup - ); - $data ['facetGroupPrintName'] = $facetGroup; - $data ['facetGroupType'] = 'daterange'; - $facetItems = array (); - $facetvalueskeys = array_keys ((array)$facetvalues); - foreach ($facetvalueskeys as $i => $k) { - if ($k != 'gap' && $k != 'start' && $k != 'end') { - $dataItem = array (); - if ($i < count ($facetvalueskeys) - 4) { - - $dataItem ['facetName'] = '[' . $k . '%20TO%20' . $facetvalueskeys [$i + 1] . ']'; - $dataItem ['facetPrintName'] = '[' . $k . '%20TO%20' . $facetvalueskeys [$i + 1] . ']'; - } - else { - // the last group - $dataItem ['facetName'] = '[' . $k . '%20TO%20' . $facetvalues->end . ']'; - $dataItem ['facetPrintName'] = '[' . $k . '%20TO%20' . $facetvalues->end . ']'; - } - - $dataItem ['facetCount'] = $facetvalues->$k; - $dataItem ['facetSelectCondition'] = $facetRequestEntity->selectedFacetsString . (empty ($facetRequestEntity->selectedFacetsString) ? '' : ',') . $data ['facetGroupName'] . '::' . $data ['facetGroupPrintName'] . ':::' . $dataItem ['facetName'] . '::' . $dataItem ['facetPrintName']; - $newFacetItem = Entity_FacetItem::createForInsert ($dataItem); - $facetItems [] = $newFacetItem; - } - } - - $data ['facetItems'] = $facetItems; - $newFacetGroup = Entity_FacetGroup::createForInsert ($data); - - $facetGroups [] = $newFacetGroup; - } - } - } - // TODO:convert facet queries - // ----- - /** - * *************************************************************** - */ - // Create a filter string used in the filter of results of a datatable - $filterText = ''; // the list of selected filters used for filtering result, - // send in ajax - foreach ($aSelectedFacetGroups as $selectedFacetGroup) { - $filterText .= $selectedFacetGroup->selectedFacetGroupName . ':' . urlencode ($selectedFacetGroup->selectedFacetItemName) . ','; - } - $filterText = substr_replace ($filterText, '', - 1); - // $filterText = ($filterText == '')?'':'&filterText='.$filterText; - - /** - * *************************************************************** - */ - // Create result - $dataFacetResult = array ( - 'aFacetGroups' => $facetGroups, - 'aSelectedFacetGroups' => $aSelectedFacetGroups, - 'sFilterText' => $filterText - ); - $facetResult = Entity_FacetResult::createForRequest ($dataFacetResult); - - return $facetResult; - } - - /** - * Get the total number of documents in search server - * @param string $workspace - * @return integer number of documents - * - */ - public function getNumberDocuments($workspace) - { - require_once ('class.solr.php'); - // require_once (ROOT_PATH . - // '/businessLogic/modules/SearchIndexAccess/Solr.php'); - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // create list of facets - $numberDocuments = $solr->getNumberDocuments ($workspace); - - return $numberDocuments; - } - - /** - * Update document Index - * @param SolrUpdateDocumentEntity $solrUpdateDocumentEntity - */ - public function updateIndexDocument($solrUpdateDocumentEntity) - { - G::LoadClass ('solr'); - - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // create list of facets - $solr->updateDocument ($solrUpdateDocumentEntity); - } - - /** - * Delete document from index - * @param string $workspace - * @param string $idQuery - */ - public function deleteDocumentFromIndex($workspace, $idQuery) - { - G::LoadClass ('solr'); - - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // create list of facets - $solr->deleteDocument ($workspace, $idQuery); - } - - /** - * Commit index changes - * @param string $workspace - */ - public function commitIndexChanges($workspace) - { - G::LoadClass ('solr'); - - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // commit - $solr->commitChanges ($workspace); - } - - /** - * Optimize index changes - * @param string $workspace - */ - public function optimizeIndexChanges($workspace) - { - G::LoadClass ('solr'); - - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // commit - $solr->optimizeChanges ($workspace); - } - - /** - * Call Solr server to return the list of paginated pages. - * @param FacetRequest $solrRequestData - * @return Entity_SolrQueryResult - */ - public function getDataTablePaginatedList($solrRequestData) - { - require_once ('class.solr.php'); - require_once ('entities/SolrRequestData.php'); - require_once ('entities/SolrQueryResult.php'); - - // prepare the list of sorted columns - // verify if the data of sorting is available - if (isset ($solrRequestData->sortCols [0])) { - for ($i = 0; $i < $solrRequestData->numSortingCols; $i ++) { - // verify if column is sortable - if ($solrRequestData->includeCols [$solrRequestData->sortCols [$i]] != '' && $solrRequestData->sortableCols [$i] == "true") { - // change sorting column index to column names - $solrRequestData->sortCols [$i] = $solrRequestData->includeCols [$solrRequestData->sortCols [$i]]; - // define the direction of the sorting columns - $solrRequestData->sortDir [$i] = $solrRequestData->sortDir [$i]; - } - } - } - // remove placeholder fields - // the placeholder doesn't affect the the solr's response - // $solrRequestData->includeCols = array_diff($solrRequestData->includeCols, - // array('')); - - // execute query - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - $solrPaginatedResult = $solr->executeQuery ($solrRequestData); - - // get total number of documents in index - $numTotalDocs = $solr->getNumberDocuments ($solrRequestData->workspace); - - // create the Datatable response of the query - $numFound = $solrPaginatedResult->response->numFound; - - $docs = $solrPaginatedResult->response->docs; - // print_r($docs); - // insert list of names in docs result - $data = array ( - "sEcho" => '', // must be completed in response - "iTotalRecords" => intval ($numTotalDocs), // we must get the - // total number of - // documents - "iTotalDisplayRecords" => $numFound, - "aaData" => array () - ); - // copy result document or add placeholders to result - foreach ($docs as $i => $doc) { - $data ['aaData'] [$i] = array (); - foreach ($solrRequestData->includeCols as $columnName) { - if ($columnName == '') { - $data ['aaData'] [$i] [] = ''; // placeholder - } - else { - if (isset ($doc->$columnName)) { - $data ['aaData'] [$i] [] = $doc->$columnName; - } - else { - $data ['aaData'] [$i] [] = ''; - } - } - } - } - - $solrQueryResponse = Entity_SolrQueryResult::createForRequest ($data); - // - - return $solrQueryResponse; - } - - /** - * Return the list of stored fields in the index. - * @param string $workspace - * @return array of index fields - */ - public function getIndexFields($workspace) - { - require_once ('class.solr.php'); + private $_solrIsEnabled = false; + private $_solrHost = ""; - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // print "SearchIndex!!!!"; - // create list of facets - $solrFieldsData = $solr->getListIndexedStoredFields ($workspace); - // copy list of arrays - $listFields = array (); - foreach ($solrFieldsData->fields as $key => $fieldData) { - if (array_key_exists ('dynamicBase', $fieldData)) { - $originalFieldName = substr ($key, 0, - strlen ($fieldData->dynamicBase) + 1); - // $listFields[strtolower($originalFieldName)] = $key; //in case of case insentive strings - // Maintain case sensitive variable names - $listFields [$originalFieldName] = $key; - } - else { - // $listFields[strtolower($key)] = $key; - // Maintain case sensitive variable names - $listFields [$key] = $key; - } + public function __construct ($solrIsEnabled = false, $solrHost = "") + { + // check if Zend Library is available + // if(class_exists("Zend_Registry")){ + // $registry = Zend_Registry::getInstance(); + // //check if configuration is enabled + // $this->solrIsEnabled = $registry->isRegistered('solrEnabled') && + // $registry->get('solrEnabled') == 1; + // $this->solrHost = + // $registry->isRegistered('solrHost')?$registry->get('solrHost'):""; + // } + // else{ + // //use the parameters to initialize class + $this->_solrIsEnabled = $solrIsEnabled; + $this->_solrHost = $solrHost; + // } + } + + /** + * Verify if the Solr service is available + * @gearman = false + * @rest = false + * @background = false + * + * no input parameters @param[in] + * + * @param [out] bool true if index service is enabled false in other case + */ + public function isEnabled () + { + // require_once (ROOT_PATH . + // '/businessLogic/modules/SearchIndexAccess/Solr.php'); + require_once ('class.solr.php'); + $solr = new BpmnEngine_SearchIndexAccess_Solr( $this->_solrIsEnabled, $this->_solrHost ); + return $solr->isEnabled(); + } + + /** + * Get the list of facets in base to the specified query and filter + * @gearman = true + * @rest = false + * @background = false + * + * @param [in] Entity_FacetRequest facetRequestEntity Facet request entity + * @param [out] array FacetGroup + */ + public function getFacetsList ($facetRequestEntity) + { + require_once ('class.solr.php'); + // require_once (ROOT_PATH . + // '/businessLogic/modules/SearchIndexAccess/Solr.php'); + require_once ('entities/FacetGroup.php'); + require_once ('entities/FacetItem.php'); + require_once ('entities/SelectedFacetGroupItem.php'); + require_once ('entities/FacetResult.php'); + + /** + * *************************************************************** + */ + // get array of selected facet groups + $facetRequestEntity->selectedFacetsString = str_replace( ',,', ',', $facetRequestEntity->selectedFacetsString ); + // remove descriptions of selected facet groups + + + $aGroups = explode( ',', $facetRequestEntity->selectedFacetsString ); + + $aGroups = array_filter( $aGroups ); // remove empty items + + + $aSelectedFacetGroups = array (); + foreach ($aGroups as $i => $value) { + $gi = explode( ':::', $value ); + $gr = explode( '::', $gi[0] ); + $it = explode( '::', $gi[1] ); + + // create string for remove condition + $count = 0; + $removeCondition = str_replace( $value . ',', '', $facetRequestEntity->selectedFacetsString, $count ); + if ($count == 0) { + $removeCondition = str_replace( $value, '', $facetRequestEntity->selectedFacetsString, $count ); + } + $selectedFacetGroupData = array ('selectedFacetGroupName' => $gr[0],'selectedFacetGroupPrintName' => $gr[1],'selectedFacetItemName' => $it[0],'selectedFacetItemPrintName' => $it[1],'selectedFacetRemoveCondition' => $removeCondition + ); + + $aSelectedFacetGroups[] = Entity_SelectedFacetGroupItem::createForRequest( $selectedFacetGroupData ); + } + + /** + * *************************************************************** + */ + // convert request to index request + // create filters + $filters = array (); + if (! empty( $aSelectedFacetGroups )) { + // exclude facetFields and facetDates included in filter from the next + // list of facets + foreach ($aSelectedFacetGroups as $value) { + $facetRequestEntity->facetFields = array_diff( $facetRequestEntity->facetFields, array ($value->selectedFacetGroupName + ) ); + $facetRequestEntity->facetDates = array_diff( $facetRequestEntity->facetDates, array ($value->selectedFacetGroupName + ) ); + } + + // $facetFields = array_diff($facetFields, + // $facetInterfaceRequestEntity->selectedFacetGroups); + // $facetDates = array_diff($facetDates, + // $facetInterfaceRequestEntity->selectedFacetGroups); + foreach ($aSelectedFacetGroups as $group) { + $filters[] = $group->selectedFacetGroupName . ':' . urlencode( $group->selectedFacetItemName ); + } + } + $facetRequestEntity->filters = $filters; + + $solr = new BpmnEngine_SearchIndexAccess_Solr( $this->_solrIsEnabled, $this->_solrHost ); + + // create list of facets + $facetsList = $solr->getFacetsList( $facetRequestEntity ); + + $numFound = $facetsList->response->numFound; + + $facetCounts = $facetsList->facet_counts; + + $facetGroups = array (); + // convert facet fields result to objects + /** + * ********************************************************************* + */ + // include facet field results + $facetFieldsResult = $facetsList->facet_counts->facet_fields; + if (! empty( $facetFieldsResult )) { + foreach ($facetFieldsResult as $facetGroup => $facetvalues) { + if (count( $facetvalues ) > 0) // if the group have facets included +{ + $data = array ('facetGroupName' => $facetGroup + ); + $data['facetGroupPrintName'] = $facetGroup; + $data['facetGroupType'] = 'field'; + $facetItems = array (); + for ($i = 0; $i < count( $facetvalues ); $i += 2) { + $dataItem = array (); + $dataItem['facetName'] = $facetvalues[$i]; + $dataItem['facetPrintName'] = $facetvalues[$i]; + $dataItem['facetCount'] = $facetvalues[$i + 1]; + $dataItem['facetSelectCondition'] = $facetRequestEntity->selectedFacetsString . (empty( $facetRequestEntity->selectedFacetsString ) ? '' : ',') . $data['facetGroupName'] . '::' . $data['facetGroupPrintName'] . ':::' . $dataItem['facetName'] . '::' . $dataItem['facetPrintName']; + $newFacetItem = Entity_FacetItem::createForInsert( $dataItem ); + $facetItems[] = $newFacetItem; + } + $data['facetItems'] = $facetItems; + $newFacetGroup = Entity_FacetGroup::createForInsert( $data ); + + $facetGroups[] = $newFacetGroup; + } + } + } + /** + * ********************************************************************* + */ + // include facet date ranges results + $facetDatesResult = $facetsList->facet_counts->facet_dates; + if (! empty( $facetDatesResult )) { + foreach ($facetDatesResult as $facetGroup => $facetvalues) { + if (count( (array) $facetvalues ) > 3) // if the group have any facets included + // besides start, end and gap + { + $data = array ('facetGroupName' => $facetGroup + ); + $data['facetGroupPrintName'] = $facetGroup; + $data['facetGroupType'] = 'daterange'; + $facetItems = array (); + $facetvalueskeys = array_keys( (array) $facetvalues ); + foreach ($facetvalueskeys as $i => $k) { + if ($k != 'gap' && $k != 'start' && $k != 'end') { + $dataItem = array (); + if ($i < count( $facetvalueskeys ) - 4) { + + $dataItem['facetName'] = '[' . $k . '%20TO%20' . $facetvalueskeys[$i + 1] . ']'; + $dataItem['facetPrintName'] = '[' . $k . '%20TO%20' . $facetvalueskeys[$i + 1] . ']'; + } else { + // the last group + $dataItem['facetName'] = '[' . $k . '%20TO%20' . $facetvalues->end . ']'; + $dataItem['facetPrintName'] = '[' . $k . '%20TO%20' . $facetvalues->end . ']'; + } + + $dataItem['facetCount'] = $facetvalues->$k; + $dataItem['facetSelectCondition'] = $facetRequestEntity->selectedFacetsString . (empty( $facetRequestEntity->selectedFacetsString ) ? '' : ',') . $data['facetGroupName'] . '::' . $data['facetGroupPrintName'] . ':::' . $dataItem['facetName'] . '::' . $dataItem['facetPrintName']; + $newFacetItem = Entity_FacetItem::createForInsert( $dataItem ); + $facetItems[] = $newFacetItem; + } + } + + $data['facetItems'] = $facetItems; + $newFacetGroup = Entity_FacetGroup::createForInsert( $data ); + + $facetGroups[] = $newFacetGroup; + } + } + } + // TODO:convert facet queries + // ----- + /** + * *************************************************************** + */ + // Create a filter string used in the filter of results of a datatable + $filterText = ''; // the list of selected filters used for filtering result, + // send in ajax + foreach ($aSelectedFacetGroups as $selectedFacetGroup) { + $filterText .= $selectedFacetGroup->selectedFacetGroupName . ':' . urlencode( $selectedFacetGroup->selectedFacetItemName ) . ','; + } + $filterText = substr_replace( $filterText, '', - 1 ); + // $filterText = ($filterText == '')?'':'&filterText='.$filterText; + + + /** + * *************************************************************** + */ + // Create result + $dataFacetResult = array ('aFacetGroups' => $facetGroups,'aSelectedFacetGroups' => $aSelectedFacetGroups,'sFilterText' => $filterText + ); + $facetResult = Entity_FacetResult::createForRequest( $dataFacetResult ); + + return $facetResult; + } + + /** + * Get the total number of documents in search server + * + * @param string $workspace + * @return integer number of documents + * + */ + public function getNumberDocuments ($workspace) + { + require_once ('class.solr.php'); + // require_once (ROOT_PATH . + // '/businessLogic/modules/SearchIndexAccess/Solr.php'); + $solr = new BpmnEngine_SearchIndexAccess_Solr( $this->_solrIsEnabled, $this->_solrHost ); + + // create list of facets + $numberDocuments = $solr->getNumberDocuments( $workspace ); + + return $numberDocuments; + } + + /** + * Update document Index + * + * @param SolrUpdateDocumentEntity $solrUpdateDocumentEntity + */ + public function updateIndexDocument ($solrUpdateDocumentEntity) + { + G::LoadClass( 'solr' ); + + $solr = new BpmnEngine_SearchIndexAccess_Solr( $this->_solrIsEnabled, $this->_solrHost ); + + // create list of facets + $solr->updateDocument( $solrUpdateDocumentEntity ); + } + + /** + * Delete document from index + * + * @param string $workspace + * @param string $idQuery + */ + public function deleteDocumentFromIndex ($workspace, $idQuery) + { + G::LoadClass( 'solr' ); + + $solr = new BpmnEngine_SearchIndexAccess_Solr( $this->_solrIsEnabled, $this->_solrHost ); + + // create list of facets + $solr->deleteDocument( $workspace, $idQuery ); + } + + /** + * Commit index changes + * + * @param string $workspace + */ + public function commitIndexChanges ($workspace) + { + G::LoadClass( 'solr' ); + + $solr = new BpmnEngine_SearchIndexAccess_Solr( $this->_solrIsEnabled, $this->_solrHost ); + + // commit + $solr->commitChanges( $workspace ); + } + + /** + * Optimize index changes + * + * @param string $workspace + */ + public function optimizeIndexChanges ($workspace) + { + G::LoadClass( 'solr' ); + + $solr = new BpmnEngine_SearchIndexAccess_Solr( $this->_solrIsEnabled, $this->_solrHost ); + + // commit + $solr->optimizeChanges( $workspace ); + } + + /** + * Call Solr server to return the list of paginated pages. + * + * @param FacetRequest $solrRequestData + * @return Entity_SolrQueryResult + */ + public function getDataTablePaginatedList ($solrRequestData) + { + require_once ('class.solr.php'); + require_once ('entities/SolrRequestData.php'); + require_once ('entities/SolrQueryResult.php'); + + // prepare the list of sorted columns + // verify if the data of sorting is available + if (isset( $solrRequestData->sortCols[0] )) { + for ($i = 0; $i < $solrRequestData->numSortingCols; $i ++) { + // verify if column is sortable + if ($solrRequestData->includeCols[$solrRequestData->sortCols[$i]] != '' && $solrRequestData->sortableCols[$i] == "true") { + // change sorting column index to column names + $solrRequestData->sortCols[$i] = $solrRequestData->includeCols[$solrRequestData->sortCols[$i]]; + // define the direction of the sorting columns + $solrRequestData->sortDir[$i] = $solrRequestData->sortDir[$i]; + } + } + } + // remove placeholder fields + // the placeholder doesn't affect the the solr's response + // $solrRequestData->includeCols = array_diff($solrRequestData->includeCols, + // array('')); + + + // execute query + $solr = new BpmnEngine_SearchIndexAccess_Solr( $this->_solrIsEnabled, $this->_solrHost ); + $solrPaginatedResult = $solr->executeQuery( $solrRequestData ); + + // get total number of documents in index + $numTotalDocs = $solr->getNumberDocuments( $solrRequestData->workspace ); + + // create the Datatable response of the query + $numFound = $solrPaginatedResult->response->numFound; + + $docs = $solrPaginatedResult->response->docs; + // print_r($docs); + // insert list of names in docs result + $data = array ("sEcho" => '', // must be completed in response +"iTotalRecords" => intval( $numTotalDocs ), // we must get the + // total number of + // documents + "iTotalDisplayRecords" => $numFound,"aaData" => array () + ); + // copy result document or add placeholders to result + foreach ($docs as $i => $doc) { + $data['aaData'][$i] = array (); + foreach ($solrRequestData->includeCols as $columnName) { + if ($columnName == '') { + $data['aaData'][$i][] = ''; // placeholder + } else { + if (isset( $doc->$columnName )) { + $data['aaData'][$i][] = $doc->$columnName; + } else { + $data['aaData'][$i][] = ''; + } + } + } + } + + $solrQueryResponse = Entity_SolrQueryResult::createForRequest( $data ); + // + + + return $solrQueryResponse; + } + + /** + * Return the list of stored fields in the index. + * + * @param string $workspace + * @return array of index fields + */ + public function getIndexFields ($workspace) + { + require_once ('class.solr.php'); + + $solr = new BpmnEngine_SearchIndexAccess_Solr( $this->_solrIsEnabled, $this->_solrHost ); + + // print "SearchIndex!!!!"; + // create list of facets + $solrFieldsData = $solr->getListIndexedStoredFields( $workspace ); + // copy list of arrays + $listFields = array (); + foreach ($solrFieldsData->fields as $key => $fieldData) { + if (array_key_exists( 'dynamicBase', $fieldData )) { + $originalFieldName = substr( $key, 0, - strlen( $fieldData->dynamicBase ) + 1 ); + // $listFields[strtolower($originalFieldName)] = $key; //in case of case insentive strings + // Maintain case sensitive variable names + $listFields[$originalFieldName] = $key; + } else { + // $listFields[strtolower($key)] = $key; + // Maintain case sensitive variable names + $listFields[$key] = $key; + } + } + + return $listFields; } - - return $listFields; - } } \ No newline at end of file From b5a9522b6c468d7a32442d1da0a9f7d8b3aca1f5 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:22:25 -0400 Subject: [PATCH 05/18] CODE STYLE class.serverConfiguration.php --- .../classes/class.serverConfiguration.php | 786 ++++++++++-------- 1 file changed, 419 insertions(+), 367 deletions(-) diff --git a/workflow/engine/classes/class.serverConfiguration.php b/workflow/engine/classes/class.serverConfiguration.php index d1e2a2926..399ca25eb 100755 --- a/workflow/engine/classes/class.serverConfiguration.php +++ b/workflow/engine/classes/class.serverConfiguration.php @@ -1,6 +1,8 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. @@ -25,392 +27,442 @@ /** * ServerConfiguration - serverConf class + * * @author Hugo Loza * @copyright 2010 COLOSA * @license GNU Affero General Public License * @package workflow.engine.ProcessMaker */ -class serverConf { - private $_aProperties = array (); - private $_aHeartbeatConfig = array (); - private $_aWSapces = array (); - private $aWSinfo = array (); - private $pluginsA = array (); - private $errors = array (); - private static $instance = NULL; - private $haveSetupData = false; - private $beatType = 'starting'; - private $ip; - private $index = 0; - private $os; - private $webserver; - private $host; - private $php; - private $mysql; - private $pmVersion; - private $pmProduct = 'PMCE'; - private $nextBeatDate; - public $logins; - private $lanDirection; - private $lanLanguage; - public $workspaces = array(); - public $rtlLang = array('ar','iw','fa'); - public $filePath = ''; +class serverConf +{ + private $_aProperties = array (); + private $_aHeartbeatConfig = array (); + private $_aWSapces = array (); + private $aWSinfo = array (); + private $pluginsA = array (); + private $errors = array (); + private static $instance = NULL; + private $haveSetupData = false; + private $beatType = 'starting'; + private $ip; + private $index = 0; + private $os; + private $webserver; + private $host; + private $php; + private $mysql; + private $pmVersion; + private $pmProduct = 'PMCE'; + private $nextBeatDate; + public $logins; + private $lanDirection; + private $lanLanguage; + public $workspaces = array (); + public $rtlLang = array ('ar','iw','fa' + ); + public $filePath = ''; - - public function __construct() { - if (defined('PATH_DATA')) { - $this->filePath = PATH_DATA . 'srvConf.singleton'; - } - } - - /** - * This function is instancing to this object - * param - * @return object - */ - function &getSingleton() { - if (self::$instance == NULL) { - self::$instance = new serverConf ( ); - if ((file_exists ( self::$instance->filePath ))&&(filesize(self::$instance->filePath)>0)){ - self::$instance->unSerializeInstance ( file_get_contents ( self::$instance->filePath ) ); - } - } - return self::$instance; - } - - /** - * This function generates a storable representation of this obejct - * param - * @return void - */ - function serializeInstance() { - return serialize ( self::$instance ); - } - - /** - * This function takes a single serialized object and converts it back a object - * @param string $serialized - * @return void - */ - function unSerializeInstance($serialized) { - if (self::$instance == NULL) { - self::$instance = new serverConf ( ); - } - - if($instance = @unserialize ( $serialized )){ - self::$instance = $instance; - } - } - - /** - * This will save the object in the specified file (defined as a property of this class) - * param - * @return void - */ - - function saveSingleton() { - if (defined('PATH_DATA')) { - $this->filePath = PATH_DATA . 'srvConf.singleton'; - $size = file_put_contents ( $this->filePath, $this->serializeInstance () ); - } - } - - /** - * With this is possible to save a property that will be saved in the properties - * array of this class. - * @param string $propertyName - * @param string $propertyValue - */ - function setProperty($propertyName, $propertyValue) { - $this->_aProperties [$propertyName] = $propertyValue; - $this->saveSingleton (); - } - - /** - * To unset a defined property. If it doesn't exist then it does nothing. - * @param string $propertyName - * @return void - */ - function unsetProperty($propertyName) { - if (isset ( $this->_aProperties [$propertyName] )) { - unset ( $this->_aProperties [$propertyName] ); - $this->saveSingleton (); - } - } - - /** - * Returns the value of a defined property. If it doesn't exist then returns null - * @param string $propertyName - * @return string/null - */ - function getProperty($propertyName) { - if (isset ( $this->_aProperties [$propertyName] )) { - return $this->_aProperties [$propertyName]; - } - else { - return null; - } - } - - /** - * Used to have a record of succesful logins to the system (total and by WS) - * param - * @return void - */ - function sucessfulLogin() { - $this->logins ++; - if ( isset ($this->workspaces[SYS_SYS]) && isset ($this->workspaces[SYS_SYS]['WSP_LOGINS']) ) - $this->workspaces[SYS_SYS]['WSP_LOGINS'] ++; - - if ( isset ($this->workspaces[SYS_SYS]) && !isset ($this->workspaces[SYS_SYS]['WSP_LOGINS']) ) - $this->workspaces[SYS_SYS]['WSP_LOGINS'] = 1; - - $this->saveSingleton (); - } - - function setWsInfo($wsname,$info){ - $this->aWSinfo[$wsname]=$info; - } - - /** - * This will togle the status of a workspace (enabled,disabled) - * @param string $wsName - * @return void - */ - function changeStatusWS($wsName) { - - if (isset ( $this->_aWSapces [$wsName] )) { //Enable WS - unset ( $this->_aWSapces [$wsName] ); - } - else { - $this->_aWSapces [$wsName] = 'disabled'; - } - $this->saveSingleton (); - } - - /** - * Return the status of a WS. If is disabled will return 1 otherwise 0 - * @param $wsname - * @return boolean - */ - function isWSDisabled($wsName) { - return isset ( $this->_aWSapces [$wsName] ); - } - - /** - * Check only if the server address or server name has changed, - * to send another beat in next minute. - * param - * @return boolean - */ - function checkIfHostNameHasChanged() { - //removed the PM_VERSION control, because when an upgrade is done, the haveSetupData has to be changed. - if ($this->ip != getenv ( 'SERVER_ADDR' )) - return false; - - if ($this->host != getenv ( 'SERVER_NAME' )) - return false; - - return $this->haveSetupData; - } - - - /** - * Will return a list of all WS in this system and their related information. - * @uses getWSList - * param - * @return array - */ - function getWSList() { - $dir = PATH_DB; - $wsArray = array (); - if (file_exists ( $dir )) { - if ($handle = opendir ( $dir )) { - while ( false !== ($file = readdir ( $handle )) ) { - if (($file != ".") && ($file != "..")) { - if (file_exists ( PATH_DB . $file . '/db.php' )) { //print $file."/db.php
"; - $statusl = ($this->isWSDisabled ( $file )) ? 'DISABLED' : 'ENABLED'; - if(isset($this->aWSinfo[$file])){ - $wsInfo = $this->aWSinfo[$file]; - }else{ - $wsInfo ['num_processes'] = "not gathered yet"; - $wsInfo ['num_cases'] = "not gathered yet";; - $wsInfo ['num_users'] = "not gathered yet"; - } - $wsArray [$file] = array ('WSP_ID' => $file, 'WSP_NAME' => $file, 'WSP_STATUS' => $statusl, 'WSP_PROCESS_COUNT' => $wsInfo ['num_processes'], 'WSP_CASES_COUNT' => $wsInfo ['num_cases'], 'WSP_USERS_COUNT' => isset($wsInfo ['num_users'])?$wsInfo ['num_users']:"" ); - if (isset ( $this->workspaces [$file] ['WSP_LOGINS'] )) - $wsArray [$file] ['WSP_LOGINS'] = $this->workspaces [$file] ['WSP_LOGINS']; - - } - } + public function __construct () + { + if (defined( 'PATH_DATA' )) { + $this->filePath = PATH_DATA . 'srvConf.singleton'; } - closedir ( $handle ); - } } - return $wsArray; - } - /** - * Will return all the information of a WS. - * - Status - * - # of cases - * - # of processes - * - # of users - * @param string $wsName - * @return array - */ - function getWorkspaceInfo($wsName) { - $aResult = Array ('num_processes' => '0', 'num_cases' => '0' ); - $result = array(); - require_once 'classes/model/Process.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Users.php'; - - $Criteria = new Criteria('workflow'); - $Criteria->add (ProcessPeer::PRO_STATUS, 'ACTIVE' , CRITERIA::EQUAL ); - $aResult['num_processes'] = ProcessPeer::doCount($Criteria); - - $Criteria = new Criteria('workflow'); - $Criteria->add (ApplicationPeer::APP_STATUS, 'COMPLETED' , CRITERIA::NOT_EQUAL ); - $aResult['num_cases'] = ApplicationPeer::doCount($Criteria); - - $Criteria = new Criteria('workflow'); - $Criteria->add (UsersPeer::USR_STATUS, array('DELETED','DISABLED') , CRITERIA::NOT_IN ); - $aResult['num_users'] = UsersPeer::doCount($Criteria); - return $aResult; - } - - /** - * Will list the plugins of the system - * param - * @return array - */ - function getPluginsList() { - return $this->pluginsA; - } - - /*** - * Register a PLugin - */ - function addPlugin($workspace,$info){ - $this->pluginsA[$workspace]=$info; - } - - function getDBVersion(){ - $sMySQLVersion = '?????'; - if (defined ( "DB_HOST" )) { - G::LoadClass ( 'net' ); - G::LoadClass ( 'dbConnections' ); - $dbNetView = new NET ( DB_HOST ); - $dbNetView->loginDbServer ( DB_USER, DB_PASS ); - - $dbConns = new dbConnections ( '' ); - $availdb = ''; - foreach ( $dbConns->getDbServicesAvailables () as $key => $val ) { - if ($availdb != '') - $availdb .= ', '; - $availdb .= $val ['name']; - } - - try { - $sMySQLVersion = $dbNetView->getDbServerVersion ( 'mysql' ); - } - catch ( Exception $oException ) { - $sMySQLVersion = '?????'; - } + /** + * This function is instancing to this object + * param + * + * @return object + */ + function &getSingleton () + { + if (self::$instance == NULL) { + self::$instance = new serverConf(); + if ((file_exists( self::$instance->filePath )) && (filesize( self::$instance->filePath ) > 0)) { + self::$instance->unSerializeInstance( file_get_contents( self::$instance->filePath ) ); + } + } + return self::$instance; } - return $sMySQLVersion; - } - /** - * Will reset all the logins' count - * param - * @return void - */ - function resetLogins() { - $this->logins = 0; - if(is_array($this->workspaces)){ - foreach ( $this->workspaces as $wsName => $wsinfo ) { - $this->workspaces [$wsName] ['WSP_LOGINS'] = 0; + /** + * This function generates a storable representation of this obejct + * param + * + * @return void + */ + function serializeInstance () + { + return serialize( self::$instance ); } - } - } + /** + * This function takes a single serialized object and converts it back a object + * + * @param string $serialized + * @return void + */ + function unSerializeInstance ($serialized) + { + if (self::$instance == NULL) { + self::$instance = new serverConf(); + } - /** - * Get the value of language direction property - * @param void - * @return string - */ - function getLanDirection() { - if (!isset($this->lanDirection) ) { - $this->lanDirection = 'L'; - } - if( defined('SYS_LANG') ) { - //if we already have the landirection for this language, just return from serverConf - if ( $this->lanLanguage == SYS_LANG ) - return $this->lanDirection; + if ($instance = @unserialize( $serialized )) { + self::$instance = $instance; + } + } - //if not , we need to query Database, in order to get the direction - $this->lanDirection = 'L'; //default value; - $this->lanLanguage = SYS_LANG; - require_once 'classes/model/Language.php'; - $oLang = new Language(); - try{ - $aLang = $oLang->load(SYS_LANG); - if( isset($aLang['LAN_DIRECTION']) ){ - $this->lanDirection = strtoupper($aLang['LAN_DIRECTION']); + /** + * This will save the object in the specified file (defined as a property of this class) + * param + * + * @return void + */ + + function saveSingleton () + { + if (defined( 'PATH_DATA' )) { + $this->filePath = PATH_DATA . 'srvConf.singleton'; + $size = file_put_contents( $this->filePath, $this->serializeInstance() ); + } + } + + /** + * With this is possible to save a property that will be saved in the properties + * array of this class. + * + * @param string $propertyName + * @param string $propertyValue + */ + function setProperty ($propertyName, $propertyValue) + { + $this->_aProperties[$propertyName] = $propertyValue; + $this->saveSingleton(); + } + + /** + * To unset a defined property. + * If it doesn't exist then it does nothing. + * + * @param string $propertyName + * @return void + */ + function unsetProperty ($propertyName) + { + if (isset( $this->_aProperties[$propertyName] )) { + unset( $this->_aProperties[$propertyName] ); + $this->saveSingleton(); + } + } + + /** + * Returns the value of a defined property. + * If it doesn't exist then returns null + * + * @param string $propertyName + * @return string/null + */ + function getProperty ($propertyName) + { + if (isset( $this->_aProperties[$propertyName] )) { + return $this->_aProperties[$propertyName]; + } else { + return null; + } + } + + /** + * Used to have a record of succesful logins to the system (total and by WS) + * param + * + * @return void + */ + function sucessfulLogin () + { + $this->logins ++; + if (isset( $this->workspaces[SYS_SYS] ) && isset( $this->workspaces[SYS_SYS]['WSP_LOGINS'] )) + $this->workspaces[SYS_SYS]['WSP_LOGINS'] ++; + + if (isset( $this->workspaces[SYS_SYS] ) && ! isset( $this->workspaces[SYS_SYS]['WSP_LOGINS'] )) + $this->workspaces[SYS_SYS]['WSP_LOGINS'] = 1; + + $this->saveSingleton(); + } + + function setWsInfo ($wsname, $info) + { + $this->aWSinfo[$wsname] = $info; + } + + /** + * This will togle the status of a workspace (enabled,disabled) + * + * @param string $wsName + * @return void + */ + function changeStatusWS ($wsName) + { + + if (isset( $this->_aWSapces[$wsName] )) { //Enable WS + unset( $this->_aWSapces[$wsName] ); + } else { + $this->_aWSapces[$wsName] = 'disabled'; } $this->saveSingleton(); - } - catch(Exception $e){ - $this->lanDirection = 'L'; - } } - return $this->lanDirection; - } -/** - * With this is possible to save a property that will be saved in the properties - * array of this class. - * @param string $propertyName - * @param string $propertyValue - * @param string $workspace - */ - function setHeartbeatProperty($propertyName, $propertyValue, $workspace) { - $this->_aHeartbeatConfig [$workspace][$propertyName] = $propertyValue; - $this->saveSingleton (); - } - /** - * To unset a defined property. If it doesn't exist then it does nothing. - * @param string $propertyName - * @param string $workspace - * @return void - */ - function unsetHeartbeatProperty($propertyName,$workspace) { - if (isset ( $this->_aHeartbeatConfig [$workspace][$propertyName] )) - unset ( $this->_aHeartbeatConfig [$workspace][$propertyName] ); - $this->saveSingleton (); - } - - /** - * Returns the value of a defined property. If it doesn't exist then returns null - * @param string $propertyName - * @return string/null - */ - function getHeartbeatProperty($propertyName, $workspace) { - if (isset ( $this->_aHeartbeatConfig [$workspace][$propertyName] )) { - return $this->_aHeartbeatConfig [$workspace][$propertyName]; - } else { - return null; + /** + * Return the status of a WS. + * If is disabled will return 1 otherwise 0 + * + * @param $wsname + * @return boolean + */ + function isWSDisabled ($wsName) + { + return isset( $this->_aWSapces[$wsName] ); } - } - function isRtl ($lang = SYS_LANG) { - $lang = substr($lang, 0, 2); - return in_array($lang, $this->rtlLang); - } + /** + * Check only if the server address or server name has changed, + * to send another beat in next minute. + * param + * + * @return boolean + */ + function checkIfHostNameHasChanged () + { + //removed the PM_VERSION control, because when an upgrade is done, the haveSetupData has to be changed. + if ($this->ip != getenv( 'SERVER_ADDR' )) + return false; + if ($this->host != getenv( 'SERVER_NAME' )) + return false; + + return $this->haveSetupData; + } + + /** + * Will return a list of all WS in this system and their related information. + * + * @uses getWSList + * param + * @return array + */ + function getWSList () + { + $dir = PATH_DB; + $wsArray = array (); + if (file_exists( $dir )) { + if ($handle = opendir( $dir )) { + while (false !== ($file = readdir( $handle ))) { + if (($file != ".") && ($file != "..")) { + if (file_exists( PATH_DB . $file . '/db.php' )) { //print $file."/db.php
"; + $statusl = ($this->isWSDisabled( $file )) ? 'DISABLED' : 'ENABLED'; + if (isset( $this->aWSinfo[$file] )) { + $wsInfo = $this->aWSinfo[$file]; + } else { + $wsInfo['num_processes'] = "not gathered yet"; + $wsInfo['num_cases'] = "not gathered yet"; + ; + $wsInfo['num_users'] = "not gathered yet"; + } + $wsArray[$file] = array ('WSP_ID' => $file,'WSP_NAME' => $file,'WSP_STATUS' => $statusl,'WSP_PROCESS_COUNT' => $wsInfo['num_processes'],'WSP_CASES_COUNT' => $wsInfo['num_cases'],'WSP_USERS_COUNT' => isset( $wsInfo['num_users'] ) ? $wsInfo['num_users'] : "" + ); + if (isset( $this->workspaces[$file]['WSP_LOGINS'] )) + $wsArray[$file]['WSP_LOGINS'] = $this->workspaces[$file]['WSP_LOGINS']; + + } + } + } + closedir( $handle ); + } + } + return $wsArray; + + } + + /** + * Will return all the information of a WS. + * - Status + * - # of cases + * - # of processes + * - # of users + * + * @param string $wsName + * @return array + */ + function getWorkspaceInfo ($wsName) + { + $aResult = Array ('num_processes' => '0','num_cases' => '0' + ); + $result = array (); + require_once 'classes/model/Process.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Users.php'; + + $Criteria = new Criteria( 'workflow' ); + $Criteria->add( ProcessPeer::PRO_STATUS, 'ACTIVE', CRITERIA::EQUAL ); + $aResult['num_processes'] = ProcessPeer::doCount( $Criteria ); + + $Criteria = new Criteria( 'workflow' ); + $Criteria->add( ApplicationPeer::APP_STATUS, 'COMPLETED', CRITERIA::NOT_EQUAL ); + $aResult['num_cases'] = ApplicationPeer::doCount( $Criteria ); + + $Criteria = new Criteria( 'workflow' ); + $Criteria->add( UsersPeer::USR_STATUS, array ('DELETED','DISABLED' + ), CRITERIA::NOT_IN ); + $aResult['num_users'] = UsersPeer::doCount( $Criteria ); + return $aResult; + } + + /** + * Will list the plugins of the system + * param + * + * @return array + */ + function getPluginsList () + { + return $this->pluginsA; + } + + /** + * * + * Register a PLugin + */ + function addPlugin ($workspace, $info) + { + $this->pluginsA[$workspace] = $info; + } + + function getDBVersion () + { + $sMySQLVersion = '?????'; + if (defined( "DB_HOST" )) { + G::LoadClass( 'net' ); + G::LoadClass( 'dbConnections' ); + $dbNetView = new NET( DB_HOST ); + $dbNetView->loginDbServer( DB_USER, DB_PASS ); + + $dbConns = new dbConnections( '' ); + $availdb = ''; + foreach ($dbConns->getDbServicesAvailables() as $key => $val) { + if ($availdb != '') + $availdb .= ', '; + $availdb .= $val['name']; + } + + try { + $sMySQLVersion = $dbNetView->getDbServerVersion( 'mysql' ); + } catch (Exception $oException) { + $sMySQLVersion = '?????'; + } + } + return $sMySQLVersion; + } + + /** + * Will reset all the logins' count + * param + * + * @return void + */ + function resetLogins () + { + $this->logins = 0; + if (is_array( $this->workspaces )) { + foreach ($this->workspaces as $wsName => $wsinfo) { + $this->workspaces[$wsName]['WSP_LOGINS'] = 0; + } + } + } + + /** + * Get the value of language direction property + * + * @param void + * @return string + */ + function getLanDirection () + { + if (! isset( $this->lanDirection )) { + $this->lanDirection = 'L'; + } + if (defined( 'SYS_LANG' )) { + //if we already have the landirection for this language, just return from serverConf + if ($this->lanLanguage == SYS_LANG) + return $this->lanDirection; + + //if not , we need to query Database, in order to get the direction + $this->lanDirection = 'L'; //default value; + $this->lanLanguage = SYS_LANG; + require_once 'classes/model/Language.php'; + $oLang = new Language(); + try { + $aLang = $oLang->load( SYS_LANG ); + if (isset( $aLang['LAN_DIRECTION'] )) { + $this->lanDirection = strtoupper( $aLang['LAN_DIRECTION'] ); + } + $this->saveSingleton(); + } catch (Exception $e) { + $this->lanDirection = 'L'; + } + } + return $this->lanDirection; + } + + /** + * With this is possible to save a property that will be saved in the properties + * array of this class. + * + * @param string $propertyName + * @param string $propertyValue + * @param string $workspace + */ + function setHeartbeatProperty ($propertyName, $propertyValue, $workspace) + { + $this->_aHeartbeatConfig[$workspace][$propertyName] = $propertyValue; + $this->saveSingleton(); + } + + /** + * To unset a defined property. + * If it doesn't exist then it does nothing. + * + * @param string $propertyName + * @param string $workspace + * @return void + */ + function unsetHeartbeatProperty ($propertyName, $workspace) + { + if (isset( $this->_aHeartbeatConfig[$workspace][$propertyName] )) + unset( $this->_aHeartbeatConfig[$workspace][$propertyName] ); + $this->saveSingleton(); + } + + /** + * Returns the value of a defined property. + * If it doesn't exist then returns null + * + * @param string $propertyName + * @return string/null + */ + function getHeartbeatProperty ($propertyName, $workspace) + { + if (isset( $this->_aHeartbeatConfig[$workspace][$propertyName] )) { + return $this->_aHeartbeatConfig[$workspace][$propertyName]; + } else { + return null; + } + } + + function isRtl ($lang = SYS_LANG) + { + $lang = substr( $lang, 0, 2 ); + return in_array( $lang, $this->rtlLang ); + } } \ No newline at end of file From f11a2fdd935ab94eda5dbabaf49b99ce8b7513aa Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:22:53 -0400 Subject: [PATCH 06/18] CODE STYLE class.sessions.php --- workflow/engine/classes/class.sessions.php | 461 +++++++++++---------- 1 file changed, 232 insertions(+), 229 deletions(-) diff --git a/workflow/engine/classes/class.sessions.php b/workflow/engine/classes/class.sessions.php index 283ea6164..e4912f36b 100755 --- a/workflow/engine/classes/class.sessions.php +++ b/workflow/engine/classes/class.sessions.php @@ -1,11 +1,12 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., + * along with this program. If not, see . + * + * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * + * */ require_once 'classes/model/Session.php'; + /** * Sessions - Sessions class + * * @package workflow.engine.ProcessMaker * @author Everth S. Berrios Morales * @copyright 2008 COLOSA */ -class Sessions { - - protected $tmpfile; - private $sessionId; - private $globals; - - /** - * This function is the constructor of the Sessions class - * @param string $sSessionId - * @return void - */ - public function __construct($sSessionId=NULL){ - $this->sessionId = $sSessionId; - } - - /** - * This function gets the user session - * - * - * @name getSessionUser - * - * @param string sSessionId - * @return array - */ - public function getSessionUser($sSessionId=NULL) - { - try - { - if($sSessionId != NULL){ - $this->sessionId = $sSessionId; - } else if($this->sessionId == NULL){ - throw new Exception('session id was not set.'); - } - - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(SessionPeer::USR_UID); - $oCriteria->addSelectColumn(SessionPeer::SES_STATUS); - $oCriteria->addSelectColumn(SessionPeer::SES_DUE_DATE); - $oCriteria->add(SessionPeer::SES_UID, $this->sessionId); - - $oDataset = SessionPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - $aRow = $oDataset->getRow(); - - if( !is_array($aRow) ){ - $this->deleteTmpfile(); - } - return $aRow; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * This function checks the user session - * - * - * @name verifySession - * - * @param string sSessionId - * @return array - */ - public function verifySession($sSessionId=NULL) - { - try - { - if($sSessionId != NULL){ - $this->sessionId = $sSessionId; - } else if($this->sessionId == NULL){ - throw new Exception('session id was not set.'); - } - - $date=date('Y-m-d H:i:s'); - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(SessionPeer::USR_UID); - $oCriteria->addSelectColumn(SessionPeer::SES_STATUS); - $oCriteria->addSelectColumn(SessionPeer::SES_DUE_DATE); - $oCriteria->add(SessionPeer::SES_UID, $this->sessionId); - $oCriteria->add(SessionPeer::SES_STATUS, 'ACTIVE'); - $oCriteria->add(SessionPeer::SES_DUE_DATE, $date, Criteria::GREATER_EQUAL); - - $oDataset = SessionPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - $aRow = $oDataset->getRow(); +class Sessions +{ - if( !is_array($aRow) ){ - $this->deleteTmpfile(); - } - - return $aRow; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * This function registers into globals variables - * - * - * @name registerGlobal - * - * @param string $name - * @param string $value - * @return void - */ - public function registerGlobal($name, $value) - { - $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; - - if($this->sessionId == NULL){ - throw new Exception('session id was not set.'); - } - - $tmpfile_content = ''; - if( is_file($this->tmpfile) && trim(file_get_contents($this->tmpfile)) != '' ) { - $tmpfile_content = file_get_contents($this->tmpfile); - } - - //getting the global array - if( $tmpfile_content != ''){ - $this->globals = unserialize($tmpfile_content); - } else { - $this->globals = Array(); - } - - //registering the new global variable - $this->globals[$name] = $value; - - //saving the global array - $tmpfile_content = serialize($this->globals); - file_put_contents($this->tmpfile, $tmpfile_content); - - } - - /** - * This function gets a global variable - * - * - * @name getGlobal - * - * @param string $name - * @return string - */ - public function getGlobal($name) - { - $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; - - if($this->sessionId == NULL){ - throw new Exception('session id was not set.'); - } - - $tmpfile_content = ''; - if( is_file($this->tmpfile) && trim(file_get_contents($this->tmpfile)) != '' ) { - $tmpfile_content = file_get_contents($this->tmpfile); - } - - //getting the global array - if( $tmpfile_content != ''){ - $this->globals = unserialize($tmpfile_content); - } else { - $this->globals = Array(); - } - - //getting the new global variable - if( isset($this->globals[$name]) ){ - return $this->globals[$name]; - } else { - return ''; - } - } - - /** - * This function gets all globals variables - * - * - * @name getGlobals - * - * @param string $name - * @return array - */ - public function getGlobals() - { - $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; - - if($this->sessionId == NULL){ - throw new Exception('session id was not set.'); - } - - $tmpfile_content = ''; - if( is_file($this->tmpfile) && trim(file_get_contents($this->tmpfile)) != '' ) { - $tmpfile_content = file_get_contents($this->tmpfile); - } - - //getting the global array - if( $tmpfile_content != ''){ - $this->globals = unserialize($tmpfile_content); - } else { - $this->globals = Array(); - } - return $this->globals; - } - - /** - * This function removes a temporal file - * - * - * @name deleteTmpfile - * - * param - * @return void - */ - private function deleteTmpfile(){ - if($this->sessionId == NULL){ - throw new Exception('session id was not set.'); + protected $tmpfile; + private $sessionId; + private $globals; + + /** + * This function is the constructor of the Sessions class + * + * @param string $sSessionId + * @return void + */ + public function __construct ($sSessionId = NULL) + { + $this->sessionId = $sSessionId; } - $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; - @unlink($this->tmpfile); - } - + + /** + * This function gets the user session + * + * + * @name getSessionUser + * + * @param string sSessionId + * @return array + */ + public function getSessionUser ($sSessionId = NULL) + { + try { + if ($sSessionId != NULL) { + $this->sessionId = $sSessionId; + } else if ($this->sessionId == NULL) { + throw new Exception( 'session id was not set.' ); + } + + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( SessionPeer::USR_UID ); + $oCriteria->addSelectColumn( SessionPeer::SES_STATUS ); + $oCriteria->addSelectColumn( SessionPeer::SES_DUE_DATE ); + $oCriteria->add( SessionPeer::SES_UID, $this->sessionId ); + + $oDataset = SessionPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aRow = $oDataset->getRow(); + + if (! is_array( $aRow )) { + $this->deleteTmpfile(); + } + return $aRow; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * This function checks the user session + * + * + * @name verifySession + * + * @param string sSessionId + * @return array + */ + public function verifySession ($sSessionId = NULL) + { + try { + if ($sSessionId != NULL) { + $this->sessionId = $sSessionId; + } else if ($this->sessionId == NULL) { + throw new Exception( 'session id was not set.' ); + } + + $date = date( 'Y-m-d H:i:s' ); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( SessionPeer::USR_UID ); + $oCriteria->addSelectColumn( SessionPeer::SES_STATUS ); + $oCriteria->addSelectColumn( SessionPeer::SES_DUE_DATE ); + $oCriteria->add( SessionPeer::SES_UID, $this->sessionId ); + $oCriteria->add( SessionPeer::SES_STATUS, 'ACTIVE' ); + $oCriteria->add( SessionPeer::SES_DUE_DATE, $date, Criteria::GREATER_EQUAL ); + + $oDataset = SessionPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aRow = $oDataset->getRow(); + + if (! is_array( $aRow )) { + $this->deleteTmpfile(); + } + + return $aRow; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * This function registers into globals variables + * + * + * @name registerGlobal + * + * @param string $name + * @param string $value + * @return void + */ + public function registerGlobal ($name, $value) + { + $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; + + if ($this->sessionId == NULL) { + throw new Exception( 'session id was not set.' ); + } + + $tmpfile_content = ''; + if (is_file( $this->tmpfile ) && trim( file_get_contents( $this->tmpfile ) ) != '') { + $tmpfile_content = file_get_contents( $this->tmpfile ); + } + + //getting the global array + if ($tmpfile_content != '') { + $this->globals = unserialize( $tmpfile_content ); + } else { + $this->globals = Array (); + } + + //registering the new global variable + $this->globals[$name] = $value; + + //saving the global array + $tmpfile_content = serialize( $this->globals ); + file_put_contents( $this->tmpfile, $tmpfile_content ); + + } + + /** + * This function gets a global variable + * + * + * @name getGlobal + * + * @param string $name + * @return string + */ + public function getGlobal ($name) + { + $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; + + if ($this->sessionId == NULL) { + throw new Exception( 'session id was not set.' ); + } + + $tmpfile_content = ''; + if (is_file( $this->tmpfile ) && trim( file_get_contents( $this->tmpfile ) ) != '') { + $tmpfile_content = file_get_contents( $this->tmpfile ); + } + + //getting the global array + if ($tmpfile_content != '') { + $this->globals = unserialize( $tmpfile_content ); + } else { + $this->globals = Array (); + } + + //getting the new global variable + if (isset( $this->globals[$name] )) { + return $this->globals[$name]; + } else { + return ''; + } + } + + /** + * This function gets all globals variables + * + * + * @name getGlobals + * + * @param string $name + * @return array + */ + public function getGlobals () + { + $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; + + if ($this->sessionId == NULL) { + throw new Exception( 'session id was not set.' ); + } + + $tmpfile_content = ''; + if (is_file( $this->tmpfile ) && trim( file_get_contents( $this->tmpfile ) ) != '') { + $tmpfile_content = file_get_contents( $this->tmpfile ); + } + + //getting the global array + if ($tmpfile_content != '') { + $this->globals = unserialize( $tmpfile_content ); + } else { + $this->globals = Array (); + } + return $this->globals; + } + + /** + * This function removes a temporal file + * + * + * @name deleteTmpfile + * + * param + * @return void + */ + private function deleteTmpfile () + { + if ($this->sessionId == NULL) { + throw new Exception( 'session id was not set.' ); + } + $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; + @unlink( $this->tmpfile ); + } + } From afa04ae6a88b80822e735e92d7e41e48f3a92590 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:23:16 -0400 Subject: [PATCH 07/18] CODE STYLE class.solr.php --- workflow/engine/classes/class.solr.php | 1070 ++++++++++++------------ 1 file changed, 541 insertions(+), 529 deletions(-) diff --git a/workflow/engine/classes/class.solr.php b/workflow/engine/classes/class.solr.php index 52061bad4..6aa025006 100644 --- a/workflow/engine/classes/class.solr.php +++ b/workflow/engine/classes/class.solr.php @@ -1,6 +1,6 @@ _solrIsEnabled = $solrIsEnabled; - $this->_solrHost = $solrHost; - } - - /** - * Verify if the Solr service is available - * @gearman = false - * @rest = false - * @background = false - * - * @return bool - */ - public function isEnabled() - { - // verify solr server response - - return $this->_solrIsEnabled; - } - - /** - * Returns the total number of indexed documents - * @gearman = false - * @rest = false - * @background = false - * - * @param - * workspace: workspace name - * @return total - */ - public function getNumberDocuments($workspace) - { - if (! $this->_solrIsEnabled) - return; - // get configuration information in base to workspace parameter - - // get total number of documents in registry - $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $workspace; - $solrIntruct .= "/select/?q=*:*"; - $solrIntruct .= self::SOLR_VERSION; - $solrIntruct .= "&start=0&rows=0&echoParams=none&wt=json"; - - $handlerTotal = curl_init ($solrIntruct); - curl_setopt ($handlerTotal, CURLOPT_RETURNTRANSFER, true); - - //Apply proxy settings - $sysConf = System::getSystemConfiguration(); - if ($sysConf['proxy_host'] != '') { - curl_setopt($handlerTotal, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); - if ($sysConf['proxy_port'] != '') { - curl_setopt($handlerTotal, CURLOPT_PROXYPORT, $sysConf['proxy_port']); - } - if ($sysConf['proxy_user'] != '') { - curl_setopt($handlerTotal, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); - } - curl_setopt($handlerTotal, CURLOPT_HTTPHEADER, array('Expect:')); + public function __construct ($solrIsEnabled = false, $solrHost = "") + { + // use the parameters to initialize class + $this->_solrIsEnabled = $solrIsEnabled; + $this->_solrHost = $solrHost; } - $responseTotal = curl_exec ($handlerTotal); - curl_close ($handlerTotal); + /** + * Verify if the Solr service is available + * @gearman = false + * @rest = false + * @background = false + * + * @return bool + */ + public function isEnabled () + { + // verify solr server response - // verify the result of solr - $responseSolrTotal = G::json_decode ($responseTotal); - if ($responseSolrTotal->responseHeader->status != 0) { - throw new Exception ("Error returning the total number of documents in Solr." . $solrIntruct . " response error: " . $response . "\n"); - } - $numTotalDocs = $responseSolrTotal->response->numFound; - return $numTotalDocs; - } - /** - * Execute a query in base to Requested data - * @gearman = false - * @rest = false - * @background = false - * - * @return solr response - */ - public function executeQuery($solrRequestData) - { - if (! $this->_solrIsEnabled) - return; - $solrIntruct = ''; - // get configuration information in base to workspace parameter - $workspace = $solrRequestData->workspace; - - // format request - $query = empty ($solrRequestData->searchText) ? '*:*' : $solrRequestData->searchText; - $query = rawurlencode ($query); - $start = '&start=' . $solrRequestData->startAfter; - $rows = '&rows=' . $solrRequestData->pageSize; - $fieldList = ''; - $cols = $solrRequestData->includeCols; - if (! empty ($cols)) { - $fieldList = "&fl=" . implode (",", $cols); - } - $sort = ''; - if ($solrRequestData->numSortingCols > 0) { - $sort = '&sort='; - for ($i = 0; $i < $solrRequestData->numSortingCols; $i ++) { - $sort .= $solrRequestData->sortCols [$i] . "%20" . $solrRequestData->sortDir [$i] . ","; - } - - $sort = substr_replace ($sort, "", - 1); - } - $resultFormat = empty ($solrRequestData->resultFormat) ? '' : '&wt=' . $solrRequestData->resultFormat; - $filters = ''; - $aFilters = explode (',', $solrRequestData->filterText); - foreach ($aFilters as $value) { - $filters .= '&fq=' . urlencode ($value); + return $this->_solrIsEnabled; } - $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $workspace; - $solrIntruct .= "/select/?q=$query"; - $solrIntruct .= "&echoParams=none"; - $solrIntruct .= self::SOLR_VERSION; - $solrIntruct .= $start; - $solrIntruct .= $rows; - $solrIntruct .= $fieldList; - $solrIntruct .= $sort; - $solrIntruct .= $filters; - $solrIntruct .= $resultFormat; - // send query - // search the cases in base to datatable parameters - $handler = curl_init ($solrIntruct); - curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true); + /** + * Returns the total number of indexed documents + * @gearman = false + * @rest = false + * @background = false + * + * @param workspace: workspace name + * @return total + */ + public function getNumberDocuments ($workspace) + { + if (! $this->_solrIsEnabled) + return; + // get configuration information in base to workspace parameter - //Apply proxy settings - $sysConf = System::getSystemConfiguration(); - if ($sysConf['proxy_host'] != '') { - curl_setopt($handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); - if ($sysConf['proxy_port'] != '') { - curl_setopt($handler, CURLOPT_PROXYPORT, $sysConf['proxy_port']); - } - if ($sysConf['proxy_user'] != '') { - curl_setopt($handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); - } - curl_setopt($handler, CURLOPT_HTTPHEADER, array('Expect:')); + + // get total number of documents in registry + $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $workspace; + $solrIntruct .= "/select/?q=*:*"; + $solrIntruct .= self::SOLR_VERSION; + $solrIntruct .= "&start=0&rows=0&echoParams=none&wt=json"; + + $handlerTotal = curl_init( $solrIntruct ); + curl_setopt( $handlerTotal, CURLOPT_RETURNTRANSFER, true ); + + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt( $handlerTotal, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + if ($sysConf['proxy_port'] != '') { + curl_setopt( $handlerTotal, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt( $handlerTotal, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + } + curl_setopt( $handlerTotal, CURLOPT_HTTPHEADER, array ('Expect:' + ) ); + } + + $responseTotal = curl_exec( $handlerTotal ); + curl_close( $handlerTotal ); + + // verify the result of solr + $responseSolrTotal = G::json_decode( $responseTotal ); + if ($responseSolrTotal->responseHeader->status != 0) { + throw new Exception( "Error returning the total number of documents in Solr." . $solrIntruct . " response error: " . $response . "\n" ); + } + $numTotalDocs = $responseSolrTotal->response->numFound; + return $numTotalDocs; } - $response = curl_exec ($handler); - curl_close ($handler); + /** + * Execute a query in base to Requested data + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function executeQuery ($solrRequestData) + { + if (! $this->_solrIsEnabled) + return; + $solrIntruct = ''; + // get configuration information in base to workspace parameter + $workspace = $solrRequestData->workspace; - // decode - $responseSolr = G::json_decode ($response); - if ($responseSolr->responseHeader->status != 0) { - throw new Exception ("Error executing query to Solr." . $solrIntruct . " response error: " . $response . "\n"); + // format request + $query = empty( $solrRequestData->searchText ) ? '*:*' : $solrRequestData->searchText; + $query = rawurlencode( $query ); + $start = '&start=' . $solrRequestData->startAfter; + $rows = '&rows=' . $solrRequestData->pageSize; + $fieldList = ''; + $cols = $solrRequestData->includeCols; + if (! empty( $cols )) { + $fieldList = "&fl=" . implode( ",", $cols ); + } + $sort = ''; + if ($solrRequestData->numSortingCols > 0) { + $sort = '&sort='; + for ($i = 0; $i < $solrRequestData->numSortingCols; $i ++) { + $sort .= $solrRequestData->sortCols[$i] . "%20" . $solrRequestData->sortDir[$i] . ","; + } + + $sort = substr_replace( $sort, "", - 1 ); + } + $resultFormat = empty( $solrRequestData->resultFormat ) ? '' : '&wt=' . $solrRequestData->resultFormat; + $filters = ''; + $aFilters = explode( ',', $solrRequestData->filterText ); + foreach ($aFilters as $value) { + $filters .= '&fq=' . urlencode( $value ); + } + + $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $workspace; + $solrIntruct .= "/select/?q=$query"; + $solrIntruct .= "&echoParams=none"; + $solrIntruct .= self::SOLR_VERSION; + $solrIntruct .= $start; + $solrIntruct .= $rows; + $solrIntruct .= $fieldList; + $solrIntruct .= $sort; + $solrIntruct .= $filters; + $solrIntruct .= $resultFormat; + // send query + // search the cases in base to datatable parameters + $handler = curl_init( $solrIntruct ); + curl_setopt( $handler, CURLOPT_RETURNTRANSFER, true ); + + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt( $handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + if ($sysConf['proxy_port'] != '') { + curl_setopt( $handler, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt( $handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + } + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Expect:' + ) ); + } + + $response = curl_exec( $handler ); + curl_close( $handler ); + + // decode + $responseSolr = G::json_decode( $response ); + if ($responseSolr->responseHeader->status != 0) { + throw new Exception( "Error executing query to Solr." . $solrIntruct . " response error: " . $response . "\n" ); + } + + return $responseSolr; } - return $responseSolr; - } + /** + * Insert or Update document index + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function updateDocument ($solrUpdateDocument) + { + if (! $this->_solrIsEnabled) + return; + $solrIntruct = ''; + // get configuration information in base to workspace parameter + $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $solrUpdateDocument->workspace; + $solrIntruct .= "/update"; - /** - * Insert or Update document index - * @gearman = false - * @rest = false - * @background = false - * - * @return solr response - */ - public function updateDocument($solrUpdateDocument) - { - if (! $this->_solrIsEnabled) - return; - $solrIntruct = ''; - // get configuration information in base to workspace parameter - $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $solrUpdateDocument->workspace; - $solrIntruct .= "/update"; + $handler = curl_init( $solrIntruct ); + curl_setopt( $handler, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Content-type:application/xml' + ) ); // -H + curl_setopt( $handler, CURLOPT_BINARYTRANSFER, TRUE ); // --data-binary + curl_setopt( $handler, CURLOPT_POSTFIELDS, $solrUpdateDocument->document ); // data - $handler = curl_init ($solrIntruct); - curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true); - curl_setopt ($handler, CURLOPT_HTTPHEADER, array ( - 'Content-type:application/xml' - )); // -H - curl_setopt ($handler, CURLOPT_BINARYTRANSFER, TRUE); // --data-binary - curl_setopt ($handler, CURLOPT_POSTFIELDS, $solrUpdateDocument->document); // data - //Apply proxy settings - $sysConf = System::getSystemConfiguration(); - if ($sysConf['proxy_host'] != '') { - curl_setopt($handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); - if ($sysConf['proxy_port'] != '') { - curl_setopt($handler, CURLOPT_PROXYPORT, $sysConf['proxy_port']); - } - if ($sysConf['proxy_user'] != '') { - curl_setopt($handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); - } - curl_setopt($handler, CURLOPT_HTTPHEADER, array('Expect:')); + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt( $handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + if ($sysConf['proxy_port'] != '') { + curl_setopt( $handler, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt( $handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + } + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Expect:' + ) ); + } + + $response = curl_exec( $handler ); + curl_close( $handler ); + + $swOk = strpos( $response, '0' ); + if (! $swOk) { + throw new Exception( "Error updating document in Solr." . $solrIntruct . " response error: " . $response . "\n" ); + } } - $response = curl_exec ($handler); - curl_close ($handler); + /** + * Commit the changes since the last commit + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function commitChanges ($workspace) + { + if (! $this->_solrIsEnabled) + return; + $solrIntruct = ''; + // get configuration information in base to workspace parameter + $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $workspace; + $solrIntruct .= "/update"; - $swOk = strpos ($response, '0'); - if (! $swOk) { - throw new Exception ("Error updating document in Solr." . $solrIntruct . " response error: " . $response . "\n"); - } - } + $handler = curl_init( $solrIntruct ); + curl_setopt( $handler, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Content-type:application/xml' + ) ); // -H + curl_setopt( $handler, CURLOPT_BINARYTRANSFER, TRUE ); // --data-binary + curl_setopt( $handler, CURLOPT_POSTFIELDS, "" ); // data - /** - * Commit the changes since the last commit - * @gearman = false - * @rest = false - * @background = false - * - * @return solr response - */ - public function commitChanges($workspace) - { - if (! $this->_solrIsEnabled) - return; - $solrIntruct = ''; - // get configuration information in base to workspace parameter - $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $workspace; - $solrIntruct .= "/update"; - $handler = curl_init ($solrIntruct); - curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true); - curl_setopt ($handler, CURLOPT_HTTPHEADER, array ( - 'Content-type:application/xml' - )); // -H - curl_setopt ($handler, CURLOPT_BINARYTRANSFER, TRUE); // --data-binary - curl_setopt ($handler, CURLOPT_POSTFIELDS, ""); // data + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt( $handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + if ($sysConf['proxy_port'] != '') { + curl_setopt( $handler, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt( $handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + } + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Expect:' + ) ); + } - //Apply proxy settings - $sysConf = System::getSystemConfiguration(); - if ($sysConf['proxy_host'] != '') { - curl_setopt($handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); - if ($sysConf['proxy_port'] != '') { - curl_setopt($handler, CURLOPT_PROXYPORT, $sysConf['proxy_port']); - } - if ($sysConf['proxy_user'] != '') { - curl_setopt($handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); - } - curl_setopt($handler, CURLOPT_HTTPHEADER, array('Expect:')); + $response = curl_exec( $handler ); + curl_close( $handler ); + + $swOk = strpos( $response, '0' ); + if (! $swOk) { + throw new Exception( "Error commiting changes in Solr." . $solrIntruct . " response error: " . $response . "\n" ); + } } - $response = curl_exec ($handler); - curl_close ($handler); + /** + * Rollback the changes since the last commit + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function rollbackChanges ($workspace) + { + if (! $this->_solrIsEnabled) + return; - $swOk = strpos ($response, '0'); - if (! $swOk) { - throw new Exception ("Error commiting changes in Solr." . $solrIntruct . " response error: " . $response . "\n"); - } - } + $solrIntruct = ''; + // get configuration information in base to workspace parameter + $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $workspace; + $solrIntruct .= "/update"; - /** - * Rollback the changes since the last commit - * @gearman = false - * @rest = false - * @background = false - * - * @return solr response - */ - public function rollbackChanges($workspace) - { - if (! $this->_solrIsEnabled) - return; + $handler = curl_init( $solrIntruct ); + curl_setopt( $handler, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Content-type:application/xml' + ) ); // -H + curl_setopt( $handler, CURLOPT_BINARYTRANSFER, TRUE ); // --data-binary + curl_setopt( $handler, CURLOPT_POSTFIELDS, "" ); // data - $solrIntruct = ''; - // get configuration information in base to workspace parameter - $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $workspace; - $solrIntruct .= "/update"; - $handler = curl_init ($solrIntruct); - curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true); - curl_setopt ($handler, CURLOPT_HTTPHEADER, array ( - 'Content-type:application/xml' - )); // -H - curl_setopt ($handler, CURLOPT_BINARYTRANSFER, TRUE); // --data-binary - curl_setopt ($handler, CURLOPT_POSTFIELDS, ""); // data + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt( $handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + if ($sysConf['proxy_port'] != '') { + curl_setopt( $handler, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt( $handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + } + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Expect:' + ) ); + } - //Apply proxy settings - $sysConf = System::getSystemConfiguration(); - if ($sysConf['proxy_host'] != '') { - curl_setopt($handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); - if ($sysConf['proxy_port'] != '') { - curl_setopt($handler, CURLOPT_PROXYPORT, $sysConf['proxy_port']); - } - if ($sysConf['proxy_user'] != '') { - curl_setopt($handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); - } - curl_setopt($handler, CURLOPT_HTTPHEADER, array('Expect:')); + $response = curl_exec( $handler ); + curl_close( $handler ); + + $swOk = strpos( $response, '0' ); + if (! $swOk) { + throw new Exception( "Error rolling back changes in Solr." . $solrIntruct . " response error: " . $response . "\n" ); + } } - $response = curl_exec ($handler); - curl_close ($handler); + /** + * Optimize Solr index + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function optimizeChanges ($workspace) + { + if (! $this->_solrIsEnabled) + return; - $swOk = strpos ($response, '0'); - if (! $swOk) { - throw new Exception ("Error rolling back changes in Solr." . $solrIntruct . " response error: " . $response . "\n"); - } - } + $solrIntruct = ''; + // get configuration information in base to workspace parameter + $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $workspace; + $solrIntruct .= "/update"; - /** - * Optimize Solr index - * @gearman = false - * @rest = false - * @background = false - * - * @return solr response - */ - public function optimizeChanges($workspace) - { - if (! $this->_solrIsEnabled) - return; + $handler = curl_init( $solrIntruct ); + curl_setopt( $handler, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Content-type:application/xml' + ) ); // -H + curl_setopt( $handler, CURLOPT_BINARYTRANSFER, TRUE ); // --data-binary + curl_setopt( $handler, CURLOPT_POSTFIELDS, "" ); // data - $solrIntruct = ''; - // get configuration information in base to workspace parameter - $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $workspace; - $solrIntruct .= "/update"; - $handler = curl_init ($solrIntruct); - curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true); - curl_setopt ($handler, CURLOPT_HTTPHEADER, array ( - 'Content-type:application/xml' - )); // -H - curl_setopt ($handler, CURLOPT_BINARYTRANSFER, TRUE); // --data-binary - curl_setopt ($handler, CURLOPT_POSTFIELDS, ""); // data + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt( $handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + if ($sysConf['proxy_port'] != '') { + curl_setopt( $handler, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt( $handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + } + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Expect:' + ) ); + } - //Apply proxy settings - $sysConf = System::getSystemConfiguration(); - if ($sysConf['proxy_host'] != '') { - curl_setopt($handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); - if ($sysConf['proxy_port'] != '') { - curl_setopt($handler, CURLOPT_PROXYPORT, $sysConf['proxy_port']); - } - if ($sysConf['proxy_user'] != '') { - curl_setopt($handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); - } - curl_setopt($handler, CURLOPT_HTTPHEADER, array('Expect:')); + $response = curl_exec( $handler ); + curl_close( $handler ); + + $swOk = strpos( $response, '0' ); + if (! $swOk) { + throw new Exception( "Error optimizing changes in Solr." . $solrIntruct . " response error: " . $response . "\n" ); + } } - $response = curl_exec ($handler); - curl_close ($handler); + /** + * Return the list of the stored fields in Solr + * + * @param string $workspace Solr instance name + * @throws Exception + * @return void mixed of field names + */ + public function getListIndexedStoredFields ($workspace) + { + if (! $this->_solrIsEnabled) + return; - $swOk = strpos ($response, '0'); - if (! $swOk) { - throw new Exception ("Error optimizing changes in Solr." . $solrIntruct . " response error: " . $response . "\n"); - } - } + $solrIntruct = ''; + // get configuration information in base to workspace parameter + $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $workspace; + $solrIntruct .= "/admin/luke?numTerms=0&wt=json"; - /** - * Return the list of the stored fields in Solr - * - * @param string $workspace - * Solr instance name - * @throws Exception - * @return void mixed of field names - */ - public function getListIndexedStoredFields($workspace) - { - if (! $this->_solrIsEnabled) - return; + $handler = curl_init( $solrIntruct ); + curl_setopt( $handler, CURLOPT_RETURNTRANSFER, true ); - $solrIntruct = ''; - // get configuration information in base to workspace parameter - $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $workspace; - $solrIntruct .= "/admin/luke?numTerms=0&wt=json"; + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt( $handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + if ($sysConf['proxy_port'] != '') { + curl_setopt( $handler, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt( $handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + } + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Expect:' + ) ); + } - $handler = curl_init ($solrIntruct); - curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true); - - //Apply proxy settings - $sysConf = System::getSystemConfiguration(); - if ($sysConf['proxy_host'] != '') { - curl_setopt($handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); - if ($sysConf['proxy_port'] != '') { - curl_setopt($handler, CURLOPT_PROXYPORT, $sysConf['proxy_port']); - } - if ($sysConf['proxy_user'] != '') { - curl_setopt($handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); - } - curl_setopt($handler, CURLOPT_HTTPHEADER, array('Expect:')); + $response = curl_exec( $handler ); + curl_close( $handler ); + // decode + $responseSolr = G::json_decode( $response ); + if ($responseSolr->responseHeader->status != 0) { + throw new Exception( "Error getting index fields in Solr." . $solrIntruct . " response error: " . $response . "\n" ); + } + return $responseSolr; } - $response = curl_exec ($handler); - curl_close ($handler); - // decode - $responseSolr = G::json_decode ($response); - if ($responseSolr->responseHeader->status != 0) { - throw new Exception ("Error getting index fields in Solr." . $solrIntruct . " response error: " . $response . "\n"); - } - return $responseSolr; - } + /** + * Delete all documents from index + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function deleteAllDocuments ($workspace) + { + if (! $this->_solrIsEnabled) + return; + // $registry = Zend_Registry::getInstance(); - /** - * Delete all documents from index - * @gearman = false - * @rest = false - * @background = false - * - * @return solr response - */ - public function deleteAllDocuments($workspace) - { - if (! $this->_solrIsEnabled) - return; - // $registry = Zend_Registry::getInstance(); - $solrIntruct = ''; - // get configuration information in base to workspace parameter - $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $workspace; - $solrIntruct .= "/update"; + $solrIntruct = ''; + // get configuration information in base to workspace parameter + $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $workspace; + $solrIntruct .= "/update"; - $handler = curl_init ($solrIntruct); - curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true); - curl_setopt ($handler, CURLOPT_HTTPHEADER, array ( - 'Content-type:application/xml' - )); // -H - curl_setopt ($handler, CURLOPT_BINARYTRANSFER, TRUE); // --data-binary - curl_setopt ($handler, CURLOPT_POSTFIELDS, "*:*"); // data + $handler = curl_init( $solrIntruct ); + curl_setopt( $handler, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Content-type:application/xml' + ) ); // -H + curl_setopt( $handler, CURLOPT_BINARYTRANSFER, TRUE ); // --data-binary + curl_setopt( $handler, CURLOPT_POSTFIELDS, "*:*" ); // data - //Apply proxy settings - $sysConf = System::getSystemConfiguration(); - if ($sysConf['proxy_host'] != '') { - curl_setopt($handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); - if ($sysConf['proxy_port'] != '') { - curl_setopt($handler, CURLOPT_PROXYPORT, $sysConf['proxy_port']); - } - if ($sysConf['proxy_user'] != '') { - curl_setopt($handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); - } - curl_setopt($handler, CURLOPT_HTTPHEADER, array('Expect:')); + + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt( $handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + if ($sysConf['proxy_port'] != '') { + curl_setopt( $handler, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt( $handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + } + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Expect:' + ) ); + } + + $response = curl_exec( $handler ); + + curl_close( $handler ); + + $swOk = strpos( $response, '0' ); + if (! $swOk) { + throw new Exception( "Error deleting all documents in Solr." . $solrIntruct . " response error: " . $response . "\n" ); + } } - $response = curl_exec ($handler); + /** + * Delete specified documents from index + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function deleteDocument ($workspace, $idQuery) + { + if (! $this->_solrIsEnabled) + return; + // $registry = Zend_Registry::getInstance(); - curl_close ($handler); - $swOk = strpos ($response, '0'); - if (! $swOk) { - throw new Exception ("Error deleting all documents in Solr." . $solrIntruct . " response error: " . $response . "\n"); - } - } + $solrIntruct = ''; + // get configuration information in base to workspace parameter + $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $workspace; + $solrIntruct .= "/update"; - /** - * Delete specified documents from index - * @gearman = false - * @rest = false - * @background = false - * - * @return solr response - */ - public function deleteDocument($workspace, $idQuery) - { - if (! $this->_solrIsEnabled) - return; - // $registry = Zend_Registry::getInstance(); + $handler = curl_init( $solrIntruct ); + curl_setopt( $handler, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Content-type:application/xml' + ) ); // -H + curl_setopt( $handler, CURLOPT_BINARYTRANSFER, TRUE ); // --data-binary + curl_setopt( $handler, CURLOPT_POSTFIELDS, "" . $idQuery . "" ); // data - $solrIntruct = ''; - // get configuration information in base to workspace parameter - $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $workspace; - $solrIntruct .= "/update"; - $handler = curl_init ($solrIntruct); - curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true); - curl_setopt ($handler, CURLOPT_HTTPHEADER, array ( - 'Content-type:application/xml' - )); // -H - curl_setopt ($handler, CURLOPT_BINARYTRANSFER, TRUE); // --data-binary - curl_setopt ($handler, CURLOPT_POSTFIELDS, "" . $idQuery . ""); // data + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt( $handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + if ($sysConf['proxy_port'] != '') { + curl_setopt( $handler, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt( $handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + } + curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Expect:' + ) ); + } - //Apply proxy settings - $sysConf = System::getSystemConfiguration(); - if ($sysConf['proxy_host'] != '') { - curl_setopt($handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); - if ($sysConf['proxy_port'] != '') { - curl_setopt($handler, CURLOPT_PROXYPORT, $sysConf['proxy_port']); - } - if ($sysConf['proxy_user'] != '') { - curl_setopt($handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); - } - curl_setopt($handler, CURLOPT_HTTPHEADER, array('Expect:')); + $response = curl_exec( $handler ); + + curl_close( $handler ); + + $swOk = strpos( $response, '0' ); + if (! $swOk) { + throw new Exception( "Error deleting document in Solr." . $solrIntruct . " response error: " . $response . "\n" ); + } } - $response = curl_exec ($handler); + /** + * Execute a query in base to Request data + * + * @param Entity_FacetRequest $facetRequestEntity + * @return solr response: list of facets array + */ + public function getFacetsList ($facetRequest) + { + if (! $this->_solrIsEnabled) + return; - curl_close ($handler); + $solrIntruct = ''; + // get configuration information in base to workspace parameter + $workspace = $facetRequest->workspace; - $swOk = strpos ($response, '0'); - if (! $swOk) { - throw new Exception ("Error deleting document in Solr." . $solrIntruct . " response error: " . $response . "\n"); + // format request + $query = empty( $facetRequest->searchText ) ? '*:*' : $facetRequest->searchText; + $query = rawurlencode( $query ); + $start = '&start=0'; + $rows = '&rows=0'; + $facets = '&facet=on&facet.mincount=1&facet.limit=20'; // enable facet and + // only return facets + // with minimun one + // instance + foreach ($facetRequest->facetFields as $value) { + $facets .= '&facet.field=' . $value; + } + foreach ($facetRequest->facetQueries as $value) { + $facets .= '&facet.query=' . $value; + } + if (! empty( $facetRequest->facetDates )) { + foreach ($facetRequest->facetDates as $value) { + $facets .= '&facet.date=' . $value; + } + $facets .= '&facet.date.start=' . $facetRequest->facetDatesStart; + $facets .= '&facet.date.end=' . $facetRequest->facetDatesEnd; + $facets .= '&facet.date.gap=' . $facetRequest->facetDateGap; + } + $filters = ''; + foreach ($facetRequest->filters as $value) { + $filters .= '&fq=' . $value; + } + // echo "
";
+
+
+        $resultFormat = '&wt=json';
+
+        $solrIntruct = (substr( $this->_solrHost, - 1 ) == "/") ? $this->_solrHost : $this->_solrHost . "/";
+        $solrIntruct .= $workspace;
+        $solrIntruct .= "/select/?q=$query";
+        $solrIntruct .= "&echoParams=none";
+        $solrIntruct .= self::SOLR_VERSION;
+        $solrIntruct .= $start;
+        $solrIntruct .= $rows;
+        $solrIntruct .= $facets;
+        $solrIntruct .= $filters;
+        $solrIntruct .= $resultFormat;
+
+        // send query
+        // search the cases in base to datatable parameters
+        $handler = curl_init( $solrIntruct );
+        curl_setopt( $handler, CURLOPT_RETURNTRANSFER, true );
+
+        //Apply proxy settings
+        $sysConf = System::getSystemConfiguration();
+        if ($sysConf['proxy_host'] != '') {
+            curl_setopt( $handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') );
+            if ($sysConf['proxy_port'] != '') {
+                curl_setopt( $handler, CURLOPT_PROXYPORT, $sysConf['proxy_port'] );
+            }
+            if ($sysConf['proxy_user'] != '') {
+                curl_setopt( $handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') );
+            }
+            curl_setopt( $handler, CURLOPT_HTTPHEADER, array ('Expect:'
+            ) );
+        }
+
+        $response = curl_exec( $handler );
+        curl_close( $handler );
+
+        // decode
+        $responseSolr = G::json_decode( $response );
+        if ($responseSolr->responseHeader->status != 0) {
+            throw new Exception( "Error getting faceted list from Solr." . $solrIntruct . " response error: " . $response . "\n" );
+        }
+
+        return $responseSolr;
     }
-  }
-
-  /**
-   * Execute a query in base to Request data
-   *
-   * @param Entity_FacetRequest $facetRequestEntity
-   * @return solr response: list of facets array
-   */
-  public function getFacetsList($facetRequest)
-  {
-    if (! $this->_solrIsEnabled)
-      return;
-
-    $solrIntruct = '';
-    // get configuration information in base to workspace parameter
-    $workspace = $facetRequest->workspace;
-
-    // format request
-    $query = empty ($facetRequest->searchText) ? '*:*' : $facetRequest->searchText;
-    $query = rawurlencode ($query);
-    $start = '&start=0';
-    $rows = '&rows=0';
-    $facets = '&facet=on&facet.mincount=1&facet.limit=20'; // enable facet and
-                                                           // only return facets
-                                                           // with minimun one
-                                                           // instance
-    foreach ($facetRequest->facetFields as $value) {
-      $facets .= '&facet.field=' . $value;
-    }
-    foreach ($facetRequest->facetQueries as $value) {
-      $facets .= '&facet.query=' . $value;
-    }
-    if (! empty ($facetRequest->facetDates)) {
-      foreach ($facetRequest->facetDates as $value) {
-        $facets .= '&facet.date=' . $value;
-      }
-      $facets .= '&facet.date.start=' . $facetRequest->facetDatesStart;
-      $facets .= '&facet.date.end=' . $facetRequest->facetDatesEnd;
-      $facets .= '&facet.date.gap=' . $facetRequest->facetDateGap;
-    }
-    $filters = '';
-    foreach ($facetRequest->filters as $value) {
-      $filters .= '&fq=' . $value;
-    }
-    // echo "
";
-
-    $resultFormat = '&wt=json';
-
-    $solrIntruct = (substr ($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/";
-    $solrIntruct .= $workspace;
-    $solrIntruct .= "/select/?q=$query";
-    $solrIntruct .= "&echoParams=none";
-    $solrIntruct .= self::SOLR_VERSION;
-    $solrIntruct .= $start;
-    $solrIntruct .= $rows;
-    $solrIntruct .= $facets;
-    $solrIntruct .= $filters;
-    $solrIntruct .= $resultFormat;
-
-    // send query
-    // search the cases in base to datatable parameters
-    $handler = curl_init ($solrIntruct);
-    curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true);
-
-    //Apply proxy settings
-    $sysConf = System::getSystemConfiguration();
-    if ($sysConf['proxy_host'] != '') {
-      curl_setopt($handler, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : ''));
-      if ($sysConf['proxy_port'] != '') {
-        curl_setopt($handler, CURLOPT_PROXYPORT, $sysConf['proxy_port']);
-      }
-      if ($sysConf['proxy_user'] != '') {
-        curl_setopt($handler, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
-      }
-      curl_setopt($handler, CURLOPT_HTTPHEADER, array('Expect:'));
-    }
-
-    $response = curl_exec ($handler);
-    curl_close ($handler);
-
-    // decode
-    $responseSolr = G::json_decode ($response);
-    if ($responseSolr->responseHeader->status != 0) {
-      throw new Exception ("Error getting faceted list from Solr." . $solrIntruct . " response error: " . $response . "\n");
-    }
-
-    return $responseSolr;
-  }
 }

From f926ac68e9037b0a9a5087c0dda74009313dd593 Mon Sep 17 00:00:00 2001
From: Fernando Ontiveros 
Date: Tue, 9 Oct 2012 13:24:35 -0400
Subject: [PATCH 08/18] CODE STYLE class.spool.php

---
 workflow/engine/classes/class.spool.php | 959 ++++++++++++------------
 1 file changed, 480 insertions(+), 479 deletions(-)

diff --git a/workflow/engine/classes/class.spool.php b/workflow/engine/classes/class.spool.php
index c145addff..497728e6d 100755
--- a/workflow/engine/classes/class.spool.php
+++ b/workflow/engine/classes/class.spool.php
@@ -1,6 +1,7 @@
 .
+ * along with this program. If not, see .
  *
  * For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
  * Coral Gables, FL, 33134, USA, or email info@colosa.com.
@@ -26,6 +27,7 @@
 
 /**
  * spoolRun - brief send email from the spool database, and see if we have all the addresses we send to.
+ *
  * @author Ian K Armstrong 
  * @copyright Copyright (c) 2007, Ian K Armstrong
  * @license http://www.opensource.org/licenses/gpl-3.0.html GNU Public License
@@ -36,7 +38,7 @@
  * LOG FIXES
  * =========
  *
- * 24-03-2010   Erik A.O. 
+ * 24-03-2010 Erik A.O. 
  * class: the $ExceptionCode and $aWarnings class attributes were added
  * function handleFrom(): Validations for invalid data for {$this->fileData['from_email']} were added
  * function resendEmails(): handler for warnings was added and fixes
@@ -46,472 +48,492 @@
 
 require_once ('classes/model/AppMessage.php');
 
- /**
-  * @package workflow.engine.ProcessMaker
-  */
+/**
+ *
+ * @package workflow.engine.ProcessMaker
+ */
+
+class spoolRun
+{
+    public $config;
+    private $fileData;
+    private $spool_id;
+    public $status;
+    public $error;
+
+    private $ExceptionCode = Array (); //Array to define the Expetion codes
+    private $aWarnings = Array (); //Array to store the warning that were throws by the class
 
 
-class spoolRun {
-  public  $config;
-  private $fileData;
-  private $spool_id;
-  public  $status;
-  public  $error;
+    private $longMailEreg;
+    private $mailEreg;
 
-  private $ExceptionCode = Array (); //Array to define the Expetion codes
-  private $aWarnings = Array (); //Array to store the warning that were throws by the class
+    /**
+     * Class constructor - iniatilize default values
+     *
+     * @param none
+     * @return none
+     */
+    public function __construct ()
+    {
+        $this->config = array ();
+        $this->fileData = array ();
+        $this->spool_id = '';
+        $this->status = 'pending';
+        $this->error = '';
 
-  private $longMailEreg;
-  private $mailEreg;
+        $this->ExceptionCode['FATAL'] = 1;
+        $this->ExceptionCode['WARNING'] = 2;
+        $this->ExceptionCode['NOTICE'] = 3;
 
+        $this->longMailEreg = '/(.*)(<([\w\-\.]+@[\w\-_\.]+\.\w{2,3})+>)/';
+        $this->mailEreg = '/^([\w\-_\.]+@[\w\-_\.]+\.\w{2,3}+)$/';
+    }
 
-  /**
-   * Class constructor - iniatilize default values
-   * @param none
-   * @return none
-   */
-  function __construct() {
-    $this->config = array ();
-    $this->fileData = array ();
-    $this->spool_id = '';
-    $this->status = 'pending';
-    $this->error = '';
+    /**
+     * get all files into spool in a list
+     *
+     * @param none
+     * @return none
+     */
+    public function getSpoolFilesList ()
+    {
+        $sql = "SELECT * FROM APP_MESSAGE WHERE APP_MSG_STATUS ='pending'";
 
-    $this->ExceptionCode['FATAL']   = 1;
-    $this->ExceptionCode['WARNING'] = 2;
-    $this->ExceptionCode['NOTICE']  = 3;
+        $con = Propel::getConnection( "workflow" );
+        $stmt = $con->prepareStatement( $sql );
+        $rs = $stmt->executeQuery();
 
-    $this->longMailEreg = '/(.*)(<([\w\-\.]+@[\w\-_\.]+\.\w{2,3})+>)/';
-    $this->mailEreg     = '/^([\w\-_\.]+@[\w\-_\.]+\.\w{2,3}+)$/';
-  }
+        while ($rs->next()) {
+            $this->spool_id = $rs->getString( 'APP_MSG_UID' );
+            $this->fileData['subject'] = $rs->getString( 'APP_MSG_SUBJECT' );
+            $this->fileData['from'] = $rs->getString( 'APP_MSG_FROM' );
+            $this->fileData['to'] = $rs->getString( 'APP_MSG_TO' );
+            $this->fileData['body'] = $rs->getString( 'APP_MSG_BODY' );
+            $this->fileData['date'] = $rs->getString( 'APP_MSG_DATE' );
+            $this->fileData['cc'] = $rs->getString( 'APP_MSG_CC' );
+            $this->fileData['bcc'] = $rs->getString( 'APP_MSG_BCC' );
+            $this->fileData['template'] = $rs->getString( 'APP_MSG_TEMPLATE' );
+            $this->fileData['attachments'] = array (); //$rs->getString('APP_MSG_ATTACH');
+            if ($this->config['MESS_ENGINE'] == 'OPENMAIL') {
+                if ($this->config['MESS_SERVER'] != '') {
+                    if (($sAux = @gethostbyaddr( $this->config['MESS_SERVER'] ))) {
+                        $this->fileData['domain'] = $sAux;
+                    } else {
+                        $this->fileData['domain'] = $this->config['MESS_SERVER'];
+                    }
+                } else {
+                    $this->fileData['domain'] = gethostbyaddr( '127.0.0.1' );
+                }
+            }
+            $this->sendMail();
+        }
+    }
 
-  /**
-   * get all files into spool in a list
-   * @param none
-   * @return none
-   */
-  public function getSpoolFilesList() {
-    $sql = "SELECT * FROM APP_MESSAGE WHERE APP_MSG_STATUS ='pending'";
+    /**
+     * create a msg record for spool
+     *
+     * @param array $aData
+     * @return none
+     */
+    public function create ($aData)
+    {
+        $sUID = $this->db_insert( $aData );
 
-    $con = Propel::getConnection("workflow");
-    $stmt = $con->prepareStatement($sql);
-    $rs = $stmt->executeQuery();
+        $aData['app_msg_date'] = isset( $aData['app_msg_date'] ) ? $aData['app_msg_date'] : '';
 
-    while( $rs->next() ) {
-      $this->spool_id = $rs->getString('APP_MSG_UID');
-      $this->fileData['subject'] = $rs->getString('APP_MSG_SUBJECT');
-      $this->fileData['from'] = $rs->getString('APP_MSG_FROM');
-      $this->fileData['to'] = $rs->getString('APP_MSG_TO');
-      $this->fileData['body'] = $rs->getString('APP_MSG_BODY');
-      $this->fileData['date'] = $rs->getString('APP_MSG_DATE');
-      $this->fileData['cc'] = $rs->getString('APP_MSG_CC');
-      $this->fileData['bcc'] = $rs->getString('APP_MSG_BCC');
-      $this->fileData['template'] = $rs->getString('APP_MSG_TEMPLATE');
-      $this->fileData['attachments'] = array (); //$rs->getString('APP_MSG_ATTACH');
-      if( $this->config['MESS_ENGINE'] == 'OPENMAIL' ) {
-        if( $this->config['MESS_SERVER'] != '' ) {
-          if( ($sAux = @gethostbyaddr($this->config['MESS_SERVER'])) ) {
-            $this->fileData['domain'] = $sAux;
-          } else {
-            $this->fileData['domain'] = $this->config['MESS_SERVER'];
-          }
+        if (isset( $aData['app_msg_status'] )) {
+            $this->status = strtolower( $aData['app_msg_status'] );
+        }
+
+        $this->setData( $sUID, $aData['app_msg_subject'], $aData['app_msg_from'], $aData['app_msg_to'], $aData['app_msg_body'], $aData['app_msg_date'], $aData['app_msg_cc'], $aData['app_msg_bcc'], $aData['app_msg_template'], $aData['app_msg_attach'] );
+    }
+
+    /**
+     * set configuration
+     *
+     * @param array $aConfig
+     * @return none
+     */
+    public function setConfig ($aConfig)
+    {
+        $this->config = $aConfig;
+    }
+
+    /**
+     * set email parameters
+     *
+     * @param string $sAppMsgUid, $sSubject, $sFrom, $sTo, $sBody, $sDate, $sCC, $sBCC, $sTemplate
+     * @return none
+     */
+    public function setData ($sAppMsgUid, $sSubject, $sFrom, $sTo, $sBody, $sDate = '', $sCC = '', $sBCC = '', $sTemplate = '', $aAttachment = array())
+    {
+        $this->spool_id = $sAppMsgUid;
+        $this->fileData['subject'] = $sSubject;
+        $this->fileData['from'] = $sFrom;
+        $this->fileData['to'] = $sTo;
+        $this->fileData['body'] = $sBody;
+        $this->fileData['date'] = ($sDate != '' ? $sDate : date( 'Y-m-d H:i:s' ));
+        $this->fileData['cc'] = $sCC;
+        $this->fileData['bcc'] = $sBCC;
+        $this->fileData['template'] = $sTemplate;
+        $this->fileData['attachments'] = is_array( $aAttachment ) ? $aAttachment : ($aAttachment != '' ? explode( ',', $aAttachment ) : array ());
+        $this->fileData['envelope_to'] = array ();
+
+        if ($this->config['MESS_ENGINE'] == 'OPENMAIL') {
+            if ($this->config['MESS_SERVER'] != '') {
+                if (($sAux = @gethostbyaddr( $this->config['MESS_SERVER'] ))) {
+                    $this->fileData['domain'] = $sAux;
+                } else {
+                    $this->fileData['domain'] = $this->config['MESS_SERVER'];
+                }
+            } else {
+                $this->fileData['domain'] = gethostbyaddr( '127.0.0.1' );
+            }
+        }
+    }
+
+    /**
+     * send mail
+     *
+     * @param none
+     * @return boolean true or exception
+     */
+    public function sendMail ()
+    {
+        try {
+            $this->handleFrom();
+            $this->handleEnvelopeTo();
+            $this->handleMail();
+            $this->updateSpoolStatus();
+            return true;
+        } catch (Exception $e) {
+            throw $e;
+        }
+    }
+
+    /**
+     * update the status to spool
+     *
+     * @param none
+     * @return none
+     */
+    private function updateSpoolStatus ()
+    {
+        $oAppMessage = AppMessagePeer::retrieveByPK( $this->spool_id );
+        if (is_array( $this->fileData['attachments'] )) {
+            $attachment = implode( ",", $this->fileData['attachments'] );
+            $oAppMessage->setappMsgAttach( $attachment );
+        }
+        $oAppMessage->setappMsgstatus( $this->status );
+        $oAppMessage->setappMsgsenddate( date( 'Y-m-d H:i:s' ) );
+        $oAppMessage->save();
+    }
+
+    /**
+     * handle the email that was set in "TO" parameter
+     *
+     * @param none
+     * @return boolean true or exception
+     */
+    private function handleFrom ()
+    {
+        if (strpos( $this->fileData['from'], '<' ) !== false) {
+            //to validate complex email address i.e. Erik A. O 
+            preg_match( $this->longMailEreg, $this->fileData['from'], $matches );
+            if (isset( $matches[1] ) && $matches[1] != '') {
+                //drop the " characters if they exist
+                $this->fileData['from_name'] = trim( str_replace( '"', '', $matches[1] ) );
+            } else {
+                //if the from name was not set
+                $this->fileData['from_name'] = '';
+            }
+
+            if (! isset( $matches[3] )) {
+                throw new Exception( 'Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING'] );
+            }
+
+            $this->fileData['from_email'] = trim( $matches[3] );
         } else {
-          $this->fileData['domain'] = gethostbyaddr('127.0.0.1');
+            //to validate simple email address i.e. erik@colosa.com
+            preg_match( $this->mailEreg, $this->fileData['from'], $matches );
+
+            if (! isset( $matches[0] )) {
+                throw new Exception( 'Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING'] );
+            }
+
+            $this->fileData['from_name'] = '';
+            $this->fileData['from_email'] = $matches[0];
         }
-      }
-      $this->sendMail();
-    }
-  }
 
-  /**
-   * create a msg record for spool
-   * @param array $aData
-   * @return none
-   */
-  public function create($aData) {
-    $sUID = $this->db_insert($aData);
-
-    $aData['app_msg_date'] = isset($aData['app_msg_date']) ? $aData['app_msg_date'] : '';
-
-    if( isset($aData['app_msg_status']) ) {
-      $this->status = strtolower($aData['app_msg_status']);
     }
 
-    $this->setData($sUID, $aData['app_msg_subject'], $aData['app_msg_from'], $aData['app_msg_to'], $aData['app_msg_body'], $aData['app_msg_date'], $aData['app_msg_cc'], $aData['app_msg_bcc'], $aData['app_msg_template'], $aData['app_msg_attach']);
-  }
+    /**
+     * handle all recipients to compose the mail
+     *
+     * @param none
+     * @return boolean true or exception
+     */
+    private function handleEnvelopeTo ()
+    {
+        $hold = array ();
+        $holdcc = array ();
+        $holdbcc = array ();
+        $text = trim( $this->fileData['to'] );
 
-  /**
-   * set configuration
-   * @param array $aConfig
-   * @return none
-   */
-  public function setConfig($aConfig) {
-    $this->config = $aConfig;
-  }
+        $textcc = '';
+        $textbcc = '';
+        if (isset( $this->fileData['cc'] ) && trim( $this->fileData['cc'] ) != '') {
+            $textcc = trim( $this->fileData['cc'] );
+        }
 
-  /**
-   * set email parameters
-   * @param string $sAppMsgUid, $sSubject, $sFrom, $sTo, $sBody, $sDate, $sCC, $sBCC, $sTemplate
-   * @return none
-   */
-  public function setData($sAppMsgUid, $sSubject, $sFrom, $sTo, $sBody, $sDate = '', $sCC = '', $sBCC = '', $sTemplate = '', $aAttachment = array()) {
-    $this->spool_id = $sAppMsgUid;
-    $this->fileData['subject'] = $sSubject;
-    $this->fileData['from'] = $sFrom;
-    $this->fileData['to'] = $sTo;
-    $this->fileData['body'] = $sBody;
-    $this->fileData['date'] = ($sDate != '' ? $sDate : date('Y-m-d H:i:s'));
-    $this->fileData['cc'] = $sCC;
-    $this->fileData['bcc'] = $sBCC;
-    $this->fileData['template'] = $sTemplate;
-    $this->fileData['attachments'] = is_array($aAttachment) ? $aAttachment : ($aAttachment != '' ? explode(',', $aAttachment) : array());
-    $this->fileData['envelope_to'] = array();
+        if (isset( $this->fileData['bcc'] ) && trim( $this->fileData['bcc'] ) != '') {
+            $textbcc = trim( $this->fileData['bcc'] );
+        }
 
-    if( $this->config['MESS_ENGINE'] == 'OPENMAIL' ) {
-      if( $this->config['MESS_SERVER'] != '' ) {
-        if( ($sAux = @gethostbyaddr($this->config['MESS_SERVER'])) ) {
-          $this->fileData['domain'] = $sAux;
+        if (false !== (strpos( $text, ',' ))) {
+            $hold = explode( ',', $text );
+
+            foreach ($hold as $val) {
+                if (strlen( $val ) > 0) {
+                    $this->fileData['envelope_to'][] = "$val";
+                }
+            }
+        } else if ($text != '') {
+            $this->fileData['envelope_to'][] = "$text";
         } else {
-          $this->fileData['domain'] = $this->config['MESS_SERVER'];
+            $this->fileData['envelope_to'] = Array ();
         }
-      } else {
-        $this->fileData['domain'] = gethostbyaddr('127.0.0.1');
-      }
-    }
-  }
 
-  /**
-   * send mail
-   * @param none
-   * @return boolean true or exception
-   */
-  public function sendMail() {
-    try {
-      $this->handleFrom();
-      $this->handleEnvelopeTo();
-      $this->handleMail();
-      $this->updateSpoolStatus();
-      return true;
-    } catch( Exception $e ) {
-      throw $e;
-    }
-  }
+        //CC
+        if (false !== (strpos( $textcc, ',' ))) {
+            $holdcc = explode( ',', $textcc );
 
-  /**
-   * update the status to spool
-   * @param none
-   * @return none
-   */
-  private function updateSpoolStatus() {
-    $oAppMessage = AppMessagePeer::retrieveByPK($this->spool_id);
-    if (is_array($this->fileData['attachments'])) {
-        $attachment = implode(",", $this->fileData['attachments']);
-        $oAppMessage->setappMsgAttach($attachment);
-    }
-    $oAppMessage->setappMsgstatus($this->status);
-    $oAppMessage->setappMsgsenddate(date('Y-m-d H:i:s'));
-    $oAppMessage->save();
-  }
-
-  /**
-   * handle the email that was set in "TO" parameter
-   * @param none
-   * @return boolean true or exception
-   */
-  private function handleFrom() {
-    if( strpos($this->fileData['from'], '<') !== false ) {
-      //to validate complex email address i.e. Erik A. O 
-      preg_match($this->longMailEreg, $this->fileData['from'], $matches);
-      if( isset($matches[1]) && $matches[1] != '' ) {
-        //drop the " characters if they exist
-        $this->fileData['from_name'] = trim(str_replace('"', '', $matches[1]));
-      }
-      else { //if the from name was not set
-        $this->fileData['from_name'] = '';
-      }
-
-      if( ! isset($matches[3]) ) {
-        throw new Exception('Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING']);
-      }
-
-      $this->fileData['from_email'] = trim($matches[3]);
-    }
-    else {
-      //to validate simple email address i.e. erik@colosa.com
-      preg_match($this->mailEreg, $this->fileData['from'], $matches);
-
-      if( ! isset($matches[0]) ) {
-        throw new Exception('Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING']);
-      }
-
-      $this->fileData['from_name'] = '';
-      $this->fileData['from_email'] = $matches[0];
-    }
-
-  }
-
-  /**
-   * handle all recipients to compose the mail
-   * @param none
-   * @return boolean true or exception
-   */
-  private function handleEnvelopeTo() {
-    $hold = array ();
-    $holdcc = array ();
-    $holdbcc = array ();
-    $text = trim($this->fileData['to']);
-
-    $textcc ='';
-    $textbcc='';
-    if( isset($this->fileData['cc']) && trim($this->fileData['cc']) != '' ) {
-      $textcc = trim($this->fileData['cc']);
-    }
-
-    if( isset($this->fileData['bcc']) && trim($this->fileData['bcc']) != '' ) {
-      $textbcc = trim($this->fileData['bcc']);
-    }
-
-    if( false !== (strpos($text, ',')) ) {
-      $hold = explode(',', $text);
-
-      foreach( $hold as $val ) {
-        if( strlen($val) > 0 ) {
-          $this->fileData['envelope_to'][] = "$val";
+            foreach ($holdcc as $valcc) {
+                if (strlen( $valcc ) > 0) {
+                    $this->fileData['envelope_cc'][] = "$valcc";
+                }
+            }
+        } else if ($textcc != '') {
+            $this->fileData['envelope_cc'][] = "$textcc";
+        } else {
+            $this->fileData['envelope_cc'] = Array ();
         }
-      }
-    } else if($text != '') {
-      $this->fileData['envelope_to'][] = "$text";
-    } else {
-      $this->fileData['envelope_to'] = Array();
-    }
 
-    //CC
-    if( false !== (strpos($textcc, ',')) ) {
-      $holdcc = explode(',', $textcc);
+        //BCC
+        if (false !== (strpos( $textbcc, ',' ))) {
+            $holdbcc = explode( ',', $textbcc );
 
-      foreach( $holdcc as $valcc ) {
-        if( strlen($valcc) > 0 ) {
-          $this->fileData['envelope_cc'][] = "$valcc";
+            foreach ($holdbcc as $valbcc) {
+                if (strlen( $valbcc ) > 0) {
+                    $this->fileData['envelope_bcc'][] = "$valbcc";
+                }
+            }
+        } else if ($textbcc != '') {
+            $this->fileData['envelope_bcc'][] = "$textbcc";
+        } else {
+            $this->fileData['envelope_bcc'] = Array ();
         }
-      }
-    } else if($textcc != '') {
-      $this->fileData['envelope_cc'][] = "$textcc";
-    } else {
-      $this->fileData['envelope_cc'] = Array();
+
     }
 
-    //BCC
-    if( false !== (strpos($textbcc, ',')) ) {
-      $holdbcc = explode(',', $textbcc);
+    /**
+     * handle and compose the email content and parameters
+     *
+     * @param none
+     * @return none
+     */
+    private function handleMail ()
+    {
+        if (count( $this->fileData['envelope_to'] ) > 0) {
+            switch ($this->config['MESS_ENGINE']) {
+                case 'MAIL':
+                case 'PHPMAILER':
+                    G::LoadThirdParty( 'phpmailer', 'class.phpmailer' );
 
-      foreach( $holdbcc as $valbcc ) {
-        if( strlen($valbcc) > 0 ) {
-          $this->fileData['envelope_bcc'][] = "$valbcc";
+                    switch ($this->config['MESS_ENGINE']) {
+                        case 'MAIL':
+                            $oPHPMailer = new PHPMailer();
+                            $oPHPMailer->Mailer = 'mail';
+                            break;
+                        case 'PHPMAILER':
+                            $oPHPMailer = new PHPMailer( true );
+                            $oPHPMailer->Mailer = 'smtp';
+                            break;
+                    }
+
+                    $oPHPMailer->SMTPAuth = (isset( $this->config['SMTPAuth'] ) ? $this->config['SMTPAuth'] : '');
+
+                    switch ($this->config['MESS_ENGINE']) {
+                        case 'MAIL':
+                            break;
+                        case 'PHPMAILER':
+                            //Posible Options for SMTPSecure are: "", "ssl" or "tls"
+                            if (isset( $this->config['SMTPSecure'] ) && preg_match( '/^(ssl|tls)$/', $this->config['SMTPSecure'] )) {
+                                $oPHPMailer->SMTPSecure = $this->config['SMTPSecure'];
+                            }
+                            break;
+                    }
+
+                    $oPHPMailer->CharSet = "UTF-8";
+                    $oPHPMailer->Encoding = "8bit";
+                    $oPHPMailer->Host = $this->config['MESS_SERVER'];
+                    $oPHPMailer->Port = $this->config['MESS_PORT'];
+                    $oPHPMailer->Username = $this->config['MESS_ACCOUNT'];
+                    $passwd = $this->config['MESS_PASSWORD'];
+                    $passwdDec = G::decrypt( $passwd, 'EMAILENCRYPT' );
+                    $auxPass = explode( 'hash:', $passwdDec );
+
+                    if (count( $auxPass ) > 1) {
+                        if (count( $auxPass ) == 2) {
+                            $passwd = $auxPass[1];
+                        } else {
+                            array_shift( $auxPass );
+                            $passwd = implode( '', $auxPass );
+                        }
+                    }
+
+                    $this->config['MESS_PASSWORD'] = $passwd;
+                    $oPHPMailer->Password = $this->config['MESS_PASSWORD'];
+                    $oPHPMailer->From = $this->fileData['from_email'];
+                    $oPHPMailer->FromName = utf8_decode( $this->fileData['from_name'] );
+
+                    $msSubject = $this->fileData['subject'];
+
+                    if (! (mb_detect_encoding( $msSubject, "UTF-8" ) == "UTF-8")) {
+                        $msSubject = utf8_encode( $msSubject );
+                    }
+
+                    $oPHPMailer->Subject = $msSubject;
+
+                    $msBody = $this->fileData['body'];
+
+                    if (! (mb_detect_encoding( $msBody, "UTF-8" ) == "UTF-8")) {
+                        $msBody = utf8_encode( $msBody );
+                    }
+
+                    $oPHPMailer->Body = $msBody;
+
+                    if (is_array( $this->fileData['attachments'] )) {
+                        foreach ($this->fileData['attachments'] as $key => $fileAttach) {
+                            if (file_exists( $fileAttach )) {
+                                $oPHPMailer->AddAttachment( $fileAttach, is_int( $key ) ? '' : $key );
+                            }
+                        }
+                    }
+
+                    foreach ($this->fileData['envelope_to'] as $sEmail) {
+                        if (strpos( $sEmail, '<' ) !== false) {
+                            preg_match( $this->longMailEreg, $sEmail, $matches );
+                            $sTo = trim( $matches[3] );
+                            $sToName = trim( $matches[1] );
+                            $oPHPMailer->AddAddress( $sTo, $sToName );
+                        } else {
+                            $oPHPMailer->AddAddress( $sEmail );
+                        }
+                    }
+
+                    //CC
+                    foreach ($this->fileData['envelope_cc'] as $sEmail) {
+                        if (strpos( $sEmail, '<' ) !== false) {
+                            preg_match( $this->longMailEreg, $sEmail, $matches );
+                            $sTo = trim( $matches[3] );
+                            $sToName = trim( $matches[1] );
+                            $oPHPMailer->AddCC( $sTo, $sToName );
+                        } else {
+                            $oPHPMailer->AddCC( $sEmail );
+                        }
+                    }
+
+                    //BCC
+                    foreach ($this->fileData['envelope_bcc'] as $sEmail) {
+                        if (strpos( $sEmail, '<' ) !== false) {
+                            preg_match( $this->longMailEreg, $sEmail, $matches );
+                            $sTo = trim( $matches[3] );
+                            $sToName = trim( $matches[1] );
+                            $oPHPMailer->AddBCC( $sTo, $sToName );
+                        } else {
+                            $oPHPMailer->AddBCC( $sEmail );
+                        }
+                    }
+
+                    $oPHPMailer->IsHTML( true );
+
+                    if ($oPHPMailer->Send()) {
+                        $this->error = '';
+                        $this->status = 'sent';
+                    } else {
+                        $this->error = $oPHPMailer->ErrorInfo;
+                        $this->status = 'failed';
+                    }
+                    break;
+                case 'OPENMAIL':
+                    G::LoadClass( 'package' );
+                    G::LoadClass( 'smtp' );
+                    $pack = new package( $this->fileData );
+                    $header = $pack->returnHeader();
+                    $body = $pack->returnBody();
+                    $send = new smtp();
+                    $send->setServer( $this->config['MESS_SERVER'] );
+                    $send->setPort( $this->config['MESS_PORT'] );
+                    $send->setUsername( $this->config['MESS_ACCOUNT'] );
+
+                    $passwd = $this->config['MESS_PASSWORD'];
+                    $passwdDec = G::decrypt( $passwd, 'EMAILENCRYPT' );
+                    $auxPass = explode( 'hash:', $passwdDec );
+
+                    if (count( $auxPass ) > 1) {
+                        if (count( $auxPass ) == 2) {
+                            $passwd = $auxPass[1];
+                        } else {
+                            array_shift( $auxPass );
+                            $passwd = implode( '', $auxPass );
+                        }
+                    }
+
+                    $this->config['MESS_PASSWORD'] = $passwd;
+                    $send->setPassword( $this->config['MESS_PASSWORD'] );
+                    $send->setReturnPath( $this->fileData['from_email'] );
+                    $send->setHeaders( $header );
+                    $send->setBody( $body );
+                    $send->setEnvelopeTo( $this->fileData['envelope_to'] );
+                    if ($send->sendMessage()) {
+                        $this->error = '';
+                        $this->status = 'sent';
+                    } else {
+                        $this->error = implode( ', ', $send->returnErrors() );
+                        $this->status = 'failed';
+                    }
+                    break;
+            }
         }
-      }
-    } else if($textbcc != '') {
-      $this->fileData['envelope_bcc'][] = "$textbcc";
-    } else {
-      $this->fileData['envelope_bcc'] = Array();
     }
 
-
-  }
-
-  /**
-   * handle and compose the email content and parameters
-   * @param none
-   * @return none
-   */
-  private function handleMail() {
-    if( count($this->fileData['envelope_to']) > 0 ) {
-      switch ($this->config['MESS_ENGINE']) {
-        case 'MAIL':
-        case 'PHPMAILER':
-          G::LoadThirdParty('phpmailer', 'class.phpmailer');
-
-          switch($this->config['MESS_ENGINE']) {
-              case 'MAIL':
-                  $oPHPMailer = new PHPMailer();
-                  $oPHPMailer->Mailer = 'mail';
-                  break;
-              case 'PHPMAILER':
-                  $oPHPMailer = new PHPMailer(true);
-                  $oPHPMailer->Mailer = 'smtp';
-                  break;
-          }
-
-          $oPHPMailer->SMTPAuth = (isset($this->config['SMTPAuth']) ? $this->config['SMTPAuth'] : '');
-
-          switch($this->config['MESS_ENGINE']) {
-              case 'MAIL':
-                  break;
-              case 'PHPMAILER':
-                  //Posible Options for SMTPSecure are: "", "ssl" or "tls"
-                  if (isset($this->config['SMTPSecure']) && preg_match('/^(ssl|tls)$/', $this->config['SMTPSecure'])) {
-                      $oPHPMailer->SMTPSecure = $this->config['SMTPSecure'];
-                  }
-                  break;
-          }
-
-          $oPHPMailer->CharSet = "UTF-8";
-          $oPHPMailer->Encoding = "8bit";
-          $oPHPMailer->Host = $this->config['MESS_SERVER'];
-          $oPHPMailer->Port = $this->config['MESS_PORT'];
-          $oPHPMailer->Username = $this->config['MESS_ACCOUNT'];
-          $passwd = $this->config['MESS_PASSWORD'];
-          $passwdDec = G::decrypt($passwd,'EMAILENCRYPT');
-          $auxPass = explode('hash:', $passwdDec);
-
-          if (count($auxPass) > 1) {
-              if (count($auxPass) == 2) {
-                  $passwd = $auxPass[1];
-              } else {
-                  array_shift($auxPass);
-                  $passwd = implode('', $auxPass);
-              }
-          }
-
-          $this->config['MESS_PASSWORD'] = $passwd;
-          $oPHPMailer->Password = $this->config['MESS_PASSWORD'];
-          $oPHPMailer->From = $this->fileData['from_email'];
-          $oPHPMailer->FromName = utf8_decode($this->fileData['from_name']);
-
-          $msSubject = $this->fileData['subject'];
-
-          if(!(mb_detect_encoding($msSubject, "UTF-8") == "UTF-8")) {
-            $msSubject = utf8_encode($msSubject);
-          }
-
-          $oPHPMailer->Subject = $msSubject;
-
-          $msBody = $this->fileData['body'];
-
-          if(!(mb_detect_encoding($msBody, "UTF-8") == "UTF-8")) {
-            $msBody = utf8_encode($msBody);
-          }
-
-          $oPHPMailer->Body = $msBody;
-
-          if(is_array($this->fileData['attachments'])){
-            foreach($this->fileData['attachments'] as $key => $fileAttach){
-              if (file_exists($fileAttach)) {
-                $oPHPMailer->AddAttachment($fileAttach, is_int($key) ? '' : $key);
-              }
-            }
-          }
-
-          foreach ($this->fileData['envelope_to'] as $sEmail) {
-            if( strpos($sEmail, '<') !== false ) {
-              preg_match($this->longMailEreg, $sEmail, $matches);
-              $sTo = trim($matches[3]);
-              $sToName = trim($matches[1]);
-              $oPHPMailer->AddAddress($sTo, $sToName);
-            } else {
-              $oPHPMailer->AddAddress($sEmail);
-            }
-          }
-
-          //CC
-          foreach ($this->fileData['envelope_cc'] as $sEmail) {
-            if(strpos($sEmail, '<') !== false) {
-              preg_match($this->longMailEreg, $sEmail, $matches);
-              $sTo = trim($matches[3]);
-              $sToName = trim($matches[1]);
-              $oPHPMailer->AddCC($sTo, $sToName);
-            } else {
-              $oPHPMailer->AddCC($sEmail);
-            }
-          }
-
-          //BCC
-          foreach ($this->fileData['envelope_bcc'] as $sEmail) {
-            if(strpos($sEmail, '<') !== false) {
-              preg_match($this->longMailEreg, $sEmail, $matches);
-              $sTo = trim($matches[3]);
-              $sToName = trim($matches[1]);
-              $oPHPMailer->AddBCC($sTo, $sToName);
-            } else {
-              $oPHPMailer->AddBCC($sEmail);
-            }
-          }
-
-          $oPHPMailer->IsHTML(true);
-
-          if($oPHPMailer->Send()) {
-              $this->error = '';
-              $this->status = 'sent';
-          } else {
-              $this->error = $oPHPMailer->ErrorInfo;
-              $this->status = 'failed';
-          }
-          break;
-        case 'OPENMAIL':
-          G::LoadClass('package');
-          G::LoadClass('smtp');
-          $pack = new package($this->fileData);
-          $header = $pack->returnHeader();
-          $body = $pack->returnBody();
-          $send = new smtp();
-          $send->setServer($this->config['MESS_SERVER']);
-          $send->setPort($this->config['MESS_PORT']);
-          $send->setUsername($this->config['MESS_ACCOUNT']);
-
-          $passwd = $this->config['MESS_PASSWORD'];
-          $passwdDec = G::decrypt($passwd,'EMAILENCRYPT');
-          $auxPass = explode('hash:', $passwdDec);
-
-          if (count($auxPass) > 1) {
-              if (count($auxPass) == 2) {
-                  $passwd = $auxPass[1];
-              } else {
-                  array_shift($auxPass);
-                  $passwd = implode('', $auxPass);
-              }
-          }
-
-          $this->config['MESS_PASSWORD'] = $passwd;
-          $send->setPassword($this->config['MESS_PASSWORD']);
-          $send->setReturnPath($this->fileData['from_email']);
-          $send->setHeaders($header);
-          $send->setBody($body);
-          $send->setEnvelopeTo($this->fileData['envelope_to']);
-          if( $send->sendMessage() ) {
-            $this->error = '';
-            $this->status = 'sent';
-          } else {
-            $this->error = implode(', ', $send->returnErrors());
-            $this->status = 'failed';
-          }
-          break;
-      }
-    }
-  }
-
     /**
      * try resend the emails from spool
+     *
      * @param string $dateResend
      * @return none or exception
      */
-    public function resendEmails($dateResend=null, $cron=0)
+    public function resendEmails ($dateResend = null, $cron = 0)
     {
         require_once ("classes/model/Configuration.php");
 
         $oConfiguration = new Configuration();
 
-        $aConfiguration = $oConfiguration->load("Emails", "", "", "", "");
+        $aConfiguration = $oConfiguration->load( "Emails", "", "", "", "" );
 
-        $aConfiguration = unserialize($aConfiguration["CFG_VALUE"]);
+        $aConfiguration = unserialize( $aConfiguration["CFG_VALUE"] );
         $passwd = $aConfiguration["MESS_PASSWORD"];
-        $passwdDec = G::decrypt($passwd,"EMAILENCRYPT");
-        $auxPass   = explode("hash:", $passwdDec);
+        $passwdDec = G::decrypt( $passwd, "EMAILENCRYPT" );
+        $auxPass = explode( "hash:", $passwdDec );
 
-        if (count($auxPass) > 1) {
-            if (count($auxPass) == 2) {
+        if (count( $auxPass ) > 1) {
+            if (count( $auxPass ) == 2) {
                 $passwd = $auxPass[1];
             } else {
-                array_shift($auxPass);
-                $passwd = implode("", $auxPass);
+                array_shift( $auxPass );
+                $passwd = implode( "", $auxPass );
             }
         }
 
@@ -520,60 +542,37 @@ class spoolRun {
         if ($aConfiguration["MESS_ENABLED"] == "1") {
             require_once ("classes/model/AppMessage.php");
 
-            $this->setConfig(array(
-                "MESS_ENGINE" => $aConfiguration["MESS_ENGINE"],
-                "MESS_SERVER" => $aConfiguration["MESS_SERVER"],
-                "MESS_PORT"   => $aConfiguration["MESS_PORT"],
-                "MESS_ACCOUNT"  => $aConfiguration["MESS_ACCOUNT"],
-                "MESS_PASSWORD" => $aConfiguration["MESS_PASSWORD"],
-                "SMTPAuth"   => $aConfiguration["MESS_RAUTH"],
-                "SMTPSecure" => $aConfiguration["SMTPSecure"]
-            ));
+            $this->setConfig( array ("MESS_ENGINE" => $aConfiguration["MESS_ENGINE"],"MESS_SERVER" => $aConfiguration["MESS_SERVER"],"MESS_PORT" => $aConfiguration["MESS_PORT"],"MESS_ACCOUNT" => $aConfiguration["MESS_ACCOUNT"],"MESS_PASSWORD" => $aConfiguration["MESS_PASSWORD"],"SMTPAuth" => $aConfiguration["MESS_RAUTH"],"SMTPSecure" => $aConfiguration["SMTPSecure"]
+            ) );
 
-            $criteria = new Criteria("workflow");
-            $criteria->add(AppMessagePeer::APP_MSG_STATUS, "sent", Criteria::NOT_EQUAL);
+            $criteria = new Criteria( "workflow" );
+            $criteria->add( AppMessagePeer::APP_MSG_STATUS, "sent", Criteria::NOT_EQUAL );
 
             if ($dateResend != null) {
-                $criteria->add(AppMessagePeer::APP_MSG_DATE, $dateResend, Criteria::GREATER_EQUAL);
+                $criteria->add( AppMessagePeer::APP_MSG_DATE, $dateResend, Criteria::GREATER_EQUAL );
             }
 
-            $rsCriteria = AppMessagePeer::doSelectRS($criteria);
-            $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);
+            $rsCriteria = AppMessagePeer::doSelectRS( $criteria );
+            $rsCriteria->setFetchmode( ResultSet::FETCHMODE_ASSOC );
 
             while ($rsCriteria->next()) {
                 if ($cron == 1) {
-                    $arrayCron = unserialize(trim(@file_get_contents(PATH_DATA . "cron")));
+                    $arrayCron = unserialize( trim( @file_get_contents( PATH_DATA . "cron" ) ) );
                     $arrayCron["processcTimeStart"] = time();
-                    @file_put_contents(PATH_DATA . "cron", serialize($arrayCron));
+                    @file_put_contents( PATH_DATA . "cron", serialize( $arrayCron ) );
                 }
 
                 $row = $rsCriteria->getRow();
 
                 try {
-                    $this->setData(
-                        $row["APP_MSG_UID"],
-                        $row["APP_MSG_SUBJECT"],
-                        $row["APP_MSG_FROM"],
-                        $row["APP_MSG_TO"],
-                        $row["APP_MSG_BODY"],
-                        date("Y-m-d H:i:s"),
-                        $row["APP_MSG_CC"],
-                        $row["APP_MSG_BCC"],
-                        $row["APP_MSG_TEMPLATE"],
-                        $row["APP_MSG_ATTACH"]
-                    );
+                    $this->setData( $row["APP_MSG_UID"], $row["APP_MSG_SUBJECT"], $row["APP_MSG_FROM"], $row["APP_MSG_TO"], $row["APP_MSG_BODY"], date( "Y-m-d H:i:s" ), $row["APP_MSG_CC"], $row["APP_MSG_BCC"], $row["APP_MSG_TEMPLATE"], $row["APP_MSG_ATTACH"] );
 
                     $this->sendMail();
                 } catch (Exception $e) {
-                    $strAux = "Spool::resendEmails(): Using " .
-                              $aConfiguration["MESS_ENGINE"] .
-                              " for APP_MGS_UID=" .
-                              $row["APP_MSG_UID"] .
-                              " -> With message: " .
-                              $e->getMessage();
+                    $strAux = "Spool::resendEmails(): Using " . $aConfiguration["MESS_ENGINE"] . " for APP_MGS_UID=" . $row["APP_MSG_UID"] . " -> With message: " . $e->getMessage();
 
                     if ($e->getCode() == $this->ExceptionCode["WARNING"]) {
-                        array_push($this->aWarnings, $strAux);
+                        array_push( $this->aWarnings, $strAux );
                         continue;
                     } else {
                         throw $e;
@@ -585,12 +584,13 @@ class spoolRun {
 
     /**
      * gets all warnings
+     *
      * @param none
      * @return string $this->aWarnings
      */
-    public function getWarnings()
+    public function getWarnings ()
     {
-        if (sizeof($this->aWarnings) != 0) {
+        if (sizeof( $this->aWarnings ) != 0) {
             return $this->aWarnings;
         }
 
@@ -600,36 +600,37 @@ class spoolRun {
     /**
      * db_insert
      *
-     * @param  array  $db_spool
+     * @param array $db_spool
      * @return string $sUID;
      */
-    public function db_insert($db_spool)
+    public function db_insert ($db_spool)
     {
-        $sUID  = G::generateUniqueID();
+        $sUID = G::generateUniqueID();
         $spool = new AppMessage();
-        $spool->setAppMsgUid($sUID);
-        $spool->setMsgUid($db_spool['msg_uid']);
-        $spool->setAppUid($db_spool['app_uid']);
-        $spool->setDelIndex($db_spool['del_index']);
-        $spool->setAppMsgType($db_spool['app_msg_type']);
-        $spool->setAppMsgSubject($db_spool['app_msg_subject']);
-        $spool->setAppMsgFrom($db_spool['app_msg_from']);
-        $spool->setAppMsgTo($db_spool['app_msg_to']);
-        $spool->setAppMsgBody($db_spool['app_msg_body']);
-        $spool->setAppMsgDate(date('Y-m-d H:i:s'));
-        $spool->setAppMsgCc($db_spool['app_msg_cc']);
-        $spool->setAppMsgBcc($db_spool['app_msg_bcc']);
-        $spool->setappMsgAttach($db_spool['app_msg_attach']);
-        $spool->setAppMsgTemplate($db_spool['app_msg_template']);
-        $spool->setAppMsgStatus($db_spool['app_msg_status']);
-        $spool->setAppMsgSendDate(date('Y-m-d H:i:s')); // Add by Ankit
+        $spool->setAppMsgUid( $sUID );
+        $spool->setMsgUid( $db_spool['msg_uid'] );
+        $spool->setAppUid( $db_spool['app_uid'] );
+        $spool->setDelIndex( $db_spool['del_index'] );
+        $spool->setAppMsgType( $db_spool['app_msg_type'] );
+        $spool->setAppMsgSubject( $db_spool['app_msg_subject'] );
+        $spool->setAppMsgFrom( $db_spool['app_msg_from'] );
+        $spool->setAppMsgTo( $db_spool['app_msg_to'] );
+        $spool->setAppMsgBody( $db_spool['app_msg_body'] );
+        $spool->setAppMsgDate( date( 'Y-m-d H:i:s' ) );
+        $spool->setAppMsgCc( $db_spool['app_msg_cc'] );
+        $spool->setAppMsgBcc( $db_spool['app_msg_bcc'] );
+        $spool->setappMsgAttach( $db_spool['app_msg_attach'] );
+        $spool->setAppMsgTemplate( $db_spool['app_msg_template'] );
+        $spool->setAppMsgStatus( $db_spool['app_msg_status'] );
+        $spool->setAppMsgSendDate( date( 'Y-m-d H:i:s' ) ); // Add by Ankit
 
-        if (!$spool->validate()) {
+
+        if (! $spool->validate()) {
             $errors = $spool->getValidationFailures();
             $this->status = 'error';
 
             foreach ($errors as $key => $value) {
-                echo "Validation error - " . $value->getMessage($key) . "\n";
+                echo "Validation error - " . $value->getMessage( $key ) . "\n";
             }
         } else {
             //echo "Saving - validation ok\n";

From 1028fb9788e829d1693027eb0f44840c05615a8c Mon Sep 17 00:00:00 2001
From: Fernando Ontiveros 
Date: Tue, 9 Oct 2012 13:25:03 -0400
Subject: [PATCH 09/18] CODE STYLE class.system.php

---
 workflow/engine/classes/class.system.php | 2006 +++++++++++-----------
 1 file changed, 998 insertions(+), 1008 deletions(-)

diff --git a/workflow/engine/classes/class.system.php b/workflow/engine/classes/class.system.php
index 2b157b717..d716e6647 100755
--- a/workflow/engine/classes/class.system.php
+++ b/workflow/engine/classes/class.system.php
@@ -1,6 +1,8 @@
 .
+ * along with this program. If not, see .
  *
  * For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
  * Coral Gables, FL, 33134, USA, or email info@colosa.com.
@@ -29,1094 +31,1082 @@
  *
  * author Erik A.O.
  * date May 12th, 2010
+ *
  * @package workflow.engine.classes
  *
  */
 
-class System {
+class System
+{
 
-  var $sFilename;
-  var $sFilesList;
-  var $sUpgradeFileList;
-  var $aErrors;
-  var $aWorkspaces;
-  var $sRevision;
-  var $sPath;
-  var $newSystemClass;
+    var $sFilename;
+    var $sFilesList;
+    var $sUpgradeFileList;
+    var $aErrors;
+    var $aWorkspaces;
+    var $sRevision;
+    var $sPath;
+    var $newSystemClass;
 
-  /**
-  * List currently installed plugins
-  *
-  * param
-  * @return array with the names of the plugins
-  */
-  public static function getPlugins() {
-    $plugins = array ();
+    /**
+     * List currently installed plugins
+     *
+     * param
+     *
+     * @return array with the names of the plugins
+     */
+    public static function getPlugins ()
+    {
+        $plugins = array ();
 
-    foreach (glob(PATH_PLUGINS . "*") as $filename) {
-      $info = pathinfo($filename);
-      if (array_key_exists("extension", $info) && (strcmp($info["extension"], "php") == 0)) {
-        $plugins[] = basename($filename, ".php");
-      }
+        foreach (glob( PATH_PLUGINS . "*" ) as $filename) {
+            $info = pathinfo( $filename );
+            if (array_key_exists( "extension", $info ) && (strcmp( $info["extension"], "php" ) == 0)) {
+                $plugins[] = basename( $filename, ".php" );
+            }
+        }
+
+        sort( $plugins, SORT_STRING );
+        return $plugins;
     }
 
-    sort($plugins, SORT_STRING);
-    return $plugins;
-  }
-
-  /**
-   * Lists existing workspaces, returning an array of workspaceTools object
-   * for each.
-   * This is a class method, it does not require an instance.
-   *
-   * @author Alexandre Rosenfeld 
-   * @access public
-   * @return array of workspace tools objects
-   */
-  public static function listWorkspaces() {
-    $oDirectory = dir(PATH_DB);
-    $aWorkspaces = array();
-    foreach (glob(PATH_DB . "*") as $filename) {
-      if (is_dir($filename) && file_exists($filename . "/db.php"))
-        $aWorkspaces[] = new workspaceTools (basename($filename));
-    }
-    return $aWorkspaces;
-  }
-
-  /**
-   * Get the ProcessMaker version. If version-pmos.php is not found, try to
-   * retrieve the version from git.
-   *
-   * @author Alexandre Rosenfeld 
-   * @return string system
-   */
-  public static function getVersion() {
-    if (! defined ( 'PM_VERSION' )) {
-      if (file_exists ( PATH_METHODS . 'login/version-pmos.php' )) {
-        include (PATH_METHODS . 'login/version-pmos.php');
-      } else {
-        $version = self::getVersionFromGit();
-        if ($version === false)
-          $version = 'Development Version';
-        define ( 'PM_VERSION', $version );
-      }
-    }
-    return PM_VERSION;
-  }
-
-  /**
-   * Get the branch and tag information from a git repository.
-   *
-   * @author Alexandre Rosenfeld 
-   * @return string branch and tag information
-   */
-  public static function getVersionFromGit($dir = NULL) {
-    if ($dir == NULL)
-      $dir = PATH_TRUNK;
-    if (!file_exists("$dir/.git"))
-      return false;
-    if (exec("cd $dir && git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/^* \(.*\)$/(Branch \\1)/'", $target)) {
-      exec("cd $dir && git describe", $target);
-      return implode(' ', $target);
-    }
-    return false;
-  }
-
-  /**
-  * Get system information
-  *
-  * param
-  * @return array with system information
-  */
-  public static function getSysInfo() {
-    $ipe = explode(" ", $_SERVER['SSH_CONNECTION']);
-
-    if( getenv('HTTP_CLIENT_IP') ) {
-      $ip = getenv('HTTP_CLIENT_IP');
-    } elseif( getenv('HTTP_X_FORWARDED_FOR') ) {
-      $ip = getenv('HTTP_X_FORWARDED_FOR');
-    } else {
-      $ip = getenv('REMOTE_ADDR');
+    /**
+     * Lists existing workspaces, returning an array of workspaceTools object
+     * for each.
+     * This is a class method, it does not require an instance.
+     *
+     * @author Alexandre Rosenfeld 
+     * @access public
+     * @return array of workspace tools objects
+     */
+    public static function listWorkspaces ()
+    {
+        $oDirectory = dir( PATH_DB );
+        $aWorkspaces = array ();
+        foreach (glob( PATH_DB . "*" ) as $filename) {
+            if (is_dir( $filename ) && file_exists( $filename . "/db.php" ))
+                $aWorkspaces[] = new workspaceTools( basename( $filename ) );
+        }
+        return $aWorkspaces;
     }
 
-    /* For distros with the lsb_release, this returns a one-line description of
+    /**
+     * Get the ProcessMaker version.
+     * If version-pmos.php is not found, try to
+     * retrieve the version from git.
+     *
+     * @author Alexandre Rosenfeld 
+     * @return string system
+     */
+    public static function getVersion ()
+    {
+        if (! defined( 'PM_VERSION' )) {
+            if (file_exists( PATH_METHODS . 'login/version-pmos.php' )) {
+                include (PATH_METHODS . 'login/version-pmos.php');
+            } else {
+                $version = self::getVersionFromGit();
+                if ($version === false)
+                    $version = 'Development Version';
+                define( 'PM_VERSION', $version );
+            }
+        }
+        return PM_VERSION;
+    }
+
+    /**
+     * Get the branch and tag information from a git repository.
+     *
+     * @author Alexandre Rosenfeld 
+     * @return string branch and tag information
+     */
+    public static function getVersionFromGit ($dir = NULL)
+    {
+        if ($dir == NULL)
+            $dir = PATH_TRUNK;
+        if (! file_exists( "$dir/.git" ))
+            return false;
+        if (exec( "cd $dir && git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/^* \(.*\)$/(Branch \\1)/'", $target )) {
+            exec( "cd $dir && git describe", $target );
+            return implode( ' ', $target );
+        }
+        return false;
+    }
+
+    /**
+     * Get system information
+     *
+     * param
+     *
+     * @return array with system information
+     */
+    public static function getSysInfo ()
+    {
+        $ipe = explode( " ", $_SERVER['SSH_CONNECTION'] );
+
+        if (getenv( 'HTTP_CLIENT_IP' )) {
+            $ip = getenv( 'HTTP_CLIENT_IP' );
+        } elseif (getenv( 'HTTP_X_FORWARDED_FOR' )) {
+            $ip = getenv( 'HTTP_X_FORWARDED_FOR' );
+        } else {
+            $ip = getenv( 'REMOTE_ADDR' );
+        }
+
+        /* For distros with the lsb_release, this returns a one-line description of
      * the distro name, such as "CentOS release 5.3 (Final)" or "Ubuntu 10.10"
      */
-    $distro = exec("lsb_release -d -s 2> /dev/null");
+        $distro = exec( "lsb_release -d -s 2> /dev/null" );
 
-    /* For distros without lsb_release, we look for *release (such as
+        /* For distros without lsb_release, we look for *release (such as
      * redhat-release, gentoo-release, SuSE-release, etc) or *version (such as
      * debian_version, slackware-version, etc)
      */
-    if (empty($distro)) {
-      foreach (glob("/etc/*release") as $filename) {
-        $distro = trim(file_get_contents($filename));
-        if (!empty($distro))
-          break;
-      }
-      if (empty($distro)) {
-        foreach (glob("/etc/*version") as $filename) {
-          $distro = trim(file_get_contents($filename));
-          if (!empty($distro))
-            break;
+        if (empty( $distro )) {
+            foreach (glob( "/etc/*release" ) as $filename) {
+                $distro = trim( file_get_contents( $filename ) );
+                if (! empty( $distro ))
+                    break;
+            }
+            if (empty( $distro )) {
+                foreach (glob( "/etc/*version" ) as $filename) {
+                    $distro = trim( file_get_contents( $filename ) );
+                    if (! empty( $distro ))
+                        break;
+                }
+            }
         }
-      }
-    }
 
-    /* CentOS returns a string with quotes, remove them and append
+        /* CentOS returns a string with quotes, remove them and append
      * the OS name (such as LINUX, WINNT, DARWIN, etc)
      */
-    $distro = trim($distro, "\"") . " (" . PHP_OS . ")";
+        $distro = trim( $distro, "\"" ) . " (" . PHP_OS . ")";
 
-    $Fields = array();
-    $Fields['SYSTEM'] = $distro;
-    $Fields['PHP'] = phpversion();
-    $Fields['PM_VERSION'] = self::getVersion();
-    $Fields['SERVER_ADDR'] = $ipe[2]; //lookup($ipe[2]);
-    $Fields['IP'] = $ipe[0]; //lookup($ipe[0]);
+        $Fields = array ();
+        $Fields['SYSTEM'] = $distro;
+        $Fields['PHP'] = phpversion();
+        $Fields['PM_VERSION'] = self::getVersion();
+        $Fields['SERVER_ADDR'] = $ipe[2]; //lookup($ipe[2]);
+        $Fields['IP'] = $ipe[0]; //lookup($ipe[0]);
 
-    $Fields['PLUGINS_LIST'] = System::getPlugins();
 
-    return $Fields;
-  }
+        $Fields['PLUGINS_LIST'] = System::getPlugins();
 
-  public static function listPoFiles() {
-    $folders = glob(PATH_CORE . '/content/translations/*');
-
-    $items = glob(PATH_CORE . '/content/translations/*.po');
-    foreach ($folders as $folder) {
-      if (is_dir($folder)) {
-        $add = glob($folder . "/*.po");
-        $items = array_merge($items, $add);
-      }
+        return $Fields;
     }
 
-    return $items;
-  }
+    public static function listPoFiles ()
+    {
+        $folders = glob( PATH_CORE . '/content/translations/*' );
 
-  public static function verifyChecksum() {
-    if (!file_exists(PATH_TRUNK . "checksum.txt"))
-      return false;
-    $lines = explode("\n", file_get_contents(PATH_TRUNK . "checksum.txt"));
-    $result = array("diff" => array(), "missing" => array());
-    foreach ($lines as $line) {
-      if (empty($line))
-        continue;
-      list($checksum, $empty, $filename) = explode(" ", $line);
-      //Skip xmlform because these files always change.
-      if (strpos($filename, "/xmlform/") !== false)
-        continue;
-      if (file_exists(realpath($filename))) {
-        if (strcmp($checksum, md5_file(realpath($filename))) != 0) {
-          $result['diff'][] = $filename;
+        $items = glob( PATH_CORE . '/content/translations/*.po' );
+        foreach ($folders as $folder) {
+            if (is_dir( $folder )) {
+                $add = glob( $folder . "/*.po" );
+                $items = array_merge( $items, $add );
+            }
         }
-      } else {
-        $result['missing'][] = $filename;
-      }
-    }
-    return $result;
-  }
 
-  /**
-  * This function checks files to do updated to pm
-  *
-  *
-  * @name verifyFileForUpgrade
-  *
-  * param
-  * @return boolean
-  */
-  function verifyFileForUpgrade()
-  {
-   $upgradeFilename = isset($_FILES['form']['name']['UPGRADE_FILENAME']) ? $_FILES['form']['name']['UPGRADE_FILENAME'] : '';
-   $tempFilename    = isset($_FILES['form']['tmp_name']['UPGRADE_FILENAME']) ? $_FILES['form']['tmp_name']['UPGRADE_FILENAME'] : '';
-   $this->sRevision = str_replace('.tar.gz', '', str_replace('pmos-patch-', '', $upgradeFilename));
-   $sTemFilename    = $tempFilename;
-   $this->sFilename = PATH_DATA . 'upgrade' . PATH_SEP . $upgradeFilename;
-   $this->sPath     = dirname($this->sFilename) . PATH_SEP;
-   G::mk_dir(PATH_DATA . 'upgrade');
-   if( ! move_uploaded_file($sTemFilename, $this->sFilename) ) {
-     return false;
-   }
-   return true;
-  }
-
-  /**
-  * This function gets files to do updated to pm
-  *
-  *
-  * @name getUpgradedFilesList
-  *
-  * param
-  * @return void
-  */
-  function getUpgradedFilesList()
-  {
-   G::LoadClass('archive');
-   $this->sFilesList = new gzip_file($this->sFilename);
-   $this->sFilesList->set_options(array (
-     'basedir'   => dirname($this->sFilename),
-     'overwrite' => 1
-   ));
-   $this->sFilesList->extract_files();
-    if( count($this->sFilesList->error) > 0 ) {
-      $msg = '';
-      foreach( $this->sFilesList->error as $key => $val ) {
-        $msg .= $val . "\n";
-    }
-     throw new Exception($msg);
-   }
-   if( count($this->sFilesList->files) == 0 ) {
-     throw new Exception('The uploaded file is an invalid patch file.');
-   }
-  }
-
-  /**
-  * This function checks to do updated for boot
-  *
-  *
-  * @name verifyForBootstrapUpgrade
-  *
-  * param
-  * @return boolean
-  */
-  function verifyForBootstrapUpgrade()
-  {
-   foreach( $this->sFilesList->files as $sFile ) {
-     if( basename($sFile) == 'schema.xml' ) {
-       $this->newSystemClass = $sFile;
-       return true;
-     }
-   }
-   return false;
-  }
-
-  /**
-  * This function updates to the files
-  *
-  *
-  * @name upgrade
-  *
-  * param
-  * @return array
-  */
-  function upgrade()
-  {
-   //get special files
-   $sListFile         = '';
-   $sCheckListFile    = '';
-   $sPatchVersionFile = '';
-   $sPoFile           = '';
-   $sSchemaFile       = '';
-   $sSchemaRBACFile   = '';
-   foreach( $this->sFilesList->files as $sFile ) {
-    if( basename($sFile) == 'schema.xml' ) {
-      if( strpos($sFile, '/rbac/engine/') === false ) {
-        $sOldSchema  = '';
-        $sSchemaFile = $sFile;
-      } else {
-        $sOldSchemaRBAC  = '';
-        $sSchemaRBACFile = $sFile;
-      }
+        return $items;
     }
 
-    //files.lst
-    if( basename($sFile) == 'files.lst' ) {
-      $this->sUpgradeFileList = $sFile;
-    }
-
-    //files.lst
-    if( basename($sFile) == 'patch.version.txt' ) {
-      $sPatchVersionFile = $sFile;
-    }
-
-    //files.rev.txt
-    if( substr(basename($sFile), 0, 6) == 'files.' && substr(basename($sFile), - 4) == '.txt' ) {
-      $sCheckListFile = $sFile;
-    }
-
-    //po files
-    $sExtension = substr($sFile, strrpos($sFile, '.') + 1, strlen($sFile));
-    if( $sExtension == 'po' ) {
-      $sPoFile = $sFile;
-    }
-   }
-
-   $pmVersion = explode('-', self::getVersion());
-   array_shift($pmVersion);
-   $patchVersion = explode('-', $this->sRevision);
-
-   if( $sPatchVersionFile != '' && file_exists($sPatchVersionFile) ) {
-    $this->sRevision = file_get_contents($sPatchVersionFile);
-    $patchVersion    = explode('-', $this->sRevision);
-   }
-
-   if( ! file_exists(PATH_DATA . 'log' . PATH_SEP) ) {
-     G::mk_dir(PATH_DATA . 'log' . PATH_SEP);
-   }
-
-   //empty query log
-   $sqlLog = PATH_DATA . 'log' . PATH_SEP . "query.log";
-   $fp     = fopen($sqlLog, "w+");
-   fwrite($fp, "");
-   fclose($fp);
-
-   $aEnvironmentsUpdated = array ();
-   $aEnvironmentsDiff    = array ();
-   $aErrors              = array ();
-
-   //now will verify each folder and file has permissions to write and add files.
-   if( $this->sUpgradeFileList != '' ) {
-    $bCopySchema = true;
-    $oFile       = fopen($this->sUpgradeFileList, 'r');
-    while( $sLine = trim(fgets($oFile)) ) {
-     $sLine = substr($sLine, 1);
-     $aAux  = explode(PATH_SEP, $sLine);
-     array_shift($aAux);
-     $sFilePath      = implode(PATH_SEP, $aAux);
-     $targetFileName = PATH_TRUNK . $sFilePath;
-     if( ! is_dir($this->sPath . 'processmaker' . PATH_SEP . $sFilePath) ) {
-      //if we are updating or deleting a file
-      if( file_exists($this->sPath . 'processmaker' . PATH_SEP . $sFilePath) ) {
-       if( file_exists($targetFileName) ) {
-        if( ! is_writable($targetFileName) ) {
-          throw (new Exception("File $targetFileName is not writable."));
+    public static function verifyChecksum ()
+    {
+        if (! file_exists( PATH_TRUNK . "checksum.txt" ))
+            return false;
+        $lines = explode( "\n", file_get_contents( PATH_TRUNK . "checksum.txt" ) );
+        $result = array ("diff" => array (),"missing" => array ()
+        );
+        foreach ($lines as $line) {
+            if (empty( $line ))
+                continue;
+            list ($checksum, $empty, $filename) = explode( " ", $line );
+            //Skip xmlform because these files always change.
+            if (strpos( $filename, "/xmlform/" ) !== false)
+                continue;
+            if (file_exists( realpath( $filename ) )) {
+                if (strcmp( $checksum, md5_file( realpath( $filename ) ) ) != 0) {
+                    $result['diff'][] = $filename;
+                }
+            } else {
+                $result['missing'][] = $filename;
+            }
         }
-       } else {
-        //verify parent folder, and ask if that folder is writable
-        $auxDir = explode('/', $targetFileName);
-        array_pop($auxDir);
-        $parentDir = implode('/', $auxDir);
-        if( ! is_dir($parentDir) ) {
-          //throw (new Exception("File $parentDir is an invalid directory."));
-          G::mk_dir($parentDir);
-        }
-        if( ! is_writable($parentDir) ) {
-          throw (new Exception("Directory $parentDir is not writable."));
-        }
-       }
-      } else {
-       //delete unused files
-       if( file_exists($targetFileName) && ! is_writable($targetFileName) ) {
-         throw (new Exception("File $targetFileName is not writable."));
-       }
-      }
-     } else {
-       $dirName = PATH_TRUNK . $sFilePath;
-       if( $dirName[strlen($dirName) - 1] == '/' )
-         $dirName = substr($dirName, 0, strlen($dirName) - 1);
-       $auxDir = explode('/', $dirName);
-       array_pop($auxDir);
-       $parentDir = implode('/', $auxDir);
-       if( file_exists($dirName) ) {
-        if( is_writable($dirName) ) {
-          //print "e. ok $dirName 
"; - } else { - throw (new Exception("$dirName is not writable")); - } - } else { - if( is_writable($parentDir) ) { - mkdir($dirName, 0777); - } else { - throw (new Exception("$dirName does not exist and parent folder $parentDir is not writable")); - } - } - } + return $result; } - } - - //processing list file files.lst - if( $this->sUpgradeFileList != '' ) { - $bCopySchema = true; - $oFile = fopen($this->sUpgradeFileList, 'r'); - while( $sLine = trim(fgets($oFile)) ) { - $action = substr($sLine, 0, 1); - $sLine = substr($sLine, 1); - $aAux = explode(PATH_SEP, $sLine); - array_shift($aAux); - $sFilePath = implode(PATH_SEP, $aAux); - $targetFileName = PATH_TRUNK . $sFilePath; - if( strtoupper($action) != 'D'){ - if( ! is_dir($this->sPath . 'processmaker' . PATH_SEP . $sFilePath) ) { - if( file_exists($this->sPath . 'processmaker' . PATH_SEP . $sFilePath) ) { - if( strpos($sFilePath, 'schema.xml') !== false && $bCopySchema ) { - $bCopySchema = false; - $sOldSchema = str_replace('schema.xml', 'schema_' . date('Ymd') . '.xml', PATH_TRUNK . $sFilePath); - $this->pm_copy(PATH_TRUNK . $sFilePath, $sOldSchema); - } - if( file_exists($targetFileName) ) { - if( is_writable($targetFileName) ) { - $this->pm_copy($this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName); - @chmod($targetFileName, 0666); - } else - throw (new Exception("Failed to open file: Permission denied in $targetFileName.")); - } else { - $this->pm_copy($this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName); - @chmod($targetFileName, 0666); - } - } else { //delete unused files - if( file_exists($targetFileName) ) { - @unlink($targetFileName); - } - } - } else { - if( ! file_exists(PATH_TRUNK . $sFilePath) ) { - mkdir(PATH_TRUNK . $sFilePath, 0777); - } - } - } else if( file_exists(PATH_TRUNK . $sFilePath) && $sFilePath != 'workflow/engine/gulliver' ) { - @unlink(PATH_TRUNK . $sFilePath); - } - } - } - - //end files copied. - $missedFiles = ''; - $distinctFiles = ''; - $missed = 0; - $distinct = 0; - //checking files of this installation server with the files in Repository Code. - if( $sCheckListFile != '' ) { - $fp = fopen($sCheckListFile, 'r'); - while( ! feof($fp) ) { - $line = explode(' ', fgets($fp)); - if( count($line) == 3 ) { - $file = PATH_TRUNK . trim($line[2]); - if( is_readable($file) ) { - $size = sprintf("%07d", filesize($file)); - $checksum = sprintf("%010u", crc32(file_get_contents($file))); - if( ! ($line[0] == $size && $line[1] == $checksum) && substr($file, - 4) != '.xml' ) { - $distinctFiles .= $file . "\n"; - $distinct ++; - } - } else { - $missedFiles .= $file . "\n"; - $missed ++; - } - } - } - fclose($fp); - } - - if( $missed > 0 ) - $aErrors[] = "Warning: there are $missed missed files. "; - $aErrors[] = $missedFiles; - - if( $distinct > 0 ) { - $aErrors[] = "Warning: there are $distinct files with differences. "; - $aErrors[] = $distinctFiles; - } - - //now include the files and classes needed for upgrade databases, dont move this files, because we - //are getting the last files in this point. Even the files was in the patch we will take the new ones. - include PATH_METHODS . PATH_SEP . 'setup' . PATH_SEP . 'upgrade_RBAC.php'; - G::LoadClass('languages'); - G::LoadSystem('database_mysql'); - - $bForceXml = true; - $bParseSchema = true; - $bParseSchemaRBAC = true; - $oDirectory = dir(PATH_DB); - - //count db.php files ( workspaces ) - $aWorkspaces = array (); - while( ($sObject = $oDirectory->read()) ) { - if( is_dir(PATH_DB . $sObject) && substr($sObject, 0, 1) != '.' && file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php') ) { - $aWorkspaces[] = $sObject; - } - } - $aUpgradeData = array (); - $aUpgradeData['workspaces'] = $aWorkspaces; - $aUpgradeData['wsQuantity'] = count($aWorkspaces); - $aUpgradeData['sPoFile'] = $sPoFile; - $aUpgradeData['bForceXmlPoFile'] = true; - $aUpgradeData['sSchemaFile'] = $sSchemaFile; - $aUpgradeData['sSchemaRBACFile'] = $sSchemaRBACFile; - - file_put_contents(PATH_DATA . 'log' . PATH_SEP . "upgrade.data.bin", serialize($aUpgradeData)); - - $sSchemaFile = ''; - $sPoFile = ''; - $sSchemaRBACFile = ''; - - $oDirectory = dir(PATH_DB); - while( ($sObject = $oDirectory->read()) ) { - if( is_dir(PATH_DB . $sObject) && substr($sObject, 0, 1) != '.' ) { - if( file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php') ) { - - eval($this->getDatabaseCredentials(PATH_DB . $sObject . PATH_SEP . 'db.php')); - - } - $aEnvironmentsUpdated[] = $sObject; - $aEnvironmentsDiff[] = $sObject; - } - } - $oDirectory->close(); - @unlink(PATH_CORE . 'config/_databases_.php'); - - //clean up smarty directory - $oDirectory = dir(PATH_SMARTY_C); - while( $sFilename = $oDirectory->read() ) { - if( ($sFilename != '.') && ($sFilename != '..') ) { - @unlink(PATH_SMARTY_C . PATH_SEP . $sFilename); - } - } - - //clean up xmlform folders - $sDir = PATH_C . 'xmlform'; - if( file_exists($sDir) && is_dir($sDir) ) { - $oDirectory = dir($sDir); - while( $sObjectName = $oDirectory->read() ) { - if( ($sObjectName != '.') && ($sObjectName != '..') ) { - if (is_dir($sDir . PATH_SEP . $sObjectName)) { - G::rm_dir($sDir . PATH_SEP . $sObjectName); - } - } - } - $oDirectory->close(); - } - - //changing the PM_VERSION according the patch file name - $oFile = fopen(PATH_METHODS . 'login/version-pmos.php', 'w+'); - if( isset($this->sRevision) && $this->sRevision != '' ) { - fwrite($oFile, "sRevision . "' ));\n?>"); - } else { - fwrite($oFile, ""); - } - fclose($oFile); - $ver = explode("-", $this->sRevision); - $this->aErrors = $aErrors; - $this->aWorkspaces = $aWorkspaces; - - return $ver; - } /** - * This function does to clean up to the upgrate directory - * - * - * @name cleanupUpgradeDirectory - * - * param - * @return array - */ - public function cleanupUpgradeDirectory() + * This function checks files to do updated to pm + * + * + * @name verifyFileForUpgrade + * + * param + * @return boolean + */ + function verifyFileForUpgrade () { - G::rm_dir(PATH_DATA . "upgrade" . PATH_SEP . "processmaker"); + $upgradeFilename = isset( $_FILES['form']['name']['UPGRADE_FILENAME'] ) ? $_FILES['form']['name']['UPGRADE_FILENAME'] : ''; + $tempFilename = isset( $_FILES['form']['tmp_name']['UPGRADE_FILENAME'] ) ? $_FILES['form']['tmp_name']['UPGRADE_FILENAME'] : ''; + $this->sRevision = str_replace( '.tar.gz', '', str_replace( 'pmos-patch-', '', $upgradeFilename ) ); + $sTemFilename = $tempFilename; + $this->sFilename = PATH_DATA . 'upgrade' . PATH_SEP . $upgradeFilename; + $this->sPath = dirname( $this->sFilename ) . PATH_SEP; + G::mk_dir( PATH_DATA . 'upgrade' ); + if (! move_uploaded_file( $sTemFilename, $this->sFilename )) { + return false; + } + return true; } - /** - * This function creates a directory - * - * - * @name pm_copy - * - * @param string $source - * @param string $target - * @return void - */ - function pm_copy($source, $target) - { - if( ! is_dir(dirname($target)) ) { - G::mk_dir(dirname($target)); + /** + * This function gets files to do updated to pm + * + * + * @name getUpgradedFilesList + * + * param + * @return void + */ + function getUpgradedFilesList () + { + G::LoadClass( 'archive' ); + $this->sFilesList = new gzip_file( $this->sFilename ); + $this->sFilesList->set_options( array ('basedir' => dirname( $this->sFilename ),'overwrite' => 1 + ) ); + $this->sFilesList->extract_files(); + if (count( $this->sFilesList->error ) > 0) { + $msg = ''; + foreach ($this->sFilesList->error as $key => $val) { + $msg .= $val . "\n"; + } + throw new Exception( $msg ); + } + if (count( $this->sFilesList->files ) == 0) { + throw new Exception( 'The uploaded file is an invalid patch file.' ); + } } - if( ! copy($source, $target) ) { - krumo($source); - krumo($target); + + /** + * This function checks to do updated for boot + * + * + * @name verifyForBootstrapUpgrade + * + * param + * @return boolean + */ + function verifyForBootstrapUpgrade () + { + foreach ($this->sFilesList->files as $sFile) { + if (basename( $sFile ) == 'schema.xml') { + $this->newSystemClass = $sFile; + return true; + } + } + return false; } - } - /** - * This function gets info about db - * - * - * @name getDatabaseCredentials - * - * @param string $dbFile - * @return $sContent - */ - function getDatabaseCredentials($dbFile) - { - $sContent = file_get_contents($dbFile); - $sContent = str_replace('', '', $sContent); - $sContent = str_replace('define', '', $sContent); - $sContent = str_replace("('", '$', $sContent); - $sContent = str_replace("',", '=', $sContent); - $sContent = str_replace(");", ';', $sContent); - return $sContent; - } + /** + * This function updates to the files + * + * + * @name upgrade + * + * param + * @return array + */ + function upgrade () + { + //get special files + $sListFile = ''; + $sCheckListFile = ''; + $sPatchVersionFile = ''; + $sPoFile = ''; + $sSchemaFile = ''; + $sSchemaRBACFile = ''; + foreach ($this->sFilesList->files as $sFile) { + if (basename( $sFile ) == 'schema.xml') { + if (strpos( $sFile, '/rbac/engine/' ) === false) { + $sOldSchema = ''; + $sSchemaFile = $sFile; + } else { + $sOldSchemaRBAC = ''; + $sSchemaRBACFile = $sFile; + } + } - /** - * Retrieves the system schema. - * - * @return schema content in an array - */ - public static function getSystemSchema() { - return System::getSchema(PATH_TRUNK . "workflow/engine/config/schema.xml"); - } + //files.lst + if (basename( $sFile ) == 'files.lst') { + $this->sUpgradeFileList = $sFile; + } - /** - * Retrieves the schema for a plugin. - * - * @param string $pluginName name of the plugin - * @return $sContent - */ - public static function getPluginSchema($pluginName) { - if (file_exists(PATH_PLUGINS . $pluginName . "/config/schema.xml")) - return System::getSchema(PATH_PLUGINS . $pluginName . "/config/schema.xml"); - else - return false; - } + //files.lst + if (basename( $sFile ) == 'patch.version.txt') { + $sPatchVersionFile = $sFile; + } - /** - * Retrieves a schema array from a file. - * - * @param string $sSchemaFile schema filename - * @return $sContent - */ - public static function getSchema($sSchemaFile) { - /* This is the MySQL mapping that Propel uses (from MysqlPlatform.php) */ - $mysqlTypes = array( - 'NUMERIC' => "DECIMAL", - 'LONGVARCHAR' => "MEDIUMTEXT", - 'TIMESTAMP' => "DATETIME", - 'BU_TIMESTAMP' => "DATETIME", - 'BINARY' => "BLOB", - 'VARBINARY' => "MEDIUMBLOB", - 'LONGVARBINARY' => "LONGBLOB", - 'BLOB' => "LONGBLOB", - 'CLOB' => "LONGTEXT", + //files.rev.txt + if (substr( basename( $sFile ), 0, 6 ) == 'files.' && substr( basename( $sFile ), - 4 ) == '.txt') { + $sCheckListFile = $sFile; + } + + //po files + $sExtension = substr( $sFile, strrpos( $sFile, '.' ) + 1, strlen( $sFile ) ); + if ($sExtension == 'po') { + $sPoFile = $sFile; + } + } + + $pmVersion = explode( '-', self::getVersion() ); + array_shift( $pmVersion ); + $patchVersion = explode( '-', $this->sRevision ); + + if ($sPatchVersionFile != '' && file_exists( $sPatchVersionFile )) { + $this->sRevision = file_get_contents( $sPatchVersionFile ); + $patchVersion = explode( '-', $this->sRevision ); + } + + if (! file_exists( PATH_DATA . 'log' . PATH_SEP )) { + G::mk_dir( PATH_DATA . 'log' . PATH_SEP ); + } + + //empty query log + $sqlLog = PATH_DATA . 'log' . PATH_SEP . "query.log"; + $fp = fopen( $sqlLog, "w+" ); + fwrite( $fp, "" ); + fclose( $fp ); + + $aEnvironmentsUpdated = array (); + $aEnvironmentsDiff = array (); + $aErrors = array (); + + //now will verify each folder and file has permissions to write and add files. + if ($this->sUpgradeFileList != '') { + $bCopySchema = true; + $oFile = fopen( $this->sUpgradeFileList, 'r' ); + while ($sLine = trim( fgets( $oFile ) )) { + $sLine = substr( $sLine, 1 ); + $aAux = explode( PATH_SEP, $sLine ); + array_shift( $aAux ); + $sFilePath = implode( PATH_SEP, $aAux ); + $targetFileName = PATH_TRUNK . $sFilePath; + if (! is_dir( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath )) { + //if we are updating or deleting a file + if (file_exists( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath )) { + if (file_exists( $targetFileName )) { + if (! is_writable( $targetFileName )) { + throw (new Exception( "File $targetFileName is not writable." )); + } + } else { + //verify parent folder, and ask if that folder is writable + $auxDir = explode( '/', $targetFileName ); + array_pop( $auxDir ); + $parentDir = implode( '/', $auxDir ); + if (! is_dir( $parentDir )) { + //throw (new Exception("File $parentDir is an invalid directory.")); + G::mk_dir( $parentDir ); + } + if (! is_writable( $parentDir )) { + throw (new Exception( "Directory $parentDir is not writable." )); + } + } + } else { + //delete unused files + if (file_exists( $targetFileName ) && ! is_writable( $targetFileName )) { + throw (new Exception( "File $targetFileName is not writable." )); + } + } + } else { + $dirName = PATH_TRUNK . $sFilePath; + if ($dirName[strlen( $dirName ) - 1] == '/') + $dirName = substr( $dirName, 0, strlen( $dirName ) - 1 ); + $auxDir = explode( '/', $dirName ); + array_pop( $auxDir ); + $parentDir = implode( '/', $auxDir ); + if (file_exists( $dirName )) { + if (is_writable( $dirName )) { + //print "e. ok $dirName
"; + } else { + throw (new Exception( "$dirName is not writable" )); + } + } else { + if (is_writable( $parentDir )) { + mkdir( $dirName, 0777 ); + } else { + throw (new Exception( "$dirName does not exist and parent folder $parentDir is not writable" )); + } + } + } + } + } + + //processing list file files.lst + if ($this->sUpgradeFileList != '') { + $bCopySchema = true; + $oFile = fopen( $this->sUpgradeFileList, 'r' ); + while ($sLine = trim( fgets( $oFile ) )) { + $action = substr( $sLine, 0, 1 ); + $sLine = substr( $sLine, 1 ); + $aAux = explode( PATH_SEP, $sLine ); + array_shift( $aAux ); + $sFilePath = implode( PATH_SEP, $aAux ); + $targetFileName = PATH_TRUNK . $sFilePath; + if (strtoupper( $action ) != 'D') { + if (! is_dir( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath )) { + if (file_exists( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath )) { + if (strpos( $sFilePath, 'schema.xml' ) !== false && $bCopySchema) { + $bCopySchema = false; + $sOldSchema = str_replace( 'schema.xml', 'schema_' . date( 'Ymd' ) . '.xml', PATH_TRUNK . $sFilePath ); + $this->pm_copy( PATH_TRUNK . $sFilePath, $sOldSchema ); + } + if (file_exists( $targetFileName )) { + if (is_writable( $targetFileName )) { + $this->pm_copy( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName ); + @chmod( $targetFileName, 0666 ); + } else + throw (new Exception( "Failed to open file: Permission denied in $targetFileName." )); + } else { + $this->pm_copy( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName ); + @chmod( $targetFileName, 0666 ); + } + } else { //delete unused files + if (file_exists( $targetFileName )) { + @unlink( $targetFileName ); + } + } + } else { + if (! file_exists( PATH_TRUNK . $sFilePath )) { + mkdir( PATH_TRUNK . $sFilePath, 0777 ); + } + } + } else if (file_exists( PATH_TRUNK . $sFilePath ) && $sFilePath != 'workflow/engine/gulliver') { + @unlink( PATH_TRUNK . $sFilePath ); + } + } + } + + //end files copied. + $missedFiles = ''; + $distinctFiles = ''; + $missed = 0; + $distinct = 0; + //checking files of this installation server with the files in Repository Code. + if ($sCheckListFile != '') { + $fp = fopen( $sCheckListFile, 'r' ); + while (! feof( $fp )) { + $line = explode( ' ', fgets( $fp ) ); + if (count( $line ) == 3) { + $file = PATH_TRUNK . trim( $line[2] ); + if (is_readable( $file )) { + $size = sprintf( "%07d", filesize( $file ) ); + $checksum = sprintf( "%010u", crc32( file_get_contents( $file ) ) ); + if (! ($line[0] == $size && $line[1] == $checksum) && substr( $file, - 4 ) != '.xml') { + $distinctFiles .= $file . "\n"; + $distinct ++; + } + } else { + $missedFiles .= $file . "\n"; + $missed ++; + } + } + } + fclose( $fp ); + } + + if ($missed > 0) + $aErrors[] = "Warning: there are $missed missed files. "; + $aErrors[] = $missedFiles; + + if ($distinct > 0) { + $aErrors[] = "Warning: there are $distinct files with differences. "; + $aErrors[] = $distinctFiles; + } + + //now include the files and classes needed for upgrade databases, dont move this files, because we + //are getting the last files in this point. Even the files was in the patch we will take the new ones. + include PATH_METHODS . PATH_SEP . 'setup' . PATH_SEP . 'upgrade_RBAC.php'; + G::LoadClass( 'languages' ); + G::LoadSystem( 'database_mysql' ); + + $bForceXml = true; + $bParseSchema = true; + $bParseSchemaRBAC = true; + $oDirectory = dir( PATH_DB ); + + //count db.php files ( workspaces ) + $aWorkspaces = array (); + while (($sObject = $oDirectory->read())) { + if (is_dir( PATH_DB . $sObject ) && substr( $sObject, 0, 1 ) != '.' && file_exists( PATH_DB . $sObject . PATH_SEP . 'db.php' )) { + $aWorkspaces[] = $sObject; + } + } + $aUpgradeData = array (); + $aUpgradeData['workspaces'] = $aWorkspaces; + $aUpgradeData['wsQuantity'] = count( $aWorkspaces ); + $aUpgradeData['sPoFile'] = $sPoFile; + $aUpgradeData['bForceXmlPoFile'] = true; + $aUpgradeData['sSchemaFile'] = $sSchemaFile; + $aUpgradeData['sSchemaRBACFile'] = $sSchemaRBACFile; + + file_put_contents( PATH_DATA . 'log' . PATH_SEP . "upgrade.data.bin", serialize( $aUpgradeData ) ); + + $sSchemaFile = ''; + $sPoFile = ''; + $sSchemaRBACFile = ''; + + $oDirectory = dir( PATH_DB ); + while (($sObject = $oDirectory->read())) { + if (is_dir( PATH_DB . $sObject ) && substr( $sObject, 0, 1 ) != '.') { + if (file_exists( PATH_DB . $sObject . PATH_SEP . 'db.php' )) { + + eval( $this->getDatabaseCredentials( PATH_DB . $sObject . PATH_SEP . 'db.php' ) ); + + } + $aEnvironmentsUpdated[] = $sObject; + $aEnvironmentsDiff[] = $sObject; + } + } + $oDirectory->close(); + @unlink( PATH_CORE . 'config/_databases_.php' ); + + //clean up smarty directory + $oDirectory = dir( PATH_SMARTY_C ); + while ($sFilename = $oDirectory->read()) { + if (($sFilename != '.') && ($sFilename != '..')) { + @unlink( PATH_SMARTY_C . PATH_SEP . $sFilename ); + } + } + + //clean up xmlform folders + $sDir = PATH_C . 'xmlform'; + if (file_exists( $sDir ) && is_dir( $sDir )) { + $oDirectory = dir( $sDir ); + while ($sObjectName = $oDirectory->read()) { + if (($sObjectName != '.') && ($sObjectName != '..')) { + if (is_dir( $sDir . PATH_SEP . $sObjectName )) { + G::rm_dir( $sDir . PATH_SEP . $sObjectName ); + } + } + } + $oDirectory->close(); + } + + //changing the PM_VERSION according the patch file name + $oFile = fopen( PATH_METHODS . 'login/version-pmos.php', 'w+' ); + if (isset( $this->sRevision ) && $this->sRevision != '') { + fwrite( $oFile, "sRevision . "' ));\n?>" ); + } else { + fwrite( $oFile, "" ); + } + fclose( $oFile ); + $ver = explode( "-", $this->sRevision ); + $this->aErrors = $aErrors; + $this->aWorkspaces = $aWorkspaces; + + return $ver; + } + + /** + * This function does to clean up to the upgrate directory + * + * + * @name cleanupUpgradeDirectory + * + * param + * @return array + */ + public function cleanupUpgradeDirectory () + { + G::rm_dir( PATH_DATA . "upgrade" . PATH_SEP . "processmaker" ); + } + + /** + * This function creates a directory + * + * + * @name pm_copy + * + * @param string $source + * @param string $target + * @return void + */ + function pm_copy ($source, $target) + { + if (! is_dir( dirname( $target ) )) { + G::mk_dir( dirname( $target ) ); + } + if (! copy( $source, $target )) { + krumo( $source ); + krumo( $target ); + } + } + + /** + * This function gets info about db + * + * + * @name getDatabaseCredentials + * + * @param string $dbFile + * @return $sContent + */ + function getDatabaseCredentials ($dbFile) + { + $sContent = file_get_contents( $dbFile ); + $sContent = str_replace( '', '', $sContent ); + $sContent = str_replace( 'define', '', $sContent ); + $sContent = str_replace( "('", '$', $sContent ); + $sContent = str_replace( "',", '=', $sContent ); + $sContent = str_replace( ");", ';', $sContent ); + return $sContent; + } + + /** + * Retrieves the system schema. + * + * @return schema content in an array + */ + public static function getSystemSchema () + { + return System::getSchema( PATH_TRUNK . "workflow/engine/config/schema.xml" ); + } + + /** + * Retrieves the schema for a plugin. + * + * @param string $pluginName name of the plugin + * @return $sContent + */ + public static function getPluginSchema ($pluginName) + { + if (file_exists( PATH_PLUGINS . $pluginName . "/config/schema.xml" )) + return System::getSchema( PATH_PLUGINS . $pluginName . "/config/schema.xml" ); + else + return false; + } + + /** + * Retrieves a schema array from a file. + * + * @param string $sSchemaFile schema filename + * @return $sContent + */ + public static function getSchema ($sSchemaFile) + { + /* This is the MySQL mapping that Propel uses (from MysqlPlatform.php) */ + $mysqlTypes = array ('NUMERIC' => "DECIMAL",'LONGVARCHAR' => "MEDIUMTEXT",'TIMESTAMP' => "DATETIME",'BU_TIMESTAMP' => "DATETIME",'BINARY' => "BLOB",'VARBINARY' => "MEDIUMBLOB",'LONGVARBINARY' => "LONGBLOB",'BLOB' => "LONGBLOB",'CLOB' => "LONGTEXT", /* This is not from Propel, but is required to get INT right */ - 'INTEGER' => "INT"); - - $aSchema = array(); - $oXml = new DomDocument(); - $oXml->load($sSchemaFile); - $aTables = $oXml->getElementsByTagName('table'); - foreach ($aTables as $oTable) { - $aPrimaryKeys = array(); - $sTableName = $oTable->getAttribute('name'); - $aSchema[$sTableName] = array(); - $aColumns = $oTable->getElementsByTagName('column'); - foreach ($aColumns as $oColumn) { - $sColumName = $oColumn->getAttribute('name'); - - /* Get the field type. Propel uses VARCHAR if nothing else is specified */ - $type = $oColumn->hasAttribute('type') ? strtoupper($oColumn->getAttribute('type')) : "VARCHAR"; - - /* Convert type to MySQL type according to Propel */ - if (array_key_exists($type, $mysqlTypes)) - $type = $mysqlTypes[$type]; - - $size = $oColumn->hasAttribute('size') ? $oColumn->getAttribute('size') : NULL; - /* Add default sizes from MySQL */ - if ($type == "TINYINT" && !$size) - $size = "4"; - if ($type == "INT" && !$size) - $size = "11"; - - if ($size) - $type = "$type($size)"; - - $required = $oColumn->hasAttribute('required') ? $oColumn->getAttribute('required') : NULL; - /* Convert $required to a bool */ - $required = (in_array (strtolower ($required), array('1', 'true'))); - - $default = $oColumn->hasAttribute('default') ? $oColumn->getAttribute('default') : NULL; - - $primaryKey = $oColumn->hasAttribute('primaryKey') ? $oColumn->getAttribute('primaryKey') : NULL; - /* Convert $primaryKey to a bool */ - $primaryKey = (in_array (strtolower ($primaryKey), array('1', 'true'))); - if ($primaryKey) - $aPrimaryKeys[] = $sColumName; - - $aSchema[$sTableName][$sColumName] = array( - 'Field' => $sColumName, - 'Type' => $type, - 'Null' => $required ? "NO" : "YES", - 'Default' => $default + 'INTEGER' => "INT" ); - } - if ( is_array($aPrimaryKeys) && count($aPrimaryKeys) > 0 ) { - $aSchema[$sTableName]['INDEXES']['PRIMARY'] = $aPrimaryKeys; - } - $aIndexes = $oTable->getElementsByTagName('index'); - foreach ($aIndexes as $oIndex) { - $aIndex = array(); - $aIndexesColumns = $oIndex->getElementsByTagName('index-column'); - foreach ($aIndexesColumns as $oIndexColumn) { - $aIndex[] = $oIndexColumn->getAttribute('name'); - } - $aSchema[$sTableName]['INDEXES'][ $oIndex->getAttribute('name') ] = $aIndex; - } - } - return $aSchema; - } + $aSchema = array (); + $oXml = new DomDocument(); + $oXml->load( $sSchemaFile ); + $aTables = $oXml->getElementsByTagName( 'table' ); + foreach ($aTables as $oTable) { + $aPrimaryKeys = array (); + $sTableName = $oTable->getAttribute( 'name' ); + $aSchema[$sTableName] = array (); + $aColumns = $oTable->getElementsByTagName( 'column' ); + foreach ($aColumns as $oColumn) { + $sColumName = $oColumn->getAttribute( 'name' ); - /** - * Returns the difference between two schema arrays - * - * @param array $aOldSchema original schema array - * @param array $aNewSchema new schema array - * @return array with tablesToAdd, tablesToAlter, tablesWithNewIndex and tablesToAlterIndex - */ - public static function compareSchema($aOldSchema, $aNewSchema) { - //$aChanges = array('tablesToDelete' => array(), 'tablesToAdd' => array(), 'tablesToAlter' => array()); - //Tables to delete, but this is disabled - //foreach ($aOldSchema as $sTableName => $aColumns) { - // if ( !isset($aNewSchema[$sTableName])) { - // if (!in_array($sTableName, array('KT_APPLICATION', 'KT_DOCUMENT', 'KT_PROCESS'))) { - // $aChanges['tablesToDelete'][] = $sTableName; - // } - // } - //} + /* Get the field type. Propel uses VARCHAR if nothing else is specified */ + $type = $oColumn->hasAttribute( 'type' ) ? strtoupper( $oColumn->getAttribute( 'type' ) ) : "VARCHAR"; - $aChanges = array('tablesToAdd' => array(), 'tablesToAlter' => array(), 'tablesWithNewIndex' => array(), 'tablesToAlterIndex'=> array()); + /* Convert type to MySQL type according to Propel */ + if (array_key_exists( $type, $mysqlTypes )) + $type = $mysqlTypes[$type]; - //new tables to create and alter - foreach ($aNewSchema as $sTableName => $aColumns) { - if (!isset($aOldSchema[$sTableName])) { - $aChanges['tablesToAdd'][$sTableName] = $aColumns; - } - else { - //drop old columns - foreach ($aOldSchema[$sTableName] as $sColumName => $aParameters) { - if (!isset($aNewSchema[$sTableName][$sColumName])) { - if (!isset($aChanges['tablesToAlter'][$sTableName])) { - $aChanges['tablesToAlter'][$sTableName] = array('DROP' => array(), 'ADD' => array(), 'CHANGE' => array()); + $size = $oColumn->hasAttribute( 'size' ) ? $oColumn->getAttribute( 'size' ) : NULL; + /* Add default sizes from MySQL */ + if ($type == "TINYINT" && ! $size) + $size = "4"; + if ($type == "INT" && ! $size) + $size = "11"; + + if ($size) + $type = "$type($size)"; + + $required = $oColumn->hasAttribute( 'required' ) ? $oColumn->getAttribute( 'required' ) : NULL; + /* Convert $required to a bool */ + $required = (in_array( strtolower( $required ), array ('1','true' + ) )); + + $default = $oColumn->hasAttribute( 'default' ) ? $oColumn->getAttribute( 'default' ) : NULL; + + $primaryKey = $oColumn->hasAttribute( 'primaryKey' ) ? $oColumn->getAttribute( 'primaryKey' ) : NULL; + /* Convert $primaryKey to a bool */ + $primaryKey = (in_array( strtolower( $primaryKey ), array ('1','true' + ) )); + if ($primaryKey) + $aPrimaryKeys[] = $sColumName; + + $aSchema[$sTableName][$sColumName] = array ('Field' => $sColumName,'Type' => $type,'Null' => $required ? "NO" : "YES",'Default' => $default + ); } - $aChanges['tablesToAlter'][$sTableName]['DROP'][$sColumName] = $sColumName; - } - } - //create new columns - //foreach ($aNewSchema[$sTableName] as $sColumName => $aParameters) { - foreach ($aColumns as $sColumName => $aParameters) { - if ($sColumName != 'INDEXES') { - if (!isset($aOldSchema[$sTableName][$sColumName])) { //this column doesnt exist in oldschema - if (!isset($aChanges['tablesToAlter'][$sTableName])) { - $aChanges['tablesToAlter'][$sTableName] = array('DROP' => array(), 'ADD' => array(), 'CHANGE' => array()); - } - $aChanges['tablesToAlter'][$sTableName]['ADD'][$sColumName] = $aParameters; + if (is_array( $aPrimaryKeys ) && count( $aPrimaryKeys ) > 0) { + $aSchema[$sTableName]['INDEXES']['PRIMARY'] = $aPrimaryKeys; } - else { //the column exists - $newField = $aNewSchema[$sTableName][$sColumName]; - $oldField = $aOldSchema[$sTableName][$sColumName]; - //both are null, no change is required - if ( !isset($newField['Default']) && !isset($oldField['Default'])) $changeDefaultAttr = false; - //one of them is null, change IS required - if ( !isset($newField['Default']) && isset($oldField['Default']) && $oldField['Default']!= '') $changeDefaultAttr = true; - if ( isset($newField['Default']) && !isset($oldField['Default'])) $changeDefaultAttr = true; - //both are defined and they are different. - if ( isset($newField['Default']) && isset($oldField['Default']) ) { - if ( $newField['Default'] != $oldField['Default'] ) - $changeDefaultAttr = true; - else - $changeDefaultAttr = false; - } - //special cases - // BLOB and TEXT columns cannot have DEFAULT values. http://dev.mysql.com/doc/refman/5.0/en/blob.html - if ( in_array(strtolower($newField['Type']), array('text','mediumtext') ) ) - $changeDefaultAttr = false; - - //#1067 - Invalid default value for datetime field - if ( in_array($newField['Type'], array('datetime')) && isset($newField['Default']) && $newField['Default']== '' ) - $changeDefaultAttr = false; - - //#1067 - Invalid default value for int field - if ( substr($newField['Type'], 0, 3 ) == "int" && isset($newField['Default']) && $newField['Default']== '' ) - $changeDefaultAttr = false; - - //if any difference exists, then insert the difference in aChanges - if ( strcasecmp($newField['Field'], $oldField['Field']) !== 0 || - strcasecmp($newField['Type'], $oldField['Type']) !== 0 || - strcasecmp($newField['Null'], $oldField['Null']) !== 0 || - $changeDefaultAttr ) { - if (!isset($aChanges['tablesToAlter'][$sTableName])) { - $aChanges['tablesToAlter'][$sTableName] = array('DROP' => array(), 'ADD' => array(), 'CHANGE' => array()); + $aIndexes = $oTable->getElementsByTagName( 'index' ); + foreach ($aIndexes as $oIndex) { + $aIndex = array (); + $aIndexesColumns = $oIndex->getElementsByTagName( 'index-column' ); + foreach ($aIndexesColumns as $oIndexColumn) { + $aIndex[] = $oIndexColumn->getAttribute( 'name' ); } - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Field'] = $newField['Field']; - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Type'] = $newField['Type']; - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Null'] = $newField['Null']; - if ( isset($newField['Default']) ) - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = $newField['Default']; - else - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = null; - - } + $aSchema[$sTableName]['INDEXES'][$oIndex->getAttribute( 'name' )] = $aIndex; } - } //only columns, no the indexes column - }//foreach $aColumns - - //now check the indexes of table - if ( isset($aNewSchema[$sTableName]['INDEXES']) ) { - foreach ( $aNewSchema[$sTableName]['INDEXES'] as $indexName => $indexFields ) { - if (!isset( $aOldSchema[$sTableName]['INDEXES'][$indexName]) ) { - if (!isset($aChanges['tablesWithNewIndex'][$sTableName])) { - $aChanges['tablesWithNewIndex'][$sTableName] = array(); - } - $aChanges['tablesWithNewIndex'][$sTableName][$indexName] = $indexFields; - } - else { - if ( $aOldSchema[$sTableName]['INDEXES'][$indexName] != $indexFields ) { - if (!isset($aChanges['tablesToAlterIndex'][$sTableName])) { - $aChanges['tablesToAlterIndex'][$sTableName] = array(); - } - $aChanges['tablesToAlterIndex'][$sTableName][$indexName] = $indexFields; - } - } - } } - } //for-else table exists - } //for new schema - return $aChanges; - } - - - function getEmailConfiguration() - { - G::LoadClass('configuration'); - $conf = new Configurations(); - $config = $conf->load('Emails'); - - return $config; - } - - function getSkingList() - { - //Create Skins custom folder if it doesn't exists - if(!is_dir(PATH_CUSTOM_SKINS)){ - G::verifyPath(PATH_CUSTOM_SKINS, true); + return $aSchema; } - //Get Skin Config files - $skinListArray = array(); - $customSkins = glob(PATH_CUSTOM_SKINS . "*/config.xml"); - - // getting al base skins - $baseSkins = glob(G::ExpandPath("skinEngine") . '*/config.xml'); - - // filtering no public skins (uxs, simplified) - foreach ($baseSkins as $i => $skinName) { - if (strpos($skinName, 'simplified') !== false || strpos($skinName, 'uxs') !== false) { - unset($baseSkins[$i]); - } - } - - $customSkins = array_merge($baseSkins, $customSkins); - - //Read and parse each Configuration File - foreach ($customSkins as $key => $configInformation) { - $folderId = basename(dirname($configInformation)); - - if ($folderId == 'base') { - $folderId = 'classic'; - } - - $xmlConfiguration = file_get_contents($configInformation); - $xmlConfigurationObj = G::xmlParser($xmlConfiguration); - - if (isset($xmlConfigurationObj->result['skinConfiguration'])) { - $skinInformationArray = $skinFilesArray = $xmlConfigurationObj->result['skinConfiguration']['__CONTENT__']['information']['__CONTENT__']; - $res = array(); - $res['SKIN_FOLDER_ID'] = strtolower($folderId); - - foreach ($skinInformationArray as $keyInfo => $infoValue) { - $res['SKIN_' . strtoupper($keyInfo)] = $infoValue['__VALUE__']; - } - - $skinListArray['skins'][] = $res; - } - } - - $skinListArray['currentSkin'] = SYS_SKIN; - - return $skinListArray; - } - - function getAllTimeZones() - { - $timezones = DateTimeZone::listAbbreviations(); - - $cities = array(); - foreach( $timezones as $key => $zones ) + /** + * Returns the difference between two schema arrays + * + * @param array $aOldSchema original schema array + * @param array $aNewSchema new schema array + * @return array with tablesToAdd, tablesToAlter, tablesWithNewIndex and tablesToAlterIndex + */ + public static function compareSchema ($aOldSchema, $aNewSchema) { - foreach( $zones as $id => $zone ) - { - /** - * Only get timezones explicitely not part of "Others". - * @see http://www.php.net/manual/en/timezones.others.php - */ - if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Africa|Europe|Indian|Pacific)\//', $zone['timezone_id'] ) - && $zone['timezone_id']) { - $cities[$zone['timezone_id']][] = $key; + //$aChanges = array('tablesToDelete' => array(), 'tablesToAdd' => array(), 'tablesToAlter' => array()); + //Tables to delete, but this is disabled + //foreach ($aOldSchema as $sTableName => $aColumns) { + // if ( !isset($aNewSchema[$sTableName])) { + // if (!in_array($sTableName, array('KT_APPLICATION', 'KT_DOCUMENT', 'KT_PROCESS'))) { + // $aChanges['tablesToDelete'][] = $sTableName; + // } + // } + //} + + + $aChanges = array ('tablesToAdd' => array (),'tablesToAlter' => array (),'tablesWithNewIndex' => array (),'tablesToAlterIndex' => array () + ); + + //new tables to create and alter + foreach ($aNewSchema as $sTableName => $aColumns) { + if (! isset( $aOldSchema[$sTableName] )) { + $aChanges['tablesToAdd'][$sTableName] = $aColumns; + } else { + //drop old columns + foreach ($aOldSchema[$sTableName] as $sColumName => $aParameters) { + if (! isset( $aNewSchema[$sTableName][$sColumName] )) { + if (! isset( $aChanges['tablesToAlter'][$sTableName] )) { + $aChanges['tablesToAlter'][$sTableName] = array ('DROP' => array (),'ADD' => array (),'CHANGE' => array () + ); + } + $aChanges['tablesToAlter'][$sTableName]['DROP'][$sColumName] = $sColumName; + } + } + + //create new columns + //foreach ($aNewSchema[$sTableName] as $sColumName => $aParameters) { + foreach ($aColumns as $sColumName => $aParameters) { + if ($sColumName != 'INDEXES') { + if (! isset( $aOldSchema[$sTableName][$sColumName] )) { //this column doesnt exist in oldschema + if (! isset( $aChanges['tablesToAlter'][$sTableName] )) { + $aChanges['tablesToAlter'][$sTableName] = array ('DROP' => array (),'ADD' => array (),'CHANGE' => array () + ); + } + $aChanges['tablesToAlter'][$sTableName]['ADD'][$sColumName] = $aParameters; + } else { //the column exists + $newField = $aNewSchema[$sTableName][$sColumName]; + $oldField = $aOldSchema[$sTableName][$sColumName]; + //both are null, no change is required + if (! isset( $newField['Default'] ) && ! isset( $oldField['Default'] )) + $changeDefaultAttr = false; + //one of them is null, change IS required + if (! isset( $newField['Default'] ) && isset( $oldField['Default'] ) && $oldField['Default'] != '') + $changeDefaultAttr = true; + if (isset( $newField['Default'] ) && ! isset( $oldField['Default'] )) + $changeDefaultAttr = true; + //both are defined and they are different. + if (isset( $newField['Default'] ) && isset( $oldField['Default'] )) { + if ($newField['Default'] != $oldField['Default']) + $changeDefaultAttr = true; + else + $changeDefaultAttr = false; + } + //special cases + // BLOB and TEXT columns cannot have DEFAULT values. http://dev.mysql.com/doc/refman/5.0/en/blob.html + if (in_array( strtolower( $newField['Type'] ), array ('text','mediumtext' + ) )) + $changeDefaultAttr = false; + + //#1067 - Invalid default value for datetime field + if (in_array( $newField['Type'], array ('datetime' + ) ) && isset( $newField['Default'] ) && $newField['Default'] == '') + $changeDefaultAttr = false; + + //#1067 - Invalid default value for int field + if (substr( $newField['Type'], 0, 3 ) == "int" && isset( $newField['Default'] ) && $newField['Default'] == '') + $changeDefaultAttr = false; + + //if any difference exists, then insert the difference in aChanges + if (strcasecmp( $newField['Field'], $oldField['Field'] ) !== 0 || strcasecmp( $newField['Type'], $oldField['Type'] ) !== 0 || strcasecmp( $newField['Null'], $oldField['Null'] ) !== 0 || $changeDefaultAttr) { + if (! isset( $aChanges['tablesToAlter'][$sTableName] )) { + $aChanges['tablesToAlter'][$sTableName] = array ('DROP' => array (),'ADD' => array (),'CHANGE' => array () + ); + } + $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Field'] = $newField['Field']; + $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Type'] = $newField['Type']; + $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Null'] = $newField['Null']; + if (isset( $newField['Default'] )) + $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = $newField['Default']; + else + $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = null; + + } + } + } //only columns, no the indexes column + } //foreach $aColumns + + + //now check the indexes of table + if (isset( $aNewSchema[$sTableName]['INDEXES'] )) { + foreach ($aNewSchema[$sTableName]['INDEXES'] as $indexName => $indexFields) { + if (! isset( $aOldSchema[$sTableName]['INDEXES'][$indexName] )) { + if (! isset( $aChanges['tablesWithNewIndex'][$sTableName] )) { + $aChanges['tablesWithNewIndex'][$sTableName] = array (); + } + $aChanges['tablesWithNewIndex'][$sTableName][$indexName] = $indexFields; + } else { + if ($aOldSchema[$sTableName]['INDEXES'][$indexName] != $indexFields) { + if (! isset( $aChanges['tablesToAlterIndex'][$sTableName] )) { + $aChanges['tablesToAlterIndex'][$sTableName] = array (); + } + $aChanges['tablesToAlterIndex'][$sTableName][$indexName] = $indexFields; + } + } + } + } + } //for-else table exists + } //for new schema + return $aChanges; + } + + function getEmailConfiguration () + { + G::LoadClass( 'configuration' ); + $conf = new Configurations(); + $config = $conf->load( 'Emails' ); + + return $config; + } + + function getSkingList () + { + //Create Skins custom folder if it doesn't exists + if (! is_dir( PATH_CUSTOM_SKINS )) { + G::verifyPath( PATH_CUSTOM_SKINS, true ); + } + + //Get Skin Config files + $skinListArray = array (); + $customSkins = glob( PATH_CUSTOM_SKINS . "*/config.xml" ); + + // getting al base skins + $baseSkins = glob( G::ExpandPath( "skinEngine" ) . '*/config.xml' ); + + // filtering no public skins (uxs, simplified) + foreach ($baseSkins as $i => $skinName) { + if (strpos( $skinName, 'simplified' ) !== false || strpos( $skinName, 'uxs' ) !== false) { + unset( $baseSkins[$i] ); } } - } - // For each city, have a comma separated list of all possible timezones for that city. - foreach( $cities as $key => $value ) - $cities[$key] = join( ', ', $value); + $customSkins = array_merge( $baseSkins, $customSkins ); - // Only keep one city (the first and also most important) for each set of possibilities. - $cities = array_unique( $cities ); + //Read and parse each Configuration File + foreach ($customSkins as $key => $configInformation) { + $folderId = basename( dirname( $configInformation ) ); - // Sort by area/city name. - ksort( $cities ); - - return $cities; - } - - public static function getSystemConfiguration($globalIniFile = '', $wsIniFile = '', $wsName = '') - { - $readGlobalIniFile = false; - $readWsIniFile = false; - - if (empty($globalIniFile)) { - $globalIniFile = PATH_CORE . 'config' . PATH_SEP . 'env.ini'; - } - - if (empty($wsIniFile)) { - if (defined('PATH_DB')) { // if we're on a valid workspace env. - if (empty($wsName)) { - $uriParts = explode('/', getenv("REQUEST_URI")); - - if (isset($uriParts[1])) { - if (substr($uriParts[1], 0, 3 ) == 'sys') { - $wsName = substr($uriParts[1], 3); + if ($folderId == 'base') { + $folderId = 'classic'; + } + + $xmlConfiguration = file_get_contents( $configInformation ); + $xmlConfigurationObj = G::xmlParser( $xmlConfiguration ); + + if (isset( $xmlConfigurationObj->result['skinConfiguration'] )) { + $skinInformationArray = $skinFilesArray = $xmlConfigurationObj->result['skinConfiguration']['__CONTENT__']['information']['__CONTENT__']; + $res = array (); + $res['SKIN_FOLDER_ID'] = strtolower( $folderId ); + + foreach ($skinInformationArray as $keyInfo => $infoValue) { + $res['SKIN_' . strtoupper( $keyInfo )] = $infoValue['__VALUE__']; + } + + $skinListArray['skins'][] = $res; } - } } - $wsIniFile = PATH_DB . $wsName . PATH_SEP . 'env.ini'; - } + + $skinListArray['currentSkin'] = SYS_SKIN; + + return $skinListArray; } - $readGlobalIniFile = file_exists($globalIniFile) ? true : false; - $readWsIniFile = file_exists($wsIniFile) ? true : false; + function getAllTimeZones () + { + $timezones = DateTimeZone::listAbbreviations(); - if (isset($_SESSION['PROCESSMAKER_ENV'])) { - $md5 = array(); + $cities = array (); + foreach ($timezones as $key => $zones) { + foreach ($zones as $id => $zone) { + /** + * Only get timezones explicitely not part of "Others". + * + * @see http://www.php.net/manual/en/timezones.others.php + */ + if (preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Africa|Europe|Indian|Pacific)\//', $zone['timezone_id'] ) && $zone['timezone_id']) { + $cities[$zone['timezone_id']][] = $key; + } + } + } - if ($readGlobalIniFile) - $md5[] = md5_file($globalIniFile); + // For each city, have a comma separated list of all possible timezones for that city. + foreach ($cities as $key => $value) + $cities[$key] = join( ', ', $value ); - if ($readWsIniFile) - $md5[] = md5_file($wsIniFile); + // Only keep one city (the first and also most important) for each set of possibilities. + $cities = array_unique( $cities ); - $hash = implode('-', $md5); + // Sort by area/city name. + ksort( $cities ); - if ($_SESSION['PROCESSMAKER_ENV_HASH'] === $hash) { - $_SESSION['PROCESSMAKER_ENV']['from_cache'] = 1; - return $_SESSION['PROCESSMAKER_ENV']; - } + return $cities; } - // default configuration - $config = array( - 'debug' => 0, - 'debug_sql' => 0, - 'debug_time' => 0, - 'debug_calendar' => 0, - 'wsdl_cache' => 1, - 'memory_limit' => '128M', - 'time_zone' => 'America/New_York', - 'memcached' => 0, - 'memcached_server' => '', - 'default_skin' => 'classic', - 'default_lang' => 'en', - 'proxy_host' => '', - 'proxy_port' => '', - 'proxy_user' => '', - 'proxy_pass' => '' - ); + public static function getSystemConfiguration ($globalIniFile = '', $wsIniFile = '', $wsName = '') + { + $readGlobalIniFile = false; + $readWsIniFile = false; - // read the global env.ini configuration file - if ($readGlobalIniFile && ($globalConf = @parse_ini_file($globalIniFile)) !== false) { - $config = array_merge($config, $globalConf); + if (empty( $globalIniFile )) { + $globalIniFile = PATH_CORE . 'config' . PATH_SEP . 'env.ini'; + } + + if (empty( $wsIniFile )) { + if (defined( 'PATH_DB' )) { // if we're on a valid workspace env. + if (empty( $wsName )) { + $uriParts = explode( '/', getenv( "REQUEST_URI" ) ); + + if (isset( $uriParts[1] )) { + if (substr( $uriParts[1], 0, 3 ) == 'sys') { + $wsName = substr( $uriParts[1], 3 ); + } + } + } + $wsIniFile = PATH_DB . $wsName . PATH_SEP . 'env.ini'; + } + } + + $readGlobalIniFile = file_exists( $globalIniFile ) ? true : false; + $readWsIniFile = file_exists( $wsIniFile ) ? true : false; + + if (isset( $_SESSION['PROCESSMAKER_ENV'] )) { + $md5 = array (); + + if ($readGlobalIniFile) + $md5[] = md5_file( $globalIniFile ); + + if ($readWsIniFile) + $md5[] = md5_file( $wsIniFile ); + + $hash = implode( '-', $md5 ); + + if ($_SESSION['PROCESSMAKER_ENV_HASH'] === $hash) { + $_SESSION['PROCESSMAKER_ENV']['from_cache'] = 1; + return $_SESSION['PROCESSMAKER_ENV']; + } + } + + // default configuration + $config = array ('debug' => 0,'debug_sql' => 0,'debug_time' => 0,'debug_calendar' => 0,'wsdl_cache' => 1,'memory_limit' => '128M','time_zone' => 'America/New_York','memcached' => 0,'memcached_server' => '','default_skin' => 'classic','default_lang' => 'en','proxy_host' => '','proxy_port' => '','proxy_user' => '','proxy_pass' => '' + ); + + // read the global env.ini configuration file + if ($readGlobalIniFile && ($globalConf = @parse_ini_file( $globalIniFile )) !== false) { + $config = array_merge( $config, $globalConf ); + } + + // Workspace environment configuration + if ($readWsIniFile && ($wsConf = @parse_ini_file( $wsIniFile )) !== false) { + $config = array_merge( $config, $wsConf ); + } + + // validation debug config, only binary value is valid; debug = 1, to enable + $config['debug'] = $config['debug'] == 1 ? 1 : 0; + + if ($config['proxy_pass'] != '') { + $config['proxy_pass'] = G::decrypt( $config['proxy_pass'], 'proxy_pass' ); + } + + $md5 = array (); + if ($readGlobalIniFile) + $md5[] = md5_file( $globalIniFile ); + + if ($readWsIniFile) + $md5[] = md5_file( $wsIniFile ); + + $hash = implode( '-', $md5 ); + + $_SESSION['PROCESSMAKER_ENV'] = $config; + $_SESSION['PROCESSMAKER_ENV_HASH'] = $hash; + + return $config; } - // Workspace environment configuration - if ($readWsIniFile && ($wsConf = @parse_ini_file($wsIniFile)) !== false) { - $config = array_merge($config, $wsConf); + function updateIndexFile ($conf) + { + if (! file_exists( PATH_HTML . 'index.html' )) { + throw new Exception( 'The public index file "' . PATH_HTML . 'index.html" does not exist!' ); + } else { + if (! is_writable( PATH_HTML . 'index.html' )) { + throw new Exception( 'The index.html file is not writable on workflow/public_html directory.' ); + } + } + + $content = file_get_contents( PATH_HTML . 'index.html' ); + $result = false; + + $patt = '//'; + + @preg_match( $patt, $content, $match ); + + if (is_array( $match ) && count( $match ) > 0 && isset( $match[1] )) { + $newUrl = 'sys/' . $conf['lang'] . '/' . $conf['skin'] . '/login/login'; + + $newMetaStr = str_replace( $match[1], $newUrl, $match[0] ); + $newContent = str_replace( $match[0], $newMetaStr, $content ); + + $result = (@file_put_contents( PATH_HTML . 'index.html', $newContent ) !== false); + } + + return $result; } - // validation debug config, only binary value is valid; debug = 1, to enable - $config['debug'] = $config['debug'] == 1 ? 1 : 0; + function solrEnv ($sysName = '') + { + if (empty( $sysName )) { + $conf = System::getSystemConfiguration(); + } else { + $conf = System::getSystemConfiguration( '', '', $sysName ); + } - if ($config['proxy_pass'] != '') { - $config['proxy_pass'] = G::decrypt($config['proxy_pass'], 'proxy_pass'); + if (! isset( $conf['solr_enabled'] ) || ! isset( $conf['solr_host'] ) || ! isset( $conf['solr_instance'] )) { + return false; + } + + if ($conf['solr_enabled']) { + return array ('solr_enabled' => $conf['solr_enabled'],'solr_host' => $conf['solr_host'],'solr_instance' => $conf['solr_instance'] + ); + } + + return false; } - $md5 = array(); - if ($readGlobalIniFile) - $md5[] = md5_file($globalIniFile); - - if ($readWsIniFile) - $md5[] = md5_file($wsIniFile); - - $hash = implode('-', $md5); - - $_SESSION['PROCESSMAKER_ENV'] = $config; - $_SESSION['PROCESSMAKER_ENV_HASH'] = $hash; - - return $config; - } - - function updateIndexFile($conf) - { - if (!file_exists(PATH_HTML . 'index.html')) { - throw new Exception('The public index file "'.PATH_HTML . 'index.html" does not exist!'); - } - else { - if (!is_writable(PATH_HTML . 'index.html')) { - throw new Exception('The index.html file is not writable on workflow/public_html directory.'); - } - } - - $content = file_get_contents(PATH_HTML . 'index.html'); - $result = false; - - $patt = '//'; - - @preg_match($patt, $content, $match); - - if (is_array($match) && count($match) > 0 && isset($match[1])) { - $newUrl = 'sys/'.$conf['lang'].'/'.$conf['skin'].'/login/login'; - - $newMetaStr = str_replace($match[1], $newUrl, $match[0]); - $newContent = str_replace($match[0], $newMetaStr, $content); - - $result = (@file_put_contents(PATH_HTML . 'index.html', $newContent) !== false); - } - - return $result; - } - - function solrEnv($sysName = '') - { - if (empty($sysName)) { - $conf = System::getSystemConfiguration(); - } - else { - $conf = System::getSystemConfiguration('', '', $sysName); - } - - if (!isset($conf['solr_enabled']) || !isset($conf['solr_host']) || !isset($conf['solr_instance'])) { - return false; - } - - if ($conf['solr_enabled']) { - return array( - 'solr_enabled' => $conf['solr_enabled'], - 'solr_host' => $conf['solr_host'], - 'solr_instance' => $conf['solr_instance'] - ); - } - - return false; - } - }// end System class From 46a75b786763d5a624947fd50af3785735fa6c4a Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:25:26 -0400 Subject: [PATCH 10/18] CODE STYLE class.tasks.php --- workflow/engine/classes/class.tasks.php | 1517 ++++++++++++----------- 1 file changed, 763 insertions(+), 754 deletions(-) diff --git a/workflow/engine/classes/class.tasks.php b/workflow/engine/classes/class.tasks.php index f15786669..fbb2eda83 100755 --- a/workflow/engine/classes/class.tasks.php +++ b/workflow/engine/classes/class.tasks.php @@ -1,6 +1,7 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. @@ -38,322 +39,329 @@ require_once 'classes/model/Gateway.php'; /** * Tasks - Tasks class + * * @package workflow.engine.ProcessMaker * @author Julio Cesar Laura Avenda�o * @copyright 2007 COLOSA */ -class Tasks +class Tasks { - /** - * Get the assigned groups of a task - * @param string $sTaskUID - * @param integer $iType - * @return array - */ - public function getGroupsOfTask($sTaskUID, $iType) - { - try { - $aGroups = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->addJoin(GroupwfPeer::GRP_UID, TaskUserPeer::USR_UID, Criteria::LEFT_JOIN); - $oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID); - $oCriteria->add(TaskUserPeer::TU_TYPE, $iType); - $oCriteria->add(TaskUserPeer::TU_RELATION, 2); - $oCriteria->add(GroupwfPeer::GRP_STATUS, 'ACTIVE'); - $oDataset = GroupwfPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aGroups[] = $aRow; - $oDataset->next(); - } - return $aGroups; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Get all tasks for any Process - * @param string $sProUid - * @return array - */ - public function getAllTasks($sProUid) - { - try { - $aTasks = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(TaskPeer::PRO_UID, $sProUid); - $oDataset = TaskPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $oTask = new Task(); - $aTasks[] = $oTask->Load($aRow['TAS_UID']); - $oDataset->next(); - } - return $aTasks; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * creates row tasks from an Task Array - * @param string $aTasks - * @return array - */ - public function createTaskRows( $aTask ) - { - foreach ( $aTask as $key => $row ) { - $oTask = new Task(); - if($oTask->taskExists ($row['TAS_UID'])) - $oTask->remove($row['TAS_UID']); - $res = $oTask->createRow($row); - } - return; - } - - /** - * updates row tasks from an Task Array - * @param string $aTasks - * @return array - */ - public function updateTaskRows( $aTask ) - { - foreach ( $aTask as $key => $row ) { - $oTask = new Task(); - if($oTask->taskExists ($row['TAS_UID'])) - $oTask->remove($row['TAS_UID']); - else - $res = $oTask->update($row); - } - return; - } - - /** - * Get all Routes for any Process - * @param string $sProUid - * @return array - */ - public function getAllRoutes($sProUid) - { - try { - $aRoutes = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(RoutePeer::PRO_UID, $sProUid); - $oDataset = RoutePeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aRoutes[] = $aRow; - $oDataset->next(); - } - return $aRoutes; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * creates row tasks from an Route Array - * @param string $aTasks - * @return array - */ - public function createRouteRows( $aRoutes ) - { - $routeID = array(); - $aField = array(); - $taskParallel = ''; - $taskSecJoin = ''; - $taskEvaluate = ''; - $taskParallelEv = ''; - $taskSelect = ''; - $taskDiscriminator = ''; - foreach ( $aRoutes as $key => $row ) { - $sRouteType = $row['ROU_TYPE']; - $oRoute = new Route(); - $oProcessMap = new processMap(); - $oTask = new Task(); - $oEvent = new Event(); - //unset ($row['ROU_UID']); - - //Saving Gateway into the GATEWAY table - $idTask = $row['TAS_UID']; - $nextTask = $row['ROU_NEXT_TASK']; - if($nextTask == "-1"){ - $end=1; - } - if($sRouteType != 'SEQUENTIAL'){ - switch($sRouteType){ - case 'PARALLEL': - if($idTask != $taskParallel){ - $taskParallel = $idTask; - - $sGatewayUID = $oProcessMap->saveNewGateway($row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK']); + /** + * Get the assigned groups of a task + * + * @param string $sTaskUID + * @param integer $iType + * @return array + */ + public function getGroupsOfTask ($sTaskUID, $iType) + { + try { + $aGroups = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addJoin( GroupwfPeer::GRP_UID, TaskUserPeer::USR_UID, Criteria::LEFT_JOIN ); + $oCriteria->add( TaskUserPeer::TAS_UID, $sTaskUID ); + $oCriteria->add( TaskUserPeer::TU_TYPE, $iType ); + $oCriteria->add( TaskUserPeer::TU_RELATION, 2 ); + $oCriteria->add( GroupwfPeer::GRP_STATUS, 'ACTIVE' ); + $oDataset = GroupwfPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aGroups[] = $aRow; + $oDataset->next(); } - break; - case 'SEC-JOIN': - if($nextTask != $taskSecJoin){ - $taskSecJoin = $nextTask; - $sGatewayUID = $oProcessMap->saveNewGateway($row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK']); - } - break; - case 'EVALUATE': - if($idTask != $taskEvaluate){ - $taskEvaluate = $idTask; - $sGatewayUID = $oProcessMap->saveNewGateway($row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK']); - } - break; - case 'PARALLEL-BY-EVALUATION': - if($idTask != $taskParallelEv){ - $taskParallelEv = $idTask; - $sGatewayUID = $oProcessMap->saveNewGateway($row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK']); - } - break; - case 'SELECT': - if($idTask != $taskSelect){ - $taskSelect = $idTask; - $sGatewayUID = $oProcessMap->saveNewGateway($row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK']); - } - break; - case 'DISCRIMINATOR': - if($nextTask != $taskDiscriminator){ - $taskDiscriminator = $nextTask; - $sGatewayUID = $oProcessMap->saveNewGateway($row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK']); - } - break; - } - $row['GAT_UID'] = $sGatewayUID; - } - - if($oRoute->routeExists($row['ROU_UID'])) - $oRoute->remove($row['ROU_UID']); - - $routeID = $oRoute->create($row); - - //saving end event while import old processes - if(isset($end) && $end==1){ - if(! $oEvent->existsByTaskUidFrom($idTask)) { - if($sRouteType == "SEQUENTIAL"){ - $aTaskDetails = $oTask->load($idTask); - $positionX = $aTaskDetails['TAS_POSX'] + $aTaskDetails['TAS_WIDTH']/2; - $positionY = $aTaskDetails['TAS_POSY'] + $aTaskDetails['TAS_HEIGHT'] + 10; - - $aData['PRO_UID'] = $row['PRO_UID']; - $aData['EVN_TYPE'] = 'bpmnEventEmptyEnd'; - $aData['EVN_POSX'] = $positionX; - $aData['EVN_POSY'] = $positionY; - $aData['EVN_TAS_UID_FROM'] = $idTask; - $aData['EVN_STATUS'] = 'ACTIVE'; - $aData['EVN_RELATED_TO'] = 'MULTIPLE'; - $aData['EVN_WHEN'] = '1'; - $aData['EVN_ACTION'] = ''; - $sEvn_uid = $oEvent->create($aData); - - $aField['ROU_UID'] = $routeID; - $aField['ROU_EVN_UID'] = $sEvn_uid; - $oRoute->update($aField); - $end = 0; - } + return $aGroups; + } catch (Exception $oError) { + throw ($oError); } - } - } - return; - } - /** - * updates row tasks from an Route Array - * @param string $aTasks - * @return array - */ - public function updateRouteRows( $aRoutes ) - { - foreach ( $aRoutes as $key => $row ) { - $oRoute = new Route(); - //krumo ($row); - if(is_array($oRoute->load($row['ROU_UID']))) - $oRoute->remove($row['ROU_UID']); - else - $res = $oRoute->update($row); + /** + * Get all tasks for any Process + * + * @param string $sProUid + * @return array + */ + public function getAllTasks ($sProUid) + { + try { + $aTasks = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( TaskPeer::PRO_UID, $sProUid ); + $oDataset = TaskPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $oTask = new Task(); + $aTasks[] = $oTask->Load( $aRow['TAS_UID'] ); + $oDataset->next(); + } + return $aTasks; + } catch (Exception $oError) { + throw ($oError); + } } - return; - } - /** - * Get the assigned users of a task - * @param string $sTaskUID - * @param integer $iType - * @return array - */ - public function getUsersOfTask($sTaskUID, $iType) - { - try { - $aUsers = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->addJoin(UsersPeer::USR_UID, TaskUserPeer::USR_UID, Criteria::LEFT_JOIN); - $oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID); - $oCriteria->add(TaskUserPeer::TU_TYPE, $iType); - $oCriteria->add(TaskUserPeer::TU_RELATION, 1); - $oDataset = UsersPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aUsers[] = $aRow; - $oDataset->next(); - } - return $aUsers; + /** + * creates row tasks from an Task Array + * + * @param string $aTasks + * @return array + */ + public function createTaskRows ($aTask) + { + foreach ($aTask as $key => $row) { + $oTask = new Task(); + if ($oTask->taskExists( $row['TAS_UID'] )) + $oTask->remove( $row['TAS_UID'] ); + $res = $oTask->createRow( $row ); + } + return; } - catch (Exception $oError) { - throw($oError); - } - } - /** - * Delete a task - * @param string $sTaskUID - * @return void - */ - function deleteTask($sTaskUID = '') - { - try { - //Instance classes - $oTask = new Task(); - $oTasks = new Tasks(); - $oTaskUser = new TaskUser(); - $oStep = new Step(); - $oStepTrigger = new StepTrigger(); - //Get task information - $aFields = $oTask->load($sTaskUID); - //Delete routes - $oTasks->deleteAllRoutesOfTask($aFields['PRO_UID'], $sTaskUID, true); - //Delete gateways - $oTasks->deleteAllGatewayOfTask($aFields['PRO_UID'], $sTaskUID, true); - //Delete the users assigned to task - $oCriteria = new Criteria('workflow'); - $oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID); - $oDataset1 = TaskUserPeer::doSelectRS($oCriteria); - $oDataset1->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset1->next(); - while ($aRow1 = $oDataset1->getRow()) { - $oTaskUser->remove($aRow1['TAS_UID'], $aRow1['USR_UID'], $aRow1['TU_TYPE'], $aRow1['TU_RELATION']); - $oDataset1->next(); - } - //Delete the steps of task - $oCriteria = new Criteria('workflow'); - $oCriteria->add(StepPeer::TAS_UID, $sTaskUID); - $oDataset1 = StepPeer::doSelectRS($oCriteria); - $oDataset1->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset1->next(); - while ($aRow1 = $oDataset1->getRow()) { - //Delete the triggers assigned to step - /*$oCriteria = new Criteria('workflow'); + /** + * updates row tasks from an Task Array + * + * @param string $aTasks + * @return array + */ + public function updateTaskRows ($aTask) + { + foreach ($aTask as $key => $row) { + $oTask = new Task(); + if ($oTask->taskExists( $row['TAS_UID'] )) + $oTask->remove( $row['TAS_UID'] ); + else + $res = $oTask->update( $row ); + } + return; + } + + /** + * Get all Routes for any Process + * + * @param string $sProUid + * @return array + */ + public function getAllRoutes ($sProUid) + { + try { + $aRoutes = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( RoutePeer::PRO_UID, $sProUid ); + $oDataset = RoutePeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aRoutes[] = $aRow; + $oDataset->next(); + } + return $aRoutes; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * creates row tasks from an Route Array + * + * @param string $aTasks + * @return array + */ + public function createRouteRows ($aRoutes) + { + $routeID = array (); + $aField = array (); + $taskParallel = ''; + $taskSecJoin = ''; + $taskEvaluate = ''; + $taskParallelEv = ''; + $taskSelect = ''; + $taskDiscriminator = ''; + foreach ($aRoutes as $key => $row) { + $sRouteType = $row['ROU_TYPE']; + $oRoute = new Route(); + $oProcessMap = new processMap(); + $oTask = new Task(); + $oEvent = new Event(); + //unset ($row['ROU_UID']); + + + //Saving Gateway into the GATEWAY table + $idTask = $row['TAS_UID']; + $nextTask = $row['ROU_NEXT_TASK']; + if ($nextTask == "-1") { + $end = 1; + } + if ($sRouteType != 'SEQUENTIAL') { + switch ($sRouteType) { + case 'PARALLEL': + if ($idTask != $taskParallel) { + $taskParallel = $idTask; + + $sGatewayUID = $oProcessMap->saveNewGateway( $row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK'] ); + } + break; + case 'SEC-JOIN': + if ($nextTask != $taskSecJoin) { + $taskSecJoin = $nextTask; + $sGatewayUID = $oProcessMap->saveNewGateway( $row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK'] ); + } + break; + case 'EVALUATE': + if ($idTask != $taskEvaluate) { + $taskEvaluate = $idTask; + $sGatewayUID = $oProcessMap->saveNewGateway( $row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK'] ); + } + break; + case 'PARALLEL-BY-EVALUATION': + if ($idTask != $taskParallelEv) { + $taskParallelEv = $idTask; + $sGatewayUID = $oProcessMap->saveNewGateway( $row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK'] ); + } + break; + case 'SELECT': + if ($idTask != $taskSelect) { + $taskSelect = $idTask; + $sGatewayUID = $oProcessMap->saveNewGateway( $row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK'] ); + } + break; + case 'DISCRIMINATOR': + if ($nextTask != $taskDiscriminator) { + $taskDiscriminator = $nextTask; + $sGatewayUID = $oProcessMap->saveNewGateway( $row['PRO_UID'], $row['TAS_UID'], $row['ROU_NEXT_TASK'] ); + } + break; + } + $row['GAT_UID'] = $sGatewayUID; + } + + if ($oRoute->routeExists( $row['ROU_UID'] )) + $oRoute->remove( $row['ROU_UID'] ); + + $routeID = $oRoute->create( $row ); + + //saving end event while import old processes + if (isset( $end ) && $end == 1) { + if (! $oEvent->existsByTaskUidFrom( $idTask )) { + if ($sRouteType == "SEQUENTIAL") { + $aTaskDetails = $oTask->load( $idTask ); + $positionX = $aTaskDetails['TAS_POSX'] + $aTaskDetails['TAS_WIDTH'] / 2; + $positionY = $aTaskDetails['TAS_POSY'] + $aTaskDetails['TAS_HEIGHT'] + 10; + + $aData['PRO_UID'] = $row['PRO_UID']; + $aData['EVN_TYPE'] = 'bpmnEventEmptyEnd'; + $aData['EVN_POSX'] = $positionX; + $aData['EVN_POSY'] = $positionY; + $aData['EVN_TAS_UID_FROM'] = $idTask; + $aData['EVN_STATUS'] = 'ACTIVE'; + $aData['EVN_RELATED_TO'] = 'MULTIPLE'; + $aData['EVN_WHEN'] = '1'; + $aData['EVN_ACTION'] = ''; + $sEvn_uid = $oEvent->create( $aData ); + + $aField['ROU_UID'] = $routeID; + $aField['ROU_EVN_UID'] = $sEvn_uid; + $oRoute->update( $aField ); + $end = 0; + } + } + } + + } + return; + } + + /** + * updates row tasks from an Route Array + * + * @param string $aTasks + * @return array + */ + public function updateRouteRows ($aRoutes) + { + foreach ($aRoutes as $key => $row) { + $oRoute = new Route(); + //krumo ($row); + if (is_array( $oRoute->load( $row['ROU_UID'] ) )) + $oRoute->remove( $row['ROU_UID'] ); + else + $res = $oRoute->update( $row ); + } + return; + } + + /** + * Get the assigned users of a task + * + * @param string $sTaskUID + * @param integer $iType + * @return array + */ + public function getUsersOfTask ($sTaskUID, $iType) + { + try { + $aUsers = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addJoin( UsersPeer::USR_UID, TaskUserPeer::USR_UID, Criteria::LEFT_JOIN ); + $oCriteria->add( TaskUserPeer::TAS_UID, $sTaskUID ); + $oCriteria->add( TaskUserPeer::TU_TYPE, $iType ); + $oCriteria->add( TaskUserPeer::TU_RELATION, 1 ); + $oDataset = UsersPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aUsers[] = $aRow; + $oDataset->next(); + } + return $aUsers; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Delete a task + * + * @param string $sTaskUID + * @return void + */ + function deleteTask ($sTaskUID = '') + { + try { + //Instance classes + $oTask = new Task(); + $oTasks = new Tasks(); + $oTaskUser = new TaskUser(); + $oStep = new Step(); + $oStepTrigger = new StepTrigger(); + //Get task information + $aFields = $oTask->load( $sTaskUID ); + //Delete routes + $oTasks->deleteAllRoutesOfTask( $aFields['PRO_UID'], $sTaskUID, true ); + //Delete gateways + $oTasks->deleteAllGatewayOfTask( $aFields['PRO_UID'], $sTaskUID, true ); + //Delete the users assigned to task + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( TaskUserPeer::TAS_UID, $sTaskUID ); + $oDataset1 = TaskUserPeer::doSelectRS( $oCriteria ); + $oDataset1->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset1->next(); + while ($aRow1 = $oDataset1->getRow()) { + $oTaskUser->remove( $aRow1['TAS_UID'], $aRow1['USR_UID'], $aRow1['TU_TYPE'], $aRow1['TU_RELATION'] ); + $oDataset1->next(); + } + //Delete the steps of task + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( StepPeer::TAS_UID, $sTaskUID ); + $oDataset1 = StepPeer::doSelectRS( $oCriteria ); + $oDataset1->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset1->next(); + while ($aRow1 = $oDataset1->getRow()) { + //Delete the triggers assigned to step + /*$oCriteria = new Criteria('workflow'); $oCriteria->add(StepTriggerPeer::STEP_UID, $aRow1['STEP_UID']); $oDataset2 = StepTriggerPeer::doSelectRS($oCriteria); $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); @@ -362,168 +370,170 @@ class Tasks $oStepTrigger->remove($aRow2['STEP_UID'], $aRow2['TAS_UID'], $aRow2['TRI_UID'], $aRow2['ST_TYPE']); $oDataset2->next(); }*/ - $oStep->remove($aRow1['STEP_UID']); - $oDataset1->next(); - } - //Delete step triggers - $oCriteria = new Criteria('workflow'); - $oCriteria->add(StepTriggerPeer::TAS_UID, $sTaskUID); - StepTriggerPeer::doDelete($oCriteria); - //Delete permissions - $oCriteria = new Criteria('workflow'); - $oCriteria->add(ObjectPermissionPeer::TAS_UID, $sTaskUID); - ObjectPermissionPeer::doDelete($oCriteria); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(ObjectPermissionPeer::OP_TASK_SOURCE, $sTaskUID); - ObjectPermissionPeer::doDelete($oCriteria); - //Delete task - $oTask->remove($sTaskUID); - //Delete cases schedulers added by krlos - $oCriteria = new Criteria('workflow'); - $oCriteria->add(CaseSchedulerPeer::TAS_UID, $sTaskUID); - CaseSchedulerPeer::doDelete($oCriteria); + $oStep->remove( $aRow1['STEP_UID'] ); + $oDataset1->next(); + } + //Delete step triggers + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( StepTriggerPeer::TAS_UID, $sTaskUID ); + StepTriggerPeer::doDelete( $oCriteria ); + //Delete permissions + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( ObjectPermissionPeer::TAS_UID, $sTaskUID ); + ObjectPermissionPeer::doDelete( $oCriteria ); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( ObjectPermissionPeer::OP_TASK_SOURCE, $sTaskUID ); + ObjectPermissionPeer::doDelete( $oCriteria ); + //Delete task + $oTask->remove( $sTaskUID ); + //Delete cases schedulers added by krlos + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( CaseSchedulerPeer::TAS_UID, $sTaskUID ); + CaseSchedulerPeer::doDelete( $oCriteria ); + } catch (Exception $oError) { + throw ($oError); + } } - catch (Exception $oError) { - throw($oError); - } - } - /** - * Delete all routes from a task - * @param string $sProcessUID - * @param string $sTaskUID - * @return boolean - */ - public function deleteAllRoutesOfTask($sProcessUID = '', $sTaskUID = '', $bAll = false) - { - try { - $oProcess = new Process(); - $aFields = $oProcess->load($sProcessUID); - $oTask = new Task(); - $aFields = $oTask->load($sTaskUID); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(RoutePeer::PRO_UID, $sProcessUID); - $oCriteria->add(RoutePeer::TAS_UID, $sTaskUID); - RoutePeer::doDelete($oCriteria); - if ($bAll) { - $oCriteria = new Criteria('workflow'); - $oCriteria->add(RoutePeer::PRO_UID, $sProcessUID); - $oCriteria->add(RoutePeer::ROU_NEXT_TASK, $sTaskUID); - RoutePeer::doDelete($oCriteria); - } - return true; + /** + * Delete all routes from a task + * + * @param string $sProcessUID + * @param string $sTaskUID + * @return boolean + */ + public function deleteAllRoutesOfTask ($sProcessUID = '', $sTaskUID = '', $bAll = false) + { + try { + $oProcess = new Process(); + $aFields = $oProcess->load( $sProcessUID ); + $oTask = new Task(); + $aFields = $oTask->load( $sTaskUID ); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( RoutePeer::PRO_UID, $sProcessUID ); + $oCriteria->add( RoutePeer::TAS_UID, $sTaskUID ); + RoutePeer::doDelete( $oCriteria ); + if ($bAll) { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( RoutePeer::PRO_UID, $sProcessUID ); + $oCriteria->add( RoutePeer::ROU_NEXT_TASK, $sTaskUID ); + RoutePeer::doDelete( $oCriteria ); + } + return true; + } catch (Exception $oError) { + throw ($oError); + } } - catch (Exception $oError) { - throw($oError); - } - } - /** - * Get all gateways for any Process - * @param string $sProUid - * @return array - */ - public function getAllGateways($sProUid) - { - try { - $aGateways = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(GatewayPeer::PRO_UID, $sProUid); - $oDataset = GatewayPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $oGateway = new Gateway(); - $aGateways[] = $oGateway->load($aRow['GAT_UID']); - $oDataset->next(); - } - return $aGateways; + /** + * Get all gateways for any Process + * + * @param string $sProUid + * @return array + */ + public function getAllGateways ($sProUid) + { + try { + $aGateways = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( GatewayPeer::PRO_UID, $sProUid ); + $oDataset = GatewayPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $oGateway = new Gateway(); + $aGateways[] = $oGateway->load( $aRow['GAT_UID'] ); + $oDataset->next(); + } + return $aGateways; + } catch (Exception $oError) { + throw ($oError); + } } - catch (Exception $oError) { - throw($oError); - } - } - /** - * creates row tasks from an Task Array - * @param string $aTasks - * @return array - */ - public function createGatewayRows( $aGateway ) - { - foreach ( $aGateway as $key => $row ) { - $oGateway = new Gateway(); - if($oGateway->gatewayExists ($row['GAT_UID'])) - $oGateway->remove($row['GAT_UID']); + /** + * creates row tasks from an Task Array + * + * @param string $aTasks + * @return array + */ + public function createGatewayRows ($aGateway) + { + foreach ($aGateway as $key => $row) { + $oGateway = new Gateway(); + if ($oGateway->gatewayExists( $row['GAT_UID'] )) + $oGateway->remove( $row['GAT_UID'] ); - if($row['TAS_UID'] != '' && $row['GAT_NEXT_TASK'] != '') - continue; - else - $res = $oGateway->createRow($row); + if ($row['TAS_UID'] != '' && $row['GAT_NEXT_TASK'] != '') + continue; + else + $res = $oGateway->createRow( $row ); + } + return; } - return; - } - /** - * Delete all routes from a task - * @param string $sProcessUID - * @param string $sTaskUID - * @return boolean - */ - public function deleteAllGatewayOfTask($sProcessUID = '', $sTaskUID = '', $bAll = false) - { - try { - $oProcess = new Process(); - $aFields = $oProcess->load($sProcessUID); - $oTask = new Task(); - $aFields = $oTask->load($sTaskUID); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(GatewayPeer::PRO_UID, $sProcessUID); - $oCriteria->add(GatewayPeer::TAS_UID, $sTaskUID); - GatewayPeer::doDelete($oCriteria); - if ($bAll) { - $oCriteria = new Criteria('workflow'); - $oCriteria->add(GatewayPeer::PRO_UID, $sProcessUID); - $oCriteria->add(GatewayPeer::GAT_NEXT_TASK, $sTaskUID); - GatewayPeer::doDelete($oCriteria); - } - return true; + /** + * Delete all routes from a task + * + * @param string $sProcessUID + * @param string $sTaskUID + * @return boolean + */ + public function deleteAllGatewayOfTask ($sProcessUID = '', $sTaskUID = '', $bAll = false) + { + try { + $oProcess = new Process(); + $aFields = $oProcess->load( $sProcessUID ); + $oTask = new Task(); + $aFields = $oTask->load( $sTaskUID ); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( GatewayPeer::PRO_UID, $sProcessUID ); + $oCriteria->add( GatewayPeer::TAS_UID, $sTaskUID ); + GatewayPeer::doDelete( $oCriteria ); + if ($bAll) { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( GatewayPeer::PRO_UID, $sProcessUID ); + $oCriteria->add( GatewayPeer::GAT_NEXT_TASK, $sTaskUID ); + GatewayPeer::doDelete( $oCriteria ); + } + return true; + } catch (Exception $oError) { + throw ($oError); + } } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Assign a user to task - * @param string $sTaskUID - * @param string $sUserUID - * @param string $iType - * @return integer - */ - public function assignUser($sTaskUID = '', $sUserUID = '', $iType = '') - { - try { - $oTaskUser = new TaskUser(); - return $oTaskUser->create(array('TAS_UID' => $sTaskUID, 'USR_UID' => $sUserUID, 'TU_TYPE' => $iType, 'TU_RELATION' => 1)); - } - catch (Exception $oError) { - throw($oError); - } - } - /** - * Assign a group to task - * @param string $sTaskUID - * @param string $sGroupUID - * @param string $iType - * @return integer - */ - public function assignGroup($sTaskUID = '', $sGroupUID = '', $iType = '') - { - try { - $oTaskUser = new TaskUser(); - /*$oCriteria = new Criteria('workflow'); + /** + * Assign a user to task + * + * @param string $sTaskUID + * @param string $sUserUID + * @param string $iType + * @return integer + */ + public function assignUser ($sTaskUID = '', $sUserUID = '', $iType = '') + { + try { + $oTaskUser = new TaskUser(); + return $oTaskUser->create( array ('TAS_UID' => $sTaskUID,'USR_UID' => $sUserUID,'TU_TYPE' => $iType,'TU_RELATION' => 1 + ) ); + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Assign a group to task + * + * @param string $sTaskUID + * @param string $sGroupUID + * @param string $iType + * @return integer + */ + public function assignGroup ($sTaskUID = '', $sGroupUID = '', $iType = '') + { + try { + $oTaskUser = new TaskUser(); + /*$oCriteria = new Criteria('workflow'); $oCriteria->add(GroupUserPeer::GRP_UID, $sGroupUID); $oDataset = GroupUserPeer::doSelectRS($oCriteria); $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); @@ -541,318 +551,317 @@ class Tasks } $oDataset->next(); }*/ - return $oTaskUser->create(array('TAS_UID' => $sTaskUID, 'USR_UID' => $sGroupUID, 'TU_TYPE' => $iType, 'TU_RELATION' => 2)); - } - catch (Exception $oError) { - throw($oError); - } - } - /** - * of the assign user of all the tasks - * @param string $sUserUID - * @return void - */ - public function ofToAssignUserOfAllTasks($sUserUID = '') - { - try { - $oCriteria = new Criteria('workflow'); - $oCriteria->add(TaskUserPeer::USR_UID, $sUserUID); - TaskUserPeer::doDelete($oCriteria); - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Of to assign a user from a task - * @param string $sTaskUID - * @param string $sUserUID - * @param integer $iType - * @return boolean - */ - public function ofToAssignUser($sTaskUID = '', $sUserUID = '', $iType = 0) - { - try { - $oTaskUser = new TaskUser(); - $oTaskUser->remove($sTaskUID, $sUserUID, $iType, 1); - return true; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Of to assign a group from a task - * @param string $sTaskUID - * @param string $sGroupUID - * @param integer $iType - * @return boolean - */ - public function ofToAssignGroup($sTaskUID = '', $sGroupUID = '', $iType = 0) - { - try { - $oTaskUser = new TaskUser(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(GroupUserPeer::GRP_UID, $sGroupUID); - $oDataset = GroupUserPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aGroupUser = $oDataset->getRow()) { - $oCriteria = new Criteria('workflow'); - $oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID); - $oCriteria->add(TaskUserPeer::USR_UID, $aGroupUser['USR_UID']); - $oDataset2 = TaskUserPeer::doSelectRS($oCriteria); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - $aRow = $oDataset2->getRow(); - if (is_array($aRow)) { - $this->ofToAssignUser($sTaskUID, $aGroupUser['USR_UID'], $iType); + return $oTaskUser->create( array ('TAS_UID' => $sTaskUID,'USR_UID' => $sGroupUID,'TU_TYPE' => $iType,'TU_RELATION' => 2 + ) ); + } catch (Exception $oError) { + throw ($oError); } - $oDataset->next(); - } - return $oTaskUser->remove($sTaskUID, $sGroupUID, $iType, 2); } - catch (Exception $oError) { - throw($oError); - } - } - /** - * Get the assigned steps of a task - * @param string $sTaskUID - * @return array - */ - public function getStepsOfTask($sTaskUID) - { - try { - $aSteps = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(StepPeer::TAS_UID, $sTaskUID); - $oCriteria->addAscendingOrderByColumn(StepPeer::STEP_POSITION); - $oDataset = StepPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aSteps[] = $aRow; - $oDataset->next(); - } - return $aSteps; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Return if exists building elements to add steps - * @param string $sProcessUID - * @return boolean - */ - public function existsBuildingElements($sProcessUID) - { - try { - $oCriteria = new Criteria('workflow'); - //$oCriteria->add(StepPeer::PRO_UID, $sProcessUID); - //$oDataset = StepPeer::doSelectRS($oCriteria); - //$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - //$oDataset->next(); - return true; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Get all tasks for any Process - * @param string $sProUid - * @return array - */ - public function getStartingTaskForUser($sProUid, $sUsrUid) - { - try { - $aTasks = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(TaskPeer::PRO_UID, $sProUid); - //$oCriteria->add(TaskPeer::TAS_USER, $sUsrUid); - $oCriteria->add(TaskPeer::TAS_START, 'TRUE'); - $oDataset = TaskPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $oTask = new Task(); - $aTasks[] = $oTask->Load($aRow['TAS_UID']); - $oDataset->next(); - } - return $aTasks; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Verify the user assig in any task - * @param string $sTaskUID - * @return array - */ - public function assignUsertoTask($sTaskUID) - { - try { - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(TaskUserPeer::USR_UID); - $oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID); - $oDataset = TaskUserPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - $aRow = $oDataset->getRow(); - if(is_array($aRow)) - return 1; - else - return 0; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Verify the user assig in task - * @param string $sUsrUid, $sTaskUID - * @return array - */ - public function verifyUsertoTask($sUsrUid, $sTaskUID) - { - try { - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(TaskUserPeer::USR_UID); - $oCriteria->addSelectColumn(TaskUserPeer::TAS_UID); - $oCriteria->addSelectColumn(TaskUserPeer::TU_RELATION); - $oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID); - $oCriteria->add(TaskUserPeer::USR_UID, $sUsrUid); - $oDataset = TaskUserPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - $aRow = $oDataset->getRow(); - if(is_array($aRow)) - return $aRow; - else - return $aRow; - } - catch (Exception $oError) { - throw($oError); - } - } - - /** - * Get tasks that the usser is assigned - * @param string $sUsrUID - * @return array - */ - public function getTasksThatUserIsAssigned($sUserUID) - { - try { - $aTasks = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(TaskUserPeer::USR_UID, $sUserUID); - $oCriteria->add(TaskUserPeer::TU_RELATION, 1); - $oDataset = TaskUserPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aTasks[] = $aRow['TAS_UID']; - $oDataset->next(); - } - $aGroups = array(); - $oCriteria = new Criteria(); - $oCriteria->add(GroupwfPeer::GRP_UID, '', Criteria::NOT_EQUAL); - $oCriteria->add(GroupUserPeer::USR_UID, $sUserUID); - $oCriteria->add(GroupwfPeer::GRP_STATUS, 'ACTIVE'); - $oCriteria->addJoin(GroupUserPeer::GRP_UID, GroupwfPeer::GRP_UID, Criteria::LEFT_JOIN); - $oDataset = GroupwfPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aGroups[] = $aRow['GRP_UID']; - $oDataset->next(); - } - $oCriteria = new Criteria('workflow'); - $oCriteria->add(TaskUserPeer::USR_UID, $aGroups, Criteria::IN); - $oCriteria->add(TaskUserPeer::TU_RELATION, 2); - $oDataset = TaskUserPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - if (!in_array($aRow['TAS_UID'], $aTasks)) { - $aTasks[] = $aRow['TAS_UID']; + /** + * of the assign user of all the tasks + * + * @param string $sUserUID + * @return void + */ + public function ofToAssignUserOfAllTasks ($sUserUID = '') + { + try { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( TaskUserPeer::USR_UID, $sUserUID ); + TaskUserPeer::doDelete( $oCriteria ); + } catch (Exception $oError) { + throw ($oError); } - $oDataset->next(); - } - return $aTasks; } - catch (Exception $oError) { - throw($oError); - } - } - /** - * Get Routes for any Process and any Task - * @param string $sProUid, $sTaskUid - * @return array - * by Everth - */ - public function getRoute($sProUid, $sTaskUid) - { - try { - $aRoutes = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(RoutePeer::PRO_UID, $sProUid); - $oCriteria->add(RoutePeer::TAS_UID, $sTaskUid); - $oDataset = RoutePeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aRoutes[] = $aRow; - $oDataset->next(); - } + /** + * Of to assign a user from a task + * + * @param string $sTaskUID + * @param string $sUserUID + * @param integer $iType + * @return boolean + */ + public function ofToAssignUser ($sTaskUID = '', $sUserUID = '', $iType = 0) + { + try { + $oTaskUser = new TaskUser(); + $oTaskUser->remove( $sTaskUID, $sUserUID, $iType, 1 ); + return true; + } catch (Exception $oError) { + throw ($oError); + } + } - return $aRoutes; + /** + * Of to assign a group from a task + * + * @param string $sTaskUID + * @param string $sGroupUID + * @param integer $iType + * @return boolean + */ + public function ofToAssignGroup ($sTaskUID = '', $sGroupUID = '', $iType = 0) + { + try { + $oTaskUser = new TaskUser(); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( GroupUserPeer::GRP_UID, $sGroupUID ); + $oDataset = GroupUserPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aGroupUser = $oDataset->getRow()) { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( TaskUserPeer::TAS_UID, $sTaskUID ); + $oCriteria->add( TaskUserPeer::USR_UID, $aGroupUser['USR_UID'] ); + $oDataset2 = TaskUserPeer::doSelectRS( $oCriteria ); + $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset2->next(); + $aRow = $oDataset2->getRow(); + if (is_array( $aRow )) { + $this->ofToAssignUser( $sTaskUID, $aGroupUser['USR_UID'], $iType ); + } + $oDataset->next(); + } + return $oTaskUser->remove( $sTaskUID, $sGroupUID, $iType, 2 ); + } catch (Exception $oError) { + throw ($oError); + } } - catch (Exception $oError) { - throw($oError); - } - } -/** - * Get Routes for any Process,route type,route next task - * @param string $sProUid, $sTaskUid - * @return array - * by Girish - */ - public function getRouteByType($sProUid, $sRouteNextTaskUid,$sRouteType) - { - try { - $aRoutes = array(); - $oCriteria = new Criteria('workflow'); - $oCriteria->add(RoutePeer::PRO_UID, $sProUid); - $oCriteria->add(RoutePeer::ROU_NEXT_TASK, $sRouteNextTaskUid); - $oCriteria->add(RoutePeer::ROU_TYPE, $sRouteType); - $oDataset = RoutePeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $aRoutes[] = $aRow; - $oDataset->next(); - } + /** + * Get the assigned steps of a task + * + * @param string $sTaskUID + * @return array + */ + public function getStepsOfTask ($sTaskUID) + { + try { + $aSteps = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( StepPeer::TAS_UID, $sTaskUID ); + $oCriteria->addAscendingOrderByColumn( StepPeer::STEP_POSITION ); + $oDataset = StepPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aSteps[] = $aRow; + $oDataset->next(); + } + return $aSteps; + } catch (Exception $oError) { + throw ($oError); + } + } - return $aRoutes; + /** + * Return if exists building elements to add steps + * + * @param string $sProcessUID + * @return boolean + */ + public function existsBuildingElements ($sProcessUID) + { + try { + $oCriteria = new Criteria( 'workflow' ); + //$oCriteria->add(StepPeer::PRO_UID, $sProcessUID); + //$oDataset = StepPeer::doSelectRS($oCriteria); + //$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + //$oDataset->next(); + return true; + } catch (Exception $oError) { + throw ($oError); + } } - catch (Exception $oError) { - throw($oError); + + /** + * Get all tasks for any Process + * + * @param string $sProUid + * @return array + */ + public function getStartingTaskForUser ($sProUid, $sUsrUid) + { + try { + $aTasks = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( TaskPeer::PRO_UID, $sProUid ); + //$oCriteria->add(TaskPeer::TAS_USER, $sUsrUid); + $oCriteria->add( TaskPeer::TAS_START, 'TRUE' ); + $oDataset = TaskPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $oTask = new Task(); + $aTasks[] = $oTask->Load( $aRow['TAS_UID'] ); + $oDataset->next(); + } + return $aTasks; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Verify the user assig in any task + * + * @param string $sTaskUID + * @return array + */ + public function assignUsertoTask ($sTaskUID) + { + try { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( TaskUserPeer::USR_UID ); + $oCriteria->add( TaskUserPeer::TAS_UID, $sTaskUID ); + $oDataset = TaskUserPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aRow = $oDataset->getRow(); + if (is_array( $aRow )) + return 1; + else + return 0; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Verify the user assig in task + * + * @param string $sUsrUid, $sTaskUID + * @return array + */ + public function verifyUsertoTask ($sUsrUid, $sTaskUID) + { + try { + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( TaskUserPeer::USR_UID ); + $oCriteria->addSelectColumn( TaskUserPeer::TAS_UID ); + $oCriteria->addSelectColumn( TaskUserPeer::TU_RELATION ); + $oCriteria->add( TaskUserPeer::TAS_UID, $sTaskUID ); + $oCriteria->add( TaskUserPeer::USR_UID, $sUsrUid ); + $oDataset = TaskUserPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aRow = $oDataset->getRow(); + if (is_array( $aRow )) + return $aRow; + else + return $aRow; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Get tasks that the usser is assigned + * + * @param string $sUsrUID + * @return array + */ + public function getTasksThatUserIsAssigned ($sUserUID) + { + try { + $aTasks = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( TaskUserPeer::USR_UID, $sUserUID ); + $oCriteria->add( TaskUserPeer::TU_RELATION, 1 ); + $oDataset = TaskUserPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aTasks[] = $aRow['TAS_UID']; + $oDataset->next(); + } + $aGroups = array (); + $oCriteria = new Criteria(); + $oCriteria->add( GroupwfPeer::GRP_UID, '', Criteria::NOT_EQUAL ); + $oCriteria->add( GroupUserPeer::USR_UID, $sUserUID ); + $oCriteria->add( GroupwfPeer::GRP_STATUS, 'ACTIVE' ); + $oCriteria->addJoin( GroupUserPeer::GRP_UID, GroupwfPeer::GRP_UID, Criteria::LEFT_JOIN ); + $oDataset = GroupwfPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aGroups[] = $aRow['GRP_UID']; + $oDataset->next(); + } + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( TaskUserPeer::USR_UID, $aGroups, Criteria::IN ); + $oCriteria->add( TaskUserPeer::TU_RELATION, 2 ); + $oDataset = TaskUserPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + if (! in_array( $aRow['TAS_UID'], $aTasks )) { + $aTasks[] = $aRow['TAS_UID']; + } + $oDataset->next(); + } + return $aTasks; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Get Routes for any Process and any Task + * + * @param string $sProUid, $sTaskUid + * @return array by Everth + */ + public function getRoute ($sProUid, $sTaskUid) + { + try { + $aRoutes = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( RoutePeer::PRO_UID, $sProUid ); + $oCriteria->add( RoutePeer::TAS_UID, $sTaskUid ); + $oDataset = RoutePeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aRoutes[] = $aRow; + $oDataset->next(); + } + + return $aRoutes; + } catch (Exception $oError) { + throw ($oError); + } + } + + /** + * Get Routes for any Process,route type,route next task + * + * @param string $sProUid, $sTaskUid + * @return array by Girish + */ + public function getRouteByType ($sProUid, $sRouteNextTaskUid, $sRouteType) + { + try { + $aRoutes = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( RoutePeer::PRO_UID, $sProUid ); + $oCriteria->add( RoutePeer::ROU_NEXT_TASK, $sRouteNextTaskUid ); + $oCriteria->add( RoutePeer::ROU_TYPE, $sRouteType ); + $oDataset = RoutePeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $aRoutes[] = $aRow; + $oDataset->next(); + } + + return $aRoutes; + } catch (Exception $oError) { + throw ($oError); + } } - } } ?> From eb8a057ac1893d3f99eaa37fb039ac6131e013a4 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:25:46 -0400 Subject: [PATCH 11/18] CODE STYLE class.toolBar.php --- workflow/engine/classes/class.toolBar.php | 238 +++++++++++----------- 1 file changed, 116 insertions(+), 122 deletions(-) diff --git a/workflow/engine/classes/class.toolBar.php b/workflow/engine/classes/class.toolBar.php index 22628101a..46336aed4 100755 --- a/workflow/engine/classes/class.toolBar.php +++ b/workflow/engine/classes/class.toolBar.php @@ -1,6 +1,8 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. * */ - + /** * ToolBar - ToolBar class + * * @package workflow.engine.ProcessMaker */ -class ToolBar extends form +class ToolBar extends form { - var $type = 'toolbar'; - var $align = 'left'; + var $type = 'toolbar'; + var $align = 'left'; } - - /** + +/** * XmlForm_Field_ToolBar - XmlForm_Field_ToolBar class + * * @package workflow.engine.ProcessMaker */ -class XmlForm_Field_ToolBar extends XmlForm_Field +class XmlForm_Field_ToolBar extends XmlForm_Field { - var $xmlfile = ''; - var $type = 'toolbar'; - var $toolBar; - var $home=''; - var $withoutLabel = true; - - /** - * Constructor of the class XmlForm_Field_ToolBar - * @param string $xmlNode - * @param string $lang - * @param string $home - * @param string $owner - * @return void - */ - function XmlForm_Field_ToolBar($xmlNode, $lang='en', $home='', $owner) - { - parent::XmlForm_Field($xmlNode, $lang, $home, $owner); - $this->home = $home; - } - - /** - * Prints the ToolBar - * @param string $value - * @return string - */ - function render( $value ) - { - $this->toolBar = new toolBar( $this->xmlfile , $this->home ); - $template = PATH_CORE . 'templates/' . $this->type . '.html'; - $out = $this->toolBar->render( $template , $scriptCode ) ; - $oHeadPublisher =& headPublisher::getSingleton(); - $oHeadPublisher->addScriptFile( $this->toolBar->scriptURL ); - $oHeadPublisher->addScriptCode( $scriptCode ); - return $out; - } + var $xmlfile = ''; + var $type = 'toolbar'; + var $toolBar; + var $home = ''; + var $withoutLabel = true; + + /** + * Constructor of the class XmlForm_Field_ToolBar + * + * @param string $xmlNode + * @param string $lang + * @param string $home + * @param string $owner + * @return void + */ + function XmlForm_Field_ToolBar ($xmlNode, $lang = 'en', $home = '', $owner) + { + parent::XmlForm_Field( $xmlNode, $lang, $home, $owner ); + $this->home = $home; + } + + /** + * Prints the ToolBar + * + * @param string $value + * @return string + */ + function render ($value) + { + $this->toolBar = new toolBar( $this->xmlfile, $this->home ); + $template = PATH_CORE . 'templates/' . $this->type . '.html'; + $out = $this->toolBar->render( $template, $scriptCode ); + $oHeadPublisher = & headPublisher::getSingleton(); + $oHeadPublisher->addScriptFile( $this->toolBar->scriptURL ); + $oHeadPublisher->addScriptCode( $scriptCode ); + return $out; + } } /** * XmlForm_Field_toolButton - XmlForm_Field_toolButton class + * * @package workflow.engine.ProcessMaker */ class XmlForm_Field_toolButton extends XmlForm_Field { - var $file = ''; - var $fileAlt = ''; - var $url = ''; - var $urlAlt = ''; - var $home = 'public_html'; - /* types of buttons: + var $file = ''; + var $fileAlt = ''; + var $url = ''; + var $urlAlt = ''; + var $home = 'public_html'; + /* types of buttons: * image * text * image/text * text/image */ - var $buttonType = 'image'; - var $withoutLabel = false; - var $buttonStyle = ''; + var $buttonType = 'image'; + var $withoutLabel = false; + var $buttonStyle = ''; /*$hoverMethod : back | switch*/ - var $hoverMethod='back'; - var $class; - - /** - * Prints the components of the toolBar - * @param string $value - * @return string - */ - function render( $value ) - { - $url = $this->file; - if ($this->home === "methods") - $url = G::encryptlink( SYS_URI . $url ); - if ($this->home === "public_html") - $url ='/' . $url ; - $urlAlt = $this->fileAlt; - if ($this->fileAlt!=='') { - if ($this->home === "methods") - $urlAlt = G::encryptlink( SYS_URI . $urlAlt ); - if ($this->home === "public_html") - $urlAlt ='/' . $urlAlt ; - } - $this->url=$url; - $this->urlAlt=$urlAlt; - switch($this->buttonType){ - case 'image': - $html=''; - if ($this->hoverMethod==='back') { - $html='style)?' style="'.$this->style.'"':'').' onmouseover=\'backImage(this,"url('.htmlentities( $urlAlt, ENT_QUOTES, 'utf-8').') no-repeat")\' onmouseout=\'backImage(this,"")\' title=\'' . addslashes($this->label) . '\' />'; - } - elseif($this->hoverMethod==='switch'){ - $html='style)?' style="'.$this->style.'"':'').' onmouseover=\'switchImage(this,"'.htmlentities( $url, ENT_QUOTES, 'utf-8').'","'.htmlentities( $urlAlt, ENT_QUOTES, 'utf-8').'")\' onmouseout=\'switchImage(this,"'.htmlentities( $url, ENT_QUOTES, 'utf-8').'","'.htmlentities( $urlAlt, ENT_QUOTES, 'utf-8').'")\'/>'; - } - else { - $html='style)?' style="'.$this->style.'"':'').'/>'; + var $hoverMethod = 'back'; + var $class; + + /** + * Prints the components of the toolBar + * + * @param string $value + * @return string + */ + function render ($value) + { + $url = $this->file; + if ($this->home === "methods") + $url = G::encryptlink( SYS_URI . $url ); + if ($this->home === "public_html") + $url = '/' . $url; + $urlAlt = $this->fileAlt; + if ($this->fileAlt !== '') { + if ($this->home === "methods") + $urlAlt = G::encryptlink( SYS_URI . $urlAlt ); + if ($this->home === "public_html") + $urlAlt = '/' . $urlAlt; } - break; - case 'text': - $html=$this->htmlentities($this->label, ENT_QUOTES,'utf-8'); - break; - case 'html': - $html='
'. - $this->label.'
'; - - //$html=$this->label; - break; - case 'image/text': - $html='style)?' style="'.$this->style.'"':'').'/>
'. - $this->htmlentities($this->label, ENT_QUOTES,'utf-8'); - break; - case 'text/image': - $html=$this->htmlentities($this->label, ENT_QUOTES,'utf-8'). - '
style)?' style="'.$this->style.'"':'').'/>'; - break; - case 'class': - $html=' -
+ $this->url = $url; + $this->urlAlt = $urlAlt; + switch ($this->buttonType) { + case 'image': + $html = ''; + if ($this->hoverMethod === 'back') { + $html = 'style) ? ' style="' . $this->style . '"' : '') . ' onmouseover=\'backImage(this,"url(' . htmlentities( $urlAlt, ENT_QUOTES, 'utf-8' ) . ') no-repeat")\' onmouseout=\'backImage(this,"")\' title=\'' . addslashes( $this->label ) . '\' />'; + } elseif ($this->hoverMethod === 'switch') { + $html = 'style) ? ' style="' . $this->style . '"' : '') . ' onmouseover=\'switchImage(this,"' . htmlentities( $url, ENT_QUOTES, 'utf-8' ) . '","' . htmlentities( $urlAlt, ENT_QUOTES, 'utf-8' ) . '")\' onmouseout=\'switchImage(this,"' . htmlentities( $url, ENT_QUOTES, 'utf-8' ) . '","' . htmlentities( $urlAlt, ENT_QUOTES, 'utf-8' ) . '")\'/>'; + } else { + $html = 'style) ? ' style="' . $this->style . '"' : '') . '/>'; + } + break; + case 'text': + $html = $this->htmlentities( $this->label, ENT_QUOTES, 'utf-8' ); + break; + case 'html': + $html = '
' . $this->label . '
'; + + //$html=$this->label; + break; + case 'image/text': + $html = 'style) ? ' style="' . $this->style . '"' : '') . '/>
' . $this->htmlentities( $this->label, ENT_QUOTES, 'utf-8' ); + break; + case 'text/image': + $html = $this->htmlentities( $this->label, ENT_QUOTES, 'utf-8' ) . '
style) ? ' style="' . $this->style . '"' : '') . '/>'; + break; + case 'class': + $html = '
+
'; - return $html; - + return $html; + + } + return 'buttonStyle) ? ' style="' . $this->buttonStyle . '"' : '') . (($this->onclick) ? ' onclick="' . htmlentities( $this->onclick, ENT_QUOTES, 'utf-8' ) . '"' : '') . '>' . $html . ''; } - return 'buttonStyle)?' style="'.$this->buttonStyle.'"':''). - (($this->onclick)?' onclick="'. htmlentities($this->onclick, ENT_QUOTES,'utf-8').'"':''). - '>'.$html.''; - } } ?> From 4d36a97f1d131e3589156109ad61aa8ac07f0586 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:26:07 -0400 Subject: [PATCH 12/18] CODE STYLE class.triggerLibrary.php --- .../engine/classes/class.triggerLibrary.php | 280 +++++++++--------- 1 file changed, 142 insertions(+), 138 deletions(-) diff --git a/workflow/engine/classes/class.triggerLibrary.php b/workflow/engine/classes/class.triggerLibrary.php index 6da1845c4..91173e38f 100755 --- a/workflow/engine/classes/class.triggerLibrary.php +++ b/workflow/engine/classes/class.triggerLibrary.php @@ -1,165 +1,169 @@ * - * This class Helps registering and implementing Wizard for Triggers + * This class Helps registering and implementing Wizard for Triggers */ -G::LoadThirdParty ( 'html2ps_pdf/classes', 'include' ); -G::LoadThirdParty ( 'html2ps_pdf/classes/org/active-link/doc', 'PHPClass' ); +G::LoadThirdParty( 'html2ps_pdf/classes', 'include' ); +G::LoadThirdParty( 'html2ps_pdf/classes/org/active-link/doc', 'PHPClass' ); - /** - * @package workflow.engine.ProcessMaker - */ +/** + * + * @package workflow.engine.ProcessMaker + */ -class triggerLibrary { +class triggerLibrary +{ - private $_aTriggerClasses_ = array (); + private $_aTriggerClasses_ = array (); - private static $instance = NULL; + private static $instance = NULL; - /** - * __construct - * - * @return void - */ - function __construct() - { - //Initialize the Library and register the Default - $this->registerFunctionsFileToLibrary ( PATH_CORE . "classes" . PATH_SEP . "class.pmFunctions.php", "ProcessMaker Functions" ); + /** + * __construct + * + * @return void + */ + function __construct () + { + //Initialize the Library and register the Default + $this->registerFunctionsFileToLibrary( PATH_CORE . "classes" . PATH_SEP . "class.pmFunctions.php", "ProcessMaker Functions" ); + + //Register all registered PLugin Functions + if (class_exists( 'folderData' )) { + //$folderData = new folderData($sProUid, $proFields['PRO_TITLE'], $sAppUid, $Fields['APP_TITLE'], $sUsrUid); + $oPluginRegistry = &PMPluginRegistry::getSingleton(); + $aAvailablePmFunctions = $oPluginRegistry->getPmFunctions(); + foreach ($aAvailablePmFunctions as $key => $class) { + $filePlugin = PATH_PLUGINS . $class . PATH_SEP . 'classes' . PATH_SEP . 'class.pmFunctions.php'; + + if (file_exists( $filePlugin ) && ! is_dir( $filePlugin )) { + $this->registerFunctionsFileToLibrary( $filePlugin, "ProcessMaker Functions" ); + } + } - //Register all registered PLugin Functions - if (class_exists ( 'folderData' )) { - //$folderData = new folderData($sProUid, $proFields['PRO_TITLE'], $sAppUid, $Fields['APP_TITLE'], $sUsrUid); - $oPluginRegistry = &PMPluginRegistry::getSingleton (); - $aAvailablePmFunctions = $oPluginRegistry->getPmFunctions (); - foreach ( $aAvailablePmFunctions as $key => $class ) { - $filePlugin = PATH_PLUGINS . $class . PATH_SEP . 'classes' . PATH_SEP . 'class.pmFunctions.php'; - - if ( file_exists($filePlugin) && !is_dir($filePlugin)) { - $this->registerFunctionsFileToLibrary ( $filePlugin, "ProcessMaker Functions" ); } - } + //Add External Triggers + $dir = G::ExpandPath( "classes" ) . 'triggers'; + $filesArray = array (); - } - //Add External Triggers - $dir = G::ExpandPath( "classes" ).'triggers'; - $filesArray = array(); - - if (file_exists($dir)){ - if ($handle = opendir($dir)) { - while (false !== ($file = readdir($handle))) { - if( $file != "." && $file != ".." && !is_dir($dir . PATH_SEP . $file)){ - $this->registerFunctionsFileToLibrary( $dir . PATH_SEP . $file, "ProcessMaker External Functions"); - } + if (file_exists( $dir )) { + if ($handle = opendir( $dir )) { + while (false !== ($file = readdir( $handle ))) { + if ($file != "." && $file != ".." && ! is_dir( $dir . PATH_SEP . $file )) { + $this->registerFunctionsFileToLibrary( $dir . PATH_SEP . $file, "ProcessMaker External Functions" ); + } + } + closedir( $handle ); + } } - closedir($handle); - } - } - } - - /** - * &getSingleton - * - * @return self::$instance; - */ - function &getSingleton() - { - if (self::$instance == NULL) { - self::$instance = new triggerLibrary ( ); - } - return self::$instance; - } - - /** - * serializeInstance - * - * @return serialize ( self::$instance ); - */ - function serializeInstance() - { - return serialize ( self::$instance ); - } - - /** - * unSerializeInstance - * - * @param integer $serialized - * @return void - */ - function unSerializeInstance($serialized) - { - if (self::$instance == NULL) { - self::$instance = new PMPluginRegistry ( ); } - $instance = unserialize ( $serialized ); - self::$instance = $instance; - } - - /** - * registerFunctionsFileToLibrary - * - * @param string $filePath - * @param string $libraryName - * @return void - */ - function registerFunctionsFileToLibrary($filePath, $libraryName) - { - $aLibrary = $this->getMethodsFromLibraryFile ( $filePath ); - $aLibrary->libraryFile = $filePath; - $aLibrary->libraryName = $libraryName; - if(isset($aLibrary->info['className'])){ - $this->_aTriggerClasses_ [$aLibrary->info['className']] = $aLibrary; + /** + * &getSingleton + * + * @return self::$instance; + */ + function &getSingleton () + { + if (self::$instance == NULL) { + self::$instance = new triggerLibrary(); + } + return self::$instance; } - } + /** + * serializeInstance + * + * @return serialize ( self::$instance ); + */ + function serializeInstance () + { + return serialize( self::$instance ); + } - /** - * getMethodsFromLibraryFile - * - * @param string $file - * @return object(PHPClass) $parsedLibrary - */ - function getMethodsFromLibraryFile($file) - { - // parse class comments from file - $parsedLibrary = new PHPClass ( ); - //$success = $parsedLibrary->parseFromFile ( PATH_CORE . "classes" . PATH_SEP . $file ); - $success = $parsedLibrary->parseFromFile ( $file ); + /** + * unSerializeInstance + * + * @param integer $serialized + * @return void + */ + function unSerializeInstance ($serialized) + { + if (self::$instance == NULL) { + self::$instance = new PMPluginRegistry(); + } - return $parsedLibrary; - } + $instance = unserialize( $serialized ); + self::$instance = $instance; + } - /** - * getRegisteredClasses - * - * @return array ($this->_aTriggerClasses_) - */ - function getRegisteredClasses() - { - return ($this->_aTriggerClasses_); - } + /** + * registerFunctionsFileToLibrary + * + * @param string $filePath + * @param string $libraryName + * @return void + */ + function registerFunctionsFileToLibrary ($filePath, $libraryName) + { + $aLibrary = $this->getMethodsFromLibraryFile( $filePath ); + $aLibrary->libraryFile = $filePath; + $aLibrary->libraryName = $libraryName; + if (isset( $aLibrary->info['className'] )) { + $this->_aTriggerClasses_[$aLibrary->info['className']] = $aLibrary; + } - /** - * getLibraryDefinition - * - * @param string $libraryClassName - * @return array ($this->_aTriggerClasses_[$libraryClassName]) - */ - function getLibraryDefinition($libraryClassName) - { - return ($this->_aTriggerClasses_[$libraryClassName]); - } + } - /** - * __destruct - * - * @return void - */ function __destruct() - { + /** + * getMethodsFromLibraryFile + * + * @param string $file + * @return object(PHPClass) $parsedLibrary + */ + function getMethodsFromLibraryFile ($file) + { + // parse class comments from file + $parsedLibrary = new PHPClass(); + //$success = $parsedLibrary->parseFromFile ( PATH_CORE . "classes" . PATH_SEP . $file ); + $success = $parsedLibrary->parseFromFile( $file ); - //TODO - Insert your code here - } + return $parsedLibrary; + } + + /** + * getRegisteredClasses + * + * @return array ($this->_aTriggerClasses_) + */ + function getRegisteredClasses () + { + return ($this->_aTriggerClasses_); + } + + /** + * getLibraryDefinition + * + * @param string $libraryClassName + * @return array ($this->_aTriggerClasses_[$libraryClassName]) + */ + function getLibraryDefinition ($libraryClassName) + { + return ($this->_aTriggerClasses_[$libraryClassName]); + } + + /** + * __destruct + * + * @return void + */ + function __destruct () + { + + //TODO - Insert your code here + } } ?> \ No newline at end of file From 1a19f161c67f633fe1897ce07a9681f5e646bfc5 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:26:29 -0400 Subject: [PATCH 13/18] CODE STYLE class.webdav.php --- workflow/engine/classes/class.webdav.php | 1860 +++++++++++----------- 1 file changed, 937 insertions(+), 923 deletions(-) diff --git a/workflow/engine/classes/class.webdav.php b/workflow/engine/classes/class.webdav.php index 9f6c496ed..1564bed9a 100755 --- a/workflow/engine/classes/class.webdav.php +++ b/workflow/engine/classes/class.webdav.php @@ -1,252 +1,271 @@ base = '/'; - $this->uriBase = '/sys' . SYS_SYS . '/' . SYS_LANG . '/' . SYS_SKIN . '/services/webdav/'; - - // let the base class do all the work - parent::ServeRequest(); - } + /** + * Serve a webdav request + * + * @access public + * @param string + */ + function ServeRequest ($base = false) + { + //$this->base = '/'; + $this->uriBase = '/sys' . SYS_SYS . '/' . SYS_LANG . '/' . SYS_SKIN . '/services/webdav/'; - /** - * No authentication is needed here - * - * @access private - * @param string HTTP Authentication type (Basic, Digest, ...) - * @param string Username - * @param string Password - * @return bool true on successful authentication - */ - function check_auth($type, $user, $pass) - { - return true; - } - - /** - * PROPFIND method handler - * - * @param array general parameter passing array - * @param array return array for file properties - * @return bool true on success - */ - function PROPFIND(&$options, &$files) - { - $paths = $this->paths; - // prepare property array - $files["files"] = array(); - - $pathClasses = PATH_DB . PATH_SEP . SYS_SYS . PATH_SEP . 'classes' . PATH_SEP; - if ( count($paths) == 0 && is_dir( $pathClasses ) ) { - $props = array (); - $props[] = $this->mkprop("displayname", 'Classes' ); - $props[] = $this->mkprop("creationdate", filectime($pathClasses) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathClasses) ); - $props[] = $this->mkprop("lastaccessed", filemtime($pathClasses) ); - $props[] = $this->mkprop("resourcetype", 'collection' ); - $props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' ); - $files["files"][] = array ( 'path' => 'classes' , 'props' => $props); + // let the base class do all the work + parent::ServeRequest(); } - if ( count($paths) > 0 && $paths[0] == 'classes' && is_dir( $pathClasses ) ) { - // try to open directory - $handle = @opendir($pathClasses); - if ($handle) { - while ($filename = readdir($handle)) { - $ext = array_pop ( explode ( '.', $filename) ); - if ($filename != "." && $filename != ".." && !is_dir($pathClasses.$filename) && $ext == 'php' ) { - $props = array (); - $props[] = $this->mkprop("displayname", $filename ); - $props[] = $this->mkprop("creationdate", filectime($pathClasses.$filename) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathClasses.$filename) ); - $props[] = $this->mkprop("getetag", fileatime($pathClasses.$filename) ); - $props[] = $this->mkprop("lastaccessed", filemtime($pathClasses.$filename) ); - $props[] = $this->mkprop("resourcetype", '' ); - $props[] = $this->mkprop("getcontenttype", 'text/plain' ); - $props[] = $this->mkprop("getcontentlength", filesize($pathClasses.$filename) ); - if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) ) - $files["files"][] = array ( 'path' => "classes/$filename" , 'props' => $props); - } - } - } - - }//path classes - - $pathProcesses = PATH_DB . SYS_SYS . PATH_SEP ; - if ( count($paths) == 0 && is_dir( $pathProcesses ) ) { - $props = array (); - $props[] = $this->mkprop("displayname", 'Processes' ); - $props[] = $this->mkprop("creationdate", filectime($pathProcesses) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathProcesses) ); - $props[] = $this->mkprop("resourcetype", 'collection' ); - $props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' ); - $files["files"][] = array ( 'path' => 'processes' , 'props' => $props); + /** + * No authentication is needed here + * + * @access private + * @param string HTTP Authentication type (Basic, Digest, ...) + * @param string Username + * @param string Password + * @return bool true on successful authentication + */ + function check_auth ($type, $user, $pass) + { + return true; } - - //list all active processes - if ( count($paths) == 1 && $paths[0] == 'processes' && is_dir( $pathProcesses ) ) { - // try to get the process directory list - G::LoadClass ( 'processMap'); - G::LoadClass ( 'model/Process'); - $oProcessMap = new processMap(); - $oProcess = new Process(); - $c = $oProcessMap->getConditionProcessList(); - $oDataset = ProcessPeer::doSelectRS($c); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - if ($aRow['PRO_STATUS'] == 'ACTIVE' ) { - $aProcess = $oProcess->load($aRow['PRO_UID']); - $props = array (); - $props[] = $this->mkprop("displayname", $aProcess['PRO_TITLE'] ); - $props[] = $this->mkprop("creationdate", filectime($pathProcesses) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathProcesses) ); - $props[] = $this->mkprop("lastaccessed", filemtime($pathProcesses) ); - $props[] = $this->mkprop("resourcetype", 'collection' ); - $props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' ); - $files["files"][] = array ( 'path' => "processes/". $aRow['PRO_UID'] , 'props' => $props); + + /** + * PROPFIND method handler + * + * @param array general parameter passing array + * @param array return array for file properties + * @return bool true on success + */ + function PROPFIND (&$options, &$files) + { + $paths = $this->paths; + // prepare property array + $files["files"] = array (); + + $pathClasses = PATH_DB . PATH_SEP . SYS_SYS . PATH_SEP . 'classes' . PATH_SEP; + if (count( $paths ) == 0 && is_dir( $pathClasses )) { + $props = array (); + $props[] = $this->mkprop( "displayname", 'Classes' ); + $props[] = $this->mkprop( "creationdate", filectime( $pathClasses ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathClasses ) ); + $props[] = $this->mkprop( "lastaccessed", filemtime( $pathClasses ) ); + $props[] = $this->mkprop( "resourcetype", 'collection' ); + $props[] = $this->mkprop( "getcontenttype", 'httpd/unix-directory' ); + $files["files"][] = array ('path' => 'classes','props' => $props + ); } - $oDataset->next(); - } - }//dir of processes - //content of any process ( the three major folders of Processes ) - $pathXmlform = $pathProcesses . 'xmlForms' . PATH_SEP; - if ( count($paths) == 2 && $paths[0] == 'processes' && is_dir( $pathProcesses ) ) { - $props = array (); - $props[] = $this->mkprop("displayname", 'xmlforms' ); - $props[] = $this->mkprop("creationdate", filectime($pathXmlform) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathXmlform) ); - $props[] = $this->mkprop("lastaccessed", filemtime($pathXmlform) ); - $props[] = $this->mkprop("resourcetype", 'collection' ); - $props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' ); - $files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/xmlforms' , 'props' => $props); + if (count( $paths ) > 0 && $paths[0] == 'classes' && is_dir( $pathClasses )) { + // try to open directory + $handle = @opendir( $pathClasses ); + if ($handle) { + while ($filename = readdir( $handle )) { + $ext = array_pop( explode( '.', $filename ) ); + if ($filename != "." && $filename != ".." && ! is_dir( $pathClasses . $filename ) && $ext == 'php') { + $props = array (); + $props[] = $this->mkprop( "displayname", $filename ); + $props[] = $this->mkprop( "creationdate", filectime( $pathClasses . $filename ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathClasses . $filename ) ); + $props[] = $this->mkprop( "getetag", fileatime( $pathClasses . $filename ) ); + $props[] = $this->mkprop( "lastaccessed", filemtime( $pathClasses . $filename ) ); + $props[] = $this->mkprop( "resourcetype", '' ); + $props[] = $this->mkprop( "getcontenttype", 'text/plain' ); + $props[] = $this->mkprop( "getcontentlength", filesize( $pathClasses . $filename ) ); + if (count( $paths ) == 1 || (count( $paths ) == 2 && $paths[1] == $filename)) + $files["files"][] = array ('path' => "classes/$filename",'props' => $props + ); + } + } + } - $props[] = $this->mkprop("displayname", 'mailTemplates' ); - $props[] = $this->mkprop("creationdate", filectime($pathProcesses) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathProcesses) ); - $props[] = $this->mkprop("lastaccessed", filemtime($pathProcesses) ); - $props[] = $this->mkprop("resourcetype", 'collection' ); - $props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' ); - $files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/mailTemplates' , 'props' => $props); + } //path classes - $props[] = $this->mkprop("displayname", 'public_html' ); - $props[] = $this->mkprop("creationdate", filectime($pathProcesses) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathProcesses) ); - $props[] = $this->mkprop("lastaccessed", filemtime($pathProcesses) ); - $props[] = $this->mkprop("resourcetype", 'collection' ); - $props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' ); - $files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/public_html' , 'props' => $props); - }//content of any processes - //list available xmlforms - if ( count($paths) == 3 && $paths[0] == 'processes' && $paths[2] == 'xmlforms' && is_dir( $pathXmlform ) ) { - $pathXmlform = $pathProcesses . 'xmlForms' . PATH_SEP . $paths[1] . PATH_SEP; - - $handle = @opendir($pathXmlform); - if ($handle) { - while ($filename = readdir($handle)) { - $ext = array_pop ( explode ( '.', $filename) ); - if ($filename != "." && $filename != ".." && !is_dir($pathXmlform.$filename) && ( $ext == 'xml' || $ext == 'html' ) ) { - $props = array (); - $props[] = $this->mkprop("displayname", $filename ); - $props[] = $this->mkprop("creationdate", filectime($pathXmlform.$filename) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathXmlform.$filename) ); - $props[] = $this->mkprop("getetag", fileatime($pathXmlform.$filename) ); - $props[] = $this->mkprop("lastaccessed", filemtime($pathXmlform.$filename) ); - $props[] = $this->mkprop("resourcetype", '' ); - $props[] = $this->mkprop("getcontenttype", 'text/plain' ); - $props[] = $this->mkprop("getcontentlength", filesize($pathXmlform.$filename) ); - //if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) ) - $files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/xmlforms/' . $filename , 'props' => $props); - } + $pathProcesses = PATH_DB . SYS_SYS . PATH_SEP; + if (count( $paths ) == 0 && is_dir( $pathProcesses )) { + $props = array (); + $props[] = $this->mkprop( "displayname", 'Processes' ); + $props[] = $this->mkprop( "creationdate", filectime( $pathProcesses ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathProcesses ) ); + $props[] = $this->mkprop( "resourcetype", 'collection' ); + $props[] = $this->mkprop( "getcontenttype", 'httpd/unix-directory' ); + $files["files"][] = array ('path' => 'processes','props' => $props + ); } - } - }//content of xmlforms - //list available mailTemplates - $pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP; - if ( count($paths) == 3 && $paths[0] == 'processes' && $paths[2] == 'mailTemplates' && is_dir( $pathTemplates ) ) { - $pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP . $paths[1] . PATH_SEP; - - $handle = @opendir($pathTemplates); - if ($handle) { - while ($filename = readdir($handle)) { - $ext = array_pop ( explode ( '.', $filename) ); - if ($filename != "." && $filename != ".." && !is_dir($pathTemplates.$filename) /* && ( $ext == 'xml' || $ext == 'html' ) */ ) { - $props = array (); - $props[] = $this->mkprop("displayname", $filename ); - $props[] = $this->mkprop("creationdate", filectime($pathTemplates.$filename) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathTemplates.$filename) ); - $props[] = $this->mkprop("getetag", fileatime($pathTemplates.$filename) ); - $props[] = $this->mkprop("lastaccessed", filemtime($pathTemplates.$filename) ); - $props[] = $this->mkprop("resourcetype", '' ); - $props[] = $this->mkprop("getcontenttype", 'text/plain' ); - $props[] = $this->mkprop("getcontentlength", filesize($pathTemplates.$filename) ); - //if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) ) - $files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/mailTemplates/' . $filename , 'props' => $props); - } - } - } - }//content of mailTemplates + //list all active processes + if (count( $paths ) == 1 && $paths[0] == 'processes' && is_dir( $pathProcesses )) { + // try to get the process directory list + G::LoadClass( 'processMap' ); + G::LoadClass( 'model/Process' ); + $oProcessMap = new processMap(); + $oProcess = new Process(); + $c = $oProcessMap->getConditionProcessList(); + $oDataset = ProcessPeer::doSelectRS( $c ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + if ($aRow['PRO_STATUS'] == 'ACTIVE') { + $aProcess = $oProcess->load( $aRow['PRO_UID'] ); + $props = array (); + $props[] = $this->mkprop( "displayname", $aProcess['PRO_TITLE'] ); + $props[] = $this->mkprop( "creationdate", filectime( $pathProcesses ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathProcesses ) ); + $props[] = $this->mkprop( "lastaccessed", filemtime( $pathProcesses ) ); + $props[] = $this->mkprop( "resourcetype", 'collection' ); + $props[] = $this->mkprop( "getcontenttype", 'httpd/unix-directory' ); + $files["files"][] = array ('path' => "processes/" . $aRow['PRO_UID'],'props' => $props + ); + } + $oDataset->next(); + } + } //dir of processes - //list available public_html files - $pathPublic = $pathProcesses . 'public' . PATH_SEP; - if ( count($paths) == 3 && $paths[0] == 'processes' && $paths[2] == 'public_html' && is_dir( $pathTemplates ) ) { - $pathPublic = $pathProcesses . 'public' . PATH_SEP . $paths[1] . PATH_SEP; - - $handle = @opendir($pathPublic); - if ($handle) { - while ($filename = readdir($handle)) { - $ext = array_pop ( explode ( '.', $filename) ); - if ($filename != "." && $filename != ".." && !is_dir($pathPublic.$filename) /* && ( $ext == 'xml' || $ext == 'html' ) */ ) { - $props = array (); - $props[] = $this->mkprop("displayname", $filename ); - $props[] = $this->mkprop("creationdate", filectime($pathPublic.$filename) ); - $props[] = $this->mkprop("getlastmodified", filemtime($pathPublic.$filename) ); - $props[] = $this->mkprop("getetag", fileatime($pathPublic.$filename) ); - $props[] = $this->mkprop("lastaccessed", filemtime($pathPublic.$filename) ); - $props[] = $this->mkprop("resourcetype", '' ); - $props[] = $this->mkprop("getcontenttype", 'text/plain' ); - $props[] = $this->mkprop("getcontentlength", filesize($pathPublic.$filename) ); - //if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) ) - $files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/public_html/' . $filename , 'props' => $props); - } - } - } - }//content of public_html files - /* + //content of any process ( the three major folders of Processes ) + $pathXmlform = $pathProcesses . 'xmlForms' . PATH_SEP; + if (count( $paths ) == 2 && $paths[0] == 'processes' && is_dir( $pathProcesses )) { + $props = array (); + $props[] = $this->mkprop( "displayname", 'xmlforms' ); + $props[] = $this->mkprop( "creationdate", filectime( $pathXmlform ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathXmlform ) ); + $props[] = $this->mkprop( "lastaccessed", filemtime( $pathXmlform ) ); + $props[] = $this->mkprop( "resourcetype", 'collection' ); + $props[] = $this->mkprop( "getcontenttype", 'httpd/unix-directory' ); + $files["files"][] = array ('path' => 'processes/' . $paths[1] . '/xmlforms','props' => $props + ); + + $props[] = $this->mkprop( "displayname", 'mailTemplates' ); + $props[] = $this->mkprop( "creationdate", filectime( $pathProcesses ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathProcesses ) ); + $props[] = $this->mkprop( "lastaccessed", filemtime( $pathProcesses ) ); + $props[] = $this->mkprop( "resourcetype", 'collection' ); + $props[] = $this->mkprop( "getcontenttype", 'httpd/unix-directory' ); + $files["files"][] = array ('path' => 'processes/' . $paths[1] . '/mailTemplates','props' => $props + ); + + $props[] = $this->mkprop( "displayname", 'public_html' ); + $props[] = $this->mkprop( "creationdate", filectime( $pathProcesses ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathProcesses ) ); + $props[] = $this->mkprop( "lastaccessed", filemtime( $pathProcesses ) ); + $props[] = $this->mkprop( "resourcetype", 'collection' ); + $props[] = $this->mkprop( "getcontenttype", 'httpd/unix-directory' ); + $files["files"][] = array ('path' => 'processes/' . $paths[1] . '/public_html','props' => $props + ); + } //content of any processes + + + //list available xmlforms + if (count( $paths ) == 3 && $paths[0] == 'processes' && $paths[2] == 'xmlforms' && is_dir( $pathXmlform )) { + $pathXmlform = $pathProcesses . 'xmlForms' . PATH_SEP . $paths[1] . PATH_SEP; + + $handle = @opendir( $pathXmlform ); + if ($handle) { + while ($filename = readdir( $handle )) { + $ext = array_pop( explode( '.', $filename ) ); + if ($filename != "." && $filename != ".." && ! is_dir( $pathXmlform . $filename ) && ($ext == 'xml' || $ext == 'html')) { + $props = array (); + $props[] = $this->mkprop( "displayname", $filename ); + $props[] = $this->mkprop( "creationdate", filectime( $pathXmlform . $filename ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathXmlform . $filename ) ); + $props[] = $this->mkprop( "getetag", fileatime( $pathXmlform . $filename ) ); + $props[] = $this->mkprop( "lastaccessed", filemtime( $pathXmlform . $filename ) ); + $props[] = $this->mkprop( "resourcetype", '' ); + $props[] = $this->mkprop( "getcontenttype", 'text/plain' ); + $props[] = $this->mkprop( "getcontentlength", filesize( $pathXmlform . $filename ) ); + //if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) ) + $files["files"][] = array ('path' => 'processes/' . $paths[1] . '/xmlforms/' . $filename,'props' => $props + ); + } + } + } + } //content of xmlforms + + + //list available mailTemplates + $pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP; + if (count( $paths ) == 3 && $paths[0] == 'processes' && $paths[2] == 'mailTemplates' && is_dir( $pathTemplates )) { + $pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP . $paths[1] . PATH_SEP; + + $handle = @opendir( $pathTemplates ); + if ($handle) { + while ($filename = readdir( $handle )) { + $ext = array_pop( explode( '.', $filename ) ); + if ($filename != "." && $filename != ".." && ! is_dir( $pathTemplates . $filename ) /* && ( $ext == 'xml' || $ext == 'html' ) */ ) { + $props = array (); + $props[] = $this->mkprop( "displayname", $filename ); + $props[] = $this->mkprop( "creationdate", filectime( $pathTemplates . $filename ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathTemplates . $filename ) ); + $props[] = $this->mkprop( "getetag", fileatime( $pathTemplates . $filename ) ); + $props[] = $this->mkprop( "lastaccessed", filemtime( $pathTemplates . $filename ) ); + $props[] = $this->mkprop( "resourcetype", '' ); + $props[] = $this->mkprop( "getcontenttype", 'text/plain' ); + $props[] = $this->mkprop( "getcontentlength", filesize( $pathTemplates . $filename ) ); + //if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) ) + $files["files"][] = array ('path' => 'processes/' . $paths[1] . '/mailTemplates/' . $filename,'props' => $props + ); + } + } + } + } //content of mailTemplates + + + //list available public_html files + $pathPublic = $pathProcesses . 'public' . PATH_SEP; + if (count( $paths ) == 3 && $paths[0] == 'processes' && $paths[2] == 'public_html' && is_dir( $pathTemplates )) { + $pathPublic = $pathProcesses . 'public' . PATH_SEP . $paths[1] . PATH_SEP; + + $handle = @opendir( $pathPublic ); + if ($handle) { + while ($filename = readdir( $handle )) { + $ext = array_pop( explode( '.', $filename ) ); + if ($filename != "." && $filename != ".." && ! is_dir( $pathPublic . $filename ) /* && ( $ext == 'xml' || $ext == 'html' ) */ ) { + $props = array (); + $props[] = $this->mkprop( "displayname", $filename ); + $props[] = $this->mkprop( "creationdate", filectime( $pathPublic . $filename ) ); + $props[] = $this->mkprop( "getlastmodified", filemtime( $pathPublic . $filename ) ); + $props[] = $this->mkprop( "getetag", fileatime( $pathPublic . $filename ) ); + $props[] = $this->mkprop( "lastaccessed", filemtime( $pathPublic . $filename ) ); + $props[] = $this->mkprop( "resourcetype", '' ); + $props[] = $this->mkprop( "getcontenttype", 'text/plain' ); + $props[] = $this->mkprop( "getcontentlength", filesize( $pathPublic . $filename ) ); + //if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) ) + $files["files"][] = array ('path' => 'processes/' . $paths[1] . '/public_html/' . $filename,'props' => $props + ); + } + } + } + } //content of public_html files + + + /* if ( 1 ) { $props = array (); $props[] = $this->mkprop("displayname", print_r ($pathPublic, 1) ); @@ -257,741 +276,736 @@ class ProcessMakerWebDav extends HTTP_WebDAV_Server $files["files"][] = array ( 'path' => '/' , 'props' => $props); } */ - // ok, all done - return true; - } - - /** - * detect if a given program is found in the search PATH - * - * helper function used by _mimetype() to detect if the - * external 'file' utility is available - * - * @param string program name - * @param string optional search path, defaults to $PATH - * @return bool true if executable program found in path - */ - function _can_execute($name, $path = false) - { - // path defaults to PATH from environment if not set - if ($path === false) { - $path = getenv("PATH"); - } - - // check method depends on operating system - if (!strncmp(PHP_OS, "WIN", 3)) { - // on Windows an appropriate COM or EXE file needs to exist - $exts = array(".exe", ".com"); - $check_fn = "file_exists"; - } else { - // anywhere else we look for an executable file of that name - $exts = array(""); - $check_fn = "is_executable"; - } - - // now check the directories in the path for the program - foreach (explode(PATH_SEPARATOR, $path) as $dir) { - // skip invalid path entries - if (!file_exists($dir)) continue; - if (!is_dir($dir)) continue; - - // and now look for the file - foreach ($exts as $ext) { - if ($check_fn("$dir/$name".$ext)) return true; - } - } - - return false; - } - - /** - * try to detect the mime type of a file - * - * @param string file path - * @return string guessed mime type - */ - function _mimetype($fspath) - { - if (@is_dir($fspath)) { - // directories are easy - return "httpd/unix-directory"; - } else if (function_exists("mime_content_type")) { - // use mime magic extension if available - $mime_type = mime_content_type($fspath); - } else if ($this->_can_execute("file")) { - // it looks like we have a 'file' command, - // lets see it it does have mime support - $fp = popen("file -i '$fspath' 2>/dev/null", "r"); - $reply = fgets($fp); - pclose($fp); - - // popen will not return an error if the binary was not found - // and find may not have mime support using "-i" - // so we test the format of the returned string - - // the reply begins with the requested filename - if (!strncmp($reply, "$fspath: ", strlen($fspath)+2)) { - $reply = substr($reply, strlen($fspath)+2); - // followed by the mime type (maybe including options) - if (preg_match('/^[[:alnum:]_-]+/[[:alnum:]_-]+;?.*/', $reply, $matches)) { - $mime_type = $matches[0]; - } - } - } - - if (empty($mime_type)) { - // Fallback solution: try to guess the type by the file extension - // TODO: add more ... - // TODO: it has been suggested to delegate mimetype detection - // to apache but this has at least three issues: - // - works only with apache - // - needs file to be within the document tree - // - requires apache mod_magic - // TODO: can we use the registry for this on Windows? - // OTOH if the server is Windos the clients are likely to - // be Windows, too, and tend do ignore the Content-Type - // anyway (overriding it with information taken from - // the registry) - // TODO: have a seperate PEAR class for mimetype detection? - switch (strtolower(strrchr(basename($fspath), "."))) { - case ".html": - $mime_type = "text/html"; - break; - case ".gif": - $mime_type = "image/gif"; - break; - case ".jpg": - $mime_type = "image/jpeg"; - break; - default: - $mime_type = "application/octet-stream"; - break; - } - } - - return $mime_type; - } - - /** - * GET method handler - * - * @param array parameter passing array - * @return bool true on success - */ - function GET(&$options) { - $paths = $this->paths; - - $pathClasses = PATH_DB . SYS_SYS . PATH_SEP . 'classes' . PATH_SEP; - if ( count($paths) > 0 && $paths[0] == 'classes' && is_dir( $pathClasses ) ) { - $fsFile = $pathClasses. $paths[1]; - if ( count($paths) == 2 && file_exists( $fsFile ) ) { - $content = file_get_contents ($fsFile); - print $content; - header("Content-Type: " . mime_content_type($fsFile ) ); - header("Last-Modified: " . date("D, j M Y H:m:s ", file_mtime($fsFile )) . "GMT"); - header("Content-Length: ". filesize($fsFile)); + // ok, all done return true; - } } - $pathProcesses = PATH_DB . SYS_SYS . PATH_SEP; - if ( count($paths) > 0 && $paths[0] == 'processes' && is_dir( $pathProcesses ) ) { - if ( count($paths) == 4 && $paths[2] == 'xmlforms' ) { - $pathXmlform = $pathProcesses . 'xmlForms' . PATH_SEP . $paths[1] . PATH_SEP; - $fsFile = $pathXmlform. $paths[3]; - if ( count($paths) == 4 && file_exists( $fsFile ) ) { - $content = file_get_contents ($fsFile); - print $content; - header("Content-Type: " . mime_content_type($fsFile ) ); - header("Last-Modified: " . date("D, j M Y H:m:s ", file_mtime($fsFile )) . "GMT"); - header("Content-Length: ". filesize($fsFile)); - return true; + /** + * detect if a given program is found in the search PATH + * + * helper function used by _mimetype() to detect if the + * external 'file' utility is available + * + * @param string program name + * @param string optional search path, defaults to $PATH + * @return bool true if executable program found in path + */ + function _can_execute ($name, $path = false) + { + // path defaults to PATH from environment if not set + if ($path === false) { + $path = getenv( "PATH" ); } - } - - if ( count($paths) == 4 && $paths[2] == 'mailTemplates' ) { - $pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP . $paths[1] . PATH_SEP; - $fsFile = $pathTemplates. $paths[3]; - if ( count($paths) == 4 && file_exists( $fsFile ) ) { - $content = file_get_contents ($fsFile); - print $content; - header("Content-Type: " . mime_content_type($fsFile ) ); - header("Last-Modified: " . date("D, j M Y H:m:s ", file_mtime($fsFile )) . "GMT"); - header("Content-Length: ". filesize($fsFile)); - return true; + + // check method depends on operating system + if (! strncmp( PHP_OS, "WIN", 3 )) { + // on Windows an appropriate COM or EXE file needs to exist + $exts = array (".exe",".com" + ); + $check_fn = "file_exists"; + } else { + // anywhere else we look for an executable file of that name + $exts = array ("" + ); + $check_fn = "is_executable"; } - } - - if ( count($paths) == 4 && $paths[2] == 'public_html' ) { - $pathPublic = $pathProcesses . 'public' . PATH_SEP . $paths[1] . PATH_SEP; - $fsFile = $pathPublic. $paths[3]; - if ( count($paths) == 4 && file_exists( $fsFile ) ) { - $content = file_get_contents ($fsFile); - print $content; - header("Content-Type: " . mime_content_type($fsFile ) ); - header("Last-Modified: " . date("D, j M Y H:m:s ", file_mtime($fsFile )) . "GMT"); - header("Content-Length: ". filesize($fsFile)); - return true; + + // now check the directories in the path for the program + foreach (explode( PATH_SEPARATOR, $path ) as $dir) { + // skip invalid path entries + if (! file_exists( $dir )) + continue; + if (! is_dir( $dir )) + continue; + + // and now look for the file + foreach ($exts as $ext) { + if ($check_fn( "$dir/$name" . $ext )) + return true; + } } - } - } - - print_r ( $paths ); - return true; - - if ( $options["path"] == '/' ) { - return $this->getRoot( $options ); - } - //print_r ($options); - - - // get absolute fs path to requested resource - $fspath = $this->base . $options["path"]; - - // sanity check - if (!file_exists($fspath)) return false; - - // is this a collection? - if (is_dir($fspath)) { - return $this->GetDir($fspath, $options); - } - - // detect resource type - $options['mimetype'] = $this->_mimetype($fspath); - - // detect modification time - // see rfc2518, section 13.7 - // some clients seem to treat this as a reverse rule - // requiering a Last-Modified header if the getlastmodified header was set - $options['mtime'] = filemtime($fspath); - - // detect resource size - $options['size'] = filesize($fspath); - - // no need to check result here, it is handled by the base class - $options['stream'] = fopen($fspath, "r"); - - return true; - } - - /** - * getRoot - * - * @param string &$options - * @return boolean false - */ - function getRoot (&$options) - { - $path = $this->_slashify($options["path"]); - // fixed width directory column format - $format = "%15s %-19s %-s\n"; - - echo "Index of " . htmlspecialchars($options['path']) . "\n"; - echo "

Index of " . htmlspecialchars($options['path']) . "

\n"; - - echo "
";
-    printf($format, "Size", "Last modified", "Filename");
-    echo "
"; - - $pathRoot = array ( 'xmlforms', 'public_html', 'dir1', 'dir2' ); - - foreach ( $pathRoot as $key => $val ) { - $fullpath = $fspath."/".$filename; - $name = htmlspecialchars($val); - printf($format, number_format(filesize($fullpath)), - strftime("%Y-%m-%d %H:%M:%S", filemtime($fullpath)), - "$name"); - } - - echo "
"; - echo "\n"; - - die; - - $handle = @opendir($fspath); - if (!$handle) { - return false; - } - - - while ($filename = readdir($handle)) { - if ($filename != "." && $filename != "..") { - $fullpath = $fspath."/".$filename; - $name = htmlspecialchars($filename); - printf($format, - number_format(filesize($fullpath)), - strftime("%Y-%m-%d %H:%M:%S", filemtime($fullpath)), - "$name"); - } - } - - echo "
"; - - closedir($handle); - - echo "\n"; - - exit; - } - - /** - * GET method handler for directories - * - * This is a very simple mod_index lookalike. - * See RFC 2518, Section 8.4 on GET/HEAD for collections - * - * @param string directory path - * @return void function has to handle HTTP response itself - */ - function GetDir($fspath, &$options) - { - $path = $this->_slashify($options["path"]); - if ($path != $options["path"]) { - header("Location: ".$this->base_uri.$path); - exit; - } - - // fixed width directory column format - $format = "%15s %-19s %-s\n"; - - $handle = @opendir($fspath); - if (!$handle) { return false; } - echo "Index of ".htmlspecialchars($options['path'])."\n"; - - echo "

Index of ".htmlspecialchars($options['path'])."

\n"; - - echo "
";
-    printf($format, "Size", "Last modified", "Filename");
-    echo "
"; + /** + * try to detect the mime type of a file + * + * @param string file path + * @return string guessed mime type + */ + function _mimetype ($fspath) + { + if (@is_dir( $fspath )) { + // directories are easy + return "httpd/unix-directory"; + } else if (function_exists( "mime_content_type" )) { + // use mime magic extension if available + $mime_type = mime_content_type( $fspath ); + } else if ($this->_can_execute( "file" )) { + // it looks like we have a 'file' command, + // lets see it it does have mime support + $fp = popen( "file -i '$fspath' 2>/dev/null", "r" ); + $reply = fgets( $fp ); + pclose( $fp ); - while ($filename = readdir($handle)) { - if ($filename != "." && $filename != "..") { - $fullpath = $fspath."/".$filename; - $name = htmlspecialchars($filename); - printf($format, - number_format(filesize($fullpath)), - strftime("%Y-%m-%d %H:%M:%S", filemtime($fullpath)), - "$name"); - } - } - - echo "
"; - - closedir($handle); - - echo "\n"; - - exit; - } - - /** - * PUT method handler - * - * @param array parameter passing array - * @return bool true on success - */ - function PUT(&$options) - { - $paths = $this->paths; - - $pathClasses = PATH_DB . PATH_SEP . 'classes' . PATH_SEP; - if ( count($paths) > 0 && $paths[0] == 'classes' && is_dir( $pathClasses ) ) { - $fsFile = $pathClasses. $paths[1]; - if ( count($paths) == 2 && file_exists( $fsFile ) ) { - $fp = fopen($fsFile, "w"); - if ( is_resource($fp) && is_resource($options["stream"])) { - while( !feof($options["stream"])) { - fwrite($fp, fread($options["stream"], 4096)); - } - fclose($fp); - fclose($options["stream"]); - } - return "201 Created " . $fsFile; - } - } - - $pathProcesses = PATH_DB . SYS_SYS . PATH_SEP ; - if ( count($paths) > 0 && $paths[0] == 'processes' && is_dir( $pathProcesses ) ) { - if ( $paths[2] == 'xmlforms' ) { - $pathTemplates = $pathProcesses . 'xmlForms' . PATH_SEP . $paths[1] . PATH_SEP; - $fsFile = $pathTemplates. $paths[3]; - if ( count($paths) == 4 && file_exists( $fsFile ) ) { - $fp = fopen($fsFile, "w"); - if ( is_resource($fp) && is_resource($options["stream"])) { - while( !feof($options["stream"])) { - fwrite($fp, fread($options["stream"], 4096)); - } - fclose($fp); - fclose($options["stream"]); - } - return "201 Created " . $fsFile; - } - } - - if ( $paths[2] == 'mailTemplates' ) { - $pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP . $paths[1] . PATH_SEP; - $fsFile = $pathTemplates. $paths[3]; - if ( count($paths) == 4 && file_exists( $fsFile ) ) { - $fp = fopen($fsFile, "w"); - if ( is_resource($fp) && is_resource($options["stream"])) { - while( !feof($options["stream"])) { - fwrite($fp, fread($options["stream"], 4096)); - } - fclose($fp); - fclose($options["stream"]); - } - return "201 Created " . $fsFile; - } - } - - - if ( $paths[2] == 'public_html' ) { - $pathPublic = $pathProcesses . 'public' . PATH_SEP . $paths[1] . PATH_SEP; - $fsFile = $pathPublic. $paths[3]; - if ( count($paths) == 4 && file_exists( $fsFile ) ) { - $fp = fopen($fsFile, "w"); - if ( is_resource($fp) && is_resource($options["stream"])) { - while( !feof($options["stream"])) { - fwrite($fp, fread($options["stream"], 4096)); - } - fclose($fp); - fclose($options["stream"]); - } - return "201 Created " . $fsFile; - } - } - - } - - return "409 Conflict"; - - } - - /** - * MKCOL method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function MKCOL($options) - { - $path = $this->base .$options["path"]; - $parent = dirname($path); - $name = basename($path); - - if (!file_exists($parent)) { - return "409 Conflict"; - } - - if (!is_dir($parent)) { - return "403 Forbidden"; - } - - if ( file_exists($parent."/".$name) ) { - return "405 Method not allowed"; - } - - if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet - return "415 Unsupported media type"; - } - - $stat = mkdir ($parent."/".$name,0777); - if (!$stat) { - return "403 Forbidden"; - } - - return ("201 Created"); - } - - - /** - * DELETE method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function DELETE($options) - { - $path = $this->base . "/" .$options["path"]; - - if (!file_exists($path)) { - return "404 Not found"; - } - - if (is_dir($path)) { - $query = "DELETE FROM properties WHERE path LIKE '".$this->_slashify($options["path"])."%'"; - mysql_query($query); - System::rm("-rf $path"); - } else { - unlink ($path); - } - $query = "DELETE FROM properties WHERE path = '$options[path]'"; - mysql_query($query); - - return "204 No Content"; - } + // popen will not return an error if the binary was not found + // and find may not have mime support using "-i" + // so we test the format of the returned string - /** - * MOVE method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function MOVE($options) - { - return "423 Locked"; - //return $this->COPY($options, true); - } - - /** - * COPY method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function COPY($options, $del=false) - { - // TODO Property updates still broken (Litmus should detect this?) - - if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet - return "415 Unsupported media type"; - } - - // no copying to different WebDAV Servers yet - if (isset($options["dest_url"])) { - return "502 bad gateway"; - } - - $source = $this->base .$options["path"]; - if (!file_exists($source)) return "404 Not found"; - - $dest = $this->base . $options["dest"]; - - $new = !file_exists($dest); - $existing_col = false; - - if (!$new) { - if ($del && is_dir($dest)) { - if (!$options["overwrite"]) { - return "412 precondition failed"; - } - $dest .= basename($source); - if (file_exists($dest)) { - $options["dest"] .= basename($source); - } else { - $new = true; - $existing_col = true; - } - } - } - - if (!$new) { - if ($options["overwrite"]) { - $stat = $this->DELETE(array("path" => $options["dest"])); - if (($stat{0} != "2") && (substr($stat, 0, 3) != "404")) { - return $stat; - } - } else { - return "412 precondition failed"; - } - } - - if (is_dir($source) && ($options["depth"] != "infinity")) { - // RFC 2518 Section 9.2, last paragraph - return "400 Bad request"; - } - - if ($del) { - if (!rename($source, $dest)) { - return "500 Internal server error"; - } - $destpath = $this->_unslashify($options["dest"]); - if (is_dir($source)) { - $query = "UPDATE properties - SET path = REPLACE(path, '".$options["path"]."', '".$destpath."') - WHERE path LIKE '".$this->_slashify($options["path"])."%'"; - mysql_query($query); - } - - $query = "UPDATE properties - SET path = '".$destpath."' - WHERE path = '".$options["path"]."'"; - mysql_query($query); - } else { - if (is_dir($source)) { - $files = System::find($source); - $files = array_reverse($files); - } else { - $files = array($source); - } - - if (!is_array($files) || empty($files)) { - return "500 Internal server error"; - } - - foreach ($files as $file) { - if (is_dir($file)) { - $file = $this->_slashify($file); - } - - $destfile = str_replace($source, $dest, $file); - - if (is_dir($file)) { - if (!is_dir($destfile)) { - // TODO "mkdir -p" here? (only natively supported by PHP 5) - if (!mkdir($destfile)) { - return "409 Conflict"; - } - } else { - error_log("existing dir '$destfile'"); - } - } else { - if (!copy($file, $destfile)) { - return "409 Conflict"; + // the reply begins with the requested filename + if (! strncmp( $reply, "$fspath: ", strlen( $fspath ) + 2 )) { + $reply = substr( $reply, strlen( $fspath ) + 2 ); + // followed by the mime type (maybe including options) + if (preg_match( '/^[[:alnum:]_-]+/[[:alnum:]_-]+;?.*/', $reply, $matches )) { + $mime_type = $matches[0]; + } } } - } - $query = "INSERT INTO properties SELECT ... FROM properties WHERE path = '".$options['path']."'"; + if (empty( $mime_type )) { + // Fallback solution: try to guess the type by the file extension + // TODO: add more ... + // TODO: it has been suggested to delegate mimetype detection + // to apache but this has at least three issues: + // - works only with apache + // - needs file to be within the document tree + // - requires apache mod_magic + // TODO: can we use the registry for this on Windows? + // OTOH if the server is Windos the clients are likely to + // be Windows, too, and tend do ignore the Content-Type + // anyway (overriding it with information taken from + // the registry) + // TODO: have a seperate PEAR class for mimetype detection? + switch (strtolower( strrchr( basename( $fspath ), "." ) )) { + case ".html": + $mime_type = "text/html"; + break; + case ".gif": + $mime_type = "image/gif"; + break; + case ".jpg": + $mime_type = "image/jpeg"; + break; + default: + $mime_type = "application/octet-stream"; + break; + } + } + + return $mime_type; } - return ($new && !$existing_col) ? "201 Created" : "204 No Content"; - } + /** + * GET method handler + * + * @param array parameter passing array + * @return bool true on success + */ + function GET (&$options) + { + $paths = $this->paths; - /** - * PROPPATCH method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function PROPPATCH(&$options) - { - global $prefs, $tab; + $pathClasses = PATH_DB . SYS_SYS . PATH_SEP . 'classes' . PATH_SEP; + if (count( $paths ) > 0 && $paths[0] == 'classes' && is_dir( $pathClasses )) { + $fsFile = $pathClasses . $paths[1]; + if (count( $paths ) == 2 && file_exists( $fsFile )) { + $content = file_get_contents( $fsFile ); + print $content; + header( "Content-Type: " . mime_content_type( $fsFile ) ); + header( "Last-Modified: " . date( "D, j M Y H:m:s ", file_mtime( $fsFile ) ) . "GMT" ); + header( "Content-Length: " . filesize( $fsFile ) ); + return true; + } + } - $msg = ""; - - $path = $options["path"]; - - $dir = dirname($path)."/"; - $base = basename($path); - - foreach($options["props"] as $key => $prop) { - if ($prop["ns"] == "DAV:") { - $options["props"][$key]['status'] = "403 Forbidden"; - } else { - if (isset($prop["val"])) { - $query = "REPLACE INTO properties SET path = '$options[path]', name = '$prop[name]', ns= '$prop[ns]', value = '$prop[val]'"; - error_log($query); - } else { - $query = "DELETE FROM properties WHERE path = '$options[path]' AND name = '$prop[name]' AND ns = '$prop[ns]'"; - } - mysql_query($query); - } - } - return ""; - } + $pathProcesses = PATH_DB . SYS_SYS . PATH_SEP; + if (count( $paths ) > 0 && $paths[0] == 'processes' && is_dir( $pathProcesses )) { + if (count( $paths ) == 4 && $paths[2] == 'xmlforms') { + $pathXmlform = $pathProcesses . 'xmlForms' . PATH_SEP . $paths[1] . PATH_SEP; + $fsFile = $pathXmlform . $paths[3]; + if (count( $paths ) == 4 && file_exists( $fsFile )) { + $content = file_get_contents( $fsFile ); + print $content; + header( "Content-Type: " . mime_content_type( $fsFile ) ); + header( "Last-Modified: " . date( "D, j M Y H:m:s ", file_mtime( $fsFile ) ) . "GMT" ); + header( "Content-Length: " . filesize( $fsFile ) ); + return true; + } + } + if (count( $paths ) == 4 && $paths[2] == 'mailTemplates') { + $pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP . $paths[1] . PATH_SEP; + $fsFile = $pathTemplates . $paths[3]; + if (count( $paths ) == 4 && file_exists( $fsFile )) { + $content = file_get_contents( $fsFile ); + print $content; + header( "Content-Type: " . mime_content_type( $fsFile ) ); + header( "Last-Modified: " . date( "D, j M Y H:m:s ", file_mtime( $fsFile ) ) . "GMT" ); + header( "Content-Length: " . filesize( $fsFile ) ); + return true; + } + } - /** - * LOCK method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function LOCK(&$options) - { - if (isset($options["update"])) { // Lock Update - $query = "UPDATE locks SET expires = ".(time()+300); - mysql_query($query); - - if (mysql_affected_rows()) { - $options["timeout"] = 300; // 5min hardcoded + if (count( $paths ) == 4 && $paths[2] == 'public_html') { + $pathPublic = $pathProcesses . 'public' . PATH_SEP . $paths[1] . PATH_SEP; + $fsFile = $pathPublic . $paths[3]; + if (count( $paths ) == 4 && file_exists( $fsFile )) { + $content = file_get_contents( $fsFile ); + print $content; + header( "Content-Type: " . mime_content_type( $fsFile ) ); + header( "Last-Modified: " . date( "D, j M Y H:m:s ", file_mtime( $fsFile ) ) . "GMT" ); + header( "Content-Length: " . filesize( $fsFile ) ); + return true; + } + } + + } + + print_r( $paths ); return true; - } else { - return false; - } - } - - $options["timeout"] = time()+300; // 5min. hardcoded - $query = "INSERT INTO locks + if ($options["path"] == '/') { + return $this->getRoot( $options ); + } + //print_r ($options); + + + // get absolute fs path to requested resource + $fspath = $this->base . $options["path"]; + + // sanity check + if (! file_exists( $fspath )) + return false; + + // is this a collection? + if (is_dir( $fspath )) { + return $this->GetDir( $fspath, $options ); + } + + // detect resource type + $options['mimetype'] = $this->_mimetype( $fspath ); + + // detect modification time + // see rfc2518, section 13.7 + // some clients seem to treat this as a reverse rule + // requiering a Last-Modified header if the getlastmodified header was set + $options['mtime'] = filemtime( $fspath ); + + // detect resource size + $options['size'] = filesize( $fspath ); + + // no need to check result here, it is handled by the base class + $options['stream'] = fopen( $fspath, "r" ); + + return true; + } + + /** + * getRoot + * + * @param string &$options + * @return boolean false + */ + function getRoot (&$options) + { + $path = $this->_slashify( $options["path"] ); + // fixed width directory column format + $format = "%15s %-19s %-s\n"; + + echo "Index of " . htmlspecialchars( $options['path'] ) . "\n"; + echo "

Index of " . htmlspecialchars( $options['path'] ) . "

\n"; + + echo "
";
+        printf( $format, "Size", "Last modified", "Filename" );
+        echo "
"; + + $pathRoot = array ('xmlforms','public_html','dir1','dir2' + ); + + foreach ($pathRoot as $key => $val) { + $fullpath = $fspath . "/" . $filename; + $name = htmlspecialchars( $val ); + printf( $format, number_format( filesize( $fullpath ) ), strftime( "%Y-%m-%d %H:%M:%S", filemtime( $fullpath ) ), "$name" ); + } + + echo "
"; + echo "\n"; + + die(); + + $handle = @opendir( $fspath ); + if (! $handle) { + return false; + } + + while ($filename = readdir( $handle )) { + if ($filename != "." && $filename != "..") { + $fullpath = $fspath . "/" . $filename; + $name = htmlspecialchars( $filename ); + printf( $format, number_format( filesize( $fullpath ) ), strftime( "%Y-%m-%d %H:%M:%S", filemtime( $fullpath ) ), "$name" ); + } + } + + echo "
"; + + closedir( $handle ); + + echo "\n"; + + exit(); + } + + /** + * GET method handler for directories + * + * This is a very simple mod_index lookalike. + * See RFC 2518, Section 8.4 on GET/HEAD for collections + * + * @param string directory path + * @return void function has to handle HTTP response itself + */ + function GetDir ($fspath, &$options) + { + $path = $this->_slashify( $options["path"] ); + if ($path != $options["path"]) { + header( "Location: " . $this->base_uri . $path ); + exit(); + } + + // fixed width directory column format + $format = "%15s %-19s %-s\n"; + + $handle = @opendir( $fspath ); + if (! $handle) { + return false; + } + + echo "Index of " . htmlspecialchars( $options['path'] ) . "\n"; + + echo "

Index of " . htmlspecialchars( $options['path'] ) . "

\n"; + + echo "
";
+        printf( $format, "Size", "Last modified", "Filename" );
+        echo "
"; + + while ($filename = readdir( $handle )) { + if ($filename != "." && $filename != "..") { + $fullpath = $fspath . "/" . $filename; + $name = htmlspecialchars( $filename ); + printf( $format, number_format( filesize( $fullpath ) ), strftime( "%Y-%m-%d %H:%M:%S", filemtime( $fullpath ) ), "$name" ); + } + } + + echo "
"; + + closedir( $handle ); + + echo "\n"; + + exit(); + } + + /** + * PUT method handler + * + * @param array parameter passing array + * @return bool true on success + */ + function PUT (&$options) + { + $paths = $this->paths; + + $pathClasses = PATH_DB . PATH_SEP . 'classes' . PATH_SEP; + if (count( $paths ) > 0 && $paths[0] == 'classes' && is_dir( $pathClasses )) { + $fsFile = $pathClasses . $paths[1]; + if (count( $paths ) == 2 && file_exists( $fsFile )) { + $fp = fopen( $fsFile, "w" ); + if (is_resource( $fp ) && is_resource( $options["stream"] )) { + while (! feof( $options["stream"] )) { + fwrite( $fp, fread( $options["stream"], 4096 ) ); + } + fclose( $fp ); + fclose( $options["stream"] ); + } + return "201 Created " . $fsFile; + } + } + + $pathProcesses = PATH_DB . SYS_SYS . PATH_SEP; + if (count( $paths ) > 0 && $paths[0] == 'processes' && is_dir( $pathProcesses )) { + if ($paths[2] == 'xmlforms') { + $pathTemplates = $pathProcesses . 'xmlForms' . PATH_SEP . $paths[1] . PATH_SEP; + $fsFile = $pathTemplates . $paths[3]; + if (count( $paths ) == 4 && file_exists( $fsFile )) { + $fp = fopen( $fsFile, "w" ); + if (is_resource( $fp ) && is_resource( $options["stream"] )) { + while (! feof( $options["stream"] )) { + fwrite( $fp, fread( $options["stream"], 4096 ) ); + } + fclose( $fp ); + fclose( $options["stream"] ); + } + return "201 Created " . $fsFile; + } + } + + if ($paths[2] == 'mailTemplates') { + $pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP . $paths[1] . PATH_SEP; + $fsFile = $pathTemplates . $paths[3]; + if (count( $paths ) == 4 && file_exists( $fsFile )) { + $fp = fopen( $fsFile, "w" ); + if (is_resource( $fp ) && is_resource( $options["stream"] )) { + while (! feof( $options["stream"] )) { + fwrite( $fp, fread( $options["stream"], 4096 ) ); + } + fclose( $fp ); + fclose( $options["stream"] ); + } + return "201 Created " . $fsFile; + } + } + + if ($paths[2] == 'public_html') { + $pathPublic = $pathProcesses . 'public' . PATH_SEP . $paths[1] . PATH_SEP; + $fsFile = $pathPublic . $paths[3]; + if (count( $paths ) == 4 && file_exists( $fsFile )) { + $fp = fopen( $fsFile, "w" ); + if (is_resource( $fp ) && is_resource( $options["stream"] )) { + while (! feof( $options["stream"] )) { + fwrite( $fp, fread( $options["stream"], 4096 ) ); + } + fclose( $fp ); + fclose( $options["stream"] ); + } + return "201 Created " . $fsFile; + } + } + + } + + return "409 Conflict"; + + } + + /** + * MKCOL method handler + * + * @param array general parameter passing array + * @return bool true on success + */ + function MKCOL ($options) + { + $path = $this->base . $options["path"]; + $parent = dirname( $path ); + $name = basename( $path ); + + if (! file_exists( $parent )) { + return "409 Conflict"; + } + + if (! is_dir( $parent )) { + return "403 Forbidden"; + } + + if (file_exists( $parent . "/" . $name )) { + return "405 Method not allowed"; + } + + if (! empty( $_SERVER["CONTENT_LENGTH"] )) { // no body parsing yet + return "415 Unsupported media type"; + } + + $stat = mkdir( $parent . "/" . $name, 0777 ); + if (! $stat) { + return "403 Forbidden"; + } + + return ("201 Created"); + } + + /** + * DELETE method handler + * + * @param array general parameter passing array + * @return bool true on success + */ + function DELETE ($options) + { + $path = $this->base . "/" . $options["path"]; + + if (! file_exists( $path )) { + return "404 Not found"; + } + + if (is_dir( $path )) { + $query = "DELETE FROM properties WHERE path LIKE '" . $this->_slashify( $options["path"] ) . "%'"; + mysql_query( $query ); + System::rm( "-rf $path" ); + } else { + unlink( $path ); + } + $query = "DELETE FROM properties WHERE path = '$options[path]'"; + mysql_query( $query ); + + return "204 No Content"; + } + + /** + * MOVE method handler + * + * @param array general parameter passing array + * @return bool true on success + */ + function MOVE ($options) + { + return "423 Locked"; + //return $this->COPY($options, true); + } + + /** + * COPY method handler + * + * @param array general parameter passing array + * @return bool true on success + */ + function COPY ($options, $del = false) + { + // TODO Property updates still broken (Litmus should detect this?) + + + if (! empty( $_SERVER["CONTENT_LENGTH"] )) { // no body parsing yet + return "415 Unsupported media type"; + } + + // no copying to different WebDAV Servers yet + if (isset( $options["dest_url"] )) { + return "502 bad gateway"; + } + + $source = $this->base . $options["path"]; + if (! file_exists( $source )) + return "404 Not found"; + + $dest = $this->base . $options["dest"]; + + $new = ! file_exists( $dest ); + $existing_col = false; + + if (! $new) { + if ($del && is_dir( $dest )) { + if (! $options["overwrite"]) { + return "412 precondition failed"; + } + $dest .= basename( $source ); + if (file_exists( $dest )) { + $options["dest"] .= basename( $source ); + } else { + $new = true; + $existing_col = true; + } + } + } + + if (! $new) { + if ($options["overwrite"]) { + $stat = $this->DELETE( array ("path" => $options["dest"] + ) ); + if (($stat{0} != "2") && (substr( $stat, 0, 3 ) != "404")) { + return $stat; + } + } else { + return "412 precondition failed"; + } + } + + if (is_dir( $source ) && ($options["depth"] != "infinity")) { + // RFC 2518 Section 9.2, last paragraph + return "400 Bad request"; + } + + if ($del) { + if (! rename( $source, $dest )) { + return "500 Internal server error"; + } + $destpath = $this->_unslashify( $options["dest"] ); + if (is_dir( $source )) { + $query = "UPDATE properties + SET path = REPLACE(path, '" . $options["path"] . "', '" . $destpath . "') + WHERE path LIKE '" . $this->_slashify( $options["path"] ) . "%'"; + mysql_query( $query ); + } + + $query = "UPDATE properties + SET path = '" . $destpath . "' + WHERE path = '" . $options["path"] . "'"; + mysql_query( $query ); + } else { + if (is_dir( $source )) { + $files = System::find( $source ); + $files = array_reverse( $files ); + } else { + $files = array ($source + ); + } + + if (! is_array( $files ) || empty( $files )) { + return "500 Internal server error"; + } + + foreach ($files as $file) { + if (is_dir( $file )) { + $file = $this->_slashify( $file ); + } + + $destfile = str_replace( $source, $dest, $file ); + + if (is_dir( $file )) { + if (! is_dir( $destfile )) { + // TODO "mkdir -p" here? (only natively supported by PHP 5) + if (! mkdir( $destfile )) { + return "409 Conflict"; + } + } else { + error_log( "existing dir '$destfile'" ); + } + } else { + if (! copy( $file, $destfile )) { + return "409 Conflict"; + } + } + } + + $query = "INSERT INTO properties SELECT ... FROM properties WHERE path = '" . $options['path'] . "'"; + } + + return ($new && ! $existing_col) ? "201 Created" : "204 No Content"; + } + + /** + * PROPPATCH method handler + * + * @param array general parameter passing array + * @return bool true on success + */ + function PROPPATCH (&$options) + { + global $prefs, $tab; + + $msg = ""; + + $path = $options["path"]; + + $dir = dirname( $path ) . "/"; + $base = basename( $path ); + + foreach ($options["props"] as $key => $prop) { + if ($prop["ns"] == "DAV:") { + $options["props"][$key]['status'] = "403 Forbidden"; + } else { + if (isset( $prop["val"] )) { + $query = "REPLACE INTO properties SET path = '$options[path]', name = '$prop[name]', ns= '$prop[ns]', value = '$prop[val]'"; + error_log( $query ); + } else { + $query = "DELETE FROM properties WHERE path = '$options[path]' AND name = '$prop[name]' AND ns = '$prop[ns]'"; + } + mysql_query( $query ); + } + } + return ""; + } + + /** + * LOCK method handler + * + * @param array general parameter passing array + * @return bool true on success + */ + function LOCK (&$options) + { + if (isset( $options["update"] )) { // Lock Update + $query = "UPDATE locks SET expires = " . (time() + 300); + mysql_query( $query ); + + if (mysql_affected_rows()) { + $options["timeout"] = 300; // 5min hardcoded + return true; + } else { + return false; + } + } + + $options["timeout"] = time() + 300; // 5min. hardcoded + + + $query = "INSERT INTO locks SET token = '$options[locktoken]' , path = '$options[path]' , owner = '$options[owner]' , expires = '$options[timeout]' - , exclusivelock = " .($options['scope'] === "exclusive" ? "1" : "0") ; - mysql_query($query); + , exclusivelock = " . ($options['scope'] === "exclusive" ? "1" : "0"); + mysql_query( $query ); - return mysql_affected_rows() ? "200 OK" : "409 Conflict"; - } - - /** - * UNLOCK method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function UNLOCK(&$options) - { - $query = "DELETE FROM locks - WHERE path = '$options[path]' - AND token = '$options[token]'"; - mysql_query($query); - - return mysql_affected_rows() ? "204 No Content" : "409 Conflict"; - } - - /** - * checkLock() helper - * - * @param string resource path to check for locks - * @return bool true on success - */ - function checkLock($path) - { - $result = false; - - $query = "SELECT owner, token, expires, exclusivelock - FROM locks - WHERE path = '$path' "; - $res = mysql_query($query); - - if ($res) { - $row = mysql_fetch_array($res); - mysql_free_result($res); - - if ($row) { - $result = array( "type" => "write", - "scope" => $row["exclusivelock"] ? "exclusive" : "shared", - "depth" => 0, - "owner" => $row['owner'], - "token" => $row['token'], - "expires" => $row['expires'] - ); - } + return mysql_affected_rows() ? "200 OK" : "409 Conflict"; } - return $result; - } + /** + * UNLOCK method handler + * + * @param array general parameter passing array + * @return bool true on success + */ + function UNLOCK (&$options) + { + $query = "DELETE FROM locks + WHERE path = '$options[path]' + AND token = '$options[token]'"; + mysql_query( $query ); + return mysql_affected_rows() ? "204 No Content" : "409 Conflict"; + } + + /** + * checkLock() helper + * + * @param string resource path to check for locks + * @return bool true on success + */ + function checkLock ($path) + { + $result = false; + + $query = "SELECT owner, token, expires, exclusivelock + FROM locks + WHERE path = '$path' "; + $res = mysql_query( $query ); + + if ($res) { + $row = mysql_fetch_array( $res ); + mysql_free_result( $res ); + + if ($row) { + $result = array ("type" => "write","scope" => $row["exclusivelock"] ? "exclusive" : "shared","depth" => 0,"owner" => $row['owner'],"token" => $row['token'],"expires" => $row['expires'] + ); + } + } + + return $result; + } + + /** + * create database tables for property and lock storage + * + * @param void + * @return bool true on success + */ + function create_database () + { + // TODO + return false; + } - /** - * create database tables for property and lock storage - * - * @param void - * @return bool true on success - */ - function create_database() - { - // TODO - return false; - } - } ?> From 749b1c141e0e90e762b0eb33654ada64398c5272 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:27:29 -0400 Subject: [PATCH 14/18] CODE STYLE class.wsResponse.php --- workflow/engine/classes/class.wsResponse.php | 311 ++++++++++--------- 1 file changed, 166 insertions(+), 145 deletions(-) diff --git a/workflow/engine/classes/class.wsResponse.php b/workflow/engine/classes/class.wsResponse.php index 9fa7a21ba..f3c4ece35 100755 --- a/workflow/engine/classes/class.wsResponse.php +++ b/workflow/engine/classes/class.wsResponse.php @@ -1,6 +1,8 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ - /** +/** + * * @package workflow.engine.classes */ - + class wsResponse { - public $status_code = 0; - public $message = ''; - public $timestamp = ''; - - /** - * Function __construct - * Constructor of the class - * @param string $status - * @param string $message - * @return void - */ - function __construct( $status, $message ) - { - $this->status_code = $status; - $this->message = $message; - $this->timestamp = date('Y-m-d H:i:s'); - } - - /** - * Function getPayloadString - * @param string $operation - * @return string - */ - function getPayloadString ( $operation ) - { - $res = "<$operation>\n"; - $res .= "" . $this->status_code . ""; - $res .= "" . $this->message . ""; - $res .= "" . $this->timestamp . ""; -// $res .= "" . $this->timestamp . ""; - $res .= "<$operation>"; - return $res; - } + public $status_code = 0; + public $message = ''; + public $timestamp = ''; - /** - * Function getPayloadArray - * @return array - */ - function getPayloadArray() - { - return array("status_code" => $this->status_code , 'message'=> $this->message, 'timestamp' => $this->timestamp); - } + /** + * Function __construct + * Constructor of the class + * + * @param string $status + * @param string $message + * @return void + */ + function __construct ($status, $message) + { + $this->status_code = $status; + $this->message = $message; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } + + /** + * Function getPayloadString + * + * @param string $operation + * @return string + */ + function getPayloadString ($operation) + { + $res = "<$operation>\n"; + $res .= "" . $this->status_code . ""; + $res .= "" . $this->message . ""; + $res .= "" . $this->timestamp . ""; + // $res .= "" . $this->timestamp . ""; + $res .= "<$operation>"; + return $res; + } + + /** + * Function getPayloadArray + * + * @return array + */ + function getPayloadArray () + { + return array ("status_code" => $this->status_code,'message' => $this->message,'timestamp' => $this->timestamp + ); + } } /** * Class wsCreateUserResponse + * * @package workflow.engine.classes - */ + */ class wsCreateUserResponse { - public $status_code = 0; - public $message = ''; - public $userUID = ''; - public $timestamp = ''; - - /** - * Function __construct - * Constructor of the class - * @param string $status - * @param string $message - * @param string $userUID - * @return void - */ - function __construct( $status, $message, $userUID ) - { - $this->status_code = $status; - $this->message = $message; - $this->userUID = $userUID; - $this->timestamp = date('Y-m-d H:i:s'); - } + public $status_code = 0; + public $message = ''; + public $userUID = ''; + public $timestamp = ''; + + /** + * Function __construct + * Constructor of the class + * + * @param string $status + * @param string $message + * @param string $userUID + * @return void + */ + function __construct ($status, $message, $userUID) + { + $this->status_code = $status; + $this->message = $message; + $this->userUID = $userUID; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } } /** * Class wsCreateGroupResponse + * * @package workflow.engine.classes - */ + */ class wsCreateGroupResponse { - public $status_code = 0; - public $message = ''; - public $groupUID = ''; - public $timestamp = ''; - - /** - * Function __construct - * Constructor of the class - * @param string $status - * @param string $message - * @param string $groupUID - * @return void - */ - function __construct( $status, $message, $groupUID ) { - $this->status_code = $status; - $this->message = $message; - $this->groupUID = $groupUID; - $this->timestamp = date('Y-m-d H:i:s'); - } - + public $status_code = 0; + public $message = ''; + public $groupUID = ''; + public $timestamp = ''; + + /** + * Function __construct + * Constructor of the class + * + * @param string $status + * @param string $message + * @param string $groupUID + * @return void + */ + function __construct ($status, $message, $groupUID) + { + $this->status_code = $status; + $this->message = $message; + $this->groupUID = $groupUID; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } + } /** * Class wsCreateDepartmentResponse + * * @package workflow.engine.classes - */ + */ class wsCreateDepartmentResponse { - public $status_code = 0; - public $message = ''; - public $departmentUID = ''; - public $timestamp = ''; - - /** - * Function __construct - * Constructor of the class - * @param string $status - * @param string $message - * @param string $departmentUID - * @return void - */ - function __construct( $status, $message, $departmentUID ) { - $this->status_code = $status; - $this->message = $message; - $this->departmentUID = $departmentUID; - $this->timestamp = date('Y-m-d H:i:s'); - } + public $status_code = 0; + public $message = ''; + public $departmentUID = ''; + public $timestamp = ''; + + /** + * Function __construct + * Constructor of the class + * + * @param string $status + * @param string $message + * @param string $departmentUID + * @return void + */ + function __construct ($status, $message, $departmentUID) + { + $this->status_code = $status; + $this->message = $message; + $this->departmentUID = $departmentUID; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } } /** * Class wsGetVariableResponse + * * @package workflow.engine.classes */ class wsGetVariableResponse { - public $status_code = 0; - public $message = ''; - public $variables = null; - public $timestamp = ''; - - /** - * Function __construct - * Constructor of the class - * @param string $status - * @param string $message - * @param string $variables - * @return void - */ - function __construct( $status, $message, $variables ) { - $this->status_code = $status; - $this->message = $message; - $this->variables = $variables; - $this->timestamp = date('Y-m-d H:i:s'); - } + public $status_code = 0; + public $message = ''; + public $variables = null; + public $timestamp = ''; + + /** + * Function __construct + * Constructor of the class + * + * @param string $status + * @param string $message + * @param string $variables + * @return void + */ + function __construct ($status, $message, $variables) + { + $this->status_code = $status; + $this->message = $message; + $this->variables = $variables; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } } /** * Class wsGetCaseNotesResponse + * * @package workflow.engine.classes */ class wsGetCaseNotesResponse { - public $status_code = 0; - public $message = ''; - public $notes = null; - public $timestamp = ''; - - /** - * Function __construct - * Constructor of the class - * @param string $status - * @param string $message - * @param array|object|string $notes - * @return void - */ - function __construct( $status, $message, $notes ) { - $this->status_code = $status; - $this->message = $message; - $this->notes = $notes; - $this->timestamp = date('Y-m-d H:i:s'); - } + public $status_code = 0; + public $message = ''; + public $notes = null; + public $timestamp = ''; + + /** + * Function __construct + * Constructor of the class + * + * @param string $status + * @param string $message + * @param array|object|string $notes + * @return void + */ + function __construct ($status, $message, $notes) + { + $this->status_code = $status; + $this->message = $message; + $this->notes = $notes; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } } ?> \ No newline at end of file From ad4953d138712cb5ed786dd5860d70d9cfa725f3 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:29:25 -0400 Subject: [PATCH 15/18] CODE STYLE class.wsBase --- workflow/engine/classes/class.wsBase.php | 2130 +++++++++++----------- 1 file changed, 1029 insertions(+), 1101 deletions(-) diff --git a/workflow/engine/classes/class.wsBase.php b/workflow/engine/classes/class.wsBase.php index 461a8808d..8237b19f6 100755 --- a/workflow/engine/classes/class.wsBase.php +++ b/workflow/engine/classes/class.wsBase.php @@ -1,6 +1,7 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ +//It works with the table CONFIGURATION in a WF dataBase +require_once ("classes/model/Application.php"); +require_once ("classes/model/AppCacheView.php"); +require_once ("classes/model/AppDelegation.php"); +require_once ("classes/model/AppDocument.php"); +require_once ("classes/model/AppDelay.php"); +require_once ("classes/model/AppThread.php"); +require_once ("classes/model/Department.php"); +require_once ("classes/model/Dynaform.php"); +require_once ("classes/model/Groupwf.php"); +require_once ("classes/model/InputDocument.php"); +require_once ("classes/model/Language.php"); +require_once ("classes/model/OutputDocument.php"); +require_once ("classes/model/Process.php"); +require_once ("classes/model/ReportTable.php"); +require_once ("classes/model/ReportVar.php"); +require_once ("classes/model/Route.php"); +require_once ("classes/model/Step.php"); +require_once ("classes/model/StepTrigger.php"); +require_once ("classes/model/Task.php"); +require_once ("classes/model/TaskUser.php"); +require_once ("classes/model/Triggers.php"); +require_once ("classes/model/Users.php"); +require_once ("classes/model/Session.php"); +require_once ("classes/model/Content.php"); +G::LoadClass( "ArrayPeer" ); +G::LoadClass( "BasePeer" ); +G::LoadClass( 'case' ); +G::LoadClass( 'derivation' ); +G::LoadClass( 'groups' ); +G::LoadClass( 'sessions' ); +G::LoadClass( 'processes' ); +G::LoadClass( 'processMap' ); +G::LoadClass( 'pmScript' ); +G::LoadClass( 'spool' ); +G::LoadClass( 'tasks' ); +G::LoadClass( 'wsResponse' ); - //It works with the table CONFIGURATION in a WF dataBase - require_once ("classes/model/Application.php"); - require_once ("classes/model/AppCacheView.php"); - require_once ("classes/model/AppDelegation.php"); - require_once ("classes/model/AppDocument.php"); - require_once ("classes/model/AppDelay.php"); - require_once ("classes/model/AppThread.php"); - require_once ("classes/model/Department.php"); - require_once ("classes/model/Dynaform.php"); - require_once ("classes/model/Groupwf.php"); - require_once ("classes/model/InputDocument.php"); - require_once ("classes/model/Language.php"); - require_once ("classes/model/OutputDocument.php"); - require_once ("classes/model/Process.php"); - require_once ("classes/model/ReportTable.php"); - require_once ("classes/model/ReportVar.php"); - require_once ("classes/model/Route.php"); - require_once ("classes/model/Step.php"); - require_once ("classes/model/StepTrigger.php"); - require_once ("classes/model/Task.php"); - require_once ("classes/model/TaskUser.php"); - require_once ("classes/model/Triggers.php"); - require_once ("classes/model/Users.php"); - require_once ("classes/model/Session.php"); - require_once ("classes/model/Content.php"); - G::LoadClass("ArrayPeer"); - G::LoadClass("BasePeer"); - G::LoadClass('case'); - G::LoadClass('derivation'); - G::LoadClass('groups'); - G::LoadClass('sessions'); - G::LoadClass('processes'); - G::LoadClass('processMap'); - G::LoadClass('pmScript'); - G::LoadClass('spool'); - G::LoadClass('tasks'); - G::LoadClass('wsResponse'); - - /** +/** * Copyright (C) 2009 COLOSA * License: LGPL, see LICENSE * Last Modify: 26.06.2008 10:05:00 * Last modify by: Erik Amaru Ortiz * Last Modify comment(26.06.2008): the session expired verification was removed from here to soap class + * * @package workflow.engine.classes */ @@ -76,84 +77,83 @@ class wsBase public $stored_system_variables; //boolean public $wsSessionId; //web service session id, if the wsbase function is used from a WS request - public function __construct($params=null) + + public 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->stored_system_variables = (isset( $params->stored_system_variables ) ? $params->stored_system_variables : false); - $this->wsSessionId = isset($params->wsSessionId)? $params->wsSessionId: ''; + $this->wsSessionId = isset( $params->wsSessionId ) ? $params->wsSessionId : ''; } } /** * 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) + public function login ($userid, $password) { global $RBAC; try { - $uid = $RBAC->VerifyLogin($userid , $password); + $uid = $RBAC->VerifyLogin( $userid, $password ); switch ($uid) { case '': - case -1: //The user doesn't exist - $wsResponse = new wsResponse(3, G::loadTranslation('ID_USER_NOT_REGISTERED')); + 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')); + 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')); + case - 3: //The user is inactive + $wsResponse = new wsResponse( 5, G::loadTranslation( 'ID_USER_INACTIVE' ) ); + break; + case - 4: //The Due date is finished + $wsResponse = new wsResponse( 5, G::loadTranslation( 'ID_USER_INACTIVE' ) ); break; } if ($uid < 0 || $uid == '') { - throw (new Exception(serialize($wsResponse))); + throw (new Exception( serialize( $wsResponse ) )); } //check access to PM - $RBAC->loadUserRolePermission($RBAC->sSystem, $uid); - $res = $RBAC->userCanAccess("PM_LOGIN"); + $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))); + $wsResponse = new wsResponse( 2, G::loadTranslation( 'ID_USER_HAVENT_RIGHTS_SYSTEM' ) ); + throw (new Exception( serialize( $wsResponse ) )); } - $sessionId = G::generateUniqueID(); - $wsResponse = new wsResponse('0', $sessionId); + $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->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()); + $wsResponse = unserialize( $e->getMessage() ); return $wsResponse; } @@ -161,30 +161,33 @@ class wsBase /** * get all groups + * * @param none * @return $result will return an object */ - public function processList() + public function processList () { try { - $result = array(); - $oCriteria = new Criteria('workflow'); + $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); + $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']); + $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()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } @@ -192,60 +195,65 @@ class wsBase /** * get all roles, to see all roles + * * @param none * @return $result will return an object */ - public function roleList() + public function roleList () { try { - $result = array(); + $result = array (); - $RBAC =& RBAC::getSingleton(); + $RBAC = & RBAC::getSingleton(); $RBAC->initRBAC(); $oCriteria = $RBAC->listAllRoles(); - $oDataset = GulliverBasePeer::doSelectRs($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $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']); + $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()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } } - /** * get all groups + * * @param none * @return $result will return an object */ - public function groupList() + 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); + $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']); + $arrayGroupwf = $oGroupwf->Load( $aRow['GRP_UID'] ); + $result[] = array ('guid' => $aRow['GRP_UID'],'name' => $arrayGroupwf['GRP_TITLE'] + ); $oDataset->next(); } return $result; } catch (Exception $e) { - $result[] = array('guid' => $e->getMessage(), 'name' => $e->getMessage()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } @@ -253,22 +261,23 @@ class wsBase /** * get all department + * * @param none * @return $result will return an object */ - public function departmentList() + 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); + $result = array (); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( DepartmentPeer::DEP_STATUS, 'ACTIVE' ); + $oDataset = DepartmentPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); while ($aRow = $oDataset->getRow()) { $oDepartment = new Department(); - $aDepartment = $oDepartment->Load( $aRow['DEP_UID']); + $aDepartment = $oDepartment->Load( $aRow['DEP_UID'] ); $node['guid'] = $aRow['DEP_UID']; $node['name'] = $aDepartment['DEPO_TITLE']; $node['parentUID'] = $aDepartment['DEP_PARENT']; @@ -277,9 +286,9 @@ class wsBase //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); + $c->addSelectColumn( 'COUNT(*)' ); + $c->add( UsersPeer::DEP_UID, $aRow['DEP_UID'] ); + $rs = UsersPeer::doSelectRS( $c ); $rs->next(); $row = $rs->getRow(); $count = $row[0]; @@ -291,7 +300,8 @@ class wsBase return $result; } catch (Exception $e) { - $result[] = array('guid' => $e->getMessage(), 'name' => $e->getMessage()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } @@ -299,35 +309,40 @@ class wsBase /** * Get case list + * * @param string $userId * @return $result will return an object */ - public function caseList($userId) + 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); + $result = array (); + $oCriteria = new Criteria( 'workflow' ); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn( ApplicationPeer::APP_UID ); + $oCriteria->addSelectColumn( ApplicationPeer::APP_NUMBER ); + $oCriteria->addSelectColumn( ApplicationPeer::APP_STATUS ); + $oCriteria->addSelectColumn( AppDelegationPeer::DEL_INDEX ); + $oCriteria->addAsColumn( 'CASE_TITLE', 'C1.CON_VALUE' ); + $oCriteria->addAlias( "C1", 'CONTENT' ); + $caseTitleConds = array (); + $caseTitleConds[] = array (ApplicationPeer::APP_UID,'C1.CON_ID' + ); + $caseTitleConds[] = array ('C1.CON_CATEGORY',$del . 'APP_TITLE' . $del + ); + $caseTitleConds[] = array ('C1.CON_LANG',$del . SYS_LANG . $del + ); + $oCriteria->addJoinMC( $caseTitleConds, Criteria::LEFT_JOIN ); - $oCriteria->addJoin(ApplicationPeer::APP_UID, AppDelegationPeer::APP_UID, Criteria::LEFT_JOIN); + $oCriteria->addJoin( ApplicationPeer::APP_UID, AppDelegationPeer::APP_UID, Criteria::LEFT_JOIN ); - $oCriteria->add(ApplicationPeer::APP_STATUS , array('TO_DO','DRAFT'), Criteria::IN); - $oCriteria->add(AppDelegationPeer::USR_UID, $userId); - $oCriteria->add(AppDelegationPeer::DEL_FINISH_DATE, null, Criteria::ISNULL); - $oCriteria->addDescendingOrderByColumn(ApplicationPeer::APP_NUMBER); - $oDataset = ApplicationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $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()) { @@ -339,22 +354,14 @@ class wsBase 'delIndex' => $aRow['DEL_INDEX'] ); */ - $result[] = array( - 'guid' => $aRow['APP_UID'], - 'name' => $aRow['APP_NUMBER'], - '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() + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage(),'status' => $e->getMessage(),'status' => $e->getMessage() ); return $result; @@ -363,36 +370,30 @@ class wsBase /** * Get unassigned case list + * * @param string $userId * @return $result will return an object */ - public function unassignedCaseList($userId) + public function unassignedCaseList ($userId) { try { - $result = array(); + $result = array (); $oAppCache = new AppCacheView(); - $Criteria = $oAppCache->getUnassignedListCriteria($userId); - $oDataset = AppCacheViewPeer::doSelectRS($Criteria); - $oDataset -> setFetchmode(ResultSet::FETCHMODE_ASSOC); + $Criteria = $oAppCache->getUnassignedListCriteria( $userId ); + $oDataset = AppCacheViewPeer::doSelectRS( $Criteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); while ($aRow = $oDataset->getRow()) { - $result[] = array( - 'guid' => $aRow['APP_UID'], - 'name' => $aRow['APP_NUMBER'], - 'delIndex' => $aRow['DEL_INDEX'] + $result[] = array ('guid' => $aRow['APP_UID'],'name' => $aRow['APP_NUMBER'],'delIndex' => $aRow['DEL_INDEX'] ); - $oDataset-> next(); + $oDataset->next(); } return $result; } catch (Exception $e) { - $result[] = array( - 'guid' => $e->getMessage(), - 'name' => $e->getMessage(), - 'status' => $e->getMessage(), - 'status' => $e->getMessage() + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage(),'status' => $e->getMessage(),'status' => $e->getMessage() ); return $result; @@ -401,29 +402,32 @@ class wsBase /** * get all groups + * * @param none * @return $result will return an object */ - public function userList() + 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); + $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']); + $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()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } @@ -431,36 +435,37 @@ class wsBase /** * get list of all the available triggers in a workspace + * * @param none * @return $result will return an object */ - public function triggerList() + 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'); + $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); + $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 = 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'] + $result[] = array ('guid' => $aRow['TRI_UID'],'name' => $aRow['TITLE'],'processId' => $aRow['PRO_UID'] ); $oDataset->next(); @@ -468,7 +473,8 @@ class wsBase return $result; } catch (Exception $e) { - $result[] = array('guid' => $e->getMessage(), 'name' => $e->getMessage()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } @@ -476,41 +482,43 @@ class wsBase /** * get list of the uploaded documents for a given case + * * @param string $sApplicationUID * @param string $sUserUID * @return $result */ - public function inputDocumentList($sApplicationUID, $sUserUID) + public function inputDocumentList ($sApplicationUID, $sUserUID) { try { $oCase = new Cases(); - $fields = $oCase->loadCase($sApplicationUID); + $fields = $oCase->loadCase( $sApplicationUID ); $sProcessUID = $fields['PRO_UID']; $sTaskUID = ''; - $oCriteria = $oCase->getAllUploadedDocumentsCriteria($sProcessUID, $sApplicationUID, $sTaskUID, $sUserUID); + $oCriteria = $oCase->getAllUploadedDocumentsCriteria( $sProcessUID, $sApplicationUID, $sTaskUID, $sUserUID ); - $result = array(); + $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']; + 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']; + $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()); + $result[] = array ('guid' => $e->getMessage() + ); return $result; } @@ -518,23 +526,24 @@ class wsBase /** * input document process list + * * @param string $sProcessUID * @return $result will return an object */ - public function inputDocumentProcessList($sProcessUID) + public function inputDocumentProcessList ($sProcessUID) { try { global $_DBArray; - $_DBArray = (isset($_SESSION['_DBArray']) ? $_SESSION['_DBArray'] : ''); + $_DBArray = (isset( $_SESSION['_DBArray'] ) ? $_SESSION['_DBArray'] : ''); $oMap = new processMap(); - $oCriteria = $oMap->getInputDocumentsCriteria($sProcessUID); - $oDataset = InputDocumentPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oCriteria = $oMap->getInputDocumentsCriteria( $sProcessUID ); + $oDataset = InputDocumentPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); - $result = array(); + $result = array (); /* //not necesary for SOAP message @@ -546,27 +555,29 @@ class wsBase */ while ($aRow = $oDataset->getRow()) { - if ( $aRow['INP_DOC_TITLE'] == null) { + 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']; + $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 = array (); + $docrow['guid'] = $aRow['INP_DOC_UID']; + $docrow['name'] = $aRow['INP_DOC_TITLE']; $docrow['description'] = $aRow['INP_DOC_DESCRIPTION']; $result[] = $docrow; - $oDataset->next (); + $oDataset->next(); } //$_DBArray['inputDocArray'] = $inputDocArray; + return $result; } catch (Exception $e) { - $result[] = array('guid' => $e->getMessage()); + $result[] = array ('guid' => $e->getMessage() + ); return $result; } @@ -574,42 +585,44 @@ class wsBase /** * output document list + * * @param string $sApplicationUID * @param string $sUserUID * @return $result will return an object */ - public function outputDocumentList($sApplicationUID, $sUserUID) + public function outputDocumentList ($sApplicationUID, $sUserUID) { try { $oCase = new Cases(); - $fields = $oCase->loadCase($sApplicationUID); + $fields = $oCase->loadCase( $sApplicationUID ); $sProcessUID = $fields['PRO_UID']; $sTaskUID = ''; - $oCriteria = $oCase->getAllGeneratedDocumentsCriteria($sProcessUID, $sApplicationUID, $sTaskUID, $sUserUID); + $oCriteria = $oCase->getAllGeneratedDocumentsCriteria( $sProcessUID, $sApplicationUID, $sTaskUID, $sUserUID ); - $result = array(); + $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']; + 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['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']; + $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()); + $result[] = array ('guid' => $e->getMessage() + ); return $result; } @@ -617,19 +630,20 @@ class wsBase /** * remove document + * * @param string $appDocUid * @return $result will return an object */ - public function removeDocument($appDocUid) + public function removeDocument ($appDocUid) { try { $oAppDocument = new AppDocument(); - $oAppDocument->remove($appDocUid, 1); //always send version 1 - $result = new wsResponse(0, " $appDocUid"); + $oAppDocument->remove( $appDocUid, 1 ); //always send version 1 + $result = new wsResponse( 0, " $appDocUid" ); return $result; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -637,45 +651,51 @@ class wsBase /** * get task list + * * @param string $userId * @return $result will return an object */ - public function taskList($userId) + public function taskList ($userId) { try { - g::loadClass('groups'); + g::loadClass( 'groups' ); $oGroup = new Groups(); - $aGroups = $oGroup->getActiveGroupsForAnUser($userId); + $aGroups = $oGroup->getActiveGroupsForAnUser( $userId ); - $result = array(); - $oCriteria = new Criteria('workflow'); + $result = array (); + $oCriteria = new Criteria( 'workflow' ); $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn(TaskPeer::TAS_UID); + $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->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); + $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 = TaskPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); while ($aRow = $oDataset->getRow()) { - $result[] = array('guid' => $aRow['TAS_UID'], 'name' => $aRow['TAS_TITLE']); + $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()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } @@ -683,6 +703,7 @@ class wsBase /** * send message + * * @param string $caseId * @param string $sFrom * @param string $sTo @@ -693,55 +714,40 @@ class wsBase * @param $appFields = null * @return $result will return an object */ - public function sendMessage( - $caseId, - $sFrom, - $sTo, - $sCc, - $sBcc, - $sSubject, - $sTemplate, - $appFields=null, - $aAttachment=null - ) { + public function sendMessage ($caseId, $sFrom, $sTo, $sCc, $sBcc, $sSubject, $sTemplate, $appFields = null, $aAttachment = null) + { try { - G::loadClass('system'); + G::loadClass( 'system' ); $aSetup = System::getEmailConfiguration(); - $passwd =$aSetup['MESS_PASSWORD']; - $passwdDec = G::decrypt($passwd,'EMAILENCRYPT'); - $auxPass = explode('hash:', $passwdDec); - if (count($auxPass) > 1) { - if (count($auxPass) == 2) { + $passwd = $aSetup['MESS_PASSWORD']; + $passwdDec = G::decrypt( $passwd, 'EMAILENCRYPT' ); + $auxPass = explode( 'hash:', $passwdDec ); + if (count( $auxPass ) > 1) { + if (count( $auxPass ) == 2) { $passwd = $auxPass[1]; } else { - array_shift($auxPass); - $passwd = implode('', $auxPass); + array_shift( $auxPass ); + $passwd = implode( '', $auxPass ); } - } + } $aSetup['MESS_PASSWORD'] = $passwd; $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'] - )); + $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); + G::mk_dir( $pathEmail, 0777, true ); - if (!file_exists($fileTemplate)) { + if (! file_exists( $fileTemplate )) { $data['FILE_TEMPLATE'] = $fileTemplate; - $result = new wsResponse(28, G::LoadTranslation('ID_TEMPLATE_FILE_NOT_EXIST', SYS_LANG, $data)); + $result = new wsResponse( 28, G::LoadTranslation( 'ID_TEMPLATE_FILE_NOT_EXIST', SYS_LANG, $data ) ); return $result; } @@ -749,98 +755,77 @@ class wsBase if ($appFields == null) { $Fields = $oldFields['APP_DATA']; } else { - $Fields = array_merge($oldFields['APP_DATA'], $appFields); + $Fields = array_merge( $oldFields['APP_DATA'], $appFields ); } - $templateContents = file_get_contents($fileTemplate); + $templateContents = file_get_contents( $fileTemplate ); //$sContent = G::unhtmlentities($sContent); - $iAux = 0; - $iOcurrences = preg_match_all('/\@(?:([\>])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*(?:[\\\\][\w\W])?)*)\))((?:\s*\[[\'"]?\w+[\'"]?\])+)?/', $templateContents, $aMatch, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); + $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 - ); + 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]; + $sGridName = $aMatch[2][$i][0]; $sStringToRepeat = $aMatch2[1][0][0]; - if (isset($Fields[$sGridName])) { - if (is_array($Fields[$sGridName])) { + if (isset( $Fields[$sGridName] )) { + if (is_array( $Fields[$sGridName] )) { $sAux = ''; foreach ($Fields[$sGridName] as $aRow) { - $sAux .= G::replaceDataField($sStringToRepeat, $aRow); + $sAux .= G::replaceDataField( $sStringToRepeat, $aRow ); } } } - $templateContents = str_replace( - '@>' . $sGridName . $sStringToRepeat . '@<' . $sGridName, - $sAux, - $templateContents - ); + $templateContents = str_replace( '@>' . $sGridName . $sStringToRepeat . '@<' . $sGridName, $sAux, $templateContents ); } } - $sBody = G::replaceDataField( $templateContents, $Fields); - $hasEmailFrom = preg_match('/(.+)@(.+)\.(.+)/', $sFrom, $match); + $sBody = G::replaceDataField( $templateContents, $Fields ); + $hasEmailFrom = preg_match( '/(.+)@(.+)\.(.+)/', $sFrom, $match ); - if (!$hasEmailFrom || strpos($sFrom, $aSetup['MESS_ACCOUNT']) === false) { - $sFrom = '"' . stripslashes($sFrom) . '" <' . $aSetup['MESS_ACCOUNT'] . ">"; + if (! $hasEmailFrom || strpos( $sFrom, $aSetup['MESS_ACCOUNT'] ) === false) { + $sFrom = '"' . stripslashes( $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' + $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->create( $messageArray ); $oSpool->sendMail(); - if ( $oSpool->status == 'sent' ) { - $result = new wsResponse(0, G::loadTranslation ('ID_MESSAGE_SENT') . ": ". $sTo); + if ($oSpool->status == 'sent') { + $result = new wsResponse( 0, G::loadTranslation( 'ID_MESSAGE_SENT' ) . ": " . $sTo ); } else { - $result = new wsResponse(29, $oSpool->status . ' ' . $oSpool->error . print_r ($aSetup ,1 )); + $result = new wsResponse( 29, $oSpool->status . ' ' . $oSpool->error . print_r( $aSetup, 1 ) ); } return $result; } catch (Exception $e) { - return new wsResponse(100, $e->getMessage()); + return new wsResponse( 100, $e->getMessage() ); } } /** * get case information + * * @param string $caseId * @param string $iDelIndex * @return $result will return an object */ - public function getCaseInfo($caseId, $iDelIndex) + public function getCaseInfo ($caseId, $iDelIndex) { try { $oCase = new Cases(); - $aRows = $oCase->loadCase($caseId, $iDelIndex); + $aRows = $oCase->loadCase( $caseId, $iDelIndex ); - if (count($aRows) == 0) { + if (count( $aRows ) == 0) { $data['CASE_NUMBER'] = $caseNumber; - $result = new wsResponse(16, G::loadTranslation('ID_CASE_DOES_NOT_EXIST', SYS_LANG, $data)); + $result = new wsResponse( 16, G::loadTranslation( 'ID_CASE_DOES_NOT_EXIST', SYS_LANG, $data ) ); return $result; } @@ -848,41 +833,41 @@ class wsBase $oProcess = new Process(); try { - $uFields = $oProcess->load($aRows['PRO_UID']); + $uFields = $oProcess->load( $aRows['PRO_UID'] ); $processName = $uFields['PRO_TITLE']; } catch (Exception $e) { $processName = ''; } - $result = new wsResponse(0, G::loadTranslation ('ID_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 = new wsResponse( 0, G::loadTranslation( 'ID_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']; - $result->updateDate = $aRows['UPDATE_DATE']; + $result->processId = $aRows['PRO_UID']; + $result->processName = $processName; + $result->createDate = $aRows['CREATE_DATE']; + $result->updateDate = $aRows['UPDATE_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 = 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); + $oCriteria->addAscendingOrderByColumn( AppDelegationPeer::DEL_INDEX ); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $aCurrentUsers = array(); + $aCurrentUsers = array (); while ($oDataset->next()) { $aAppDel = $oDataset->getRow(); @@ -890,8 +875,8 @@ class wsBase $oUser = new Users(); try { - $oUser->load($aAppDel['USR_UID']); - $uFields = $oUser->toArray(BasePeer::TYPE_FIELDNAME); + $oUser->load( $aAppDel['USR_UID'] ); + $uFields = $oUser->toArray( BasePeer::TYPE_FIELDNAME ); $currentUserName = $oUser->getUsrFirstname() . ' ' . $oUser->getUsrLastname(); } catch (Exception $e) { $currentUserName = ''; @@ -900,19 +885,19 @@ class wsBase $oTask = new Task(); try { - $uFields = $oTask->load($aAppDel['TAS_UID']); + $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->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; } @@ -921,7 +906,7 @@ class wsBase return $result; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -929,67 +914,61 @@ class wsBase /** * Create an new user + * * @param string sessionId : The session ID. - * @param string userName : The username for the new user. + * @param string userName : 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). - * @param string dueDate : Optional parameter. The expiration date must be a string in the format "yyyy-mm-dd". - * @param string status : Optional parameter. The user's status, such as "ACTIVE", "INACTIVE" or "VACATION". + * @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). + * @param string dueDate : Optional parameter. The expiration date must be a string in the format "yyyy-mm-dd". + * @param string status : Optional parameter. The user's status, such as "ACTIVE", "INACTIVE" or "VACATION". * @return $result will return an object */ - public function createUser($userName, $firstName, $lastName, $email, $role, $password, $dueDate=null, $status=null) + public function createUser ($userName, $firstName, $lastName, $email, $role, $password, $dueDate = null, $status = null) { try { global $RBAC; $RBAC->initRBAC(); - if (empty($userName)) { - $result = new wsCreateUserResponse(25, G::loadTranslation("ID_USERNAME_REQUIRED"), null); + if (empty( $userName )) { + $result = new wsCreateUserResponse( 25, G::loadTranslation( "ID_USERNAME_REQUIRED" ), null ); return $result; } - if (empty($firstName)) { - $result = new wsCreateUserResponse(27, G::loadTranslation("ID_MSG_ERROR_USR_FIRSTNAME"), null); + if (empty( $firstName )) { + $result = new wsCreateUserResponse( 27, G::loadTranslation( "ID_MSG_ERROR_USR_FIRSTNAME" ), null ); return $result; } - if (empty($password)) { - $result = new wsCreateUserResponse(26, G::loadTranslation("ID_PASSWD_REQUIRED"), null); + if (empty( $password )) { + $result = new wsCreateUserResponse( 26, G::loadTranslation( "ID_PASSWD_REQUIRED" ), null ); return $result; } $mktimeDueDate = 0; - if (!empty($dueDate)) { - if (!preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $dueDate, $arrayMatch)) { - $result = new wsCreateUserResponse(-1, G::loadTranslation("ID_INVALID_DATA") . " $dueDate", null); + if (! empty( $dueDate )) { + if (! preg_match( "/^(\d{4})-(\d{2})-(\d{2})$/", $dueDate, $arrayMatch )) { + $result = new wsCreateUserResponse( - 1, G::loadTranslation( "ID_INVALID_DATA" ) . " $dueDate", null ); return $result; } else { - $mktimeDueDate = mktime( - 0, - 0, - 0, - intval($arrayMatch[2]), - intval($arrayMatch[3]), - intval($arrayMatch[1]) - ); + $mktimeDueDate = mktime( 0, 0, 0, intval( $arrayMatch[2] ), intval( $arrayMatch[3] ), intval( $arrayMatch[1] ) ); } } else { - $mktimeDueDate = mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1); + $mktimeDueDate = mktime( 0, 0, 0, date( "m" ), date( "d" ), date( "Y" ) + 1 ); } - if (!empty($status)) { + if (! empty( $status )) { if ($status != "ACTIVE" && $status != "INACTIVE" && $status != "VACATION") { - $result = new wsCreateUserResponse(-1, G::loadTranslation("ID_INVALID_DATA") . " $status", null); + $result = new wsCreateUserResponse( - 1, G::loadTranslation( "ID_INVALID_DATA" ) . " $status", null ); return $result; } @@ -997,95 +976,88 @@ class wsBase $status = "ACTIVE"; } - $arrayRole = $RBAC->loadById($role); + $arrayRole = $RBAC->loadById( $role ); $strRole = null; - if (is_array($arrayRole)) { + if (is_array( $arrayRole )) { $strRole = $arrayRole["ROL_CODE"]; } else { $strRole = $role; - if ($RBAC->verifyByCode($role) == 0) { - $data = array(); + if ($RBAC->verifyByCode( $role ) == 0) { + $data = array (); $data["ROLE"] = $role; - $result = new wsCreateUserResponse(6, G::loadTranslation("ID_INVALID_ROLE", SYS_LANG, $data), null); + $result = new wsCreateUserResponse( 6, G::loadTranslation( "ID_INVALID_ROLE", SYS_LANG, $data ), null ); return $result; } } - if (strlen($password) > 20) { - $result = new wsCreateUserResponse(-1, G::loadTranslation("ID_PASSWORD_SURPRASES"), null); + if (strlen( $password ) > 20) { + $result = new wsCreateUserResponse( - 1, G::loadTranslation( "ID_PASSWORD_SURPRASES" ), null ); return $result; } - if ($RBAC->verifyUser($userName) == 1) { - $data = array(); + if ($RBAC->verifyUser( $userName ) == 1) { + $data = array (); $data["USER_ID"] = $userName; - $result = new wsCreateUserResponse( - 7, - G::loadTranslation("ID_USERNAME_ALREADY_EXISTS", SYS_LANG, $data), - null - ); + $result = new wsCreateUserResponse( 7, G::loadTranslation( "ID_USERNAME_ALREADY_EXISTS", SYS_LANG, $data ), null ); return $result; } //Set fields - $arrayData = array(); + $arrayData = array (); - $arrayData["USR_USERNAME"] = $userName; - $arrayData["USR_PASSWORD"] = md5($password); - $arrayData["USR_FIRSTNAME"] = $firstName; - $arrayData["USR_LASTNAME"] = $lastName; - $arrayData["USR_EMAIL"] = $email; - $arrayData["USR_DUE_DATE"] = $mktimeDueDate; - $arrayData["USR_CREATE_DATE"] = date("Y-m-d H:i:s"); - $arrayData["USR_UPDATE_DATE"] = date("Y-m-d H:i:s"); - $arrayData["USR_BIRTHDAY"] = date("Y-m-d"); + $arrayData["USR_USERNAME"] = $userName; + $arrayData["USR_PASSWORD"] = md5( $password ); + $arrayData["USR_FIRSTNAME"] = $firstName; + $arrayData["USR_LASTNAME"] = $lastName; + $arrayData["USR_EMAIL"] = $email; + $arrayData["USR_DUE_DATE"] = $mktimeDueDate; + $arrayData["USR_CREATE_DATE"] = date( "Y-m-d H:i:s" ); + $arrayData["USR_UPDATE_DATE"] = date( "Y-m-d H:i:s" ); + $arrayData["USR_BIRTHDAY"] = date( "Y-m-d" ); $arrayData["USR_AUTH_USER_DN"] = ""; - $arrayData["USR_STATUS"] = ($status == "ACTIVE")? 1 : 0; + $arrayData["USR_STATUS"] = ($status == "ACTIVE") ? 1 : 0; - $userUid = $RBAC->createUser($arrayData, $strRole); + $userUid = $RBAC->createUser( $arrayData, $strRole ); - $arrayData["USR_UID"] = $userUid; - $arrayData["USR_STATUS"] = $status; + $arrayData["USR_UID"] = $userUid; + $arrayData["USR_STATUS"] = $status; //$arrayData["USR_PASSWORD"] = md5($userUid); - $arrayData["USR_COUNTRY"] = ""; - $arrayData["USR_CITY"] = ""; + $arrayData["USR_COUNTRY"] = ""; + $arrayData["USR_CITY"] = ""; $arrayData["USR_LOCATION"] = ""; - $arrayData["USR_ADDRESS"] = ""; - $arrayData["USR_PHONE"] = ""; + $arrayData["USR_ADDRESS"] = ""; + $arrayData["USR_PHONE"] = ""; $arrayData["USR_ZIP_CODE"] = ""; $arrayData["USR_POSITION"] = ""; //$arrayData["USR_RESUME"] - $arrayData["USR_ROLE"] = $strRole ; + $arrayData["USR_ROLE"] = $strRole; //$arrayData["USR_REPLACED_BY"] + $user = new Users(); - $user->create($arrayData); + $user->create( $arrayData ); //Response - $data = array(); + $data = array (); $data["FIRSTNAME"] = $firstName; $data["LASTNAME"] = $lastName; $data["USER_ID"] = $userName; - $res = new wsResponse(0, G::loadTranslation("ID_USER_CREATED_SUCCESSFULLY", SYS_LANG, $data)); + $res = new wsResponse( 0, G::loadTranslation( "ID_USER_CREATED_SUCCESSFULLY", SYS_LANG, $data ) ); - $result = array( - "status_code" => $res->status_code, - "message" => $res->message, - "userUID" => $userUid, - "timestamp" => $res->timestamp + $result = array ("status_code" => $res->status_code,"message" => $res->message,"userUID" => $userUid,"timestamp" => $res->timestamp ); return $result; } catch (Exception $e) { - $result = wsCreateUserResponse(100 , $e->getMessage(), null); + $result = wsCreateUserResponse( 100, $e->getMessage(), null ); return $result; } @@ -1093,75 +1065,60 @@ class wsBase /** * Update user - * @param string userUid : The user UID. - * @param string userName : The username for the user. + * + * @param string userUid : The user UID. + * @param string userName : The username for the user. * @param string firstName : Optional parameter. The user's first name. - * @param string lastName : Optional parameter. The user's last name. - * @param string email : Optional parameter. The user's email address. - * @param string dueDate : Optional parameter. The expiration date must be a string in the format "yyyy-mm-dd". - * @param string status : Optional parameter. The user's status, such as "ACTIVE", "INACTIVE" or "VACATION". - * @param string role : Optional parameter. The user's role, such - * as "PROCESSMAKER_ADMIN" or "PROCESSMAKER_OPERATOR". - * @param string password : Optional parameter. The user's password such as "Be@gle2" (It will be automatically - * encrypted with an MD5 hash). + * @param string lastName : Optional parameter. The user's last name. + * @param string email : Optional parameter. The user's email address. + * @param string dueDate : Optional parameter. The expiration date must be a string in the format "yyyy-mm-dd". + * @param string status : Optional parameter. The user's status, such as "ACTIVE", "INACTIVE" or "VACATION". + * @param string role : Optional parameter. The user's role, such + * as "PROCESSMAKER_ADMIN" or "PROCESSMAKER_OPERATOR". + * @param string password : Optional parameter. 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 updateUser( - $userUid, - $userName, - $firstName=null, - $lastName=null, - $email=null, - $dueDate=null, - $status=null, - $role=null, - $password=null - ) { + public function updateUser ($userUid, $userName, $firstName = null, $lastName = null, $email = null, $dueDate = null, $status = null, $role = null, $password = null) + { try { global $RBAC; $RBAC->initRBAC(); - if (empty($userUid)) { - $result = new wsResponse(25, G::LoadTranslation("ID_REQUIRED_FIELD") . " userUid"); + if (empty( $userUid )) { + $result = new wsResponse( 25, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " userUid" ); return $result; } - if (empty($userName)) { - $result = new wsResponse(25, G::LoadTranslation("ID_USERNAME_REQUIRED")); + if (empty( $userName )) { + $result = new wsResponse( 25, G::LoadTranslation( "ID_USERNAME_REQUIRED" ) ); return $result; } - if ($RBAC->verifyUserId($userUid) == 0) { - $result = new wsResponse(3, G::loadTranslation("ID_USER_NOT_REGISTERED_SYSTEM")); + if ($RBAC->verifyUserId( $userUid ) == 0) { + $result = new wsResponse( 3, G::loadTranslation( "ID_USER_NOT_REGISTERED_SYSTEM" ) ); return $result; } $mktimeDueDate = 0; - if (!empty($dueDate)) { - if (!preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $dueDate, $arrayMatch)) { - $result = new wsResponse(-1, G::LoadTranslation("ID_INVALID_DATA") . " $dueDate"); + if (! empty( $dueDate )) { + if (! preg_match( "/^(\d{4})-(\d{2})-(\d{2})$/", $dueDate, $arrayMatch )) { + $result = new wsResponse( - 1, G::LoadTranslation( "ID_INVALID_DATA" ) . " $dueDate" ); return $result; } else { - $mktimeDueDate = mktime( - 0, - 0, - 0, - intval($arrayMatch[2]), - intval($arrayMatch[3]), - intval($arrayMatch[1]) - ); + $mktimeDueDate = mktime( 0, 0, 0, intval( $arrayMatch[2] ), intval( $arrayMatch[3] ), intval( $arrayMatch[1] ) ); } } - if (!empty($status)) { + if (! empty( $status )) { if ($status != "ACTIVE" && $status != "INACTIVE" && $status != "VACATION") { - $result = new wsResponse(-1, G::LoadTranslation("ID_INVALID_DATA") . " $status"); + $result = new wsResponse( - 1, G::LoadTranslation( "ID_INVALID_DATA" ) . " $status" ); return $result; } @@ -1169,61 +1126,61 @@ class wsBase $strRole = null; - if (!empty($role)) { - $arrayRole = $RBAC->loadById($role); + if (! empty( $role )) { + $arrayRole = $RBAC->loadById( $role ); - if (is_array($arrayRole)) { + if (is_array( $arrayRole )) { $strRole = $arrayRole["ROL_CODE"]; } else { $strRole = $role; - if ($RBAC->verifyByCode($role) == 0) { - $data = array(); + if ($RBAC->verifyByCode( $role ) == 0) { + $data = array (); $data["ROLE"] = $role; - $result = new wsResponse(6, G::LoadTranslation("ID_INVALID_ROLE", SYS_LANG, $data)); + $result = new wsResponse( 6, G::LoadTranslation( "ID_INVALID_ROLE", SYS_LANG, $data ) ); return $result; } } } - if (!empty($password) && strlen($password) > 20) { - $result = new wsResponse(-1, G::LoadTranslation("ID_PASSWORD_SURPRASES")); + if (! empty( $password ) && strlen( $password ) > 20) { + $result = new wsResponse( - 1, G::LoadTranslation( "ID_PASSWORD_SURPRASES" ) ); return $result; } $criteria = new Criteria(); - $criteria->addSelectColumn(UsersPeer::USR_UID); - $criteria->add(UsersPeer::USR_USERNAME, $userName); - $criteria->add(UsersPeer::USR_UID, $userUid, Criteria::NOT_EQUAL); - $rs = UsersPeer::doSelectRS($criteria); + $criteria->addSelectColumn( UsersPeer::USR_UID ); + $criteria->add( UsersPeer::USR_USERNAME, $userName ); + $criteria->add( UsersPeer::USR_UID, $userUid, Criteria::NOT_EQUAL ); + $rs = UsersPeer::doSelectRS( $criteria ); if ($rs->next()) { - $data = array(); + $data = array (); $data["USER_ID"] = $userName; - $result = new wsResponse(7, G::LoadTranslation("ID_USERNAME_ALREADY_EXISTS", SYS_LANG, $data)); + $result = new wsResponse( 7, G::LoadTranslation( "ID_USERNAME_ALREADY_EXISTS", SYS_LANG, $data ) ); return $result; } //Set fields - $arrayData = array(); + $arrayData = array (); - $arrayData["USR_UID"] = $userUid; + $arrayData["USR_UID"] = $userUid; $arrayData["USR_USERNAME"] = $userName; - if (!empty($firstName)) { + if (! empty( $firstName )) { $arrayData["USR_FIRSTNAME"] = $firstName; } - if (!empty($lastName)) { + if (! empty( $lastName )) { $arrayData["USR_LASTNAME"] = $lastName; } - if (!empty($email)) { + if (! empty( $email )) { $arrayData["USR_EMAIL"] = $email; } @@ -1231,9 +1188,9 @@ class wsBase $arrayData["USR_DUE_DATE"] = $mktimeDueDate; } - $arrayData["USR_UPDATE_DATE"] = date("Y-m-d H:i:s"); + $arrayData["USR_UPDATE_DATE"] = date( "Y-m-d H:i:s" ); - if (!empty($status)) { + if (! empty( $status )) { $arrayData["USR_STATUS"] = $status; } @@ -1241,33 +1198,30 @@ class wsBase $arrayData["USR_ROLE"] = $strRole; } - if (!empty($password)) { - $arrayData["USR_PASSWORD"] = md5($password); + if (! empty( $password )) { + $arrayData["USR_PASSWORD"] = md5( $password ); } //Update user if ($strRole != null) { - $RBAC->updateUser($arrayData, $strRole); + $RBAC->updateUser( $arrayData, $strRole ); } else { - $RBAC->updateUser($arrayData); + $RBAC->updateUser( $arrayData ); } $user = new Users(); - $user->update($arrayData); + $user->update( $arrayData ); //Response //$res = new wsResponse(0, G::LoadTranslation("ID_OBJECT_UPDATE")); - $res = new wsResponse(0, G::LoadTranslation("ID_UPDATED_SUCCESSFULLY")); + $res = new wsResponse( 0, G::LoadTranslation( "ID_UPDATED_SUCCESSFULLY" ) ); - $result = array( - "status_code" => $res->status_code, - "message" => $res->message, - "timestamp" => $res->timestamp + $result = array ("status_code" => $res->status_code,"message" => $res->message,"timestamp" => $res->timestamp ); return $result; } catch (Exception $e) { - $result = wsResponse(100, $e->getMessage()); + $result = wsResponse( 100, $e->getMessage() ); return $result; } @@ -1275,32 +1229,29 @@ class wsBase /** * create Group + * * @param string $groupName * @return $result will return an object */ - public function createGroup($groupName) + public function createGroup ($groupName) { try { - if (trim($groupName) == '') { - $result = new wsCreateGroupResponse(25, G::loadTranslation('ID_GROUP_NAME_REQUIRED'), ''); + if (trim( $groupName ) == '') { + $result = new wsCreateGroupResponse( 25, G::loadTranslation( 'ID_GROUP_NAME_REQUIRED' ), '' ); return $result; } $group = new Groupwf(); $grpRow['GRP_TITLE'] = $groupName; - $groupId = $group->create($grpRow); + $groupId = $group->create( $grpRow ); $data['GROUP_NAME'] = $groupName; - $result = new wsCreateGroupResponse( - 0, - G::loadTranslation('ID_GROUP_CREATED_SUCCESSFULLY', SYS_LANG, $data), - $groupId - ); + $result = new wsCreateGroupResponse( 0, G::loadTranslation( 'ID_GROUP_CREATED_SUCCESSFULLY', SYS_LANG, $data ), $groupId ); return $result; } catch (Exception $e) { - $result = wsCreateGroupResponse(100 , $e->getMessage(), ''); + $result = wsCreateGroupResponse( 100, $e->getMessage(), '' ); return $result; } @@ -1308,33 +1259,30 @@ class wsBase /** * 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) + public function createDepartment ($departmentName, $parentUID) { try { - if (trim($departmentName) == '') { - $result = new wsCreateDepartmentResponse(25, G::loadTranslation('ID_DEPARTMENT_NAME_REQUIRED'), ''); + if (trim( $departmentName ) == '') { + $result = new wsCreateDepartmentResponse( 25, G::loadTranslation( 'ID_DEPARTMENT_NAME_REQUIRED' ), '' ); return $result; } $department = new Department(); - if (($parentUID != '') && !($department->existsDepartment($parentUID))) { - $result = new wsCreateDepartmentResponse( - 26, - G::loadTranslation('ID_PARENT_DEPARTMENT_NOT_EXIST'), - $parentUID - ); + if (($parentUID != '') && ! ($department->existsDepartment( $parentUID ))) { + $result = new wsCreateDepartmentResponse( 26, G::loadTranslation( 'ID_PARENT_DEPARTMENT_NOT_EXIST' ), $parentUID ); return $result; } - if ($department->checkDepartmentName($departmentName, $parentUID)) { - $result = new wsCreateDepartmentResponse(27, G::loadTranslation('ID_DEPARTMENT_EXISTS'), ''); + if ($department->checkDepartmentName( $departmentName, $parentUID )) { + $result = new wsCreateDepartmentResponse( 27, G::loadTranslation( 'ID_DEPARTMENT_EXISTS' ), '' ); return $result; } @@ -1342,21 +1290,17 @@ class wsBase $row['DEP_TITLE'] = $departmentName; $row['DEP_PARENT'] = $parentUID; - $departmentId = $department->create($row); + $departmentId = $department->create( $row ); $data['DEPARTMENT_NAME'] = $departmentName; - $data['PARENT_UID'] = $parentUID; + $data['PARENT_UID'] = $parentUID; $data['DEPARTMENT_NAME'] = $departmentName; - $result = new wsCreateDepartmentResponse( - 0, - G::loadTranslation('ID_DEPARTMENT_CREATED_SUCCESSFULLY', SYS_LANG, $data), - $departmentId - ); + $result = new wsCreateDepartmentResponse( 0, G::loadTranslation( 'ID_DEPARTMENT_CREATED_SUCCESSFULLY', SYS_LANG, $data ), $departmentId ); return $result; } catch (Exception $e) { - $result = wsCreateDepartmentResponse(100, $e->getMessage(), ''); + $result = wsCreateDepartmentResponse( 100, $e->getMessage(), '' ); return $result; } @@ -1364,49 +1308,50 @@ class wsBase /** * remove user from group + * * @param string $appDocUid * @return $result will return an object */ - public function removeUserFromGroup($userId, $groupId) + public function removeUserFromGroup ($userId, $groupId) { try { - G::LoadClass('groups'); + G::LoadClass( 'groups' ); global $RBAC; $RBAC->initRBAC(); - $user=$RBAC->verifyUserId($userId); + $user = $RBAC->verifyUserId( $userId ); if ($user == 0) { - $result = new wsResponse(3, G::loadTranslation('ID_USER_NOT_REGISTERED_SYSTEM')); + $result = new wsResponse( 3, G::loadTranslation( 'ID_USER_NOT_REGISTERED_SYSTEM' ) ); return $result; } - $groups = new Groups; - $very_group = $groups->verifyGroup($groupId); + $groups = new Groups(); + $very_group = $groups->verifyGroup( $groupId ); if ($very_group == 0) { - $result = new wsResponse(9, G::loadTranslation('ID_GROUP_NOT_REGISTERED_SYSTEM')); + $result = new wsResponse( 9, G::loadTranslation( 'ID_GROUP_NOT_REGISTERED_SYSTEM' ) ); return $result; } - $very_user = $groups->verifyUsertoGroup($groupId, $userId); + $very_user = $groups->verifyUsertoGroup( $groupId, $userId ); if ($very_user == 1) { $oGroup = new Groups(); - $oGroup->removeUserOfGroup($groupId, $userId); - $result = new wsResponse (0, G::loadTranslation('ID_COMMAND_EXECUTED_SUCCESSFULY')); + $oGroup->removeUserOfGroup( $groupId, $userId ); + $result = new wsResponse( 0, G::loadTranslation( 'ID_COMMAND_EXECUTED_SUCCESSFULY' ) ); return $result; } //$oGroup->removeUserOfGroup($_POST['GRP_UID'], $_POST['USR_UID']); - $result = new wsResponse(8, G::loadTranslation('ID_USER_NOT_REGISTERED_GROUP')); + $result = new wsResponse( 8, G::loadTranslation( 'ID_USER_NOT_REGISTERED_GROUP' ) ); return $result; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -1418,45 +1363,46 @@ class wsBase /** * assigns a user to a group + * * @param string $userId * @param string $groupId * @return $result will return an object */ - public function assignUserToGroup($userId, $groupId) + public function assignUserToGroup ($userId, $groupId) { try { global $RBAC; $RBAC->initRBAC(); - $user = $RBAC->verifyUserId($userId); + $user = $RBAC->verifyUserId( $userId ); if ($user == 0) { - $result = new wsResponse(3, G::loadTranslation('ID_USER_NOT_REGISTERED_SYSTEM')); + $result = new wsResponse( 3, G::loadTranslation( 'ID_USER_NOT_REGISTERED_SYSTEM' ) ); return $result; } $groups = new Groups(); - $very_group = $groups->verifyGroup($groupId); + $very_group = $groups->verifyGroup( $groupId ); if ($very_group == 0) { - $result = new wsResponse(9, G::loadTranslation('ID_GROUP_NOT_REGISTERED_SYSTEM')); + $result = new wsResponse( 9, G::loadTranslation( 'ID_GROUP_NOT_REGISTERED_SYSTEM' ) ); return $result; } - $very_user = $groups->verifyUsertoGroup($groupId, $userId); + $very_user = $groups->verifyUsertoGroup( $groupId, $userId ); if ($very_user == 1) { - $result = new wsResponse(8, G::loadTranslation('ID_USER_ALREADY_EXISTS_GROUP')); + $result = new wsResponse( 8, G::loadTranslation( 'ID_USER_ALREADY_EXISTS_GROUP' ) ); return $result; } - $groups->addUserToGroup($groupId, $userId); - $result = new wsResponse(0, G::loadTranslation('ID_COMMAND_EXECUTED_SUCCESSFULY')); + $groups->addUserToGroup( $groupId, $userId ); + $result = new wsResponse( 0, G::loadTranslation( 'ID_COMMAND_EXECUTED_SUCCESSFULY' ) ); return $result; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -1464,46 +1410,44 @@ class wsBase /** * 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) + public function assignUserToDepartment ($userId, $depId, $manager) { try { global $RBAC; $RBAC->initRBAC(); - $user = $RBAC->verifyUserId($userId); + $user = $RBAC->verifyUserId( $userId ); - if ($user == 0 ) { - $result = new wsResponse(3, G::loadTranslation('ID_USER_NOT_REGISTERED_SYSTEM')); + if ($user == 0) { + $result = new wsResponse( 3, G::loadTranslation( 'ID_USER_NOT_REGISTERED_SYSTEM' ) ); return $result; } - $deps = new Department; + $deps = new Department(); - if (!$deps->existsDepartment($depId)) { + if (! $deps->existsDepartment( $depId )) { $data['DEP_ID'] = $depId; - $result = new wsResponse( - 100, - G::loadTranslation('ID_DEPARTMENT_NOT_REGISTERED_SYSTEM', SYS_LANG, $data) - ); + $result = new wsResponse( 100, G::loadTranslation( 'ID_DEPARTMENT_NOT_REGISTERED_SYSTEM', SYS_LANG, $data ) ); return $result; } - if (!$deps->existsUserInDepartment($depId, $userId)) { - $deps->addUserToDepartment($depId, $userId, $manager, true); + if (! $deps->existsUserInDepartment( $depId, $userId )) { + $deps->addUserToDepartment( $depId, $userId, $manager, true ); } - $result = new wsResponse(0, G::loadTranslation('ID_COMMAND_EXECUTED_SUCCESSFULY')); + $result = new wsResponse( 0, G::loadTranslation( 'ID_COMMAND_EXECUTED_SUCCESSFULY' ) ); return $result; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -1511,119 +1455,116 @@ class wsBase /** * sends variables to a case + * * @param string $caseId * @param string $variables * @return $result will return an object */ - public function sendVariables($caseId, $variables) + 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 = 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); + $oCriteria->addDescendingOrderByColumn( AppDelegationPeer::DEL_INDEX ); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $cnt = 0; while ($oDataset->next()) { $aRow = $oDataset->getRow(); - $cnt++; + $cnt ++; } if ($cnt == 0) { - $result = new wsResponse(18, G::loadTranslation('ID_CASE_DELEGATION_ALREADY_CLOSED')); + $result = new wsResponse( 18, G::loadTranslation( 'ID_CASE_DELEGATION_ALREADY_CLOSED' ) ); return $result; } - if (is_array($variables)) { - $cant = count($variables); + 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); + $oldFields = $oCase->loadCase( $caseId ); + $oldFields['APP_DATA'] = array_merge( $oldFields['APP_DATA'], $variables ); ob_start(); - print_r($variables); + print_r( $variables ); $cdata = ob_get_contents(); ob_end_clean(); - $up_case = $oCase->updateCase($caseId, $oldFields); + $up_case = $oCase->updateCase( $caseId, $oldFields ); - $result = new wsResponse( - 0, - $cant . " " . G::loadTranslation('ID_VARIABLES_RECEIVED') . ": \n" . trim( - str_replace('Array', '', $cdata) - ) - ); + $result = new wsResponse( 0, $cant . " " . G::loadTranslation( 'ID_VARIABLES_RECEIVED' ) . ": \n" . trim( str_replace( 'Array', '', $cdata ) ) ); return $result; } else { - $result = new wsResponse(23, G::loadTranslation('ID_VARIABLES_PARAM_ZERO')); + $result = new wsResponse( 23, G::loadTranslation( 'ID_VARIABLES_PARAM_ZERO' ) ); return $result; } } else { - $result = new wsResponse(24, G::loadTranslation('ID_VARIABLES_PARAM_NOT_ARRAY')); + $result = new wsResponse( 24, G::loadTranslation( 'ID_VARIABLES_PARAM_NOT_ARRAY' ) ); return $result; } } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } } /** - * get variables The variables can be system variables and/or case variables + * 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) + public function getVariables ($caseId, $variables) { try { - if (is_array($variables)) { - $cant = count($variables); + if (is_array( $variables )) { + $cant = count( $variables ); if ($cant > 0) { $oCase = new Cases(); - $caseFields = $oCase->loadCase($caseId); - $oldFields = $caseFields['APP_DATA']; - $resFields = array(); + $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]; + 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) { //Special Variables like grids or checkgroups - if (is_array($gridRow)) { + if (is_array( $gridRow )) { //Grids foreach ($gridRow as $col => $colValue) { - $node = new stdClass(); - $node->name = $val->name . "][" . $gridKey . "][" . $col; + $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); + $node = new stdClass(); + $node->name = $key; + $node->value = implode( "|", $val ); $resFields[] = $node; } } @@ -1631,60 +1572,55 @@ class wsBase } } - $result = new wsGetVariableResponse( - 0, - count($resFields) . G::loadTranslation('ID_VARIABLES_SENT'), $resFields - ); + $result = new wsGetVariableResponse( 0, count( $resFields ) . G::loadTranslation( 'ID_VARIABLES_SENT' ), $resFields ); return $result; } else { - $result = new wsGetVariableResponse(23, G::loadTranslation('ID_VARIABLES_PARAM_ZERO'), null); + $result = new wsGetVariableResponse( 23, G::loadTranslation( 'ID_VARIABLES_PARAM_ZERO' ), null ); return $result; } } else { - $result = new wsGetVariableResponse(24, G::loadTranslation('ID_VARIABLES_PARAM_NOT_ARRAY'), null); + $result = new wsGetVariableResponse( 24, G::loadTranslation( 'ID_VARIABLES_PARAM_NOT_ARRAY' ), null ); return $result; } } catch (Exception $e) { - $result = new wsGetVariableResponse(100, $e->getMessage(), null); + $result = new wsGetVariableResponse( 100, $e->getMessage(), null ); return $result; } } /** - * get all variables the system and case selected + * get all variables the system and case selected + * * @param string $caseId * * @return $result will return an object */ - public function getVariablesNames($caseId) + public function getVariablesNames ($caseId) { try { $oCase = new Cases(); - $caseFields = $oCase->loadCase($caseId); + $caseFields = $oCase->loadCase( $caseId ); - $oldFields = $caseFields['APP_DATA']; - $resFields = array(); + $oldFields = $caseFields['APP_DATA']; + $resFields = array (); foreach ($oldFields as $key => $val) { $node = new stdClass(); - $node->name = $key; + $node->name = $key; $resFields[] = $node; } - $result = new wsGetVariableResponse( - 0, - count($resFields) . G::loadTranslation('ID_VARIABLES_SENT'), $resFields - ); + $result = new wsGetVariableResponse( 0, count( $resFields ) . G::loadTranslation( 'ID_VARIABLES_SENT' ), $resFields ); return $result; } catch (Exception $e) { - $result = new wsGetVariableResponse(100, $e->getMessage(), null); + $result = new wsGetVariableResponse( 100, $e->getMessage(), null ); return $result; } @@ -1692,79 +1628,80 @@ class wsBase /** * 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) + public function newCase ($processId, $userId, $taskId, $variables) { try { - $originalValues = array(); + $originalValues = array (); //Unset any variable, because we are starting a new case - if (isset($_SESSION['APPLICATION'])) { + if (isset( $_SESSION['APPLICATION'] )) { $originalValues['APPLICATION'] = $_SESSION['APPLICATION']; - unset($_SESSION['APPLICATION']); + unset( $_SESSION['APPLICATION'] ); } - if (isset($_SESSION['PROCESS'])) { + if (isset( $_SESSION['PROCESS'] )) { $originalValues['PROCESS'] = $_SESSION['PROCESS']; - unset($_SESSION['PROCESS']); + unset( $_SESSION['PROCESS'] ); } - if (isset($_SESSION['TASK'])) { + if (isset( $_SESSION['TASK'] )) { $originalValues['TASK'] = $_SESSION['TASK']; - unset($_SESSION['TASK']); + unset( $_SESSION['TASK'] ); } - if (isset($_SESSION['INDEX'])) { + if (isset( $_SESSION['INDEX'] )) { $originalValues['INDEX'] = $_SESSION['INDEX']; - unset($_SESSION['INDEX']); + unset( $_SESSION['INDEX'] ); } - if (isset($_SESSION['USER_LOGGED'])) { + if (isset( $_SESSION['USER_LOGGED'] )) { $originalValues['USER_LOGGED'] = $_SESSION['USER_LOGGED']; - unset($_SESSION['USER_LOGGED']); + unset( $_SESSION['USER_LOGGED'] ); } - if (isset($_SESSION['USR_USERNAME'])) { + if (isset( $_SESSION['USR_USERNAME'] )) { $originalValues['USR_USERNAME'] = $_SESSION['USR_USERNAME']; - unset($_SESSION['USR_USERNAME']); + unset( $_SESSION['USR_USERNAME'] ); } - if (isset($_SESSION['STEP_POSITION'])) { + if (isset( $_SESSION['STEP_POSITION'] )) { $originalValues['STEP_POSITION'] = $_SESSION['STEP_POSITION']; - unset($_SESSION['STEP_POSITION']); + unset( $_SESSION['STEP_POSITION'] ); } - $Fields = array(); + $Fields = array (); - if (is_array($variables) && count($variables) > 0) { + if (is_array( $variables ) && count( $variables ) > 0) { $Fields = $variables; } $oProcesses = new Processes(); - $pro = $oProcesses->processExists($processId); + $pro = $oProcesses->processExists( $processId ); - if (!$pro) { - $result = new wsResponse(11, G::loadTranslation('ID_INVALID_PROCESS') . " " . $processId); + if (! $pro) { + $result = new wsResponse( 11, G::loadTranslation( 'ID_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 = ''; + $startingTasks = $oCase->getStartCases( $userId ); + array_shift( $startingTasks ); //remove the first row, the header row + $founded = ''; $tasksInThisProcess = 0; - $validTaskId = $taskId; + $validTaskId = $taskId; foreach ($startingTasks as $key => $val) { if ($val['pro_uid'] == $processId) { - $tasksInThisProcess++; + $tasksInThisProcess ++; $validTaskId = $val['uid']; } @@ -1776,73 +1713,73 @@ class wsBase if ($taskId == '') { if ($tasksInThisProcess == 1) { $founded = $validTaskId; - $taskId = $validTaskId; + $taskId = $validTaskId; } if ($tasksInThisProcess > 1) { - $result = new wsResponse(13, G::loadTranslation('ID_MULTIPLE_STARTING_TASKS')); + $result = new wsResponse( 13, G::loadTranslation( 'ID_MULTIPLE_STARTING_TASKS' ) ); return $result; } } - if ( $founded == '') { - $result = new wsResponse(14, G::loadTranslation('ID_TASK_INVALID_USER_NOT_ASSIGNED_TASK')); + if ($founded == '') { + $result = new wsResponse( 14, G::loadTranslation( 'ID_TASK_INVALID_USER_NOT_ASSIGNED_TASK' ) ); return $result; } - $case = $oCase->startCase($taskId, $userId); + $case = $oCase->startCase( $taskId, $userId ); - $_SESSION['APPLICATION'] = $case['APPLICATION']; - $_SESSION['PROCESS'] = $case['PROCESS']; - $_SESSION['TASK'] = $taskId; - $_SESSION['INDEX'] = $case['INDEX']; - $_SESSION['USER_LOGGED'] = $userId; - $_SESSION['USR_USERNAME'] = $case['USR_USERNAME']; + $_SESSION['APPLICATION'] = $case['APPLICATION']; + $_SESSION['PROCESS'] = $case['PROCESS']; + $_SESSION['TASK'] = $taskId; + $_SESSION['INDEX'] = $case['INDEX']; + $_SESSION['USER_LOGGED'] = $userId; + $_SESSION['USR_USERNAME'] = $case['USR_USERNAME']; $_SESSION['STEP_POSITION'] = 0; $caseId = $case['APPLICATION']; $caseNr = $case['CASE_NUMBER']; - $oldFields = $oCase->loadCase($caseId); + $oldFields = $oCase->loadCase( $caseId ); - $oldFields['APP_DATA'] = array_merge($oldFields['APP_DATA'], $Fields); + $oldFields['APP_DATA'] = array_merge( $oldFields['APP_DATA'], $Fields ); - $up_case = $oCase->updateCase($caseId, $oldFields); + $up_case = $oCase->updateCase( $caseId, $oldFields ); //Restore original values - if (isset($originalValues['APPLICATION'])) { + if (isset( $originalValues['APPLICATION'] )) { $_SESSION['APPLICATION'] = $originalValues['APPLICATION']; } - if (isset($originalValues['PROCESS'])) { + if (isset( $originalValues['PROCESS'] )) { $_SESSION['PROCESS'] = $originalValues['PROCESS']; } - if (isset($originalValues['TASK'])) { + if (isset( $originalValues['TASK'] )) { $_SESSION['TASK'] = $originalValues['TASK']; } - if (isset($originalValues['INDEX'])) { + if (isset( $originalValues['INDEX'] )) { $_SESSION['INDEX'] = $originalValues['INDEX']; } - if (isset($originalValues['USR_USERNAME'])) { + if (isset( $originalValues['USR_USERNAME'] )) { $_SESSION['USR_USERNAME'] = $originalValues['USR_USERNAME']; } - if (isset($originalValues['STEP_POSITION'])) { + if (isset( $originalValues['STEP_POSITION'] )) { $_SESSION['STEP_POSITION'] = $originalValues['STEP_POSITION']; } - $result = new wsResponse(0, G::loadTranslation('ID_STARTED_SUCCESSFULLY')); - $result->caseId = $caseId; + $result = new wsResponse( 0, G::loadTranslation( 'ID_STARTED_SUCCESSFULLY' ) ); + $result->caseId = $caseId; $result->caseNumber = $caseNr; return $result; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -1850,85 +1787,86 @@ class wsBase /** * 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) + public function newCaseImpersonate ($processId, $userId, $variables) { try { - if (is_array($variables)) { - if (count($variables) > 0) { - $c = count($variables); + 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, G::loadTranslation('ID_ARRAY_VARIABLES_EMPTY')); + $result = new wsResponse( 10, G::loadTranslation( 'ID_ARRAY_VARIABLES_EMPTY' ) ); return $result; } } } else { - $result = new wsResponse(10, G::loadTranslation('ID_VARIABLES_PARAM_NOT_ARRAY')); + $result = new wsResponse( 10, G::loadTranslation( 'ID_VARIABLES_PARAM_NOT_ARRAY' ) ); return $result; } $processes = new Processes(); - if (!$processes->processExists($processId)) { - $result = new wsResponse(11, G::loadTranslation('ID_INVALID_PROCESS') . " " . $processId . "!!"); + if (! $processes->processExists( $processId )) { + $result = new wsResponse( 11, G::loadTranslation( 'ID_INVALID_PROCESS' ) . " " . $processId . "!!" ); return $result; } $user = new Users(); - if (!$user->userExists($userId)) { - $result = new wsResponse(11, G::loadTranslation('ID_USER_NOT_REGISTERED') . " " . $userId . "!!"); + if (! $user->userExists( $userId )) { + $result = new wsResponse( 11, G::loadTranslation( 'ID_USER_NOT_REGISTERED' ) . " " . $userId . "!!" ); return $result; } $oCase = new Cases(); - $arrayTask = $processes->getStartingTaskForUser($processId, null); - $numTasks = count($arrayTask); + $arrayTask = $processes->getStartingTaskForUser( $processId, null ); + $numTasks = count( $arrayTask ); if ($numTasks == 1) { - $case = $oCase->startCase($arrayTask[0]['TAS_UID'], $userId); - $caseId = $case['APPLICATION']; + $case = $oCase->startCase( $arrayTask[0]['TAS_UID'], $userId ); + $caseId = $case['APPLICATION']; $caseNumber = $case['CASE_NUMBER']; - $oldFields = $oCase->loadCase($caseId); + $oldFields = $oCase->loadCase( $caseId ); - $oldFields['APP_DATA'] = array_merge($oldFields['APP_DATA'], $Fields); + $oldFields['APP_DATA'] = array_merge( $oldFields['APP_DATA'], $Fields ); - $up_case = $oCase->updateCase($caseId, $oldFields); + $up_case = $oCase->updateCase( $caseId, $oldFields ); - $result = new wsResponse(0, G::loadTranslation('ID_COMMAND_EXECUTED_SUCCESSFULLY')); + $result = new wsResponse( 0, G::loadTranslation( 'ID_COMMAND_EXECUTED_SUCCESSFULLY' ) ); - $result->caseId = $caseId; + $result->caseId = $caseId; $result->caseNumber = $caseNumber; return $result; } else { if ($numTasks == 0) { - $result = new wsResponse(12, G::loadTranslation('ID_NO_STARTING_TASK')); + $result = new wsResponse( 12, G::loadTranslation( 'ID_NO_STARTING_TASK' ) ); return $result; } if ($numTasks > 1) { - $result = new wsResponse(13, G::loadTranslation ('ID_MULTIPLE_STARTING_TASKS')); + $result = new wsResponse( 13, G::loadTranslation( 'ID_MULTIPLE_STARTING_TASKS' ) ); return $result; } } } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -1936,12 +1874,13 @@ class wsBase /** * 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) + public function derivateCase ($userId, $caseId, $delIndex, $bExecuteTriggersBeforeAssignment = false) { try { $sStatus = 'TO_DO'; @@ -1950,133 +1889,126 @@ class wsBase $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); + $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, G::loadTranslation('ID_SPECIFY_DELEGATION_INDEX')); + if (AppDelegationPeer::doCount( $oCriteria ) > 1) { + $result = new wsResponse( 20, G::loadTranslation( 'ID_SPECIFY_DELEGATION_INDEX' ) ); return $result; } - $oDataset = AppDelegationPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); - $aRow = $oDataset->getRow(); + $aRow = $oDataset->getRow(); $delIndex = $aRow['DEL_INDEX']; } $oAppDel = new AppDelegation(); - $appdel = $oAppDel->Load($caseId, $delIndex); + $appdel = $oAppDel->Load( $caseId, $delIndex ); if ($userId != $appdel['USR_UID']) { - $result = new wsResponse(17, G::loadTranslation('ID_CASE_ASSIGNED_ANOTHER_USER')); + $result = new wsResponse( 17, G::loadTranslation( 'ID_CASE_ASSIGNED_ANOTHER_USER' ) ); return $result; } if ($appdel['DEL_FINISH_DATE'] != null) { - $result = new wsResponse(18, G::loadTranslation('ID_CASE_DELEGATION_ALREADY_CLOSED')); + $result = new wsResponse( 18, G::loadTranslation( 'ID_CASE_DELEGATION_ALREADY_CLOSED' ) ); 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); + $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, G::loadTranslation('ID_CASE_IN_STATUS') . " " . $aRow['APP_TYPE']); + 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, G::loadTranslation( 'ID_CASE_IN_STATUS' ) . " " . $aRow['APP_TYPE'] ); return $result; } } - $aData['APP_UID'] = $caseId; + $aData['APP_UID'] = $caseId; $aData['DEL_INDEX'] = $delIndex; - $aData['USER_UID'] = $userId; + $aData['USER_UID'] = $userId; //Load data - $oCase = new Cases(); - $appFields = $oCase->loadCase($caseId, $delIndex); + $oCase = new Cases(); + $appFields = $oCase->loadCase( $caseId, $delIndex ); - if (is_null($appFields["DEL_INIT_DATE"])) { - $oCase->setDelInitDate($caseId, $delIndex); - $appFields = $oCase->loadCase($caseId, $delIndex); + if (is_null( $appFields["DEL_INIT_DATE"] )) { + $oCase->setDelInitDate( $caseId, $delIndex ); + $appFields = $oCase->loadCase( $caseId, $delIndex ); } $appFields["APP_DATA"]["APPLICATION"] = $caseId; - if (!isset($_SESSION["PROCESS"])) { + if (! isset( $_SESSION["PROCESS"] )) { $_SESSION["PROCESS"] = $appFields["PRO_UID"]; } if ($bExecuteTriggersBeforeAssignment) { //Execute triggers before assignment - $aTriggers = $oCase->loadTriggers($appdel['TAS_UID'], 'ASSIGN_TASK', -1, 'BEFORE'); + $aTriggers = $oCase->loadTriggers( $appdel['TAS_UID'], 'ASSIGN_TASK', - 1, 'BEFORE' ); - if (count($aTriggers) > 0) { + if (count( $aTriggers ) > 0) { $oPMScript = new PMScript(); foreach ($aTriggers as $aTrigger) { //$appFields = $oCase->loadCase( $caseId ); //$appFields['APP_DATA']['APPLICATION'] = $caseId; + //Set variables $params = new stdClass(); $params->appData = $appFields["APP_DATA"]; if ($this->stored_system_variables) { $params->option = "STORED SESSION"; - $params->SID = $this->wsSessionId; + $params->SID = $this->wsSessionId; } - $appFields["APP_DATA"] = array_merge($appFields["APP_DATA"], G::getSystemConstants($params)); + $appFields["APP_DATA"] = array_merge( $appFields["APP_DATA"], G::getSystemConstants( $params ) ); //PMScript - $oPMScript->setFields($appFields['APP_DATA']); + $oPMScript->setFields( $appFields['APP_DATA'] ); $bExecute = true; if ($aTrigger['ST_CONDITION'] !== '') { - $oPMScript->setScript($aTrigger['ST_CONDITION']); + $oPMScript->setScript( $aTrigger['ST_CONDITION'] ); $bExecute = $oPMScript->evaluate(); } if ($bExecute) { - $oPMScript->setScript($aTrigger['TRI_WEBBOT']); + $oPMScript->setScript( $aTrigger['TRI_WEBBOT'] ); $oPMScript->execute(); - $varTriggers .= "
-= Before Assignment =-
" . nl2br( - htmlentities($aTrigger['TRI_WEBBOT'], ENT_QUOTES) - ) . "
"; + $varTriggers .= "
-= Before Assignment =-
" . nl2br( htmlentities( $aTrigger['TRI_WEBBOT'], ENT_QUOTES ) ) . "
"; //$appFields = $oCase->loadCase( $caseId ); $appFields['APP_DATA'] = $oPMScript->aFields; - $oCase->updateCase($caseId, $appFields); + $oCase->updateCase( $caseId, $appFields ); } } } } //Execute triggers before derivation - $aTriggers = $oCase->loadTriggers($appdel['TAS_UID'], 'ASSIGN_TASK', -2, 'BEFORE'); + $aTriggers = $oCase->loadTriggers( $appdel['TAS_UID'], 'ASSIGN_TASK', - 2, 'BEFORE' ); - if (count($aTriggers) > 0) { + if (count( $aTriggers ) > 0) { $varTriggers .= "-= Before Derivation =-
"; $oPMScript = new PMScript(); @@ -2085,89 +2017,88 @@ class wsBase //$appFields = $oCase->loadCase( $caseId ); //$appFields['APP_DATA']['APPLICATION'] = $caseId; + //Set variables $params = new stdClass(); $params->appData = $appFields["APP_DATA"]; if ($this->stored_system_variables) { $params->option = "STORED SESSION"; - $params->SID = $this->wsSessionId; + $params->SID = $this->wsSessionId; } - $appFields["APP_DATA"] = array_merge($appFields["APP_DATA"], G::getSystemConstants($params)); + $appFields["APP_DATA"] = array_merge( $appFields["APP_DATA"], G::getSystemConstants( $params ) ); //PMScript - $oPMScript->setFields($appFields['APP_DATA']); + $oPMScript->setFields( $appFields['APP_DATA'] ); $bExecute = true; if ($aTrigger['ST_CONDITION'] !== '') { - $oPMScript->setScript($aTrigger['ST_CONDITION']); + $oPMScript->setScript( $aTrigger['ST_CONDITION'] ); $bExecute = $oPMScript->evaluate(); } if ($bExecute) { - $oPMScript->setScript($aTrigger['TRI_WEBBOT']); + $oPMScript->setScript( $aTrigger['TRI_WEBBOT'] ); $oPMScript->execute(); - $oTrigger = TriggersPeer::retrieveByPk($aTrigger['TRI_UID']); - $varTriggers .= " - " . nl2br(htmlentities($oTrigger->getTriTitle(), ENT_QUOTES)) ."
"; + $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); + $oCase->updateCase( $caseId, $appFields ); } } } $oDerivation = new Derivation(); - $derive = $oDerivation->prepareInformation($aData); + $derive = $oDerivation->prepareInformation( $aData ); - if (isset($derive[1])) { + if (isset( $derive[1] )) { if ($derive[1]['ROU_TYPE'] == 'SELECT') { - $result = new wsResponse(21, G::loadTranslation('ID_CAN_NOT_ROUTE_CASE_USING_WEBSERVICES')); + $result = new wsResponse( 21, G::loadTranslation( 'ID_CAN_NOT_ROUTE_CASE_USING_WEBSERVICES' ) ); return $result; } } else { - $result = new wsResponse(22, G::loadTranslation('ID_TASK_DOES_NOT_HAVE_ROUTING_RULE')); + $result = new wsResponse( 22, G::loadTranslation( 'ID_TASK_DOES_NOT_HAVE_ROUTING_RULE' ) ); return $result; } foreach ($derive as $key => $val) { if ($val['NEXT_TASK']['TAS_ASSIGN_TYPE'] == 'MANUAL') { - $result = new wsResponse(15, G::loadTranslation('ID_TASK_DEFINED_MANUAL_ASSIGNMENT')); + $result = new wsResponse( 15, G::loadTranslation( 'ID_TASK_DEFINED_MANUAL_ASSIGNMENT' ) ); return $result; } //Routed to the next task, if end process then not exist user - $nodeNext = array(); + $nodeNext = array (); $usrasgdUid = null; $usrasgdUserName = null; - if (isset($val['NEXT_TASK']['USER_ASSIGNED'])) { + if (isset( $val['NEXT_TASK']['USER_ASSIGNED'] )) { $usrasgdUid = $val['NEXT_TASK']['USER_ASSIGNED']['USR_UID']; $usrasgdUserName = '(' . $val['NEXT_TASK']['USER_ASSIGNED']['USR_USERNAME'] . ')'; } $nodeNext['TAS_UID'] = $val['NEXT_TASK']['TAS_UID']; $nodeNext['USR_UID'] = $usrasgdUid; - $nodeNext['TAS_ASSIGN_TYPE'] = $val['NEXT_TASK']['TAS_ASSIGN_TYPE']; + $nodeNext['TAS_ASSIGN_TYPE'] = $val['NEXT_TASK']['TAS_ASSIGN_TYPE']; $nodeNext['TAS_DEF_PROC_CODE'] = $val['NEXT_TASK']['TAS_DEF_PROC_CODE']; $nodeNext['DEL_PRIORITY'] = $appdel['DEL_PRIORITY']; - $nodeNext['TAS_PARENT'] = $val['NEXT_TASK']['TAS_PARENT']; + $nodeNext['TAS_PARENT'] = $val['NEXT_TASK']['TAS_PARENT']; $nextDelegations[] = $nodeNext; - $varResponse = $varResponse . ( - ($varResponse != '')? ',' : '' - ) . $val['NEXT_TASK']['TAS_TITLE'] . $usrasgdUserName; + $varResponse = $varResponse . (($varResponse != '') ? ',' : '') . $val['NEXT_TASK']['TAS_TITLE'] . $usrasgdUserName; } $appFields['DEL_INDEX'] = $delIndex; - if (isset($derive['TAS_UID'])) { - $appFields['TAS_UID'] = $derive['TAS_UID']; + if (isset( $derive['TAS_UID'] )) { + $appFields['TAS_UID'] = $derive['TAS_UID']; } //Save data - Start @@ -2175,53 +2106,51 @@ class wsBase //$oCase->updateCase ( $caseId, $appFields ); //Save data - End - $row = array(); - $oCriteria = new Criteria('workflow'); + + $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); + $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']); + $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'] + $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); + $oDerivation->derivate( $aCurrentDerivation, $nextDelegations ); + $appFields = $oCase->loadCase( $caseId ); //Execute triggers after derivation - $aTriggers = $oCase->loadTriggers($appdel['TAS_UID'], 'ASSIGN_TASK', -2, 'AFTER'); + $aTriggers = $oCase->loadTriggers( $appdel['TAS_UID'], 'ASSIGN_TASK', - 2, 'AFTER' ); - if (count($aTriggers) > 0) { + if (count( $aTriggers ) > 0) { //$appFields['APP_DATA']['APPLICATION'] = $caseId; + //Set variables $params = new stdClass(); $params->appData = $appFields["APP_DATA"]; if ($this->stored_system_variables) { $params->option = "STORED SESSION"; - $params->SID = $this->wsSessionId; + $params->SID = $this->wsSessionId; } - $appFields["APP_DATA"] = array_merge($appFields["APP_DATA"], G::getSystemConstants($params)); + $appFields["APP_DATA"] = array_merge( $appFields["APP_DATA"], G::getSystemConstants( $params ) ); //PMScript $oPMScript = new PMScript(); - $oPMScript->setFields($appFields['APP_DATA']); + $oPMScript->setFields( $appFields['APP_DATA'] ); $varTriggers .= "-= After Derivation =-
"; @@ -2229,79 +2158,71 @@ class wsBase $bExecute = true; if ($aTrigger['ST_CONDITION'] !== '') { - $oPMScript->setScript($aTrigger['ST_CONDITION']); + $oPMScript->setScript( $aTrigger['ST_CONDITION'] ); $bExecute = $oPMScript->evaluate(); } if ($bExecute) { - $oPMScript->setScript($aTrigger['TRI_WEBBOT']); + $oPMScript->setScript( $aTrigger['TRI_WEBBOT'] ); $oPMScript->execute(); - $oTrigger = TriggersPeer::retrieveByPk($aTrigger['TRI_UID']); - $varTriggers .= " - ".nl2br(htmlentities($oTrigger->getTriTitle(), ENT_QUOTES)) . "
"; + $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); + $oCase->updateCase( $caseId, $appFields ); } } } $oUser = new Users(); - $aUser = $oUser->load($userId); + $aUser = $oUser->load( $userId ); - if (trim($aUser['USR_EMAIL']) == '') { - $aUser['USR_EMAIL'] = 'info@'.$_SERVER['HTTP_HOST']; + if (trim( $aUser['USR_EMAIL'] ) == '') { + $aUser['USR_EMAIL'] = 'info@' . $_SERVER['HTTP_HOST']; } - $sFromName = '"' . $aUser['USR_FIRSTNAME'] . ' ' . $aUser['USR_LASTNAME'] . '" <'.$aUser['USR_EMAIL'].'>'; - $oCase->sendNotifications( - $appdel['TAS_UID'], - $nextDelegations, - $appFields['APP_DATA'], - $caseId, - $delIndex, - $sFromName - ); + $sFromName = '"' . $aUser['USR_FIRSTNAME'] . ' ' . $aUser['USR_LASTNAME'] . '" <' . $aUser['USR_EMAIL'] . '>'; + $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']); + $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 . " + + if (isset( $oProcessFieds['PRO_DEBUG'] ) && $oProcessFieds['PRO_DEBUG']) { + $result = new wsResponse( 0, $varResponse . "

- " . G::LoadTranslation('ID_DEBUG_MESSAGE') . "
" . $varTriggers - ); + " . G::LoadTranslation( 'ID_DEBUG_MESSAGE' ) . "" . $varTriggers ); } else { - $result = new wsResponse(0, $varResponse." --- ".$oProcessFieds['PRO_DEBUG']); + $result = new wsResponse( 0, $varResponse . " --- " . $oProcessFieds['PRO_DEBUG'] ); } $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); + $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(); + $aCurrentUsers = array (); while ($oDataset->next()) { $aAppDel = $oDataset->getRow(); @@ -2309,8 +2230,8 @@ class wsBase $oUser = new Users(); try { - $oUser->load($aAppDel['USR_UID']); - $uFields = $oUser->toArray(BasePeer::TYPE_FIELDNAME); + $oUser->load( $aAppDel['USR_UID'] ); + $uFields = $oUser->toArray( BasePeer::TYPE_FIELDNAME ); $currentUserName = $oUser->getUsrFirstname() . ' ' . $oUser->getUsrLastname(); } catch (Exception $e) { $currentUserName = ''; @@ -2319,7 +2240,7 @@ class wsBase $oTask = new Task(); try { - $uFields = $oTask->load($aAppDel['TAS_UID']); + $uFields = $oTask->load( $aAppDel['TAS_UID'] ); $taskName = $uFields['TAS_TITLE']; } catch (Exception $e) { $taskName = ''; @@ -2332,15 +2253,16 @@ class wsBase $eventTas = $aAppDel['TAS_UID']; $oEvent = new Event(); - $oEvent->createAppEvents($eventPro, $eventApp, $eventInd, $eventTas); + $oEvent->createAppEvents( $eventPro, $eventApp, $eventInd, $eventTas ); // end events + $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->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; @@ -2350,106 +2272,105 @@ class wsBase return $res; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } } /** - * execute Trigger, executes a ProcessMaker trigger. Note that triggers which are tied to case derivation + * 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) + public function executeTrigger ($userId, $caseId, $triggerIndex, $delIndex) { try { $oAppDel = new AppDelegation(); - $appdel = $oAppDel->Load($caseId, $delIndex); + $appdel = $oAppDel->Load( $caseId, $delIndex ); - if ($userId!=$appdel['USR_UID']) { - $result = new wsResponse(17, G::loadTranslation('ID_CASE_ASSIGNED_ANOTHER_USER')); + if ($userId != $appdel['USR_UID']) { + $result = new wsResponse( 17, G::loadTranslation( 'ID_CASE_ASSIGNED_ANOTHER_USER' ) ); return $result; } if ($appdel['DEL_FINISH_DATE'] != null) { - $result = new wsResponse(18, G::loadTranslation('ID_CASE_DELEGATION_ALREADY_CLOSED')); + $result = new wsResponse( 18, G::loadTranslation( 'ID_CASE_DELEGATION_ALREADY_CLOSED' ) ); 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); + $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 (is_array( $aRow )) { if ($aRow['APP_DISABLE_ACTION_USER'] != 0 && $aRow['APP_DISABLE_ACTION_DATE'] != '') { - $result = new wsResponse(19, G::loadTranslation('ID_CASE_IN_STATUS') . " ". $aRow['APP_TYPE']); + $result = new wsResponse( 19, G::loadTranslation( 'ID_CASE_IN_STATUS' ) . " " . $aRow['APP_TYPE'] ); return $result; } } //Load data - $oCase = new Cases(); - $appFields = $oCase->loadCase($caseId); + $oCase = new Cases(); + $appFields = $oCase->loadCase( $caseId ); $appFields["APP_DATA"]["APPLICATION"] = $caseId; - if (!isset($_SESSION["PROCESS"])) { + if (! isset( $_SESSION["PROCESS"] )) { $_SESSION["PROCESS"] = $appFields["PRO_UID"]; } //executeTrigger - $aTriggers = array(); + $aTriggers = array (); $c = new Criteria(); - $c->add(TriggersPeer::TRI_UID, $triggerIndex); - $rs = TriggersPeer::doSelectRS($c); - $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $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' ) { + if (is_array( $row ) && $row['TRI_TYPE'] == 'SCRIPT') { $aTriggers[] = $row; $oPMScript = new PMScript(); - $oPMScript->setFields($appFields['APP_DATA']); - $oPMScript->setScript($row['TRI_WEBBOT']); + $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); + $oCase->updateCase( $caseId, $appFields ); //Save data - End } else { $data['TRIGGER_INDEX'] = $triggerIndex; - $result = new wsResponse(100, G::loadTranslation('ID_INVALID_TRIGGER', SYS_LANG, $data)); + $result = new wsResponse( 100, G::loadTranslation( 'ID_INVALID_TRIGGER', SYS_LANG, $data ) ); return $result; } - $result = new wsResponse(0, G::loadTranslation('ID_EXECUTED') . ": " . trim($row['TRI_WEBBOT'])); + $result = new wsResponse( 0, G::loadTranslation( 'ID_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()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -2457,42 +2378,48 @@ class wsBase /** * 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 + * + * @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) + public function taskCase ($caseId) { try { - $result = array(); - $oCriteria = new Criteria('workflow'); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn(AppDelegationPeer::DEL_INDEX); + $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->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); + $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']); + $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()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } @@ -2500,26 +2427,29 @@ class wsBase /** * process list verified - * @param string sessionId : The session ID which is obtained when logging in - * @param string userId : - * @return $result will return an object + * + * @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) + public function processListVerified ($userId) { try { $oCase = new Cases(); - $rows = $oCase->getStartCases($userId); - $result = array(); + $rows = $oCase->getStartCases( $userId ); + $result = array (); foreach ($rows as $key => $val) { if ($key != 0) { - $result[] = array('guid' => $val['pro_uid'], 'name' => $val['value']); + $result[] = array ('guid' => $val['pro_uid'],'name' => $val['value'] + ); } } return $result; } catch (Exception $e) { - $result[] = array('guid' => $e->getMessage(), 'name' => $e->getMessage()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } @@ -2527,109 +2457,121 @@ class wsBase /** * 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 + * + * @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) + public function reassignCase ($sessionId, $caseId, $delIndex, $userIdSource, $userIdTarget) { try { if ($userIdTarget == $userIdSource) { - $result = new wsResponse(30, G::loadTranslation('ID_TARGET_ORIGIN_USER_SAME')); + $result = new wsResponse( 30, G::loadTranslation( 'ID_TARGET_ORIGIN_USER_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); + /** + * ****************( 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, G::loadTranslation('ID_INVALID_ORIGIN_USER')); + if (! is_array( $aRow )) { + $result = new wsResponse( 31, G::loadTranslation( 'ID_INVALID_ORIGIN_USER' ) ); return $result; } - /******************( 2 )******************/ + /** + * ****************( 2 )***************** + */ $oCase = new Cases(); - $rows = $oCase->loadCase($caseId); + $rows = $oCase->loadCase( $caseId ); - if (!is_array($aRow)) { - $result = new wsResponse(32, G::loadTranslation('ID_CASE_NOT_OPEN')); + if (! is_array( $aRow )) { + $result = new wsResponse( 32, G::loadTranslation( 'ID_CASE_NOT_OPEN' ) ); return $result; } - /******************( 3 )******************/ - $oCriteria = new Criteria('workflow'); - $aConditions = array(); + /** + * ****************( 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); + $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, G::loadTranslation('ID_INVALID_CASE_DELEGATION_INDEX')); + if (! is_array( $aRow )) { + $result = new wsResponse( 33, G::loadTranslation( 'ID_INVALID_CASE_DELEGATION_INDEX' ) ); return $result; } $tasUid = $aRow['TAS_UID']; $derivation = new Derivation(); - $userList = $derivation->getAllUsersFromAnyTask($tasUid); + $userList = $derivation->getAllUsersFromAnyTask( $tasUid ); - if (!in_array($userIdTarget, $userList)) { - $result = new wsResponse(34, G::loadTranslation('ID_TARGET_USER_DOES_NOT_HAVE_RIGHTS')); + if (! in_array( $userIdTarget, $userList )) { + $result = new wsResponse( 34, G::loadTranslation( 'ID_TARGET_USER_DOES_NOT_HAVE_RIGHTS' ) ); 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); + /** + * ****************( 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, G::loadTranslation('ID_TARGET_USER_DESTINATION_INVALID')); + if (! is_array( $aRow )) { + $result = new wsResponse( 35, G::loadTranslation( 'ID_TARGET_USER_DESTINATION_INVALID' ) ); return $result; } - /******************( 5 )******************/ - $var = $oCase->reassignCase($caseId, $delIndex, $userIdSource, $userIdTarget); + /** + * ****************( 5 )***************** + */ + $var = $oCase->reassignCase( $caseId, $delIndex, $userIdSource, $userIdTarget ); - if (!$var) { - $result = new wsResponse(36, G::loadTranslation('ID_CASE_COULD_NOT_REASSIGNED')); + if (! $var) { + $result = new wsResponse( 36, G::loadTranslation( 'ID_CASE_COULD_NOT_REASSIGNED' ) ); return $result; } - $result = new wsResponse(0, G::loadTranslation('ID_COMMAND_EXECUTED_SUCCESSFULLY')); + $result = new wsResponse( 0, G::loadTranslation( 'ID_COMMAND_EXECUTED_SUCCESSFULLY' ) ); return $result; } catch (Exception $e) { - $result[] = array('guid' => $e->getMessage(), 'name' => $e->getMessage()); + $result[] = array ('guid' => $e->getMessage(),'name' => $e->getMessage() + ); return $result; } @@ -2637,37 +2579,38 @@ class wsBase /** * get system information - * @param string sessionId : The session ID (which was obtained at login) + * + * @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() + public function systemInformation () { try { - define('SKIP_RENDER_SYSTEM_INFORMATION', true); + define( 'SKIP_RENDER_SYSTEM_INFORMATION', true ); require_once (PATH_METHODS . 'login' . PATH_SEP . 'dbInfo.php'); - $result->status_code = 0; - $result->message = G::loadTranslation ('ID_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->status_code = 0; + $result->message = G::loadTranslation( 'ID_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']; + $result->userBrowser = $Fields['HTTP_USER_AGENT']; + $result->userIp = $Fields['IP']; return $result; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -2675,32 +2618,28 @@ class wsBase /** * 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 + * @return $eturns will return an object */ - public function importProcessFromLibrary( - $processId, - $version='', - $importOption='', - $usernameLibrary='', - $passwordLibrary='' - ) { + public function importProcessFromLibrary ($processId, $version = '', $importOption = '', $usernameLibrary = '', $passwordLibrary = '') + { try { - G::LoadClass('processes'); + G::LoadClass( 'processes' ); //$versionReq = $_GET['v']; //. (isset($_GET['s']) ? '&s=' . $_GET['s'] : '') - $ipaddress = $_SERVER['REMOTE_ADDR']; + $ipaddress = $_SERVER['REMOTE_ADDR']; $oProcesses = new Processes(); $oProcesses->ws_open_public(); - $oProcess = $oProcesses->ws_processGetData($processId); + $oProcess = $oProcesses->ws_processGetData( $processId ); if ($oProcess->status_code != 0) { - throw (new Exception($oProcess->message)); + throw (new Exception( $oProcess->message )); } $privacy = $oProcess->privacy; @@ -2710,51 +2649,52 @@ class wsBase if ($privacy != 'FREE') { global $sessionId; $antSession = $sessionId; - $oProcesses->ws_open($usernameLibrary, $passwordLibrary); + $oProcesses->ws_open( $usernameLibrary, $passwordLibrary ); $strSession = "&s=" . $sessionId; $sessionId = $antSession; } //downloading the file $localPath = PATH_DOCUMENT . 'input' . PATH_SEP; - G::mk_dir($localPath); + G::mk_dir( $localPath ); $newfilename = G::GenerateUniqueId() . '.pm'; $downloadUrl = PML_DOWNLOAD_URL . '?id=' . $processId . $strSession; $oProcess = new Processes(); - $oProcess->downloadFile($downloadUrl, $localPath, $newfilename); + $oProcess->downloadFile( $downloadUrl, $localPath, $newfilename ); //getting the ProUid from the file recently downloaded - $oData = $oProcess->getProcessData($localPath . $newfilename); + $oData = $oProcess->getProcessData( $localPath . $newfilename ); - if (is_null($oData)) { + if (is_null( $oData )) { $data['DOWNLOAD_URL'] = $downloadUrl; - $data['LOCAL_PATH'] = $localPath; + $data['LOCAL_PATH'] = $localPath; $data['NEW_FILENAME'] = $newfilename; - throw new Exception(G::loadTranslation('ID_ERROR_URL_PROCESS_INVALID', SYS_LANG, $data)); + throw new Exception( G::loadTranslation( 'ID_ERROR_URL_PROCESS_INVALID', SYS_LANG, $data ) ); } $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)) { + if ($oProcess->processExists( $sProUid )) { //Update the current Process, overwriting all tasks and steps if ($importOption == 1) { - $oProcess->updateProcessFromData ($oData, $localPath . $newfilename ); + $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); + + 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 != '..')) { $strAux = PATH_OUTTRUNK . 'compiled' . PATH_SEP . 'xmlform' . PATH_SEP; $strAux = $strAux . $sProUid . PATH_SEP . $sObjectName; - unlink($strAux); + unlink( $strAux ); } } @@ -2766,77 +2706,73 @@ class wsBase //Disable current Process and create a new version of the Process if ($importOption == 2) { - $oProcess->disablePreviousProcesses($sProUid); + $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); + $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); + $oProcess->setProcessGuid( $oData, $sNewProUid ); - $strAux = "Copy of - " . $oData->process['PRO_TITLE'] . ' - ' . date('M d, H:i'); + $strAux = "Copy of - " . $oData->process['PRO_TITLE'] . ' - ' . date( 'M d, H:i' ); $oData->process['PRO_TITLE'] = $strAux; - $oProcess->renewAll($oData); - $oProcess->createProcessFromData($oData, $localPath . $newfilename); + $oProcess->renewAll( $oData ); + $oProcess->createProcessFromData( $oData, $localPath . $newfilename ); } if ($importOption != 1 && $importOption != 2 && $importOption != 3) { - throw new Exception(G::loadTranslation('ID_PROCESS_ALREADY_IN_SYSTEM')); + throw new Exception( G::loadTranslation( 'ID_PROCESS_ALREADY_IN_SYSTEM' ) ); } } //finally, creating the process if the process doesn't exist - if (!$oProcess->processExists($processId)) { - $oProcess->createProcessFromData($oData, $localPath . $newfilename); + 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); + $processData = $oProcess->ws_processGetData( $processId ); - $result->status_code = 0; - $result->message = G::loadTranslation('ID_COMMAND_EXECUTED_SUCCESSFULLY'); - $result->timestamp = date('Y-m-d H:i:s'); - $result->processId = $processId; + $result->status_code = 0; + $result->message = G::loadTranslation( 'ID_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; + $result->category = (isset( $processData->category ) ? $processData->category : ''); + $result->version = $processData->version; return $result; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } } - public function getCaseNotes($applicationID, $userUid='') + public function getCaseNotes ($applicationID, $userUid = '') { try { - G::LoadClass('case'); + G::LoadClass( 'case' ); - $result = new wsGetCaseNotesResponse( - 0, - G::loadTranslation('ID_SUCCESS'), - Cases::getCaseNotes($applicationID, 'array', $userUid) - ); + $result = new wsGetCaseNotesResponse( 0, G::loadTranslation( 'ID_SUCCESS' ), Cases::getCaseNotes( $applicationID, 'array', $userUid ) ); - $var = array(); + $var = array (); foreach ($result->notes as $key => $value) { - $var2 = array(); + $var2 = array (); foreach ($value as $keys => $values) { - $field = strtolower($keys); + $field = strtolower( $keys ); $var2[$field] = $values; } @@ -2847,7 +2783,7 @@ class wsBase return $result; } catch (Exception $e) { - $result = new wsResponse(100, $e->getMessage()); + $result = new wsResponse( 100, $e->getMessage() ); return $result; } @@ -2855,33 +2791,31 @@ class wsBase /** * Delete case + * * @param string caseUid : ID of the case. * @return $result will return an object */ - public function deleteCase($caseUid) + public function deleteCase ($caseUid) { try { - if (empty($caseUid)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " caseUid"); + if (empty( $caseUid )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " caseUid" ); return $result; } $case = new Cases(); - $case->removeCase($caseUid); + $case->removeCase( $caseUid ); //Response - $res = new wsResponse(0, G::LoadTranslation("ID_COMMAND_EXECUTED_SUCCESSFULLY")); + $res = new wsResponse( 0, G::LoadTranslation( "ID_COMMAND_EXECUTED_SUCCESSFULLY" ) ); - $result = array( - "status_code" => $res->status_code, - "message" => $res->message, - "timestamp" => $res->timestamp + $result = array ("status_code" => $res->status_code,"message" => $res->message,"timestamp" => $res->timestamp ); return $result; } catch (Exception $e) { - $result = wsResponse(100, $e->getMessage()); + $result = wsResponse( 100, $e->getMessage() ); return $result; } @@ -2889,47 +2823,45 @@ class wsBase /** * Cancel case - * @param string caseUid : ID of the case. - * @param int delIndex : Delegation index of the case. - * @param string userUid : The unique ID of the user who will cancel the case. + * + * @param string caseUid : ID of the case. + * @param int delIndex : Delegation index of the case. + * @param string userUid : The unique ID of the user who will cancel the case. * @return $result will return an object */ - public function cancelCase($caseUid, $delIndex, $userUid) + public function cancelCase ($caseUid, $delIndex, $userUid) { try { - if (empty($caseUid)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " caseUid"); + if (empty( $caseUid )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " caseUid" ); return $result; } - if (empty($delIndex)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " delIndex"); + if (empty( $delIndex )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " delIndex" ); return $result; } - if (empty($userUid)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " userUid"); + if (empty( $userUid )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " userUid" ); return $result; } $case = new Cases(); - $case->cancelCase($caseUid, $delIndex, $userUid); + $case->cancelCase( $caseUid, $delIndex, $userUid ); //Response - $res = new wsResponse(0, G::LoadTranslation("ID_COMMAND_EXECUTED_SUCCESSFULLY")); + $res = new wsResponse( 0, G::LoadTranslation( "ID_COMMAND_EXECUTED_SUCCESSFULLY" ) ); - $result = array( - "status_code" => $res->status_code, - "message" => $res->message, - "timestamp" => $res->timestamp + $result = array ("status_code" => $res->status_code,"message" => $res->message,"timestamp" => $res->timestamp ); return $result; } catch (Exception $e) { - $result = wsResponse(100, $e->getMessage()); + $result = wsResponse( 100, $e->getMessage() ); return $result; } @@ -2937,57 +2869,55 @@ class wsBase /** * Pause case - * @param string caseUid : ID of the case. - * @param int delIndex : Delegation index of the case. - * @param string userUid : The unique ID of the user who will pause the case. + * + * @param string caseUid : ID of the case. + * @param int delIndex : Delegation index of the case. + * @param string userUid : The unique ID of the user who will pause the case. * @param string unpauseDate : Optional parameter. The date in the format "yyyy-mm-dd" indicating when to unpause - * the case. + * the case. * @return $result will return an object */ - public function pauseCase($caseUid, $delIndex, $userUid, $unpauseDate=null) + public function pauseCase ($caseUid, $delIndex, $userUid, $unpauseDate = null) { try { - if (empty($caseUid)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " caseUid"); + if (empty( $caseUid )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " caseUid" ); return $result; } - if (empty($delIndex)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " delIndex"); + if (empty( $delIndex )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " delIndex" ); return $result; } - if (empty($userUid)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " userUid"); + if (empty( $userUid )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " userUid" ); return $result; } - if (!empty($unpauseDate)) { - if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $unpauseDate)) { - $result = new wsResponse(100, G::LoadTranslation("ID_INVALID_DATA") . " $unpauseDate"); + if (! empty( $unpauseDate )) { + if (! preg_match( "/^\d{4}-\d{2}-\d{2}$/", $unpauseDate )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_INVALID_DATA" ) . " $unpauseDate" ); return $result; } } $case = new Cases(); - $case->pauseCase($caseUid, $delIndex, $userUid, $unpauseDate); + $case->pauseCase( $caseUid, $delIndex, $userUid, $unpauseDate ); //Response - $res = new wsResponse(0, G::LoadTranslation("ID_COMMAND_EXECUTED_SUCCESSFULLY")); + $res = new wsResponse( 0, G::LoadTranslation( "ID_COMMAND_EXECUTED_SUCCESSFULLY" ) ); - $result = array( - "status_code" => $res->status_code, - "message" => $res->message, - "timestamp" => $res->timestamp + $result = array ("status_code" => $res->status_code,"message" => $res->message,"timestamp" => $res->timestamp ); return $result; } catch (Exception $e) { - $result = wsResponse(100, $e->getMessage()); + $result = wsResponse( 100, $e->getMessage() ); return $result; } @@ -2995,47 +2925,45 @@ class wsBase /** * Unpause case - * @param string caseUid : ID of the case. - * @param int delIndex : Delegation index of the case. - * @param string userUid : The unique ID of the user who will unpause the case. + * + * @param string caseUid : ID of the case. + * @param int delIndex : Delegation index of the case. + * @param string userUid : The unique ID of the user who will unpause the case. * @return $result will return an object */ - public function unpauseCase($caseUid, $delIndex, $userUid) + public function unpauseCase ($caseUid, $delIndex, $userUid) { try { - if (empty($caseUid)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " caseUid"); + if (empty( $caseUid )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " caseUid" ); return $result; } - if (empty($delIndex)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " delIndex"); + if (empty( $delIndex )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " delIndex" ); return $result; } - if (empty($userUid)) { - $result = new wsResponse(100, G::LoadTranslation("ID_REQUIRED_FIELD") . " userUid"); + if (empty( $userUid )) { + $result = new wsResponse( 100, G::LoadTranslation( "ID_REQUIRED_FIELD" ) . " userUid" ); return $result; } $case = new Cases(); - $case->unpauseCase($caseUid, $delIndex, $userUid); + $case->unpauseCase( $caseUid, $delIndex, $userUid ); //Response - $res = new wsResponse(0, G::LoadTranslation("ID_COMMAND_EXECUTED_SUCCESSFULLY")); + $res = new wsResponse( 0, G::LoadTranslation( "ID_COMMAND_EXECUTED_SUCCESSFULLY" ) ); - $result = array( - "status_code" => $res->status_code, - "message" => $res->message, - "timestamp" => $res->timestamp + $result = array ("status_code" => $res->status_code,"message" => $res->message,"timestamp" => $res->timestamp ); return $result; } catch (Exception $e) { - $result = wsResponse(100, $e->getMessage()); + $result = wsResponse( 100, $e->getMessage() ); return $result; } From 264c13737dea5fbf15a85117f5457627c1940078 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:30:11 -0400 Subject: [PATCH 16/18] CODE STYLE class.xmlDB.php --- workflow/engine/classes/class.xmlDb.php | 1112 +++++++++++------------ 1 file changed, 552 insertions(+), 560 deletions(-) diff --git a/workflow/engine/classes/class.xmlDb.php b/workflow/engine/classes/class.xmlDb.php index f9af52543..b56c00f41 100755 --- a/workflow/engine/classes/class.xmlDb.php +++ b/workflow/engine/classes/class.xmlDb.php @@ -1,6 +1,8 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. * */ - /** -* XMLDB -* -* ProcessMaker Open Source Edition -* -* @copyright (C) 2004 - 2008 Colosa Inc.23 -* @package workflow.engine.ProcessMaker -*/ -class XMLDB + * XMLDB + * + * ProcessMaker Open Source Edition + * + * @copyright (C) 2004 - 2008 Colosa Inc.23 + * @package workflow.engine.ProcessMaker + * + */ +class XMLDB { - /** - * &connect - * - * @param string $dsn - * @return array $options - */ - function &connect ($dsn, $options = array()) - { - //Needed for $mysql_real_escape_string - $mresdbc = new DBConnection(); + /** + * &connect + * + * @param string $dsn + * @return array $options + */ + function &connect ($dsn, $options = array()) + { + //Needed for $mysql_real_escape_string + $mresdbc = new DBConnection(); - if ( !file_exists( $dsn ) ) { - $err = new DB_Error( "File $dsn not found." ); - return $err; + if (! file_exists( $dsn )) { + $err = new DB_Error( "File $dsn not found." ); + return $err; + } + $dbc = new XMLConnection( $dsn ); + return $dbc; } - $dbc = new XMLConnection($dsn); - return $dbc; - } - /** - * isError - * - * @param string $result - * @return boolean is_a($result, 'DB_Error') - */ - function isError ( $result ) - { - return is_a($result, 'DB_Error'); - } + /** + * isError + * + * @param string $result + * @return boolean is_a($result, 'DB_Error') + */ + function isError ($result) + { + return is_a( $result, 'DB_Error' ); + } } /** -* XMLConnection -* -* ProcessMaker Open Source Edition -* -* @copyright (C) 2004 - 2008 Colosa Inc.23 -* @package workflow.engine.ProcessMaker -*/ -class XMLConnection + * XMLConnection + * + * ProcessMaker Open Source Edition + * + * @copyright (C) 2004 - 2008 Colosa Inc.23 + * @package workflow.engine.ProcessMaker + * + */ +class XMLConnection { - var $phptype = 'myxml'; - var $caseFolding = true; - var $xmldoc = NULL; - var $xmlFile = ''; + var $phptype = 'myxml'; + var $caseFolding = true; + var $xmldoc = NULL; + var $xmlFile = ''; - /** - * XMLConnection - * - * @param string $file - * @return void - */ - function XMLConnection ( $file ) - { - $this->xmldoc = new Xml_Document(); - $this->xmldoc->parseXmlFile( $file ); - $this->xmlFile = $file; - } - - /** - * &query - * Actualy the only one supported query is simple SELECT. - * - * @param string $sql - * @return object(XMLResult) $result - */ - function &query( $sql ) - { - if ( !isset( $this->xmldoc ) ) { - $err = new DB_Error( "Error: Closed xmlConnection." ); - return $err; + /** + * XMLConnection + * + * @param string $file + * @return void + */ + function XMLConnection ($file) + { + $this->xmldoc = new Xml_Document(); + $this->xmldoc->parseXmlFile( $file ); + $this->xmlFile = $file; } - if (1===preg_match('/^\s*SELECT\s+([\w\W]+?)(?:\s+FROM\s+`?([^`]+?)`?)(?:\s+WHERE\s+([\w\W]+?))?(?:\s+GROUP\s+BY\s+([\w\W]+?))?(?:\s+ORDER\s+BY\s+([\w\W]+?))?(?:\s+BETWEEN\s+([\w\W]+?)\s+AND\s+([\w\W]+?))?(?:\s+LIMIT\s+(\d+)\s*,\s*(\d+))?\s*$/im', $sql, $matches)) { - $sqlColumns = $matches[1]; - $sqlFrom = isset($matches[2])?$matches[2]:''; - $sqlWhere = isset($matches[3])?$matches[3]:''; - $sqlGroupBy = isset($matches[4])?$matches[4]:''; - $sqlOrderBy = isset($matches[5])?$matches[5]:''; - $sqlLowLimit = isset($matches[8])?$matches[8]:''; - $sqlHighLimit = isset($matches[9])?$matches[9]:''; - /* Start Block: Fields list */ - $count = preg_match_all('/\s*(\*|[\w\.]+)(?:\s+AS\s+([\w\.]+))?/im',$sqlColumns,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); - $fieldsList = array(); - for($r=0; $r< $count;$r++) { - $name = (is_array($match[2][$r]) && $match[2][$r][0]!=='') ? $match[2][$r][0] : $match[1][$r][0]; - $fieldsList[$name] = $match[1][$r][0]; - } - /* End Block */ + + /** + * &query + * Actualy the only one supported query is simple SELECT. + * + * @param string $sql + * @return object(XMLResult) $result + */ + function &query ($sql) + { + if (! isset( $this->xmldoc )) { + $err = new DB_Error( "Error: Closed xmlConnection." ); + return $err; + } + if (1 === preg_match( '/^\s*SELECT\s+([\w\W]+?)(?:\s+FROM\s+`?([^`]+?)`?)(?:\s+WHERE\s+([\w\W]+?))?(?:\s+GROUP\s+BY\s+([\w\W]+?))?(?:\s+ORDER\s+BY\s+([\w\W]+?))?(?:\s+BETWEEN\s+([\w\W]+?)\s+AND\s+([\w\W]+?))?(?:\s+LIMIT\s+(\d+)\s*,\s*(\d+))?\s*$/im', $sql, $matches )) { + $sqlColumns = $matches[1]; + $sqlFrom = isset( $matches[2] ) ? $matches[2] : ''; + $sqlWhere = isset( $matches[3] ) ? $matches[3] : ''; + $sqlGroupBy = isset( $matches[4] ) ? $matches[4] : ''; + $sqlOrderBy = isset( $matches[5] ) ? $matches[5] : ''; + $sqlLowLimit = isset( $matches[8] ) ? $matches[8] : ''; + $sqlHighLimit = isset( $matches[9] ) ? $matches[9] : ''; + /* Start Block: Fields list */ + $count = preg_match_all( '/\s*(\*|[\w\.]+)(?:\s+AS\s+([\w\.]+))?/im', $sqlColumns, $match, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE ); + $fieldsList = array (); + for ($r = 0; $r < $count; $r ++) { + $name = (is_array( $match[2][$r] ) && $match[2][$r][0] !== '') ? $match[2][$r][0] : $match[1][$r][0]; + $fieldsList[$name] = $match[1][$r][0]; + } + /* End Block */ /* Start Block: Order list */ - $count=preg_match_all('/\s*(\*|[\w\.]+)(\s+ASC|\s+DESC)?\s*,?/im',$sqlOrderBy,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); - $orderList = array(); - for($r = $count-1; $r>=0; $r--) { - $direction = (is_array($match[2][$r]) && $match[2][$r][0]!=='') ? $match[2][$r][0] : 'ASC'; - $direction = strtoupper( $direction ); - $orderList[$match[1][$r][0]] = $direction; - } - /* End Block */ - $xmlFrom = '/' . str_replace( '.','/' , $sqlFrom ); - $node =& $this->xmldoc->findNode( $xmlFrom ); - if (!isset($node)) { - //$err = new DB_Error( "$xmlFrom node not found in $dsn." ); - throw new Exception( "$xmlFrom node not found in " . $this->xmlFile . "." ); - return $err; - } else { - $res = $this->fetchChildren ( $node ); - } - /* Start Block: WHERE*/ - if ($sqlWhere!=='') { - /*Start Block: Replace the operator */ - $blocks = preg_split('/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', $sqlWhere , -1 , PREG_SPLIT_DELIM_CAPTURE ); - $sqlWhere = ''; - for($r = 0 ; $r < sizeof($blocks) ; $r++ ){ - if ( ($r % 2) === 0 ) { - $blocks[$r] = str_replace( '=' , '==', $blocks[$r]); - $blocks[$r] = str_replace( '<>' , '!=', $blocks[$r]); - $blocks[$r] = str_replace( 'AND' , '&&', $blocks[$r]); - $blocks[$r] = str_replace( 'and' , '&&', $blocks[$r]); - $blocks[$r] = str_replace( 'OR' , '||', $blocks[$r]); - $blocks[$r] = str_replace( 'or' , '||', $blocks[$r]); - $blocks[$r] = str_replace( 'NOT' , '!', $blocks[$r]); - $blocks[$r] = str_replace( 'not' , '!', $blocks[$r]); - $blocks[$r] = preg_replace('/\b[a-zA-Z_][\w\.]*\b/im', '$res[$r][\'$0\']', $blocks[$r] ); - $blocks[$r] = preg_replace('/\$res\[\$r\]\[\'(like)\'\]/im', '$1', $blocks[$r] ); - } - $sqlWhere .= $blocks[$r]; - } - $sqlWhere = preg_replace_callback('/(.+)\s+like\s+("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', - array('XMLConnection','sqlWhereLike'), $sqlWhere ); - $sqlWhere = preg_replace_callback('/"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'/im', - array('XMLConnection','sqlString'), $sqlWhere ); - $newRes = array(); - for( $r=0 ; $r < sizeof($res) ; $r++ ) { - $evalWhere = false; - @eval('$evalWhere = '.$sqlWhere.';'); - if ( $evalWhere ) $newRes[] = $res[$r]; - } - $res = $newRes; - } - /* End Block */ + $count = preg_match_all( '/\s*(\*|[\w\.]+)(\s+ASC|\s+DESC)?\s*,?/im', $sqlOrderBy, $match, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE ); + $orderList = array (); + for ($r = $count - 1; $r >= 0; $r --) { + $direction = (is_array( $match[2][$r] ) && $match[2][$r][0] !== '') ? $match[2][$r][0] : 'ASC'; + $direction = strtoupper( $direction ); + $orderList[$match[1][$r][0]] = $direction; + } + /* End Block */ + $xmlFrom = '/' . str_replace( '.', '/', $sqlFrom ); + $node = & $this->xmldoc->findNode( $xmlFrom ); + if (! isset( $node )) { + //$err = new DB_Error( "$xmlFrom node not found in $dsn." ); + throw new Exception( "$xmlFrom node not found in " . $this->xmlFile . "." ); + return $err; + } else { + $res = $this->fetchChildren( $node ); + } + /* Start Block: WHERE*/ + if ($sqlWhere !== '') { + /*Start Block: Replace the operator */ + $blocks = preg_split( '/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', $sqlWhere, - 1, PREG_SPLIT_DELIM_CAPTURE ); + $sqlWhere = ''; + for ($r = 0; $r < sizeof( $blocks ); $r ++) { + if (($r % 2) === 0) { + $blocks[$r] = str_replace( '=', '==', $blocks[$r] ); + $blocks[$r] = str_replace( '<>', '!=', $blocks[$r] ); + $blocks[$r] = str_replace( 'AND', '&&', $blocks[$r] ); + $blocks[$r] = str_replace( 'and', '&&', $blocks[$r] ); + $blocks[$r] = str_replace( 'OR', '||', $blocks[$r] ); + $blocks[$r] = str_replace( 'or', '||', $blocks[$r] ); + $blocks[$r] = str_replace( 'NOT', '!', $blocks[$r] ); + $blocks[$r] = str_replace( 'not', '!', $blocks[$r] ); + $blocks[$r] = preg_replace( '/\b[a-zA-Z_][\w\.]*\b/im', '$res[$r][\'$0\']', $blocks[$r] ); + $blocks[$r] = preg_replace( '/\$res\[\$r\]\[\'(like)\'\]/im', '$1', $blocks[$r] ); + } + $sqlWhere .= $blocks[$r]; + } + $sqlWhere = preg_replace_callback( '/(.+)\s+like\s+("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', array ('XMLConnection','sqlWhereLike' + ), $sqlWhere ); + $sqlWhere = preg_replace_callback( '/"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'/im', array ('XMLConnection','sqlString' + ), $sqlWhere ); + $newRes = array (); + for ($r = 0; $r < sizeof( $res ); $r ++) { + $evalWhere = false; + @eval( '$evalWhere = ' . $sqlWhere . ';' ); + if ($evalWhere) + $newRes[] = $res[$r]; + } + $res = $newRes; + } + /* End Block */ /* Start Block: Expands the resultant data according to fill an array * with the required fields in the query. */ - for( $r=0 ; $r < sizeof($res) ; $r++ ) { - $res[$r] = $this->expandFields( $res[$r] , $fieldsList ); - } - /* End Block */ - /* Start Block: ORDER BY*/ - foreach($orderList as $field => $direction ) { - for( $i=0 ; $i < sizeof($res) ; $i++ ) { - for( $j= $i+1 ; $j < sizeof($res) ; $j++ ) { - $condition = ($direction==='ASC')? - ($res[$j] < $res[$i]) : ($res[$j] > $res[$i]); - if ( $condition ) { - $swap = $res[$i]; - $res[$i] = $res[$j]; - $res[$j] = $swap; + for ($r = 0; $r < sizeof( $res ); $r ++) { + $res[$r] = $this->expandFields( $res[$r], $fieldsList ); } - } - } - } - /* End Block */ + /* End Block */ + /* Start Block: ORDER BY*/ + foreach ($orderList as $field => $direction) { + for ($i = 0; $i < sizeof( $res ); $i ++) { + for ($j = $i + 1; $j < sizeof( $res ); $j ++) { + $condition = ($direction === 'ASC') ? ($res[$j] < $res[$i]) : ($res[$j] > $res[$i]); + if ($condition) { + $swap = $res[$i]; + $res[$i] = $res[$j]; + $res[$j] = $swap; + } + } + } + } + /* End Block */ /* Start Block: Apply limits */ - if ($sqlLowLimit!='' && $sqlHighLimit!='') - { - $sqlLowLimit = (int) $sqlLowLimit; - $sqlHighLimit = (int) $sqlHighLimit; - $res = array_slice( $res , $sqlLowLimit , $sqlHighLimit ); - } - /* End Block */ - $result = new XMLResult( $res ); - return $result; - } - elseif (1===preg_match('/^\s*DELETE\s+FROM\s+`?([^`]+?)`?(?:\s+WHERE\s+([\w\W]+?))?\s*$/im',$sql,$matches)) - { - $sqlFrom = isset($matches[1])?$matches[1]:''; - $sqlWhere = isset($matches[2])?$matches[2]:'1'; - /* Start Block: WHERE*/ + if ($sqlLowLimit != '' && $sqlHighLimit != '') { + $sqlLowLimit = (int) $sqlLowLimit; + $sqlHighLimit = (int) $sqlHighLimit; + $res = array_slice( $res, $sqlLowLimit, $sqlHighLimit ); + } + /* End Block */ + $result = new XMLResult( $res ); + return $result; + } elseif (1 === preg_match( '/^\s*DELETE\s+FROM\s+`?([^`]+?)`?(?:\s+WHERE\s+([\w\W]+?))?\s*$/im', $sql, $matches )) { + $sqlFrom = isset( $matches[1] ) ? $matches[1] : ''; + $sqlWhere = isset( $matches[2] ) ? $matches[2] : '1'; + /* Start Block: WHERE*/ /*Start Block: Replace the operator */ - $blocks = preg_split('/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', $sqlWhere , -1 , PREG_SPLIT_DELIM_CAPTURE ); - $sqlWhere = ''; - for($r = 0 ; $r < sizeof($blocks) ; $r++ ){ - if ( ($r % 2) === 0 ) { - $blocks[$r] = str_replace( '=' , '==', $blocks[$r]); - $blocks[$r] = str_replace( '<>' , '!=', $blocks[$r]); - $blocks[$r] = str_replace( 'AND' , '&&', $blocks[$r]); - $blocks[$r] = str_replace( 'and' , '&&', $blocks[$r]); - $blocks[$r] = str_replace( 'OR' , '||', $blocks[$r]); - $blocks[$r] = str_replace( 'or' , '||', $blocks[$r]); - $blocks[$r] = str_replace( 'NOT' , '!', $blocks[$r]); - $blocks[$r] = str_replace( 'not' , '!', $blocks[$r]); - $blocks[$r] = preg_replace('/\b[a-zA-Z_][\w\.]*\b/im', '$res[$r][\'$0\']', $blocks[$r] ); - $blocks[$r] = preg_replace('/\$res\[\$r\]\[\'(like)\'\]/im', '$1', $blocks[$r] ); - } - $sqlWhere .= $blocks[$r]; - } - /* End Block */ - $sqlWhere = preg_replace_callback('/(.+)\s+like\s+("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', - array('XMLConnection','sqlWhereLike'), $sqlWhere ); - $sqlWhere = preg_replace_callback('/"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'/im', - array('XMLConnection','sqlString'), $sqlWhere ); + $blocks = preg_split( '/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', $sqlWhere, - 1, PREG_SPLIT_DELIM_CAPTURE ); + $sqlWhere = ''; + for ($r = 0; $r < sizeof( $blocks ); $r ++) { + if (($r % 2) === 0) { + $blocks[$r] = str_replace( '=', '==', $blocks[$r] ); + $blocks[$r] = str_replace( '<>', '!=', $blocks[$r] ); + $blocks[$r] = str_replace( 'AND', '&&', $blocks[$r] ); + $blocks[$r] = str_replace( 'and', '&&', $blocks[$r] ); + $blocks[$r] = str_replace( 'OR', '||', $blocks[$r] ); + $blocks[$r] = str_replace( 'or', '||', $blocks[$r] ); + $blocks[$r] = str_replace( 'NOT', '!', $blocks[$r] ); + $blocks[$r] = str_replace( 'not', '!', $blocks[$r] ); + $blocks[$r] = preg_replace( '/\b[a-zA-Z_][\w\.]*\b/im', '$res[$r][\'$0\']', $blocks[$r] ); + $blocks[$r] = preg_replace( '/\$res\[\$r\]\[\'(like)\'\]/im', '$1', $blocks[$r] ); + } + $sqlWhere .= $blocks[$r]; + } + /* End Block */ + $sqlWhere = preg_replace_callback( '/(.+)\s+like\s+("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', array ('XMLConnection','sqlWhereLike' + ), $sqlWhere ); + $sqlWhere = preg_replace_callback( '/"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'/im', array ('XMLConnection','sqlString' + ), $sqlWhere ); - /*Start Block: Removing fields */ - $xmlFrom = '/' . str_replace( '.','/' , $sqlFrom ); - $node =& $this->xmldoc->findNode( $xmlFrom ); - if (!isset($node)) { - $err = new DB_Error( "$xmlFrom node not found!." ); - return $err; - } else { - $res = $this->fetchChildren ( $node ); - } - $newRes = array(); - for( $r=0 ; $r < sizeof($res) ; $r++ ) { - $evalWhere = false; - @eval('$evalWhere = '.$sqlWhere.';'); - if ( $evalWhere ) { - unset($node->children[$r]); - $newRes[] = $res[$r]; - } - } - //Re-index - $node->children = array_values( $node->children ); - /* End Block */ - $this->xmldoc->save( $this->xmlFile ); - $result = new XMLResult( $newRes ); - return $result; - } - elseif (1===preg_match('/^\s*INSERT\s+INTO\s+`?([^`]+?)`?\s*\(([\w\W]+?)\)\s+VALUES\s*\(([\w\W]+?)\)\s*$/im',$sql,$matches)) - { - $sqlFrom = isset($matches[1])?$matches[1]:''; - $sqlColumns = isset($matches[2])?$matches[2]:'1'; - $sqlValues = isset($matches[3])?$matches[3]:'1'; - $xmlFrom = '/' . str_replace( '.','/' , $sqlFrom ); - $node =& $this->xmldoc->findNode( $xmlFrom ); - /* Start Block: Fields list */ - $count = preg_match_all('/([\w\.]+)/im',$sqlColumns,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); - $fieldsList = array(); - for($r=0; $r< $count;$r++) { - $fieldsList[] = $match[1][$r][0]; - } - /* End Block */ + /*Start Block: Removing fields */ + $xmlFrom = '/' . str_replace( '.', '/', $sqlFrom ); + $node = & $this->xmldoc->findNode( $xmlFrom ); + if (! isset( $node )) { + $err = new DB_Error( "$xmlFrom node not found!." ); + return $err; + } else { + $res = $this->fetchChildren( $node ); + } + $newRes = array (); + for ($r = 0; $r < sizeof( $res ); $r ++) { + $evalWhere = false; + @eval( '$evalWhere = ' . $sqlWhere . ';' ); + if ($evalWhere) { + unset( $node->children[$r] ); + $newRes[] = $res[$r]; + } + } + //Re-index + $node->children = array_values( $node->children ); + /* End Block */ + $this->xmldoc->save( $this->xmlFile ); + $result = new XMLResult( $newRes ); + return $result; + } elseif (1 === preg_match( '/^\s*INSERT\s+INTO\s+`?([^`]+?)`?\s*\(([\w\W]+?)\)\s+VALUES\s*\(([\w\W]+?)\)\s*$/im', $sql, $matches )) { + $sqlFrom = isset( $matches[1] ) ? $matches[1] : ''; + $sqlColumns = isset( $matches[2] ) ? $matches[2] : '1'; + $sqlValues = isset( $matches[3] ) ? $matches[3] : '1'; + $xmlFrom = '/' . str_replace( '.', '/', $sqlFrom ); + $node = & $this->xmldoc->findNode( $xmlFrom ); + /* Start Block: Fields list */ + $count = preg_match_all( '/([\w\.]+)/im', $sqlColumns, $match, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE ); + $fieldsList = array (); + for ($r = 0; $r < $count; $r ++) { + $fieldsList[] = $match[1][$r][0]; + } + /* End Block */ /* Start Block: Fields Values */ - $count=preg_match_all('/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'|\d+)/im', $sqlValues,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); - $fieldsValues = array(); - for($r=0; $r< $count;$r++) { - if (substr($match[1][$r][0],0,1)==='"') { - $match[1][$r][0] = substr( $match[1][$r][0] ,1, -1 ); - $match[1][$r][0] = str_replace('""', '"' , $match[1][$r][0] ); - $match[1][$r][0] = str_replace("''", "'" , $match[1][$r][0] ); - } if (substr($match[1][$r][0],0,1)==="'") { - $match[1][$r][0] = substr( $match[1][$r][0] ,1, -1 ); - $match[1][$r][0] = str_replace("''", "'" , $match[1][$r][0] ); - $match[1][$r][0] = str_replace('""', '"' , $match[1][$r][0] ); - } - $fieldsValues[$fieldsList[$r]] = $match[1][$r][0]; - } - /* End Block */ - $AAA = getNames($this->xmldoc->children[0]->children); - $this->insertRow( $node , $fieldsValues ); - $DDD = getNames($this->xmldoc->children[0]->children); - $this->xmldoc->save( $this->xmlFile ); - $result = new XMLResult( array( $fieldsValues ) ); - return $result; - } - elseif (1===preg_match('/^\s*UPDATE\s+`?([^`]+?)`?\s+SET\s+((?:(?:[a-z][\w\.]*)\s*=\s*(?:"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'|\d+)\s*(?:,\s*)?)+)(?:\s+WHERE\s+([\w\W]+?))?\s*$/im',$sql,$matches)) - { - $sqlFrom = isset($matches[1])?$matches[1]:''; - $sqlColumns = isset($matches[2])?$matches[2]:''; - $sqlWhere = isset($matches[3])?$matches[3]:'1'; - $count = preg_match_all('/([a-z][\w\.]*)\s*=\s*("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'|\d+)/im',$sqlColumns,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); - $fieldsValues = array(); - for($r=0; $r< $count;$r++) { - if (substr($match[2][$r][0],0,1)==='"') { - $match[2][$r][0] = substr( $match[2][$r][0] ,1, -1 ); - $match[2][$r][0] = str_replace('""', '"' , $match[2][$r][0] ); - $match[2][$r][0] = str_replace("''", "'" , $match[2][$r][0] ); - } if (substr($match[2][$r][0],0,1)==="'") { - $match[2][$r][0] = substr( $match[2][$r][0] ,1, -1 ); - $match[2][$r][0] = str_replace("''", "'" , $match[2][$r][0] ); - $match[2][$r][0] = str_replace('""', '"' , $match[2][$r][0] ); - } - $fieldsValues[$match[1][$r][0]] = $match[2][$r][0]; - } - /* Start Block: WHERE*/ + $count = preg_match_all( '/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'|\d+)/im', $sqlValues, $match, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE ); + $fieldsValues = array (); + for ($r = 0; $r < $count; $r ++) { + if (substr( $match[1][$r][0], 0, 1 ) === '"') { + $match[1][$r][0] = substr( $match[1][$r][0], 1, - 1 ); + $match[1][$r][0] = str_replace( '""', '"', $match[1][$r][0] ); + $match[1][$r][0] = str_replace( "''", "'", $match[1][$r][0] ); + } + if (substr( $match[1][$r][0], 0, 1 ) === "'") { + $match[1][$r][0] = substr( $match[1][$r][0], 1, - 1 ); + $match[1][$r][0] = str_replace( "''", "'", $match[1][$r][0] ); + $match[1][$r][0] = str_replace( '""', '"', $match[1][$r][0] ); + } + $fieldsValues[$fieldsList[$r]] = $match[1][$r][0]; + } + /* End Block */ + $AAA = getNames( $this->xmldoc->children[0]->children ); + $this->insertRow( $node, $fieldsValues ); + $DDD = getNames( $this->xmldoc->children[0]->children ); + $this->xmldoc->save( $this->xmlFile ); + $result = new XMLResult( array ($fieldsValues + ) ); + return $result; + } elseif (1 === preg_match( '/^\s*UPDATE\s+`?([^`]+?)`?\s+SET\s+((?:(?:[a-z][\w\.]*)\s*=\s*(?:"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'|\d+)\s*(?:,\s*)?)+)(?:\s+WHERE\s+([\w\W]+?))?\s*$/im', $sql, $matches )) { + $sqlFrom = isset( $matches[1] ) ? $matches[1] : ''; + $sqlColumns = isset( $matches[2] ) ? $matches[2] : ''; + $sqlWhere = isset( $matches[3] ) ? $matches[3] : '1'; + $count = preg_match_all( '/([a-z][\w\.]*)\s*=\s*("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'|\d+)/im', $sqlColumns, $match, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE ); + $fieldsValues = array (); + for ($r = 0; $r < $count; $r ++) { + if (substr( $match[2][$r][0], 0, 1 ) === '"') { + $match[2][$r][0] = substr( $match[2][$r][0], 1, - 1 ); + $match[2][$r][0] = str_replace( '""', '"', $match[2][$r][0] ); + $match[2][$r][0] = str_replace( "''", "'", $match[2][$r][0] ); + } + if (substr( $match[2][$r][0], 0, 1 ) === "'") { + $match[2][$r][0] = substr( $match[2][$r][0], 1, - 1 ); + $match[2][$r][0] = str_replace( "''", "'", $match[2][$r][0] ); + $match[2][$r][0] = str_replace( '""', '"', $match[2][$r][0] ); + } + $fieldsValues[$match[1][$r][0]] = $match[2][$r][0]; + } + /* Start Block: WHERE*/ /*Start Block: Replace the operator */ - $blocks = preg_split('/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', $sqlWhere , -1 , PREG_SPLIT_DELIM_CAPTURE ); - $sqlWhere = ''; - for($r = 0 ; $r < sizeof($blocks) ; $r++ ){ - if ( ($r % 2) === 0 ) { - $blocks[$r] = str_replace( '=' , '==', $blocks[$r]); - $blocks[$r] = str_replace( '<>' , '!=', $blocks[$r]); - $blocks[$r] = str_replace( 'AND' , '&&', $blocks[$r]); - $blocks[$r] = str_replace( 'and' , '&&', $blocks[$r]); - $blocks[$r] = str_replace( 'OR' , '||', $blocks[$r]); - $blocks[$r] = str_replace( 'or' , '||', $blocks[$r]); - $blocks[$r] = str_replace( 'NOT' , '!', $blocks[$r]); - $blocks[$r] = str_replace( 'not' , '!', $blocks[$r]); - $blocks[$r] = preg_replace('/\b[a-zA-Z_][\w\.]*\b/im', '$res[$r][\'$0\']', $blocks[$r] ); - $blocks[$r] = preg_replace('/\$res\[\$r\]\[\'(like)\'\]/im', '$1', $blocks[$r] ); - } - $sqlWhere .= $blocks[$r]; - } - /* End Block */ - $sqlWhere = preg_replace_callback('/(.+)\s+like\s+("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', - array('XMLConnection','sqlWhereLike'), $sqlWhere ); - $sqlWhere = preg_replace_callback('/"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'/im', - array('XMLConnection','sqlString'), $sqlWhere ); - /*Start Block: Removing fields */ - $xmlFrom = '/' . str_replace( '.','/' , $sqlFrom ); - $node =& $this->xmldoc->findNode( $xmlFrom ); - if (!isset($node)) { - $err = new DB_Error( "$xmlFrom node not found in $dsn." ); - return $err; + $blocks = preg_split( '/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', $sqlWhere, - 1, PREG_SPLIT_DELIM_CAPTURE ); + $sqlWhere = ''; + for ($r = 0; $r < sizeof( $blocks ); $r ++) { + if (($r % 2) === 0) { + $blocks[$r] = str_replace( '=', '==', $blocks[$r] ); + $blocks[$r] = str_replace( '<>', '!=', $blocks[$r] ); + $blocks[$r] = str_replace( 'AND', '&&', $blocks[$r] ); + $blocks[$r] = str_replace( 'and', '&&', $blocks[$r] ); + $blocks[$r] = str_replace( 'OR', '||', $blocks[$r] ); + $blocks[$r] = str_replace( 'or', '||', $blocks[$r] ); + $blocks[$r] = str_replace( 'NOT', '!', $blocks[$r] ); + $blocks[$r] = str_replace( 'not', '!', $blocks[$r] ); + $blocks[$r] = preg_replace( '/\b[a-zA-Z_][\w\.]*\b/im', '$res[$r][\'$0\']', $blocks[$r] ); + $blocks[$r] = preg_replace( '/\$res\[\$r\]\[\'(like)\'\]/im', '$1', $blocks[$r] ); + } + $sqlWhere .= $blocks[$r]; + } + /* End Block */ + $sqlWhere = preg_replace_callback( '/(.+)\s+like\s+("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', array ('XMLConnection','sqlWhereLike' + ), $sqlWhere ); + $sqlWhere = preg_replace_callback( '/"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'/im', array ('XMLConnection','sqlString' + ), $sqlWhere ); + /*Start Block: Removing fields */ + $xmlFrom = '/' . str_replace( '.', '/', $sqlFrom ); + $node = & $this->xmldoc->findNode( $xmlFrom ); + if (! isset( $node )) { + $err = new DB_Error( "$xmlFrom node not found in $dsn." ); + return $err; + } else { + $res = $this->fetchChildren( $node ); + } + $newRes = array (); + for ($r = 0; $r < sizeof( $res ); $r ++) { + $evalWhere = false; + @eval( '$evalWhere = ' . $sqlWhere . ';' ); + if ($evalWhere) { + $this->updateRow( $node->children[$r], $fieldsValues ); + $newRes[] = array_merge( $res[$r], $fieldsValues ); + } + } + /* End Block */ + $nodeTEST = & $this->xmldoc->findNode( $xmlFrom ); + $this->xmldoc->save( $this->xmlFile ); + $result = new XMLResult( $newRes ); + return $result; } else { - $res = $this->fetchChildren ( $node ); + echo ($sql); + $err = new DB_Error( "SQL Query is not well formed." ); + return $err; } - $newRes = array(); - for( $r=0 ; $r < sizeof($res) ; $r++ ) { - $evalWhere = false; - @eval('$evalWhere = '.$sqlWhere.';'); - if ( $evalWhere ) { - $this->updateRow( $node->children[$r] , $fieldsValues ); - $newRes[] = array_merge( $res[$r] , $fieldsValues ); - } - } - /* End Block */ - $nodeTEST =& $this->xmldoc->findNode( $xmlFrom ); - $this->xmldoc->save( $this->xmlFile ); - $result = new XMLResult( $newRes ); - return $result; } - else + + /** + * sqlLike + * + * @param string $a + * @return void $b + */ + function sqlLike ($a, $b) { - echo($sql); - $err = new DB_Error( "SQL Query is not well formed." ); - return $err; + $b = addcslashes( $b, '[]()\/{}.?' ); + $b = str_replace( "%", '.*', $b ); + $b = '/^' . $b . '$/im'; + return preg_match( $b, $a ); } - } - /** - * sqlLike - * - * @param string $a - * @return void $b - */ - function sqlLike( $a , $b ) - { - $b = addcslashes( $b , '[]()\/{}.?' ); - $b = str_replace( "%" , '.*' , $b ); - $b = '/^'. $b . '$/im'; - return preg_match( $b , $a ); - } + /** + * expandFields + * + * @param string $resRow + * @param string $fieldsList + * @return array $res + */ + function expandFields ($resRow, $fieldsList) + { + $res = array (); + foreach ($fieldsList as $key => $value) { + if ($key === '*') { + foreach ($resRow as $k => $v) + $res[$k] = $v; + } else { + $res[$key] = array_key_exists( $value, $resRow ) ? $resRow[$value] : NULL; + } + } + return $res; + } - /** - * expandFields - * - * @param string $resRow - * @param string $fieldsList - * @return array $res - */ - function expandFields( $resRow, $fieldsList ) - { - $res = array(); - foreach($fieldsList as $key => $value ) { - if ($key==='*') { - foreach( $resRow as $k => $v ) $res[$k] = $v; - } else { - $res[$key] = array_key_exists( $value , $resRow ) ? $resRow[$value] : NULL; - } + /** + * fetchNode + * + * @param object &$node + * @return array $res + */ + function fetchNode (&$node) + { + $res = array ('XMLNODE_NAME' => $node->name,'XMLNODE_TYPE' => $node->type,'XMLNODE_VALUE' => $node->value + ); + foreach ($node->attributes as $name => $value) { + if ($this->caseFolding) + $name = strtoupper( $name ); + $res[$name] = $value; + } + return $res; } - return $res; - } - /** - * fetchNode - * - * @param object &$node - * @return array $res - */ - function fetchNode( &$node ) - { - $res = array ( - 'XMLNODE_NAME' => $node->name, - 'XMLNODE_TYPE' => $node->type, - 'XMLNODE_VALUE' => $node->value, - ); - foreach( $node->attributes as $name => $value ) { - if ($this->caseFolding) $name = strtoupper( $name ); - $res[$name] = $value; + /** + * fetchChildren + * + * @param string &$node + * @return array $res + */ + function fetchChildren (&$node) + { + $res = array (); + foreach ($node->children as $name => $child) { + $res[] = $this->fetchNode( $child ); + } + return $res; } - return $res; - } - - /** - * fetchChildren - * - * @param string &$node - * @return array $res - */ - function fetchChildren( &$node ) - { - $res = array(); - foreach( $node->children as $name => $child ) { - $res[] = $this->fetchNode( $child ); - } - return $res; - } - - /** - * disconnect - * - * @return void - */ - function disconnect() - { - unset( $this->xmldoc ); - } - - /** - * - * - * @param array $match - * @return object(DB_Error) $err - */ - function sqlWhereLike( $match ) - { - switch (substr($match[2],0,1)) { - case '"': - return ' $this->sqlLike( '.$match[1].', '.$match[2].' ) '; - break; - case "'": - return ' $this->sqlLike( '.$match[1].', '.$match[2].' ) '; - break; - default: - $err = new DB_Error( "XMLDB: Syntax error on $match[0]" ); - die; - return $err; - } - } - - /** - * sqlString - * - * @param array $match - * @return object(DB_Error) $err - */ - function sqlString( $match ) - { - switch (substr($match[0],0,1)) { - case '"': - $match[0] = substr( $match[0] ,1, -1 ); - $match[0] = str_replace('""', '"' , $match[0] ); - $match[0] = str_replace("''", "'" , $match[0] ); - $match[0] = addcslashes( $match[0] , '\\\'' ); - return "'$match[0]'"; - break; - case "'": - $match[0] = substr( $match[0] ,1, -1 ); - $match[0] = str_replace("''", "'" , $match[0] ); - $match[0] = str_replace('""', '"' , $match[0] ); - $match[0] = addcslashes( $match[0] , '\\\'' ); - return "'$match[0]'"; - break; - default: - $err = new DB_Error( "XMLDB: Syntax error on $match[0]" ); - die; - return $err; - } - } - /** - * insertRow - * - * @param string &$node - * @param object $values - * @return void - */ - function insertRow( &$node , $values ) - { - $attributes = array(); - foreach( $values as $field => $value ) { - switch( $field ) { - case 'XMLNODE_NAME' : - case 'XMLNODE_TYPE' : - case 'XMLNODE_VALUE': - break; - default: - $attributes[strtolower($field)] = $value; - } + /** + * disconnect + * + * @return void + */ + function disconnect () + { + unset( $this->xmldoc ); } - $values['XMLNODE_NAME'] = !isset($values['XMLNODE_NAME']) ? - '': $values['XMLNODE_NAME']; - $values['XMLNODE_TYPE'] = !isset($values['XMLNODE_TYPE']) ? - 'open': $values['XMLNODE_TYPE']; - $values['XMLNODE_VALUE'] = !isset($values['XMLNODE_VALUE']) ? - '': $values['XMLNODE_VALUE']; - $node->addChildNode( new Xml_Node( - $values['XMLNODE_NAME'] , $values['XMLNODE_TYPE'] , $values['XMLNODE_VALUE'], $attributes ) ); - } - /** - * updateRow - * - * @param string &$node - * @param object $values - * @return void - */ - function updateRow( &$node , $values ) - { - foreach( $values as $field => $value ) { - switch( $field ) { - case 'XMLNODE_NAME' : - $node->name = $value; - break; - case 'XMLNODE_TYPE' : - $node->type = $value; - break; - case 'XMLNODE_VALUE': - $node->value = $value; - break; - default: - $node->attributes[strtolower($field)] = $value; - } + /** + * + * @param array $match + * @return object(DB_Error) $err + */ + function sqlWhereLike ($match) + { + switch (substr( $match[2], 0, 1 )) { + case '"': + return ' $this->sqlLike( ' . $match[1] . ', ' . $match[2] . ' ) '; + break; + case "'": + return ' $this->sqlLike( ' . $match[1] . ', ' . $match[2] . ' ) '; + break; + default: + $err = new DB_Error( "XMLDB: Syntax error on $match[0]" ); + die(); + return $err; + } + } + + /** + * sqlString + * + * @param array $match + * @return object(DB_Error) $err + */ + function sqlString ($match) + { + switch (substr( $match[0], 0, 1 )) { + case '"': + $match[0] = substr( $match[0], 1, - 1 ); + $match[0] = str_replace( '""', '"', $match[0] ); + $match[0] = str_replace( "''", "'", $match[0] ); + $match[0] = addcslashes( $match[0], '\\\'' ); + return "'$match[0]'"; + break; + case "'": + $match[0] = substr( $match[0], 1, - 1 ); + $match[0] = str_replace( "''", "'", $match[0] ); + $match[0] = str_replace( '""', '"', $match[0] ); + $match[0] = addcslashes( $match[0], '\\\'' ); + return "'$match[0]'"; + break; + default: + $err = new DB_Error( "XMLDB: Syntax error on $match[0]" ); + die(); + return $err; + } + } + + /** + * insertRow + * + * @param string &$node + * @param object $values + * @return void + */ + function insertRow (&$node, $values) + { + $attributes = array (); + foreach ($values as $field => $value) { + switch ($field) { + case 'XMLNODE_NAME': + case 'XMLNODE_TYPE': + case 'XMLNODE_VALUE': + break; + default: + $attributes[strtolower( $field )] = $value; + } + } + $values['XMLNODE_NAME'] = ! isset( $values['XMLNODE_NAME'] ) ? '' : $values['XMLNODE_NAME']; + $values['XMLNODE_TYPE'] = ! isset( $values['XMLNODE_TYPE'] ) ? 'open' : $values['XMLNODE_TYPE']; + $values['XMLNODE_VALUE'] = ! isset( $values['XMLNODE_VALUE'] ) ? '' : $values['XMLNODE_VALUE']; + $node->addChildNode( new Xml_Node( $values['XMLNODE_NAME'], $values['XMLNODE_TYPE'], $values['XMLNODE_VALUE'], $attributes ) ); + } + + /** + * updateRow + * + * @param string &$node + * @param object $values + * @return void + */ + function updateRow (&$node, $values) + { + foreach ($values as $field => $value) { + switch ($field) { + case 'XMLNODE_NAME': + $node->name = $value; + break; + case 'XMLNODE_TYPE': + $node->type = $value; + break; + case 'XMLNODE_VALUE': + $node->value = $value; + break; + default: + $node->attributes[strtolower( $field )] = $value; + } + } } - } } /** -* XMLResult -* -* ProcessMaker Open Source Edition -* -* @copyright (C) 2004 - 2008 Colosa Inc.23 -* @package workflow.engine.ProcessMaker -*/ -class XMLResult + * XMLResult + * + * ProcessMaker Open Source Edition + * + * @copyright (C) 2004 - 2008 Colosa Inc.23 + * @package workflow.engine.ProcessMaker + * + */ +class XMLResult { - var $result = array(); - var $cursor = 0; - - /** - * XMLResult - * - * @param array $result - * @return void - */ - function XMLResult( $result = array() ) - { - $this->result = $result; - $this->cursor = 0; - } + var $result = array (); + var $cursor = 0; - /** - * numRows - * - * @return integer sizeof($this->result) - */ - function numRows() - { - return sizeof($this->result); - } + /** + * XMLResult + * + * @param array $result + * @return void + */ + function XMLResult ($result = array()) + { + $this->result = $result; + $this->cursor = 0; + } - /** - * fetchRow - * - * @param string $const - * @return integer $this->result[ $this->cursor-1 ]; - */ - function fetchRow ( $const ) - { - if ($this->cursor>=$this->numRows()) - return NULL; - $this->cursor++; - return $this->result[ $this->cursor-1 ]; - } + /** + * numRows + * + * @return integer sizeof($this->result) + */ + function numRows () + { + return sizeof( $this->result ); + } + + /** + * fetchRow + * + * @param string $const + * @return integer $this->result[ $this->cursor-1 ]; + */ + function fetchRow ($const) + { + if ($this->cursor >= $this->numRows()) + return NULL; + $this->cursor ++; + return $this->result[$this->cursor - 1]; + } } - /** - * getNames - * - * @param object $children - * @return array $names - */ - function getNames( $children ) - { - $names = array(); - $r = 0; - foreach($children as $child) { - $names[$r]=$child->name; - $r++; +/** + * getNames + * + * @param object $children + * @return array $names + */ +function getNames ($children) +{ + $names = array (); + $r = 0; + foreach ($children as $child) { + $names[$r] = $child->name; + $r ++; } return $names; - } +} ?> \ No newline at end of file From f07f0d1e7de8c5168da95630e3c747416c3e46ab Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:43:23 -0400 Subject: [PATCH 17/18] CODE STYLE class.xmlfield_Image.php and class.xmlfield_InputPM.php --- .../engine/classes/class.xmlfield_Image.php | 40 +- .../engine/classes/class.xmlfield_InputPM.php | 784 +++++++++--------- 2 files changed, 423 insertions(+), 401 deletions(-) diff --git a/workflow/engine/classes/class.xmlfield_Image.php b/workflow/engine/classes/class.xmlfield_Image.php index a01eedeb0..51f2f5c3b 100755 --- a/workflow/engine/classes/class.xmlfield_Image.php +++ b/workflow/engine/classes/class.xmlfield_Image.php @@ -1,6 +1,8 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. @@ -26,23 +28,27 @@ // DEPRECATED this class is also part of the xmlform package this class will be also removed // in future releases of pm, its discouraged the inclusion this class in the future from a // external file like this - /** +/** + * * @package workflow.engine.classes */ class XmlForm_Field_Image extends XmlForm_Field { - var $file = ''; - var $home = 'public_html'; - var $withoutLabel = false; - function render( $value, $owner = null ) - { - $url = G::replaceDataField($this->file, $owner->values); - if ($this->home === "methods") $url = G::encryptlink( SYS_URI . $url ); - if ($this->home === "public_html") $url ='/' . $url ; - return 'style)?'style="'.$this->style.'"':'') - .' alt ="'.htmlentities($value,ENT_QUOTES,'utf-8').'"/>'; - } - } -?> \ No newline at end of file + public $file = ''; + public $home = 'public_html'; + public $withoutLabel = false; + + public function render ($value, $owner = null) + { + $url = G::replaceDataField( $this->file, $owner->values ); + if ($this->home === "methods") { + $url = G::encryptlink( SYS_URI . $url ); + } + if ($this->home === "public_html") { + $url = '/' . $url; + } + return 'style) ? 'style="' . $this->style . '"' : '') . ' alt ="' . htmlentities( $value, ENT_QUOTES, 'utf-8' ) . '"/>'; + } +} + diff --git a/workflow/engine/classes/class.xmlfield_InputPM.php b/workflow/engine/classes/class.xmlfield_InputPM.php index 1d4b22ddf..e5ec93b83 100755 --- a/workflow/engine/classes/class.xmlfield_InputPM.php +++ b/workflow/engine/classes/class.xmlfield_InputPM.php @@ -1,6 +1,8 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. @@ -27,125 +29,129 @@ class XmlForm_Field_TextPM extends XmlForm_Field_SimpleText { - var $size=15; - var $maxLength=64; - var $validate='Any'; - var $mask = ''; - var $defaultValue=''; - var $required=false; - var $dependentFields=''; - var $linkField=''; -//Possible values:(-|UPPER|LOWER|CAPITALIZE) - var $strTo=''; - var $readOnly=false; - var $sqlConnection=0; - var $sql=''; - var $sqlOption=array(); - //Atributes only for grids - var $formula = ''; - var $function = ''; - var $replaceTags = 0; - var $showVars = 0; - var $process = ''; - var $symbol = '@@'; + public $size = 15; + public $maxLength = 64; + public $validate = 'Any'; + public $mask = ''; + public $defaultValue = ''; + public $required = false; + public $dependentFields = ''; + public $linkField = ''; + //Possible values:(-|UPPER|LOWER|CAPITALIZE) + public $strTo = ''; + public $readOnly = false; + public $sqlConnection = 0; + public $sql = ''; + public $sqlOption = array (); + //Atributes only for grids + public $formula = ''; + public $function = ''; + public $replaceTags = 0; + public $showVars = 0; + public $process = ''; + public $symbol = '@@'; - /** - * Function render - * @author Julio Cesar Laura Avendano - * @access public - * @parameter string value - * @parameter string owner - * @return string - */ - function render( $value = NULL , $owner = NULL ) - { - //$this->executeSQL(); - //if (isset($this->sqlOption)) { - // reset($this->sqlOption); - // $firstElement=key($this->sqlOption); - // if (isset($firstElement)) $value = $firstElement; - //} - //NOTE: string functions must be in G class - if ($this->strTo==='UPPER') - $value = strtoupper($value); - if ($this->strTo==='LOWER') - $value = strtolower($value); - //if ($this->strTo==='CAPITALIZE') $value = strtocapitalize($value); - $onkeypress = G::replaceDataField( $this->onkeypress, $owner->values ); - if ($this->replaceTags == 1) { - $value = G::replaceDataField( $value, $owner->values ); + /** + * Function render + * + * @author Julio Cesar Laura Avendano + * @access public + * @param eter string value + * @param eter string owner + * @return string + */ + public function render ($value = null, $owner = null) + { + //$this->executeSQL(); + //if (isset($this->sqlOption)) { + // reset($this->sqlOption); + // $firstElement=key($this->sqlOption); + // if (isset($firstElement)) $value = $firstElement; + //} + //NOTE: string functions must be in G class + if ($this->strTo === 'UPPER') { + $value = strtoupper( $value ); + } + if ($this->strTo === 'LOWER') { + $value = strtolower( $value ); + } + //if ($this->strTo==='CAPITALIZE') $value = strtocapitalize($value); + $onkeypress = G::replaceDataField( $this->onkeypress, $owner->values ); + if ($this->replaceTags == 1) { + $value = G::replaceDataField( $value, $owner->values ); + } + if ($this->showVars == 1) { + $this->process = G::replaceDataField( $this->process, $owner->values ); + //$sShowVars = ' ' . $this->symbol . ''; + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' readOnly="readOnly" style="' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $sShowVars; + } else { + return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' style="' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $sShowVars; + } + } elseif ($this->mode === 'view') { + return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' style="display:none;' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $this->htmlentities( $value, ENT_COMPAT, 'utf-8' ); + } else { + return $this->htmlentities( $value, ENT_COMPAT, 'utf-8' ); + } } - if ($this->showVars == 1) { - $this->process = G::replaceDataField($this->process, $owner->values ); - //$sShowVars = ' ' . $this->symbol . ''; - $sShowVars = ' '; - } - else { - $sShowVars = ''; - } - if ($this->mode==='edit') { - if ($this->readOnly) - return 'htmlentities( $value , ENT_COMPAT, 'utf-8').'\' readOnly="readOnly" style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars; - else - return 'htmlentities( $value , ENT_COMPAT, 'utf-8').'\' style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars; - } elseif ($this->mode==='view') { - return 'htmlentities( $value , ENT_COMPAT, 'utf-8').'\' style="display:none;'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . - $this->htmlentities( $value , ENT_COMPAT, 'utf-8'); - } else { - return $this->htmlentities( $value , ENT_COMPAT, 'utf-8'); - } - } - /** - * Function renderGrid - * @author Julio Cesar Laura Avendano - * @access public - * @parameter array values - * @parameter string owner - * @return string - */ - function renderGrid( $values=array() , $owner ) - { - $result=array(); - $r=1; - foreach($values as $v) { - if ($this->replaceTags == 1) { - $v = G::replaceDataField( $v, $owner->values ); - } - if ($this->showVars == 1) { - $this->process = G::replaceDataField($this->process, $owner->values ); - //$sShowVars = ' ' . $this->symbol . ''; - $sShowVars = ' '; - } - else { - $sShowVars = ''; - } - if ($this->mode==='edit') { - if ($this->readOnly) - $result[] = '' . $sShowVars; - else - $result[] = '' . $sShowVars; - } elseif ($this->mode==='view') { - $result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8'); - } else { - $result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8'); - } - $r++; + /** + * Function renderGrid + * + * @author Julio Cesar Laura Avendano + * @access public + * @param eter array values + * @param eter string owner + * @return string + */ + public function renderGrid ($values = array(), $owner) + { + $result = array (); + $r = 1; + foreach ($values as $v) { + if ($this->replaceTags == 1) { + $v = G::replaceDataField( $v, $owner->values ); + } + if ($this->showVars == 1) { + $this->process = G::replaceDataField( $this->process, $owner->values ); + //$sShowVars = ' ' . $this->symbol . ''; + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + $result[] = '' . $sShowVars; + } else { + $result[] = '' . $sShowVars; + } + } elseif ($this->mode === 'view') { + $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' ); + } else { + $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' ); + } + $r ++; + } + return $result; } - return $result; - } - /** - * Function attachEvents - * @access public - * @parameter string $element - * @return string - */ - function attachEvents($element) - { - return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}'); + /** + * Function attachEvents + * + * @access public + * @param eter string $element + * @return string + */ + public function attachEvents ($element) + { + return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}'); myForm.aElements[i].setAttributes(" . $this->getAttributes() . ");"; - } + } } /** @@ -153,86 +159,87 @@ class XmlForm_Field_TextPM extends XmlForm_Field_SimpleText */ class XmlForm_Field_TextareaPM extends XmlForm_Field { - var $rows = 12; - var $cols = 40; - var $required = false; - var $readOnly = false; - var $wrap = 'OFF'; - var $showVars = 0; - var $process = ''; - var $symbol = '@@'; + public $rows = 12; + public $cols = 40; + public $required = false; + public $readOnly = false; + public $wrap = 'OFF'; + public $showVars = 0; + public $process = ''; + public $symbol = '@@'; - /** - * Function render - * @author Julio Cesar Laura Avendao - * @access public - * @parameter string value - * @parameter string owner - * @return string - */ - function render( $value = NULL, $owner ) - { - if ($this->showVars == 1) { - $this->process = G::replaceDataField($this->process, $owner->values ); - $sShowVars = ' '; + /** + * Function render + * + * @author Julio Cesar Laura Avendao + * @access public + * @param eter string value + * @param eter string owner + * @return string + */ + public function render ($value = null, $owner) + { + if ($this->showVars == 1) { + $this->process = G::replaceDataField( $this->process, $owner->values ); + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + return '' . $sShowVars; + } else { + return '' . $sShowVars; + } + } elseif ($this->mode === 'view') { + return ''; + } else { + return ''; + } } - else { - $sShowVars = ''; - } - if ($this->mode==='edit') { - if ($this->readOnly) - return '' . $sShowVars; - else - return '' . $sShowVars; - } elseif ($this->mode==='view') { - return ''; - } else { - return ''; - } - } - /** - * Function renderGrid - * @author Julio Cesar Laura Avendano - * @access public - * @parameter string values - * @parameter string owner - * @return string - */ - function renderGrid( $values = NULL , $owner ) - { - $result=array(); - $r=1; - foreach($values as $v) { - if ($this->showVars == 1) { - $this->process = G::replaceDataField($this->process, $owner->values ); - //$sShowVars = ' ' . $this->symbol . ''; - $sShowVars = ' '; - } - else { - $sShowVars = ''; - } - if ($this->mode==='edit') { - if ($this->readOnly) - $result[] = 'htmlentities( $v , ENT_COMPAT, 'utf-8').'\' readOnly="readOnly"/>' . $sShowVars; - else - $result[] = 'htmlentities( $v , ENT_COMPAT, 'utf-8').'\' />' . $sShowVars; - } elseif ($this->mode==='view') { - if(stristr($_SERVER['HTTP_USER_AGENT'], 'iPhone')){ - //$result[] = '
'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'
'; - $result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8'); - } - else{ - //$result[] = '
'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'
'; - $result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8'); - } - } else{ - $result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8'); - } - $r++; + /** + * Function renderGrid + * + * @author Julio Cesar Laura Avendano + * @access public + * @param eter string values + * @param eter string owner + * @return string + */ + public function renderGrid ($values = null, $owner) + { + $result = array (); + $r = 1; + foreach ($values as $v) { + if ($this->showVars == 1) { + $this->process = G::replaceDataField( $this->process, $owner->values ); + //$sShowVars = ' ' . $this->symbol . ''; + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + $result[] = 'htmlentities( $v, ENT_COMPAT, 'utf-8' ) . '\' readOnly="readOnly"/>' . $sShowVars; + } else { + $result[] = 'htmlentities( $v, ENT_COMPAT, 'utf-8' ) . '\' />' . $sShowVars; + } + } elseif ($this->mode === 'view') { + if (stristr( $_SERVER['HTTP_USER_AGENT'], 'iPhone' )) { + //$result[] = '
'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'
'; + $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' ); + } else { + //$result[] = '
'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'
'; + $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' ); + } + } else { + $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' ); + } + $r ++; + } + return $result; } - return $result; - } } /** @@ -240,230 +247,239 @@ class XmlForm_Field_TextareaPM extends XmlForm_Field */ class XmlForm_Field_hours extends XmlForm_Field_SimpleText { - var $size = 15; - var $maxLength = 64; - var $validate = 'Any'; - var $mask = ''; - var $defaultValue = ''; - var $required = false; - var $dependentFields= ''; - var $linkField = ''; -//Possible values:(-|UPPER|LOWER|CAPITALIZE) - var $strTo = ''; - var $readOnly = false; - var $sqlConnection = 0; - var $sql = ''; - var $sqlOption = array(); - //Atributes only for grids - var $formula = ''; - var $function = ''; - var $replaceTags = 0; - var $showVars = 0; - var $process = ''; - var $symbol = '@@'; + public $size = 15; + public $maxLength = 64; + public $validate = 'Any'; + public $mask = ''; + public $defaultValue = ''; + public $required = false; + public $dependentFields = ''; + public $linkField = ''; + //Possible values:(-|UPPER|LOWER|CAPITALIZE) + public $strTo = ''; + public $readOnly = false; + public $sqlConnection = 0; + public $sql = ''; + public $sqlOption = array (); + //Atributes only for grids + public $formula = ''; + public $function = ''; + public $replaceTags = 0; + public $showVars = 0; + public $process = ''; + public $symbol = '@@'; - /** - * Function render - * @author Julio Cesar Laura Avendano - * @access public - * @parameter string value - * @parameter string owner - * @return string - */ - function render( $value = NULL , $owner = NULL ) - { - if ($this->strTo==='UPPER') - $value = strtoupper($value); - if ($this->strTo==='LOWER') - $value = strtolower($value); - //if ($this->strTo==='CAPITALIZE') $value = strtocapitalize($value); - $onkeypress = G::replaceDataField( $this->onkeypress, $owner->values ); - if ($this->replaceTags == 1) { - $value = G::replaceDataField( $value, $owner->values ); + /** + * Function render + * + * @author Julio Cesar Laura Avendano + * @access public + * @param eter string value + * @param eter string owner + * @return string + */ + public function render ($value = null, $owner = null) + { + if ($this->strTo === 'UPPER') { + $value = strtoupper( $value ); + } + if ($this->strTo === 'LOWER') { + $value = strtolower( $value ); + } + //if ($this->strTo==='CAPITALIZE') $value = strtocapitalize($value); + $onkeypress = G::replaceDataField( $this->onkeypress, $owner->values ); + if ($this->replaceTags == 1) { + $value = G::replaceDataField( $value, $owner->values ); + } + if ($this->showVars == 1) { + $this->process = G::replaceDataField( $this->process, $owner->values ); + //$sShowVars = ' ' . $this->symbol . ''; + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' readOnly="readOnly" style="' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $sShowVars; + } else { + return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' style="' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $sShowVars; + } + } elseif ($this->mode === 'view') { + return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' style="display:none;' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $this->htmlentities( $value, ENT_COMPAT, 'utf-8' ); + } else { + return $this->htmlentities( $value, ENT_COMPAT, 'utf-8' ); + } } - if ($this->showVars == 1) { - $this->process = G::replaceDataField($this->process, $owner->values ); - //$sShowVars = ' ' . $this->symbol . ''; - $sShowVars = ' '; - } - else { - $sShowVars = ''; - } - if ($this->mode==='edit') { - if ($this->readOnly) - return 'htmlentities( $value , ENT_COMPAT, 'utf-8').'\' readOnly="readOnly" style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars; - else - return 'htmlentities( $value , ENT_COMPAT, 'utf-8').'\' style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars; - } elseif ($this->mode==='view') { - return 'htmlentities( $value , ENT_COMPAT, 'utf-8').'\' style="display:none;'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . - $this->htmlentities( $value , ENT_COMPAT, 'utf-8'); - } else { - return $this->htmlentities( $value , ENT_COMPAT, 'utf-8'); - } - } - /** - * Function renderGrid - * @author Julio Cesar Laura Avendano - * @access public - * @parameter array values - * @parameter string owner - * @return string - */ - function renderGrid( $values=array() , $owner ) - { - $result=array(); - $r=1; - foreach($values as $v) { - if ($this->replaceTags == 1) { - $v = G::replaceDataField( $v, $owner->values ); - } - if ($this->showVars == 1) { - $this->process = G::replaceDataField($this->process, $owner->values ); - //$sShowVars = ' ' . $this->symbol . ''; - $sShowVars = ' '; - } - else { - $sShowVars = ''; - } - if ($this->mode==='edit') { - if ($this->readOnly) - $result[] = '' . $sShowVars; - else - $result[] = '' . $sShowVars; - } elseif ($this->mode==='view') { - $result[] = '

'.$this->htmlentities( number_format($v, 2), ENT_COMPAT, 'utf-8').'

'; - } else { - $result[] = '

'.$this->htmlentities( number_format($v, 2), ENT_COMPAT, 'utf-8').'

'; - } - $r++; + /** + * Function renderGrid + * + * @author Julio Cesar Laura Avendano + * @access public + * @param eter array values + * @param eter string owner + * @return string + */ + public function renderGrid ($values = array(), $owner) + { + $result = array (); + $r = 1; + foreach ($values as $v) { + if ($this->replaceTags == 1) { + $v = G::replaceDataField( $v, $owner->values ); + } + if ($this->showVars == 1) { + $this->process = G::replaceDataField( $this->process, $owner->values ); + //$sShowVars = ' ' . $this->symbol . ''; + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + $result[] = '' . $sShowVars; + } else { + $result[] = '' . $sShowVars; + } + } elseif ($this->mode === 'view') { + $result[] = '

' . $this->htmlentities( number_format( $v, 2 ), ENT_COMPAT, 'utf-8' ) . '

'; + } else { + $result[] = '

' . $this->htmlentities( number_format( $v, 2 ), ENT_COMPAT, 'utf-8' ) . '

'; + } + $r ++; + } + return $result; } - return $result; - } - /** - * Function attachEvents - * @access public - * @parameter string $element - * @return string - */ - function attachEvents($element) - { - return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}'); + /** + * Function attachEvents + * + * @access public + * @param eter string $element + * @return string + */ + public function attachEvents ($element) + { + return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}'); myForm.aElements[i].setAttributes(" . $this->getAttributes() . ");"; - } + } } - /** - * Function getDynaformsVars - * @access public - * @parameter string $sProcessUID - * @parameter boolean $bSystemVars - * @return array - */ - function getDynaformsVars($sProcessUID, $bSystemVars = true, $bIncMulSelFields = 0) - { - $aFields = array(); - $aFieldsNames = array(); +/** + * Function getDynaformsVars + * + * @access public + * @param eter string $sProcessUID + * @param eter boolean $bSystemVars + * @return array + */ +public function getDynaformsVars ($sProcessUID, $bSystemVars = true, $bIncMulSelFields = 0) +{ + $aFields = array (); + $aFieldsNames = array (); if ($bSystemVars) { - $aAux = G::getSystemConstants(); - foreach ($aAux as $sName => $sValue) { - $aFields[] = array('sName' => $sName, 'sType' => 'system', 'sLabel'=> 'System variable'); - } - //we're adding the ping variable to the system list - $aFields[] = array('sName' => 'PIN', 'sType' => 'system', 'sLabel' => 'System variable'); + $aAux = G::getSystemConstants(); + foreach ($aAux as $sName => $sValue) { + $aFields[] = array ('sName' => $sName,'sType' => 'system','sLabel' => 'System variable' + ); + } + //we're adding the ping variable to the system list + $aFields[] = array ('sName' => 'PIN','sType' => 'system','sLabel' => 'System variable' + ); } - $aInvalidTypes = array('title', 'subtitle', 'link', 'file', 'button', 'reset', 'submit', 'javascript'); - $aMultipleSelectionFields = array('listbox', 'checkgroup', 'grid'); + $aInvalidTypes = array ('title','subtitle','link','file','button','reset','submit','javascript' + ); + $aMultipleSelectionFields = array ('listbox','checkgroup','grid' + ); if ($bIncMulSelFields != 0) { - $aInvalidTypes = array_merge($aInvalidTypes, $aMultipleSelectionFields); + $aInvalidTypes = array_merge( $aInvalidTypes, $aMultipleSelectionFields ); } require_once 'classes/model/Dynaform.php'; - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(DynaformPeer::DYN_FILENAME); - $oCriteria->add(DynaformPeer::PRO_UID, $sProcessUID); - $oCriteria->add(DynaformPeer::DYN_TYPE, 'xmlform'); - $oDataset = DynaformPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( DynaformPeer::DYN_FILENAME ); + $oCriteria->add( DynaformPeer::PRO_UID, $sProcessUID ); + $oCriteria->add( DynaformPeer::DYN_TYPE, 'xmlform' ); + $oDataset = DynaformPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); while ($aRow = $oDataset->getRow()) { - if (file_exists(PATH_DYNAFORM . PATH_SEP . $aRow['DYN_FILENAME'] . '.xml')) { - $G_FORM = new Form($aRow['DYN_FILENAME'], PATH_DYNAFORM, SYS_LANG); - if (($G_FORM->type == 'xmlform') || ($G_FORM->type == '')) { - foreach($G_FORM->fields as $k => $v) { - if (!in_array($v->type, $aInvalidTypes)) { - if (!in_array($k, $aFieldsNames)) { - $aFields[] = array('sName' => $k, - 'sType' => $v->type, - 'sLabel'=> ($v->type != 'grid' ? $v->label : '[ ' . G::LoadTranslation('ID_GRID') . ' ]') - ); - $aFieldsNames[] = $k; - } + if (file_exists( PATH_DYNAFORM . PATH_SEP . $aRow['DYN_FILENAME'] . '.xml' )) { + $G_FORM = new Form( $aRow['DYN_FILENAME'], PATH_DYNAFORM, SYS_LANG ); + if (($G_FORM->type == 'xmlform') || ($G_FORM->type == '')) { + foreach ($G_FORM->fields as $k => $v) { + if (! in_array( $v->type, $aInvalidTypes )) { + if (! in_array( $k, $aFieldsNames )) { + $aFields[] = array ('sName' => $k,'sType' => $v->type,'sLabel' => ($v->type != 'grid' ? $v->label : '[ ' . G::LoadTranslation( 'ID_GRID' ) . ' ]') + ); + $aFieldsNames[] = $k; + } + } + } } - } } - } - $oDataset->next(); + $oDataset->next(); } return $aFields; - } +} - /** - * Function getGridsVars - * @access public - * @parameter string $sProcessUID - * @return array - */ - function getGridsVars($sProcessUID) - { - $aFields = array(); - $aFieldsNames = array(); +/** + * Function getGridsVars + * + * @access public + * @param eter string $sProcessUID + * @return array + */ +public function getGridsVars ($sProcessUID) +{ + $aFields = array (); + $aFieldsNames = array (); require_once 'classes/model/Dynaform.php'; - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(DynaformPeer::DYN_FILENAME); - $oCriteria->add(DynaformPeer::PRO_UID, $sProcessUID); - $oDataset = DynaformPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( DynaformPeer::DYN_FILENAME ); + $oCriteria->add( DynaformPeer::PRO_UID, $sProcessUID ); + $oDataset = DynaformPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); while ($aRow = $oDataset->getRow()) { - $G_FORM = new Form($aRow['DYN_FILENAME'], PATH_DYNAFORM, SYS_LANG); - if ($G_FORM->type == 'xmlform') { - foreach($G_FORM->fields as $k => $v) { - if ($v->type == 'grid') { - if (!in_array($k, $aFieldsNames)) { - $aFields[] = array('sName' => $k, 'sXmlForm' => str_replace($sProcessUID . '/', '', $v->xmlGrid)); - $aFieldsNames[] = $k; + $G_FORM = new Form( $aRow['DYN_FILENAME'], PATH_DYNAFORM, SYS_LANG ); + if ($G_FORM->type == 'xmlform') { + foreach ($G_FORM->fields as $k => $v) { + if ($v->type == 'grid') { + if (! in_array( $k, $aFieldsNames )) { + $aFields[] = array ('sName' => $k,'sXmlForm' => str_replace( $sProcessUID . '/', '', $v->xmlGrid ) + ); + $aFieldsNames[] = $k; + } + } } - } } - } - $oDataset->next(); + $oDataset->next(); } return $aFields; - } +} /** * Class XmlForm_Field_CheckBoxTable */ class XmlForm_Field_CheckBoxTable extends XmlForm_Field_Checkbox { - /** - * Function render - * @author The Answer - * @access public - * @parameter string value - * @parameter string owner - * @return string - */ - function render( $value = NULL , $owner = NULL ) - { - //$optionName = $owner->values['USR_UID']; - $optionName = $value; - $onclick = (($this->onclick)? ' onclick="' . G::replaceDataField( $this->onclick, $owner->values ) . '" ' : ''); - $html =' '; - return $html; - } + + /** + * Function render + * + * @author The Answer + * @access public + * @param eter string value + * @param eter string owner + * @return string + */ + public function render ($value = null, $owner = null) + { + //$optionName = $owner->values['USR_UID']; + $optionName = $value; + $onclick = (($this->onclick) ? ' onclick="' . G::replaceDataField( $this->onclick, $owner->values ) . '" ' : ''); + $html = ' '; + return $html; + } } -?> + From 25da96a837772c0576f419cfe2119d10d3f049f9 Mon Sep 17 00:00:00 2001 From: Fernando Ontiveros Date: Tue, 9 Oct 2012 13:48:54 -0400 Subject: [PATCH 18/18] CODE STYLE class.xpdl.php --- workflow/engine/classes/class.xpdl.php | 6807 ++++++++++++------------ 1 file changed, 3409 insertions(+), 3398 deletions(-) diff --git a/workflow/engine/classes/class.xpdl.php b/workflow/engine/classes/class.xpdl.php index 04b0daa26..b69e9e279 100755 --- a/workflow/engine/classes/class.xpdl.php +++ b/workflow/engine/classes/class.xpdl.php @@ -1,6 +1,7 @@ . + * along with this program. If not, see . * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ -G::LoadClass('processes'); -G::LoadClass('tasks'); -G::LoadClass('derivation'); +G::LoadClass( 'processes' ); +G::LoadClass( 'tasks' ); +G::LoadClass( 'derivation' ); require_once 'classes/model/Users.php'; require_once 'classes/model/Configuration.php'; require_once 'classes/model/Gateway.php'; require_once 'classes/model/Event.php'; /** + * * @package workflow.engine.classes */ class Xpdl extends processes { - /** - * This function creates a new Process, defined in the object $oData - * @param array $aData - * @param array $tasks - * @param string $pmFilename - * @return void - */ - function createProcessFromDataXpdl ($oData,$tasks) { - if ( !isset($oData->process['PRO_UID']) || trim($oData->process['PRO_UID']) == '' ) - $oData->process['PRO_UID'] = G::generateUniqueID() ; + /** + * This public function creates a new Process, defined in the object $oData + * + * @param array $aData + * @param array $tasks + * @param string $pmFilename + * @return void + */ + public function createProcessFromDataXpdl ($oData, $tasks) + { + if (! isset( $oData->process['PRO_UID'] ) || trim( $oData->process['PRO_UID'] ) == '') { + $oData->process['PRO_UID'] = G::generateUniqueID(); + } + $this->removeProcessRows( $oData->process['PRO_UID'] ); + $uid = $this->createProcessRow( $oData->process ); + $this->createTaskRows( $oData->tasks ); + $newTasks = $this->verifyTasks( $uid, $tasks ); + if (! isset( $oData->routes )) { + $oData->routes = array (); + } + $this->createRouteRowsXpdl( $uid, $oData->routes, $newTasks ); + $this->createLaneRows( $oData->lanes ); + $this->createDynaformRows( $oData->dynaforms ); + $this->createInputRows( $oData->inputs ); + $this->createOutputRows( $oData->outputs ); + $this->createStepRows( $oData->steps ); + $this->createStepSupervisorRows( isset( $oData->stepSupervisor ) ? $oData->stepSupervisor : array () ); + $this->createTriggerRows( $oData->triggers ); + $this->createStepTriggerRows( $oData->steptriggers ); + $this->createTaskUserRows( $oData->taskusers ); + $this->createGroupRow( $oData->groupwfs ); + $this->createDBConnectionsRows( isset( $oData->dbconnections ) ? $oData->dbconnections : array () ); + $this->createReportTables( isset( $oData->reportTables ) ? $oData->reportTables : array (), isset( $oData->reportTablesVars ) ? $oData->reportTablesVars : array () ); + $this->createSubProcessRowsXpdl( $uid, isset( $oData->subProcess ) ? $oData->subProcess : array (), $newTasks ); + $this->createCaseTrackerRows( isset( $oData->caseTracker ) ? $oData->caseTracker : array () ); + $this->createCaseTrackerObjectRows( isset( $oData->caseTrackerObject ) ? $oData->caseTrackerObject : array () ); + $this->createObjectPermissionsRows( isset( $oData->objectPermissions ) ? $oData->objectPermissions : array () ); + $this->createStageRows( isset( $oData->stage ) ? $oData->stage : array () ); + $this->createFieldCondition( isset( $oData->fieldCondition ) ? $oData->fieldCondition : array (), $oData->dynaforms ); + $this->createEventRows( isset( $oData->event ) ? $oData->event : array () ); + $this->createCaseSchedulerRows( isset( $oData->caseScheduler ) ? $oData->caseScheduler : array () ); + } - $this->removeProcessRows ($oData->process['PRO_UID'] ); - $uid = $this->createProcessRow($oData->process); - $this->createTaskRows($oData->tasks); - $newTasks=$this->verifyTasks($uid,$tasks); - if ( !isset($oData->routes) ) $oData->routes = array(); - $this->createRouteRowsXpdl($uid,$oData->routes,$newTasks); - $this->createLaneRows($oData->lanes); - $this->createDynaformRows($oData->dynaforms); - $this->createInputRows($oData->inputs); - $this->createOutputRows($oData->outputs); - $this->createStepRows($oData->steps); - $this->createStepSupervisorRows(isset($oData->stepSupervisor) ? $oData->stepSupervisor : array()); - $this->createTriggerRows($oData->triggers); - $this->createStepTriggerRows($oData->steptriggers); - $this->createTaskUserRows($oData->taskusers); - $this->createGroupRow($oData->groupwfs); - $this->createDBConnectionsRows(isset($oData->dbconnections) ? $oData->dbconnections : array()); - $this->createReportTables(isset($oData->reportTables) ? $oData->reportTables : array(), isset($oData->reportTablesVars) ? $oData->reportTablesVars : array()); - $this->createSubProcessRowsXpdl($uid,isset($oData->subProcess) ? $oData->subProcess : array(),$newTasks); - $this->createCaseTrackerRows(isset($oData->caseTracker) ? $oData->caseTracker : array()); - $this->createCaseTrackerObjectRows(isset($oData->caseTrackerObject) ? $oData->caseTrackerObject: array()); - $this->createObjectPermissionsRows(isset($oData->objectPermissions) ? $oData->objectPermissions : array()); - $this->createStageRows(isset($oData->stage) ? $oData->stage : array()); - $this->createFieldCondition(isset($oData->fieldCondition) ? $oData->fieldCondition : array(), $oData->dynaforms); - $this->createEventRows(isset($oData->event) ? $oData->event : array()); - $this->createCaseSchedulerRows(isset($oData->caseScheduler) ? $oData->caseScheduler : array()); - } + /** + * this public function creates a new Process, defined in the object $oData + * + * @param string $sProUid + * @return boolean + */ + public function updateProcessFromDataXpdl ($oData, $tasks) + { + if (is_array( $oData->process )) { + $this->updateProcessRow( $oData->process ); + } + $this->removeProcessRows( $oData->process['PRO_UID'] ); + $uid = $this->createProcessRow( $oData->process ); + $this->createTaskRows( $oData->tasks ); + $newTasks = $this->verifyTasks( $uid, $tasks ); + $this->createRouteRowsXpdl( $uid, $oData->routes, $newTasks ); + $this->createLaneRows( $oData->lanes ); + $this->createDynaformRows( $oData->dynaforms ); + $this->createInputRows( $oData->inputs ); + $this->createOutputRows( $oData->outputs ); + $this->createStepRows( $oData->steps ); + $this->createStepSupervisorRows( $oData->stepSupervisor ); + $this->createTriggerRows( $oData->triggers ); + $this->createStepTriggerRows( $oData->steptriggers ); + $this->createTaskUserRows( $oData->taskusers ); + $this->createGroupRow( $oData->groupwfs ); + $this->createDBConnectionsRows( $oData->dbconnections ); + $this->updateReportTables( $oData->reportTables, $oData->reportTablesVars ); + $this->createSubProcessRows( $oData->subProcess ); + $this->createCaseTrackerRows( $oData->caseTracker ); + $this->createCaseTrackerObjectRows( $oData->caseTrackerObject ); + $this->createObjectPermissionsRows( $oData->objectPermissions ); + $this->createStageRows( $oData->stage ); + $this->createFieldCondition( $oData->fieldCondition, $oData->dynaforms ); + $this->createEventRows( $oData->event ); + $this->createCaseSchedulerRows( $oData->caseScheduler ); - /** - * this function creates a new Process, defined in the object $oData - * @param string $sProUid - * @return boolean - */ - function updateProcessFromDataXpdl ($oData, $tasks ) { - if(is_array($oData->process)) - $this->updateProcessRow ($oData->process ); - $this->removeProcessRows ($oData->process['PRO_UID'] ); - $uid = $this->createProcessRow($oData->process); - $this->createTaskRows($oData->tasks); - $newTasks=$this->verifyTasks($uid,$tasks); - $this->createRouteRowsXpdl($uid,$oData->routes,$newTasks); - $this->createLaneRows ($oData->lanes ); - $this->createDynaformRows ($oData->dynaforms ); - $this->createInputRows ($oData->inputs ); - $this->createOutputRows ($oData->outputs ); - $this->createStepRows ($oData->steps ); - $this->createStepSupervisorRows($oData->stepSupervisor); - $this->createTriggerRows ($oData->triggers); - $this->createStepTriggerRows ($oData->steptriggers); - $this->createTaskUserRows ($oData->taskusers); - $this->createGroupRow ($oData->groupwfs ); - $this->createDBConnectionsRows($oData->dbconnections); - $this->updateReportTables($oData->reportTables, $oData->reportTablesVars); - $this->createSubProcessRows( $oData->subProcess ); - $this->createCaseTrackerRows( $oData->caseTracker); - $this->createCaseTrackerObjectRows( $oData->caseTrackerObject); - $this->createObjectPermissionsRows( $oData->objectPermissions); - $this->createStageRows( $oData->stage); - $this->createFieldCondition($oData->fieldCondition, $oData->dynaforms); - $this->createEventRows( $oData->event); - $this->createCaseSchedulerRows( $oData->caseScheduler ); + } - } - /** - * this function creates a new Process, defined in the object $oData - * @param string $sProUid - * @return boolean - */ - function createProcessFromDataPmxml ($oData ) - { - $this->removeProcessRows ($oData->process['PRO_UID'] ); - $this->createProcessRow($oData->process); - $this->createDynaformRows($oData->dynaforms); - } + /** + * this public function creates a new Process, defined in the object $oData + * + * @param string $sProUid + * @return boolean + */ + public function createProcessFromDataPmxml ($oData) + { + $this->removeProcessRows( $oData->process['PRO_UID'] ); + $this->createProcessRow( $oData->process ); + $this->createDynaformRows( $oData->dynaforms ); + } - /** - * This function update the dynaforms - * @param string $sProUid - * @param array $fields - * @return boolean - */ -// function updateDynaformsPmxml($uid,$fields) -// { -// $oData->dynaforms = $this->getDynaformRows ( $uid); -// $count = sizeof($oData->dynaforms); -// foreach ($fields as $val => $id){ -// $oData->dynaforms[$count]= $id; -// $count = $count + 1 ; -// } -// $this->createDynaformRows ($oData->dynaforms ); -// } + /** + * This public function update the dynaforms + * + * @param string $sProUid + * @param array $fields + * @return boolean + */ + // public function updateDynaformsPmxml($uid,$fields) + // { + // $oData->dynaforms = $this->getDynaformRows ( $uid); + // $count = sizeof($oData->dynaforms); + // foreach ($fields as $val => $id){ + // $oData->dynaforms[$count]= $id; + // $count = $count + 1 ; + // } + // $this->createDynaformRows ($oData->dynaforms ); + // } - /** - * This function create the subProcess from data - * @param array $oData - * @param array $tasks - * @return void - */ - function createSubProcessFromDataXpdl ($oData,$tasks) - { $this->removeProcessRows ($oData->process['PRO_UID'] ); - $uid = $this->createProcessRow($oData->process); - $this->createTaskRows($oData->tasks); - $newTasks = $this->verifyTasks($uid,$tasks); - $this->createRouteRowsXpdl($uid,$oData->routes,$newTasks); - $this->createLaneRows($oData->lanes); - $this->createDynaformRows($oData->dynaforms); - $this->createInputRows($oData->inputs); - $this->createOutputRows($oData->outputs); - $this->createStepRows($oData->steps); - $this->createStepSupervisorRows(isset($oData->stepSupervisor) ? $oData->stepSupervisor : array()); - $this->createTriggerRows($oData->triggers); - $this->createStepTriggerRows($oData->steptriggers); - $this->createTaskUserRows($oData->taskusers); - $this->createGroupRow($oData->groupwfs); - $this->createDBConnectionsRows(isset($oData->dbconnections) ? $oData->dbconnections : array()); - $this->createReportTables(isset($oData->reportTables) ? $oData->reportTables : array(), isset($oData->reportTablesVars) ? $oData->reportTablesVars : array()); - $this->createSubProcessRowsXpdl($uid,isset($oData->subProcess) ? $oData->subProcess : array(),$newTasks); - $this->createCaseTrackerRows(isset($oData->caseTracker) ? $oData->caseTracker : array()); - $this->createCaseTrackerObjectRows(isset($oData->caseTrackerObject) ? $oData->caseTrackerObject: array()); - $this->createObjectPermissionsRows(isset($oData->objectPermissions) ? $oData->objectPermissions : array()); - $this->createStageRows(isset($oData->stage) ? $oData->stage : array()); - $this->createFieldCondition(isset($oData->fieldCondition) ? $oData->fieldCondition : array(), $oData->dynaforms); - $this->createEventRows(isset($oData->event) ? $oData->event : array()); - $this->createCaseSchedulerRows(isset($oData->caseScheduler) ? $oData->caseScheduler : array()); - } - /** - * This function verify the tasks of a process that was created with the tasks they were sent to the process - * @param string $oProUid - * @param array $fieldsTasks - * @return array - */ - function verifyTasks($sProUid,$fieldsTasks) - { - $process = new Process( ); - $oData->tasks = $this->getTaskRows($sProUid); - $findTask= 0; - $findNext= 0; - foreach ($fieldsTasks as $taskVal => $idVal){ - foreach ($oData->tasks as $task => $id ){ - if($idVal['TAS_TITLE'] == $id['TAS_TITLE'] and $idVal['TAS_POSX'] == $id['TAS_POSX'] and $idVal['TAS_POSY'] == $id['TAS_POSY']){ - if(isset($idVal['TAS_DESCRIPTION']) and isset($id['TAS_DESCRIPTION'])){ - if($idVal['TAS_DESCRIPTION'] == $id['TAS_DESCRIPTION']){ - $fieldsTasks[$taskVal]['TAS_UID_DATA'] = $id['TAS_UID']; + /** + * This public function create the subProcess from data + * + * @param array $oData + * @param array $tasks + * @return void + */ + public function createSubProcessFromDataXpdl ($oData, $tasks) + { + $this->removeProcessRows( $oData->process['PRO_UID'] ); + $uid = $this->createProcessRow( $oData->process ); + $this->createTaskRows( $oData->tasks ); + $newTasks = $this->verifyTasks( $uid, $tasks ); + $this->createRouteRowsXpdl( $uid, $oData->routes, $newTasks ); + $this->createLaneRows( $oData->lanes ); + $this->createDynaformRows( $oData->dynaforms ); + $this->createInputRows( $oData->inputs ); + $this->createOutputRows( $oData->outputs ); + $this->createStepRows( $oData->steps ); + $this->createStepSupervisorRows( isset( $oData->stepSupervisor ) ? $oData->stepSupervisor : array () ); + $this->createTriggerRows( $oData->triggers ); + $this->createStepTriggerRows( $oData->steptriggers ); + $this->createTaskUserRows( $oData->taskusers ); + $this->createGroupRow( $oData->groupwfs ); + $this->createDBConnectionsRows( isset( $oData->dbconnections ) ? $oData->dbconnections : array () ); + $this->createReportTables( isset( $oData->reportTables ) ? $oData->reportTables : array (), isset( $oData->reportTablesVars ) ? $oData->reportTablesVars : array () ); + $this->createSubProcessRowsXpdl( $uid, isset( $oData->subProcess ) ? $oData->subProcess : array (), $newTasks ); + $this->createCaseTrackerRows( isset( $oData->caseTracker ) ? $oData->caseTracker : array () ); + $this->createCaseTrackerObjectRows( isset( $oData->caseTrackerObject ) ? $oData->caseTrackerObject : array () ); + $this->createObjectPermissionsRows( isset( $oData->objectPermissions ) ? $oData->objectPermissions : array () ); + $this->createStageRows( isset( $oData->stage ) ? $oData->stage : array () ); + $this->createFieldCondition( isset( $oData->fieldCondition ) ? $oData->fieldCondition : array (), $oData->dynaforms ); + $this->createEventRows( isset( $oData->event ) ? $oData->event : array () ); + $this->createCaseSchedulerRows( isset( $oData->caseScheduler ) ? $oData->caseScheduler : array () ); + } + + /** + * This public function verify the tasks of a process that was created with the tasks they were sent to the process + * + * @param string $oProUid + * @param array $fieldsTasks + * @return array + */ + public function verifyTasks ($sProUid, $fieldsTasks) + { + $process = new Process(); + $oData->tasks = $this->getTaskRows( $sProUid ); + $findTask = 0; + $findNext = 0; + foreach ($fieldsTasks as $taskVal => $idVal) { + foreach ($oData->tasks as $task => $id) { + if ($idVal['TAS_TITLE'] == $id['TAS_TITLE'] and $idVal['TAS_POSX'] == $id['TAS_POSX'] and $idVal['TAS_POSY'] == $id['TAS_POSY']) { + if (isset( $idVal['TAS_DESCRIPTION'] ) and isset( $id['TAS_DESCRIPTION'] )) { + if ($idVal['TAS_DESCRIPTION'] == $id['TAS_DESCRIPTION']) { + $fieldsTasks[$taskVal]['TAS_UID_DATA'] = $id['TAS_UID']; + } + } + $fieldsTasks[$taskVal]['TAS_UID_DATA'] = $id['TAS_UID']; + } } - } - $fieldsTasks[$taskVal]['TAS_UID_DATA'] = $id['TAS_UID']; } - } + return $fieldsTasks; } - return $fieldsTasks; - } - /** - * This function creates the rows of the process - * @param string $sProUid - * @param array $routes - * @param array $fieldsTasks - * @return void - */ - function createRouteRowsXpdl($sProUid,$routes,$fieldsTasks) - { - $process = new Process( ); - $oData->tasks = $this->getTaskRows($sProUid); - foreach ($routes as $taskRoute => $idRoute){ - $findTask = 0; - $findNext = 0; - foreach ($oData->tasks as $task => $id ){ - if($idRoute['TAS_UID'] == $id['TAS_UID']){ - $findTask = 1; + /** + * This public function creates the rows of the process + * + * @param string $sProUid + * @param array $routes + * @param array $fieldsTasks + * @return void + */ + public function createRouteRowsXpdl ($sProUid, $routes, $fieldsTasks) + { + $process = new Process(); + $oData->tasks = $this->getTaskRows( $sProUid ); + foreach ($routes as $taskRoute => $idRoute) { + $findTask = 0; + $findNext = 0; + foreach ($oData->tasks as $task => $id) { + if ($idRoute['TAS_UID'] == $id['TAS_UID']) { + $findTask = 1; + } + if ($idRoute['ROU_NEXT_TASK'] != '-1') { + if ($idRoute['ROU_NEXT_TASK'] == $id['TAS_UID']) { + $findNext = 1; + } + } else { + $findNext = 1; + } + } + if ($findTask == 0) { + $id = $this->findIdTask( $idRoute['TAS_UID'], $fieldsTasks ); + $routes[$taskRoute]['TAS_UID'] = $id; + } + if ($findNext == 0) { + $id = $this->findIdTask( $idRoute['ROU_NEXT_TASK'], $fieldsTasks ); + $routes[$taskRoute]['ROU_NEXT_TASK'] = $id; + } } - if($idRoute['ROU_NEXT_TASK']!='-1'){ - if($idRoute['ROU_NEXT_TASK'] == $id['TAS_UID']){ - $findNext= 1; - } - } - else{ - $findNext= 1; - } - } - if($findTask==0){ - $id = $this->findIdTask($idRoute['TAS_UID'],$fieldsTasks); - $routes[$taskRoute]['TAS_UID']=$id; - } - if($findNext==0){ - $id = $this->findIdTask($idRoute['ROU_NEXT_TASK'],$fieldsTasks); - $routes[$taskRoute]['ROU_NEXT_TASK']=$id; - } + $this->createRouteRows( $routes ); } - $this->createRouteRows($routes); - } - /** - * Create Sub Process rows from an array, removing those subprocesses with - * the same UID. - * @param $SubProcess array - * @return void. - */ - function createSubProcessRowsXpdl ($sProUid,$SubProcess,$tasks ) - { - $process = new Process(); - $oData->tasks = $this->getTaskRows($sProUid); - foreach ( $SubProcess as $key => $row ) { - $findTask = 0; - foreach ($oData->tasks as $task => $id ){ - if($row['TAS_PARENT'] == $id['TAS_UID']){ - $findTask = 1; + /** + * Create Sub Process rows from an array, removing those subprocesses with + * the same UID. + * + * @param $SubProcess array + * @return void. + */ + public function createSubProcessRowsXpdl ($sProUid, $SubProcess, $tasks) + { + $process = new Process(); + $oData->tasks = $this->getTaskRows( $sProUid ); + foreach ($SubProcess as $key => $row) { + $findTask = 0; + foreach ($oData->tasks as $task => $id) { + if ($row['TAS_PARENT'] == $id['TAS_UID']) { + $findTask = 1; + } + } + if ($findTask == 0) { + $id = $this->findIdTask( $row['TAS_PARENT'], $tasks ); + $SubProcess[$key]['TAS_PARENT'] = $id; + } + $oSubProcess = new SubProcess(); + if ($oSubProcess->subProcessExists( $row['SP_UID'] )) { + $oSubProcess->remove( $row['SP_UID'] ); + } + $res = $oSubProcess->create( $row ); } - } - if($findTask==0){ - $id = $this->findIdTask($row['TAS_PARENT'],$tasks ); - $SubProcess[$key]['TAS_PARENT']=$id; - } - $oSubProcess = new SubProcess(); - if($oSubProcess->subProcessExists ($row['SP_UID'])){ - $oSubProcess->remove($row['SP_UID']); - } - $res = $oSubProcess->create($row); + return; } - return; - } - /** - * this function find the id of the task - * @param string $idTask - * @param array $routes - * @return array - */ - function findIdTask($idTask,$routes) - { - foreach ($routes as $value => $id ){ - if($id['TAS_UID'] == $idTask){ - return $id['TAS_UID_DATA']; - } + /** + * this public function find the id of the task + * + * @param string $idTask + * @param array $routes + * @return array + */ + public function findIdTask ($idTask, $routes) + { + foreach ($routes as $value => $id) { + if ($id['TAS_UID'] == $idTask) { + return $id['TAS_UID_DATA']; + } + } } - } - /** - * This function create the file .xpdl from a process - * @param string $sProUid - * @return void - */ - function xmdlProcess ( $sProUid = '') - { - $oProcess = new Process(); - $oData->process = $this->getProcessRow( $sProUid, false); - $oData->tasks = $this->getTaskRows( $sProUid ); - $oData->routes = $this->getRouteRows( $sProUid ); - $oData->lanes = $this->getLaneRows( $sProUid ); - $oData->inputs = $this->getInputRows( $sProUid ); - $oData->outputs = $this->getOutputRows( $sProUid ); - $oData->dynaforms = $this->getDynaformRows ( $sProUid ); - $oData->steps = $this->getStepRows( $sProUid ); - $oData->triggers = $this->getTriggerRows( $sProUid ); - $oData->taskusers = $this->getTaskUserRows( $oData->tasks ); - $oData->groupwfs = $this->getGroupwfRows( $oData->taskusers ); - $oData->steptriggers = $this->getStepTriggerRows( $oData->tasks ); - $oData->dbconnections = $this->getDBConnectionsRows($sProUid); - $oData->reportTables = $this->getReportTablesRows($sProUid); - $oData->reportTablesVars = $this->getReportTablesVarsRows($sProUid); - $oData->stepSupervisor = $this->getStepSupervisorRows($sProUid); - $oData->objectPermissions = $this->getObjectPermissionRows ($sProUid); - $oData->subProcess = $this->getSubProcessRow ($sProUid); - $oData->caseTracker = $this->getCaseTrackerRow ($sProUid); - $oData->caseTrackerObject = $this->getCaseTrackerObjectRow ($sProUid); - $oData->stage = $this->getStageRow ($sProUid); - $oData->fieldCondition = $this->getFieldCondition($sProUid); - $oData->event = $this->getEventRow ($sProUid); - $oData->caseScheduler = $this->getCaseSchedulerRow ($sProUid); - $path = PATH_DOCUMENT . 'output' . PATH_SEP; - if ( !is_dir($path) ) { - G::verifyPath($path, true); - } - $proTitle = (substr(G::inflect($oData->process['PRO_TITLE']), 0, 245)); - $proTitle = preg_replace("/[^A-Za-z0-9_]/", "", $proTitle); - //Calculating the maximum length of file name - $pathLength = strlen(PATH_DATA ."sites".PATH_SEP.SYS_SYS.PATH_SEP."files".PATH_SEP."output".PATH_SEP); - $length = strlen($proTitle) + $pathLength; - if ($length >= 250) { - $proTitle = myTruncate($proTitle, 250 - $pathLength, '_', ''); - } - $index = ''; - $lastIndex = ''; - do { - $filename = $path . $proTitle . $index . '.xpdl'; - $lastIndex = $index; - if ( $index == '' ) - $index = 1; - else - $index ++; - } while ( file_exists ( $filename ) ); - $proTitle .= $lastIndex; - $filenameOnly = $proTitle . '.xpdl'; - $xml = fopen( $filename.'tpm', "wb"); - $process = $oData->process; - $coordinateMaximumY = 0; - $coordinateMaximumX = 0; - $lanes = $oData->lanes; - foreach ($lanes as $keyLane => $valLane ) { - if($valLane['SWI_TYPE']=="TEXT"){ - $textLane = $valLane['SWI_TEXT']; - $longText = strlen($textLane); - $height = 0; - $width = 0; - if($longText < 40){ - $height = 20; - $width = ($longText*10)+ 10; + /** + * This public function create the file . + * + * xpdl from a process + * + * @param string $sProUid + * @return void + */ + public function xmdlProcess ($sProUid = '') + { + $oProcess = new Process(); + $oData->process = $this->getProcessRow( $sProUid, false ); + $oData->tasks = $this->getTaskRows( $sProUid ); + $oData->routes = $this->getRouteRows( $sProUid ); + $oData->lanes = $this->getLaneRows( $sProUid ); + $oData->inputs = $this->getInputRows( $sProUid ); + $oData->outputs = $this->getOutputRows( $sProUid ); + $oData->dynaforms = $this->getDynaformRows( $sProUid ); + $oData->steps = $this->getStepRows( $sProUid ); + $oData->triggers = $this->getTriggerRows( $sProUid ); + $oData->taskusers = $this->getTaskUserRows( $oData->tasks ); + $oData->groupwfs = $this->getGroupwfRows( $oData->taskusers ); + $oData->steptriggers = $this->getStepTriggerRows( $oData->tasks ); + $oData->dbconnections = $this->getDBConnectionsRows( $sProUid ); + $oData->reportTables = $this->getReportTablesRows( $sProUid ); + $oData->reportTablesVars = $this->getReportTablesVarsRows( $sProUid ); + $oData->stepSupervisor = $this->getStepSupervisorRows( $sProUid ); + $oData->objectPermissions = $this->getObjectPermissionRows( $sProUid ); + $oData->subProcess = $this->getSubProcessRow( $sProUid ); + $oData->caseTracker = $this->getCaseTrackerRow( $sProUid ); + $oData->caseTrackerObject = $this->getCaseTrackerObjectRow( $sProUid ); + $oData->stage = $this->getStageRow( $sProUid ); + $oData->fieldCondition = $this->getFieldCondition( $sProUid ); + $oData->event = $this->getEventRow( $sProUid ); + $oData->caseScheduler = $this->getCaseSchedulerRow( $sProUid ); + $path = PATH_DOCUMENT . 'output' . PATH_SEP; + if (! is_dir( $path )) { + G::verifyPath( $path, true ); } - if($longText > 40){ - $numberRows = $longText/40; - $height = $numberRows * 20; - $width = 250; + $proTitle = (substr( G::inflect( $oData->process['PRO_TITLE'] ), 0, 245 )); + $proTitle = preg_replace( "/[^A-Za-z0-9_]/", "", $proTitle ); + //Calculating the maximum length of file name + $pathLength = strlen( PATH_DATA . "sites" . PATH_SEP . SYS_SYS . PATH_SEP . "files" . PATH_SEP . "output" . PATH_SEP ); + $length = strlen( $proTitle ) + $pathLength; + if ($length >= 250) { + $proTitle = myTruncate( $proTitle, 250 - $pathLength, '_', '' ); } - $coordinateX = $valLane['SWI_X'] + $width; - $coordinateY = $valLane['SWI_Y'] + $height ; - if($coordinateX > $coordinateMaximumX){ - $coordinateMaximumX = $coordinateX; + $index = ''; + $lastIndex = ''; + do { + $filename = $path . $proTitle . $index . '.xpdl'; + $lastIndex = $index; + if ($index == '') { + $index = 1; + } else { + $index ++; + } + } while (file_exists( $filename )); + $proTitle .= $lastIndex; + $filenameOnly = $proTitle . '.xpdl'; + $xml = fopen( $filename . 'tpm', "wb" ); + $process = $oData->process; + $coordinateMaximumY = 0; + $coordinateMaximumX = 0; + $lanes = $oData->lanes; + foreach ($lanes as $keyLane => $valLane) { + if ($valLane['SWI_TYPE'] == "TEXT") { + $textLane = $valLane['SWI_TEXT']; + $longText = strlen( $textLane ); + $height = 0; + $width = 0; + if ($longText < 40) { + $height = 20; + $width = ($longText * 10) + 10; + } + if ($longText > 40) { + $numberRows = $longText / 40; + $height = $numberRows * 20; + $width = 250; + } + $coordinateX = $valLane['SWI_X'] + $width; + $coordinateY = $valLane['SWI_Y'] + $height; + if ($coordinateX > $coordinateMaximumX) { + $coordinateMaximumX = $coordinateX; + } + if ($coordinateY > $coordinateMaximumY) { + $coordinateMaximumY = $coordinateY; + } + } } - if($coordinateY > $coordinateMaximumY){ - $coordinateMaximumY = $coordinateY; + foreach ($oData->tasks as $keyLane => $val) { + $coordinateX = $val['TAS_POSX'] + 160; + $coordinateY = $val['TAS_POSY'] + 38; + if ($coordinateX > $coordinateMaximumX) { + $coordinateMaximumX = $coordinateX; + } + if ($coordinateY > $coordinateMaximumY) { + $coordinateMaximumY = $coordinateY; + } } - } - } - foreach ($oData->tasks as $keyLane => $val ) { - $coordinateX = $val['TAS_POSX']+ 160; - $coordinateY = $val['TAS_POSY']+ 38; - if($coordinateX > $coordinateMaximumX){ - $coordinateMaximumX = $coordinateX; - } - if($coordinateY > $coordinateMaximumY){ - $coordinateMaximumY = $coordinateY; - } - } - $data = $this->createPool($process,$coordinateMaximumX + 60,$coordinateMaximumY +60); - fwrite ($xml, ''); - fwrite ($xml, $data); - $artifacts = ''; - $artifacts .= $this->createArtifacts($lanes,'0'); - $dataProcess =' + $data = $this->createPool( $process, $coordinateMaximumX + 60, $coordinateMaximumY + 60 ); + fwrite( $xml, '' ); + fwrite( $xml, $data ); + $artifacts = ''; + $artifacts .= $this->createArtifacts( $lanes, '0' ); + $dataProcess = ' '; - $dataProcess.= ' - + $dataProcess .= ' + '; - $activitySets = ''; - $subProcess = $oData->subProcess; - $subProcesses = $this-> createSubProcessesXpdl($subProcess,$oData->tasks); - $activitySets.= $subProcesses['ACTIVITIES']; - $activitySets.= ''; - $artifacts .= $subProcesses['ARTIFACTS']; - $artifacts .=' + $activitySets = ''; + $subProcess = $oData->subProcess; + $subProcesses = $this->createSubProcessesXpdl( $subProcess, $oData->tasks ); + $activitySets .= $subProcesses['ACTIVITIES']; + $activitySets .= ''; + $artifacts .= $subProcesses['ARTIFACTS']; + $artifacts .= ' '; - fwrite ($xml,$artifacts); - fwrite ($xml,$dataProcess); - fwrite ($xml,$activitySets); - // Here are generated activities of a file. XPDL - // for this use the process tasks - $tasks = $oData->tasks; - $events = $oData->event; - $scheduler = $oData->caseScheduler; - $dataTasks = $this-> createActivitiesXpdl($tasks,$events,$scheduler); - fwrite ($xml,$dataTasks['ACTIVITIES']); - $taskHidden = $dataTasks['TASK_HIDDEN']; - $routes = $oData->routes; - $dataRoutes = $this-> createTransitionsXpdl($routes,$tasks,$taskHidden); - fwrite ($xml,$dataRoutes['ACTIVITIES']); - $data = ' + fwrite( $xml, $artifacts ); + fwrite( $xml, $dataProcess ); + fwrite( $xml, $activitySets ); + // Here are generated activities of a file. XPDL + // for this use the process tasks + $tasks = $oData->tasks; + $events = $oData->event; + $scheduler = $oData->caseScheduler; + $dataTasks = $this->createActivitiesXpdl( $tasks, $events, $scheduler ); + fwrite( $xml, $dataTasks['ACTIVITIES'] ); + $taskHidden = $dataTasks['TASK_HIDDEN']; + $routes = $oData->routes; + $dataRoutes = $this->createTransitionsXpdl( $routes, $tasks, $taskHidden ); + fwrite( $xml, $dataRoutes['ACTIVITIES'] ); + $data = ' '; - fwrite ($xml, $data); - fwrite ($xml, $dataTasks['TRANSITION']); - fwrite ($xml, $dataRoutes['TRANSITION']); - $data = ' + fwrite( $xml, $data ); + fwrite( $xml, $dataTasks['TRANSITION'] ); + fwrite( $xml, $dataRoutes['TRANSITION'] ); + $data = ' '; - fwrite ($xml, $data); - fclose ($xml); - $filenameLink = 'processes_DownloadFileXpdl?p=' . $proTitle . '&r=' . rand(100,1000); - $result['FILENAMEXPDL'] = $proTitle.'.xpdl'; - $result['FILENAME_LINKXPDL']= $filenameLink; - return $result; - } + fwrite( $xml, $data ); + fclose( $xml ); + $filenameLink = 'processes_DownloadFileXpdl?p=' . $proTitle . '&r=' . rand( 100, 1000 ); + $result['FILENAMEXPDL'] = $proTitle . '.xpdl'; + $result['FILENAME_LINKXPDL'] = $filenameLink; + return $result; + } - /** - * This function create the pool from the process - * @param array $process - * @param string $coordinateMaximumX - * @param string $coordinateMaximumY - * @return string - */ - function createPool ($process,$coordinateMaximumX,$coordinateMaximumY) - { - $data = ''; - $data .= ' - + /** + * This public function create the pool from the process + * + * @param array $process + * @param string $coordinateMaximumX + * @param string $coordinateMaximumY + * @return string + */ + public function createPool ($process, $coordinateMaximumX, $coordinateMaximumY) + { + $data = ''; + $data .= ' + 2.1 Process Maker - '.$process['PRO_CREATE_DATE'].' - '.$process['PRO_DESCRIPTION'].' + ' . $process['PRO_CREATE_DATE'] . ' + ' . $process['PRO_DESCRIPTION'] . ' @@ -465,11 +485,11 @@ class Xpdl extends processes - + - + @@ -479,159 +499,161 @@ class Xpdl extends processes '; - return $data; - } + return $data; + } - /** - * This function generated the Artifacts of a file. XPDL - * @param array $lanes - * @param string $id - * @return string - */ - function createArtifacts($lanes,$id) - { - $artifacts = ''; - $idTask = ''; - foreach ($lanes as $keyLane => $valLane ) { - if($valLane['SWI_TYPE']=="TEXT"){ - $idLane = $valLane['SWI_UID']; - $textLane = $valLane['SWI_TEXT']; - $coordinateX = $valLane['SWI_X']; - $coordinateY = $valLane['SWI_Y']; - $longText = strlen($textLane); - if($longText < 40){ - $height = 20; - $width = ($longText*10)+ 10; - } - if($longText > 40){ - $numberRows = $longText/40; - $height = $numberRows * 20; - $width = 250; - } - if($id != 0){ - $idTask = ' ActivitySetId="'.$id.'"'; - } - $artifacts .=' - + /** + * This public function generated the Artifacts of a file. + * XPDL + * + * @param array $lanes + * @param string $id + * @return string + */ + public function createArtifacts ($lanes, $id) + { + $artifacts = ''; + $idTask = ''; + foreach ($lanes as $keyLane => $valLane) { + if ($valLane['SWI_TYPE'] == "TEXT") { + $idLane = $valLane['SWI_UID']; + $textLane = $valLane['SWI_TEXT']; + $coordinateX = $valLane['SWI_X']; + $coordinateY = $valLane['SWI_Y']; + $longText = strlen( $textLane ); + if ($longText < 40) { + $height = 20; + $width = ($longText * 10) + 10; + } + if ($longText > 40) { + $numberRows = $longText / 40; + $height = $numberRows * 20; + $width = 250; + } + if ($id != 0) { + $idTask = ' ActivitySetId="' . $id . '"'; + } + $artifacts .= ' + - - + + '; - } + } + } + return $artifacts; } - return $artifacts; - } - /** - * This function creates SubProcesses - * @param array $tasks - * @param array $subProcess - * @return array - */ - function createSubProcessesXpdl($subProcess,$tasks) - { - $activitySets = ''; - $dataCreated = ''; - $artifacts = ''; - foreach ($subProcess as $key => $row) { - if($row['SP_UID'] != ''){ - $idTask = $row['TAS_PARENT']; - foreach ($tasks as $id => $value) { - if($value['TAS_UID'] == $idTask){ - $nameTask = htmlentities($value['TAS_TITLE']); - } - } - $activitySets.=' - '; - if($row['PRO_UID'] != '' && $row['PRO_UID'] != 0){ - $dataSubProcess= $this->serializeProcess($row['PRO_UID']); - $data = unserialize ($dataSubProcess); - $tasks = $data->tasks; - $subProcessData= $data->subProcess; - $subProcessTask= $data->tasks; - $lanes = $data->lanes; - $events = $data->event; - $scheduler = $data->caseScheduler; - $artifacts = $this->createArtifacts($lanes,$idTask); - $dataCreated = $this->createSubProcessesXpdl($subProcessData,$subProcessTask); - $dataTasks = $this->createActivitiesXpdl($tasks,$events,$scheduler); - $activitySets .=$dataTasks['ACTIVITIES']; - $taskHidden = $dataTasks['TASK_HIDDEN']; - $routes = $data->routes; - $dataRoutes = $this->createTransitionsXpdl($routes,$tasks,$taskHidden); - $activitySets .=$dataRoutes['ACTIVITIES']; - $activitySets .= ' + /** + * This public function creates SubProcesses + * + * @param array $tasks + * @param array $subProcess + * @return array + */ + public function createSubProcessesXpdl ($subProcess, $tasks) + { + $activitySets = ''; + $dataCreated = ''; + $artifacts = ''; + foreach ($subProcess as $key => $row) { + if ($row['SP_UID'] != '') { + $idTask = $row['TAS_PARENT']; + foreach ($tasks as $id => $value) { + if ($value['TAS_UID'] == $idTask) { + $nameTask = htmlentities( $value['TAS_TITLE'] ); + } + } + $activitySets .= ' + '; + if ($row['PRO_UID'] != '' && $row['PRO_UID'] != 0) { + $dataSubProcess = $this->serializeProcess( $row['PRO_UID'] ); + $data = unserialize( $dataSubProcess ); + $tasks = $data->tasks; + $subProcessData = $data->subProcess; + $subProcessTask = $data->tasks; + $lanes = $data->lanes; + $events = $data->event; + $scheduler = $data->caseScheduler; + $artifacts = $this->createArtifacts( $lanes, $idTask ); + $dataCreated = $this->createSubProcessesXpdl( $subProcessData, $subProcessTask ); + $dataTasks = $this->createActivitiesXpdl( $tasks, $events, $scheduler ); + $activitySets .= $dataTasks['ACTIVITIES']; + $taskHidden = $dataTasks['TASK_HIDDEN']; + $routes = $data->routes; + $dataRoutes = $this->createTransitionsXpdl( $routes, $tasks, $taskHidden ); + $activitySets .= $dataRoutes['ACTIVITIES']; + $activitySets .= ' '; - $activitySets .=$dataTasks['TRANSITION']; - $activitySets .=$dataRoutes['TRANSITION']; - $activitySets .= ' + $activitySets .= $dataTasks['TRANSITION']; + $activitySets .= $dataRoutes['TRANSITION']; + $activitySets .= ' '; - } - else{ - $data =' + } else { + $data = ' '; + } + $activitySets .= ''; + $activitySets .= $dataCreated; + } } - $activitySets.=''; - $activitySets.=$dataCreated; - } + $fields['ACTIVITIES'] = $activitySets; + $fields['ARTIFACTS'] = $artifacts; + return $fields; } - $fields['ACTIVITIES']= $activitySets; - $fields['ARTIFACTS'] = $artifacts; - return $fields; - } - /** - * This function creates activities from the tasks - * @param array $tasks - * @return array - */ - function createActivitiesXpdl($tasks,$events,$scheduler) - { - $dataTasks = ' + /** + * This public function creates activities from the tasks + * + * @param array $tasks + * @return array + */ + public function createActivitiesXpdl ($tasks, $events, $scheduler) + { + $dataTasks = ' '; - $transitions =' + $transitions = ' '; - $start = 0; - $implementation = ''; - $taskHidden = array(); - $description = ''; - foreach ($tasks as $key => $val ) { - $idTask = $val['TAS_UID']; - $nameTask = $val['TAS_TITLE']; - $coordinateX = $val['TAS_POSX']; - $coordinateY = $val['TAS_POSY']; - if($val['TAS_TYPE']== 'NORMAL' or $val['TAS_TYPE']== 'SUBPROCESS'){ - if($val['TAS_TYPE']== 'NORMAL'){ - $implementation = ' + $start = 0; + $implementation = ''; + $taskHidden = array (); + $description = ''; + foreach ($tasks as $key => $val) { + $idTask = $val['TAS_UID']; + $nameTask = $val['TAS_TITLE']; + $coordinateX = $val['TAS_POSX']; + $coordinateY = $val['TAS_POSY']; + if ($val['TAS_TYPE'] == 'NORMAL' or $val['TAS_TYPE'] == 'SUBPROCESS') { + if ($val['TAS_TYPE'] == 'NORMAL') { + $implementation = ' '; - } - if($val['TAS_TYPE']== 'SUBPROCESS'){ - $implementation = ' - '; - } - if(isset($val['TAS_DESCRIPTION'])){ - $description = $val['TAS_DESCRIPTION']; - } - else{ - $description = ''; - } - $fillColor = $val['TAS_COLOR']; - if($val['TAS_START']=="TRUE"){ - $start = 1; - } - if($start==1){ - $start=0; - $positionX=$coordinateX+65; - $positionY=$coordinateY-45; - $dataTasks .=' - - '.$description.' + } + if ($val['TAS_TYPE'] == 'SUBPROCESS') { + $implementation = ' + '; + } + if (isset( $val['TAS_DESCRIPTION'] )) { + $description = $val['TAS_DESCRIPTION']; + } else { + $description = ''; + } + $fillColor = $val['TAS_COLOR']; + if ($val['TAS_START'] == "TRUE") { + $start = 1; + } + if ($start == 1) { + $start = 0; + $positionX = $coordinateX + 65; + $positionY = $coordinateY - 45; + $dataTasks .= ' + + ' . $description . ' @@ -639,14 +661,13 @@ class Xpdl extends processes - - + + '; - $transitions.=' - + $transitions .= ' + @@ -655,98 +676,95 @@ class Xpdl extends processes '; - } - $dataTasks .=' - - '.$description.'' - .$implementation.' + } + $dataTasks .= ' + + ' . $description . '' . $implementation . ' - - + + '; - } - else{ - if($val['TAS_TYPE']== 'HIDDEN'){ - $taskHidden[] = $tasks[$key]; - } - } - } - - $aux = $events; - foreach ($events as $key => $row) { - $aux[$key]= $row['TAS_UID']; - } - if(sizeof($events)> 0){ - array_multisort($aux,SORT_ASC,$events); - unset($aux); - } - $findTask = 0; - $idTasks = array(); - $arrayTasks = array(); - $port = 5; - foreach($events as $key => $val){ - if($val['EVN_ACTION'] == 'SEND_MESSAGE' and $val['EVN_RELATED_TO'] == 'SINGLE'){ - $idEvent = $val['EVN_UID']; - $idTask = $val['TAS_UID']; - foreach($tasks as $id => $value){ - if($value['TAS_UID'] == $idTask){ - $coordinateX = $value['TAS_POSX'] + 19; - $coordinateY = $value['TAS_POSY'] + 38; - $coordinateXM = $coordinateX + 96; - $coordinateYM = $coordinateY + 65; - } - } - foreach($arrayTasks as $id => $value){ - if($idTask == $value['ID']){ - $coordinateX = $value['X'] + 30; - $coordinateY = $value['Y']; - $coordinateXM = $value['XM']+ 30; - $coordinateYM = $value['YM']; - if($coordinateY < 30){ - $coordinateX = $value['FIRSTX'] + 30; - $coordinateY = $value['FIRSTY']; + } else { + if ($val['TAS_TYPE'] == 'HIDDEN') { + $taskHidden[] = $tasks[$key]; + } } - $arrayTasks[$id]['X'] = $coordinateX; - $arrayTasks[$id]['Y'] = $coordinateY; - $arrayTasks[$id]['PORT'] = $port + 1; - $findTask = 1; - $port = $arrayTasks[$id]['PORT']; - } } - $description = $val['EVN_DESCRIPTION']; - $arrayTo = $val['EVN_ACTION_PARAMETERS']; - foreach($arrayTo as $idTo => $valueTo){ - $to = $valueTo; + $aux = $events; + foreach ($events as $key => $row) { + $aux[$key] = $row['TAS_UID']; } - $to = explode('|',$to); - $to = $to[0]; - $oConfiguration = new Configuration(); - $emailArray = $oConfiguration->load('Emails','','','',''); - $arrayFrom = unserialize($emailArray['CFG_VALUE']); - $passwd = $arrayFrom['MESS_PASSWORD']; - $passwdDec = G::decrypt($passwd,'EMAILENCRYPT'); - if (strpos( $passwdDec, 'hash:' ) !== false) { - list($hash, $pass) = explode(":", $passwdDec); - $arrayFrom['MESS_PASSWORD'] = $pass; + if (sizeof( $events ) > 0) { + array_multisort( $aux, SORT_ASC, $events ); + unset( $aux ); } - $from = $arrayFrom['MESS_ACCOUNT']; - if($to == 'ext'){ - $oUser = new Users(); - $aUser = $oUser->load($_SESSION['USER_LOGGED']); - $to = $aUser['USR_USERNAME']; - } - $dataTasks .=' - + $findTask = 0; + $idTasks = array (); + $arrayTasks = array (); + $port = 5; + foreach ($events as $key => $val) { + if ($val['EVN_ACTION'] == 'SEND_MESSAGE' and $val['EVN_RELATED_TO'] == 'SINGLE') { + $idEvent = $val['EVN_UID']; + $idTask = $val['TAS_UID']; + foreach ($tasks as $id => $value) { + if ($value['TAS_UID'] == $idTask) { + $coordinateX = $value['TAS_POSX'] + 19; + $coordinateY = $value['TAS_POSY'] + 38; + $coordinateXM = $coordinateX + 96; + $coordinateYM = $coordinateY + 65; + } + } + foreach ($arrayTasks as $id => $value) { + if ($idTask == $value['ID']) { + $coordinateX = $value['X'] + 30; + $coordinateY = $value['Y']; + $coordinateXM = $value['XM'] + 30; + $coordinateYM = $value['YM']; + if ($coordinateY < 30) { + $coordinateX = $value['FIRSTX'] + 30; + $coordinateY = $value['FIRSTY']; + } + $arrayTasks[$id]['X'] = $coordinateX; + $arrayTasks[$id]['Y'] = $coordinateY; + $arrayTasks[$id]['PORT'] = $port + 1; + $findTask = 1; + $port = $arrayTasks[$id]['PORT']; + } + } + + $description = $val['EVN_DESCRIPTION']; + $arrayTo = $val['EVN_ACTION_PARAMETERS']; + foreach ($arrayTo as $idTo => $valueTo) { + $to = $valueTo; + } + $to = explode( '|', $to ); + $to = $to[0]; + $oConfiguration = new Configuration(); + $emailArray = $oConfiguration->load( 'Emails', '', '', '', '' ); + $arrayFrom = unserialize( $emailArray['CFG_VALUE'] ); + $passwd = $arrayFrom['MESS_PASSWORD']; + $passwdDec = G::decrypt( $passwd, 'EMAILENCRYPT' ); + if (strpos( $passwdDec, 'hash:' ) !== false) { + list ($hash, $pass) = explode( ":", $passwdDec ); + $arrayFrom['MESS_PASSWORD'] = $pass; + } + $from = $arrayFrom['MESS_ACCOUNT']; + if ($to == 'ext') { + $oUser = new Users(); + $aUser = $oUser->load( $_SESSION['USER_LOGGED'] ); + $to = $aUser['USR_USERNAME']; + } + $dataTasks .= ' + - + TimeCycle @@ -756,90 +774,90 @@ class Xpdl extends processes - + false - - '.$description.' + + ' . $description . ' - + - '.$description.' + ' . $description . ' - + false '; - $transitions.=' - + $transitions .= ' + - + '; - if($findTask == 0){ - $idTasks['ID'] = $idTask; - $idTasks['X'] = $coordinateX; - $idTasks['Y'] = $coordinateY; - $idTasks['FIRSTX'] = $coordinateX; - $idTasks['FIRSTY'] = $coordinateY; - $idTasks['XM'] = $coordinateXM; - $idTasks['YM'] = $coordinateYM; - $idTasks['PORT'] = $port; - $arrayTasks[] = $idTasks; - } - } - } - $idTasks = array(); - $arrayTasks = array(); - $findTask = 0; - foreach($scheduler as $key => $val){ - if($val['SCH_OPTION'] == 4){ - $idSch = $val['SCH_UID']; - $name = $val['SCH_NAME']; - $idTask = $val['TAS_UID']; - foreach($tasks as $id => $value){ - if($value['TAS_UID'] == $idTask){ - $coordinateX = $value['TAS_POSX'] - 60; - $coordinateY = $value['TAS_POSY'] + 5; - } - } - foreach($arrayTasks as $id => $value){ - if($idTask == $value['ID']){ - $coordinateX = $value['X']; - $coordinateY = $value['Y'] - 40; - if($coordinateY < 30){ - $coordinateX = $value['FIRSTX'] + 50; - $coordinateY = $value['FIRSTY'] - 90; + if ($findTask == 0) { + $idTasks['ID'] = $idTask; + $idTasks['X'] = $coordinateX; + $idTasks['Y'] = $coordinateY; + $idTasks['FIRSTX'] = $coordinateX; + $idTasks['FIRSTY'] = $coordinateY; + $idTasks['XM'] = $coordinateXM; + $idTasks['YM'] = $coordinateYM; + $idTasks['PORT'] = $port; + $arrayTasks[] = $idTasks; + } } - $arrayTasks[$id]['X'] = $coordinateX; - $arrayTasks[$id]['Y'] = $coordinateY; - $findTask = 1; - } } - $time = $val['SCH_TIME_NEXT_RUN']; - $time = explode(' ',$time); - $time = $time[0]; - $time = str_replace('-','/',$time); - $dataTasks .=' - + $idTasks = array (); + $arrayTasks = array (); + $findTask = 0; + foreach ($scheduler as $key => $val) { + if ($val['SCH_OPTION'] == 4) { + $idSch = $val['SCH_UID']; + $name = $val['SCH_NAME']; + $idTask = $val['TAS_UID']; + foreach ($tasks as $id => $value) { + if ($value['TAS_UID'] == $idTask) { + $coordinateX = $value['TAS_POSX'] - 60; + $coordinateY = $value['TAS_POSY'] + 5; + } + } + foreach ($arrayTasks as $id => $value) { + if ($idTask == $value['ID']) { + $coordinateX = $value['X']; + $coordinateY = $value['Y'] - 40; + if ($coordinateY < 30) { + $coordinateX = $value['FIRSTX'] + 50; + $coordinateY = $value['FIRSTY'] - 90; + } + $arrayTasks[$id]['X'] = $coordinateX; + $arrayTasks[$id]['Y'] = $coordinateY; + $findTask = 1; + } + } + $time = $val['SCH_TIME_NEXT_RUN']; + $time = explode( ' ', $time ); + $time = $time[0]; + $time = str_replace( '-', '/', $time ); + $dataTasks .= ' + - + TimeCycle @@ -848,13 +866,13 @@ class Xpdl extends processes - + false '; - $transitions.=' - + $transitions .= ' + @@ -863,40 +881,40 @@ class Xpdl extends processes '; - if($findTask == 0){ - $idTasks['ID'] = $idTask; - $idTasks['X'] = $coordinateX; - $idTasks['Y'] = $coordinateY; - $idTasks['FIRSTX'] = $coordinateX; - $idTasks['FIRSTY'] = $coordinateY; - $arrayTasks[] = $idTasks; - } - } - if($val['SCH_OPTION'] == 1){ - $idSch = $val['SCH_UID']; - $name = $val['SCH_NAME']; - $idTask = $val['TAS_UID']; - foreach($tasks as $id => $value){ - if($value['TAS_UID'] == $idTask){ - $coordinateX = $value['TAS_POSX'] - 60; - $coordinateY = $value['TAS_POSY'] + 5; - } - } - foreach($arrayTasks as $id => $value){ - if($idTask == $value['ID']){ - $coordinateX = $value['X']; - $coordinateY = $value['Y'] - 40; - if($coordinateY < 30){ - $coordinateX = $value['FIRSTX'] + 50; - $coordinateY = $value['FIRSTY'] - 90; + if ($findTask == 0) { + $idTasks['ID'] = $idTask; + $idTasks['X'] = $coordinateX; + $idTasks['Y'] = $coordinateY; + $idTasks['FIRSTX'] = $coordinateX; + $idTasks['FIRSTY'] = $coordinateY; + $arrayTasks[] = $idTasks; + } } - $arrayTasks[$id]['X'] = $coordinateX; - $arrayTasks[$id]['Y'] = $coordinateY; - $findTask = 1; - } - } - $dataTasks .=' - + if ($val['SCH_OPTION'] == 1) { + $idSch = $val['SCH_UID']; + $name = $val['SCH_NAME']; + $idTask = $val['TAS_UID']; + foreach ($tasks as $id => $value) { + if ($value['TAS_UID'] == $idTask) { + $coordinateX = $value['TAS_POSX'] - 60; + $coordinateY = $value['TAS_POSY'] + 5; + } + } + foreach ($arrayTasks as $id => $value) { + if ($idTask == $value['ID']) { + $coordinateX = $value['X']; + $coordinateY = $value['Y'] - 40; + if ($coordinateY < 30) { + $coordinateX = $value['FIRSTX'] + 50; + $coordinateY = $value['FIRSTY'] - 90; + } + $arrayTasks[$id]['X'] = $coordinateX; + $arrayTasks[$id]['Y'] = $coordinateY; + $findTask = 1; + } + } + $dataTasks .= ' + @@ -909,13 +927,13 @@ class Xpdl extends processes - + false '; - $transitions.=' - + $transitions .= ' + @@ -924,129 +942,130 @@ class Xpdl extends processes '; - if($findTask == 0){ - $idTasks['ID'] = $idTask; - $idTasks['X'] = $coordinateX; - $idTasks['Y'] = $coordinateY; - $idTasks['FIRSTX'] = $coordinateX; - $idTasks['FIRSTY'] = $coordinateY; - $arrayTasks[] = $idTasks; + if ($findTask == 0) { + $idTasks['ID'] = $idTask; + $idTasks['X'] = $coordinateX; + $idTasks['Y'] = $coordinateY; + $idTasks['FIRSTX'] = $coordinateX; + $idTasks['FIRSTY'] = $coordinateY; + $arrayTasks[] = $idTasks; + } + } } - } + $data = array (); + $data['ACTIVITIES'] = $dataTasks; + $data['TRANSITION'] = $transitions; + $data['TASK_HIDDEN'] = $taskHidden; + return $data; } - $data = array(); - $data['ACTIVITIES'] = $dataTasks; - $data['TRANSITION'] = $transitions; - $data['TASK_HIDDEN']= $taskHidden; - return $data; - } - /** - * This function creates transitions - * @param array $routes - * @param array $tasks - * @return array - */ - function createTransitionsXpdl($routes,$tasks,$taskHidden) - { - $cont = 0; - $dataRoutes = ''; - $endEvent = 1; - $taskParallel = ''; - $routeParallel = ''; - $taskSecJoin = ''; - $routeSecJoin = ''; - $taskEvaluate = ''; - $routeEvaluate = ''; - $taskParallelEv = ''; - $routeParallelEv = ''; - $taskSelect = ''; - $routeSelect = ''; - $routeEnd = ''; - $arraySecJoin = array(); - $position = 0; - $fillColor = ''; - $transitions = ''; - $condition = ''; - $nextTask = ''; - $findFrom = 0; - $findTo = 0; - $routesTasks = $routes; - foreach ($routes as $key => $row) { - if($row['ROU_TYPE'] == 'SEC-JOIN'){ - $arraySecJoin[$position] = array(); - $arraySecJoin[$position] = $row; - $position = $position + 1; - unset($routes[$key]); - } - } - $aux = $arraySecJoin ; - foreach ($arraySecJoin as $key => $row) { - $aux[$key]= $row['ROU_NEXT_TASK']; - } - if(sizeof($arraySecJoin)> 0){ - array_multisort($aux,SORT_ASC,$arraySecJoin); - unset($aux); - } - foreach ($routes as $key => $row) { - $uid[$key] = $row['TAS_UID']; - $case[$key] = $row['ROU_CASE']; - } - if(sizeof($routes)> 0){ - array_multisort($uid, SORT_ASC, $case, SORT_ASC, $routes); - } - $routes = array_merge($routes,$arraySecJoin); - $routesTasks = $routes; - foreach ($routes as $key => $val ) { - $end = 0; - $idRoute = $val['ROU_UID']; - $idTask = $val['TAS_UID']; - $nextTask = $val['ROU_NEXT_TASK']; - $condition = htmlentities($val['ROU_CONDITION']); - if($nextTask == "-1"){ - $end = 1; - } - $typeRoute = $val['ROU_TYPE']; - $route = ''; - if ($typeRoute != "SEQUENTIAL" ){ - switch($typeRoute){ - case 'PARALLEL': - $coordinateX = 0; - $coordinateY = 0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - } + /** + * This public function creates transitions + * + * @param array $routes + * @param array $tasks + * @return array + */ + public function createTransitionsXpdl ($routes, $tasks, $taskHidden) + { + $cont = 0; + $dataRoutes = ''; + $endEvent = 1; + $taskParallel = ''; + $routeParallel = ''; + $taskSecJoin = ''; + $routeSecJoin = ''; + $taskEvaluate = ''; + $routeEvaluate = ''; + $taskParallelEv = ''; + $routeParallelEv = ''; + $taskSelect = ''; + $routeSelect = ''; + $routeEnd = ''; + $arraySecJoin = array (); + $position = 0; + $fillColor = ''; + $transitions = ''; + $condition = ''; + $nextTask = ''; + $findFrom = 0; + $findTo = 0; + $routesTasks = $routes; + foreach ($routes as $key => $row) { + if ($row['ROU_TYPE'] == 'SEC-JOIN') { + $arraySecJoin[$position] = array (); + $arraySecJoin[$position] = $row; + $position = $position + 1; + unset( $routes[$key] ); } - foreach ($taskHidden as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX = $idVal['TAS_POSX']; - $coordinateY = $idVal['TAS_POSY']; - $idRoute = $idTask; - } + } + $aux = $arraySecJoin; + foreach ($arraySecJoin as $key => $row) { + $aux[$key] = $row['ROU_NEXT_TASK']; + } + if (sizeof( $arraySecJoin ) > 0) { + array_multisort( $aux, SORT_ASC, $arraySecJoin ); + unset( $aux ); + } + foreach ($routes as $key => $row) { + $uid[$key] = $row['TAS_UID']; + $case[$key] = $row['ROU_CASE']; + } + if (sizeof( $routes ) > 0) { + array_multisort( $uid, SORT_ASC, $case, SORT_ASC, $routes ); + } + $routes = array_merge( $routes, $arraySecJoin ); + $routesTasks = $routes; + foreach ($routes as $key => $val) { + $end = 0; + $idRoute = $val['ROU_UID']; + $idTask = $val['TAS_UID']; + $nextTask = $val['ROU_NEXT_TASK']; + $condition = htmlentities( $val['ROU_CONDITION'] ); + if ($nextTask == "-1") { + $end = 1; } - $positionX = $coordinateX + 60; - $positionY = $coordinateY + 40; - if($idTask != $taskParallel){ - $taskParallel = $idTask; - $routeParallel = $idRoute; - $dataRoutes .=' - + $typeRoute = $val['ROU_TYPE']; + $route = ''; + if ($typeRoute != "SEQUENTIAL") { + switch ($typeRoute) { + case 'PARALLEL': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + } + } + foreach ($taskHidden as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + $idRoute = $idTask; + } + } + $positionX = $coordinateX + 60; + $positionY = $coordinateY + 40; + if ($idTask != $taskParallel) { + $taskParallel = $idTask; + $routeParallel = $idRoute; + $dataRoutes .= ' + - - + + false '; - if($taskParallel != $routeParallel ){ - $transitions.=' - + if ($taskParallel != $routeParallel) { + $transitions .= ' + @@ -1055,9 +1074,9 @@ class Xpdl extends processes '; - } - $transitions.=' - + } + $transitions .= ' + @@ -1066,10 +1085,9 @@ class Xpdl extends processes '; - } - else{ - $transitions.=' - + } else { + $transitions .= ' + @@ -1078,45 +1096,45 @@ class Xpdl extends processes '; - } - break; - case 'SEC-JOIN': - $coordinateX = 0; - $coordinateY = 0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$nextTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - } - } - foreach ($taskHidden as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX = $idVal['TAS_POSX']; - $coordinateY = $idVal['TAS_POSY']; - $idRoute = $idTask; - } - } - $positionX = $coordinateX + 60; - $positionY = $coordinateY - 45; - if($nextTask != $taskSecJoin){ - $taskSecJoin = $nextTask; - $routeSecJoin = $idRoute; - $dataRoutes .=' - + } + break; + case 'SEC-JOIN': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $nextTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + } + } + foreach ($taskHidden as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + $idRoute = $idTask; + } + } + $positionX = $coordinateX + 60; + $positionY = $coordinateY - 45; + if ($nextTask != $taskSecJoin) { + $taskSecJoin = $nextTask; + $routeSecJoin = $idRoute; + $dataRoutes .= ' + - - + + false '; - if($routeSecJoin != $taskSecJoin ){ - $transitions.=' - + if ($routeSecJoin != $taskSecJoin) { + $transitions .= ' + @@ -1125,9 +1143,9 @@ class Xpdl extends processes '; - } - $transitions.=' - + } + $transitions .= ' + @@ -1136,10 +1154,9 @@ class Xpdl extends processes '; - } - else{ - $transitions.=' - + } else { + $transitions .= ' + @@ -1148,46 +1165,46 @@ class Xpdl extends processes '; - } - break; - case 'EVALUATE': - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - } - } - foreach ($taskHidden as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX = $idVal['TAS_POSX']; - $coordinateY = $idVal['TAS_POSY']; - $idRoute = $idTask; - } - } - $positionX=$coordinateX+60; - $positionY=$coordinateY+40; - if($idTask != $taskEvaluate){ - $taskEvaluate = $idTask; - $routeEvaluate = $idRoute; - if($nextTask != "-1"){ - $dataRoutes .=' - + } + break; + case 'EVALUATE': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + } + } + foreach ($taskHidden as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + $idRoute = $idTask; + } + } + $positionX = $coordinateX + 60; + $positionY = $coordinateY + 40; + if ($idTask != $taskEvaluate) { + $taskEvaluate = $idTask; + $routeEvaluate = $idRoute; + if ($nextTask != "-1") { + $dataRoutes .= ' + - - + + false '; - if($taskEvaluate != $routeEvaluate ){ - $transitions.=' - + if ($taskEvaluate != $routeEvaluate) { + $transitions .= ' + @@ -1196,11 +1213,11 @@ class Xpdl extends processes '; - } - $transitions.=' - + } + $transitions .= ' + - '.$condition.' + ' . $condition . ' @@ -1209,14 +1226,13 @@ class Xpdl extends processes '; - } - } - else{ - if($nextTask !="-1"){ - $transitions.=' - + } + } else { + if ($nextTask != "-1") { + $transitions .= ' + - '.$condition.' + ' . $condition . ' @@ -1225,49 +1241,48 @@ class Xpdl extends processes '; - } - else{ - $routeEnd = $routeEvaluate; - } - } - break; - case 'PARALLEL-BY-EVALUATION': - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - } - } - foreach ($taskHidden as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX = $idVal['TAS_POSX']; - $coordinateY = $idVal['TAS_POSY']; - $idRoute = $idTask; - } - } - $positionX=$coordinateX+60; - $positionY=$coordinateY+40; - if($idTask != $taskParallelEv){ - $taskParallelEv = $idTask; - $routeParallelEv = $idRoute; - $dataRoutes .=' - + } else { + $routeEnd = $routeEvaluate; + } + } + break; + case 'PARALLEL-BY-EVALUATION': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + } + } + foreach ($taskHidden as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + $idRoute = $idTask; + } + } + $positionX = $coordinateX + 60; + $positionY = $coordinateY + 40; + if ($idTask != $taskParallelEv) { + $taskParallelEv = $idTask; + $routeParallelEv = $idRoute; + $dataRoutes .= ' + - - + + false '; - if($taskParallelEv != $routeParallelEv ){ - $transitions.=' - + if ($taskParallelEv != $routeParallelEv) { + $transitions .= ' + @@ -1276,11 +1291,11 @@ class Xpdl extends processes '; - } - $transitions.=' - + } + $transitions .= ' + - '.$condition.' + ' . $condition . ' @@ -1289,12 +1304,11 @@ class Xpdl extends processes '; - } - else{ - $transitions.=' - + } else { + $transitions .= ' + - '.$condition.' + ' . $condition . ' @@ -1303,45 +1317,45 @@ class Xpdl extends processes '; - } - break; - case 'SELECT': - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - } - } - foreach ($taskHidden as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX = $idVal['TAS_POSX']; - $coordinateY = $idVal['TAS_POSY']; - $idRoute = $idTask; - } - } - $positionX=$coordinateX+60; - $positionY=$coordinateY+40; - if($idTask != $taskSelect){ - $taskSelect = $idTask; - $routeSelect = $idRoute; - $dataRoutes .=' - + } + break; + case 'SELECT': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + } + } + foreach ($taskHidden as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + $idRoute = $idTask; + } + } + $positionX = $coordinateX + 60; + $positionY = $coordinateY + 40; + if ($idTask != $taskSelect) { + $taskSelect = $idTask; + $routeSelect = $idRoute; + $dataRoutes .= ' + - - + + false '; - if($taskSelect != $routeSelect ){ - $transitions.=' - + if ($taskSelect != $routeSelect) { + $transitions .= ' + @@ -1350,11 +1364,11 @@ class Xpdl extends processes '; - } - $transitions.=' - + } + $transitions .= ' + - '.$condition.' + ' . $condition . ' @@ -1363,13 +1377,12 @@ class Xpdl extends processes '; - } - else{ - if($nextTask !="-1"){ - $transitions.=' - + } else { + if ($nextTask != "-1") { + $transitions .= ' + - '.$condition.' + ' . $condition . ' @@ -1378,53 +1391,52 @@ class Xpdl extends processes '; - } - else{ - $routeEnd = $routeSelect; - } - } - break; - case 'DISCRIMINATOR': - $coordinateX = 0; - $coordinateY = 0; - $optional = $val['ROU_OPTIONAL']; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$nextTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - } - } - foreach ($taskHidden as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX = $idVal['TAS_POSX']; - $coordinateY = $idVal['TAS_POSY']; - $idRoute = $idTask; - } - } - $positionX=$coordinateX+60; - $positionY=$coordinateY-45; - if($nextTask != $taskSecJoin){ - $taskDiscriminator = $nextTask; - $routeDiscriminator = $idRoute; - $dataRoutes .=' - + } else { + $routeEnd = $routeSelect; + } + } + break; + case 'DISCRIMINATOR': + $coordinateX = 0; + $coordinateY = 0; + $optional = $val['ROU_OPTIONAL']; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $nextTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + } + } + foreach ($taskHidden as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + $idRoute = $idTask; + } + } + $positionX = $coordinateX + 60; + $positionY = $coordinateY - 45; + if ($nextTask != $taskSecJoin) { + $taskDiscriminator = $nextTask; + $routeDiscriminator = $idRoute; + $dataRoutes .= ' + - - + + - - + + false '; - if($routeDiscriminator != $taskDiscriminator ){ - $transitions.=' - + if ($routeDiscriminator != $taskDiscriminator) { + $transitions .= ' + @@ -1433,9 +1445,9 @@ class Xpdl extends processes '; - } - $transitions.=' - + } + $transitions .= ' + @@ -1443,10 +1455,35 @@ class Xpdl extends processes '; + } else { + $transitions .= ' + + + + + + + + + '; + } + break; + } } - else{ - $transitions.=' - + if ($end == 1) { + if ($typeRoute == "SEQUENTIAL") { + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + } + } + $positionX = $coordinateX + 65; + $positionY = $coordinateY + 40; + $transitions .= ' + @@ -1455,47 +1492,20 @@ class Xpdl extends processes '; - } - break; - } - } - if($end==1){ - if($typeRoute == "SEQUENTIAL"){ - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - } - } - $positionX=$coordinateX+65; - $positionY=$coordinateY+40; - $transitions.=' - - - - - - - - - '; - } - else{ - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - } - } - $positionX = $coordinateX + 120; - $positionY = $coordinateY + 40; - $idTask = $routeEnd; - $transitions.=' - + } else { + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + } + } + $positionX = $coordinateX + 120; + $positionY = $coordinateY + 40; + $idTask = $routeEnd; + $transitions .= ' + @@ -1504,9 +1514,9 @@ class Xpdl extends processes '; - } - $dataRoutes .=' - + } + $dataRoutes .= ' + @@ -1514,19 +1524,18 @@ class Xpdl extends processes - - + + false '; - $end = 0; - $endEvent = 0; - } - else{ - if ($typeRoute == "SEQUENTIAL"){ - $transitions.=' - + $end = 0; + $endEvent = 0; + } else { + if ($typeRoute == "SEQUENTIAL") { + $transitions .= ' + @@ -1535,53 +1544,53 @@ class Xpdl extends processes '; - } - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']+190; - $coordinateY=$idVal['TAS_POSY']+5; - if(isset($idVal['TAS_DEF_MESSAGE'])){ - if($idVal['TAS_DEF_MESSAGE'] != '' and $idVal['TAS_DEF_MESSAGE'] != Null){ - $idEvent = G::generateUniqueID(); - $example = new Derivation(); - $fieldUserTo = $example->getAllUsersFromAnyTask($nextTask); - $fieldUserTo = $example->getUsersFullNameFromArray($fieldUserTo); - $fieldUserFrom = $example->getAllUsersFromAnyTask($idTask); - $fieldUserFrom = $example->getUsersFullNameFromArray($fieldUserFrom); - /*$oUser = new Users(); - $aUser = $oUser->load($_SESSION['USER_LOGGED']); - $from = $aUser['USR_USERNAME'];*/ - $description = ''; - $userFrom = ''; - $userTo = ''; - if(isset($fieldUserFrom[0]['USR_USERNAME'])){ - $userFrom = $fieldUserFrom[0]['USR_USERNAME']; - } - if(isset($fieldUserTo[0]['USR_USERNAME'])){ - $userTo = $fieldUserTo[0]['USR_USERNAME']; - } - $dataRoutes .=' - - '.$description.' + } + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX'] + 190; + $coordinateY = $idVal['TAS_POSY'] + 5; + if (isset( $idVal['TAS_DEF_MESSAGE'] )) { + if ($idVal['TAS_DEF_MESSAGE'] != '' and $idVal['TAS_DEF_MESSAGE'] != null) { + $idEvent = G::generateUniqueID(); + $example = new Derivation(); + $fieldUserTo = $example->getAllUsersFromAnyTask( $nextTask ); + $fieldUserTo = $example->getUsersFullNameFromArray( $fieldUserTo ); + $fieldUserFrom = $example->getAllUsersFromAnyTask( $idTask ); + $fieldUserFrom = $example->getUsersFullNameFromArray( $fieldUserFrom ); + /*$oUser = new Users(); + $aUser = $oUser->load($_SESSION['USER_LOGGED']); + $from = $aUser['USR_USERNAME'];*/ + $description = ''; + $userFrom = ''; + $userTo = ''; + if (isset( $fieldUserFrom[0]['USR_USERNAME'] )) { + $userFrom = $fieldUserFrom[0]['USR_USERNAME']; + } + if (isset( $fieldUserTo[0]['USR_USERNAME'] )) { + $userTo = $fieldUserTo[0]['USR_USERNAME']; + } + $dataRoutes .= ' + + ' . $description . ' - + - '.$description.' + ' . $description . ' - + false '; - $transitions.=' - + $transitions .= ' + @@ -1590,2353 +1599,2355 @@ class Xpdl extends processes '; - } - } - } - } - } - } - $data = array(); - $data['ACTIVITIES'] = $dataRoutes; - $data['TRANSITION'] = $transitions; - return $data; - } - - /** - * Get the process Data from a filename .XPDL - * @param array $pmFilename - * @return void - */ - function getProcessDataXpdl ( $pmFilename ) - { - if (! file_exists($pmFilename) ) - throw ( new Exception ( 'Unable to read uploaded file, please check permissions. ')); - if (! filesize($pmFilename) >= 9 ) - throw ( new Exception ( 'Uploaded file is corrupted, please check the file before continue. ')); - clearstatcache(); - $idProcess = 0; - $nameProcess = ''; - $sw = 0; - $file = new DOMDocument(); - @$file->load($pmFilename, LIBXML_DTDLOAD); - $root = $file->documentElement; - $node = $root->firstChild; - $numberTasks = 0; - $numberLanes = 0; - $endArray = array(); - $posEnd = 0; - $startArray = array(); - $posStart = 0; - $isEnd = 0; - $isStart = 0; - $posRoutes = 0; - $sequencial = 0; - $posT = 0; - $output = ''; - $arrayRoutes = array(); - $arrayLanes = array(); - $routeTransitions = array (); - $start = 0; - $end = 0; - $arrayScheduler = array(); - $arrayMessages = array(); - while ($node) { - if ($node->nodeType == XML_ELEMENT_NODE) { - $name = $node->nodeName; - $content = $node->firstChild; - if($content != array()){ - $output = $content->nodeValue; - } - if(strpos($name,'Pools')!== false){ - while ($content) { - if ($content->nodeType == XML_ELEMENT_NODE) { - $nameChild = $content->nodeName; - $contentChild = $content->firstChild; - if(strpos($nameChild,'Pool')!== false){ - $namePool = $content->getAttribute('Name'); - $idPool = str_replace('-','',$content->getAttribute('Process')); - $process['ID'] = $idPool; - $process['NAME']= $namePool; - $process['DESCRIPTION'] = ''; - $oData->process = $this->createProcess($process); - } - } - $content = $content->nextSibling; - } - } - if(strpos($name,'Artifacts')!== false){ - while ($content) { - if ($content->nodeType == XML_ELEMENT_NODE) { - $nameChild = $content->nodeName; - $contentChild = $content->firstChild; - $idActivity = ''; - if(strpos($nameChild,'Artifact')!== false){ - $artifactType = $content->getAttribute('ArtifactType'); - if($artifactType == 'Annotation'){ - $textAnnotation = $content->getAttribute('TextAnnotation'); - $idAnnotation = str_replace('-','',$content->getAttribute('Id')); - $idActivity = str_replace('-','',$content->getAttribute('ActivitySetId')); - $lanes = $this->findCoordinates($contentChild); - $lanes['TEXT'] = $textAnnotation; - $lanes['ID_PROCESS'] = $idPool; - $lanes['ID_LANE'] = $idAnnotation; - if($idActivity != ''){ - $lanes['ID_PROCESS'] = $idActivity; - } - $arrayLanes[$numberLanes] = $this->createLanes($lanes); - $numberLanes = $numberLanes +1; - } - } - } - $content = $content->nextSibling; - } - } - if(strpos($name,'WorkflowProcesses')!== false){ - while ($content) { - if ($content->nodeType == XML_ELEMENT_NODE) { - $nameChild = $content->nodeName; - $contentChild = $content->firstChild; - if(strpos($nameChild,'WorkflowProcess')!== false){ - $nameWorkflow = $content->getAttribute('Name'); - $idProcess = $content->getAttribute('Id'); - $idProcess = trim(str_replace('-','',$idProcess)); - $subProcesses = array(); - if($nameWorkflow == $namePool and $idProcess == $idPool){ - $idWorkflow = $idProcess; - while ($contentChild) { - if ($contentChild->nodeType == XML_ELEMENT_NODE){ - $nameNode = $contentChild->nodeName; - $contentNode = $contentChild->firstChild; - if(strpos($nameNode,'ActivitySets')!== false){ - $activitySet = $this->createSubProcesses($contentNode,$arrayLanes); - $subProcesses = $activitySet['SUB_PROCESS']; - $arraySubProcesses = $activitySet['SUBPROCESSES']; - } - if(strpos($nameNode,'Activities')!== false){ - $activities = $this->createActivities($contentNode,$idProcess,$subProcesses); - $oData->tasks = $activities['TASKS']; - $startArray = $activities['START']; - $endArray = $activities['END']; - $arrayRoutes = $activities['ROUTES']; - $arrayScheduler = $activities['SCHEDULER']; - $arrayMessages = $activities['MESSAGES']; - } - - if(strpos($nameNode,'Transitions')!== false){ - $transitions = $this->createTransitions($contentNode,$oData->tasks,$arrayRoutes,$endArray,$startArray,$idProcess,$arrayScheduler,$arrayMessages); - $oData->routes = $transitions['ROUTES']; - $oData->tasks = $transitions['TASKS']; - $routeTransitions = $transitions['TRANSITIONS']; - $numberRoutes = $transitions['NUMBER']; - $taskHidden = $transitions['TASKHIDDEN']; - $arrayScheduler = $transitions['SCHEDULER']; - $arrayMessages = $transitions['MESSAGES']; - } + } + } } - $contentChild = $contentChild->nextSibling; - } } - } } - $content = $content->nextSibling; - } } - } - $node = $node->nextSibling; - } - $oData->lanes = array(); - $numberLanes = 0; - foreach($arrayLanes as $key => $value) { - if($value['PRO_UID'] == $idProcess){ - $oData->lanes[$numberLanes] = $value; - $numberLanes = $numberLanes + 1; - } - } - $oData->inputs = array(); - $oData->outputs = array(); - $oData->dynaforms = array(); - $oData->steps = array(); - $oData->taskusers = array(); - $oData->groupwfs = $this->getGroupwfRows( $oData->taskusers ); - $oData->steptriggers = array(); - $oData->dbconnections = array(); - $oData->reportTables = array(); - $oData->reportTablesVars = array(); - $oData->stepSupervisor = array(); - $oData->objectPermissions = array(); - $oData->subProcess = array(); - $numberSubProcess = 0; - $arraySubProcess = $subProcesses; - $numberSubProcess = isset($arraySubProcesses) && is_array($arraySubProcesses) ? sizeof($arraySubProcesses) : 0; - $numberCount = 0; - foreach($subProcesses as $key => $value) { - foreach($oData->tasks as $keyTask => $valueTask) { - if($value['ID_PROCESS'] == $valueTask['TAS_UID']){ - $fields['TASK_PARENT'] = $valueTask['TAS_UID']; - $idSubProcess = $valueTask['TAS_UID']; - $findTask = 0; - $newTasks = $this->getTaskRows($idSubProcess); - foreach ($newTasks as $keyLane => $val ) { - if($val['TAS_START']==='TRUE' and $findTask == 0){ - $findTask = 1; - $value['TASK_START']=$val['TAS_UID']; - } - } - $fields['PROCESS_PARENT']= $idProcess; - $fields['TAS_UID']= $value['TASK_START']; - $oData->subProcess[$numberSubProcess]= $this->createSubProcess($fields,$arraySubProcess); - $numberSubProcess = $numberSubProcess + 1; - } - } - } - $oData->caseTracker = array(); - $oData->caseTrackerObject = array(); - $oData->stage = array(); - $oData->fieldCondition = array(); - $oData->event = $this->createEventMessages($arrayMessages,$idProcess); - $oData->triggers = array(); - $oData->caseScheduler = $this->createScheduler($arrayScheduler,$idProcess); - $oData->dynaformFiles = array(); - $numberTransitions=sizeof($routeTransitions); - if($numberTransitions > 0){ - $routesArray = $this->createGateways($routeTransitions,$endArray,$oData->routes,$numberRoutes,$idProcess,$taskHidden); - $oData->routes = $routesArray; + $data = array (); + $data['ACTIVITIES'] = $dataRoutes; + $data['TRANSITION'] = $transitions; + return $data; } - //print_r($oData);die; - //print_r($arrayMessages);die; - return $oData; - } - - /** - * This function sort a array - * @param array $fields - * @return array sorted - */ - function sortArray($fields) - { - $aux = $fields ; - foreach ($fields as $key => $row) { - $aux[$key] = $row['FROM']; - } - array_multisort($aux,SORT_ASC,$fields); - return $fields; - } - - /** - * This functions verify the routes and removes the routes that are repeated - * @param array $routeTransitions - * @param array $endArray - * @return array - */ - function verifyRoutes ($routeTransitions,$endArray,$taskHidden) - { $findFirst = 0; - $firstRoute = ''; - $taskTo = ''; - $taskFrom = ''; - $routeArrayT = $routeTransitions; - $findHidden = 0; - foreach ($routeTransitions as $valRoute => $value){ - $findHidden = 0; - if($value['ROUTE'] == $firstRoute){ - if($value['TOORFROM'] == 'TO'){ - $taskFrom = $value['FROM']; + /** + * Get the process Data from a filename . + * + * XPDL + * + * @param array $pmFilename + * @return void + */ + public function getProcessDataXpdl ($pmFilename) + { + if (! file_exists( $pmFilename )) { + throw (new Exception( 'Unable to read uploaded file, please check permissions. ' )); } - if($value['TOORFROM'] == 'FROM'){ - $taskTo = $value['TO']; + if (! filesize( $pmFilename ) >= 9) { + throw (new Exception( 'Uploaded file is corrupted, please check the file before continue. ' )); } - if($taskFrom != ''){ - foreach ($routeArrayT as $valRoutes => $values){ - $isEventEnd = 0; - foreach ($endArray as $endBase => $valueEnd){ - if($valueEnd==$values['TO']){ - $isEventEnd = 1; - } - } - if($values['ROUTE'] == $value['ROUTE'] and $values['TO'] != $value['ROUTE'] and $isEventEnd == 0 and $findHidden == 0){ - $taskFrom = $values['TO']; - } - else{ - if($values['ROUTE'] == $value['ROUTE'] and $values['TO'] == $value['ROUTE'] and $isEventEnd == 0){ - foreach ($taskHidden as $idHidden => $valueHidden){ - if($valueHidden['ID_TASK'] == $values['TO']){ - $taskFrom = $valueHidden['ID_TASK']; - $findHidden= 1; - } + clearstatcache(); + $idProcess = 0; + $nameProcess = ''; + $sw = 0; + $file = new DOMDocument(); + @$file->load( $pmFilename, LIBXML_DTDLOAD ); + $root = $file->documentElement; + $node = $root->firstChild; + $numberTasks = 0; + $numberLanes = 0; + $endArray = array (); + $posEnd = 0; + $startArray = array (); + $posStart = 0; + $isEnd = 0; + $isStart = 0; + $posRoutes = 0; + $sequencial = 0; + $posT = 0; + $output = ''; + $arrayRoutes = array (); + $arrayLanes = array (); + $routeTransitions = array (); + $start = 0; + $end = 0; + $arrayScheduler = array (); + $arrayMessages = array (); + while ($node) { + if ($node->nodeType == XML_ELEMENT_NODE) { + $name = $node->nodeName; + $content = $node->firstChild; + if ($content != array ()) { + $output = $content->nodeValue; } - } - } - } - $routeTransitions[$valRoute]['TO']=$taskFrom; - $taskFrom = ''; - } - if($taskTo != ''){ - foreach ($routeArrayT as $valRoutes => $values){ - if($values['ROUTE'] == $value['ROUTE'] and $values['FROM'] != $value['ROUTE'] and $findHidden == 0 ){ - $taskTo = $values['FROM']; - } - } - $routeTransitions[$valRoute]['FROM']=$taskTo; - $taskTo = ''; - } - } - else{ - $firstRoute = $value['ROUTE']; - $taskToE = ''; - $taskFromE = ''; - if($value['TOORFROM'] == 'TO'){ - $taskFromE = $value['FROM']; - } - if($value['TOORFROM'] == 'FROM'){ - $taskToE = $value['TO']; - } - if($taskFromE != ''){ - $findHidden = 0; - foreach ($routeArrayT as $valRoutes => $values){ - $isEventEnd = 0; - foreach ($endArray as $endBase => $valueEnd){ - if($valueEnd==$values['TO']){ - $isEventEnd = 1; - } - } - if($values['ROUTE'] == $value['ROUTE'] and $values['TO'] != $value['ROUTE'] and $isEventEnd == 0 and $findHidden == 0){ - $taskFromE = $values['TO']; - } - else{ - if($values['ROUTE'] == $value['ROUTE'] and $values['TO'] == $value['ROUTE'] and $isEventEnd == 0){ - foreach ($taskHidden as $idHidden => $valueHidden){ - if($valueHidden['ID_TASK'] == $values['TO']){ - $taskFromE = $valueHidden['ID_TASK']; - $findHidden = 1; - } + if (strpos( $name, 'Pools' ) !== false) { + while ($content) { + if ($content->nodeType == XML_ELEMENT_NODE) { + $nameChild = $content->nodeName; + $contentChild = $content->firstChild; + if (strpos( $nameChild, 'Pool' ) !== false) { + $namePool = $content->getAttribute( 'Name' ); + $idPool = str_replace( '-', '', $content->getAttribute( 'Process' ) ); + $process['ID'] = $idPool; + $process['NAME'] = $namePool; + $process['DESCRIPTION'] = ''; + $oData->process = $this->createProcess( $process ); + } + } + $content = $content->nextSibling; + } + } + if (strpos( $name, 'Artifacts' ) !== false) { + while ($content) { + if ($content->nodeType == XML_ELEMENT_NODE) { + $nameChild = $content->nodeName; + $contentChild = $content->firstChild; + $idActivity = ''; + if (strpos( $nameChild, 'Artifact' ) !== false) { + $artifactType = $content->getAttribute( 'ArtifactType' ); + if ($artifactType == 'Annotation') { + $textAnnotation = $content->getAttribute( 'TextAnnotation' ); + $idAnnotation = str_replace( '-', '', $content->getAttribute( 'Id' ) ); + $idActivity = str_replace( '-', '', $content->getAttribute( 'ActivitySetId' ) ); + $lanes = $this->findCoordinates( $contentChild ); + $lanes['TEXT'] = $textAnnotation; + $lanes['ID_PROCESS'] = $idPool; + $lanes['ID_LANE'] = $idAnnotation; + if ($idActivity != '') { + $lanes['ID_PROCESS'] = $idActivity; + } + $arrayLanes[$numberLanes] = $this->createLanes( $lanes ); + $numberLanes = $numberLanes + 1; + } + } + } + $content = $content->nextSibling; + } + } + if (strpos( $name, 'WorkflowProcesses' ) !== false) { + while ($content) { + if ($content->nodeType == XML_ELEMENT_NODE) { + $nameChild = $content->nodeName; + $contentChild = $content->firstChild; + if (strpos( $nameChild, 'WorkflowProcess' ) !== false) { + $nameWorkflow = $content->getAttribute( 'Name' ); + $idProcess = $content->getAttribute( 'Id' ); + $idProcess = trim( str_replace( '-', '', $idProcess ) ); + $subProcesses = array (); + if ($nameWorkflow == $namePool and $idProcess == $idPool) { + $idWorkflow = $idProcess; + while ($contentChild) { + if ($contentChild->nodeType == XML_ELEMENT_NODE) { + $nameNode = $contentChild->nodeName; + $contentNode = $contentChild->firstChild; + if (strpos( $nameNode, 'ActivitySets' ) !== false) { + $activitySet = $this->createSubProcesses( $contentNode, $arrayLanes ); + $subProcesses = $activitySet['SUB_PROCESS']; + $arraySubProcesses = $activitySet['SUBPROCESSES']; + } + if (strpos( $nameNode, 'Activities' ) !== false) { + $activities = $this->createActivities( $contentNode, $idProcess, $subProcesses ); + $oData->tasks = $activities['TASKS']; + $startArray = $activities['START']; + $endArray = $activities['END']; + $arrayRoutes = $activities['ROUTES']; + $arrayScheduler = $activities['SCHEDULER']; + $arrayMessages = $activities['MESSAGES']; + } + + if (strpos( $nameNode, 'Transitions' ) !== false) { + $transitions = $this->createTransitions( $contentNode, $oData->tasks, $arrayRoutes, $endArray, $startArray, $idProcess, $arrayScheduler, $arrayMessages ); + $oData->routes = $transitions['ROUTES']; + $oData->tasks = $transitions['TASKS']; + $routeTransitions = $transitions['TRANSITIONS']; + $numberRoutes = $transitions['NUMBER']; + $taskHidden = $transitions['TASKHIDDEN']; + $arrayScheduler = $transitions['SCHEDULER']; + $arrayMessages = $transitions['MESSAGES']; + } + } + $contentChild = $contentChild->nextSibling; + } + } + } + } + $content = $content->nextSibling; + } } - } } - } - $routeTransitions[$valRoute]['TO']=$taskFromE; - $taskFromE = ''; + $node = $node->nextSibling; } - if($taskToE != ''){ - foreach ($routeArrayT as $valRoutes => $values){ - if($values['ROUTE'] == $value['ROUTE'] and $values['FROM'] != $value['ROUTE'] and $findHidden == 0){ - $taskToE = $values['FROM']; + $oData->lanes = array (); + $numberLanes = 0; + foreach ($arrayLanes as $key => $value) { + if ($value['PRO_UID'] == $idProcess) { + $oData->lanes[$numberLanes] = $value; + $numberLanes = $numberLanes + 1; } - } - $routeTransitions[$valRoute]['FROM']=$taskToE; - $taskToE = ''; } - } + $oData->inputs = array (); + $oData->outputs = array (); + $oData->dynaforms = array (); + $oData->steps = array (); + $oData->taskusers = array (); + $oData->groupwfs = $this->getGroupwfRows( $oData->taskusers ); + $oData->steptriggers = array (); + $oData->dbconnections = array (); + $oData->reportTables = array (); + $oData->reportTablesVars = array (); + $oData->stepSupervisor = array (); + $oData->objectPermissions = array (); + $oData->subProcess = array (); + $numberSubProcess = 0; + $arraySubProcess = $subProcesses; + $numberSubProcess = isset( $arraySubProcesses ) && is_array( $arraySubProcesses ) ? sizeof( $arraySubProcesses ) : 0; + $numberCount = 0; + foreach ($subProcesses as $key => $value) { + foreach ($oData->tasks as $keyTask => $valueTask) { + if ($value['ID_PROCESS'] == $valueTask['TAS_UID']) { + $fields['TASK_PARENT'] = $valueTask['TAS_UID']; + $idSubProcess = $valueTask['TAS_UID']; + $findTask = 0; + $newTasks = $this->getTaskRows( $idSubProcess ); + foreach ($newTasks as $keyLane => $val) { + if ($val['TAS_START'] === 'TRUE' and $findTask == 0) { + $findTask = 1; + $value['TASK_START'] = $val['TAS_UID']; + } + } + $fields['PROCESS_PARENT'] = $idProcess; + $fields['TAS_UID'] = $value['TASK_START']; + $oData->subProcess[$numberSubProcess] = $this->createSubProcess( $fields, $arraySubProcess ); + $numberSubProcess = $numberSubProcess + 1; + } + } + } + $oData->caseTracker = array (); + $oData->caseTrackerObject = array (); + $oData->stage = array (); + $oData->fieldCondition = array (); + $oData->event = $this->createEventMessages( $arrayMessages, $idProcess ); + $oData->triggers = array (); + $oData->caseScheduler = $this->createScheduler( $arrayScheduler, $idProcess ); + $oData->dynaformFiles = array (); + $numberTransitions = sizeof( $routeTransitions ); + if ($numberTransitions > 0) { + $routesArray = $this->createGateways( $routeTransitions, $endArray, $oData->routes, $numberRoutes, $idProcess, $taskHidden ); + $oData->routes = $routesArray; + } + + //print_r($oData);die; + //print_r($arrayMessages);die; + return $oData; } - $firstRoute = 0; - $cont = 0; - $routeChange = $routeTransitions; - foreach ($routeTransitions as $valRoutes => $value){ - $route = $value['ROUTE']; - $type = $value['ROU_TYPE']; - $countFrom = 0; - $countTo = 0; - foreach ($routeChange as $valRoutes2 => $values){ - if($value['ROUTE'] == $values['ROUTE'] and $values['TOORFROM'] == 'TO'){ - $countTo = $countTo + 1; + + /** + * This public function sort a array + * + * @param array $fields + * @return array sorted + */ + public function sortArray ($fields) + { + $aux = $fields; + foreach ($fields as $key => $row) { + $aux[$key] = $row['FROM']; } - if($value['ROUTE'] == $values['ROUTE'] and $values['TOORFROM'] == 'FROM'){ - $countFrom = $countFrom + 1; - } - } - if($type == 'PARALLEL'){ - if($countTo > $countFrom){ - $routeTransitions[$valRoutes]['ROU_TYPE'] = 'SEC-JOIN'; - } - } + array_multisort( $aux, SORT_ASC, $fields ); + return $fields; } - $routeArrayT2 = $routeTransitions; - $routeArrayT1 = $routeTransitions; - foreach ($routeArrayT1 as $valRoutes => $value){ - if($firstRoute == 0){ - $taskFirst = $value['ROUTE']; - } - if($taskFirst == $value['ROUTE']){ - if($firstRoute == 0){ - foreach ($routeArrayT2 as $valRoutes2 => $values){ - if($values['ROUTE'] == $taskFirst and $values['FROM'] == $value['FROM'] and $values['TO'] == $value['TO'] and $values['ID'] != $value['ID']){ - unset($routeArrayT2[$valRoutes2]); - $firstRoute = 1; + + /** + * This functions verify the routes and removes the routes that are repeated + * + * @param array $routeTransitions + * @param array $endArray + * @return array + */ + public function verifyRoutes ($routeTransitions, $endArray, $taskHidden) + { + $findFirst = 0; + $firstRoute = ''; + $taskTo = ''; + $taskFrom = ''; + $routeArrayT = $routeTransitions; + $findHidden = 0; + foreach ($routeTransitions as $valRoute => $value) { + $findHidden = 0; + if ($value['ROUTE'] == $firstRoute) { + if ($value['TOORFROM'] == 'TO') { + $taskFrom = $value['FROM']; + } + if ($value['TOORFROM'] == 'FROM') { + $taskTo = $value['TO']; + } + if ($taskFrom != '') { + foreach ($routeArrayT as $valRoutes => $values) { + $isEventEnd = 0; + foreach ($endArray as $endBase => $valueEnd) { + if ($valueEnd == $values['TO']) { + $isEventEnd = 1; + } + } + if ($values['ROUTE'] == $value['ROUTE'] and $values['TO'] != $value['ROUTE'] and $isEventEnd == 0 and $findHidden == 0) { + $taskFrom = $values['TO']; + } else { + if ($values['ROUTE'] == $value['ROUTE'] and $values['TO'] == $value['ROUTE'] and $isEventEnd == 0) { + foreach ($taskHidden as $idHidden => $valueHidden) { + if ($valueHidden['ID_TASK'] == $values['TO']) { + $taskFrom = $valueHidden['ID_TASK']; + $findHidden = 1; + } + } + } + } + } + $routeTransitions[$valRoute]['TO'] = $taskFrom; + $taskFrom = ''; + } + if ($taskTo != '') { + foreach ($routeArrayT as $valRoutes => $values) { + if ($values['ROUTE'] == $value['ROUTE'] and $values['FROM'] != $value['ROUTE'] and $findHidden == 0) { + $taskTo = $values['FROM']; + } + } + $routeTransitions[$valRoute]['FROM'] = $taskTo; + $taskTo = ''; + } + } else { + $firstRoute = $value['ROUTE']; + $taskToE = ''; + $taskFromE = ''; + if ($value['TOORFROM'] == 'TO') { + $taskFromE = $value['FROM']; + } + if ($value['TOORFROM'] == 'FROM') { + $taskToE = $value['TO']; + } + if ($taskFromE != '') { + $findHidden = 0; + foreach ($routeArrayT as $valRoutes => $values) { + $isEventEnd = 0; + foreach ($endArray as $endBase => $valueEnd) { + if ($valueEnd == $values['TO']) { + $isEventEnd = 1; + } + } + if ($values['ROUTE'] == $value['ROUTE'] and $values['TO'] != $value['ROUTE'] and $isEventEnd == 0 and $findHidden == 0) { + $taskFromE = $values['TO']; + } else { + if ($values['ROUTE'] == $value['ROUTE'] and $values['TO'] == $value['ROUTE'] and $isEventEnd == 0) { + foreach ($taskHidden as $idHidden => $valueHidden) { + if ($valueHidden['ID_TASK'] == $values['TO']) { + $taskFromE = $valueHidden['ID_TASK']; + $findHidden = 1; + } + } + } + } + } + $routeTransitions[$valRoute]['TO'] = $taskFromE; + $taskFromE = ''; + } + if ($taskToE != '') { + foreach ($routeArrayT as $valRoutes => $values) { + if ($values['ROUTE'] == $value['ROUTE'] and $values['FROM'] != $value['ROUTE'] and $findHidden == 0) { + $taskToE = $values['FROM']; + } + } + $routeTransitions[$valRoute]['FROM'] = $taskToE; + $taskToE = ''; + } } - } } - } - else{ $firstRoute = 0; - } - } - return $routeArrayT2; - } - - /** - * this function creates an array for the process that will be created according to the data given in an array - * @param array $fields - * @return array $process - */ - function createProcess($fields) - { $process = array(); - $process['PRO_UID'] = $fields['ID']; - $process['PRO_PARENT'] = $fields['ID']; - $process['PRO_TIME'] = 1; - $process['PRO_TIMEUNIT'] = 'DAYS'; - $process['PRO_STATUS'] = 'ACTIVE'; - $process['PRO_TYPE_DAY'] = ''; - $process['PRO_TYPE'] = 'NORMAL'; - $process['PRO_ASSIGNMENT'] = 'FALSE'; - $process['PRO_SHOW_MAP'] = 0; - $process['PRO_SHOW_MESSAGE'] = 0; - $process['PRO_SHOW_DELEGATE'] = 0; - $process['PRO_SHOW_DYNAFORM'] = 0; - $process['PRO_CATEGORY'] = ''; - $process['PRO_SUB_CATEGORY'] = ''; - $process['PRO_INDUSTRY'] = 0; - $process['PRO_UPDATE_DATE'] = date("D M j G:i:s T Y"); - $process['PRO_CREATE_DATE'] = date("D M j G:i:s T Y"); - $process['PRO_CREATE_USER'] = 00000000000000000000000000000001; - $process['PRO_HEIGHT'] = 5000; - $process['PRO_WIDTH'] = 10000; - $process['PRO_TITLE_X'] = 0; - $process['PRO_TITLE_Y'] = 0; - $process['PRO_DEBUG'] = 0; - $process['PRO_TITLE'] = $fields['NAME']; - $process['PRO_DESCRIPTION'] = $fields['DESCRIPTION']; - return $process; - } - - /** - * this function creates an array for the subProcess that will be created,according to the data given in an array - * @param array $contentNode - * @param array $arrayLanes - * @return array - */ - function createSubProcesses($contentNode,$arrayLanes) - { $activities = array(); - $numberActivities = 0; - $numberLanes = 0; - $number = 0; - $contentSubNode = $contentNode; - $numberSub = 0; - while ($contentSubNode){ - if ($contentSubNode->nodeType == XML_ELEMENT_NODE){ - $nameActivity = $contentSubNode->nodeName; - $contentActivity = $contentSubNode->firstChild; - if(strpos($nameActivity,'ActivitySet')!== false){ - $idSetActivity = str_replace('-','',$contentSubNode->getAttribute('Id')); - $arrayActivity[$number]['ID_PROCESS']= $idSetActivity; - $number = $number + 1; + $cont = 0; + $routeChange = $routeTransitions; + foreach ($routeTransitions as $valRoutes => $value) { + $route = $value['ROUTE']; + $type = $value['ROU_TYPE']; + $countFrom = 0; + $countTo = 0; + foreach ($routeChange as $valRoutes2 => $values) { + if ($value['ROUTE'] == $values['ROUTE'] and $values['TOORFROM'] == 'TO') { + $countTo = $countTo + 1; + } + if ($value['ROUTE'] == $values['ROUTE'] and $values['TOORFROM'] == 'FROM') { + $countFrom = $countFrom + 1; + } + } + if ($type == 'PARALLEL') { + if ($countTo > $countFrom) { + $routeTransitions[$valRoutes]['ROU_TYPE'] = 'SEC-JOIN'; + } + } } - } - $contentSubNode = $contentSubNode->nextSibling; - } - $number = 0; - $arraySubProcesses = array(); - while ($contentNode){ - if ($contentNode->nodeType == XML_ELEMENT_NODE){ - $isSubProcess = 0; - $nameActivity = $contentNode->nodeName; - $contentActivity = $contentNode->firstChild; - $idSetActivity = 0; - if(strpos($nameActivity,'ActivitySet')!== false){ - $idSetActivity = str_replace('-','',$contentNode->getAttribute('Id')); - if($idSetActivity !== 0){ - $isSubProcess = 1; - } - $nameSetActivity = $contentNode->getAttribute('Name'); - $contentChild = $contentNode->firstChild; - $process['ID'] = $idSetActivity; - $process['NAME'] = $nameSetActivity; - $process['DESCRIPTION'] = ''; - $subProcess->process = $this->createProcess($process); - $activities[$number]['ID_PROCESS']= $idSetActivity ; - while ($contentChild){ - if ($contentChild->nodeType == XML_ELEMENT_NODE){ - - $nameChild = $contentChild->nodeName; - $contentFirst = $contentChild->firstChild; - if(strpos($nameChild,'Activities')!== false){ - $arrayActivities = $this->createActivities($contentFirst,$idSetActivity,$arrayActivity); - $subProcess->tasks = $arrayActivities['TASKS']; - $startArray = $arrayActivities['START']; - $endArray = $arrayActivities['END']; - $arrayRoutes = $arrayActivities['ROUTES']; - $arrayScheduler = $arrayActivities['SCHEDULER']; - $arrayMessages = $arrayActivities['MESSAGES']; - } - - if(strpos($nameChild,'Transitions')!== false){ - $transitions = $this->createTransitions($contentFirst,$subProcess->tasks,$arrayRoutes,$endArray,$startArray,$idSetActivity,$arrayScheduler,$arrayMessages); - $subProcess->routes = $transitions['ROUTES']; - $subProcess->tasks = $transitions['TASKS']; - $routeTransitions = $transitions['TRANSITIONS']; - $numberRoutes = $transitions['NUMBER']; - $arrayMessages = $transitions['MESSAGES']; - } + $routeArrayT2 = $routeTransitions; + $routeArrayT1 = $routeTransitions; + foreach ($routeArrayT1 as $valRoutes => $value) { + if ($firstRoute == 0) { + $taskFirst = $value['ROUTE']; } - $contentChild = $contentChild->nextSibling; - } - - $values = $subProcess; - if($isSubProcess == 1){ - $arraySubProcesses[$numberSub]['ID_PROCESS']=$idSetActivity ; - $arraySubProcesses[$numberSub]['TASKS'] =$subProcess->tasks; - $numberSub = $numberSub+1; - } - $activities[$number]['TASK_START']= $startArray[0]['ID_TASK']; - $number = $number + 1; - $subProcess->lanes = array(); - $numberLanes = 0; - foreach($arrayLanes as $key => $value) { - if($value['PRO_UID'] ==$idSetActivity){ - $subProcess->lanes[$numberLanes] = $value; - $numberLanes = $numberLanes + 1; - } - } - $subProcess->inputs = array(); - $subProcess->outputs = array(); - $subProcess->dynaforms = array(); - $subProcess->steps = array(); - $subProcess->triggers = array(); - $subProcess->taskusers = array(); - $subProcess->groupwfs = $this->getGroupwfRows($subProcess->taskusers ); - $subProcess->steptriggers = array(); - $subProcess->dbconnections = array(); - $subProcess->reportTables = array(); - $subProcess->reportTablesVars = array(); - $subProcess->stepSupervisor = array(); - $subProcess->objectPermissions = array(); - $subProcess->subProcess = array(); - $subProcess->caseTracker = array(); - $subProcess->caseTrackerObject = array(); - $subProcess->stage = array(); - $subProcess->fieldCondition = array(); - $subProcess->event = array(); - $subProcess->caseScheduler = array(); - $subProcess->dynaformFiles = array(); - $numberTransitions = sizeof($routeTransitions); - if($numberTransitions > 0){ - $routesArray = $this->createGateways($routeTransitions,$endArray,$subProcess->routes,$numberRoutes,$idProcess,''); - $subProcess->routes = $routesArray; - } - $numberSubProcess = 0; - foreach($subProcess->tasks as $key => $value) { - if($value['TAS_TYPE'] === 'SUBPROCESS'){ - $fields['TASK_PARENT'] = $value['TAS_UID']; - $idSubProcess = $value['TAS_UID']; - $newTasks = $this->getTaskRows($idSubProcess); - - $findTask = 0; - foreach ($newTasks as $keyLane => $val ) { - if($val['TAS_START']==='TRUE' and $findTask == 0){ - $findTask = 1; - $value['TASK_START']=$val['TAS_UID']; - } - } - $fields['PROCESS_PARENT'] = $idSetActivity; - $fields['TAS_UID'] = $value['TAS_UID']; - $subProcess->subProcess[$numberSubProcess]= $this->createSubProcess($fields,$arrayActivity); - $numberSubProcess = $numberSubProcess + 1; - } - } - $this->createSubProcessFromDataXpdl($subProcess,$subProcess->tasks); - } - } - $contentNode = $contentNode->nextSibling; - } - $arrayActivities['SUBPROCESSES'] = $arraySubProcesses; - $arrayActivities['SUB_PROCESS'] = $activities; - return $arrayActivities; - } - - /** - * This function creates an array for the task that will be created according to the data given in an array - * @param array $fields - * @return array $task - */ - function createTask($fields) - { - $task = array(); - $task['PRO_UID'] = $fields['ID_PROCESS']; - $task['TAS_UID'] = $fields['ID_TASK']; - $task['TAS_TYPE'] = $fields['TASK_TYPE']; - $task['TAS_DURATION'] = 1; - $task['TAS_DELAY_TYPE'] =''; - $task['TAS_TEMPORIZER'] = 0; - $task['TAS_TYPE_DAY'] ='' ; - $task['TAS_TIMEUNIT'] = 'DAYS'; - $task['TAS_ALERT'] = 'FALSE'; - $task['TAS_PRIORITY_VARIABLE'] = '@@SYS_CASE_PRIORITY'; - $task['TAS_ASSIGN_TYPE'] = 'BALANCED'; - $task['TAS_ASSIGN_VARIABLE'] = '@@SYS_NEXT_USER_TO_BE_ASSIGNED'; - $task['TAS_ASSIGN_LOCATION'] = 'FALSE'; - $task['TAS_ASSIGN_LOCATION_ADHOC']= 'FALSE'; - $task['TAS_TRANSFER_FLY'] = 'FALSE'; - $task['TAS_LAST_ASSIGNED'] = '00000000000000000000000000000001'; - $task['TAS_USER'] = '0'; - $task['TAS_CAN_UPLOAD'] = 'FALSE'; - $task['TAS_VIEW_UPLOAD'] = 'FALSE'; - $task['TAS_VIEW_ADDITIONAL_DOCUMENTATION']= 'FALSE'; - $task['TAS_CAN_CANCEL'] = 'FALSE'; - $task['TAS_OWNER_APP'] = 'FALSE'; - $task['STG_UID'] = ''; - $task['TAS_CAN_PAUSE'] = 'FALSE'; - $task['TAS_CAN_SEND_MESSAGE'] = 'TRUE'; - $task['TAS_CAN_DELETE_DOCS'] = 'FALSE'; - $task['TAS_SELF_SERVICE'] = 'FALSE'; - $task['TAS_START'] = 'FALSE'; - $task['TAS_TO_LAST_USER'] = 'FALSE'; - $task['TAS_SEND_LAST_EMAIL'] = 'FALSE'; - $task['TAS_DERIVATION'] = 'NORMAL'; - $task['TAS_POSX'] = $fields['X']; - $task['TAS_POSY'] = $fields['Y']; - $task['TAS_COLOR'] = ''; - $task['TAS_DEF_MESSAGE'] = ''; - $task['TAS_DEF_PROC_CODE'] = ''; - $task['TAS_DEF_DESCRIPTION'] = ''; - $task['TAS_TITLE'] = $fields['TAS_TITLE']; - $task['TAS_DESCRIPTION'] = $fields['DESCRIPTION']; - $task['TAS_DEF_TITLE'] = ''; - return $task; - } - - function createDataTask($fields) - { - $task = array(); - $task['PRO_UID'] = $fields['ID_PROCESS']; - $task['TAS_UID'] = $fields['ID_TASK']; - $task['TAS_TYPE'] = $fields['TAS_TYPE']; - $task['TAS_DURATION'] = 1; - $task['TAS_DELAY_TYPE'] =''; - $task['TAS_TEMPORIZER'] = 0; - $task['TAS_TYPE_DAY'] ='' ; - $task['TAS_TIMEUNIT'] = 'DAYS'; - $task['TAS_ALERT'] = 'FALSE'; - $task['TAS_PRIORITY_VARIABLE'] = '@@SYS_CASE_PRIORITY'; - $task['TAS_ASSIGN_TYPE'] = 'BALANCED'; - $task['TAS_ASSIGN_VARIABLE'] = '@@SYS_NEXT_USER_TO_BE_ASSIGNED'; - $task['TAS_MI_INSTANCE_VARIABLE'] = '@@SYS_VAR_TOTAL_INSTANCE'; - $task['TAS_MI_COMPLETE_VARIABLE'] = '@@SYS_VAR_TOTAL_INSTANCES_COMPLETE'; - $task['TAS_ASSIGN_LOCATION'] = 'FALSE'; - $task['TAS_ASSIGN_LOCATION_ADHOC']= 'FALSE'; - $task['TAS_TRANSFER_FLY'] = 'FALSE'; - $task['TAS_LAST_ASSIGNED'] = '00000000000000000000000000000001'; - $task['TAS_USER'] = '0'; - $task['TAS_CAN_UPLOAD'] = 'FALSE'; - $task['TAS_VIEW_UPLOAD'] = 'FALSE'; - $task['TAS_VIEW_ADDITIONAL_DOCUMENTATION']= 'FALSE'; - $task['TAS_CAN_CANCEL'] = 'FALSE'; - $task['TAS_OWNER_APP'] = 'FALSE'; - $task['STG_UID'] = ''; - $task['TAS_CAN_PAUSE'] = 'FALSE'; - $task['TAS_CAN_SEND_MESSAGE'] = 'TRUE'; - $task['TAS_CAN_DELETE_DOCS'] = 'FALSE'; - $task['TAS_SELF_SERVICE'] = 'FALSE'; - $task['TAS_START'] = $fields['START']; - $task['TAS_TO_LAST_USER'] = 'FALSE'; - $task['TAS_SEND_LAST_EMAIL'] = 'FALSE'; - $task['TAS_DERIVATION'] = 'NORMAL'; - $task['TAS_POSX'] = $fields['X']; - $task['TAS_POSY'] = $fields['Y']; - $task['TAS_COLOR'] = ''; - $task['TAS_DEF_MESSAGE'] = ''; - $task['TAS_DEF_PROC_CODE'] = ''; - $task['TAS_DEF_DESCRIPTION'] = ''; - $task['TAS_TITLE'] = $fields['TAS_TITLE']; - $task['TAS_DESCRIPTION'] = $fields['DESCRIPTION']; - $task['TAS_DEF_TITLE'] = ''; - return $task; - } -/** - * This function creates an array for the route that will be created according to the data given in an array - * @param array $fields - * @return array $route - */ - function createRoute($fields) - { - $route = array(); - $route['ROU_UID'] = $fields['ROU_UID']; - $route['ROU_PARENT'] = 0; - $route['PRO_UID'] = $fields['ID_PROCESS']; - $route['TAS_UID'] = $fields['FROM']; - $route['ROU_NEXT_TASK'] = $fields['TO']; - $route['ROU_CASE'] = 1; - $route['ROU_TYPE'] = 'SEQUENTIAL'; - $route['ROU_CONDITION'] = '' ; - $route['ROU_TO_LAST_USER'] = 'FALSE'; - $route['ROU_OPTIONAL'] = 'FALSE'; - $route['ROU_SEND_EMAIL'] = 'TRUE'; - $route['ROU_SOURCEANCHOR'] = 1; - $route['ROU_TARGETANCHOR'] = 0; - return $route; - } - - /** - * This function creates an array for the subProcess that will be created according to the data given in an array - * @param array $fields - * @return array $route - */ - function createSubProcess($fields) - { - $subProcess = array(); - $subProcess['SP_UID'] = $fields['TAS_UID']; - $subProcess['PRO_UID'] = $fields['TASK_PARENT']; - $subProcess['TAS_UID'] = $fields['TAS_UID']; - $subProcess['PRO_PARENT'] = $fields['PROCESS_PARENT']; - $subProcess['TAS_PARENT'] = $fields['TASK_PARENT']; - $subProcess['SP_TYPE'] = 'SIMPLE'; - $subProcess['SP_SYNCHRONOUS'] = 0; - $subProcess['SP_SYNCHRONOUS_TYPE'] = 'ALL' ; - $subProcess['SP_SYNCHRONOUS_WAIT'] = 0; - $subProcess['SP_VARIABLES_OUT'] = 'a:1:{s:0:"";s:0:"";}'; - $subProcess['SP_VARIABLES_IN'] = 'a:1:{s:0:"";s:0:"";}'; - $subProcess['SP_GRID_IN'] = ''; - return $subProcess; - } - - /** - * This function creates an array for the routes that are not sequential that will be created according to the data given in an array - * @param array $routeTransitions - * @param array $endArray - * @param array $dataRoutes - * @param array $numberRoutes - * @param string $idProcess - * @return array $dataRoutes - */ - function createGateways($routeTransitions,$endArray,$dataRoutes,$numberRoutes,$idProcess,$taskHidden) - { - $valueCase = ''; - $value = 1; - $valueC = 1; - $aux = $routeTransitions; - foreach ($routeTransitions as $key => $row) { - $aux[$key] = $row['ROUTE']; - } - array_multisort($aux,SORT_ASC,$routeTransitions); - $routeArray = $this->verifyRoutes($routeTransitions,$endArray,$taskHidden); - $routeArray = $this->sortArray($routeArray); - foreach($routeArray as $valRoutes => $value){ - $isEventEnd = 0; - foreach ($endArray as $endBase => $valueEnd){ - if($valueEnd['ID_TASK']==$value['TO']){ - $isEventEnd = 1; - } - } - $dataRoutes[$numberRoutes]= array(); - $dataRoutes[$numberRoutes]['ROU_UID'] = $value['ID']; - $dataRoutes[$numberRoutes]['ROU_PARENT'] = 0; - $dataRoutes[$numberRoutes]['PRO_UID'] = $idProcess; - $dataRoutes[$numberRoutes]['TAS_UID'] = $value['FROM']; - - if($isEventEnd == 0){ - $dataRoutes[$numberRoutes]['ROU_NEXT_TASK'] = $value['TO']; - } - else{ - $dataRoutes[$numberRoutes]['ROU_NEXT_TASK'] = '-1'; - } - if($valueCase == $value['FROM']){ - $valueC = $valueC + 1; - } - else{ - $valueC = 1; - $valueCase = $value['FROM']; - } - if($valueCase == ''){ - $valueC = 1; - $valueCase = $value['FROM']; - } - $dataRoutes[$numberRoutes]['ROU_CASE'] = $valueC; - $dataRoutes[$numberRoutes]['ROU_TYPE'] = $value['ROU_TYPE']; - if($value['ROU_TYPE'] ==='DISCRIMINATOR'){ - $dataRoutes[$numberRoutes]['ROU_CONDITION'] = $value['CONDITION_DIS']; - $dataRoutes[$numberRoutes]['ROU_OPTIONAL'] = $value['TYPE_DIS']; - } - if($value['ROU_TYPE'] !=='DISCRIMINATOR'){ - $dataRoutes[$numberRoutes]['ROU_CONDITION'] = $value['CONDITION']; - $dataRoutes[$numberRoutes]['ROU_OPTIONAL'] = 'FALSE'; - } - $dataRoutes[$numberRoutes]['ROU_TO_LAST_USER'] = 'FALSE'; - $dataRoutes[$numberRoutes]['ROU_SEND_EMAIL'] = 'TRUE'; - $dataRoutes[$numberRoutes]['ROU_SOURCEANCHOR'] = 1; - $dataRoutes[$numberRoutes]['ROU_TARGETANCHOR'] = 0; - $numberRoutes = $numberRoutes + 1; - } - return $dataRoutes; - } - - /** - * This function creates an array for the lane that will be created according to the data given in an array - * @param array $lanes - * @return array $lane - */ - function createLanesPM($array,$idProcess) - { - $arrayLanes = array(); - $field = array(); - foreach ($array as $key=> $value){ - $field['ID_LANE'] = $value['0']; - $field['ID_PROCESS'] = $idProcess; - $field['X'] = $value['2']; - $field['Y'] = $value['3']; - $field['WIDTH'] = $value['4']; - $field['HEIGHT'] = $value['5']; - $field['TEXT'] = $value['6']; - $arrayLanes[]= $this->createLanes($field); - } - return $arrayLanes; - } - -/** - * This function creates an array for the lane that will be created according to the data given in an array - * @param array $lanes - * @return array $lane - */ - function createLanes($lanes) - { - $lane = array(); - $lane['SWI_UID'] = $lanes['ID_LANE']; - $lane['PRO_UID'] = $lanes['ID_PROCESS']; - $lane['SWI_TYPE'] = 'TEXT'; - $lane['SWI_X'] = $lanes['X']; - $lane['SWI_Y'] = $lanes['Y']; - $lane['SWI_TEXT'] = $lanes['TEXT']; - $lane['SWI_WIDTH'] = $lanes['WIDTH']; - $lane['SWI_HEIGHT']= $lanes['HEIGHT']; - return $lane; - } - - /** - * This function creates an array for the lane that will be created according to the data given in an array - * @param array $lanes - * @return array $lane - */ - function createLanesNewPM($array) - { - $arrayLanes = array(); - $field = array(); - foreach ($array as $key=> $value){ - if($value['SWI_TYPE'] == 'TEXT') - { - $field['0'] = $value['SWI_UID']; - $field['1'] = $value['SWI_TEXT']; - $field['2'] = $value['SWI_X']; - $field['3'] = $value['SWI_Y']; - $field['4'] = $value['SWI_WIDTH']; - $field['5'] = $value['SWI_HEIGHT']; - $field['6'] = $value['SWI_NEXT_UID']; - $arrayLanes[]= $field; - } - } - return $arrayLanes; - } - - /** - * This function creates activities according the content of the node - * @param object $contentNode - * @param string $idProcess - * @param string $ActivitySet - * @return array $result - */ - function createActivities($contentNode,$idProcess,$activitySet) - { - $result = array(); - $numberTasks = 0; - $posRoutes = 0; - $posEnd = 0; - $posStart = 0; - $arrayRoutes = array(); - $endArray = array(); - $endArray = array(); - $startArray = array(); - $arrayScheduler = array(); - $scheduler = array(); - $message = array(); - $arrayMessages = array(); - while ($contentNode){ - if ($contentNode->nodeType == XML_ELEMENT_NODE){ - $nameActivity = $contentNode->nodeName; - $contentActivity = $contentNode->firstChild; - if(strpos($nameActivity,'Activity')!== false){ - $idActivity = $contentNode->getAttribute('Id'); - $idActivity = trim(str_replace('-','',$idActivity)); - $name = htmlentities($contentNode->getAttribute('Name')); - $result = $this->createActivity($contentActivity); - $result['ID_PROCESS']= $idProcess; - $result['ID_TASK'] = $idActivity; - $result['TAS_TITLE'] = $name; - $result['TASK_TYPE'] = 'NORMAL'; - foreach ($activitySet as $key => $value) { - if($value['ID_PROCESS'] ==$idActivity){ - $result['TASK_TYPE']= 'SUBPROCESS'; - } - } - if($result['EVENT'] =='' and $result['ROUTE'] ==''){ - $arrayTasks[$numberTasks]= $this->createTask($result); - $numberTasks = $numberTasks +1; - } - else{ - if($result['EVENT'] !='' and $result['TRIGGER']== 'None'){ - if($result['EVENT'] =='END'){ - $endArray[$posEnd] = $result; - $posEnd = $posEnd+1; - } - if($result['EVENT'] =='START'){ - $startArray[$posStart] = $result; - $posStart= $posStart+1; - } - } - else{ - if($result['TRIGGER']== 'Timer'){ - $scheduler['ID'] = $idActivity; - $scheduler['NAME'] = $name; - if($result['TIME'] == '' or $result['TIME'] == Null){ - $scheduler['TIME'] = date("D M j G:i:s T Y"); - } - else{ - $scheduler['TIME'] = $result['TIME']; - } - $scheduler['TYPE_TIME']= $result['TYPE_TIME']; - $arrayScheduler[] = $scheduler; - } - if($result['TRIGGER']== 'Message'){ - $message['ID'] = $idActivity; - $message['NAME'] = $name; - $message['TYPE_MESSAGE'] = $result['MESSAGE']; - $arrayMessages[] = $message; - } - } - if($result['ROUTE'] !=''){ - $position = $this->findCoordinates($contentActivity); - $arrayRoutes[$posRoutes]['ID'] = $idActivity; - $arrayRoutes[$posRoutes]['ROUTE'] = $result['ROUTE']; - $arrayRoutes[$posRoutes]['TYPE_DIS'] = $result['TYPE_DISCRIMINATOR']; - $arrayRoutes[$posRoutes]['CONDITION_DIS'] = $result['CONDITION_DISCRIMINATOR']; - $arrayRoutes[$posRoutes]['X'] = $position['X']; - $arrayRoutes[$posRoutes]['Y'] = $position['Y']; - $posRoutes = $posRoutes + 1; - } - } - } - } - $contentNode = $contentNode->nextSibling; - } - $result['TASKS'] = $arrayTasks; - $result['END'] = $endArray; - $result['START'] = $startArray; - $result['ROUTES'] = $arrayRoutes; - $result['SCHEDULER']= $arrayScheduler; - $result['MESSAGES'] = $arrayMessages; - return $result; - } - - -/** - * This function creates the scheduler - * @param array $fields - * @return array $result - */ - function createEventMessages($fields,$idProcess) - { - $result = array(); - $event = array(); - $example = new Derivation(); - foreach($fields as $key => $value){ - $oEvent = new Event(); - $event['EVN_UID'] = $value['ID']; - $event['PRO_UID'] = $idProcess; - $event['EVN_RELATED_TO'] = 'SINGLE'; - $event['TAS_UID'] = $value['ID_TASK']; - $event['EVN_TAS_ESTIMATED_DURATION'] = '1'; - $event['EVN_WHEN_OCCURS'] = 'AFTER'; - $event['EVN_STATUS'] = 'ACTIVE'; - $event['EVN_WHEN'] = 1; - $event['EVN_MAX_ATTEMPTS'] = 3; - $event['EVN_ACTION'] = 'SEND_MESSAGE'; - $event['EVN_DESCRIPTION'] = $value['NAME']; - $event['EVN_WHEN_OCCURS'] = 'AFTER_TIME'; - $event['EVN_ACTION_PARAMETERS'] = array( - 'SUBJECT' => 'subject', - 'TO' => array('0'=>'usr|-1','1'=>'ext|'), - 'CC' => array(), - 'BCC' => array(), - 'TEMPLATE' => 'alert_message.html' - ); - $result[] = $event; - } - return $result; - } - - /** - * This function creates the scheduler - * @param array $fields - * @return array $result - */ - function createScheduler($fields,$idProcess) - { - $result = array(); - $example = new Derivation(); - foreach($fields as $key => $value){ - if($value['TYPE_TIME'] == 'TimeDate'){ - //there is a scheduler one time only - $value['OPTION']= 4; - $result[]= $this->createArrayScheduler($value,$idProcess); - } - if($value['TYPE_TIME'] == 'TimeCycle'){ - //we calculated if is daily or monthly, etc - $time = $this->calculateTimeScheduler($value['TIME']); - /*$value['OPTION']= $time['OPTION']; - $value['TIME'] = $time['TIME'];*/ - $value['OPTION']= '1'; - } - } - //PRINT_r($result); - return $result; - } - -/** - * This function creates the scheduler - * @param array $fields - * @return array $result - */ - function calculateTimeScheduler($time) - { - $result = array(); - // The split function has been DEPRECATED as of PHP 5.3.0. - // $result = split(' ',$time); - $result = explode(' ', $time); - //print_r($result); - return $result; - } - - /** - * This function creates the array scheduler - * @param string $time - * @param string $type (TimeCycle or TimeDate) - * @return array $result - */ - function createArrayScheduler($fields,$idProcess) - { - $result['SCH_UID'] = $fields['ID']; - $result['SCH_DEL_USER_NAME'] = ''; - $result['SCH_DEL_USER_PASS'] = ''; - $result['SCH_DEL_USER_UID'] = ''; - $result['SCH_NAME'] = $fields['NAME']; - $result['PRO_UID'] = $idProcess; - $result['TAS_UID'] = $fields['ID_TASK']; - $result['SCH_TIME_NEXT_RUN'] = $fields['TIME']; - $result['SCH_LAST_RUN_TIME'] = null; - $result['SCH_STATE'] = 'ACTIVE'; - $result['SCH_LAST_STATE'] = 'CREATED'; - $result['USR_UID'] = '00000000000000000000000000000001'; - $result['SCH_OPTION'] = $fields['OPTION']; - $result['SCH_START_TIME'] = $fields['TIME']; - $result['SCH_START_DATE'] = $fields['TIME']; - $result['SCH_DAYS_PERFORM_TASK'] = ''; - $result['SCH_EVERY_DAYS'] = '0'; - $result['SCH_WEEK_DAYS'] = '0|0|0|0|0|0|0'; - $result['SCH_START_DAY'] = ''; - $result['SCH_MONTHS'] = '0|0|0|0|0|0|0|0|0|0|0|0'; - $result['SCH_END_DATE'] = $fields['TIME']; - $result['SCH_REPEAT_EVERY'] = ''; - $result['SCH_REPEAT_UNTIL'] = ''; - $result['SCH_REPEAT_STOP_IF_RUNNING'] = ''; - return $result; - } - - /** - * This function creates transitions according the content of the node - * @param object $contentNode - * @param array $dataTask - * @param array $arrayRoutes - * @param array $endArray - * @param array $startArray - * @param string $idProcess - * @return array $result - */ - - function createTransitions($contentNode,$dataTasks,$arrayRoutes,$endArray,$startArray,$idProcess,$schedulerArray,$messages) - { - $numberRoutes = 0; - $posT = 0; - $output = ''; - $routeTransitions = array(); - $taskHidden = array(); - $countHidden = 1; - $dataRoutes = array(); - $newFrom = 0; - $isScheduler = 0; - $isMessage = 0; - while ($contentNode){ - $isEnd = 0; - $isStart = 0; - $tasks = $dataTasks; - if ($contentNode->nodeType == XML_ELEMENT_NODE){ - $nameTransition = $contentNode->nodeName; - $contentTransition = $contentNode->firstChild; - if(strpos($nameTransition,'Transition')!== false){ - $idTransition = $contentNode->getAttribute('Id'); - $idTransition = trim(str_replace('-','',$idTransition)); - $from = trim(str_replace('-','',$contentNode->getAttribute('From'))); - $to = trim(str_replace('-','',$contentNode->getAttribute('To'))); - $routes['ROU_UID'] = $idTransition; - $routes['ID_PROCESS']= $idProcess; - $routes['FROM'] = $from; - $routes['TO'] = $to; - $isScheduler = 0; - $isMessage = 0; - foreach ($startArray as $startBase => $value){ - if($value['ID_TASK']==$from){ - foreach($tasks as $tasksValue=> $taskId){ - if($to==$taskId['TAS_UID']){ - $taskId['TAS_START']='TRUE'; - $dataTasks[$tasksValue]['TAS_START']='TRUE'; - $isStart = 1; - } - } - } - } - foreach ($schedulerArray as $startBase => $value){ - if($value['ID']==$from){ - $isScheduler = 1; - $schedulerArray[$startBase]['ID_TASK'] = $to; - foreach($tasks as $tasksValue=> $taskId){ - if($to==$taskId['TAS_UID']){ - $taskId['TAS_START']='TRUE'; - $dataTasks[$tasksValue]['TAS_START']='TRUE'; - $isStart = 1; - } - } - } - } - foreach ($messages as $startBase => $value){ - if($value['ID']==$from){ - $isMessage = 1; - $messages[$startBase]['ID_TASK'] = $to; - } - if($value['ID']==$to){ - $isMessage = 1; - $messages[$startBase]['ID_TASK'] = $from; - } - } - $sequencial = 0; - $findRoute = 0; - foreach ($arrayRoutes as $routeBase => $value){ - //change for task hidden - if($value['ID']==$from){ - if($findRoute == 0){ - $typeT = 'FROM'; - $valueRoute = $value['ID']; - $typeRoute = $value['ROUTE']; - $sequencial = 1; - $conditionD = $value['CONDITION_DIS']; - $typeD = $value['TYPE_DIS']; - $findRoute = 1; - } - else{ - $contendHidden = $contentTransition; - $fieldsXY = $this->findCoordinatesTransition($to,$arrayRoutes); - $hidden['ID_TASK'] = G::generateUniqueID(); - $hidden['ID_PROCESS'] = $idProcess; - $hidden['TAS_TITLE'] = ''; - $hidden['TASK_TYPE'] = 'HIDDEN'; - $hidden['DESCRIPTION'] = $countHidden; - $hidden['X'] = $fieldsXY['X']; - $hidden['Y'] = $fieldsXY['Y']; - $taskHidden[] = $hidden; - $dataTasks[] = $this->createTask($hidden); - $countHidden = $countHidden + 1; - $routeTransitions[$posT]['ID'] = G::generateUniqueID(); - $routeTransitions[$posT]['ROUTE'] = $from; - $routeTransitions[$posT]['FROM'] = $from; - $routeTransitions[$posT]['TO'] = $hidden['ID_TASK']; - $routeTransitions[$posT]['TOORFROM'] = 'FROM'; - $routeTransitions[$posT]['ROU_TYPE'] = $value['ROUTE']; - $routeTransitions[$posT]['CONDITION'] = $output; - $routeTransitions[$posT]['CONDITION_DIS'] = $conditionD; - $routeTransitions[$posT]['TYPE_DIS'] = $typeD; - $output = ''; - $posT = $posT + 1; - $from = $hidden['ID_TASK']; - } - } - if($value['ID']==$to){ - if($findRoute == 0){ - $typeT = 'TO'; - $valueRoute = $value['ID']; - $typeRoute = $value['ROUTE']; - $sequencial = 1; - $conditionD = $value['CONDITION_DIS']; - $typeD = $value['TYPE_DIS']; - $findRoute = 1; - } - else{ - - $contendHidden = $contentTransition; - $fieldsXY = $this->findCoordinatesTransition($to,$arrayRoutes); - $hidden['ID_TASK'] = G::generateUniqueID(); - $hidden['ID_PROCESS'] = $idProcess; - $hidden['TAS_TITLE'] = ''; - $hidden['TASK_TYPE'] = 'HIDDEN'; - $hidden['DESCRIPTION'] = $countHidden; - $hidden['X'] = $fieldsXY['X']; - $hidden['Y'] = $fieldsXY['Y']; - $taskHidden[] = $hidden; - $dataTasks[] = $this->createTask($hidden); - $countHidden = $countHidden + 1; - $routeTransitions[$posT]['ID'] = G::generateUniqueID(); - $routeTransitions[$posT]['ROUTE'] = $from; - $routeTransitions[$posT]['FROM'] = $from; - $routeTransitions[$posT]['TO'] = $hidden['ID_TASK']; - $routeTransitions[$posT]['TOORFROM'] = 'TO'; - $routeTransitions[$posT]['ROU_TYPE'] = $typeRoute; - $routeTransitions[$posT]['CONDITION'] = $output; - $routeTransitions[$posT]['CONDITION_DIS'] = $conditionD; - $routeTransitions[$posT]['TYPE_DIS'] = $typeD; - $output = ''; - $posT = $posT + 1; - $from = $hidden['ID_TASK']; - $conditionD = $value['CONDITION_DIS']; - $typeRoute = $value['ROUTE']; - $typeT = 'TO'; - $valueRoute = $value['ID']; - $sequencial = 1; - $conditionD = $value['CONDITION_DIS']; - $typeD = $value['TYPE_DIS']; - } - } - } - if($sequencial == 0){ - foreach ($endArray as $endBase => $value){ - if($value['ID_TASK']==$to){ - foreach($tasks as $tasksValue=> $taskId){ - if($from==$taskId['TAS_UID']){ - $routes['TO'] = '-1'; - $dataRoutes[$numberRoutes]= $this->createRoute($routes); - $numberRoutes = $numberRoutes +1; - $isEnd = 1; - } - } - } - } - } - if($sequencial == 1){ - while ($contentTransition) { - $nameCondition = $contentTransition->nodeName; - $contentCondition = $contentTransition->firstChild; - if(strpos($nameCondition,'Condition')!== false){ - while ($contentCondition) { - $nameExpression = $contentCondition->nodeName; - $contentCondition1 = ''; - if(strpos($nameExpression,'Expression')!== false){ - $contentCondition1 = $contentCondition->firstChild; - if($contentCondition1 != array()){ - $output = $contentCondition1->nodeValue; + if ($taskFirst == $value['ROUTE']) { + if ($firstRoute == 0) { + foreach ($routeArrayT2 as $valRoutes2 => $values) { + if ($values['ROUTE'] == $taskFirst and $values['FROM'] == $value['FROM'] and $values['TO'] == $value['TO'] and $values['ID'] != $value['ID']) { + unset( $routeArrayT2[$valRoutes2] ); + $firstRoute = 1; + } } - } - $contentCondition = $contentCondition->nextSibling; } - } - $contentTransition = $contentTransition->nextSibling; + } else { + $firstRoute = 0; } - $routeTransitions[$posT]['ID'] = $idTransition; - $routeTransitions[$posT]['ROUTE'] = $valueRoute; - $routeTransitions[$posT]['FROM'] = $from; - $routeTransitions[$posT]['TO'] = $to; - $routeTransitions[$posT]['TOORFROM'] = $typeT; - $routeTransitions[$posT]['ROU_TYPE'] = $typeRoute; - $routeTransitions[$posT]['CONDITION'] = $output; - $routeTransitions[$posT]['CONDITION_DIS'] = $conditionD; - $routeTransitions[$posT]['TYPE_DIS'] = $typeD; - $output = ''; - $posT = $posT + 1; - $sequencial = 1; - } - if($isEnd==0 and $isStart == 0 and $sequencial == 0 and $isScheduler == 0 and $isMessage == 0){ - $dataRoutes[$numberRoutes]= $this->createRoute($routes); - $numberRoutes = $numberRoutes +1; - } } - } - $contentNode = $contentNode->nextSibling; + return $routeArrayT2; } - $routes = $routeTransitions; - foreach($routeTransitions as $key => $id){ - $findTo = 0; - $findFrom = 0; - foreach ($dataTasks as $keyHidden => $value){ - if($id['FROM']== $value['TAS_UID']){ - $findFrom= 1; - } - if($id['TO']== $value['TAS_UID']){ - $findTo = 1; - } - } - if($findTo == 0){ - foreach($routes as $keyR => $idR){ - if($id['TO'] == $idR['ROUTE']){ - $routeTransitions[$key]['ROU_TYPE'] = $idR['ROU_TYPE']; - $routeTransitions[$key]['ROUTE'] = $id['TO']; - $routeTransitions[$key]['TOORFROM'] = 'TO'; - } - } - } - if($findFrom == 0){ - foreach($routes as $keyR => $idR){ - if($id['FROM'] == $idR['ROUTE']){ - $routeTransitions[$key]['ROU_TYPE'] = $idR['ROU_TYPE']; - $routeTransitions[$key]['ROUTE'] = $id['FROM']; - $routeTransitions[$key]['TOORFROM'] = 'FROM'; - } - } - } - } - $result['ROUTES'] = $dataRoutes; - $result['TRANSITIONS']= $routeTransitions; - $result['TASKS'] = $dataTasks; - $result['NUMBER'] = $numberRoutes; - $result['TASKHIDDEN'] = $taskHidden; - $result['SCHEDULER'] = $schedulerArray; - $result['MESSAGES'] = $messages; - return $result; - } -/** - * this function creates a array according to the data given in a node - * @param object $contentNode - * @return array - */ - function createActivity($contentNode) - { - $coordinates = array(); - $event = ''; - $typeRoute = ''; - $markerVisible = ''; - $typePM = ''; - $isRoute = 0; - $description = ''; - $isSubProcess = 0 ; - $trigger = ''; - $time = ''; - $typeTime = ''; - $isMessage = 0; - while ($contentNode) { - if ($contentNode->nodeType == XML_ELEMENT_NODE) { - $nameChild = $contentNode->nodeName; - $contentChild = $contentNode->firstChild; - if(strpos($nameChild,'Description')!== false){ - $description = $contentNode->nodeValue; - } - if(strpos($nameChild,'ExtendedAttributes')!== false){ - $result = $this->createExtended($contentChild); - } - if(strpos($nameChild,'BlockActivity')!== false){ - $isSubProcess = 1; - $idSubProcess = trim(str_replace('-','',$contentNode->getAttribute('ActivitySetId'))); - } - if(strpos($nameChild,'Event')!== false){ - while ($contentChild) { - if ($contentChild->nodeType == XML_ELEMENT_NODE) { - $nameInfo = $contentChild->nodeName; - $contentInfo = $contentChild->firstChild; - if(strpos($nameInfo,'StartEvent')!== false){ - $event = 'START'; - $trigger = $contentChild->getAttribute('Trigger'); - } - if(strpos($nameInfo,'EndEvent')!== false){ - $event = 'END'; - $trigger = $contentChild->getAttribute('Trigger'); - if($trigger == ''){ - $trigger = 'None'; - } - } - if(strpos($nameInfo,'IntermediateEvent')!== false){ - $event = 'INTERMEDIATE'; - $trigger = $contentChild->getAttribute('Trigger'); - } - } - $contentChild = $contentChild->nextSibling; - } - if($trigger != 'None'){ - if($trigger == 'Timer'){ - while ($contentInfo) { - $nameTrigger = $contentInfo->nodeName; - $contentTrigger = $contentInfo->firstChild; - if(strpos($nameTrigger,'TriggerTimer')!== false){ - $time = $contentInfo->getAttribute('TimeCycle'); - $typeTime = 'TimeCycle'; - if($time == ''){ - $time = $contentInfo->getAttribute('TimeDate'); - $typeTime = 'TimeDate'; - } - } - $contentInfo = $contentInfo->nextSibling; - } - } - if($trigger == 'Message'){ - $typeMessage = ''; - $isMessage = 1; - while ($contentInfo) { - $nameTrigger = $contentInfo->nodeName; - $contentTrigger = $contentInfo->firstChild; - if(strpos($nameTrigger,'TriggerResultMessage')!== false){ - $typeMessage = $contentInfo->getAttribute('CatchThrow'); - } - $contentInfo = $contentInfo->nextSibling; - } - } - } - } - if(strpos($nameChild,'Route')!== false){ - $typePM = ''; - $typeRoute = $contentNode->getAttribute('GatewayType'); - $markerVisible = $contentNode->getAttribute('MarkerVisible'); - if($markerVisible !=''){ - $coordinates['ROUTE'] = $markerVisible; - } - if($typeRoute !=''){ - $coordinates['ROUTE'] = $typeRoute; - } - if($typeRoute =='' and $markerVisible ==''){ - $coordinates['ROUTE'] = 'EVALUATE'; - } - switch($coordinates['ROUTE']){ - case 'AND': - $typePM = 'PARALLEL'; - break; - case 'true': - $typePM = 'EVALUATE'; - break; - case 'EVALUATE': + /** + * this public function creates an array for the process that will be created according to the data given in an array + * + * @param array $fields + * @return array $process + */ + public function createProcess ($fields) + { + $process = array (); + $process['PRO_UID'] = $fields['ID']; + $process['PRO_PARENT'] = $fields['ID']; + $process['PRO_TIME'] = 1; + $process['PRO_TIMEUNIT'] = 'DAYS'; + $process['PRO_STATUS'] = 'ACTIVE'; + $process['PRO_TYPE_DAY'] = ''; + $process['PRO_TYPE'] = 'NORMAL'; + $process['PRO_ASSIGNMENT'] = 'FALSE'; + $process['PRO_SHOW_MAP'] = 0; + $process['PRO_SHOW_MESSAGE'] = 0; + $process['PRO_SHOW_DELEGATE'] = 0; + $process['PRO_SHOW_DYNAFORM'] = 0; + $process['PRO_CATEGORY'] = ''; + $process['PRO_SUB_CATEGORY'] = ''; + $process['PRO_INDUSTRY'] = 0; + $process['PRO_UPDATE_DATE'] = date( "D M j G:i:s T Y" ); + $process['PRO_CREATE_DATE'] = date( "D M j G:i:s T Y" ); + $process['PRO_CREATE_USER'] = 00000000000000000000000000000001; + $process['PRO_HEIGHT'] = 5000; + $process['PRO_WIDTH'] = 10000; + $process['PRO_TITLE_X'] = 0; + $process['PRO_TITLE_Y'] = 0; + $process['PRO_DEBUG'] = 0; + $process['PRO_TITLE'] = $fields['NAME']; + $process['PRO_DESCRIPTION'] = $fields['DESCRIPTION']; + return $process; + } + + /** + * this public function creates an array for the subProcess that will be created,according to the data given in an array + * + * @param array $contentNode + * @param array $arrayLanes + * @return array + */ + public function createSubProcesses ($contentNode, $arrayLanes) + { + $activities = array (); + $numberActivities = 0; + $numberLanes = 0; + $number = 0; + $contentSubNode = $contentNode; + $numberSub = 0; + while ($contentSubNode) { + if ($contentSubNode->nodeType == XML_ELEMENT_NODE) { + $nameActivity = $contentSubNode->nodeName; + $contentActivity = $contentSubNode->firstChild; + if (strpos( $nameActivity, 'ActivitySet' ) !== false) { + $idSetActivity = str_replace( '-', '', $contentSubNode->getAttribute( 'Id' ) ); + $arrayActivity[$number]['ID_PROCESS'] = $idSetActivity; + $number = $number + 1; + } + } + $contentSubNode = $contentSubNode->nextSibling; + } + $number = 0; + $arraySubProcesses = array (); + while ($contentNode) { + if ($contentNode->nodeType == XML_ELEMENT_NODE) { + $isSubProcess = 0; + $nameActivity = $contentNode->nodeName; + $contentActivity = $contentNode->firstChild; + $idSetActivity = 0; + if (strpos( $nameActivity, 'ActivitySet' ) !== false) { + $idSetActivity = str_replace( '-', '', $contentNode->getAttribute( 'Id' ) ); + if ($idSetActivity !== 0) { + $isSubProcess = 1; + } + $nameSetActivity = $contentNode->getAttribute( 'Name' ); + $contentChild = $contentNode->firstChild; + $process['ID'] = $idSetActivity; + $process['NAME'] = $nameSetActivity; + $process['DESCRIPTION'] = ''; + $subProcess->process = $this->createProcess( $process ); + $activities[$number]['ID_PROCESS'] = $idSetActivity; + while ($contentChild) { + if ($contentChild->nodeType == XML_ELEMENT_NODE) { + + $nameChild = $contentChild->nodeName; + $contentFirst = $contentChild->firstChild; + if (strpos( $nameChild, 'Activities' ) !== false) { + $arrayActivities = $this->createActivities( $contentFirst, $idSetActivity, $arrayActivity ); + $subProcess->tasks = $arrayActivities['TASKS']; + $startArray = $arrayActivities['START']; + $endArray = $arrayActivities['END']; + $arrayRoutes = $arrayActivities['ROUTES']; + $arrayScheduler = $arrayActivities['SCHEDULER']; + $arrayMessages = $arrayActivities['MESSAGES']; + } + + if (strpos( $nameChild, 'Transitions' ) !== false) { + $transitions = $this->createTransitions( $contentFirst, $subProcess->tasks, $arrayRoutes, $endArray, $startArray, $idSetActivity, $arrayScheduler, $arrayMessages ); + $subProcess->routes = $transitions['ROUTES']; + $subProcess->tasks = $transitions['TASKS']; + $routeTransitions = $transitions['TRANSITIONS']; + $numberRoutes = $transitions['NUMBER']; + $arrayMessages = $transitions['MESSAGES']; + } + } + $contentChild = $contentChild->nextSibling; + } + + $values = $subProcess; + if ($isSubProcess == 1) { + $arraySubProcesses[$numberSub]['ID_PROCESS'] = $idSetActivity; + $arraySubProcesses[$numberSub]['TASKS'] = $subProcess->tasks; + $numberSub = $numberSub + 1; + } + $activities[$number]['TASK_START'] = $startArray[0]['ID_TASK']; + $number = $number + 1; + $subProcess->lanes = array (); + $numberLanes = 0; + foreach ($arrayLanes as $key => $value) { + if ($value['PRO_UID'] == $idSetActivity) { + $subProcess->lanes[$numberLanes] = $value; + $numberLanes = $numberLanes + 1; + } + } + $subProcess->inputs = array (); + $subProcess->outputs = array (); + $subProcess->dynaforms = array (); + $subProcess->steps = array (); + $subProcess->triggers = array (); + $subProcess->taskusers = array (); + $subProcess->groupwfs = $this->getGroupwfRows( $subProcess->taskusers ); + $subProcess->steptriggers = array (); + $subProcess->dbconnections = array (); + $subProcess->reportTables = array (); + $subProcess->reportTablesVars = array (); + $subProcess->stepSupervisor = array (); + $subProcess->objectPermissions = array (); + $subProcess->subProcess = array (); + $subProcess->caseTracker = array (); + $subProcess->caseTrackerObject = array (); + $subProcess->stage = array (); + $subProcess->fieldCondition = array (); + $subProcess->event = array (); + $subProcess->caseScheduler = array (); + $subProcess->dynaformFiles = array (); + $numberTransitions = sizeof( $routeTransitions ); + if ($numberTransitions > 0) { + $routesArray = $this->createGateways( $routeTransitions, $endArray, $subProcess->routes, $numberRoutes, $idProcess, '' ); + $subProcess->routes = $routesArray; + } + $numberSubProcess = 0; + foreach ($subProcess->tasks as $key => $value) { + if ($value['TAS_TYPE'] === 'SUBPROCESS') { + $fields['TASK_PARENT'] = $value['TAS_UID']; + $idSubProcess = $value['TAS_UID']; + $newTasks = $this->getTaskRows( $idSubProcess ); + + $findTask = 0; + foreach ($newTasks as $keyLane => $val) { + if ($val['TAS_START'] === 'TRUE' and $findTask == 0) { + $findTask = 1; + $value['TASK_START'] = $val['TAS_UID']; + } + } + $fields['PROCESS_PARENT'] = $idSetActivity; + $fields['TAS_UID'] = $value['TAS_UID']; + $subProcess->subProcess[$numberSubProcess] = $this->createSubProcess( $fields, $arrayActivity ); + $numberSubProcess = $numberSubProcess + 1; + } + } + $this->createSubProcessFromDataXpdl( $subProcess, $subProcess->tasks ); + } + } + $contentNode = $contentNode->nextSibling; + } + $arrayActivities['SUBPROCESSES'] = $arraySubProcesses; + $arrayActivities['SUB_PROCESS'] = $activities; + return $arrayActivities; + } + + /** + * This public function creates an array for the task that will be created according to the data given in an array + * + * @param array $fields + * @return array $task + */ + public function createTask ($fields) + { + $task = array (); + $task['PRO_UID'] = $fields['ID_PROCESS']; + $task['TAS_UID'] = $fields['ID_TASK']; + $task['TAS_TYPE'] = $fields['TASK_TYPE']; + $task['TAS_DURATION'] = 1; + $task['TAS_DELAY_TYPE'] = ''; + $task['TAS_TEMPORIZER'] = 0; + $task['TAS_TYPE_DAY'] = ''; + $task['TAS_TIMEUNIT'] = 'DAYS'; + $task['TAS_ALERT'] = 'FALSE'; + $task['TAS_PRIORITY_VARIABLE'] = '@@SYS_CASE_PRIORITY'; + $task['TAS_ASSIGN_TYPE'] = 'BALANCED'; + $task['TAS_ASSIGN_VARIABLE'] = '@@SYS_NEXT_USER_TO_BE_ASSIGNED'; + $task['TAS_ASSIGN_LOCATION'] = 'FALSE'; + $task['TAS_ASSIGN_LOCATION_ADHOC'] = 'FALSE'; + $task['TAS_TRANSFER_FLY'] = 'FALSE'; + $task['TAS_LAST_ASSIGNED'] = '00000000000000000000000000000001'; + $task['TAS_USER'] = '0'; + $task['TAS_CAN_UPLOAD'] = 'FALSE'; + $task['TAS_VIEW_UPLOAD'] = 'FALSE'; + $task['TAS_VIEW_ADDITIONAL_DOCUMENTATION'] = 'FALSE'; + $task['TAS_CAN_CANCEL'] = 'FALSE'; + $task['TAS_OWNER_APP'] = 'FALSE'; + $task['STG_UID'] = ''; + $task['TAS_CAN_PAUSE'] = 'FALSE'; + $task['TAS_CAN_SEND_MESSAGE'] = 'TRUE'; + $task['TAS_CAN_DELETE_DOCS'] = 'FALSE'; + $task['TAS_SELF_SERVICE'] = 'FALSE'; + $task['TAS_START'] = 'FALSE'; + $task['TAS_TO_LAST_USER'] = 'FALSE'; + $task['TAS_SEND_LAST_EMAIL'] = 'FALSE'; + $task['TAS_DERIVATION'] = 'NORMAL'; + $task['TAS_POSX'] = $fields['X']; + $task['TAS_POSY'] = $fields['Y']; + $task['TAS_COLOR'] = ''; + $task['TAS_DEF_MESSAGE'] = ''; + $task['TAS_DEF_PROC_CODE'] = ''; + $task['TAS_DEF_DESCRIPTION'] = ''; + $task['TAS_TITLE'] = $fields['TAS_TITLE']; + $task['TAS_DESCRIPTION'] = $fields['DESCRIPTION']; + $task['TAS_DEF_TITLE'] = ''; + return $task; + } + + public function createDataTask ($fields) + { + $task = array (); + $task['PRO_UID'] = $fields['ID_PROCESS']; + $task['TAS_UID'] = $fields['ID_TASK']; + $task['TAS_TYPE'] = $fields['TAS_TYPE']; + $task['TAS_DURATION'] = 1; + $task['TAS_DELAY_TYPE'] = ''; + $task['TAS_TEMPORIZER'] = 0; + $task['TAS_TYPE_DAY'] = ''; + $task['TAS_TIMEUNIT'] = 'DAYS'; + $task['TAS_ALERT'] = 'FALSE'; + $task['TAS_PRIORITY_VARIABLE'] = '@@SYS_CASE_PRIORITY'; + $task['TAS_ASSIGN_TYPE'] = 'BALANCED'; + $task['TAS_ASSIGN_VARIABLE'] = '@@SYS_NEXT_USER_TO_BE_ASSIGNED'; + $task['TAS_MI_INSTANCE_VARIABLE'] = '@@SYS_VAR_TOTAL_INSTANCE'; + $task['TAS_MI_COMPLETE_VARIABLE'] = '@@SYS_VAR_TOTAL_INSTANCES_COMPLETE'; + $task['TAS_ASSIGN_LOCATION'] = 'FALSE'; + $task['TAS_ASSIGN_LOCATION_ADHOC'] = 'FALSE'; + $task['TAS_TRANSFER_FLY'] = 'FALSE'; + $task['TAS_LAST_ASSIGNED'] = '00000000000000000000000000000001'; + $task['TAS_USER'] = '0'; + $task['TAS_CAN_UPLOAD'] = 'FALSE'; + $task['TAS_VIEW_UPLOAD'] = 'FALSE'; + $task['TAS_VIEW_ADDITIONAL_DOCUMENTATION'] = 'FALSE'; + $task['TAS_CAN_CANCEL'] = 'FALSE'; + $task['TAS_OWNER_APP'] = 'FALSE'; + $task['STG_UID'] = ''; + $task['TAS_CAN_PAUSE'] = 'FALSE'; + $task['TAS_CAN_SEND_MESSAGE'] = 'TRUE'; + $task['TAS_CAN_DELETE_DOCS'] = 'FALSE'; + $task['TAS_SELF_SERVICE'] = 'FALSE'; + $task['TAS_START'] = $fields['START']; + $task['TAS_TO_LAST_USER'] = 'FALSE'; + $task['TAS_SEND_LAST_EMAIL'] = 'FALSE'; + $task['TAS_DERIVATION'] = 'NORMAL'; + $task['TAS_POSX'] = $fields['X']; + $task['TAS_POSY'] = $fields['Y']; + $task['TAS_COLOR'] = ''; + $task['TAS_DEF_MESSAGE'] = ''; + $task['TAS_DEF_PROC_CODE'] = ''; + $task['TAS_DEF_DESCRIPTION'] = ''; + $task['TAS_TITLE'] = $fields['TAS_TITLE']; + $task['TAS_DESCRIPTION'] = $fields['DESCRIPTION']; + $task['TAS_DEF_TITLE'] = ''; + return $task; + } + + /** + * This public function creates an array for the route that will be created according to the data given in an array + * + * @param array $fields + * @return array $route + */ + public function createRoute ($fields) + { + $route = array (); + $route['ROU_UID'] = $fields['ROU_UID']; + $route['ROU_PARENT'] = 0; + $route['PRO_UID'] = $fields['ID_PROCESS']; + $route['TAS_UID'] = $fields['FROM']; + $route['ROU_NEXT_TASK'] = $fields['TO']; + $route['ROU_CASE'] = 1; + $route['ROU_TYPE'] = 'SEQUENTIAL'; + $route['ROU_CONDITION'] = ''; + $route['ROU_TO_LAST_USER'] = 'FALSE'; + $route['ROU_OPTIONAL'] = 'FALSE'; + $route['ROU_SEND_EMAIL'] = 'TRUE'; + $route['ROU_SOURCEANCHOR'] = 1; + $route['ROU_TARGETANCHOR'] = 0; + return $route; + } + + /** + * This public function creates an array for the subProcess that will be created according to the data given in an array + * + * @param array $fields + * @return array $route + */ + public function createSubProcess ($fields) + { + $subProcess = array (); + $subProcess['SP_UID'] = $fields['TAS_UID']; + $subProcess['PRO_UID'] = $fields['TASK_PARENT']; + $subProcess['TAS_UID'] = $fields['TAS_UID']; + $subProcess['PRO_PARENT'] = $fields['PROCESS_PARENT']; + $subProcess['TAS_PARENT'] = $fields['TASK_PARENT']; + $subProcess['SP_TYPE'] = 'SIMPLE'; + $subProcess['SP_SYNCHRONOUS'] = 0; + $subProcess['SP_SYNCHRONOUS_TYPE'] = 'ALL'; + $subProcess['SP_SYNCHRONOUS_WAIT'] = 0; + $subProcess['SP_VARIABLES_OUT'] = 'a:1:{s:0:"";s:0:"";}'; + $subProcess['SP_VARIABLES_IN'] = 'a:1:{s:0:"";s:0:"";}'; + $subProcess['SP_GRID_IN'] = ''; + return $subProcess; + } + + /** + * This public function creates an array for the routes that are not sequential that will be created according to the data given in an array + * + * @param array $routeTransitions + * @param array $endArray + * @param array $dataRoutes + * @param array $numberRoutes + * @param string $idProcess + * @return array $dataRoutes + */ + public function createGateways ($routeTransitions, $endArray, $dataRoutes, $numberRoutes, $idProcess, $taskHidden) + { + $valueCase = ''; + $value = 1; + $valueC = 1; + $aux = $routeTransitions; + foreach ($routeTransitions as $key => $row) { + $aux[$key] = $row['ROUTE']; + } + array_multisort( $aux, SORT_ASC, $routeTransitions ); + $routeArray = $this->verifyRoutes( $routeTransitions, $endArray, $taskHidden ); + $routeArray = $this->sortArray( $routeArray ); + foreach ($routeArray as $valRoutes => $value) { + $isEventEnd = 0; + foreach ($endArray as $endBase => $valueEnd) { + if ($valueEnd['ID_TASK'] == $value['TO']) { + $isEventEnd = 1; + } + } + $dataRoutes[$numberRoutes] = array (); + $dataRoutes[$numberRoutes]['ROU_UID'] = $value['ID']; + $dataRoutes[$numberRoutes]['ROU_PARENT'] = 0; + $dataRoutes[$numberRoutes]['PRO_UID'] = $idProcess; + $dataRoutes[$numberRoutes]['TAS_UID'] = $value['FROM']; + + if ($isEventEnd == 0) { + $dataRoutes[$numberRoutes]['ROU_NEXT_TASK'] = $value['TO']; + } else { + $dataRoutes[$numberRoutes]['ROU_NEXT_TASK'] = '-1'; + } + if ($valueCase == $value['FROM']) { + $valueC = $valueC + 1; + } else { + $valueC = 1; + $valueCase = $value['FROM']; + } + if ($valueCase == '') { + $valueC = 1; + $valueCase = $value['FROM']; + } + $dataRoutes[$numberRoutes]['ROU_CASE'] = $valueC; + $dataRoutes[$numberRoutes]['ROU_TYPE'] = $value['ROU_TYPE']; + if ($value['ROU_TYPE'] === 'DISCRIMINATOR') { + $dataRoutes[$numberRoutes]['ROU_CONDITION'] = $value['CONDITION_DIS']; + $dataRoutes[$numberRoutes]['ROU_OPTIONAL'] = $value['TYPE_DIS']; + } + if ($value['ROU_TYPE'] !== 'DISCRIMINATOR') { + $dataRoutes[$numberRoutes]['ROU_CONDITION'] = $value['CONDITION']; + $dataRoutes[$numberRoutes]['ROU_OPTIONAL'] = 'FALSE'; + } + $dataRoutes[$numberRoutes]['ROU_TO_LAST_USER'] = 'FALSE'; + $dataRoutes[$numberRoutes]['ROU_SEND_EMAIL'] = 'TRUE'; + $dataRoutes[$numberRoutes]['ROU_SOURCEANCHOR'] = 1; + $dataRoutes[$numberRoutes]['ROU_TARGETANCHOR'] = 0; + $numberRoutes = $numberRoutes + 1; + } + return $dataRoutes; + } + + /** + * This public function creates an array for the lane that will be created according to the data given in an array + * + * @param array $lanes + * @return array $lane + */ + public function createLanesPM ($array, $idProcess) + { + $arrayLanes = array (); + $field = array (); + foreach ($array as $key => $value) { + $field['ID_LANE'] = $value['0']; + $field['ID_PROCESS'] = $idProcess; + $field['X'] = $value['2']; + $field['Y'] = $value['3']; + $field['WIDTH'] = $value['4']; + $field['HEIGHT'] = $value['5']; + $field['TEXT'] = $value['6']; + $arrayLanes[] = $this->createLanes( $field ); + } + return $arrayLanes; + } + + /** + * This public function creates an array for the lane that will be created according to the data given in an array + * + * @param array $lanes + * @return array $lane + */ + public function createLanes ($lanes) + { + $lane = array (); + $lane['SWI_UID'] = $lanes['ID_LANE']; + $lane['PRO_UID'] = $lanes['ID_PROCESS']; + $lane['SWI_TYPE'] = 'TEXT'; + $lane['SWI_X'] = $lanes['X']; + $lane['SWI_Y'] = $lanes['Y']; + $lane['SWI_TEXT'] = $lanes['TEXT']; + $lane['SWI_WIDTH'] = $lanes['WIDTH']; + $lane['SWI_HEIGHT'] = $lanes['HEIGHT']; + return $lane; + } + + /** + * This public function creates an array for the lane that will be created according to the data given in an array + * + * @param array $lanes + * @return array $lane + */ + public function createLanesNewPM ($array) + { + $arrayLanes = array (); + $field = array (); + foreach ($array as $key => $value) { + if ($value['SWI_TYPE'] == 'TEXT') { + $field['0'] = $value['SWI_UID']; + $field['1'] = $value['SWI_TEXT']; + $field['2'] = $value['SWI_X']; + $field['3'] = $value['SWI_Y']; + $field['4'] = $value['SWI_WIDTH']; + $field['5'] = $value['SWI_HEIGHT']; + $field['6'] = $value['SWI_NEXT_UID']; + $arrayLanes[] = $field; + } + } + return $arrayLanes; + } + + /** + * This public function creates activities according the content of the node + * + * @param object $contentNode + * @param string $idProcess + * @param string $ActivitySet + * @return array $result + */ + public function createActivities ($contentNode, $idProcess, $activitySet) + { + $result = array (); + $numberTasks = 0; + $posRoutes = 0; + $posEnd = 0; + $posStart = 0; + $arrayRoutes = array (); + $endArray = array (); + $endArray = array (); + $startArray = array (); + $arrayScheduler = array (); + $scheduler = array (); + $message = array (); + $arrayMessages = array (); + while ($contentNode) { + if ($contentNode->nodeType == XML_ELEMENT_NODE) { + $nameActivity = $contentNode->nodeName; + $contentActivity = $contentNode->firstChild; + if (strpos( $nameActivity, 'Activity' ) !== false) { + $idActivity = $contentNode->getAttribute( 'Id' ); + $idActivity = trim( str_replace( '-', '', $idActivity ) ); + $name = htmlentities( $contentNode->getAttribute( 'Name' ) ); + $result = $this->createActivity( $contentActivity ); + $result['ID_PROCESS'] = $idProcess; + $result['ID_TASK'] = $idActivity; + $result['TAS_TITLE'] = $name; + $result['TASK_TYPE'] = 'NORMAL'; + foreach ($activitySet as $key => $value) { + if ($value['ID_PROCESS'] == $idActivity) { + $result['TASK_TYPE'] = 'SUBPROCESS'; + } + } + if ($result['EVENT'] == '' and $result['ROUTE'] == '') { + $arrayTasks[$numberTasks] = $this->createTask( $result ); + $numberTasks = $numberTasks + 1; + } else { + if ($result['EVENT'] != '' and $result['TRIGGER'] == 'None') { + if ($result['EVENT'] == 'END') { + $endArray[$posEnd] = $result; + $posEnd = $posEnd + 1; + } + if ($result['EVENT'] == 'START') { + $startArray[$posStart] = $result; + $posStart = $posStart + 1; + } + } else { + if ($result['TRIGGER'] == 'Timer') { + $scheduler['ID'] = $idActivity; + $scheduler['NAME'] = $name; + if ($result['TIME'] == '' or $result['TIME'] == null) { + $scheduler['TIME'] = date( "D M j G:i:s T Y" ); + } else { + $scheduler['TIME'] = $result['TIME']; + } + $scheduler['TYPE_TIME'] = $result['TYPE_TIME']; + $arrayScheduler[] = $scheduler; + } + if ($result['TRIGGER'] == 'Message') { + $message['ID'] = $idActivity; + $message['NAME'] = $name; + $message['TYPE_MESSAGE'] = $result['MESSAGE']; + $arrayMessages[] = $message; + } + } + if ($result['ROUTE'] != '') { + $position = $this->findCoordinates( $contentActivity ); + $arrayRoutes[$posRoutes]['ID'] = $idActivity; + $arrayRoutes[$posRoutes]['ROUTE'] = $result['ROUTE']; + $arrayRoutes[$posRoutes]['TYPE_DIS'] = $result['TYPE_DISCRIMINATOR']; + $arrayRoutes[$posRoutes]['CONDITION_DIS'] = $result['CONDITION_DISCRIMINATOR']; + $arrayRoutes[$posRoutes]['X'] = $position['X']; + $arrayRoutes[$posRoutes]['Y'] = $position['Y']; + $posRoutes = $posRoutes + 1; + } + } + } + } + $contentNode = $contentNode->nextSibling; + } + $result['TASKS'] = $arrayTasks; + $result['END'] = $endArray; + $result['START'] = $startArray; + $result['ROUTES'] = $arrayRoutes; + $result['SCHEDULER'] = $arrayScheduler; + $result['MESSAGES'] = $arrayMessages; + return $result; + } + + /** + * This public function creates the scheduler + * + * @param array $fields + * @return array $result + */ + public function createEventMessages ($fields, $idProcess) + { + $result = array (); + $event = array (); + $example = new Derivation(); + foreach ($fields as $key => $value) { + $oEvent = new Event(); + $event['EVN_UID'] = $value['ID']; + $event['PRO_UID'] = $idProcess; + $event['EVN_RELATED_TO'] = 'SINGLE'; + $event['TAS_UID'] = $value['ID_TASK']; + $event['EVN_TAS_ESTIMATED_DURATION'] = '1'; + $event['EVN_WHEN_OCCURS'] = 'AFTER'; + $event['EVN_STATUS'] = 'ACTIVE'; + $event['EVN_WHEN'] = 1; + $event['EVN_MAX_ATTEMPTS'] = 3; + $event['EVN_ACTION'] = 'SEND_MESSAGE'; + $event['EVN_DESCRIPTION'] = $value['NAME']; + $event['EVN_WHEN_OCCURS'] = 'AFTER_TIME'; + $event['EVN_ACTION_PARAMETERS'] = array ('SUBJECT' => 'subject','TO' => array ('0' => 'usr|-1','1' => 'ext|' + ),'CC' => array (),'BCC' => array (),'TEMPLATE' => 'alert_message.html' + ); + $result[] = $event; + } + return $result; + } + + /** + * This public function creates the scheduler + * + * @param array $fields + * @return array $result + */ + public function createScheduler ($fields, $idProcess) + { + $result = array (); + $example = new Derivation(); + foreach ($fields as $key => $value) { + if ($value['TYPE_TIME'] == 'TimeDate') { + //there is a scheduler one time only + $value['OPTION'] = 4; + $result[] = $this->createArrayScheduler( $value, $idProcess ); + } + if ($value['TYPE_TIME'] == 'TimeCycle') { + //we calculated if is daily or monthly, etc + $time = $this->calculateTimeScheduler( $value['TIME'] ); + /*$value['OPTION']= $time['OPTION']; + $value['TIME'] = $time['TIME'];*/ + $value['OPTION'] = '1'; + } + } + //PRINT_r($result); + return $result; + } + + /** + * This public function creates the scheduler + * + * @param array $fields + * @return array $result + */ + public function calculateTimeScheduler ($time) + { + $result = array (); + // The split public function has been DEPRECATED as of PHP 5.3.0. + // $result = split(' ',$time); + $result = explode( ' ', $time ); + //print_r($result); + return $result; + } + + /** + * This public function creates the array scheduler + * + * @param string $time + * @param string $type (TimeCycle or TimeDate) + * @return array $result + */ + public function createArrayScheduler ($fields, $idProcess) + { + $result['SCH_UID'] = $fields['ID']; + $result['SCH_DEL_USER_NAME'] = ''; + $result['SCH_DEL_USER_PASS'] = ''; + $result['SCH_DEL_USER_UID'] = ''; + $result['SCH_NAME'] = $fields['NAME']; + $result['PRO_UID'] = $idProcess; + $result['TAS_UID'] = $fields['ID_TASK']; + $result['SCH_TIME_NEXT_RUN'] = $fields['TIME']; + $result['SCH_LAST_RUN_TIME'] = null; + $result['SCH_STATE'] = 'ACTIVE'; + $result['SCH_LAST_STATE'] = 'CREATED'; + $result['USR_UID'] = '00000000000000000000000000000001'; + $result['SCH_OPTION'] = $fields['OPTION']; + $result['SCH_START_TIME'] = $fields['TIME']; + $result['SCH_START_DATE'] = $fields['TIME']; + $result['SCH_DAYS_PERFORM_TASK'] = ''; + $result['SCH_EVERY_DAYS'] = '0'; + $result['SCH_WEEK_DAYS'] = '0|0|0|0|0|0|0'; + $result['SCH_START_DAY'] = ''; + $result['SCH_MONTHS'] = '0|0|0|0|0|0|0|0|0|0|0|0'; + $result['SCH_END_DATE'] = $fields['TIME']; + $result['SCH_REPEAT_EVERY'] = ''; + $result['SCH_REPEAT_UNTIL'] = ''; + $result['SCH_REPEAT_STOP_IF_RUNNING'] = ''; + return $result; + } + + /** + * This public function creates transitions according the content of the node + * + * @param object $contentNode + * @param array $dataTask + * @param array $arrayRoutes + * @param array $endArray + * @param array $startArray + * @param string $idProcess + * @return array $result + */ + + public function createTransitions ($contentNode, $dataTasks, $arrayRoutes, $endArray, $startArray, $idProcess, $schedulerArray, $messages) + { + $numberRoutes = 0; + $posT = 0; + $output = ''; + $routeTransitions = array (); + $taskHidden = array (); + $countHidden = 1; + $dataRoutes = array (); + $newFrom = 0; + $isScheduler = 0; + $isMessage = 0; + while ($contentNode) { + $isEnd = 0; + $isStart = 0; + $tasks = $dataTasks; + if ($contentNode->nodeType == XML_ELEMENT_NODE) { + $nameTransition = $contentNode->nodeName; + $contentTransition = $contentNode->firstChild; + if (strpos( $nameTransition, 'Transition' ) !== false) { + $idTransition = $contentNode->getAttribute( 'Id' ); + $idTransition = trim( str_replace( '-', '', $idTransition ) ); + $from = trim( str_replace( '-', '', $contentNode->getAttribute( 'From' ) ) ); + $to = trim( str_replace( '-', '', $contentNode->getAttribute( 'To' ) ) ); + $routes['ROU_UID'] = $idTransition; + $routes['ID_PROCESS'] = $idProcess; + $routes['FROM'] = $from; + $routes['TO'] = $to; + $isScheduler = 0; + $isMessage = 0; + foreach ($startArray as $startBase => $value) { + if ($value['ID_TASK'] == $from) { + foreach ($tasks as $tasksValue => $taskId) { + if ($to == $taskId['TAS_UID']) { + $taskId['TAS_START'] = 'TRUE'; + $dataTasks[$tasksValue]['TAS_START'] = 'TRUE'; + $isStart = 1; + } + } + } + } + foreach ($schedulerArray as $startBase => $value) { + if ($value['ID'] == $from) { + $isScheduler = 1; + $schedulerArray[$startBase]['ID_TASK'] = $to; + foreach ($tasks as $tasksValue => $taskId) { + if ($to == $taskId['TAS_UID']) { + $taskId['TAS_START'] = 'TRUE'; + $dataTasks[$tasksValue]['TAS_START'] = 'TRUE'; + $isStart = 1; + } + } + } + } + foreach ($messages as $startBase => $value) { + if ($value['ID'] == $from) { + $isMessage = 1; + $messages[$startBase]['ID_TASK'] = $to; + } + if ($value['ID'] == $to) { + $isMessage = 1; + $messages[$startBase]['ID_TASK'] = $from; + } + } + $sequencial = 0; + $findRoute = 0; + foreach ($arrayRoutes as $routeBase => $value) { + //change for task hidden + if ($value['ID'] == $from) { + if ($findRoute == 0) { + $typeT = 'FROM'; + $valueRoute = $value['ID']; + $typeRoute = $value['ROUTE']; + $sequencial = 1; + $conditionD = $value['CONDITION_DIS']; + $typeD = $value['TYPE_DIS']; + $findRoute = 1; + } else { + $contendHidden = $contentTransition; + $fieldsXY = $this->findCoordinatesTransition( $to, $arrayRoutes ); + $hidden['ID_TASK'] = G::generateUniqueID(); + $hidden['ID_PROCESS'] = $idProcess; + $hidden['TAS_TITLE'] = ''; + $hidden['TASK_TYPE'] = 'HIDDEN'; + $hidden['DESCRIPTION'] = $countHidden; + $hidden['X'] = $fieldsXY['X']; + $hidden['Y'] = $fieldsXY['Y']; + $taskHidden[] = $hidden; + $dataTasks[] = $this->createTask( $hidden ); + $countHidden = $countHidden + 1; + $routeTransitions[$posT]['ID'] = G::generateUniqueID(); + $routeTransitions[$posT]['ROUTE'] = $from; + $routeTransitions[$posT]['FROM'] = $from; + $routeTransitions[$posT]['TO'] = $hidden['ID_TASK']; + $routeTransitions[$posT]['TOORFROM'] = 'FROM'; + $routeTransitions[$posT]['ROU_TYPE'] = $value['ROUTE']; + $routeTransitions[$posT]['CONDITION'] = $output; + $routeTransitions[$posT]['CONDITION_DIS'] = $conditionD; + $routeTransitions[$posT]['TYPE_DIS'] = $typeD; + $output = ''; + $posT = $posT + 1; + $from = $hidden['ID_TASK']; + } + } + if ($value['ID'] == $to) { + if ($findRoute == 0) { + $typeT = 'TO'; + $valueRoute = $value['ID']; + $typeRoute = $value['ROUTE']; + $sequencial = 1; + $conditionD = $value['CONDITION_DIS']; + $typeD = $value['TYPE_DIS']; + $findRoute = 1; + } else { + + $contendHidden = $contentTransition; + $fieldsXY = $this->findCoordinatesTransition( $to, $arrayRoutes ); + $hidden['ID_TASK'] = G::generateUniqueID(); + $hidden['ID_PROCESS'] = $idProcess; + $hidden['TAS_TITLE'] = ''; + $hidden['TASK_TYPE'] = 'HIDDEN'; + $hidden['DESCRIPTION'] = $countHidden; + $hidden['X'] = $fieldsXY['X']; + $hidden['Y'] = $fieldsXY['Y']; + $taskHidden[] = $hidden; + $dataTasks[] = $this->createTask( $hidden ); + $countHidden = $countHidden + 1; + $routeTransitions[$posT]['ID'] = G::generateUniqueID(); + $routeTransitions[$posT]['ROUTE'] = $from; + $routeTransitions[$posT]['FROM'] = $from; + $routeTransitions[$posT]['TO'] = $hidden['ID_TASK']; + $routeTransitions[$posT]['TOORFROM'] = 'TO'; + $routeTransitions[$posT]['ROU_TYPE'] = $typeRoute; + $routeTransitions[$posT]['CONDITION'] = $output; + $routeTransitions[$posT]['CONDITION_DIS'] = $conditionD; + $routeTransitions[$posT]['TYPE_DIS'] = $typeD; + $output = ''; + $posT = $posT + 1; + $from = $hidden['ID_TASK']; + $conditionD = $value['CONDITION_DIS']; + $typeRoute = $value['ROUTE']; + $typeT = 'TO'; + $valueRoute = $value['ID']; + $sequencial = 1; + $conditionD = $value['CONDITION_DIS']; + $typeD = $value['TYPE_DIS']; + } + } + } + if ($sequencial == 0) { + foreach ($endArray as $endBase => $value) { + if ($value['ID_TASK'] == $to) { + foreach ($tasks as $tasksValue => $taskId) { + if ($from == $taskId['TAS_UID']) { + $routes['TO'] = '-1'; + $dataRoutes[$numberRoutes] = $this->createRoute( $routes ); + $numberRoutes = $numberRoutes + 1; + $isEnd = 1; + } + } + } + } + } + if ($sequencial == 1) { + while ($contentTransition) { + $nameCondition = $contentTransition->nodeName; + $contentCondition = $contentTransition->firstChild; + if (strpos( $nameCondition, 'Condition' ) !== false) { + while ($contentCondition) { + $nameExpression = $contentCondition->nodeName; + $contentCondition1 = ''; + if (strpos( $nameExpression, 'Expression' ) !== false) { + $contentCondition1 = $contentCondition->firstChild; + if ($contentCondition1 != array ()) { + $output = $contentCondition1->nodeValue; + } + } + $contentCondition = $contentCondition->nextSibling; + } + } + $contentTransition = $contentTransition->nextSibling; + } + $routeTransitions[$posT]['ID'] = $idTransition; + $routeTransitions[$posT]['ROUTE'] = $valueRoute; + $routeTransitions[$posT]['FROM'] = $from; + $routeTransitions[$posT]['TO'] = $to; + $routeTransitions[$posT]['TOORFROM'] = $typeT; + $routeTransitions[$posT]['ROU_TYPE'] = $typeRoute; + $routeTransitions[$posT]['CONDITION'] = $output; + $routeTransitions[$posT]['CONDITION_DIS'] = $conditionD; + $routeTransitions[$posT]['TYPE_DIS'] = $typeD; + $output = ''; + $posT = $posT + 1; + $sequencial = 1; + } + if ($isEnd == 0 and $isStart == 0 and $sequencial == 0 and $isScheduler == 0 and $isMessage == 0) { + $dataRoutes[$numberRoutes] = $this->createRoute( $routes ); + $numberRoutes = $numberRoutes + 1; + } + } + } + $contentNode = $contentNode->nextSibling; + } + $routes = $routeTransitions; + foreach ($routeTransitions as $key => $id) { + $findTo = 0; + $findFrom = 0; + foreach ($dataTasks as $keyHidden => $value) { + if ($id['FROM'] == $value['TAS_UID']) { + $findFrom = 1; + } + if ($id['TO'] == $value['TAS_UID']) { + $findTo = 1; + } + } + if ($findTo == 0) { + foreach ($routes as $keyR => $idR) { + if ($id['TO'] == $idR['ROUTE']) { + $routeTransitions[$key]['ROU_TYPE'] = $idR['ROU_TYPE']; + $routeTransitions[$key]['ROUTE'] = $id['TO']; + $routeTransitions[$key]['TOORFROM'] = 'TO'; + } + } + } + if ($findFrom == 0) { + foreach ($routes as $keyR => $idR) { + if ($id['FROM'] == $idR['ROUTE']) { + $routeTransitions[$key]['ROU_TYPE'] = $idR['ROU_TYPE']; + $routeTransitions[$key]['ROUTE'] = $id['FROM']; + $routeTransitions[$key]['TOORFROM'] = 'FROM'; + } + } + } + } + $result['ROUTES'] = $dataRoutes; + $result['TRANSITIONS'] = $routeTransitions; + $result['TASKS'] = $dataTasks; + $result['NUMBER'] = $numberRoutes; + $result['TASKHIDDEN'] = $taskHidden; + $result['SCHEDULER'] = $schedulerArray; + $result['MESSAGES'] = $messages; + return $result; + } + + /** + * this public function creates a array according to the data given in a node + * + * @param object $contentNode + * @return array + */ + public function createActivity ($contentNode) + { + $coordinates = array (); + $event = ''; + $typeRoute = ''; + $markerVisible = ''; + $typePM = ''; + $isRoute = 0; + $description = ''; + $isSubProcess = 0; + $trigger = ''; + $time = ''; + $typeTime = ''; + $isMessage = 0; + while ($contentNode) { + if ($contentNode->nodeType == XML_ELEMENT_NODE) { + $nameChild = $contentNode->nodeName; + $contentChild = $contentNode->firstChild; + if (strpos( $nameChild, 'Description' ) !== false) { + $description = $contentNode->nodeValue; + } + if (strpos( $nameChild, 'ExtendedAttributes' ) !== false) { + $result = $this->createExtended( $contentChild ); + } + if (strpos( $nameChild, 'BlockActivity' ) !== false) { + $isSubProcess = 1; + $idSubProcess = trim( str_replace( '-', '', $contentNode->getAttribute( 'ActivitySetId' ) ) ); + } + if (strpos( $nameChild, 'Event' ) !== false) { + while ($contentChild) { + if ($contentChild->nodeType == XML_ELEMENT_NODE) { + $nameInfo = $contentChild->nodeName; + $contentInfo = $contentChild->firstChild; + if (strpos( $nameInfo, 'StartEvent' ) !== false) { + $event = 'START'; + $trigger = $contentChild->getAttribute( 'Trigger' ); + } + if (strpos( $nameInfo, 'EndEvent' ) !== false) { + $event = 'END'; + $trigger = $contentChild->getAttribute( 'Trigger' ); + if ($trigger == '') { + $trigger = 'None'; + } + } + if (strpos( $nameInfo, 'IntermediateEvent' ) !== false) { + $event = 'INTERMEDIATE'; + $trigger = $contentChild->getAttribute( 'Trigger' ); + } + } + $contentChild = $contentChild->nextSibling; + } + if ($trigger != 'None') { + if ($trigger == 'Timer') { + while ($contentInfo) { + $nameTrigger = $contentInfo->nodeName; + $contentTrigger = $contentInfo->firstChild; + if (strpos( $nameTrigger, 'TriggerTimer' ) !== false) { + $time = $contentInfo->getAttribute( 'TimeCycle' ); + $typeTime = 'TimeCycle'; + if ($time == '') { + $time = $contentInfo->getAttribute( 'TimeDate' ); + $typeTime = 'TimeDate'; + } + } + $contentInfo = $contentInfo->nextSibling; + } + } + if ($trigger == 'Message') { + $typeMessage = ''; + $isMessage = 1; + while ($contentInfo) { + $nameTrigger = $contentInfo->nodeName; + $contentTrigger = $contentInfo->firstChild; + if (strpos( $nameTrigger, 'TriggerResultMessage' ) !== false) { + $typeMessage = $contentInfo->getAttribute( 'CatchThrow' ); + } + $contentInfo = $contentInfo->nextSibling; + } + } + } + } + + if (strpos( $nameChild, 'Route' ) !== false) { + $typePM = ''; + $typeRoute = $contentNode->getAttribute( 'GatewayType' ); + $markerVisible = $contentNode->getAttribute( 'MarkerVisible' ); + if ($markerVisible != '') { + $coordinates['ROUTE'] = $markerVisible; + } + if ($typeRoute != '') { + $coordinates['ROUTE'] = $typeRoute; + } + if ($typeRoute == '' and $markerVisible == '') { + $coordinates['ROUTE'] = 'EVALUATE'; + } + switch ($coordinates['ROUTE']) { + case 'AND': + $typePM = 'PARALLEL'; + break; + case 'true': + $typePM = 'EVALUATE'; + break; + case 'EVALUATE': + $typePM = 'EVALUATE'; + break; + case 'OR': + $typePM = 'PARALLEL-BY-EVALUATION'; + break; + case 'Complex': + $typePM = 'DISCRIMINATOR'; + break; + } + $isRoute = 1; + } + if (strpos( $nameChild, 'NodeGraphicsInfos' ) !== false) { + $coordinates = $this->findCoordinates( $contentNode ); + $coordinates['EVENT'] = $event; + $coordinates['TRIGGER'] = $trigger; + $coordinates['TIME'] = $time; + $coordinates['TYPE_TIME'] = $typeTime; + $coordinates['DESCRIPTION'] = $description; + $coordinates['TYPE_DISCRIMINATOR'] = $result['TYPE']; + $coordinates['CONDITION_DISCRIMINATOR'] = $result['CONDITION']; + if ($isRoute == 1) { + $coordinates['ROUTE'] = $typePM; + } else { + $coordinates['ROUTE'] = ''; + } + if ($isMessage == 1) { + $coordinates['MESSAGE'] = $typeMessage; + } else { + $coordinates['MESSAGE'] = ''; + } + } + } + $contentNode = $contentNode->nextSibling; + } + return $coordinates; + } + + /** + * This public function return the type and the condition of a discriminator + * + * @param object $contentNode + * @return array + */ + public function createExtended ($contentNode) + { + $result = array (); + $result['TYPE'] = ''; + $result['CONDITION'] = ''; + $contentExtended = $contentNode; + while ($contentExtended) { + if ($contentExtended->nodeType == XML_ELEMENT_NODE) { + $nameChildExtended = $contentExtended->nodeName; + $contentChildExtended = $contentExtended->firstChild; + if (strpos( $nameChildExtended, 'ExtendedAttribute' ) !== false) { + $name = $contentExtended->getAttribute( 'Name' ); + if ($name == 'option') { + $result['TYPE'] = $contentExtended->getAttribute( 'Value' ); + } + if ($name == 'condition') { + $result['CONDITION'] = $contentExtended->getAttribute( 'Value' ); + } + } + } + $contentExtended = $contentExtended->nextSibling; + } + return $result; + } + + /** + * This public function find the coordinates of a object + * + * @param object $contentNode + * @return array + */ + public function findCoordinates ($contentNode) + { + $coordinates = array (); + while ($contentNode) { + if ($contentNode->nodeType == XML_ELEMENT_NODE) { + $nameChild = $contentNode->nodeName; + $contentChild = $contentNode->firstChild; + if (strpos( $nameChild, 'NodeGraphicsInfos' ) !== false) { + while ($contentChild) { + if ($contentChild->nodeType == XML_ELEMENT_NODE) { + $nameInfo = $contentChild->nodeName; + $contentInfo = $contentChild->firstChild; + if (strpos( $nameInfo, 'NodeGraphicsInfo' ) !== false) { + $coordinates['Height'] = $contentChild->getAttribute( 'Height' ); + $coordinates['Width'] = $contentChild->getAttribute( 'Width' ); + $coordinates['BorderColor'] = $contentChild->getAttribute( 'BorderColor' ); + $coordinates['FillColor'] = $contentChild->getAttribute( 'FillColor' ); + while ($contentInfo) { + $nameCoordinate = $contentInfo->nodeName; + $contentCoordinate = $contentInfo->firstChild; + + if (strpos( $nameCoordinate, 'Coordinates' ) !== false) { + $coordinates['X'] = $contentInfo->getAttribute( 'XCoordinate' ); + $coordinates['Y'] = $contentInfo->getAttribute( 'YCoordinate' ); + } + $contentInfo = $contentInfo->nextSibling; + } + + } + } + $contentChild = $contentChild->nextSibling; + } + } + } + $contentNode = $contentNode->nextSibling; + } + return $coordinates; + } + + /** + * This public function find the coordinates of a object + * + * @param string $idRoute + * @param array $aRoutes + * @return array + */ + public function findCoordinatesTransition ($idRoute, $aRoutes) + { + $coordinates = array (); + $size = sizeof( $aRoutes ); + $count = 0; + $find = 0; + while ($count < $size and $find == 0) { + if ($aRoutes[$count]['ID'] == $idRoute) { + $coordinates['X'] = $aRoutes[$count]['X']; + $coordinates['Y'] = $aRoutes[$count]['Y']; + $find = 1; + } + $count = $count + 1; + } + return $coordinates; + } + + /** + * This public function create the array Routes + * + * @param array $dataTasks + * @param array $arrayRoutes + * @param array $aEvents + * @param array $aGateways + * @param string $idProcess + * @return array + */ + public function createArrayRoutes ($dataTasks, $arrayRoutes, $aEvents, $aGateways, $aEnd, $idProcess) + { + $numberRoutes = 0; + $posT = 0; + $routeTransitions = array (); + $dataRoutes = array (); + $findRoute = 0; + $hidden = array (); + $taskHidden = array (); + $countHidden = 0; + foreach ($arrayRoutes as $idRoute => $valueRoute) { + $idTransition = $valueRoute['0']; + $from = $valueRoute['1']; + $to = $valueRoute['2']; + $toPort = $valueRoute['3']; + $fromPort = $valueRoute['4']; + $routes['ROU_UID'] = $idTransition; + $routes['ID_PROCESS'] = $idProcess; + $routes['FROM'] = $from; + $routes['TO'] = $to; + $sequencial = 0; + $isEnd = 0; + $typeRoute = ''; + $typePM = ''; + $findRoute = 0; + $isEventIntermediate = 0; + foreach ($aGateways as $routeBase => $value) { + if ($value['0'] == $from) { + if ($findRoute == 0) { + $typeT = 'FROM'; + $valueRoute = $value['0']; + $typeRoute = $value['1']; + $positionX = $value['2']; + $positionY = $value['3']; + $sequencial = 1; + $findRoute = 1; + } else { + $hidden['ID_TASK'] = G::generateUniqueID(); + $hidden['ID_PROCESS'] = $idProcess; + $hidden['TAS_TITLE'] = ''; + $hidden['TASK_TYPE'] = 'HIDDEN'; + $hidden['DESCRIPTION'] = $countHidden; + $hidden['X'] = $positionX; + $hidden['Y'] = $positionY; + $taskHidden[] = $hidden; + $dataTasks[] = $this->createTask( $hidden ); + $countHidden = $countHidden + 1; + $routeTransitions[$posT]['ID'] = G::generateUniqueID(); + $routeTransitions[$posT]['ROUTE'] = $from; + $routeTransitions[$posT]['FROM'] = $from; + $routeTransitions[$posT]['TO'] = $hidden['ID_TASK']; + $routeTransitions[$posT]['TOORFROM'] = 'FROM'; + $routeTransitions[$posT]['ROU_TYPE'] = $value['1']; + $routeTransitions[$posT]['CONDITION'] = ''; + $routeTransitions[$posT]['CONDITION_DIS'] = ''; + $routeTransitions[$posT]['TYPE_DIS'] = ''; + $posT = $posT + 1; + $from = $hidden['ID_TASK']; + } + } + if ($value['0'] == $to) { + if ($findRoute == 0) { + $typeT = 'TO'; + $valueRoute = $value['0']; + $typeRoute = $value['1']; + $positionX = $value['2']; + $positionY = $value['3']; + $sequencial = 1; + $findRoute = 1; + } else { + $hidden['ID_TASK'] = G::generateUniqueID(); + $hidden['ID_PROCESS'] = $idProcess; + $hidden['TAS_TITLE'] = ''; + $hidden['TASK_TYPE'] = 'HIDDEN'; + $hidden['DESCRIPTION'] = $countHidden; + $hidden['X'] = $positionX; + $hidden['Y'] = $positionY; + $taskHidden[] = $hidden; + $dataTasks[] = $this->createTask( $hidden ); + $countHidden = $countHidden + 1; + $routeTransitions[$posT]['ID'] = G::generateUniqueID(); + $routeTransitions[$posT]['ROUTE'] = $from; + $routeTransitions[$posT]['FROM'] = $from; + $routeTransitions[$posT]['TO'] = $hidden['ID_TASK']; + $routeTransitions[$posT]['TOORFROM'] = 'TO'; + $routeTransitions[$posT]['ROU_TYPE'] = $typeRoute; + $routeTransitions[$posT]['CONDITION'] = ''; + $routeTransitions[$posT]['CONDITION_DIS'] = ''; + $routeTransitions[$posT]['TYPE_DIS'] = ''; + $posT = $posT + 1; + $from = $hidden['ID_TASK']; + $typeT = 'TO'; + $valueRoute = $value['0']; + $typeRoute = $value['1']; + $sequencial = 1; + } + } + } + if ($sequencial == 0) { + foreach ($aEvents as $id => $value) { + if ($routes['TO'] == $value['0']) { + if ($value['1'] === 'bpmnEventEndSignal' or $value['1'] === 'bpmnEventMessageEnd') { + $routes['TO'] = '-1'; + $dataRoutes[$numberRoutes] = $this->createRoute( $routes ); + $numberRoutes = $numberRoutes + 1; + $isEnd = 1; + } else { + $isEventIntermediate = 1; + } + } + } + } + if ($sequencial == 1) { + $routeTransitions[$posT]['ID'] = $idTransition; + $routeTransitions[$posT]['ROUTE'] = $valueRoute; + $routeTransitions[$posT]['FROM'] = $from; + $routeTransitions[$posT]['TO'] = $to; + $routeTransitions[$posT]['TOORFROM'] = $typeT; + $routeTransitions[$posT]['ROU_TYPE'] = $typeRoute; + $routeTransitions[$posT]['CONDITION'] = ''; + $routeTransitions[$posT]['CONDITION_DIS'] = ''; + $routeTransitions[$posT]['TYPE_DIS'] = ''; + $posT = $posT + 1; + $sequencial = 1; + } + if ($isEnd == 0 and $sequencial == 0 and $isEventIntermediate == 0) { + $dataRoutes[$numberRoutes] = $this->createRoute( $routes ); + $numberRoutes = $numberRoutes + 1; + } + } + foreach ($routeTransitions as $id => $key) { + $typeRoute = $key['ROU_TYPE']; + switch ($typeRoute) { + case 'bpmnGatewayExclusiveData': $typePM = 'EVALUATE'; - break; - case 'OR': + break; + case 'bpmnGatewayInclusive': $typePM = 'PARALLEL-BY-EVALUATION'; - break; - case 'Complex': + break; + case 'bpmnGatewayExclusiveEvent': + $typePM = 'EVALUATE'; + break; + case 'bpmnGatewayComplex': $typePM = 'DISCRIMINATOR'; - break; - } - $isRoute = 1; + break; + case 'bpmnGatewayParallel': + $typePM = 'PARALLEL'; + break; + } + $routeTransitions[$id]['ROU_TYPE'] = $typePM; } - if(strpos($nameChild,'NodeGraphicsInfos')!== false){ - $coordinates = $this->findCoordinates($contentNode); - $coordinates['EVENT'] = $event; - $coordinates['TRIGGER'] = $trigger; - $coordinates['TIME'] = $time; - $coordinates['TYPE_TIME'] = $typeTime; - $coordinates['DESCRIPTION'] = $description; - $coordinates['TYPE_DISCRIMINATOR'] = $result['TYPE']; - $coordinates['CONDITION_DISCRIMINATOR'] = $result['CONDITION']; - if($isRoute == 1){ - $coordinates['ROUTE']= $typePM; - } - else{ - $coordinates['ROUTE']=''; - } - if($isMessage == 1){ - $coordinates['MESSAGE']= $typeMessage; - } - else{ - $coordinates['MESSAGE']=''; - } - } - } - $contentNode = $contentNode->nextSibling; - } - return $coordinates; - } - - /** - * This function return the type and the condition of a discriminator - * @param object $contentNode - * @return array - */ - function createExtended($contentNode) - { - $result = array(); - $result['TYPE']= ''; - $result['CONDITION'] = ''; - $contentExtended = $contentNode; - while ($contentExtended) { - if ($contentExtended->nodeType == XML_ELEMENT_NODE) { - $nameChildExtended = $contentExtended->nodeName; - $contentChildExtended = $contentExtended->firstChild; - if(strpos($nameChildExtended,'ExtendedAttribute')!== false){ - $name = $contentExtended->getAttribute('Name'); - if($name == 'option'){ - $result['TYPE'] = $contentExtended->getAttribute('Value'); - } - if($name == 'condition'){ - $result['CONDITION'] = $contentExtended->getAttribute('Value'); - } - } - } - $contentExtended = $contentExtended->nextSibling; - } - return $result; - } - -/** - * This function find the coordinates of a object - * @param object $contentNode - * @return array - */ - function findCoordinates($contentNode) - { - $coordinates = array(); - while ($contentNode) { - if ($contentNode->nodeType == XML_ELEMENT_NODE) { - $nameChild = $contentNode->nodeName; - $contentChild = $contentNode->firstChild; - if(strpos($nameChild,'NodeGraphicsInfos')!== false){ - while ($contentChild) { - if ($contentChild->nodeType == XML_ELEMENT_NODE) { - $nameInfo = $contentChild->nodeName; - $contentInfo = $contentChild->firstChild; - if(strpos($nameInfo,'NodeGraphicsInfo')!== false){ - $coordinates['Height'] = $contentChild->getAttribute('Height'); - $coordinates['Width'] = $contentChild->getAttribute('Width'); - $coordinates['BorderColor'] = $contentChild->getAttribute('BorderColor'); - $coordinates['FillColor'] = $contentChild->getAttribute('FillColor'); - while ($contentInfo) { - $nameCoordinate = $contentInfo->nodeName; - $contentCoordinate = $contentInfo->firstChild; - - if(strpos($nameCoordinate,'Coordinates')!== false){ - $coordinates['X'] = $contentInfo->getAttribute('XCoordinate'); - $coordinates['Y'] = $contentInfo->getAttribute('YCoordinate'); - } - $contentInfo = $contentInfo->nextSibling; + $routes = $routeTransitions; + foreach ($routeTransitions as $key => $id) { + $findTo = 0; + $findFrom = 0; + foreach ($dataTasks as $keyHidden => $value) { + if ($id['FROM'] == $value['TAS_UID']) { + $findFrom = 1; } - - } - } - $contentChild = $contentChild->nextSibling; - } - } - } - $contentNode = $contentNode->nextSibling; - } - return $coordinates; - } - -/** - * This function find the coordinates of a object - * @param string $idRoute - * @param array $aRoutes - * @return array - */ - function findCoordinatesTransition($idRoute,$aRoutes) - { - $coordinates = array(); - $size = sizeof($aRoutes); - $count = 0; - $find = 0; - while($count < $size and $find == 0){ - if($aRoutes[$count]['ID'] == $idRoute){ - $coordinates['X'] = $aRoutes[$count]['X']; - $coordinates['Y'] = $aRoutes[$count]['Y']; - $find = 1; - } - $count = $count + 1; - } - return $coordinates; - } - - /** - * This function create the array Routes - * @param array $dataTasks - * @param array $arrayRoutes - * @param array $aEvents - * @param array $aGateways - * @param string $idProcess - * @return array - */ - function createArrayRoutes($dataTasks,$arrayRoutes,$aEvents,$aGateways,$aEnd,$idProcess) - { - $numberRoutes = 0; - $posT = 0; - $routeTransitions = array(); - $dataRoutes = array(); - $findRoute = 0; - $hidden = array(); - $taskHidden = array(); - $countHidden = 0; - foreach($arrayRoutes as $idRoute => $valueRoute){ - $idTransition = $valueRoute['0']; - $from = $valueRoute['1']; - $to = $valueRoute['2']; - $toPort = $valueRoute['3']; - $fromPort = $valueRoute['4']; - $routes['ROU_UID'] = $idTransition; - $routes['ID_PROCESS']= $idProcess; - $routes['FROM'] = $from; - $routes['TO'] = $to; - $sequencial = 0; - $isEnd = 0; - $typeRoute = ''; - $typePM = ''; - $findRoute = 0; - $isEventIntermediate = 0; - foreach ($aGateways as $routeBase => $value){ - if($value['0']==$from){ - if($findRoute == 0){ - $typeT = 'FROM'; - $valueRoute = $value['0']; - $typeRoute = $value['1']; - $positionX = $value['2']; - $positionY = $value['3']; - $sequencial = 1; - $findRoute = 1; - } - else{ - $hidden['ID_TASK'] = G::generateUniqueID(); - $hidden['ID_PROCESS'] = $idProcess; - $hidden['TAS_TITLE'] = ''; - $hidden['TASK_TYPE'] = 'HIDDEN'; - $hidden['DESCRIPTION'] = $countHidden; - $hidden['X'] = $positionX; - $hidden['Y'] = $positionY; - $taskHidden[] = $hidden; - $dataTasks[] = $this->createTask($hidden); - $countHidden = $countHidden + 1; - $routeTransitions[$posT]['ID'] = G::generateUniqueID(); - $routeTransitions[$posT]['ROUTE'] = $from; - $routeTransitions[$posT]['FROM'] = $from; - $routeTransitions[$posT]['TO'] = $hidden['ID_TASK']; - $routeTransitions[$posT]['TOORFROM'] = 'FROM'; - $routeTransitions[$posT]['ROU_TYPE'] = $value['1']; - $routeTransitions[$posT]['CONDITION'] = ''; - $routeTransitions[$posT]['CONDITION_DIS'] = ''; - $routeTransitions[$posT]['TYPE_DIS'] = ''; - $posT = $posT + 1; - $from = $hidden['ID_TASK']; - } - } - if($value['0']==$to){ - if($findRoute == 0){ - $typeT = 'TO'; - $valueRoute = $value['0']; - $typeRoute = $value['1']; - $positionX = $value['2']; - $positionY = $value['3']; - $sequencial = 1; - $findRoute = 1; - } - else{ - $hidden['ID_TASK'] = G::generateUniqueID(); - $hidden['ID_PROCESS'] = $idProcess; - $hidden['TAS_TITLE'] = ''; - $hidden['TASK_TYPE'] = 'HIDDEN'; - $hidden['DESCRIPTION'] = $countHidden; - $hidden['X'] = $positionX; - $hidden['Y'] = $positionY; - $taskHidden[] = $hidden; - $dataTasks[] = $this->createTask($hidden); - $countHidden = $countHidden + 1; - $routeTransitions[$posT]['ID'] = G::generateUniqueID(); - $routeTransitions[$posT]['ROUTE'] = $from; - $routeTransitions[$posT]['FROM'] = $from; - $routeTransitions[$posT]['TO'] = $hidden['ID_TASK']; - $routeTransitions[$posT]['TOORFROM'] = 'TO'; - $routeTransitions[$posT]['ROU_TYPE'] = $typeRoute; - $routeTransitions[$posT]['CONDITION'] = ''; - $routeTransitions[$posT]['CONDITION_DIS'] = ''; - $routeTransitions[$posT]['TYPE_DIS'] = ''; - $posT = $posT + 1; - $from = $hidden['ID_TASK']; - $typeT = 'TO'; - $valueRoute = $value['0']; - $typeRoute = $value['1']; - $sequencial = 1; - } - } - } - if($sequencial == 0){ - foreach($aEvents as $id => $value){ - if($routes['TO'] == $value['0']){ - if($value['1']==='bpmnEventEndSignal' or $value['1']==='bpmnEventMessageEnd' ){ - $routes['TO'] = '-1'; - $dataRoutes[$numberRoutes]= $this->createRoute($routes); - $numberRoutes = $numberRoutes +1; - $isEnd = 1; - } - else{ - $isEventIntermediate = 1; - } - } - } - } - if($sequencial == 1){ - $routeTransitions[$posT]['ID'] = $idTransition; - $routeTransitions[$posT]['ROUTE'] = $valueRoute; - $routeTransitions[$posT]['FROM'] = $from; - $routeTransitions[$posT]['TO'] = $to; - $routeTransitions[$posT]['TOORFROM'] = $typeT; - $routeTransitions[$posT]['ROU_TYPE'] = $typeRoute; - $routeTransitions[$posT]['CONDITION'] = ''; - $routeTransitions[$posT]['CONDITION_DIS'] = ''; - $routeTransitions[$posT]['TYPE_DIS'] = ''; - $posT = $posT + 1; - $sequencial = 1; - } - if($isEnd == 0 and $sequencial == 0 and $isEventIntermediate == 0){ - $dataRoutes[$numberRoutes]= $this->createRoute($routes); - $numberRoutes = $numberRoutes +1; - } - } - foreach($routeTransitions as $id => $key){ - $typeRoute = $key['ROU_TYPE']; - switch($typeRoute){ - case 'bpmnGatewayExclusiveData': - $typePM = 'EVALUATE'; - break; - case 'bpmnGatewayInclusive': - $typePM = 'PARALLEL-BY-EVALUATION'; - break; - case 'bpmnGatewayExclusiveEvent': - $typePM = 'EVALUATE'; - break; - case 'bpmnGatewayComplex': - $typePM = 'DISCRIMINATOR'; - break; - case 'bpmnGatewayParallel': - $typePM = 'PARALLEL'; - break; - } - $routeTransitions[$id]['ROU_TYPE'] = $typePM; - } - $routes = $routeTransitions; - foreach($routeTransitions as $key => $id){ - $findTo = 0; - $findFrom = 0; - foreach ($dataTasks as $keyHidden => $value){ - if($id['FROM']== $value['TAS_UID']){ - $findFrom= 1; - } - if($id['TO']== $value['TAS_UID']){ - $findTo = 1; - } - } - if($findTo == 0){ - foreach($routes as $keyR => $idR){ - if($id['TO'] == $idR['ROUTE']){ - $routeTransitions[$key]['ROU_TYPE'] = $idR['ROU_TYPE']; - $routeTransitions[$key]['ROUTE'] = $id['TO']; - $routeTransitions[$key]['TOORFROM'] = 'TO'; - } - } - } - if($findFrom == 0){ - foreach($routes as $keyR => $idR){ - if($id['FROM'] == $idR['ROUTE']){ - $routeTransitions[$key]['ROU_TYPE'] = $idR['ROU_TYPE']; - $routeTransitions[$key]['ROUTE'] = $id['FROM']; - $routeTransitions[$key]['TOORFROM'] = 'FROM'; - } - } - } - } - $result['ROUTES'] = $dataRoutes; - $result['TRANSITIONS']= $routeTransitions; - $result['NUMBER'] = $numberRoutes; - $result['TASKS'] = $dataTasks; - $result['HIDDEN'] = $taskHidden; - return $result; - } - - /** - * This function convert the array events in a array with the events end - * @param object $aEvents - * @param string $idProcess - * @return array - */ - function convertArrayEnd($aEvents,$idProcess) - { - $result = array(); - $posEnd = 1; - $endArray = array(); - foreach($aEvents as $id => $value){ - if($value['1']==='bpmnEventEndSignal' or $value['1']==='bpmnEventMessageEnd'){ - $result['ID_PROCESS'] = $idProcess; - $result['ID_TASK'] = $value['0']; - $endArray[$posEnd] = $result; - $posEnd = $posEnd+1; - } - } - return $endArray; - } - - /** - * This function create transitions from the array transitions for the new processmap - * @param array $task - * @param array $routes - * @param array $events - * @param array $countEvents - * @param array $arrayRoutes - * @param array $countRoutes - * @return array - */ - function createTransitionsPM($tasks,$routes,$events,$countEvents,$arrayRoutes,$countRoutes) - { - $cont = 0 ; - $dataRoutes = ''; - $endEvent = 1 ; - $taskParallel = ''; - $routeParallel = ''; - $taskSecJoin = ''; - $routeSecJoin = ''; - $taskDiscriminator = ''; - $taskEvaluate = ''; - $routeEvaluate = ''; - $taskParallelEv = ''; - $routeParallelEv = ''; - $taskSelect = ''; - $routeSelect = ''; - $routeEnd = ''; - $arraySecJoin = array(); - $position = 0; - $fillColor = ''; - $transitions = ''; - $arrayGateways = array(); - $countG = 0; - $gatPosX = 0; - $gatPosY = 0; - - foreach ($routes as $key => $row) { - if($row['ROU_TYPE'] == 'SEC-JOIN'){ - $arraySecJoin[$position] = array(); - $arraySecJoin[$position] = $row; - $position = $position + 1; - unset($routes[$key]); - } - } - $aux = $arraySecJoin ; - foreach ($arraySecJoin as $key => $row) { - $aux[$key]= $row['ROU_NEXT_TASK']; - } - if(sizeof($arraySecJoin) > 0){ - array_multisort($aux,SORT_ASC,$arraySecJoin); - unset($aux); - } - foreach ($routes as $key => $row) { - $uid[$key] = $row['TAS_UID']; - $case[$key] = $row['ROU_CASE']; - } - if(sizeof($routes) > 0){ - array_multisort($uid, SORT_ASC, $case, SORT_ASC, $routes); - } - $routes = array_merge($routes,$arraySecJoin); - foreach ($routes as $key => $val ) { - $end = 0; - $idRoute = $val['ROU_UID']; - $idTask = $val['TAS_UID']; - $nextTask = $val['ROU_NEXT_TASK']; - $condition = htmlentities($val['ROU_CONDITION']); - $toPort = $val['ROU_TO_PORT']; - $fromPort = $val['ROU_FROM_PORT']; - //If End Event - if($nextTask == "-1"){ - $end=1; - } - $typeRoute = $val['ROU_TYPE']; - $route = ''; - - //Get GAT_UID from ROUTE table based on ROU_UID - $oRoute = new Route ( ); - $aRouteDetails = $oRoute->load($idRoute); - $sGateUID = $aRouteDetails['GAT_UID']; - - //Get Gateway details from above GAT_UID - $oGateway = new Gateway ( ); - if($sGateUID != '') - { - $aGatewayDetails = $oGateway->load($sGateUID); - $gatPosX = $aGatewayDetails['GAT_X']; - $gatPosY = $aGatewayDetails['GAT_Y']; - } - - //if route is of SEQUENTIAL type,assign route id to GAT_UID - if($sGateUID == '') - $sGateUID = $idRoute; - - if ($typeRoute != "SEQUENTIAL" ){ - switch($typeRoute){ - case 'PARALLEL': - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX'] + 60; - $coordinateY=$idVal['TAS_POSY'] + 60; - $tas_width =$idVal['TAS_WIDTH']; - $tas_height =$idVal['TAS_HEIGHT'] ; - } - } - $positionX=$coordinateX+62; - $positionY=$coordinateY+55; - if($idTask != $taskParallel){ - $taskParallel = $idTask; - $routeParallel = $sGateUID; - $arrayGateways[$countG]['0'] = $sGateUID; - $arrayGateways[$countG]['1'] = 'bpmnGatewayParallel'; - $arrayGateways[$countG]['2'] = $gatPosX; - $arrayGateways[$countG]['3'] = $gatPosY; - $countG = $countG + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $taskParallel; - $arrayRoutes[$countRoutes]['2']= $routeParallel; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeParallel; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - else{ - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeParallel; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - break; - case 'SEC-JOIN': - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$nextTask){ - $coordinateX=$idVal['TAS_POSX'] + 60; - $coordinateY=$idVal['TAS_POSY'] + 60; - $tas_width =$idVal['TAS_WIDTH']; - $tas_height =$idVal['TAS_HEIGHT']; - } - } - $positionX=$coordinateX+60; - $positionY=$coordinateY-45; - if($nextTask != $taskSecJoin){ - $taskSecJoin = $nextTask; - $routeSecJoin = $sGateUID; - $arrayGateways[$countG]['0'] = $sGateUID; - $arrayGateways[$countG]['1'] = 'bpmnGatewayParallel'; - $arrayGateways[$countG]['2'] = $gatPosX; - $arrayGateways[$countG]['3'] = $gatPosY; - $countG = $countG + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeSecJoin; - $arrayRoutes[$countRoutes]['2']= $taskSecJoin; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $idTask; - $arrayRoutes[$countRoutes]['2']= $routeSecJoin; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - else{ - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $idTask; - $arrayRoutes[$countRoutes]['2']= $routeSecJoin; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - break; - case 'EVALUATE': - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX'] + 60; - $coordinateY=$idVal['TAS_POSY'] + 60; - $tas_width =$idVal['TAS_WIDTH']; - $tas_height =$idVal['TAS_HEIGHT']; - } - } - $positionX=$coordinateX+62; - $positionY=$coordinateY+55; - if($idTask != $taskEvaluate){ - $taskEvaluate = $idTask; - $routeEvaluate = $sGateUID; - if($nextTask != "-1"){ - $arrayGateways[$countG]['0'] = $sGateUID; - $arrayGateways[$countG]['1'] = 'bpmnGatewayExclusiveData'; - $arrayGateways[$countG]['2'] = $gatPosX; - $arrayGateways[$countG]['3'] = $gatPosY; - $countG = $countG + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $taskEvaluate; - $arrayRoutes[$countRoutes]['2']= $routeEvaluate; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeEvaluate; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - } - else{ - if($nextTask !="-1"){ - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeEvaluate; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - else{ - $routeEnd = $routeEvaluate; - } - } - break; - case 'PARALLEL-BY-EVALUATION': - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX = $idVal['TAS_POSX'] + 60; - $coordinateY = $idVal['TAS_POSY'] + 60; - $tas_width =$idVal['TAS_WIDTH']; - $tas_height =$idVal['TAS_HEIGHT']; - } - } - $positionX=$coordinateX+62; - $positionY=$coordinateY+55; - if($idTask != $taskParallelEv){ - $taskParallelEv = $idTask; - $routeParallelEv = $sGateUID; - $arrayGateways[$countG]['0'] = $sGateUID; - $arrayGateways[$countG]['1'] = 'bpmnGatewayInclusive'; - $arrayGateways[$countG]['2'] = $gatPosX; - $arrayGateways[$countG]['3'] = $gatPosY; - $countG = $countG + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $taskParallelEv; - $arrayRoutes[$countRoutes]['2']= $routeParallelEv; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeParallelEv; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - else{ - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeParallelEv; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - break; - case 'SELECT': - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX'] + 60; - $coordinateY=$idVal['TAS_POSY'] + 60; - $tas_width =$idVal['TAS_WIDTH']; - $tas_height =$idVal['TAS_HEIGHT']; + if ($id['TO'] == $value['TAS_UID']) { + $findTo = 1; } } - $positionX=$coordinateX+60; - $positionY=$coordinateY+40; - if($idTask != $taskSelect){ - $taskSelect = $idTask; - $routeSelect = $sGateUID; - $arrayGateways[$countG]['0'] = $sGateUID; - $arrayGateways[$countG]['1'] = 'bpmnGatewayExclusiveData'; - $arrayGateways[$countG]['2'] = $gatPosX; - $arrayGateways[$countG]['3'] = $gatPosY; - $countG = $countG + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $taskSelect; - $arrayRoutes[$countRoutes]['2']= $routeSelect; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeSelect; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - else{ - if($nextTask !="-1"){ - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeSelect; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - else{ - $routeEnd = $routeSelect; - } - } - break; - case 'DISCRIMINATOR': - $coordinateX = 0; - $coordinateY = 0; - $optional = $val['ROU_OPTIONAL']; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$nextTask){ - $coordinateX=$idVal['TAS_POSX'] + 60; - $coordinateY=$idVal['TAS_POSY'] + 60; - $tas_width =$idVal['TAS_WIDTH']; - $tas_height =$idVal['TAS_HEIGHT']; + if ($findTo == 0) { + foreach ($routes as $keyR => $idR) { + if ($id['TO'] == $idR['ROUTE']) { + $routeTransitions[$key]['ROU_TYPE'] = $idR['ROU_TYPE']; + $routeTransitions[$key]['ROUTE'] = $id['TO']; + $routeTransitions[$key]['TOORFROM'] = 'TO'; + } } } - $positionX=$coordinateX+60; - $positionY=$coordinateY-45; - if($nextTask != $taskDiscriminator){ - $taskDiscriminator = $nextTask; - $routeDiscriminator = $sGateUID; - $arrayGateways[$countG]['0'] = $sGateUID; - $arrayGateways[$countG]['1'] = 'bpmnGatewayComplex'; - $arrayGateways[$countG]['2'] = $gatPosX; - $arrayGateways[$countG]['3'] = $gatPosY; - $countG = $countG + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $routeDiscriminator; - $arrayRoutes[$countRoutes]['2']= $taskDiscriminator; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $idTask; - $arrayRoutes[$countRoutes]['2']= $routeDiscriminator; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; + if ($findFrom == 0) { + foreach ($routes as $keyR => $idR) { + if ($id['FROM'] == $idR['ROUTE']) { + $routeTransitions[$key]['ROU_TYPE'] = $idR['ROU_TYPE']; + $routeTransitions[$key]['ROUTE'] = $id['FROM']; + $routeTransitions[$key]['TOORFROM'] = 'FROM'; + } + } } - else{ - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $idTask; - $arrayRoutes[$countRoutes]['2']= $routeDiscriminator; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; + } + $result['ROUTES'] = $dataRoutes; + $result['TRANSITIONS'] = $routeTransitions; + $result['NUMBER'] = $numberRoutes; + $result['TASKS'] = $dataTasks; + $result['HIDDEN'] = $taskHidden; + return $result; + } + + /** + * This public function convert the array events in a array with the events end + * + * @param object $aEvents + * @param string $idProcess + * @return array + */ + public function convertArrayEnd ($aEvents, $idProcess) + { + $result = array (); + $posEnd = 1; + $endArray = array (); + foreach ($aEvents as $id => $value) { + if ($value['1'] === 'bpmnEventEndSignal' or $value['1'] === 'bpmnEventMessageEnd') { + $result['ID_PROCESS'] = $idProcess; + $result['ID_TASK'] = $value['0']; + $endArray[$posEnd] = $result; + $posEnd = $posEnd + 1; } - break; } - } - if($end==1){ - if($typeRoute == "SEQUENTIAL"){ - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - $tas_width =$idVal['TAS_WIDTH']; - $tas_height =$idVal['TAS_HEIGHT']; - $tas_uid =$idVal['TAS_UID']; + return $endArray; + } + + /** + * This public function create transitions from the array transitions for the new processmap + * + * @param array $task + * @param array $routes + * @param array $events + * @param array $countEvents + * @param array $arrayRoutes + * @param array $countRoutes + * @return array + */ + public function createTransitionsPM ($tasks, $routes, $events, $countEvents, $arrayRoutes, $countRoutes) + { + $cont = 0; + $dataRoutes = ''; + $endEvent = 1; + $taskParallel = ''; + $routeParallel = ''; + $taskSecJoin = ''; + $routeSecJoin = ''; + $taskDiscriminator = ''; + $taskEvaluate = ''; + $routeEvaluate = ''; + $taskParallelEv = ''; + $routeParallelEv = ''; + $taskSelect = ''; + $routeSelect = ''; + $routeEnd = ''; + $arraySecJoin = array (); + $position = 0; + $fillColor = ''; + $transitions = ''; + $arrayGateways = array (); + $countG = 0; + $gatPosX = 0; + $gatPosY = 0; + + foreach ($routes as $key => $row) { + if ($row['ROU_TYPE'] == 'SEC-JOIN') { + $arraySecJoin[$position] = array (); + $arraySecJoin[$position] = $row; + $position = $position + 1; + unset( $routes[$key] ); } - } - $positionX = $coordinateX + 92; - $positionY = $coordinateY + 40; - $evn_uid = $val['ROU_EVN_UID']; - if($evn_uid != ''){ - $oEvent = new Event(); - $aEvent = $oEvent->load($evn_uid); - - $events[$countEvents]['0'] = $evn_uid; - $events[$countEvents]['1'] = $aEvent['EVN_TYPE']; - $events[$countEvents]['2'] = $positionX-25; - $events[$countEvents]['3'] = $positionY+35; - $events[$countEvents]['4'] = $tas_uid; - $countEvents = $countEvents + 1; - - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $idTask; - $arrayRoutes[$countRoutes]['2']= $evn_uid; - $arrayRoutes[$countRoutes]['3']= $toPort; - $arrayRoutes[$countRoutes]['4']= $fromPort; - $arrayRoutes[$countRoutes]['5']= $typeRoute; - $countRoutes = $countRoutes + 1; - $end = 0; - $endEvent = 0; - } } - //For $typeRoute Evaluate Function - else{ - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - $tas_width =$idVal['TAS_WIDTH']; - $tas_height =$idVal['TAS_HEIGHT']; - $tas_uid =$idVal['TAS_UID']; - } - } - $positionX = $coordinateX + $tas_width/1.5 + 19; - $positionY = $coordinateY + $tas_height/2; - $idTask = $routeEnd; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $idTask; - $arrayRoutes[$countRoutes]['2']= $idRoute; - $arrayRoutes[$countRoutes]['3']= $toPort; - $arrayRoutes[$countRoutes]['4']= $fromPort; - $arrayRoutes[$countRoutes]['5']= $typeRoute; - $countRoutes = $countRoutes + 1; - - $events[$countEvents]['0'] = $idRoute; - $events[$countEvents]['1'] = 'bpmnEventEmptyEnd'; - $events[$countEvents]['2'] = $positionX-25; - $events[$countEvents]['3'] = $positionY+35; - $events[$countEvents]['4'] = $tas_uid; - $countEvents = $countEvents + 1; - $end = 0; - $endEvent = 0; + $aux = $arraySecJoin; + foreach ($arraySecJoin as $key => $row) { + $aux[$key] = $row['ROU_NEXT_TASK']; } - } - else{ - if ($typeRoute == "SEQUENTIAL"){ - //Will Check for Intermediate Timer - $evn_uid = $val['ROU_EVN_UID']; - if($evn_uid != '') - { - $coordinateX=0; - $coordinateY=0; - foreach ($tasks as $taskVal => $idVal ){ - if($idVal['TAS_UID']==$idTask){ - $coordinateX=$idVal['TAS_POSX']; - $coordinateY=$idVal['TAS_POSY']; - $tas_width =$idVal['TAS_WIDTH']; - $tas_height =$idVal['TAS_HEIGHT']; - } + if (sizeof( $arraySecJoin ) > 0) { + array_multisort( $aux, SORT_ASC, $arraySecJoin ); + unset( $aux ); + } + foreach ($routes as $key => $row) { + $uid[$key] = $row['TAS_UID']; + $case[$key] = $row['ROU_CASE']; + } + if (sizeof( $routes ) > 0) { + array_multisort( $uid, SORT_ASC, $case, SORT_ASC, $routes ); + } + $routes = array_merge( $routes, $arraySecJoin ); + foreach ($routes as $key => $val) { + $end = 0; + $idRoute = $val['ROU_UID']; + $idTask = $val['TAS_UID']; + $nextTask = $val['ROU_NEXT_TASK']; + $condition = htmlentities( $val['ROU_CONDITION'] ); + $toPort = $val['ROU_TO_PORT']; + $fromPort = $val['ROU_FROM_PORT']; + //If End Event + if ($nextTask == "-1") { + $end = 1; } - $positionX = $coordinateX + $tas_width/1.5 + 19; - $positionY = $coordinateY + $tas_height/2; + $typeRoute = $val['ROU_TYPE']; + $route = ''; - $oEvent = new Event(); - $aEvent = $oEvent->load($evn_uid); - $events[$countEvents]['0'] = $evn_uid; - $events[$countEvents]['1'] = $aEvent['EVN_TYPE']; - $events[$countEvents]['2'] = $aEvent['EVN_POSX']; - $events[$countEvents]['3'] = $aEvent['EVN_POSY']; - $countEvents = $countEvents + 1; + //Get GAT_UID from ROUTE table based on ROU_UID + $oRoute = new Route(); + $aRouteDetails = $oRoute->load( $idRoute ); + $sGateUID = $aRouteDetails['GAT_UID']; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $idTask; - $arrayRoutes[$countRoutes]['2']= $evn_uid; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - $arrayRoutes[$countRoutes]['0']= G::generateUniqueID(); - $arrayRoutes[$countRoutes]['1']= $evn_uid; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= '1'; - $arrayRoutes[$countRoutes]['4']= '2'; - $countRoutes = $countRoutes + 1; - } - else - { - $arrayRoutes[$countRoutes]['0']= $idRoute; - $arrayRoutes[$countRoutes]['1']= $idTask; - $arrayRoutes[$countRoutes]['2']= $nextTask; - $arrayRoutes[$countRoutes]['3']= $toPort; - $arrayRoutes[$countRoutes]['4']= $fromPort; - $countRoutes = $countRoutes + 1; - } + //Get Gateway details from above GAT_UID + $oGateway = new Gateway(); + if ($sGateUID != '') { + $aGatewayDetails = $oGateway->load( $sGateUID ); + $gatPosX = $aGatewayDetails['GAT_X']; + $gatPosY = $aGatewayDetails['GAT_Y']; + } + + //if route is of SEQUENTIAL type,assign route id to GAT_UID + if ($sGateUID == '') { + $sGateUID = $idRoute; + } + if ($typeRoute != "SEQUENTIAL") { + switch ($typeRoute) { + case 'PARALLEL': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX'] + 60; + $coordinateY = $idVal['TAS_POSY'] + 60; + $tas_width = $idVal['TAS_WIDTH']; + $tas_height = $idVal['TAS_HEIGHT']; + } + } + $positionX = $coordinateX + 62; + $positionY = $coordinateY + 55; + if ($idTask != $taskParallel) { + $taskParallel = $idTask; + $routeParallel = $sGateUID; + $arrayGateways[$countG]['0'] = $sGateUID; + $arrayGateways[$countG]['1'] = 'bpmnGatewayParallel'; + $arrayGateways[$countG]['2'] = $gatPosX; + $arrayGateways[$countG]['3'] = $gatPosY; + $countG = $countG + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $taskParallel; + $arrayRoutes[$countRoutes]['2'] = $routeParallel; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeParallel; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } else { + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeParallel; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } + break; + case 'SEC-JOIN': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $nextTask) { + $coordinateX = $idVal['TAS_POSX'] + 60; + $coordinateY = $idVal['TAS_POSY'] + 60; + $tas_width = $idVal['TAS_WIDTH']; + $tas_height = $idVal['TAS_HEIGHT']; + } + } + $positionX = $coordinateX + 60; + $positionY = $coordinateY - 45; + if ($nextTask != $taskSecJoin) { + $taskSecJoin = $nextTask; + $routeSecJoin = $sGateUID; + $arrayGateways[$countG]['0'] = $sGateUID; + $arrayGateways[$countG]['1'] = 'bpmnGatewayParallel'; + $arrayGateways[$countG]['2'] = $gatPosX; + $arrayGateways[$countG]['3'] = $gatPosY; + $countG = $countG + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeSecJoin; + $arrayRoutes[$countRoutes]['2'] = $taskSecJoin; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $idTask; + $arrayRoutes[$countRoutes]['2'] = $routeSecJoin; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } else { + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $idTask; + $arrayRoutes[$countRoutes]['2'] = $routeSecJoin; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } + break; + case 'EVALUATE': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX'] + 60; + $coordinateY = $idVal['TAS_POSY'] + 60; + $tas_width = $idVal['TAS_WIDTH']; + $tas_height = $idVal['TAS_HEIGHT']; + } + } + $positionX = $coordinateX + 62; + $positionY = $coordinateY + 55; + if ($idTask != $taskEvaluate) { + $taskEvaluate = $idTask; + $routeEvaluate = $sGateUID; + if ($nextTask != "-1") { + $arrayGateways[$countG]['0'] = $sGateUID; + $arrayGateways[$countG]['1'] = 'bpmnGatewayExclusiveData'; + $arrayGateways[$countG]['2'] = $gatPosX; + $arrayGateways[$countG]['3'] = $gatPosY; + $countG = $countG + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $taskEvaluate; + $arrayRoutes[$countRoutes]['2'] = $routeEvaluate; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeEvaluate; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } + } else { + if ($nextTask != "-1") { + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeEvaluate; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } else { + $routeEnd = $routeEvaluate; + } + } + break; + case 'PARALLEL-BY-EVALUATION': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX'] + 60; + $coordinateY = $idVal['TAS_POSY'] + 60; + $tas_width = $idVal['TAS_WIDTH']; + $tas_height = $idVal['TAS_HEIGHT']; + } + } + $positionX = $coordinateX + 62; + $positionY = $coordinateY + 55; + if ($idTask != $taskParallelEv) { + $taskParallelEv = $idTask; + $routeParallelEv = $sGateUID; + $arrayGateways[$countG]['0'] = $sGateUID; + $arrayGateways[$countG]['1'] = 'bpmnGatewayInclusive'; + $arrayGateways[$countG]['2'] = $gatPosX; + $arrayGateways[$countG]['3'] = $gatPosY; + $countG = $countG + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $taskParallelEv; + $arrayRoutes[$countRoutes]['2'] = $routeParallelEv; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeParallelEv; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } else { + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeParallelEv; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } + break; + case 'SELECT': + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX'] + 60; + $coordinateY = $idVal['TAS_POSY'] + 60; + $tas_width = $idVal['TAS_WIDTH']; + $tas_height = $idVal['TAS_HEIGHT']; + } + } + $positionX = $coordinateX + 60; + $positionY = $coordinateY + 40; + if ($idTask != $taskSelect) { + $taskSelect = $idTask; + $routeSelect = $sGateUID; + $arrayGateways[$countG]['0'] = $sGateUID; + $arrayGateways[$countG]['1'] = 'bpmnGatewayExclusiveData'; + $arrayGateways[$countG]['2'] = $gatPosX; + $arrayGateways[$countG]['3'] = $gatPosY; + $countG = $countG + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $taskSelect; + $arrayRoutes[$countRoutes]['2'] = $routeSelect; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeSelect; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } else { + if ($nextTask != "-1") { + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeSelect; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } else { + $routeEnd = $routeSelect; + } + } + break; + case 'DISCRIMINATOR': + $coordinateX = 0; + $coordinateY = 0; + $optional = $val['ROU_OPTIONAL']; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $nextTask) { + $coordinateX = $idVal['TAS_POSX'] + 60; + $coordinateY = $idVal['TAS_POSY'] + 60; + $tas_width = $idVal['TAS_WIDTH']; + $tas_height = $idVal['TAS_HEIGHT']; + } + } + $positionX = $coordinateX + 60; + $positionY = $coordinateY - 45; + if ($nextTask != $taskDiscriminator) { + $taskDiscriminator = $nextTask; + $routeDiscriminator = $sGateUID; + $arrayGateways[$countG]['0'] = $sGateUID; + $arrayGateways[$countG]['1'] = 'bpmnGatewayComplex'; + $arrayGateways[$countG]['2'] = $gatPosX; + $arrayGateways[$countG]['3'] = $gatPosY; + $countG = $countG + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $routeDiscriminator; + $arrayRoutes[$countRoutes]['2'] = $taskDiscriminator; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $idTask; + $arrayRoutes[$countRoutes]['2'] = $routeDiscriminator; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } else { + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $idTask; + $arrayRoutes[$countRoutes]['2'] = $routeDiscriminator; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } + break; + } + } + if ($end == 1) { + if ($typeRoute == "SEQUENTIAL") { + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + $tas_width = $idVal['TAS_WIDTH']; + $tas_height = $idVal['TAS_HEIGHT']; + $tas_uid = $idVal['TAS_UID']; + } + } + $positionX = $coordinateX + 92; + $positionY = $coordinateY + 40; + $evn_uid = $val['ROU_EVN_UID']; + if ($evn_uid != '') { + $oEvent = new Event(); + $aEvent = $oEvent->load( $evn_uid ); + + $events[$countEvents]['0'] = $evn_uid; + $events[$countEvents]['1'] = $aEvent['EVN_TYPE']; + $events[$countEvents]['2'] = $positionX - 25; + $events[$countEvents]['3'] = $positionY + 35; + $events[$countEvents]['4'] = $tas_uid; + $countEvents = $countEvents + 1; + + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $idTask; + $arrayRoutes[$countRoutes]['2'] = $evn_uid; + $arrayRoutes[$countRoutes]['3'] = $toPort; + $arrayRoutes[$countRoutes]['4'] = $fromPort; + $arrayRoutes[$countRoutes]['5'] = $typeRoute; + $countRoutes = $countRoutes + 1; + $end = 0; + $endEvent = 0; + } + } else { + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + $tas_width = $idVal['TAS_WIDTH']; + $tas_height = $idVal['TAS_HEIGHT']; + $tas_uid = $idVal['TAS_UID']; + } + } + $positionX = $coordinateX + $tas_width / 1.5 + 19; + $positionY = $coordinateY + $tas_height / 2; + $idTask = $routeEnd; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $idTask; + $arrayRoutes[$countRoutes]['2'] = $idRoute; + $arrayRoutes[$countRoutes]['3'] = $toPort; + $arrayRoutes[$countRoutes]['4'] = $fromPort; + $arrayRoutes[$countRoutes]['5'] = $typeRoute; + $countRoutes = $countRoutes + 1; + + $events[$countEvents]['0'] = $idRoute; + $events[$countEvents]['1'] = 'bpmnEventEmptyEnd'; + $events[$countEvents]['2'] = $positionX - 25; + $events[$countEvents]['3'] = $positionY + 35; + $events[$countEvents]['4'] = $tas_uid; + $countEvents = $countEvents + 1; + $end = 0; + $endEvent = 0; + } + } else { + if ($typeRoute == "SEQUENTIAL") { + //Will Check for Intermediate Timer + $evn_uid = $val['ROU_EVN_UID']; + if ($evn_uid != '') { + $coordinateX = 0; + $coordinateY = 0; + foreach ($tasks as $taskVal => $idVal) { + if ($idVal['TAS_UID'] == $idTask) { + $coordinateX = $idVal['TAS_POSX']; + $coordinateY = $idVal['TAS_POSY']; + $tas_width = $idVal['TAS_WIDTH']; + $tas_height = $idVal['TAS_HEIGHT']; + } + } + $positionX = $coordinateX + $tas_width / 1.5 + 19; + $positionY = $coordinateY + $tas_height / 2; + + $oEvent = new Event(); + $aEvent = $oEvent->load( $evn_uid ); + $events[$countEvents]['0'] = $evn_uid; + $events[$countEvents]['1'] = $aEvent['EVN_TYPE']; + $events[$countEvents]['2'] = $aEvent['EVN_POSX']; + $events[$countEvents]['3'] = $aEvent['EVN_POSY']; + $countEvents = $countEvents + 1; + + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $idTask; + $arrayRoutes[$countRoutes]['2'] = $evn_uid; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + $arrayRoutes[$countRoutes]['0'] = G::generateUniqueID(); + $arrayRoutes[$countRoutes]['1'] = $evn_uid; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = '1'; + $arrayRoutes[$countRoutes]['4'] = '2'; + $countRoutes = $countRoutes + 1; + } else { + $arrayRoutes[$countRoutes]['0'] = $idRoute; + $arrayRoutes[$countRoutes]['1'] = $idTask; + $arrayRoutes[$countRoutes]['2'] = $nextTask; + $arrayRoutes[$countRoutes]['3'] = $toPort; + $arrayRoutes[$countRoutes]['4'] = $fromPort; + $countRoutes = $countRoutes + 1; + } + } + } } - } + $data = array (); + $data['GATEWAYS'] = $arrayGateways; + $data['TRANSITION'] = $arrayRoutes; + $data['EVENTS'] = $events; + return $data; } - $data = array(); - $data['GATEWAYS'] = $arrayGateways; - $data['TRANSITION'] = $arrayRoutes; - $data['EVENTS'] = $events; - return $data; - } - /** - * This function Removes duplicate values from an array bi-dimensional - * @param array $array - * @return array - */ - function super_unique($array) - { - $result = array_map("unserialize", array_unique(array_map("serialize", $array))); - foreach ($result as $key => $value){ - if ( is_array($value) ){ - $result[$key] = $this->super_unique($value); - } + /** + * This public function Removes duplicate values from an array bi-dimensional + * + * @param array $array + * @return array + */ + public function super_unique ($array) + { + $result = array_map( "unserialize", array_unique( array_map( "serialize", $array ) ) ); + foreach ($result as $key => $value) { + if (is_array( $value )) { + $result[$key] = $this->super_unique( $value ); + } + } + return $result; } - return $result; - } - /** - * This function create a array for open the process in the new processmap - * @param array $array - * @return array - */ - function createProcessPM($array) - { - $result = array(); - $result['0'] = $array['PRO_UID']; - $result['1'] = $array['PRO_TITLE']; - $result['2'] = $array['PRO_DESCRIPTION']; - return $result; - } - /** - * This function creates an array for the lane that will be created according to the data given in an array - * @param array $lanes - * @return array $lane - */ - function createSubProcessesPM($array) - { - $arrayLanes = array(); - $field = array(); - foreach ($array as $key=> $value){ - - $field['0'] = $value['SWI_UID']; - $field['1'] = $value['SWI_TEXT']; - $field['2'] = $value['SWI_X']; - $field['3'] = $value['SWI_Y']; - $field['4'] = '';//$value['SWI_WIDTH']; - $field['5'] = '';//$value['SWI_HEIGHT']; + /** + * This public function create a array for open the process in the new processmap + * + * @param array $array + * @return array + */ + public function createProcessPM ($array) + { + $result = array (); + $result['0'] = $array['PRO_UID']; + $result['1'] = $array['PRO_TITLE']; + $result['2'] = $array['PRO_DESCRIPTION']; + return $result; } - return $arrayLanes; - } - /** - * This function creates an array for the lane that will be created according to the data given in an array - * @param array $lanes - * @return array $lane - */ - function saveWebEntry($array) - { - $file = new DOMDocument(); - foreach($array as $key => $value){ - $link = $value->W_LINK; - // This split function has been DEPRECATED as of PHP 5.3.0. - // $link = split('>',$link); - // $link = split('<',$link[2]); - $link = explode('>',$link); - $link = explode('<',$link[2]); - $link = $link['0']; - $uid = $value->W_PRO_UID; - $name = $value->W_FILENAME; + /** + * This public function creates an array for the lane that will be created according to the data given in an array + * + * @param array $lanes + * @return array $lane + */ + public function createSubProcessesPM ($array) + { + $arrayLanes = array (); + $field = array (); + foreach ($array as $key => $value) { + + $field['0'] = $value['SWI_UID']; + $field['1'] = $value['SWI_TEXT']; + $field['2'] = $value['SWI_X']; + $field['3'] = $value['SWI_Y']; + $field['4'] = ''; //$value['SWI_WIDTH']; + $field['5'] = ''; //$value['SWI_HEIGHT']; + } + return $arrayLanes; } - } + /** + * This public function creates an array for the lane that will be created according to the data given in an array + * + * @param array $lanes + * @return array $lane + */ + public function saveWebEntry ($array) + { + $file = new DOMDocument(); + foreach ($array as $key => $value) { + $link = $value->W_LINK; + // This split public function has been DEPRECATED as of PHP 5.3.0. + // $link = split('>',$link); + // $link = split('<',$link[2]); + $link = explode( '>', $link ); + $link = explode( '<', $link[2] ); + $link = $link['0']; + $uid = $value->W_PRO_UID; + $name = $value->W_FILENAME; + } + } } +